diff --git a/.github/workflows/inplace.yml b/.github/workflows/ci.yml similarity index 66% rename from .github/workflows/inplace.yml rename to .github/workflows/ci.yml index 514c7cb3a0..8ae3e31be4 100644 --- a/.github/workflows/inplace.yml +++ b/.github/workflows/ci.yml @@ -1,64 +1,104 @@ # This workflow will install Python dependencies, run tests and lint with a single version of Python # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions -name: inplace +name: ci on: push: - branches: [ main ] + branches: + - main pull_request: - branches: [ main ] + branches: + - main + workflow_dispatch: jobs: - build: - - runs-on: ubuntu-latest + test: + runs-on: ${{ matrix.os }} strategy: + fail-fast: false matrix: - mpi: [ 'mpich', 'openmpi'] - name: Test AMUSE with ${{ matrix.mpi }} + mpi: + - mpich + - openmpi + os: + - ubuntu-22.04 + - ubuntu-20.04 + # macOS is not ready yet - needs other setup of prerequisites + # - macos-12 + # - macos-11 + python: + - 3.7 + steps: - - uses: actions/checkout@v3 + + - name: Checkout + uses: actions/checkout@v3 + - name: Setup MPI + id: setup-mpi uses: mpi4py/setup-mpi@v1 with: mpi: ${{ matrix.mpi }} + + - name: Show MPI name + run: echo "${{ steps.setup-mpi.outputs.mpi }}" + + - name: Show MPI info + run: mpichversion + if: ${{ matrix.mpi == 'mpich' }} + + - name: Show MPI info + run: ompi_info + if: ${{ matrix.mpi == 'openmpi' }} + - name: Set up JDK 1.8 uses: actions/setup-java@v3.9.0 with: distribution: 'zulu' # See 'Supported distributions' for available options java-version: '17' - - name: Set up Python 3.8 + + - name: Set up Python uses: actions/setup-python@v4 with: - python-version: 3.8 + python-version: ${{ matrix.python }} + cache: 'pip' + - name: Install dependencies run: | python -m pip install --upgrade pip sudo apt-get install gfortran libopenblas-dev libhdf5-openmpi-dev libgsl0-dev cmake libfftw3-3 libfftw3-dev libmpfr6 libmpfr-dev pip install numpy scipy matplotlib docutils mpi4py pytest pytest-timeout if [ -f requirements.txt ]; then pip install -r requirements.txt; fi + - name: Install amuse run: | pip install -e . + ./configure + - name: build AMUSE framework run: | make framework + - name: build SSE and BHTree run: | make sse.code bhtree.code + - name: check installation run: | amusifier --get-amuse-configmk pip list + - name: archive build log uses: actions/upload-artifact@v3.1.1 with: name: buildlog path: build.log + - name: test core_tests run: | pytest --pyargs amuse.test.suite.core_tests -s + - name: test compile_tests run: | ip link show @@ -67,10 +107,11 @@ jobs: env: OMPI_MCA_rmaps_base_oversubscribe: 1 OMPI_MCA_btl_tcp_if_include: lo + - name: test code_tests run: | - pytest --pyargs amuse.test.suite.codes_tests.test_bhtree -sv - pytest --pyargs amuse.test.suite.codes_tests.test_sse -sv + mpiexec -n 1 pytest --pyargs amuse.test.suite.codes_tests.test_bhtree -sv + mpiexec -n 1 pytest --pyargs amuse.test.suite.codes_tests.test_sse -sv env: OMPI_MCA_rmaps_base_oversubscribe: 1 OMPI_MCA_btl_tcp_if_include: lo diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml index 6daf93cbab..86aa53d34f 100644 --- a/.github/workflows/python-package.yml +++ b/.github/workflows/python-package.yml @@ -8,16 +8,13 @@ on: branches: [ "main" ] pull_request: branches: [ "main" ] - jobs: build: - runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: ["3.7", "3.10"] - steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} @@ -30,7 +27,7 @@ jobs: python -m pip install flake8 pytest # don't install requirements.txt as mpi4py will fail... # if [ -f requirements.txt ]; then pip install -r requirements.txt; fi - python -m pip install setuptools setuptools_scm wheel docutils numpy h5py + python -m pip install --upgrade setuptools setuptools_scm wheel docutils numpy h5py - name: Lint with flake8 run: | # stop the build if there are Python syntax errors or undefined names @@ -43,6 +40,6 @@ jobs: - name: Test with pytest (only core tests) run: | pytest src/amuse/test/suite/core_tests - - name: Create packages - run: | - cd packages && sh generate_packages.sh +# - name: Create packages +# run: | +# cd packages && sh generate_packages.sh diff --git a/.gitignore b/.gitignore index 5c14043f42..0ac1434fb2 100644 --- a/.gitignore +++ b/.gitignore @@ -483,14 +483,16 @@ test_python_sockets_implementation .idea -src/amuse/community/petar/src src/amuse/community/bonsai2/src -src/amuse/community/*/version.py -src/amuse/version.py +doc/interactive_tutorial/_version.py +src/amuse/test/suite/_version.py +src/amuse/community/*/_version.py +src/amuse/_version.py src/amuse/community/petar/src -src/amuse/community/petar/interface.cc -src/amuse/community/petar/interface.h src/amuse/community/seba/src packages/amuse*/dist packages/dist src/amuse/community/phantom/src + +# standard directory for a virtualenv +env/ diff --git a/configure b/configure index 5f38394789..3bb872ac57 100755 --- a/configure +++ b/configure @@ -1,6 +1,6 @@ #! /bin/sh # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.71 for amuse 2023.3.1.dev41+gaa14f8bf8.d20230322. +# Generated by GNU Autoconf 2.71 for amuse 2023.7.0. # # # Copyright (C) 1992-1996, 1998-2017, 2020-2021 Free Software Foundation, @@ -668,8 +668,8 @@ MAKEFLAGS= # Identity of this package. PACKAGE_NAME='amuse' PACKAGE_TARNAME='amuse' -PACKAGE_VERSION='2023.3.1.dev41+gaa14f8bf8.d20230322' -PACKAGE_STRING='amuse 2023.3.1.dev41+gaa14f8bf8.d20230322' +PACKAGE_VERSION='2023.7.0' +PACKAGE_STRING='amuse 2023.7.0' PACKAGE_BUGREPORT='' PACKAGE_URL='' @@ -1505,7 +1505,7 @@ if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF -\`configure' configures amuse 2023.3.1.dev41+gaa14f8bf8.d20230322 to adapt to many kinds of systems. +\`configure' configures amuse 2023.7.0 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... @@ -1571,7 +1571,7 @@ fi if test -n "$ac_init_help"; then case $ac_init_help in - short | recursive ) echo "Configuration of amuse 2023.3.1.dev41+gaa14f8bf8.d20230322:";; + short | recursive ) echo "Configuration of amuse 2023.7.0:";; esac cat <<\_ACEOF @@ -1725,7 +1725,7 @@ fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF -amuse configure 2023.3.1.dev41+gaa14f8bf8.d20230322 +amuse configure 2023.7.0 generated by GNU Autoconf 2.71 Copyright (C) 2021 Free Software Foundation, Inc. @@ -2259,7 +2259,7 @@ cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. -It was created by amuse $as_me 2023.3.1.dev41+gaa14f8bf8.d20230322, which was +It was created by amuse $as_me 2023.7.0, which was generated by GNU Autoconf 2.71. Invocation command line was $ $0$ac_configure_args_raw @@ -4942,13 +4942,13 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$PYTHON"; then # If the user set $PYTHON, use it and don't search something else. - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether $PYTHON version is >= 3.5" >&5 -printf %s "checking whether $PYTHON version is >= 3.5... " >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether $PYTHON version is >= 3.7" >&5 +printf %s "checking whether $PYTHON version is >= 3.7... " >&6; } prog="import sys # split strings by '.' and convert to numeric. Append some zeros # because we need at least 4 digits for the hex conversion. # map returns an iterator in Python 3.0 and a list in 2.x -minver = list(map(int, '3.5'.split('.'))) + [0, 0, 0] +minver = list(map(int, '3.7'.split('.'))) + [0, 0, 0] minverhex = 0 # xrange is not present in Python 3.0 and range returns an iterator for i in list(range(0, 4)): minverhex = (minverhex << 8) + minver[i] @@ -4970,8 +4970,8 @@ fi else # Otherwise, try each interpreter until we find one that satisfies # VERSION. - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for a Python interpreter with version >= 3.5" >&5 -printf %s "checking for a Python interpreter with version >= 3.5... " >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for a Python interpreter with version >= 3.7" >&5 +printf %s "checking for a Python interpreter with version >= 3.7... " >&6; } if test ${am_cv_pathless_PYTHON+y} then : printf %s "(cached) " >&6 @@ -4983,7 +4983,7 @@ else $as_nop # split strings by '.' and convert to numeric. Append some zeros # because we need at least 4 digits for the hex conversion. # map returns an iterator in Python 3.0 and a list in 2.x -minver = list(map(int, '3.5'.split('.'))) + [0, 0, 0] +minver = list(map(int, '3.7'.split('.'))) + [0, 0, 0] minverhex = 0 # xrange is not present in Python 3.0 and range returns an iterator for i in list(range(0, 4)): minverhex = (minverhex << 8) + minver[i] @@ -7776,7 +7776,13 @@ else $as_nop fi cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ +ifelse(main, main, , # Avoid conflicting decl of main. + /* Override any gcc2 internal prototype to avoid an error. */ + /* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ + char main(); + ) int main (void) { @@ -7860,7 +7866,13 @@ else $as_nop fi cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ +ifelse(main, main, , # Avoid conflicting decl of main. + /* Override any gcc2 internal prototype to avoid an error. */ + /* We use char because int might match the return type of a gcc2 + builtin and then its argument prototype would still apply. */ + char main(); + ) int main (void) { @@ -14322,7 +14334,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" -This file was extended by amuse $as_me 2023.3.1.dev41+gaa14f8bf8.d20230322, which was +This file was extended by amuse $as_me 2023.7.0, which was generated by GNU Autoconf 2.71. Invocation command line was CONFIG_FILES = $CONFIG_FILES @@ -14377,7 +14389,7 @@ ac_cs_config_escaped=`printf "%s\n" "$ac_cs_config" | sed "s/^ //; s/'/'\\\\\\\\ cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config='$ac_cs_config_escaped' ac_cs_version="\\ -amuse config.status 2023.3.1.dev41+gaa14f8bf8.d20230322 +amuse config.status 2023.7.0 configured by $0, generated by GNU Autoconf 2.71, with options \\"\$ac_cs_config\\" diff --git a/configure.ac b/configure.ac index 900d51163f..efb8516058 100644 --- a/configure.ac +++ b/configure.ac @@ -21,7 +21,7 @@ AC_ARG_VAR([PYTHON], [Python interpreter]) AC_SUBST(FC_ISO_C_BINDINGS) -AM_PATH_PYTHON([3.5]) +AM_PATH_PYTHON([3.7]) AC_PATH_PROG([PYTHON], [$PYTHON], []) AC_ARG_VAR([NVCC], [CUDA compiler command]) diff --git a/doc/install/howto-install-AMUSE.rst b/doc/install/howto-install-AMUSE.rst index 4ea914bb52..afe4d9d172 100644 --- a/doc/install/howto-install-AMUSE.rst +++ b/doc/install/howto-install-AMUSE.rst @@ -170,3 +170,56 @@ individual codes can be build with: make {code}.code with {code} the name of the code in lower case. + +Installation on HPC systems using modules (tested for Snellius) +*************************************************************** + +Note that the modules on your local HPC system may be differently named. + +.. code-block:: sh + + module load 2022 + module load foss/2022a + +Load python. + +.. code-block:: sh + + module load Python/3.10.4-GCCcore-11.3.0 # or another version of python, 3.7 or higher + + +Following AMUSE documentation (see above), download/upgrade the python package: (--user is required by Snellius) + +.. code-block:: sh + + mkdir MY_PROJECT_DIR + cd MY_PROJECT_DIR + python3 -m venv env # initialise a Python virtual environment, which will contain all the packages we install + source env/bin/activate # activate the virtual environment - this must be repeated every time you log in + pip install --upgrade pip + cd AMUSE_DIR # change to where you downloaded AMUSE + pip install -r requirements.txt --upgrade # install/upgrade all required packages + pip install matplotlib # not required but highly recommended + pip install -e . + +Now you can build the AMUSE framework with + +.. code-block:: sh + + make framework + +Finally, build AMUSE individual codes by running from the AMUSE directory: + +.. code-block:: sh + + make {code}.code + +When you log in again (and in your SLURM scripts), you will need to load the same modules and activate the same environment: + +.. code-block:: sh + + module load 2022 + module load foss/2022a + module load Python/3.10.4-GCCcore-11.3.0 # or another version of python, 3.7 or higher + cd MY_PROJECT_DIR + source env/bin/activate diff --git a/examples/textbook/planetary_system.py b/examples/textbook/planetary_system.py index 85b7186b97..5690122cf3 100644 --- a/examples/textbook/planetary_system.py +++ b/examples/textbook/planetary_system.py @@ -101,8 +101,8 @@ def main(Mstar, Ndisk, fmdisk, Rmin, Rmax, t_end, n_steps): filename = "planetary_system_i{0:04}.amuse".format(index) write_set_to_file(star_and_planets, filename, 'amuse', attribute_names=planet_attributes, - append_to_file=False) - write_set_to_file(disk, filename, 'amuse', attribute_names=disk_attributes) + overwrite_file=True) + write_set_to_file(disk, filename, 'amuse', attribute_names=disk_attributes, append_to_file=True) gravity_hydro = bridge.Bridge(use_threading=False) gravity_hydro.add_system(gravity, (hydro,) ) @@ -133,9 +133,9 @@ def main(Mstar, Ndisk, fmdisk, Rmin, Rmax, t_end, n_steps): filename = "planetary_system_i{0:04}.amuse".format(index) write_set_to_file(star_and_planets, filename, 'amuse', attribute_names=planet_attributes, - append_to_file=False) + overwrite_file=True) write_set_to_file(disk, filename, 'amuse', - attribute_names=disk_attributes) + attribute_names=disk_attributes, append_to_file=True) Ekin = gravity_hydro.kinetic_energy Epot = gravity_hydro.potential_energy diff --git a/m4/ax_mpi.m4 b/m4/ax_mpi.m4 index 199fc71880..dbde02a9c4 100644 --- a/m4/ax_mpi.m4 +++ b/m4/ax_mpi.m4 @@ -80,7 +80,7 @@ AU_ALIAS([ACX_MPI], [AX_MPI]) AC_DEFUN([AX_MPI], [ -AC_PREREQ(2.50) dnl for AC_LANG_CASE +AC_PREREQ([2.71]) dnl for AC_LANG_CASE AC_LANG_CASE([C], [ AC_REQUIRE([AC_PROG_CC]) @@ -194,16 +194,16 @@ if test x = x"$MPILIBS"; then AC_CHECK_LIB(mpich, MPI_Init, [MPILIBS="-lmpich"]) fi -dnl We have to use AC_TRY_COMPILE and not AC_CHECK_HEADER because the +dnl We have to use AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[]], [[]])],[],[]) and not AC_CHECK_HEADER because the dnl latter uses $CPP, not $CC (which may be mpicc). AC_LANG_CASE([C], [if test x != x"$MPILIBS"; then AC_MSG_CHECKING([for mpi.h]) - AC_TRY_COMPILE([#include ],[],[AC_MSG_RESULT(yes)], [MPILIBS="" + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[]])],[AC_MSG_RESULT(yes)],[MPILIBS="" AC_MSG_RESULT(no)]) fi], [C++], [if test x != x"$MPILIBS"; then AC_MSG_CHECKING([for mpi.h]) - AC_TRY_COMPILE([#include ],[],[AC_MSG_RESULT(yes)], [MPILIBS="" + AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[]])],[AC_MSG_RESULT(yes)],[MPILIBS="" AC_MSG_RESULT(no)]) fi], [Fortran 77], [if test x != x"$MPILIBS"; then diff --git a/m4/ax_openmp.m4 b/m4/ax_openmp.m4 index 7ea794be03..a728f63022 100644 --- a/m4/ax_openmp.m4 +++ b/m4/ax_openmp.m4 @@ -68,7 +68,7 @@ #serial 8 AC_DEFUN([AX_OPENMP], [ -AC_PREREQ(2.59) dnl for _AC_LANG_PREFIX +AC_PREREQ([2.71]) dnl for _AC_LANG_PREFIX AC_CACHE_CHECK([for OpenMP flag of _AC_LANG compiler], ax_cv_[]_AC_LANG_ABBREV[]_openmp, [save[]_AC_LANG_PREFIX[]FLAGS=$[]_AC_LANG_PREFIX[]FLAGS ax_cv_[]_AC_LANG_ABBREV[]_openmp=unknown diff --git a/m4/fftw.m4 b/m4/fftw.m4 index ad4d48a96e..45a55f06fc 100644 --- a/m4/fftw.m4 +++ b/m4/fftw.m4 @@ -4,7 +4,7 @@ # AC_DEFUN([AX_FFTW],[ AC_ARG_WITH(fftw, - AC_HELP_STRING([--with-fftw=PFX], [Prefix where FFTW has been installed] ), + AS_HELP_STRING([--with-fftw=PFX],[Prefix where FFTW has been installed ]), [ test "$withval" = no && AC_MSG_WARN([fftw is a required package for some modules]) test "$withval" = yes || fftw_prefix="$withval" diff --git a/m4/gmp.m4 b/m4/gmp.m4 index 7c67d77234..584168bd12 100644 --- a/m4/gmp.m4 +++ b/m4/gmp.m4 @@ -4,7 +4,7 @@ # AC_DEFUN([AX_GMP],[ AC_ARG_WITH(gmp, - AC_HELP_STRING([--with-gmp=PFX], [Prefix where GMP has been installed] ), + AS_HELP_STRING([--with-gmp=PFX],[Prefix where GMP has been installed ]), [ test "$withval" = no && AC_MSG_WARN([gmp is a required package for some modules]) test "$withval" = yes || gmp_prefix="$withval" diff --git a/m4/gsl.m4 b/m4/gsl.m4 index f5b6c3bbef..96c3189801 100644 --- a/m4/gsl.m4 +++ b/m4/gsl.m4 @@ -89,10 +89,9 @@ AC_ARG_ENABLE(gsltest, [ --disable-gsltest Do not try to compile and run echo "*** Could not run GSL test program, checking why..." CFLAGS="$CFLAGS $GSL_FLAGS" LIBS="$LIBS $GSL_LIBS" - AC_TRY_LINK([ + AC_LINK_IFELSE([AC_LANG_PROGRAM([[ #include - ], [ return 0; ], - [ echo "*** The test program compiled, but did not run. This usually means" + ]], [[ return 0; ]])],[ echo "*** The test program compiled, but did not run. This usually means" echo "*** that the run-time linker is not finding GSL or finding the wrong" echo "*** version of GSL. If it is not finding GSL, you'll need to set your" echo "*** LD_LIBRARY_PATH environment variable, or edit /etc/ld.so.conf to point" @@ -100,8 +99,7 @@ AC_ARG_ENABLE(gsltest, [ --disable-gsltest Do not try to compile and run echo "*** is required on your system" echo "***" echo "*** If you have an old version installed, it is best to remove it, although" - echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH"], - [ echo "*** The test program failed to compile or link. See the file config.log for the" + echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH"],[ echo "*** The test program failed to compile or link. See the file config.log for the" echo "*** exact error that occured. This usually means GSL was incorrectly installed" echo "*** or that you have moved GSL since it was installed. In the latter case, you" echo "*** may want to edit the gsl-config script: $GSL_CONFIG" ]) diff --git a/m4/hdf5.m4 b/m4/hdf5.m4 index f2a963de3e..84b20e2beb 100644 --- a/m4/hdf5.m4 +++ b/m4/hdf5.m4 @@ -4,7 +4,7 @@ # AC_DEFUN([AX_HDF5],[ AC_ARG_WITH(hdf5, - AC_HELP_STRING([--with-hdf5=PFX], [Prefix where HDF5 has been installed] ), + AS_HELP_STRING([--with-hdf5=PFX],[Prefix where HDF5 has been installed ]), [ test "$withval" = no && AC_MSG_WARN([hdf5 is a required package for some modules]) test "$withval" = yes || hdf5_prefix="$withval" diff --git a/m4/m4_ax_blas.m4 b/m4/m4_ax_blas.m4 index 95719050a9..7ba214e533 100644 --- a/m4/m4_ax_blas.m4 +++ b/m4/m4_ax_blas.m4 @@ -68,7 +68,7 @@ AU_ALIAS([ACX_BLAS], [AX_BLAS]) AC_DEFUN([AX_BLAS], [ -AC_PREREQ([2.55]) +AC_PREREQ([2.71]) AC_REQUIRE([AC_F77_LIBRARY_LDFLAGS]) AC_REQUIRE([AC_CANONICAL_HOST]) ax_blas_ok=no diff --git a/m4/m4_ax_blas_f77_func.m4 b/m4/m4_ax_blas_f77_func.m4 index 2890d58489..4c6a6fc686 100644 --- a/m4/m4_ax_blas_f77_func.m4 +++ b/m4/m4_ax_blas_f77_func.m4 @@ -56,7 +56,7 @@ AU_ALIAS([ACX_BLAS_F77_FUNC], [AX_BLAS_F77_FUNC]) AC_DEFUN([AX_BLAS_F77_FUNC], [ -AC_PREREQ(2.50) +AC_PREREQ([2.71]) AC_REQUIRE([AX_BLAS]) # F77 call-compatibility checks @@ -191,7 +191,7 @@ fi ])dnl AX_BLAS_F77_FUNC AC_DEFUN([AX_BLAS_WITH_F77_FUNC], [ -AC_PREREQ(2.50) +AC_PREREQ([2.71]) AX_BLAS([# disable special action], []) if test x$ax_blas_ok = xyes ; then AX_BLAS_F77_FUNC( diff --git a/m4/m4_ax_lib_hdf5.m4 b/m4/m4_ax_lib_hdf5.m4 index 6b02494451..b39b69779d 100644 --- a/m4/m4_ax_lib_hdf5.m4 +++ b/m4/m4_ax_lib_hdf5.m4 @@ -257,7 +257,8 @@ HDF5 support is being disabled (equivalent to --with-hdf5=no). AC_MSG_WARN([Unable to compile HDF5 test program]) fi dnl Look for HDF5's high level library - AC_HAVE_LIBRARY([hdf5_hl], [HDF5_LIBS="-lhdf5_hl $HDF5_LIBS"], [], []) + AC_CHECK_LIB([hdf5_hl],[main],[HDF5_LIBS="-lhdf5_hl $HDF5_LIBS"],[],[])ac_cv_lib_hdf5_hl=ac_cv_lib_hdf5_hl_main + CC=$ax_lib_hdf5_save_CC CPPFLAGS=$ax_lib_hdf5_save_CPPFLAGS diff --git a/m4/mpfr.m4 b/m4/mpfr.m4 index 9812d81b24..eba25c6dc9 100644 --- a/m4/mpfr.m4 +++ b/m4/mpfr.m4 @@ -4,7 +4,7 @@ # AC_DEFUN([AX_MPFR],[ AC_ARG_WITH(mpfr, - AC_HELP_STRING([--with-mpfr=PFX], [Prefix where MPFR has been installed] ), + AS_HELP_STRING([--with-mpfr=PFX],[Prefix where MPFR has been installed ]), [ test "$withval" = no && AC_MSG_WARN([mpfr is a required package for some modules]) test "$withval" = yes || mpfr_prefix="$withval" diff --git a/m4/netcdf.m4 b/m4/netcdf.m4 index cfbdd0cf4a..2b3a9d7f97 100644 --- a/m4/netcdf.m4 +++ b/m4/netcdf.m4 @@ -4,7 +4,7 @@ # AC_DEFUN([AX_NETCDF],[ AC_ARG_WITH(netcdf, - AC_HELP_STRING([--with-netcdf=PFX], [Prefix where NETCDF has been installed] ), + AS_HELP_STRING([--with-netcdf=PFX],[Prefix where NETCDF has been installed ]), [ test "$withval" = no && AC_MSG_WARN([netcdf is optional]) test "$withval" = yes || netcdf_prefix="$withval" diff --git a/m4/opencl.m4 b/m4/opencl.m4 index d0e7cd7e5c..14ff0fd4ae 100644 --- a/m4/opencl.m4 +++ b/m4/opencl.m4 @@ -49,7 +49,7 @@ ax_cv_[]_AC_LANG_ABBREV[]_compiler_ms=$ax_compiler_ms AC_DEFUN([AX_CHECK_CL], [ AC_ARG_WITH(opencl, - AC_HELP_STRING([--with-opencl=PFX], [Prefix where OpenCl has been installed] ), + AS_HELP_STRING([--with-opencl=PFX],[Prefix where OpenCl has been installed ]), [ test "$withval" = no && AC_MSG_WARN([opencl is an optional package for sapporo2 ]) diff --git a/m4/utils.m4 b/m4/utils.m4 index bcd69cda6d..cfd093b645 100644 --- a/m4/utils.m4 +++ b/m4/utils.m4 @@ -63,7 +63,7 @@ AC_DEFUN([AX_IFORT_VERSION], [ # # AC_FIND_LIB(LIBRARY, FUNCTION, LIST-OF-DIRECTORIES [, ACTION-IF-FOUND # [, ACTION-IF-NOT-FOUND [, OTHER-LIBRARIES ]]]) -AC_DEFUN(AC_FIND_LIB, +AC_DEFUN([AC_FIND_LIB], [AC_MSG_CHECKING([directories for -l$1]) # # A lot of this is taken from AC_CHECK_LIB. Note that we always check @@ -80,22 +80,18 @@ AC_DEFUN(AC_FIND_LIB, else LIBS="$LIBS -L$dir -l$1 $6" fi - AC_TRY_LINK( - ifelse([$2], [main], , # Avoid conflicting decl of main. - [/* Override any gcc2 internal prototype to avoid an error. */ - ] - [/* We use char because int might match the return type of a gcc2 + AC_LINK_IFELSE([AC_LANG_PROGRAM([[ifelse($2, main, , # Avoid conflicting decl of main. + /* Override any gcc2 internal prototype to avoid an error. */ + + /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char $2(); - ]), - [$2()], - if test "X$dir" = "X"; then + )]], [[$2()]])],[if test "X$dir" = "X"; then eval "ac_cv_lib_$ac_lib_var=yes" else eval "ac_cv_lib_$ac_lib_var=$dir" fi - break, - eval "ac_cv_lib_$ac_lib_var=no") + break],[eval "ac_cv_lib_$ac_lib_var=no"]) LIBS="$ac_cache_save_LIBS" done ])# diff --git a/packages/amuse-aarsethzare/pyproject.toml b/packages/amuse-aarsethzare/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-aarsethzare/pyproject.toml +++ b/packages/amuse-aarsethzare/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-aarsethzare/setup.py b/packages/amuse-aarsethzare/setup.py index 474aed5967..bd8c584b16 100644 --- a/packages/amuse-aarsethzare/setup.py +++ b/packages/amuse-aarsethzare/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.aarsethzare.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/aarsethzare/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/aarsethzare/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-athena/pyproject.toml b/packages/amuse-athena/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-athena/pyproject.toml +++ b/packages/amuse-athena/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-athena/setup.py b/packages/amuse-athena/setup.py index 0f3b4a8c60..04e24387aa 100644 --- a/packages/amuse-athena/setup.py +++ b/packages/amuse-athena/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.athena.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/athena/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/athena/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-bhtree/pyproject.toml b/packages/amuse-bhtree/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-bhtree/pyproject.toml +++ b/packages/amuse-bhtree/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-bhtree/setup.py b/packages/amuse-bhtree/setup.py index a60b9d9150..6cfa4f010d 100644 --- a/packages/amuse-bhtree/setup.py +++ b/packages/amuse-bhtree/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.bhtree.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/bhtree/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/bhtree/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-brutus/pyproject.toml b/packages/amuse-brutus/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-brutus/pyproject.toml +++ b/packages/amuse-brutus/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-brutus/setup.py b/packages/amuse-brutus/setup.py index 636257ac5a..b454f2b072 100644 --- a/packages/amuse-brutus/setup.py +++ b/packages/amuse-brutus/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.brutus.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/brutus/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/brutus/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-bse/pyproject.toml b/packages/amuse-bse/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-bse/pyproject.toml +++ b/packages/amuse-bse/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-bse/setup.py b/packages/amuse-bse/setup.py index 736378c024..55e97fedd8 100644 --- a/packages/amuse-bse/setup.py +++ b/packages/amuse-bse/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.bse.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/bse/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/bse/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-capreole/pyproject.toml b/packages/amuse-capreole/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-capreole/pyproject.toml +++ b/packages/amuse-capreole/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-capreole/setup.py b/packages/amuse-capreole/setup.py index 7bf47aa028..b76cc5b844 100644 --- a/packages/amuse-capreole/setup.py +++ b/packages/amuse-capreole/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.capreole.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/capreole/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/capreole/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-distributed/pyproject.toml b/packages/amuse-distributed/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-distributed/pyproject.toml +++ b/packages/amuse-distributed/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-distributed/setup.py b/packages/amuse-distributed/setup.py index a1546a4c29..cffb28c2c9 100644 --- a/packages/amuse-distributed/setup.py +++ b/packages/amuse-distributed/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.distributed.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/distributed/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/distributed/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-evtwin/pyproject.toml b/packages/amuse-evtwin/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-evtwin/pyproject.toml +++ b/packages/amuse-evtwin/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-evtwin/setup.py b/packages/amuse-evtwin/setup.py index 0797cd684c..65b282e7f8 100644 --- a/packages/amuse-evtwin/setup.py +++ b/packages/amuse-evtwin/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.evtwin.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/evtwin/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/evtwin/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-fastkick/pyproject.toml b/packages/amuse-fastkick/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-fastkick/pyproject.toml +++ b/packages/amuse-fastkick/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-fastkick/setup.py b/packages/amuse-fastkick/setup.py index 8d7655b0c9..4c5c235af2 100644 --- a/packages/amuse-fastkick/setup.py +++ b/packages/amuse-fastkick/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.fastkick.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/fastkick/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/fastkick/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-fi/pyproject.toml b/packages/amuse-fi/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-fi/pyproject.toml +++ b/packages/amuse-fi/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-fi/setup.py b/packages/amuse-fi/setup.py index e5d5e64733..e6a47a353c 100644 --- a/packages/amuse-fi/setup.py +++ b/packages/amuse-fi/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.fi.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/fi/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/fi/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-fractalcluster/pyproject.toml b/packages/amuse-fractalcluster/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-fractalcluster/pyproject.toml +++ b/packages/amuse-fractalcluster/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-fractalcluster/setup.py b/packages/amuse-fractalcluster/setup.py index c1a0fcdc03..cb607de78b 100644 --- a/packages/amuse-fractalcluster/setup.py +++ b/packages/amuse-fractalcluster/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.fractalcluster.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/fractalcluster/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/fractalcluster/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-framework/pyproject.toml b/packages/amuse-framework/pyproject.toml index cde6818011..c386f25bf6 100644 --- a/packages/amuse-framework/pyproject.toml +++ b/packages/amuse-framework/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools>=42.0.0", "setuptools_scm", "pip>=19.0.0", "wheel", "docutils", "numpy", "nose", "h5py", "pytest" ] +requires = ["setuptools>=65.0.0", "setuptools_scm>=6", "pip>=21.0.0", "wheel", "docutils", "numpy", "h5py>=3.0", "pytest>=3.0"] diff --git a/packages/amuse-framework/setup.py b/packages/amuse-framework/setup.py index 86d3f58f30..aff9df54b5 100644 --- a/packages/amuse-framework/setup.py +++ b/packages/amuse-framework/setup.py @@ -38,25 +38,18 @@ ] } -mapping_from_command_name_to_command_class=setup_commands() +mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -67,8 +60,8 @@ long_description_content_type=long_description_content_type, install_requires=install_requires, python_requires=">=3.7", - extras_require = { - "MPI" : ["mpi4py>=1.1.0"] + extras_require={ + "MPI": ["mpi4py>=1.1.0"] }, cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, @@ -76,5 +69,5 @@ packages=packages, package_data=package_data, data_files=all_data_files, - scripts=[ "bin/amusifier" ], + scripts=["bin/amusifier", ], ) diff --git a/packages/amuse-gadget2/pyproject.toml b/packages/amuse-gadget2/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-gadget2/pyproject.toml +++ b/packages/amuse-gadget2/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-gadget2/setup.py b/packages/amuse-gadget2/setup.py index 6c6d164f9b..891461fa67 100644 --- a/packages/amuse-gadget2/setup.py +++ b/packages/amuse-gadget2/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.gadget2.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/gadget2/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/gadget2/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-galactics/pyproject.toml b/packages/amuse-galactics/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-galactics/pyproject.toml +++ b/packages/amuse-galactics/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-galactics/setup.py b/packages/amuse-galactics/setup.py index ec75b00f61..700b8f7ccf 100644 --- a/packages/amuse-galactics/setup.py +++ b/packages/amuse-galactics/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.galactics.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/galactics/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/galactics/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-galaxia/pyproject.toml b/packages/amuse-galaxia/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-galaxia/pyproject.toml +++ b/packages/amuse-galaxia/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-galaxia/setup.py b/packages/amuse-galaxia/setup.py index 30a7b6b653..54b9c01bb7 100644 --- a/packages/amuse-galaxia/setup.py +++ b/packages/amuse-galaxia/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.galaxia.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/galaxia/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/galaxia/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-halogen/pyproject.toml b/packages/amuse-halogen/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-halogen/pyproject.toml +++ b/packages/amuse-halogen/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-halogen/setup.py b/packages/amuse-halogen/setup.py index 7b4e1084b1..a5756d83d0 100644 --- a/packages/amuse-halogen/setup.py +++ b/packages/amuse-halogen/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.halogen.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/halogen/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/halogen/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-hermite/pyproject.toml b/packages/amuse-hermite/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-hermite/pyproject.toml +++ b/packages/amuse-hermite/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-hermite/setup.py b/packages/amuse-hermite/setup.py index ebb81b0adf..7cc677c1df 100644 --- a/packages/amuse-hermite/setup.py +++ b/packages/amuse-hermite/setup.py @@ -34,24 +34,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.hermite.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/hermite/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/hermite/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -61,7 +54,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-hop/pyproject.toml b/packages/amuse-hop/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-hop/pyproject.toml +++ b/packages/amuse-hop/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-hop/setup.py b/packages/amuse-hop/setup.py index 8a5f620472..63114f32ba 100644 --- a/packages/amuse-hop/setup.py +++ b/packages/amuse-hop/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.hop.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/hop/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/hop/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-huayno/pyproject.toml b/packages/amuse-huayno/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-huayno/pyproject.toml +++ b/packages/amuse-huayno/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-huayno/setup.py b/packages/amuse-huayno/setup.py index 2b6a45df54..58587aad93 100644 --- a/packages/amuse-huayno/setup.py +++ b/packages/amuse-huayno/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.huayno.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/huayno/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/huayno/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-kepler-orbiters/pyproject.toml b/packages/amuse-kepler-orbiters/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-kepler-orbiters/pyproject.toml +++ b/packages/amuse-kepler-orbiters/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-kepler-orbiters/setup.py b/packages/amuse-kepler-orbiters/setup.py index 47bd19588c..4a02fa9e27 100644 --- a/packages/amuse-kepler-orbiters/setup.py +++ b/packages/amuse-kepler-orbiters/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.kepler_orbiters.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/kepler_orbiters/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/kepler_orbiters/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-kepler/pyproject.toml b/packages/amuse-kepler/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-kepler/pyproject.toml +++ b/packages/amuse-kepler/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-kepler/setup.py b/packages/amuse-kepler/setup.py index 924644a284..70aa8311ac 100644 --- a/packages/amuse-kepler/setup.py +++ b/packages/amuse-kepler/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.kepler.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/kepler/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/kepler/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-mameclot/pyproject.toml b/packages/amuse-mameclot/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-mameclot/pyproject.toml +++ b/packages/amuse-mameclot/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-mameclot/setup.py b/packages/amuse-mameclot/setup.py index 3d89a6b80e..517f82f965 100644 --- a/packages/amuse-mameclot/setup.py +++ b/packages/amuse-mameclot/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.mameclot.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/mameclot/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/mameclot/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-mercury/pyproject.toml b/packages/amuse-mercury/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-mercury/pyproject.toml +++ b/packages/amuse-mercury/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-mercury/setup.py b/packages/amuse-mercury/setup.py index 0375bd0e1b..ab047ee447 100644 --- a/packages/amuse-mercury/setup.py +++ b/packages/amuse-mercury/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.mercury.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/mercury/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/mercury/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-mesa-r15140/pyproject.toml b/packages/amuse-mesa-r15140/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-mesa-r15140/pyproject.toml +++ b/packages/amuse-mesa-r15140/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-mesa-r15140/setup.py b/packages/amuse-mesa-r15140/setup.py index 9988cf2a35..755b9082ce 100644 --- a/packages/amuse-mesa-r15140/setup.py +++ b/packages/amuse-mesa-r15140/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.mesa_r15140.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/mesa_r15140/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/mesa_r15140/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, diff --git a/packages/amuse-mesa-r2208/pyproject.toml b/packages/amuse-mesa-r2208/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-mesa-r2208/pyproject.toml +++ b/packages/amuse-mesa-r2208/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-mesa-r2208/setup.py b/packages/amuse-mesa-r2208/setup.py index 206f3d8e5c..463a1b2f97 100644 --- a/packages/amuse-mesa-r2208/setup.py +++ b/packages/amuse-mesa-r2208/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.mesa_r2208.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/mesa_r2208/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/mesa_r2208/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, diff --git a/packages/amuse-mesa/README.md b/packages/amuse-mesa/README.md index 08db0ddfac..3f3e2884ff 100644 --- a/packages/amuse-mesa/README.md +++ b/packages/amuse-mesa/README.md @@ -1 +1,2 @@ This package installs the MESA community code for AMUSE. +It will not build MESA itself, rather it requires the amuse-mesa-r15140 package for this. diff --git a/packages/amuse-mesa/pyproject.toml b/packages/amuse-mesa/pyproject.toml index 5e045ac278..cc36432cd2 100644 --- a/packages/amuse-mesa/pyproject.toml +++ b/packages/amuse-mesa/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0", "amuse-mesa-r15140>=2023.5.0"] diff --git a/packages/amuse-mesa/setup.py b/packages/amuse-mesa/setup.py index a08f6c0b02..6107d61a10 100644 --- a/packages/amuse-mesa/setup.py +++ b/packages/amuse-mesa/setup.py @@ -14,7 +14,6 @@ url = 'http://www.amusecode.org/' install_requires = [ 'amuse-framework', - 'amuse-mesa-r15140', ] description = 'The Astrophysical Multipurpose Software Environment - MESA' with open("README.md", "r") as fh: @@ -34,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.mesa.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/mesa/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/mesa/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, diff --git a/packages/amuse-mesa/src/amuse/community/mesa_r15140 b/packages/amuse-mesa/src/amuse/community/mesa_r15140 deleted file mode 120000 index b009481161..0000000000 --- a/packages/amuse-mesa/src/amuse/community/mesa_r15140 +++ /dev/null @@ -1 +0,0 @@ -../../../../../src/amuse/community/mesa_r15140 \ No newline at end of file diff --git a/packages/amuse-mikkola/pyproject.toml b/packages/amuse-mikkola/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-mikkola/pyproject.toml +++ b/packages/amuse-mikkola/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-mikkola/setup.py b/packages/amuse-mikkola/setup.py index 3e6a8d97f6..b551b71a70 100644 --- a/packages/amuse-mikkola/setup.py +++ b/packages/amuse-mikkola/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.mikkola.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/mikkola/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/mikkola/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-mmams/pyproject.toml b/packages/amuse-mmams/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-mmams/pyproject.toml +++ b/packages/amuse-mmams/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-mmams/setup.py b/packages/amuse-mmams/setup.py index c121fab16a..c18a15f1f9 100644 --- a/packages/amuse-mmams/setup.py +++ b/packages/amuse-mmams/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.mmams.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/mmams/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/mmams/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-mobse/pyproject.toml b/packages/amuse-mobse/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-mobse/pyproject.toml +++ b/packages/amuse-mobse/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-mobse/setup.py b/packages/amuse-mobse/setup.py index df4069a36b..589f1646c1 100644 --- a/packages/amuse-mobse/setup.py +++ b/packages/amuse-mobse/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.mobse.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/mobse/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/mobse/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-mosse/pyproject.toml b/packages/amuse-mosse/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-mosse/pyproject.toml +++ b/packages/amuse-mosse/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-mosse/setup.py b/packages/amuse-mosse/setup.py index 18f9050db9..b584a12a54 100644 --- a/packages/amuse-mosse/setup.py +++ b/packages/amuse-mosse/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.mosse.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/mosse/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/mosse/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-nbody6xx/MANIFEST.in b/packages/amuse-nbody6xx/MANIFEST.in new file mode 100644 index 0000000000..ab64602564 --- /dev/null +++ b/packages/amuse-nbody6xx/MANIFEST.in @@ -0,0 +1,9 @@ +include support/__init__.py +include support/setup_codes.py +include support/version.py +include support/classifiers.py +include pyproject.toml + +recursive-include src * +recursive-exclude src *.pyc *.o *~ .pc ccache *.a + diff --git a/packages/amuse-nbody6xx/README.md b/packages/amuse-nbody6xx/README.md new file mode 100644 index 0000000000..855ee90320 --- /dev/null +++ b/packages/amuse-nbody6xx/README.md @@ -0,0 +1 @@ +This package installs the Nbody6++ community code for AMUSE. diff --git a/packages/amuse-nbody6xx/pyproject.toml b/packages/amuse-nbody6xx/pyproject.toml new file mode 100644 index 0000000000..473ccb4410 --- /dev/null +++ b/packages/amuse-nbody6xx/pyproject.toml @@ -0,0 +1,2 @@ +[build-system] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-nbody6xx/setup.py b/packages/amuse-nbody6xx/setup.py new file mode 100644 index 0000000000..93da24b2cf --- /dev/null +++ b/packages/amuse-nbody6xx/setup.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +from support.classifiers import classifiers + +from setuptools import setup + +import support +support.use("system") +from support.setup_codes import setup_commands + +name = 'amuse-nbody6xx' +author = 'The AMUSE team' +author_email = 'info@amusecode.org' +license_ = "Apache License 2.0" +url = 'http://www.amusecode.org/' +install_requires = [ + 'amuse-framework', +] +description = 'The Astrophysical Multipurpose Software Environment - Nbody6++' +with open("README.md", "r") as fh: + long_description = fh.read() +long_description_content_type = "text/markdown" + +extensions = [] + +all_data_files = [] + +packages = [ + 'amuse.community.nbody6xx', +] + +package_data = { +} + +mapping_from_command_name_to_command_class = setup_commands() + +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/nbody6xx/_version.py", +} + +setup( + name=name, + use_scm_version=use_scm_version, + setup_requires=setup_requires, + classifiers=classifiers, + url=url, + author_email=author_email, + author=author, + license=license_, + description=description, + long_description=long_description, + long_description_content_type=long_description_content_type, + install_requires=install_requires, + python_requires=">=3.7", + cmdclass=mapping_from_command_name_to_command_class, + ext_modules=extensions, + package_dir={ + 'amuse.community.nbody6xx': 'src/amuse/community/nbody6xx', + }, + packages=packages, + package_data=package_data, + data_files=all_data_files, +) diff --git a/packages/amuse-nbody6xx/src/amuse/community/nbody6xx b/packages/amuse-nbody6xx/src/amuse/community/nbody6xx new file mode 120000 index 0000000000..4f9e00f877 --- /dev/null +++ b/packages/amuse-nbody6xx/src/amuse/community/nbody6xx @@ -0,0 +1 @@ +../../../../../src/amuse/community/nbody6xx \ No newline at end of file diff --git a/packages/amuse-nbody6xx/support b/packages/amuse-nbody6xx/support new file mode 120000 index 0000000000..321fcb594c --- /dev/null +++ b/packages/amuse-nbody6xx/support @@ -0,0 +1 @@ +../../support \ No newline at end of file diff --git a/packages/amuse-petar/pyproject.toml b/packages/amuse-petar/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-petar/pyproject.toml +++ b/packages/amuse-petar/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-petar/setup.py b/packages/amuse-petar/setup.py index 708df572a2..d4f5f3fd5b 100644 --- a/packages/amuse-petar/setup.py +++ b/packages/amuse-petar/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.petar.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/petar/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/petar/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-ph4/pyproject.toml b/packages/amuse-ph4/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-ph4/pyproject.toml +++ b/packages/amuse-ph4/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-ph4/setup.py b/packages/amuse-ph4/setup.py index 13631f8d34..fc7e064342 100644 --- a/packages/amuse-ph4/setup.py +++ b/packages/amuse-ph4/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.ph4.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/ph4/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/ph4/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-phantom/pyproject.toml b/packages/amuse-phantom/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-phantom/pyproject.toml +++ b/packages/amuse-phantom/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-phantom/setup.py b/packages/amuse-phantom/setup.py index cf06170d8f..0537c9dadc 100644 --- a/packages/amuse-phantom/setup.py +++ b/packages/amuse-phantom/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.phantom.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/phantom/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/phantom/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-phigrape/pyproject.toml b/packages/amuse-phigrape/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-phigrape/pyproject.toml +++ b/packages/amuse-phigrape/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-phigrape/setup.py b/packages/amuse-phigrape/setup.py index 768028a14f..ea193e6e44 100644 --- a/packages/amuse-phigrape/setup.py +++ b/packages/amuse-phigrape/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.phigrape.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/phigrape/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/phigrape/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-seba/pyproject.toml b/packages/amuse-seba/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-seba/pyproject.toml +++ b/packages/amuse-seba/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-seba/setup.py b/packages/amuse-seba/setup.py index 0e76cf04f6..e8784b948b 100644 --- a/packages/amuse-seba/setup.py +++ b/packages/amuse-seba/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.seba.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/seba/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/seba/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-secularmultiple/pyproject.toml b/packages/amuse-secularmultiple/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-secularmultiple/pyproject.toml +++ b/packages/amuse-secularmultiple/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-secularmultiple/setup.py b/packages/amuse-secularmultiple/setup.py index 604c62cbaa..79ea80c9eb 100644 --- a/packages/amuse-secularmultiple/setup.py +++ b/packages/amuse-secularmultiple/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.secularmultiple.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/secularmultiple/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/secularmultiple/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-simplex/pyproject.toml b/packages/amuse-simplex/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-simplex/pyproject.toml +++ b/packages/amuse-simplex/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-simplex/setup.py b/packages/amuse-simplex/setup.py index e1f2fe0786..cb580c0a55 100644 --- a/packages/amuse-simplex/setup.py +++ b/packages/amuse-simplex/setup.py @@ -34,24 +34,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.simplex.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/simplex/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/simplex/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -61,7 +54,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-smalln/pyproject.toml b/packages/amuse-smalln/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-smalln/pyproject.toml +++ b/packages/amuse-smalln/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-smalln/setup.py b/packages/amuse-smalln/setup.py index e10de3ea7c..54560d413e 100644 --- a/packages/amuse-smalln/setup.py +++ b/packages/amuse-smalln/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.smalln.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/smalln/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/smalln/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-sphray/pyproject.toml b/packages/amuse-sphray/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-sphray/pyproject.toml +++ b/packages/amuse-sphray/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-sphray/setup.py b/packages/amuse-sphray/setup.py index 79d36a48df..b946444b31 100644 --- a/packages/amuse-sphray/setup.py +++ b/packages/amuse-sphray/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.sphray.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/sphray/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/sphray/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-sse/pyproject.toml b/packages/amuse-sse/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-sse/pyproject.toml +++ b/packages/amuse-sse/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-sse/setup.py b/packages/amuse-sse/setup.py index 7ba464be24..a87b58c6c4 100644 --- a/packages/amuse-sse/setup.py +++ b/packages/amuse-sse/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.sse.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/sse/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/sse/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-tests/pyproject.toml b/packages/amuse-tests/pyproject.toml index f46d75a34a..473ccb4410 100644 --- a/packages/amuse-tests/pyproject.toml +++ b/packages/amuse-tests/pyproject.toml @@ -1,4 +1,2 @@ [build-system] -requires = [ - "setuptools", "wheel", "amuse-framework", -] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-tests/setup.py b/packages/amuse-tests/setup.py index 36bc69f903..1768d0d9f7 100644 --- a/packages/amuse-tests/setup.py +++ b/packages/amuse-tests/setup.py @@ -39,24 +39,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.test.suite.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/test/suite/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/test/suite/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -66,7 +59,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-tutorial/pyproject.toml b/packages/amuse-tutorial/pyproject.toml index aff2f5236d..473ccb4410 100644 --- a/packages/amuse-tutorial/pyproject.toml +++ b/packages/amuse-tutorial/pyproject.toml @@ -1,8 +1,2 @@ [build-system] -requires = [ - 'amuse-framework>=13.0.0', - 'amuse-bhtree>=13.0.0', - 'amuse-sse>=13.0.0', - 'notebook', - 'matplotlib' -] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-tutorial/setup.py b/packages/amuse-tutorial/setup.py index 2f32cc993a..a8e2e9c5b6 100644 --- a/packages/amuse-tutorial/setup.py +++ b/packages/amuse-tutorial/setup.py @@ -27,24 +27,17 @@ 'tutorial', 'share/amuse/tutorial', '*', recursive=True ) -try: - from tutorial.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "tutorial/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "tutorial/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -54,7 +47,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", # cmdclass=mapping_from_command_name_to_command_class, data_files=all_data_files, scripts=["bin/amuse-tutorial"], diff --git a/packages/amuse-twobody/pyproject.toml b/packages/amuse-twobody/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-twobody/pyproject.toml +++ b/packages/amuse-twobody/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-twobody/setup.py b/packages/amuse-twobody/setup.py index a6304181b5..4b7a18d52a 100644 --- a/packages/amuse-twobody/setup.py +++ b/packages/amuse-twobody/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.twobody.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/twobody/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/twobody/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse-vader/pyproject.toml b/packages/amuse-vader/pyproject.toml index 5e045ac278..473ccb4410 100644 --- a/packages/amuse-vader/pyproject.toml +++ b/packages/amuse-vader/pyproject.toml @@ -1,2 +1,2 @@ [build-system] -requires = [ "setuptools", "wheel", "amuse-framework" ] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/amuse-vader/setup.py b/packages/amuse-vader/setup.py index 09730c0455..f53c32698e 100644 --- a/packages/amuse-vader/setup.py +++ b/packages/amuse-vader/setup.py @@ -33,24 +33,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.vader.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/vader/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/vader/_version.py", +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -60,7 +53,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={ diff --git a/packages/amuse/pyproject.toml b/packages/amuse/pyproject.toml index 859885b7c2..a30608fa0e 100644 --- a/packages/amuse/pyproject.toml +++ b/packages/amuse/pyproject.toml @@ -1,33 +1,33 @@ [build-system] requires = [ - 'amuse-framework[MPI]>=2021.7.0', - 'amuse-athena>=2021.7.0', - 'amuse-bhtree>=2021.7.0', - # 'amuse-brutus>=2021.7.0', - 'amuse-bse>=2021.7.0', - 'amuse-capreole>=2021.7.0', - 'amuse-evtwin>=2021.7.0', - 'amuse-fastkick>=2021.7.0', - 'amuse-fi>=2021.7.0', - 'amuse-fractalcluster>=2021.7.0', - 'amuse-gadget2>=2021.7.0', - 'amuse-galactics>=2021.7.0', - 'amuse-galaxia>=2021.7.0', - 'amuse-halogen>=2021.7.0', - 'amuse-hermite>=2021.7.0', - 'amuse-hop>=2021.7.0', - 'amuse-huayno>=2021.7.0', - 'amuse-kepler>=2021.7.0', - 'amuse-kepler-orbiters>=2021.7.0', - 'amuse-mameclot>=2021.7.0', - 'amuse-mercury>=2021.7.0', - 'amuse-mmams>=2021.7.0', - 'amuse-ph4>=2021.7.0', - 'amuse-seba>=2021.7.0', - 'amuse-secularmultiple>=2021.7.0', - 'amuse-simplex>=2021.7.0', - 'amuse-smalln>=2021.7.0', - 'amuse-sphray>=2021.7.0', - 'amuse-sse>=2021.7.0', - 'amuse-twobody>=2021.7.0', + 'amuse-framework[MPI]>=2023.5.0', + 'amuse-athena>=2023.5.0', + 'amuse-bhtree>=2023.5.0', + # 'amuse-brutus>=2023.5.0', + 'amuse-bse>=2023.5.0', + 'amuse-capreole>=2023.5.0', + 'amuse-evtwin>=2023.5.0', + 'amuse-fastkick>=2023.5.0', + 'amuse-fi>=2023.5.0', + 'amuse-fractalcluster>=2023.5.0', + 'amuse-gadget2>=2023.5.0', + 'amuse-galactics>=2023.5.0', + 'amuse-galaxia>=2023.5.0', + 'amuse-halogen>=2023.5.0', + 'amuse-hermite>=2023.5.0', + 'amuse-hop>=2023.5.0', + 'amuse-huayno>=2023.5.0', + 'amuse-kepler>=2023.5.0', + 'amuse-kepler-orbiters>=2023.5.0', + 'amuse-mameclot>=2023.5.0', + 'amuse-mercury>=2023.5.0', + 'amuse-mmams>=2023.5.0', + 'amuse-ph4>=2023.5.0', + 'amuse-seba>=2023.5.0', + 'amuse-secularmultiple>=2023.5.0', + 'amuse-simplex>=2023.5.0', + 'amuse-smalln>=2023.5.0', + 'amuse-sphray>=2023.5.0', + 'amuse-sse>=2023.5.0', + 'amuse-twobody>=2023.5.0', ] diff --git a/packages/amuse/setup.py b/packages/amuse/setup.py index fdd44a70e8..c4873c9053 100644 --- a/packages/amuse/setup.py +++ b/packages/amuse/setup.py @@ -54,24 +54,16 @@ long_description_content_type = "text/markdown" -try: - from src.amuse.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = { - "root": "../..", - "relative_to": __file__, - # "write_to": "src/amuse/version.py", - } +setup_requires = ['setuptools_scm'] +use_scm_version = { + "root": "../..", + "relative_to": __file__, +} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -81,6 +73,6 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", packages=[], ) diff --git a/packages/community_package_names b/packages/community_package_names index 75187c3d63..bc58da0834 100644 --- a/packages/community_package_names +++ b/packages/community_package_names @@ -21,9 +21,13 @@ Kepler-orbiters Mameclot Mercury Mikkola +MESA +MESA-r2208 +MESA-r15140 MMAMS MOBSE MOSSE +Nbody6xx PeTar ph4 Phantom @@ -37,3 +41,4 @@ SSE tests tutorial twobody +Vader diff --git a/packages/generate_pyproject_toml_files.sh b/packages/generate_pyproject_toml_files.sh new file mode 100644 index 0000000000..9e3d9df871 --- /dev/null +++ b/packages/generate_pyproject_toml_files.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash + +while read -r line; do + pkgdir=$(echo "print('amuse-${line}'.lower())" | python); + echo ${pkgdir} + cp pyproject.toml_template ${pkgdir}/pyproject.toml; +done < community_package_names diff --git a/packages/pyproject.toml_template b/packages/pyproject.toml_template new file mode 100644 index 0000000000..473ccb4410 --- /dev/null +++ b/packages/pyproject.toml_template @@ -0,0 +1,2 @@ +[build-system] +requires = ["setuptools>=65.0.0", "wheel>=0.30", "amuse-framework>=2023.5.0"] diff --git a/packages/setup_template.py b/packages/setup_template.py index f6ebf93ed7..f86089a379 100644 --- a/packages/setup_template.py +++ b/packages/setup_template.py @@ -37,24 +37,17 @@ mapping_from_command_name_to_command_class = setup_commands() -try: - from src.amuse.community.{name_lowercase}.version import version - use_scm_version = False - setup_requires = [] -except ImportError: - version = False - setup_requires = ['setuptools_scm'] - use_scm_version = {{ - "root": "../..", - "relative_to": __file__, - "write_to": "src/amuse/community/{name_lowercase}/version.py", - }} +setup_requires = ['setuptools_scm'] +use_scm_version = {{ + "root": "../..", + "relative_to": __file__, + "version_file": "src/amuse/community/{name_lowercase}/_version.py", +}} setup( name=name, use_scm_version=use_scm_version, setup_requires=setup_requires, - version=version, classifiers=classifiers, url=url, author_email=author_email, @@ -64,7 +57,7 @@ long_description=long_description, long_description_content_type=long_description_content_type, install_requires=install_requires, - python_requires=">=3.5", + python_requires=">=3.7", cmdclass=mapping_from_command_name_to_command_class, ext_modules=extensions, package_dir={{ diff --git a/requirements.txt b/requirements.txt index e99fcc12ec..da4f7ea761 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,8 +1,8 @@ -setuptools>=45 +setuptools>=65 setuptools_scm>=6 -wheel -docutils>=0.6 -numpy>=1.2.2 +wheel>=0.30 +docutils>=0.18 +numpy>=1.18 pytest>=3.0 -mpi4py>=1.1.0 -h5py>=1.1.0 +mpi4py>=3.0 +h5py>=3.0 diff --git a/src/amuse/community/gadget2/interface.cc b/src/amuse/community/gadget2/interface.cc index 6543e80047..6902bcfdb2 100644 --- a/src/amuse/community/gadget2/interface.cc +++ b/src/amuse/community/gadget2/interface.cc @@ -1453,6 +1453,7 @@ int check_counts_and_free(int *count, int length){ #ifndef NOMPI MPI_Reduce(count, NULL, length, MPI_INT, MPI_SUM, 0, GADGET_WORLD); #endif + delete[] count; return 0; } else { #ifndef NOMPI diff --git a/src/amuse/community/mesa_r15140/Makefile b/src/amuse/community/mesa_r15140/Makefile index 62b2a75433..9f87bbb838 100644 --- a/src/amuse/community/mesa_r15140/Makefile +++ b/src/amuse/community/mesa_r15140/Makefile @@ -10,6 +10,7 @@ GFORTRAN_VERSION?=$(shell $(FC) -v 2>&1 | grep gcc\ version | cut -d\ -f3) GFORTRAN_MAJOR_MINOR=$(shell echo $(GFORTRAN_VERSION) | cut -s -d'.' -f1,2) #IFORT_VERSION?=$(shell $(FC) -v 2>&1 | cut -d\ -f2) #IFORT_MAJOR_MINOR=$(shell echo $(IFORT_VERSION) | cut -s -d'.' -f1,2) +MPIFC ?= mpif90 MPIF90 ?= mpif90 MPICC ?= mpicc FORTRAN ?= gfortran diff --git a/src/amuse/community/mesa_r15140/download.py b/src/amuse/community/mesa_r15140/download.py index 66af895ccb..7f247875d9 100755 --- a/src/amuse/community/mesa_r15140/download.py +++ b/src/amuse/community/mesa_r15140/download.py @@ -77,7 +77,7 @@ def get_crmath(): def get_crlibm(): instance = GetCodeFromHttp() - instance.url_template = 'http://www.astro.wisc.edu/~townsend/resource/download/sdk2/src/crlibm-{version}.tar.gz' + instance.url_template = 'http://user.astro.wisc.edu/~townsend/resource/download/sdk2/src/crlibm-{version}.tar.gz' instance.filename_template='crlibm-{version}.tar.gz' instance.version = '1.0beta4' instance.zip = False @@ -94,7 +94,7 @@ def get_fpx3deps(): def get_fpx3(): instance = GetCodeFromHttp() - instance.url_template = 'http://www.astro.wisc.edu/~townsend/resource/download/sdk2/src/fpx3.tar.gz' + instance.url_template = 'http://user.astro.wisc.edu/~townsend/resource/download/sdk2/src/fpx3.tar.gz' instance.filename_template='fpx3.tar.gz' instance.version = '' instance.zip = False @@ -102,8 +102,8 @@ def get_fpx3(): def get_lapack95(): instance = GetCodeFromHttp() - instance.url_template = 'http://www.astro.wisc.edu/~townsend/resource/download/sdk2/src/lapack95.tgz' - instance.filename_template='lapack95.tar.gz' + instance.url_template = 'http://user.astro.wisc.edu/~townsend/resource/download/sdk2/src/lapack95.tgz' + instance.filename_template='lapack95.tgz' instance.version = '' instance.zip = False instance.start() @@ -122,7 +122,7 @@ def get_mesa(): def get_hdf5(): instance = GetCodeFromHttp() instance.url_template = "https://support.hdfgroup.org/ftp/HDF5/releases/hdf5-1.12/hdf5-{version}/src/hdf5-{version}.tar.bz2" - instance.filename_template='hdf-{version}.tar.bz2' + instance.filename_template='hdf5-{version}.tar.bz2' instance.version = '1.12.0' instance.zip = False instance.start() diff --git a/src/amuse/community/mesa_r15140/examples/photo_load.py b/src/amuse/community/mesa_r15140/examples/photo_load.py new file mode 100644 index 0000000000..9ae637f77b --- /dev/null +++ b/src/amuse/community/mesa_r15140/examples/photo_load.py @@ -0,0 +1,54 @@ +import matplotlib.pyplot as plt +import numpy as np + +from amuse.units import units +from amuse.community.mesa.interface import MESA +from amuse import datamodel + +stellar_evolution = MESA(version='15140') + +masses=[2.0] | units.MSun +stars = datamodel.Particles(len(masses), mass=masses) + +stars = stellar_evolution.native_stars.add_particles(stars) +star = stars[0] + +star.evolve_one_step() + +print(star.time_step) + +star.time_step = 1. | units.yr + +star.evolve_one_step() + +star.save_photo('photo') +star.save_model('model.mod') + + +star.evolve_one_step() + +age = star.age + +model_number = star.get_history('model_number') + + +masses=[1.0] | units.MSun +stars = datamodel.Particles(len(masses), mass=masses,filename=['photo']) + +stars = stellar_evolution.photo_stars.add_particles(stars) +star = stars[0] + +star.evolve_one_step() # Photos will give exactly the same answer compared to a run without a save/load + +print(star.age, star.get_history('model_number'), star.mass) + + +masses=[1.0] | units.MSun +stars = datamodel.Particles(len(masses), mass=masses,filename=['model.mod']) + +stars = stellar_evolution.pre_built_stars.add_particles(stars) +star = stars[0] + +star.evolve_one_step() # Models do not give exactly the same answer as a photo + +print(star.age, star.get_history('model_number'), star.mass) \ No newline at end of file diff --git a/src/amuse/community/mesa_r15140/interface.f90 b/src/amuse/community/mesa_r15140/interface.f90 index a642684326..3d95a4115b 100644 --- a/src/amuse/community/mesa_r15140/interface.f90 +++ b/src/amuse/community/mesa_r15140/interface.f90 @@ -584,7 +584,7 @@ integer function get_stellar_type(AMUSE_id, AMUSE_value) integer, intent(out) :: AMUSE_value integer :: ierr double precision :: lgR, mass, ch1, che3, che4, cc12, cne20 - double precision :: lgL, lgLH, ah1, ahe3, ahe4, lgLHe + double precision :: lgL, lgLH, ah1, ahe3, ahe4, lgLHe, logg AMUSE_value = -99 get_stellar_type = -1 @@ -618,9 +618,12 @@ integer function get_stellar_type(AMUSE_id, AMUSE_value) call get_history_value(AMUSE_id,'average he4',ahe4, ierr) if(ierr/=MESA_SUCESS) return + call get_history_value(AMUSE_id,'photosphere_logg',logg, ierr) + if(ierr/=MESA_SUCESS) return + - if (lgR > -1.0) then + if (logg < 6.0) then if(ch1 > 1d-4) then ! MS if(lgLH-lgL < -1 ) then ! Pre-main-sequence star AMUSE_value = 17 @@ -1306,6 +1309,78 @@ end function get_gyre +!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +! Procedures for manually controlling how a step gets taken +!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + + integer function solve_one_step(AMUSE_ID, first_try, result) + integer, intent(in) :: AMUSE_ID + logical, intent(in) :: first_try + integer, intent(out) :: result + integer :: ierr + + ierr = 0 + + call do_solve_one_step(AMUSE_ID, first_try, result, ierr) + solve_one_step = ierr + + end function solve_one_step + + integer function solve_one_step_pre(AMUSE_ID, result) + integer, intent(in) :: AMUSE_ID + integer, intent(out) :: result + integer :: ierr + + call do_solve_one_step_pre(AMUSE_ID, result, ierr) + solve_one_step_pre = ierr + + end function solve_one_step_pre + + + integer function solve_one_step_post(AMUSE_ID, result) + integer, intent(in) :: AMUSE_ID + integer, intent(out) :: result + integer :: ierr + + call do_solve_one_step_post(AMUSE_ID, result, ierr) + solve_one_step_post = ierr + + end function solve_one_step_post + + + integer function prepare_retry_step(AMUSE_ID, dt, result) + ! Prepare toretake a timestep with a different dt + ! Does not actualy retry the step + integer, intent(in) :: AMUSE_ID + double precision,intent(in) :: dt + integer, intent(out) :: result + integer :: ierr + + + call set_current_dt(AMUSE_ID, dt, ierr) ! Sets dt not dt_next + if(ierr/=MESA_SUCESS) then + prepare_retry_step = ierr + return + end if + + result = do_prepare_for_retry(AMUSE_id) + prepare_retry_step = 0 + + end function prepare_retry_step + + + integer function prepare_redo_step(AMUSE_ID, result) + ! Retake the same timestep with the same dt. Useful when mdot changes + ! Does not actualy redo the step + integer, intent(in) :: AMUSE_ID + integer, intent(out) :: result + integer :: ierr + + result = do_prepare_for_redo(AMUSE_id) + prepare_redo_step = 0 + + end function prepare_redo_step end module AMUSE_mesa \ No newline at end of file diff --git a/src/amuse/community/mesa_r15140/interface.py b/src/amuse/community/mesa_r15140/interface.py index 38a5f81dcf..980c1b3ef6 100644 --- a/src/amuse/community/mesa_r15140/interface.py +++ b/src/amuse/community/mesa_r15140/interface.py @@ -914,7 +914,7 @@ def get_gyre(self, index_of_the_star, mode_l=0, """ Get gyre data. - This returns a list of dicts where each element of the list coresponds to one mode + This returns a list of dicts where each element of the list corresponds to one mode Each dict contains the pg,p,g and complex frequency for the mode as well as arrays of r/R, xi_r, xi_h, and dwdx for the mode @@ -963,7 +963,6 @@ def get_mixing_length_ratio(self,index_of_the_star): """ Retrieve the current mixing_length_ratio of the star. """ - return self.get_control(index_of_the_star,'mixing_length_alpha') def set_mixing_length_ratio(self,index_of_the_star, mixing_length_ratio): @@ -1126,6 +1125,81 @@ def set_accrete_composition_metals(self, index_of_the_star, **kwargs): return r + @legacy_function + def solve_one_step(): + """ + Takes one step forward, but does not handle retries or redo's. + Must call solve_one_step_pre first and solve_one_step_post afterwards + """ + function = LegacyFunctionSpecification() + function.addParameter('index_of_the_star', dtype='int32', direction=function.IN + , description="The index of the star to get the value of") + function.addParameter('first_try', dtype='bool', direction=function.IN + , description="If this is the first attempt at taking this timestep") + function.addParameter('result', dtype='int32', direction=function.OUT + , description="What the star should do next (keep going, redo, retry, terminate)") + function.result_type = 'int32' + return function + + + @legacy_function + def solve_one_step_pre(): + """ + Prepares to takes one step forward, but does not handle retries or redo's. + Called before solve_one_step + """ + function = LegacyFunctionSpecification() + function.addParameter('index_of_the_star', dtype='int32', direction=function.IN + , description="The index of the star to get the value of") + function.addParameter('result', dtype='int32', direction=function.OUT + , description="What the star should do next (keep going, redo, retry, terminate)") + function.result_type = 'int32' + return function + + @legacy_function + def solve_one_step_post(): + """ + After taking one step forward cleanup the model, but does not handle retries or redo's. + Called after solve_one_step + """ + function = LegacyFunctionSpecification() + function.addParameter('index_of_the_star', dtype='int32', direction=function.IN + , description="The index of the star to get the value of") + function.addParameter('result', dtype='int32', direction=function.OUT + , description="What the star should do next (keep going, redo, retry, terminate)") + function.result_type = 'int32' + return function + + @legacy_function + def prepare_retry_step(): + """ + Prepares to retry a step with a new dt. + Does not actually take the step + """ + function = LegacyFunctionSpecification() + function.addParameter('index_of_the_star', dtype='int32', direction=function.IN + , description="The index of the star to get the value of") + function.addParameter('dt_next', dtype='float64', direction=function.IN + , description="New timestep to try") + function.addParameter('result', dtype='int32', direction=function.OUT + , description="What the star should do next (keep going, redo, retry, terminate)") + function.result_type = 'int32' + return function + + @legacy_function + def prepare_redo_step(): + """ + Prepares to redo a step (a step with the same dt but where you have changed other options like the mdot) + Does not actually take the step + """ + function = LegacyFunctionSpecification() + function.addParameter('index_of_the_star', dtype='int32', direction=function.IN + , description="The index of the star to get the value of") + function.addParameter('result', dtype='int32', direction=function.OUT + , description="What the star should do next (keep going, redo, retry, terminate)") + function.result_type = 'int32' + return function + class MESA(StellarEvolution, InternalStellarStructure): @@ -1333,6 +1407,13 @@ def define_particle_sets(self, handler): handler.add_method(particle_set_name, 'get_blocker_wind_efficiency') handler.add_method(particle_set_name, 'set_blocker_wind_efficiency') + handler.add_method(particle_set_name, 'solve_one_step') + handler.add_method(particle_set_name, 'solve_one_step_pre') + handler.add_method(particle_set_name, 'solve_one_step_post') + handler.add_method(particle_set_name, 'prepare_retry_step') + handler.add_method(particle_set_name, 'prepare_redo_step') + + def define_state(self, handler): StellarEvolution.define_state(self, handler) handler.add_method('EDIT', 'new_pre_ms_particle') @@ -1776,6 +1857,36 @@ def define_methods(self, handler): (handler.ERROR_CODE) ) + handler.add_method( + "solve_one_step", + (handler.INDEX, handler.NO_UNIT), + (handler.NO_UNIT,handler.ERROR_CODE) + ) + + handler.add_method( + "solve_one_step_pre", + (handler.INDEX), + (handler.NO_UNIT,handler.ERROR_CODE) + ) + + handler.add_method( + "solve_one_step_post", + (handler.INDEX), + (handler.NO_UNIT,handler.ERROR_CODE) + ) + + handler.add_method( + "prepare_retry_step", + (handler.INDEX, units.s), + (handler.NO_UNIT,handler.ERROR_CODE) + ) + + handler.add_method( + "prepare_redo_step", + (handler.INDEX), + (handler.NO_UNIT,handler.ERROR_CODE) + ) + def initialize_module_with_default_parameters(self): self.parameters.set_defaults() self.initialize_code() diff --git a/src/amuse/community/mesa_r15140/mesa_interface.f90 b/src/amuse/community/mesa_r15140/mesa_interface.f90 index 5c4c26a482..a3c4d804c7 100644 --- a/src/amuse/community/mesa_r15140/mesa_interface.f90 +++ b/src/amuse/community/mesa_r15140/mesa_interface.f90 @@ -569,6 +569,95 @@ subroutine do_evolve_one_step(id, result, ierr) end subroutine do_evolve_one_step + integer function do_prepare_for_redo(id) + integer, intent(in) :: id + do_prepare_for_redo = star_prepare_to_redo(id) + end function do_prepare_for_redo + + integer function do_prepare_for_retry(id) + integer, intent(in) :: id + do_prepare_for_retry = star_prepare_to_retry(id) + end function do_prepare_for_retry + + + subroutine do_solve_one_step_pre(id, result, ierr) + integer, intent(in) :: id + integer, intent(out) :: result, ierr + type (star_info), pointer :: s + + integer :: model_number + logical :: continue_evolve_loop, first_try + logical,parameter :: dbg=.false. + + ierr = MESA_SUCESS + + call star_ptr(id, s, ierr) + if (failed('star_ptr',ierr)) return + + call before_step_loop(s% id, ierr) + if (failed('before_step_loop',ierr)) return + + result = s% extras_start_step(id) + if (result /= keep_going) return + + + end subroutine do_solve_one_step_pre + + + subroutine do_solve_one_step(id, first_try, result, ierr) + integer, intent(in) :: id + logical, intent(in) :: first_try + integer, intent(out) :: result, ierr + type (star_info), pointer :: s + + integer :: model_number + logical :: continue_evolve_loop + logical,parameter :: dbg=.false. + + ierr = MESA_SUCESS + + call star_ptr(id, s, ierr) + if (failed('star_ptr',ierr)) return + + + result = star_evolve_step(id, first_try) + if (result == keep_going) result = star_check_model(id) + if (result == keep_going) result = s% extras_check_model(id) + if (result == keep_going) result = star_pick_next_timestep(id) + if (result == keep_going) return + + end subroutine do_solve_one_step + + + subroutine do_solve_one_step_post(id, result, ierr) + integer, intent(in) :: id + integer, intent(out) :: result, ierr + type (star_info), pointer :: s + + integer :: model_number + logical :: continue_evolve_loop, first_try + logical,parameter :: dbg=.false. + + ierr = MESA_SUCESS + + call star_ptr(id, s, ierr) + if (failed('star_ptr',ierr)) return + + + s% doing_first_model_of_run = .false. + + call after_step_loop(s% id, s% inlist_fname, & + dbg, result, ierr) + if (failed('after_step_loop',ierr)) return + + call do_saves(id, ierr) + if (failed('do_saves',ierr)) return + + call flush() + + end subroutine do_solve_one_step_post + + subroutine evolve_until(id, delta_t, ierr) integer, intent(in) :: id real(dp), intent(in) :: delta_t @@ -639,6 +728,7 @@ subroutine set_model_number(id, new_number, ierr) s% model_number = new_number end subroutine set_model_number + subroutine set_timestep(id, dt_next, ierr) integer, intent(in) :: id real(dp), intent(in) :: dt_next @@ -649,6 +739,19 @@ subroutine set_timestep(id, dt_next, ierr) end subroutine set_timestep + subroutine set_current_dt(id, dt, ierr) + integer, intent(in) :: id + real(dp), intent(in) :: dt + integer, intent(out) :: ierr + type (star_info), pointer :: s + + call star_ptr(id, s, ierr) + if (failed('set_dt',ierr)) return + + s% dt = dt + + end subroutine set_current_dt + subroutine set_new_mass(id, new_mass, ierr) integer, intent(in) :: id real(dp), intent(in) :: new_mass diff --git a/src/amuse/community/mesa_r15140/patches/makefile_header_non_mesasdk b/src/amuse/community/mesa_r15140/patches/makefile_header_non_mesasdk index e2af426048..22411b7d41 100644 --- a/src/amuse/community/mesa_r15140/patches/makefile_header_non_mesasdk +++ b/src/amuse/community/mesa_r15140/patches/makefile_header_non_mesasdk @@ -417,7 +417,7 @@ CP_IF_NEWER = $(MESA_DIR)/utils/cp_if_newer # makedepf90 invocation (depends on whether we have the SDK2-patched version that # supports the -X flag) -ifneq ($(shell makedepf90 -V | grep sdk2),) +ifneq ($(shell src/makedepf90 -V | grep sdk2),) MAKEDEPF90_IGNORE_MODS = intrinsic omp_lib iso_c_binding iso_fortran_env ieee_arithmetic crmath hdf5 MAKEDEPF90 := $(MESA_DIR)/utils/makedepf90-2.8.8/makedepf90 -m %m.mod -X $(addprefix -u,$(MAKEDEPF90_IGNORE_MODS)) else diff --git a/src/amuse/community/mpiamrvac/patch_files.py b/src/amuse/community/mpiamrvac/patch_files.py index 745536d73c..a913ee6fb1 100755 --- a/src/amuse/community/mpiamrvac/patch_files.py +++ b/src/amuse/community/mpiamrvac/patch_files.py @@ -6,53 +6,78 @@ import re PATCHESDIR = "patches" -QUILT_PC = ".pc" +QUILT_PC = ".pc" -def execute_command_line(arguments, cwd = None): - process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd = cwd) + +def execute_command_line(arguments, cwd=None): + process = subprocess.Popen( + arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd + ) stdoutstring, stderrstring = process.communicate() returncode = process.poll() return stdoutstring, stderrstring, returncode - + + def which(executablename): - stdoutstring, stderrstring, returncode = execute_command_line(['which', executablename]) + stdoutstring, stderrstring, returncode = execute_command_line( + ["which", executablename] + ) if not returncode == 0: return None else: return stdoutstring - + + def is_quilt_installed(): - path = which('quilt') + path = which("quilt") if path is None: return False - - stdoutstring, stderrstring, returncode = execute_command_line(['quilt', '--version']) + + stdoutstring, stderrstring, returncode = execute_command_line( + ["quilt", "--version"] + ) if not returncode == 0: return False - - version_re = re.compile(r'(\d).(\d\d)') - match = version_re.match(stdoutstring) + + version_re = re.compile(r"(\d).(\d\d)") + match = version_re.match(str(stdoutstring)) if not match: return False - + return True + def apply_patches_using_quilt(): - returncode = subprocess.call(['quilt', 'push', '-a']) + returncode = subprocess.call(["quilt", "push", "-a"]) if not returncode == 0: - raise Exception("error in applying the patches, please apply by hand using quilt push") - + raise Exception( + "error in applying the patches, please apply by hand using quilt push" + ) + + def undo_patches_using_quilt(): - returncode = subprocess.call(['quilt', 'pop', '-a']) + returncode = subprocess.call(["quilt", "pop", "-a"]) if not returncode == 0: - raise Exception("error in undoing the patches, please undo by hand using quilt pop -a") + raise Exception( + "error in undoing the patches, please undo by hand using quilt pop -a" + ) + def run_patch(patchname, patchfile): - arguments = ['patch', '-p1', '--backup', '--prefix={0}/{1}/'.format(QUILT_PC, patchname), '-E', '-i', patchfile] + arguments = [ + "patch", + "-p1", + "--backup", + "--prefix={0}/{1}/".format(QUILT_PC, patchname), + "-E", + "-i", + patchfile, + ] returncode = subprocess.call(arguments) if not returncode == 0: raise Exception("could not apply patch {0}".format(patchname)) - + + def apply_patches_using_patch(): with open("patches/series", "r") as f: lines = f.readlines() @@ -61,12 +86,13 @@ def apply_patches_using_patch(): for patch in patches: path = os.path.join(PATCHESDIR, patch) run_patch(patch, path) - -def main(undo_patches = False): - print("checking if quilt is installed ... ", end=' ') + + +def main(undo_patches=False): + print("checking if quilt is installed ... ", end=" ") if not is_quilt_installed(): print("no") - + if undo_patches: print("quilt is not installed, cannot undo the patches") sys.exit(1) @@ -75,7 +101,7 @@ def main(undo_patches = False): apply_patches_using_patch() else: print("yes") - + if undo_patches: print("quilt is install, will try to undo the patches") undo_patches_using_quilt() @@ -83,6 +109,7 @@ def main(undo_patches = False): print("applying patches to source code") apply_patches_using_quilt() print("all patches applied") - -if __name__ == '__main__': + + +if __name__ == "__main__": main() diff --git a/src/amuse/community/petar/Makefile b/src/amuse/community/petar/Makefile index 656662ec38..44445b8d3c 100644 --- a/src/amuse/community/petar/Makefile +++ b/src/amuse/community/petar/Makefile @@ -40,7 +40,7 @@ LDFLAGS += -lm $(MUSE_LD_FLAGS) OBJS = interface.o -FILELIST=interface.cc interface.py interface.h +DIRLIST=src/PeTar src/SDAR src/FDPS CODELIB = @@ -53,30 +53,23 @@ clean: # make -C src clean distclean: clean - rm -rf src $(FILELIST) + rm -rf src #$(CODELIB): # make -C src all DOWNLOAD_FROM_WEB = $(PYTHON) ./download.py -download: - $(RM) -Rf .pc - $(RM) -Rf src - mkdir src +$(DIRLIST): +# $(RM) -Rf .pc +# $(RM) -Rf src +# mkdir src $(DOWNLOAD_FROM_WEB) - cp src/PeTar/amuse-interface/interface.py ./ - cp src/PeTar/amuse-interface/interface.h ./ - cp src/PeTar/amuse-interface/interface.cc ./ - - __init__.py: touch $@ -$(FILELIST): |download - -src/PeTar/src/get_version.hpp: src/PeTar/src/get_version.hpp.in |src/PeTar +src/PeTar/src/get_version.hpp: |src/PeTar sed 's/@VERSION@/'`cat src/PeTar/VERSION`'_'`cat src/SDAR/VERSION`'/g' src/PeTar/src/get_version.hpp.in >src/PeTar/src/get_version.hpp test_interface: $(OBJS) test_interface.o @@ -91,5 +84,5 @@ worker_code.h: interface.py petar_worker: worker_code.cc worker_code.h $(CODELIB) $(OBJS) interface.h $(MPICXX) $(CXXFLAGS) $(SC_FLAGS) $(AM_CFLAGS) $(LDFLAGS) $< $(OBJS) $(CODELIB) -o $@ $(SC_MPI_CLIBS) $(LIBS) $(AM_LIBS) -interface.o: interface.cc src/PeTar/src/get_version.hpp +interface.o: interface.cc src/PeTar/src/get_version.hpp |$(DIRLIST) $(MPICXX) $(CXXFLAGS) $(SC_FLAGS) -c -o $@ $< diff --git a/src/amuse/community/petar/download.py b/src/amuse/community/petar/download.py index efe54061a6..85f7ed5cfa 100644 --- a/src/amuse/community/petar/download.py +++ b/src/amuse/community/petar/download.py @@ -47,21 +47,25 @@ def unpack_downloaded_file(self, filename, name, version): print("done") def start(self): - if os.path.exists('src'): - counter = 0 - while os.path.exists('src.{0}'.format(counter)): - counter += 1 - if counter > 100: - print("too many backup directories") - break - os.rename('src', 'src.{0}'.format(counter)) - - os.mkdir('src') + if not os.path.exists('src'): + os.mkdir('src') +# if not update_flag: +# return +# counter = 0 +# while os.path.exists('src.{0}'.format(counter)): +# counter += 1 +# if counter > 100: +# print("too many backup directories") +# break +# os.rename('src', 'src.{0}'.format(counter)) for i, url_template in enumerate(self.url_template): url = url_template.format(version=self.version[i]) filename = self.filename_template.format(version=self.version[i]) filepath = os.path.join(self.src_directory(), filename) + if os.path.exists('src/'+self.name[i]): + print("src/%s exist" % self.name[i]) + continue print( "downloading version", self.version[i], "from", url, "to", filename @@ -101,21 +105,21 @@ def new_option_parser(): result = OptionParser() result.add_option( "--petar-version", - default='22437b74c6541fc9451607fb2933558bd6924a41', + default='6ccac364e83ab05e4dad27e6eb6abdf7e5c89bcc', dest="petar_version", help="PeTar commit hash to download", type="string" ) result.add_option( "--sdar-version", - default='cebf0a9cbd17111c6917e1120452bb9f661e33b0', + default='a4ff4b3d076535684313a912ea31985c1431f827', dest="sdar_version", help="SDAR commit hash to download", type="string" ) result.add_option( "--fdps-version", - default='7b02b365b7377c0d5239bf309a2012e71575ef97', + default='55b2bafd316805bad22057cf4ee96217735279bf', dest="fdps_version", help="FDPS commit hash to download", type="string" diff --git a/src/amuse/community/petar/interface.cc b/src/amuse/community/petar/interface.cc new file mode 100644 index 0000000000..32717b00a5 --- /dev/null +++ b/src/amuse/community/petar/interface.cc @@ -0,0 +1,1076 @@ +#include "petar.hpp" +#include "interface.h" + +// AMUSE STOPPING CONDITIONS SUPPORT +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Interface code + */ + + static PeTar* ptr=NULL; + static double time_start = 0.0; +#ifdef USE_SIMD + static CalcForcePPSimd fcalc; // Force calculator +#else + static CalcForcePPNoSimd fcalc; +#endif + static int n_particle_in_interrupt_connected_cluster_glb; // + + // flags + static bool particle_list_change_flag=true; + static bool initial_particle_flag=false; + + // common + + int initialize_code() { + PeTar::initial_fdps_flag = true; + ptr = new PeTar; + + int argc = 0; + char **argv=NULL; + + n_particle_in_interrupt_connected_cluster_glb = 0; + + //No second MPI init + //ptr->initialFDPS(argc,argv); + //ptr->initial_fdps_flag = true; + //ptr->my_rank= PS::Comm::getRank(); + //ptr->n_proc = PS::Comm::getNumberOfProc(); + +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: Initialize_code start\n"; +#endif + + // set print flag to rank 0 + ptr->input_parameters.print_flag = (ptr->my_rank==0) ? true: false; + // set writing flag to false + ptr->input_parameters.write_style.value = 0; + + // default input + int flag= ptr->readParameters(argc,argv); + + // set id_offset + ptr->input_parameters.id_offset.value = 10000000; + + // set restart flat to false + ptr->file_header.nfile = 0; + +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: Initialize_code end\n"; +#endif + return flag; + } + + int cleanup_code() { +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: cleanup_code start\n"; +#endif + delete ptr; + ptr=NULL; +//#ifdef INTERFACE_DEBUG_PRINT +// if(ptr->my_rank==0) std::cout<<"PETAR: cleanup_code end\n"; +//#endif + return 0; + } + + int commit_parameters() { +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: commit_parameters start\n"; +#endif + if (!ptr->read_parameters_flag) return -1; + + // set stopping condtions support + set_support_for_condition(COLLISION_DETECTION); + set_support_for_condition(PAIR_DETECTION); + +#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL + mpi_setup_stopping_conditions(); +#endif + +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: commit_parameters end\n"; +#endif + return 0; + } + + int recommit_parameters() { +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: recommit_parameters start\n"; +#endif + ptr->input_parameters.n_glb.value = ptr->stat.n_real_glb; + ptr->input_parameters.update_changeover_flag = true; + ptr->input_parameters.update_rsearch_flag = true; + ptr->initialParameters(); + ptr->initial_step_flag = false; + + // set stopping condtions support + set_support_for_condition(COLLISION_DETECTION); + set_support_for_condition(PAIR_DETECTION); + +#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL + mpi_setup_stopping_conditions(); +#endif + +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: recommit_parameters end\n"; +#endif + return 0; + } + + // GravitationalDynamicsInterface + + int new_particle(int* index_of_the_particle, double mass, double x, double y, double z, double vx, double vy, double vz, double radius) { + // if not yet initial the system +#ifdef INTERFACE_DEBUG_PRINT + if (!ptr->read_data_flag && ptr->my_rank==0) { + std::cout<<"New particle, rank "<my_rank<read_data_flag = true; + + PS::S64 id_offset = ptr->input_parameters.id_offset.value; + PS::S64 n_glb = ptr->stat.n_real_glb; + PS::S64 n_loc = ptr->stat.n_real_loc; +#ifdef INTERFACE_DEBUG + assert(n_loc == ptr->system_soft.getNumberOfParticleLocal()); + assert(n_glb == ptr->system_soft.getNumberOfParticleGlobal()); +#endif + + if(ptr->my_rank==0) { + FPSoft p; + p.mass = mass; + p.pos.x = x; + p.pos.y = y; + p.pos.z = z; + p.vel.x = vx; + p.vel.y = vy; + p.vel.z = vz; + p.radius = radius; + + if (ptr->initial_parameters_flag) p.calcRSearch(ptr->input_parameters.dt_soft.value); + p.id = n_glb+1; + if (p.id>=id_offset) return -1; + p.group_data.artificial.setParticleTypeToSingle(); + + p.rank_org = ptr->my_rank; + p.adr = n_loc; + + if (initial_particle_flag) { + PS::F64 m_fac = p.mass*Ptcl::mean_mass_inv; + PS::F64 r_out = ptr->input_parameters.r_out.value; + PS::F64 r_in = r_out*ptr->input_parameters.ratio_r_cut.value; + p.changeover.setR(m_fac, r_in, r_out); + p.calcRSearch(ptr->input_parameters.dt_soft.value); + } + + ptr->system_soft.addOneParticle(p); + + ptr->stat.n_real_loc++; + *index_of_the_particle = p.id; +#ifdef INTERFACE_DEBUG_PRINT + std::cout<stat.n_real_glb++; + + particle_list_change_flag = true; + + return 0; + } + + int delete_particle(int index_of_the_particle) { + int index = ptr->getParticleAdrFromID(index_of_the_particle); + if (index>=0) { + ptr->remove_list.push_back(index); + //ptr->stat.n_real_loc--; +#ifdef INTERFACE_DEBUG_PRINT + std::cout<<"Remove particle index "<my_rank<getParticleAdrFromID(index_of_the_particle); +#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL + int rank_mask = index==-1 ? 0 : ptr->my_rank; + int particle_rank = PS::Comm::getSum(rank_mask); + if (particle_rank==0) { + if (index==-1) return -1; + FPSoft* p = &(ptr->system_soft[index]); + *mass = p->mass; + *x = p->pos.x; + *y = p->pos.y; + *z = p->pos.z; + *vx = p->vel.x; + *vy = p->vel.y; + *vz = p->vel.z; + *radius = p->radius; + } + else { + if (ptr->my_rank==particle_rank) { // sender + FPSoft* p = &(ptr->system_soft[index]); + MPI_Send(p, 7, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD); + } + else if (ptr->my_rank==0) { // receiver + ParticleBase p; + MPI_Recv(&p, 7, MPI_DOUBLE, particle_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + + *mass = p.mass; + *x = p.pos.x; + *y = p.pos.y; + *z = p.pos.z; + *vx = p.vel.x; + *vy = p.vel.y; + *vz = p.vel.z; + *radius = p.radius; + } + } +#else + if (index>=0) { + FPSoft* p = &(ptr->system_soft[index]); + *mass = p->mass; + *x = p->pos.x; + *y = p->pos.y; + *z = p->pos.z; + *vx = p->vel.x; + *vy = p->vel.y; + *vz = p->vel.z; + *radius = p->radius; + } + else return -1; +#endif + return 0; + } + + int set_state(int index_of_the_particle, + double mass, + double x, double y, double z, + double vx, double vy, double vz, double radius) { + reconstruct_particle_list(); + int index = ptr->getParticleAdrFromID(index_of_the_particle); + if (index>=0) { + FPSoft* p = &(ptr->system_soft[index]); + p->mass = mass; + p->pos.x = x; + p->pos.y = y; + p->pos.z = z; + p->vel.x = vx; + p->vel.y = vy; + p->vel.z = vz; + p->radius= radius; + } +#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL + int check = PS::Comm::getMaxValue(index); + if (check==-1) return -1; +#else + else return -1; +#endif + return 0; + } + + int get_mass(int index_of_the_particle, double * mass) { + reconstruct_particle_list(); + int index = ptr->getParticleAdrFromID(index_of_the_particle); +#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL + double mass_local = 0.0; + if (index>=0) { + FPSoft* p = &(ptr->system_soft[index]); + mass_local = p->mass; + } + *mass = PS::Comm::getSum(mass_local); + int check = PS::Comm::getMaxValue(index); + if (check==-1) return -1; +#else + if (index>=0) { + FPSoft* p = &(ptr->system_soft[index]); + *mass = p->mass; + } + else return -1; +#endif + return 0; + } + + int set_mass(int index_of_the_particle, double mass) { + reconstruct_particle_list(); + int index = ptr->getParticleAdrFromID(index_of_the_particle); + if (index>=0) { + FPSoft* p = &(ptr->system_soft[index]); + p->mass = mass; + } +#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL + int check = PS::Comm::getMaxValue(index); + if (check==-1) return -1; +#else + else return -1; +#endif + return 0; + } + + int get_radius(int index_of_the_particle, double * radius) { + reconstruct_particle_list(); + int index = ptr->getParticleAdrFromID(index_of_the_particle); +#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL + double radius_local = 0.0; + if (index>=0) { + FPSoft* p = &(ptr->system_soft[index]); + radius_local = p->radius; + } + *radius = PS::Comm::getSum(radius_local); + int check = PS::Comm::getMaxValue(index); + if (check==-1) return -1; +#else + if (index>=0) { + FPSoft* p = &(ptr->system_soft[index]); + *radius = p->radius; + } + else return -1; +#endif + return 0; + } + + int set_radius(int index_of_the_particle, double radius) { + reconstruct_particle_list(); + int index = ptr->getParticleAdrFromID(index_of_the_particle); + if (index>=0) { + FPSoft* p = &(ptr->system_soft[index]); + p->radius = radius; + } +#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL + int check = PS::Comm::getMaxValue(index); + if (check==-1) return -1; +#else + else return -1; +#endif + return 0; + } + + int set_position(int index_of_the_particle, + double x, double y, double z) { + reconstruct_particle_list(); + int index = ptr->getParticleAdrFromID(index_of_the_particle); + if (index>=0) { + FPSoft* p = &(ptr->system_soft[index]); + p->pos.x = x; + p->pos.y = y; + p->pos.z = z; + } +#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL + int check = PS::Comm::getMaxValue(index); + if (check==-1) return -1; +#else + else return -1; +#endif + return 0; + } + + int get_position(int index_of_the_particle, + double * x, double * y, double * z) { + reconstruct_particle_list(); + int index = ptr->getParticleAdrFromID(index_of_the_particle); +#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL + int rank_mask = index==-1 ? 0 : ptr->my_rank; + int particle_rank = PS::Comm::getSum(rank_mask); + if (particle_rank==0) { + if (index==-1) return -1; + FPSoft* p = &(ptr->system_soft[index]); + + *x = p->pos.x; + *y = p->pos.y; + *z = p->pos.z; + } + else { + if (ptr->my_rank==particle_rank) { // sender + FPSoft* p = &(ptr->system_soft[index]); + double* pos = &(p->pos.x); + MPI_Send(pos, 3, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD); + } + else if (ptr->my_rank==0) { // receiver + double pos[3]; + MPI_Recv(pos, 3, MPI_DOUBLE, particle_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + + *x = pos[0]; + *y = pos[1]; + *z = pos[2]; + } + } +#else + if (index>=0) { + FPSoft* p = &(ptr->system_soft[index]); + *x = p->pos.x; + *y = p->pos.y; + *z = p->pos.z; + } + else return -1; +#endif + return 0; + } + + int set_velocity(int index_of_the_particle, + double vx, double vy, double vz) { + reconstruct_particle_list(); + int index = ptr->getParticleAdrFromID(index_of_the_particle); + if (index>=0) { + FPSoft* p = &(ptr->system_soft[index]); + p->vel.x = vx; + p->vel.y = vy; + p->vel.z = vz; + } +#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL + int check = PS::Comm::getMaxValue(index); + if (check==-1) return -1; +#else + else return -1; +#endif + return 0; + } + + int get_velocity(int index_of_the_particle, + double * vx, double * vy, double * vz) { + reconstruct_particle_list(); + int index = ptr->getParticleAdrFromID(index_of_the_particle); +#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL + int rank_mask = index==-1 ? 0 : ptr->my_rank; + int particle_rank = PS::Comm::getSum(rank_mask); + if (particle_rank==0) { + if (index==-1) return -1; + FPSoft* p = &(ptr->system_soft[index]); + + *vx = p->vel.x; + *vy = p->vel.y; + *vz = p->vel.z; + } + else { + if (ptr->my_rank==particle_rank) { // sender + FPSoft* p = &(ptr->system_soft[index]); + double* vel = &(p->vel.x); + MPI_Send(vel, 3, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD); + } + else if (ptr->my_rank==0) { // receiver + double vel[3]; + MPI_Recv(vel, 3, MPI_DOUBLE, particle_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + + *vx = vel[0]; + *vy = vel[1]; + *vz = vel[2]; + } + } +#else + if (index>=0) { + FPSoft* p = &(ptr->system_soft[index]); + *vx = p->vel.x; + *vy = p->vel.y; + *vz = p->vel.z; + } + else return -1; +#endif + return 0; + } + + int get_acceleration(int index_of_the_particle, double * ax, double * ay, double * az) { + reconstruct_particle_list(); + int index = ptr->getParticleAdrFromID(index_of_the_particle); +#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL + int rank_mask = index==-1 ? 0 : ptr->my_rank; + int particle_rank = PS::Comm::getSum(rank_mask); + if (particle_rank==0) { + if (index==-1) return -1; + FPSoft* p = &(ptr->system_soft[index]); + + *ax = p->acc.x; + *ay = p->acc.y; + *az = p->acc.z; + } + else { + if (ptr->my_rank==particle_rank) { // sender + FPSoft* p = &(ptr->system_soft[index]); + double* acc = &(p->acc.x); + MPI_Send(acc, 3, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD); + } + else if (ptr->my_rank==0) { // receiver + double acc[3]; + MPI_Recv(acc, 3, MPI_DOUBLE, particle_rank, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + + *ax = acc[0]; + *ay = acc[1]; + *az = acc[2]; + } + } +#else + if (index>=0) { + FPSoft* p = &(ptr->system_soft[index]); + *ax = p->acc.x; + *ay = p->acc.y; + *az = p->acc.z; + } + else return -1; +#endif + return 0; + } + + int set_acceleration(int index_of_the_particle, double ax, double ay, double az) { + reconstruct_particle_list(); + int index = ptr->getParticleAdrFromID(index_of_the_particle); + if (index>=0) { + FPSoft* p = &(ptr->system_soft[index]); + p->acc.x = ax; + p->acc.y = ay; + p->acc.z = az; + } +#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL + int check = PS::Comm::getMaxValue(index); + if (check==-1) return -1; +#else + else return -1; +#endif + return 0; + } + + int get_potential(int index_of_the_particle, double * potential) { + reconstruct_particle_list(); + int index = ptr->getParticleAdrFromID(index_of_the_particle); +#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL + double pot_local = 0.0; + if (index>=0) { + FPSoft* p = &(ptr->system_soft[index]); + pot_local = p->pot_tot; + } + *potential = PS::Comm::getSum(pot_local); + int check = PS::Comm::getMaxValue(index); + if (check==-1) return -1; +#else + if (index>=0) { + FPSoft* p = &(ptr->system_soft[index]); + *potential = p->pot_tot; + } + else return -1; +#endif + return 0; + } + + int evolve_model(double time_next) { +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: evolve models to "<stat.n_real_glb==0) {// escape if no particle +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: evolve models end\n"; +#endif + return 0; + } + + // check whether interrupted cases, exist, if so, copy back data to local particles + int n_interrupt_isolated = ptr->system_hard_isolated.getNumberOfInterruptClusters(); + for (int i=0; imy_rank==0) std::cout<<"interrupt isolated: "<system_hard_isolated.getInterruptHardIntegrator(i); + for (int k=0; k<2; k++) { + auto pk = interrupt_hard_int->interrupt_binary.adr->getMember(k); + + // copy data from global particle array + assert(pk->id==ptr->system_soft[pk->adr_org].id); + pk->DataCopy(ptr->system_soft[pk->adr_org]); + } + } + +#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL + // check connected cluster case + if (n_particle_in_interrupt_connected_cluster_glb>0) { + ptr->search_cluster.SendPtcl(ptr->system_soft, ptr->system_hard_connected.getPtcl()); + int n_interrupt_connected = ptr->system_hard_connected.getNumberOfInterruptClusters(); + + for (int i=0; imy_rank==0) std::cout<<"interrupt connected: "<system_hard_connected.getInterruptHardIntegrator(i); + for (int k=0; k<2; k++) { + auto pk = interrupt_hard_int->interrupt_binary.adr->getMember(k); + int pk_index = interrupt_hard_int->interrupt_binary.adr->getMemberIndex(k); + // copy data from ptcl hard or globall array + if (pk->adr_org>=0) { + assert(pk->id==ptr->system_soft[pk->adr_org].id); + pk->DataCopy(ptr->system_soft[pk->adr_org]); + } + else { + assert(pk->id==interrupt_hard_int->ptcl_origin[pk_index].id); + pk->DataCopy(interrupt_hard_int->ptcl_origin[pk_index]); + } + } + } + } + + int mpi_distribute_stopping_conditions(); +#endif + + if (ptr->n_interrupt_glb==0) { + reconstruct_particle_list(); + if (!ptr->initial_step_flag) ptr->initialStep(); + ptr->input_parameters.time_end.value = time_next*2; + } + + int is_collision_detection_enabled; + is_stopping_condition_enabled(COLLISION_DETECTION, &is_collision_detection_enabled); + int is_pair_detection_enabled; + is_stopping_condition_enabled(PAIR_DETECTION, &is_pair_detection_enabled); + if (is_collision_detection_enabled||is_pair_detection_enabled) { + ptr->input_parameters.interrupt_detection_option.value = 1; + ptr->hard_manager.ar_manager.interrupt_detection_option = 1; + } + else { + ptr->input_parameters.interrupt_detection_option.value = 0; + ptr->hard_manager.ar_manager.interrupt_detection_option = 0; + } + + // record interrupt binaries in stopping condition container. + int n_interrupt = ptr->integrateToTime(time_next); + + reset_stopping_conditions(); + + if (n_interrupt>0) { + // isolate clusters + int n_interrupt_isolated = ptr->system_hard_isolated.getNumberOfInterruptClusters(); + for (int i=0; isystem_hard_isolated.getInterruptHardIntegrator(i); + auto interrupt_state = interrupt_hard_int->interrupt_binary.adr->getLeftMember()->getBinaryInterruptState(); + switch (interrupt_state) { + case BinaryInterruptState::form: + set_stopping_condition_info(stopping_index, PAIR_DETECTION); + break; + case BinaryInterruptState::exchange: + set_stopping_condition_info(stopping_index, PAIR_DETECTION); + break; + case BinaryInterruptState::collision: + set_stopping_condition_info(stopping_index, COLLISION_DETECTION); + break; + case BinaryInterruptState::none: + continue; + default: + return -1; + } + + for (int k=0; k<2; k++) { + auto pk = interrupt_hard_int->interrupt_binary.adr->getMember(k); + set_stopping_condition_particle_index(stopping_index, k, pk->id); + + // copy back data to global particle array + ptr->system_soft[pk->adr_org].DataCopy(*pk); + } + } + +#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL + int n_particle_in_interrupt_connected_cluster=0; + int n_interrupt_connected = ptr->system_hard_connected.getNumberOfInterruptClusters(); + for (int i=0; isystem_hard_connected.getInterruptHardIntegrator(i); + auto interrupt_state = interrupt_hard_int->interrupt_binary.adr->getLeftMember()->getBinaryInterruptState(); + switch (interrupt_state) { + case BinaryInterruptState::form: + set_stopping_condition_info(stopping_index, PAIR_DETECTION); + break; + case BinaryInterruptState::exchange: + set_stopping_condition_info(stopping_index, PAIR_DETECTION); + break; + case BinaryInterruptState::collision: + set_stopping_condition_info(stopping_index, COLLISION_DETECTION); + break; + case BinaryInterruptState::none: + continue; + default: + return -1; + } + for (int k=0; k<2; k++) { + auto pk = interrupt_hard_int->interrupt_binary.adr->getMember(k); + int pk_index = interrupt_hard_int->interrupt_binary.adr->getMemberIndex(k); + set_stopping_condition_particle_index(stopping_index, k, pk->id); + + // copy back data to global particle array + if (pk->adr_org>=0) { + assert(ptr->system_soft[pk->adr_org].id==pk->id); + ptr->system_soft[pk->adr_org].DataCopy(*pk); + } + else { + // if particle is in remote node, copy back to ptcl_hard and wait for MPI_send/recv + n_particle_in_interrupt_connected_cluster++; + assert(pk->id == interrupt_hard_int->ptcl_origin[pk_index].id); + interrupt_hard_int->ptcl_origin[pk_index].DataCopy(*pk); + } + } + } + // if particle in remote node need update, call MPI send/recv + n_particle_in_interrupt_connected_cluster_glb = PS::Comm::getSum(n_particle_in_interrupt_connected_cluster); + if (n_particle_in_interrupt_connected_cluster_glb>0) + ptr->search_cluster.writeAndSendBackPtcl(ptr->system_soft, ptr->system_hard_connected.getPtcl(), ptr->remove_list); + + mpi_collect_stopping_conditions(); +#endif + } +//#ifdef PROFILE + //ptr->printProfile(); + //ptr->clearProfile(); +//#endif + ptr->reconstructIdAdrMap(); +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: evolve models end\n"; +#endif + return 0; + } + + int commit_particles() { +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: commit_particles start\n"; +#endif + + if (!ptr->read_parameters_flag) return -1; + if (!ptr->read_data_flag) return -1; + ptr->input_parameters.n_glb.value = ptr->stat.n_real_glb; + ptr->initialParameters(); + ptr->initialStep(); + ptr->reconstructIdAdrMap(); + particle_list_change_flag = false; + initial_particle_flag = true; +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: commit_particles end\n"; +#endif + return 0; + } + + int synchronize_model() { +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: synchronize_model\n"; +#endif + return 0; + } + + int reconstruct_particle_list() { + if (particle_list_change_flag) { +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: reconstruct particle list start\n"; +#endif + ptr->removeParticles(); +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: remove particles end\n"; +#endif +#ifdef PARTICLE_SIMULATOR_MPI_PARALLEL + ptr->domainDecompose(true); + ptr->exchangeParticle(); +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: exchange particles end\n"; +#endif +#endif + ptr->reconstructIdAdrMap(); +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: reconstruct particle list end\n"; +#endif + particle_list_change_flag = false; + } + return 0; + } + + int recommit_particles() { + // this function is called too frequent (every time when set_xx is used). + // thus only register the flag and do update at once in the begining of evolve_model +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: recommit_particles start\n"; +#endif + if (ptr->n_interrupt_glb==0) ptr->initial_step_flag = false; + reconstruct_particle_list(); +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: recommit_particles end\n"; +#endif + return 0; + } + + int get_eps2(double * epsilon_squared) { + *epsilon_squared = ptr->input_parameters.eps.value ; + return 0; + } + + int set_eps2(double epsilon_squared) { + ptr->input_parameters.eps.value = epsilon_squared; + return 0; + } + + // set changeover radius outer boundary (if zero, auto-determine) + int set_changeover_rout(double r_out) { + ptr->input_parameters.r_out.value = r_out; + return 0; + } + + int get_changeover_rout(double* r_out) { + *r_out = ptr->input_parameters.r_out.value; + return 0; + } + + // set changeover ratio of inner / outer boundary (if zero, auto-determine) + int set_changeover_ratio(double ratio_r_cut) { + ptr->input_parameters.ratio_r_cut.value = ratio_r_cut; + return 0; + } + + int get_changeover_ratio(double* ratio_r_cut) { + *ratio_r_cut = ptr->input_parameters.ratio_r_cut.value; + return 0; + } + + // set group detection maximum radius to switch on AR (if zero, auto-determine) + int set_group_radius(double r_bin) { + ptr->input_parameters.r_bin.value = r_bin; + return 0; + } + + int get_group_radius(double* r_bin) { + *r_bin = ptr->input_parameters.r_bin.value; + return 0; + } + + // set neighbor search radius minimum (if zero, auto-determine) + int set_rsearch_min(double r_search_min) { + ptr->input_parameters.r_search_min.value = r_search_min; + return 0; + } + + int get_rsearch_min(double* r_search_min) { + *r_search_min = ptr->input_parameters.r_search_min.value; + return 0; + } + + // set tree opening angle + int set_theta(double theta) { + ptr->input_parameters.theta.value = theta; + return 0; + } + + int get_theta(double* theta) { + *theta = ptr->input_parameters.theta.value; + return 0; + } + + // set tree time step + int set_tree_step(double dt_soft) { + ptr->input_parameters.dt_soft.value = dt_soft; + return 0; + } + + int get_tree_step(double* dt_soft) { + *dt_soft = ptr->input_parameters.dt_soft.value; + return 0; + } + + int set_output_step(double dt_snap) { + ptr->input_parameters.dt_snap.value = dt_snap; + return 0; + } + + int get_output_step(double* dt_snap) { + *dt_snap = ptr->input_parameters.dt_snap.value; + return 0; + } + + + //// set gravitational constant + //int set_gravitational_constant(double G) { + // ptr->input_parameters.unit_set.value=-1; + // ptr->input_parameters.gravitational_constant.value = G; + // return 0; + //} + // + //// get gravitational constant + //int get_gravitational_constant(double* G) { + // *G = ptr->input_parameters.gravitational_constant.value; + // return 0; + //} + + int get_kinetic_energy(double * kinetic_energy) { + // update particle array first if necessary + reconstruct_particle_list(); + if (!ptr->initial_step_flag) ptr->initialStep(); + *kinetic_energy = ptr->stat.energy.ekin; + return 0; + } + + int get_potential_energy(double * potential_energy) { + // update particle array first if necessary + reconstruct_particle_list(); + if (!ptr->initial_step_flag) ptr->initialStep(); + *potential_energy = ptr->stat.energy.epot; + return 0; + } + + int get_time(double * time) { + * time = ptr->stat.time; + return 0; + } + + int get_begin_time(double * time) { + * time = time_start; + return 0; + } + + int set_begin_time(double time) { +#ifdef INTERFACE_DEBUG_PRINT + if(ptr->my_rank==0) std::cout<<"PETAR: set begin time from "<stat.time<<" to "<stat.time = time_start; + return 0; + } + + int get_time_step(double * time_step) { + * time_step = ptr->input_parameters.dt_soft.value; + return 0; + } + + int get_total_mass(double * mass) { + // update particle array first if necessary + reconstruct_particle_list(); + * mass = ptr->stat.pcm.mass; + return 0; + } + + int get_center_of_mass_position(double * x, double * y, double * z) { + // update particle array first if necessary + reconstruct_particle_list(); + * x = ptr->stat.pcm.pos.x; + * y = ptr->stat.pcm.pos.y; + * z = ptr->stat.pcm.pos.z; + return 0; + } + + int get_center_of_mass_velocity(double * x, double * y, double * z) { + // update particle array first if necessary + reconstruct_particle_list(); + * x = ptr->stat.pcm.pos.x; + * y = ptr->stat.pcm.pos.y; + * z = ptr->stat.pcm.pos.z; + return 0; + } + + int get_total_radius(double * radius) { + // update particle array first if necessary + reconstruct_particle_list(); + * radius = ptr->stat.half_mass_radius; + return 0; + } + + int get_number_of_particles(int * number_of_particles) { + // update particle array first if necessary + reconstruct_particle_list(); + * number_of_particles = ptr->stat.n_real_glb; + return 0; + } + + int get_index_of_first_particle(int * index_of_the_particle) { + * index_of_the_particle = 1; + return 0; + } + + int get_index_of_next_particle(int index_of_the_particle, int * index_of_the_next_particle) { + * index_of_the_next_particle = index_of_the_particle + 1; + return 0; + } + + // GravityFieldInterface + + int get_gravity_at_point(double * eps, double * x, double * y, double * z, + double * forcex, double * forcey, double * forcez, int n) { + // update particle array first if necessary + reconstruct_particle_list(); + + // transform data + ParticleBase ptmp[n]; + ForceSoft force[n]; + for (int i=0; isystem_soft[0]), ptr->system_soft.getNumberOfParticleLocal(), force); + + for (int i=0; imy_rank==0) { + MPI_Reduce(MPI_IN_PLACE, forcex, n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); + MPI_Reduce(MPI_IN_PLACE, forcey, n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); + MPI_Reduce(MPI_IN_PLACE, forcez, n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); + } + else { + MPI_Reduce(forcex, NULL, n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); + MPI_Reduce(forcey, NULL, n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); + MPI_Reduce(forcez, NULL, n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); + } +#endif + return 0; + } + + + int get_potential_at_point(double * eps, + double * x, double * y, double * z, + double * phi, int n) { + // update particle array first if necessary + reconstruct_particle_list(); + + // transform data + ParticleBase ptmp[n]; + ForceSoft force[n]; + for (int i=0; isystem_soft[0]), ptr->system_soft.getNumberOfParticleLocal(), force); + + for (int i=0; imy_rank==0) MPI_Reduce(MPI_IN_PLACE, phi, n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); + else MPI_Reduce(phi, NULL, n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); +#endif + return 0; + } + +#ifdef __cplusplus +} +#endif diff --git a/src/amuse/community/petar/interface.h b/src/amuse/community/petar/interface.h new file mode 100644 index 0000000000..0cc2e7142f --- /dev/null +++ b/src/amuse/community/petar/interface.h @@ -0,0 +1,133 @@ +#pragma once +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// GravitationalDynamicsCode + +int initialize_code(); + +int cleanup_code(); + +int commit_parameters(); + +int recommit_parameters(); + +int new_particle(int* index_of_the_particle, double mass, double x, double y, double z, double vx, double vy, double vz, double radius); + +int delete_particle(int index_of_the_particle); + +int get_state(int index_of_the_particle, double * mass, double * x, double * y, double * z, double * vx, double * vy, double * vz, double * radius); + +int set_state(int index_of_the_particle, double mass, double x, double y, double z, double vx, double vy, double vz, double radius); + +int get_mass(int index_of_the_particle, double * mass); + +int set_mass(int index_of_the_particle, double mass); + +int get_radius(int index_of_the_particle, double * radius); + +int set_radius(int index_of_the_particle, double radius); + +int get_position(int index_of_the_particle, double * x, double * y, double * z); + +int set_position(int index_of_the_particle, double x, double y, double z); + +int get_velocity(int index_of_the_particle, double * vx, double * vy, double * vz); + +int set_velocity(int index_of_the_particle, double vx, double vy, double vz); + +int get_acceleration(int index_of_the_particle, double * ax, double * ay, double * az); + +int set_acceleration(int index_of_the_particle, double ax, double ay, double az); + +int get_potential(int index_of_the_particle, double * potential); + +int evolve_model(double time); + +int commit_particles(); + +int synchronize_model(); + +int recommit_particles(); + +int reconstruct_particle_list(); + +int get_eps2(double * epsilon_squared); + +int set_eps2(double epsilon_squared); + +int get_theta(double * theta); + +int set_theta(double theta); + +int get_gravitational_constant(double * G); + +int set_gravitational_constant(double G); + +int get_changeover_rout(double * r_out); + +int set_changeover_rout(double r_out); + +int get_changeover_ratio(double * ratio_r_cut); + +int set_changeover_ratio(double ratio_r_cut); + +int get_group_radius(double * r_bin); + +int set_group_radius(double r_bin); + +int get_rsearch_min(double * r_search_min); + +int set_rsearch_min(double r_search_min); + +int get_tree_step(double * dt_soft); + +int set_tree_step(double dt_soft); + +int get_output_step(double * dt_output); + +int set_output_step(double dt_output); + +int get_kinetic_energy(double * kinetic_energy); + +int get_potential_energy(double * potential_energy); + +int get_time(double * time); + +int get_begin_time(double * time); + +int set_begin_time(double time); + +int get_time_step(double * time_step); + +int get_total_mass(double * mass); + +int get_center_of_mass_position(double * x, double * y, double * z); + +int get_center_of_mass_velocity(double * vx, double * vy, double * vz); + +int get_total_radius(double * radius); + +int get_number_of_particles(int * number_of_particles); + +int get_index_of_first_particle(int * index_of_the_particle); + +int get_index_of_next_particle(int index_of_the_particle, int * index_of_the_next_particle); + +// GravityFieldCode + +int get_gravity_at_point(double * eps, double * x, double * y, double * z, double * ax, double * ay, double * az, int npoints); + +int get_potential_at_point(double * eps, double * x, double * y, double * z, double * phi, int npoints); + +//int get_eta(double * eta); + +//int set_eta(double eta); + +#ifdef __cplusplus +} +#endif + diff --git a/src/amuse/community/petar/interface.py b/src/amuse/community/petar/interface.py index a0c4ce6f89..977cb7e3cd 100644 --- a/src/amuse/community/petar/interface.py +++ b/src/amuse/community/petar/interface.py @@ -356,6 +356,48 @@ def set_tree_step(): """ return function + @legacy_function + def get_output_step(): + """ + Get dt_output, the PeTar internal output time step (0.125) + """ + function = LegacyFunctionSpecification() + function.addParameter( + 'dt_output', dtype='float64', direction=function.OUT, + description=( + "dt_output, the PeTar internal output time step (0.125)" + ) + ) + function.result_type = 'int32' + function.result_doc = """ + 0 - OK + the parameter was retrieved + -1 - ERROR + could not retrieve parameter + """ + return function + + @legacy_function + def set_output_step(): + """ + Set dt_output, the PeTar internal output time step (0.125) + """ + function = LegacyFunctionSpecification() + function.addParameter( + 'dt_output', dtype='float64', direction=function.IN, + description=( + "dt_output, the PeTar internal output time step (0.125)" + ) + ) + function.result_type = 'int32' + function.result_doc = """ + 0 - OK + the parameter was set + -1 - ERROR + could not set parameter + """ + return function + class petar(GravitationalDynamics, GravityFieldCode): @@ -443,6 +485,14 @@ def define_parameters(self, handler): default_value=0.0 | nbody_system.time ) + handler.add_method_parameter( + "get_output_step", + "set_output_step", + "dt_output", + "PeTar internal output time step (0.125)", + default_value=0.125 | nbody_system.time + ) + def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) self.stopping_conditions.define_methods(handler) @@ -542,6 +592,25 @@ def define_methods(self, handler): ) ) + handler.add_method( + "set_output_step", + ( + nbody_system.time, + ), + ( + handler.ERROR_CODE, + ) + ) + + handler.add_method( + "get_output_step", + (), + ( + nbody_system.time, + handler.ERROR_CODE, + ) + ) + def define_particle_sets(self, handler): GravitationalDynamics.define_particle_sets(self, handler) self.stopping_conditions.define_particle_set(handler) diff --git a/src/amuse/community/rebound/download.py b/src/amuse/community/rebound/download.py index 3311f8f8a0..8a686caa88 100755 --- a/src/amuse/community/rebound/download.py +++ b/src/amuse/community/rebound/download.py @@ -19,33 +19,30 @@ def directory(self): return os.path.abspath(os.path.dirname(__file__)) def src_directory(self): - return os.path.join(self.directory(), 'src') + return os.path.join(self.directory(), "src") def unpack_downloaded_file(self, filename): print("unpacking", filename) - arguments = ['tar', '-xf'] + arguments = ["tar", "-xf"] arguments.append(filename) + subprocess.call(arguments, cwd=os.path.join(self.src_directory())) subprocess.call( - arguments, - cwd=os.path.join(self.src_directory()) - ) - subprocess.call( - ['mv', 'rebound-{version}'.format(version = self.version), 'rebound'], - cwd = os.path.join(self.src_directory()) + ["mv", "rebound-{version}".format(version=self.version), "rebound"], + cwd=os.path.join(self.src_directory()), ) print("done") def start(self): - if os.path.exists('src'): + if os.path.exists("src"): counter = 0 - while os.path.exists('src.{0}'.format(counter)): + while os.path.exists("src.{0}".format(counter)): counter += 1 if counter > 100: print("too many backup directories") break - os.rename('src', 'src.{0}'.format(counter)) + os.rename("src", "src.{0}".format(counter)) - os.mkdir('src') + os.mkdir("src") url = self.url_template.format(version=self.version) filename = self.filename_template.format(version=self.version) @@ -56,7 +53,7 @@ def start(self): self.unpack_downloaded_file(filename) -def main(version=''): +def main(version=""): instance = GetCodeFromHttp() instance.version = version instance.start() @@ -66,10 +63,10 @@ def new_option_parser(): result = OptionParser() result.add_option( "--version", - default='31d117bdc92182073d0941c331f76e95f515bfc6', + default="31d117bdc92182073d0941c331f76e95f515bfc6", dest="version", help="version number to download", - type="string" + type="string", ) return result diff --git a/src/amuse/community/rebound/interface.py b/src/amuse/community/rebound/interface.py index 5c23648030..0ce390818d 100644 --- a/src/amuse/community/rebound/interface.py +++ b/src/amuse/community/rebound/interface.py @@ -4,32 +4,34 @@ from amuse.community.interface.gd import SinglePointGravityFieldInterface from amuse.community.interface.gd import GravityFieldCode -class ReboundInterface(CodeInterface, - LiteratureReferencesMixIn, - GravitationalDynamicsInterface, - StoppingConditionInterface, - #SinglePointGravityFieldInterface - ): + +class ReboundInterface( + CodeInterface, + LiteratureReferencesMixIn, + GravitationalDynamicsInterface, + StoppingConditionInterface, + # SinglePointGravityFieldInterface +): """ REBOUND - An open-source multi-purpose N-body code - + .. [#] ADS:2012A&A...537A.128R (Rein, H., Liu, S.F., *Astronomy and Astrophysics* , **Volume 537**, A128 (2012)) - + For different integrators, cite: .. [#] ADS:2015MNRAS.446.1424R (IAS15: Rein, H., Spiegel, D.S., *MNRAS* , **Volume 446**, Issue 2, p.1424-1437 (2015)) .. [#] ADS:2015MNRAS.452..376R (WHFast: Rein, H., Tamayo, D., *MNRAS* , **Volume 452**, Issue 1, p.376-388 (2015)) ... Hermes: Silburt, A., et al., in prep. .. [#] ADS:2011MNRAS.415.3168R (SEI: Rein, H., Tremaine, S., *MNRAS* , **Volume 415**, Issue 4, p.3168-3176 (2011)) .. [#] ADS:2017MNRAS.467.2377R (JANUS: Rein, H., Tamayo, D., *arXiv* , 1704.07715 (2017)) - + """ - include_headers = ['worker_code.h', 'stopcond.h'] + + include_headers = ["worker_code.h", "stopcond.h"] def __init__(self, **options): - CodeInterface.__init__(self, name_of_the_worker="rebound_worker", - **options) + CodeInterface.__init__(self, name_of_the_worker="rebound_worker", **options) LiteratureReferencesMixIn.__init__(self) - + @legacy_function def new_particle(): """ @@ -39,30 +41,80 @@ def new_particle(): """ function = LegacyFunctionSpecification() function.can_handle_array = True - function.addParameter('index_of_the_particle', dtype='int32', direction=function.OUT, description = - """ + function.addParameter( + "index_of_the_particle", + dtype="int32", + direction=function.OUT, + description=""" An index assigned to the newly created particle. This index is supposed to be a local index for the code (and not valid in other instances of the code or in other codes) - """ - ) - - function.addParameter('mass', dtype='float64', direction=function.IN, description = "The mass of the particle") - function.addParameter('x', dtype='float64', direction=function.IN, description = "The initial position vector of the particle") - function.addParameter('y', dtype='float64', direction=function.IN, description = "The initial position vector of the particle") - function.addParameter('z', dtype='float64', direction=function.IN, description = "The initial position vector of the particle") - function.addParameter('vx', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") - function.addParameter('vy', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") - function.addParameter('vz', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") - function.addParameter('radius', dtype='float64', direction=function.IN, description = "The radius of the particle", default = 0) - function.addParameter('subset', dtype='int32', direction=function.IN, description = "The subset index of the particle (defaults to 0, use new_subset for higher indices)", default = 0) - function.result_type = 'int32' + """, + ) + + function.addParameter( + "mass", + dtype="float64", + direction=function.IN, + description="The mass of the particle", + ) + function.addParameter( + "x", + dtype="float64", + direction=function.IN, + description="The initial position vector of the particle", + ) + function.addParameter( + "y", + dtype="float64", + direction=function.IN, + description="The initial position vector of the particle", + ) + function.addParameter( + "z", + dtype="float64", + direction=function.IN, + description="The initial position vector of the particle", + ) + function.addParameter( + "vx", + dtype="float64", + direction=function.IN, + description="The initial velocity vector of the particle", + ) + function.addParameter( + "vy", + dtype="float64", + direction=function.IN, + description="The initial velocity vector of the particle", + ) + function.addParameter( + "vz", + dtype="float64", + direction=function.IN, + description="The initial velocity vector of the particle", + ) + function.addParameter( + "radius", + dtype="float64", + direction=function.IN, + description="The radius of the particle", + default=0, + ) + function.addParameter( + "subset", + dtype="int32", + direction=function.IN, + description="The subset index of the particle (defaults to 0, use new_subset for higher indices)", + default=0, + ) + function.result_type = "int32" function.result_doc = """ 0 - OK particle was created and added to the model -1 - ERROR particle could not be created""" return function - + def delete_particle(self, index_of_the_particle, code_index=0): return self._delete_particle(index_of_the_particle, code_index) @@ -73,9 +125,20 @@ def _delete_particle(): """ function = LegacyFunctionSpecification() function.can_handle_array = True - function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description ="Index of the particle") - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) - function.result_type = 'int32' + function.addParameter( + "index_of_the_particle", + dtype="int32", + direction=function.IN, + description="Index of the particle", + ) + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound", + default=0, + ) + function.result_type = "int32" function.result_doc = """ 0 - OK particle was deleted -1 - ERROR @@ -84,29 +147,49 @@ def _delete_particle(): @legacy_function def _set_integrator(): - function = LegacyFunctionSpecification() - function.addParameter('integrator_name', dtype='i', direction=function.IN) - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) - function.result_type = 'int32' + function = LegacyFunctionSpecification() + function.addParameter("integrator_name", dtype="i", direction=function.IN) + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound", + default=0, + ) + function.result_type = "int32" function.can_handle_array = False - return function - + return function @legacy_function def _get_integrator(): - function = LegacyFunctionSpecification() - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) - function.addParameter('integrator_name', dtype='i', direction=function.OUT) - function.result_type = 'int32' + function = LegacyFunctionSpecification() + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound", + default=0, + ) + function.addParameter("integrator_name", dtype="i", direction=function.OUT) + function.result_type = "int32" function.can_handle_array = False - return function - + return function - INTEGRATORS = {"ias15": 0, "whfast": 1, "sei": 2, "leapfrog": 4, "hermes": 5, "whfast-helio": 6, "none": 7, "janus": 8} - def set_integrator(self, name, code_index = 0 ): + INTEGRATORS = { + "ias15": 0, + "whfast": 1, + "sei": 2, + "leapfrog": 4, + "hermes": 5, + "whfast-helio": 6, + "none": 7, + "janus": 8, + } + + def set_integrator(self, name, code_index=0): return self._set_integrator(self.INTEGRATORS[name], code_index) - - def get_integrator(self, code_index = 0): + + def get_integrator(self, code_index=0): value, error = self._get_integrator(code_index) for key, index in self.INTEGRATORS.items(): if value == index: @@ -115,29 +198,40 @@ def get_integrator(self, code_index = 0): @legacy_function def _set_solver(): - function = LegacyFunctionSpecification() - function.addParameter('solver_name', dtype='i', direction=function.IN) - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) - function.result_type = 'int32' + function = LegacyFunctionSpecification() + function.addParameter("solver_name", dtype="i", direction=function.IN) + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound", + default=0, + ) + function.result_type = "int32" function.can_handle_array = False - return function - + return function @legacy_function def _get_solver(): - function = LegacyFunctionSpecification() - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) - function.addParameter('solver_name', dtype='i', direction=function.OUT) - function.result_type = 'int32' + function = LegacyFunctionSpecification() + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound", + default=0, + ) + function.addParameter("solver_name", dtype="i", direction=function.OUT) + function.result_type = "int32" function.can_handle_array = False - return function - + return function SOLVERS = {"none": 0, "basic": 1, "compensated": 2, "tree": 3} - def set_solver(self, name, code_index = 0 ): + + def set_solver(self, name, code_index=0): return self._set_solver(self.SOLVERS[name], code_index) - - def get_solver(self, code_index = 0): + + def get_solver(self, code_index=0): value, error = self._get_solver(code_index) for key, index in self.SOLVERS.items(): if value == index: @@ -147,19 +241,39 @@ def get_solver(self, code_index = 0): @legacy_function def get_opening_angle2(): function = LegacyFunctionSpecification() - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) - function.addParameter('opening_angle2', dtype='float64', direction=function.OUT, - description = "theta, the opening angle for building the tree: between 0 and 1") - function.result_type = 'int32' + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound", + default=0, + ) + function.addParameter( + "opening_angle2", + dtype="float64", + direction=function.OUT, + description="theta, the opening angle for building the tree: between 0 and 1", + ) + function.result_type = "int32" return function @legacy_function def set_opening_angle2(): function = LegacyFunctionSpecification() - function.addParameter('opening_angle2', dtype='float64', direction=function.IN, - description = "theta, the opening angle for building the tree: between 0 and 1") - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) - function.result_type = 'int32' + function.addParameter( + "opening_angle2", + dtype="float64", + direction=function.IN, + description="theta, the opening angle for building the tree: between 0 and 1", + ) + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound", + default=0, + ) + function.result_type = "int32" return function @legacy_function @@ -169,11 +283,21 @@ def get_eps2(): Get epsilon^2, a softening parameter for gravitational potentials with point particles. """ function = LegacyFunctionSpecification() - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) - function.addParameter('epsilon_squared', dtype='float64', direction=function.OUT, - description = "epsilon^2, a softening parameter for gravitational potentials with point particles", - unit = nbody_system.length * nbody_system.length) - function.result_type = 'int32' + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound", + default=0, + ) + function.addParameter( + "epsilon_squared", + dtype="float64", + direction=function.OUT, + description="epsilon^2, a softening parameter for gravitational potentials with point particles", + unit=nbody_system.length * nbody_system.length, + ) + function.result_type = "int32" function.result_doc = """ 0 - OK the parameter was retrieved @@ -188,11 +312,21 @@ def set_eps2(): Set epsilon^2, a softening parameter for gravitational potentials with point particles. """ function = LegacyFunctionSpecification() - function.addParameter('epsilon_squared', dtype='float64', direction=function.IN, - description = "epsilon^2, a softening parameter for gravitational potentials with point particles", - unit = nbody_system.length * nbody_system.length) - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) - function.result_type = 'int32' + function.addParameter( + "epsilon_squared", + dtype="float64", + direction=function.IN, + description="epsilon^2, a softening parameter for gravitational potentials with point particles", + unit=nbody_system.length * nbody_system.length, + ) + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound", + default=0, + ) + function.result_type = "int32" function.result_doc = """ 0 - OK the parameter was set @@ -203,29 +337,40 @@ def set_eps2(): @legacy_function def _set_boundary(): - function = LegacyFunctionSpecification() - function.addParameter('boundary_name', dtype='i', direction=function.IN) - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) - function.result_type = 'int32' + function = LegacyFunctionSpecification() + function.addParameter("boundary_name", dtype="i", direction=function.IN) + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound", + default=0, + ) + function.result_type = "int32" function.can_handle_array = False - return function - + return function @legacy_function def _get_boundary(): - function = LegacyFunctionSpecification() - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) - function.addParameter('boundary_name', dtype='i', direction=function.OUT) - function.result_type = 'int32' + function = LegacyFunctionSpecification() + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound", + default=0, + ) + function.addParameter("boundary_name", dtype="i", direction=function.OUT) + function.result_type = "int32" function.can_handle_array = False - return function - + return function BOUNDARIES = {"none": 0, "open": 1, "periodic": 2, "shear": 3} - def set_boundary(self, name, code_index = 0 ): + + def set_boundary(self, name, code_index=0): return self._set_boundary(self.BOUNDARIES[name], code_index) - - def get_boundary(self, code_index = 0): + + def get_boundary(self, code_index=0): value, error = self._get_boundary(code_index) for key, index in self.BOUNDARIES.items(): if value == index: @@ -239,11 +384,21 @@ def get_boundary_size(): Get the size of the boundaries. """ function = LegacyFunctionSpecification() - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) - function.addParameter('boundary_size', dtype='float64', direction=function.OUT, - description = "boundary size", - unit = nbody_system.length) - function.result_type = 'int32' + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound", + default=0, + ) + function.addParameter( + "boundary_size", + dtype="float64", + direction=function.OUT, + description="boundary size", + unit=nbody_system.length, + ) + function.result_type = "int32" function.result_doc = """ 0 - OK the parameter was retrieved @@ -258,11 +413,21 @@ def set_boundary_size(): Set size of the boundaries. """ function = LegacyFunctionSpecification() - function.addParameter('boundary_size', dtype='float64', direction=function.IN, - description = "boundary size", - unit = nbody_system.length) - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) - function.result_type = 'int32' + function.addParameter( + "boundary_size", + dtype="float64", + direction=function.IN, + description="boundary size", + unit=nbody_system.length, + ) + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound", + default=0, + ) + function.result_type = "int32" function.result_doc = """ 0 - OK the parameter was set @@ -271,36 +436,49 @@ def set_boundary_size(): """ return function - - - @legacy_function def set_time_step(): """ Update timestep. """ function = LegacyFunctionSpecification() - function.addParameter('timestep', dtype='float64', direction=function.IN, - description = "timestep") - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) - function.result_type = 'int32' + function.addParameter( + "timestep", dtype="float64", direction=function.IN, description="timestep" + ) + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound", + default=0, + ) + function.result_type = "int32" function.result_doc = """ 0 - OK timestep was changed """ return function - @legacy_function def get_potential_energy(): """ Retrieve the current potential energy of the model """ function = LegacyFunctionSpecification() - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) - function.addParameter('potential_energy', dtype='float64', direction=function.OUT, - description = "The potential energy of the model") - function.result_type = 'int32' + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound", + default=0, + ) + function.addParameter( + "potential_energy", + dtype="float64", + direction=function.OUT, + description="The potential energy of the model", + ) + function.result_type = "int32" function.result_doc = """ 0 - OK Current value of the potential energy was set @@ -308,7 +486,6 @@ def get_potential_energy(): Kinetic potential could not be provided """ return function - @legacy_function def get_kinetic_energy(): @@ -316,10 +493,20 @@ def get_kinetic_energy(): Retrieve the current kinetic energy of the model """ function = LegacyFunctionSpecification() - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) - function.addParameter('kinetic_energy', dtype='float64', direction=function.OUT, - description = "The kinetic energy of the model") - function.result_type = 'int32' + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound", + default=0, + ) + function.addParameter( + "kinetic_energy", + dtype="float64", + direction=function.OUT, + description="The kinetic energy of the model", + ) + function.result_type = "int32" function.result_doc = """ 0 - OK Current value of the kinetic energy was set @@ -328,21 +515,29 @@ def get_kinetic_energy(): """ return function - @legacy_function def evolve_model(): """ Evolve the model until the given time, or until a stopping condition is set. """ function = LegacyFunctionSpecification() - function.addParameter('time', dtype='float64', direction=function.IN, - description = "Model time to evolve the code to. The model will be " - "evolved until this time is reached exactly or just after.") - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound (default -1, evolve all systems)", default = -1) - function.result_type = 'int32' + function.addParameter( + "time", + dtype="float64", + direction=function.IN, + description="Model time to evolve the code to. The model will be " + "evolved until this time is reached exactly or just after.", + ) + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound (default -1, evolve all systems)", + default=-1, + ) + function.result_type = "int32" return function - @legacy_function def get_time(): """ @@ -351,10 +546,20 @@ def get_time(): model time of the collision. """ function = LegacyFunctionSpecification() - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) - function.addParameter('time', dtype='float64', direction=function.OUT, - description = "The current model time") - function.result_type = 'int32' + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound", + default=0, + ) + function.addParameter( + "time", + dtype="float64", + direction=function.OUT, + description="The current model time", + ) + function.result_type = "int32" function.result_doc = """ 0 - OK Current value of the time was retrieved @@ -362,8 +567,6 @@ def get_time(): The code does not have support for querying the time """ return function - - @legacy_function def get_time_step(): @@ -371,10 +574,20 @@ def get_time_step(): Retrieve the model timestep. """ function = LegacyFunctionSpecification() - function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) - function.addParameter('time_step', dtype='float64', direction=function.OUT, - description = "The current model timestep") - function.result_type = 'int32' + function.addParameter( + "code_index", + dtype="int32", + direction=function.IN, + description="Index of the code in rebound", + default=0, + ) + function.addParameter( + "time_step", + dtype="float64", + direction=function.OUT, + description="The current model timestep", + ) + function.result_type = "int32" function.result_doc = """ 0 - OK Current value of the time step was retrieved @@ -383,7 +596,6 @@ def get_time_step(): """ return function - @legacy_function def new_subset(): """ @@ -391,21 +603,29 @@ def new_subset(): """ function = LegacyFunctionSpecification() function.can_handle_array = True - function.addParameter('index_of_the_subset', dtype='int32', direction=function.OUT, description = - """ + function.addParameter( + "index_of_the_subset", + dtype="int32", + direction=function.OUT, + description=""" An index assigned to the newly created subset - """ - ) + """, + ) - function.addParameter('time_offset', dtype='float64', direction=function.IN, description = "Time of the system (defaults to the current model time)", default = -1) - function.result_type = 'int32' + function.addParameter( + "time_offset", + dtype="float64", + direction=function.IN, + description="Time of the system (defaults to the current model time)", + default=-1, + ) + function.result_type = "int32" function.result_doc = """ 0 - OK code was created -1 - ERROR code could not be created""" return function - - + @legacy_function def get_state(): """ @@ -414,18 +634,67 @@ def get_state(): """ function = LegacyFunctionSpecification() function.can_handle_array = True - function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, - description = "Index of the particle to get the state from. This index must have been returned by an earlier call to :meth:`new_particle`") - function.addParameter('mass', dtype='float64', direction=function.OUT, description = "The current mass of the particle") - function.addParameter('x', dtype='float64', direction=function.OUT, description = "The current position vector of the particle") - function.addParameter('y', dtype='float64', direction=function.OUT, description = "The current position vector of the particle") - function.addParameter('z', dtype='float64', direction=function.OUT, description = "The current position vector of the particle") - function.addParameter('vx', dtype='float64', direction=function.OUT, description = "The current velocity vector of the particle") - function.addParameter('vy', dtype='float64', direction=function.OUT, description = "The current velocity vector of the particle") - function.addParameter('vz', dtype='float64', direction=function.OUT, description = "The current velocity vector of the particle") - function.addParameter('radius', dtype='float64', direction=function.OUT, description = "The current radius of the particle") - function.addParameter('subset', dtype='int32', direction=function.OUT, description = "The current subset of the particle") - function.result_type = 'int32' + function.addParameter( + "index_of_the_particle", + dtype="int32", + direction=function.IN, + description="Index of the particle to get the state from. This index must have been returned by an earlier call to :meth:`new_particle`", + ) + function.addParameter( + "mass", + dtype="float64", + direction=function.OUT, + description="The current mass of the particle", + ) + function.addParameter( + "x", + dtype="float64", + direction=function.OUT, + description="The current position vector of the particle", + ) + function.addParameter( + "y", + dtype="float64", + direction=function.OUT, + description="The current position vector of the particle", + ) + function.addParameter( + "z", + dtype="float64", + direction=function.OUT, + description="The current position vector of the particle", + ) + function.addParameter( + "vx", + dtype="float64", + direction=function.OUT, + description="The current velocity vector of the particle", + ) + function.addParameter( + "vy", + dtype="float64", + direction=function.OUT, + description="The current velocity vector of the particle", + ) + function.addParameter( + "vz", + dtype="float64", + direction=function.OUT, + description="The current velocity vector of the particle", + ) + function.addParameter( + "radius", + dtype="float64", + direction=function.OUT, + description="The current radius of the particle", + ) + function.addParameter( + "subset", + dtype="int32", + direction=function.OUT, + description="The current subset of the particle", + ) + function.result_type = "int32" function.result_doc = """ 0 - OK particle was removed from the model @@ -440,10 +709,19 @@ def get_subset(): Retrieve the subset index of a particle. """ function = LegacyFunctionSpecification() - function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, - description = "Index of the particle to get the subset of. This index must have been returned by an earlier call to :meth:`new_particle`") - function.addParameter('subset', dtype='int32', direction=function.OUT, description = "The current subset of the particle") - function.result_type = 'int32' + function.addParameter( + "index_of_the_particle", + dtype="int32", + direction=function.IN, + description="Index of the particle to get the subset of. This index must have been returned by an earlier call to :meth:`new_particle`", + ) + function.addParameter( + "subset", + dtype="int32", + direction=function.OUT, + description="The current subset of the particle", + ) + function.result_type = "int32" function.can_handle_array = True function.result_doc = """ 0 - OK @@ -453,7 +731,6 @@ def get_subset(): """ return function - @legacy_function def stop_subset(): """ @@ -461,20 +738,21 @@ def stop_subset(): """ function = LegacyFunctionSpecification() function.can_handle_array = True - function.addParameter('index_of_the_subset', dtype='int32', direction=function.IN, description = - """ + function.addParameter( + "index_of_the_subset", + dtype="int32", + direction=function.IN, + description=""" An index assigned to an existing subset - """ - ) + """, + ) - function.result_type = 'int32' + function.result_type = "int32" function.result_doc = """ 0 - OK subset evolving was stopped -1 - ERROR subset evolving was already stopped""" return function - - @legacy_function def set_subset(): @@ -482,10 +760,19 @@ def set_subset(): Retrieve the subset index of a particle. """ function = LegacyFunctionSpecification() - function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, - description = "Index of the particle to get the subset of. This index must have been returned by an earlier call to :meth:`new_particle`") - function.addParameter('subset', dtype='int32', direction=function.IN, description = "The new subset of the particle, as this is actually read only this will fail if changed!") - function.result_type = 'int32' + function.addParameter( + "index_of_the_particle", + dtype="int32", + direction=function.IN, + description="Index of the particle to get the subset of. This index must have been returned by an earlier call to :meth:`new_particle`", + ) + function.addParameter( + "subset", + dtype="int32", + direction=function.IN, + description="The new subset of the particle, as this is actually read only this will fail if changed!", + ) + function.result_type = "int32" function.can_handle_array = True function.result_doc = """ 0 - OK @@ -494,104 +781,93 @@ def set_subset(): particle could not be found """ return function - class Rebound(GravitationalDynamics, GravityFieldCode): - __interface__ = ReboundInterface - - def __init__(self, convert_nbody = None, **options): + def __init__(self, convert_nbody=None, **options): self.stopping_conditions = StoppingConditions(self) legacy_interface = self.__interface__(**options) self.legacy_doc = legacy_interface.__doc__ - GravitationalDynamics.__init__( - self, - legacy_interface, - convert_nbody, - **options - ) + GravitationalDynamics.__init__(self, legacy_interface, convert_nbody, **options) - def define_state(self, handler): GravitationalDynamics.define_state(self, handler) - #GravityFieldCode.define_state(self, handler) + # GravityFieldCode.define_state(self, handler) self.stopping_conditions.define_state(handler) - - handler.add_method('EDIT', 'new_subset') - handler.add_method('RUN', 'new_subset') - + handler.add_method("EDIT", "new_subset") + handler.add_method("RUN", "new_subset") def define_parameters(self, handler): self.stopping_conditions.define_parameters(handler) - #~ GravitationalDynamics.define_parameters(self, handler) - + # ~ GravitationalDynamics.define_parameters(self, handler) + handler.add_method_parameter( "get_time_step", "set_time_step", "timestep", - "constant timestep for iteration", - default_value = 0.0001 | nbody_system.time + "constant timestep for iteration", + default_value=0.0001 | nbody_system.time, ) - handler.add_method_parameter( "get_integrator", "set_integrator", "integrator", - "name of the integrator to use ({0})".format(sorted(self.INTEGRATORS.keys())), - default_value = "ias15" + "name of the integrator to use ({0})".format( + sorted(self.INTEGRATORS.keys()) + ), + default_value="ias15", ) - handler.add_method_parameter( "get_solver", "set_solver", "solver", - "name of the gravity solver to use ({0})".format(sorted(self.SOLVERS.keys())), - default_value = "compensated" + "name of the gravity solver to use ({0})".format( + sorted(self.SOLVERS.keys()) + ), + default_value="compensated", ) - handler.add_method_parameter( "get_eps2", "set_eps2", "epsilon_squared", - "smoothing parameter for gravity calculations", - default_value = 0.0 | nbody_system.length * nbody_system.length + "smoothing parameter for gravity calculations", + default_value=0.0 | nbody_system.length * nbody_system.length, ) - handler.add_method_parameter( "get_opening_angle2", "set_opening_angle2", "opening_angle2", - "opening angle, theta, for building the tree in case of tree solver: between 0 and 1", - default_value = 0.5 + "opening angle, theta, for building the tree in case of tree solver: between 0 and 1", + default_value=0.5, ) handler.add_method_parameter( "get_boundary", "set_boundary", "boundary", - "name of the boundary type to use ({0}) (required for tree solver)".format(sorted(self.BOUNDARIES.keys())), - default_value = "none" + "name of the boundary type to use ({0}) (required for tree solver)".format( + sorted(self.BOUNDARIES.keys()) + ), + default_value="none", ) handler.add_method_parameter( "get_boundary_size", "set_boundary_size", "boundary_size", - "size of the boundaries, if the type is not none", - default_value = 1.0 | nbody_system.length + "size of the boundaries, if the type is not none", + default_value=1.0 | nbody_system.length, ) - - def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) handler.add_method( @@ -610,54 +886,59 @@ def define_methods(self, handler): ( handler.INDEX, handler.ERROR_CODE, - ) - ) - + ), + ) + handler.add_method( "get_potential_energy", (handler.INDEX,), - (nbody_system.mass * nbody_system.length ** 2 * nbody_system.time ** -2, handler.ERROR_CODE,) + ( + nbody_system.mass * nbody_system.length**2 * nbody_system.time**-2, + handler.ERROR_CODE, + ), ) - handler.add_method( "get_kinetic_energy", (handler.INDEX,), - (nbody_system.mass * nbody_system.length ** 2 * nbody_system.time ** -2, handler.ERROR_CODE,) - ) - handler.add_method( - 'evolve_model', - ( - nbody_system.time, - handler.INDEX - ), ( + nbody_system.mass * nbody_system.length**2 * nbody_system.time**-2, handler.ERROR_CODE, - ) + ), + ) + handler.add_method( + "evolve_model", (nbody_system.time, handler.INDEX), (handler.ERROR_CODE,) ) handler.add_method( - 'get_time', + "get_time", (handler.INDEX,), - (nbody_system.time, handler.ERROR_CODE,) + ( + nbody_system.time, + handler.ERROR_CODE, + ), ) - + handler.add_method( "get_time_step", (handler.INDEX,), - (nbody_system.time, handler.ERROR_CODE,) + ( + nbody_system.time, + handler.ERROR_CODE, + ), ) handler.add_method( "set_time_step", - (nbody_system.time, handler.INDEX,), - (handler.ERROR_CODE,) + ( + nbody_system.time, + handler.INDEX, + ), + (handler.ERROR_CODE,), ) - + handler.add_method( "get_state", - ( - handler.NO_UNIT, - ), + (handler.NO_UNIT,), ( nbody_system.mass, nbody_system.length, @@ -668,18 +949,11 @@ def define_methods(self, handler): nbody_system.speed, nbody_system.length, handler.NO_UNIT, - handler.ERROR_CODE - ) + handler.ERROR_CODE, + ), ) handler.add_method( - "get_subset", - ( - handler.NO_UNIT, - ), - ( - handler.NO_UNIT, - handler.ERROR_CODE - ) + "get_subset", (handler.NO_UNIT,), (handler.NO_UNIT, handler.ERROR_CODE) ) handler.add_method( "set_subset", @@ -687,30 +961,22 @@ def define_methods(self, handler): handler.NO_UNIT, handler.NO_UNIT, ), - ( - - handler.ERROR_CODE, - ) + (handler.ERROR_CODE,), ) handler.add_method( - 'new_subset', - ( - nbody_system.time, - ), + "new_subset", + (nbody_system.time,), ( handler.INDEX, handler.ERROR_CODE, - ) + ), ) self.stopping_conditions.define_methods(handler) - - def define_particle_sets(self, handler): GravitationalDynamics.define_particle_sets(self, handler) - + self.stopping_conditions.define_particle_set(handler) - - handler.add_getter('particles', 'get_subset') - handler.add_setter('particles', 'set_subset') + handler.add_getter("particles", "get_subset") + handler.add_setter("particles", "set_subset") diff --git a/src/amuse/community/rebound/patch_files.py b/src/amuse/community/rebound/patch_files.py index 745536d73c..a913ee6fb1 100755 --- a/src/amuse/community/rebound/patch_files.py +++ b/src/amuse/community/rebound/patch_files.py @@ -6,53 +6,78 @@ import re PATCHESDIR = "patches" -QUILT_PC = ".pc" +QUILT_PC = ".pc" -def execute_command_line(arguments, cwd = None): - process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd = cwd) + +def execute_command_line(arguments, cwd=None): + process = subprocess.Popen( + arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd + ) stdoutstring, stderrstring = process.communicate() returncode = process.poll() return stdoutstring, stderrstring, returncode - + + def which(executablename): - stdoutstring, stderrstring, returncode = execute_command_line(['which', executablename]) + stdoutstring, stderrstring, returncode = execute_command_line( + ["which", executablename] + ) if not returncode == 0: return None else: return stdoutstring - + + def is_quilt_installed(): - path = which('quilt') + path = which("quilt") if path is None: return False - - stdoutstring, stderrstring, returncode = execute_command_line(['quilt', '--version']) + + stdoutstring, stderrstring, returncode = execute_command_line( + ["quilt", "--version"] + ) if not returncode == 0: return False - - version_re = re.compile(r'(\d).(\d\d)') - match = version_re.match(stdoutstring) + + version_re = re.compile(r"(\d).(\d\d)") + match = version_re.match(str(stdoutstring)) if not match: return False - + return True + def apply_patches_using_quilt(): - returncode = subprocess.call(['quilt', 'push', '-a']) + returncode = subprocess.call(["quilt", "push", "-a"]) if not returncode == 0: - raise Exception("error in applying the patches, please apply by hand using quilt push") - + raise Exception( + "error in applying the patches, please apply by hand using quilt push" + ) + + def undo_patches_using_quilt(): - returncode = subprocess.call(['quilt', 'pop', '-a']) + returncode = subprocess.call(["quilt", "pop", "-a"]) if not returncode == 0: - raise Exception("error in undoing the patches, please undo by hand using quilt pop -a") + raise Exception( + "error in undoing the patches, please undo by hand using quilt pop -a" + ) + def run_patch(patchname, patchfile): - arguments = ['patch', '-p1', '--backup', '--prefix={0}/{1}/'.format(QUILT_PC, patchname), '-E', '-i', patchfile] + arguments = [ + "patch", + "-p1", + "--backup", + "--prefix={0}/{1}/".format(QUILT_PC, patchname), + "-E", + "-i", + patchfile, + ] returncode = subprocess.call(arguments) if not returncode == 0: raise Exception("could not apply patch {0}".format(patchname)) - + + def apply_patches_using_patch(): with open("patches/series", "r") as f: lines = f.readlines() @@ -61,12 +86,13 @@ def apply_patches_using_patch(): for patch in patches: path = os.path.join(PATCHESDIR, patch) run_patch(patch, path) - -def main(undo_patches = False): - print("checking if quilt is installed ... ", end=' ') + + +def main(undo_patches=False): + print("checking if quilt is installed ... ", end=" ") if not is_quilt_installed(): print("no") - + if undo_patches: print("quilt is not installed, cannot undo the patches") sys.exit(1) @@ -75,7 +101,7 @@ def main(undo_patches = False): apply_patches_using_patch() else: print("yes") - + if undo_patches: print("quilt is install, will try to undo the patches") undo_patches_using_quilt() @@ -83,6 +109,7 @@ def main(undo_patches = False): print("applying patches to source code") apply_patches_using_quilt() print("all patches applied") - -if __name__ == '__main__': + + +if __name__ == "__main__": main() diff --git a/src/amuse/community/seba/download.py b/src/amuse/community/seba/download.py index 98d814094a..a5e009744b 100644 --- a/src/amuse/community/seba/download.py +++ b/src/amuse/community/seba/download.py @@ -93,7 +93,7 @@ def new_option_parser(): result = OptionParser() result.add_option( "--seba-version", - default='2f6e7f37a53167b4b0dcd6c723dff7b5ee1aecba', + default='94e9b1d6ba1466d288a12e3afaa1eba5bca6ddca', dest="seba_version", help="SeBa commit hash to download", type="string" diff --git a/src/amuse/community/seba/interface.cc b/src/amuse/community/seba/interface.cc index 871ee61a1c..0604274e0d 100644 --- a/src/amuse/community/seba/interface.cc +++ b/src/amuse/community/seba/interface.cc @@ -1,4 +1,3 @@ -#include "node.h" #include "single_star.h" #include "main_sequence.h" #include "worker_code.h" @@ -189,6 +188,51 @@ local int translate_stellar_type_to_int(stellar_type stp, const real mass) { } +local stellar_type translate_int_to_stellar_type(int type_number) { + + switch (type_number) { + case 19: + return Brown_Dwarf; + case 0: + case 1: + return Main_Sequence; + case 2: + return Hertzsprung_Gap; + case 3: + return Sub_Giant; + case 4: + return Horizontal_Branch; + case 5: + case 6: + return Super_Giant; +// return Hyper_Giant; + case 7: + return Helium_Star; + case 8: + case 9: + return Helium_Giant; + case 10: + return Helium_Dwarf; + case 11: + return Carbon_Dwarf; + case 12: + return Oxygen_Dwarf; + case 13: + return Neutron_Star; + case 14: + return Black_Hole; + case 15: + return Disintegrated; + case 17: + return Proto_Star; + case 18: + return Planet; + case -1: + return no_of_stellar_type; + } +} + + local int translate_binary_type_to_int(binary_type btp) { switch (btp) { @@ -419,6 +463,47 @@ int new_particle(int * index_of_the_star, double mass){ return 0; } + +int new_advanced_particle(int * index_of_the_star, double mass, double relative_mass, int type_number, double age, double core_mass, double COcore_mass, double radius){ + + if (relative_mass == 0) return new_particle(index_of_the_star, mass); + if (age < 0) return -1; + + node * new_node = new node(); + new_node->set_label(next_seba_id); + new_node->set_parent(seba_root); + new_node->set_mass(mass); + mapping_from_id_to_node[next_seba_id] = new_node; + + if(seba_insertion_point == 0) { + seba_insertion_point = new_node; + seba_root->set_oldest_daughter(new_node); + } else { + seba_insertion_point->set_younger_sister(new_node); + new_node->set_elder_sister(seba_insertion_point); + seba_insertion_point = new_node; + } + + stellar_type seba_stellar_type = translate_int_to_stellar_type(type_number); + + addstar(new_node, seba_time, seba_stellar_type, seba_metallicity, 0, false); + new_node->get_starbase()->set_time_offset(seba_time); + *index_of_the_star = next_seba_id; + + next_seba_id++; + + new_node->get_starbase()->set_relative_age(age); + new_node->get_starbase()->set_core_mass(core_mass); + new_node->get_starbase()->set_COcore_mass(COcore_mass); + new_node->get_starbase()->set_effective_radius(radius); + + + return 0; +} + + + + int delete_star(int index_of_the_star){ map::iterator i = mapping_from_id_to_node.find(index_of_the_star); @@ -728,6 +813,7 @@ int get_wind_mass_loss_rate(int index_of_the_star, double * wind_mass_loss_rate) + int evolve_one_step(int index_of_the_star){ int error_code = 0; int n_steps_per_phase = 10; @@ -966,3 +1052,19 @@ int set_rotation_period(int index_of_the_star, double value){ return error_code; } +int get_binary_type(int index_of_the_star, double * value){ + int error_code = 0; + node * seba_node = get_seba_node_from_index(index_of_the_star, &error_code); + if(error_code < 0) {return error_code;} + *value= seba_node->get_starbase()->get_bin_type(); + return error_code; +} + +int get_mass_transfer_type(int index_of_the_star, double * value){ + int error_code = 0; + node * seba_node = get_seba_node_from_index(index_of_the_star, &error_code); + if(error_code < 0) {return error_code;} + *value= seba_node->get_starbase()->get_current_mass_transfer_type(); + return error_code; +} + diff --git a/src/amuse/community/seba/interface.py b/src/amuse/community/seba/interface.py index 79463540d9..ed2261f7a4 100644 --- a/src/amuse/community/seba/interface.py +++ b/src/amuse/community/seba/interface.py @@ -45,6 +45,54 @@ def evolve_star(): function.can_handle_array = True return function + @legacy_function + def new_advanced_particle(): + """ + Define a new star in the code. The star will start with the given mass. + """ + function = LegacyFunctionSpecification() + function.can_handle_array = True + function.addParameter( + 'index_of_the_star', dtype='int32', direction=function.OUT, + description=( + "The new index for the star. This index can be used to refer " + "to this star in other functions" + ) + ) + function.addParameter( + 'mass', dtype='float64', direction=function.IN, + description="The initial mass of the star") + function.addParameter( + 'relative_mass', dtype='float64', direction=function.IN, default=0, + description="The initial relative mass of the star") + function.addParameter( + 'stellar_type', dtype='int32', direction=function.IN, default=0, + description="The initial stellar type of the star") + function.addParameter( + 'age', dtype='float64', direction=function.IN, default=0, + description="The initial age of the star") + function.addParameter( + 'core_mass', dtype='float64', direction=function.IN, default=0, + description="The initial core mass of the star") + function.addParameter( + 'COcore_mass', dtype='float64', direction=function.IN, default=0, + description="The initial CO core mass of the star") + function.addParameter( + 'radius', dtype='float64', direction=function.IN, default=0, + description="The initial radius of the star") + # function.addParameter( + # 'age_tag', dtype='float64', direction=function.IN, + # description="Starting age of the star *to be specified exactly*") + function.result_type = 'int32' + function.result_doc = """ + 0 - OK + New star was loaded and the index_of_the_star parameter set. + -1 - ERROR + New star could not be created. + """ + return function + + @legacy_function def new_binary(): """ @@ -145,6 +193,47 @@ def get_semi_major_axis(): A binary with the given index was not found. """ return function + + @legacy_function + def get_binary_type(): + """ + Retrieve the current binary type of the binary star. + """ + function = LegacyFunctionSpecification() + function.can_handle_array = True + function.addParameter('index_of_the_star', dtype='int32', direction=function.IN + , description="The index of the star to get the value of") + function.addParameter('value', dtype='float64', direction=function.OUT + , description="The current binary type.") + function.result_type = 'int32' + function.result_doc = """ + 0 - OK + The value has been set. + -1 - ERROR + A binary with the given index was not found. + """ + return function + + @legacy_function + def get_mass_transfer_type(): + """ + Retrieve the current mass transfer type of the binary star. + """ + function = LegacyFunctionSpecification() + function.can_handle_array = True + function.addParameter('index_of_the_star', dtype='int32', direction=function.IN + , description="The index of the star to get the value of") + function.addParameter('value', dtype='float64', direction=function.OUT + , description="The current mass transfer type.") + function.result_type = 'int32' + function.result_doc = """ + 0 - OK + The value has been set. + -1 - ERROR + A binary with the given index was not found. + """ + return function + @legacy_function def get_core_mass(): @@ -251,8 +340,6 @@ def merge_with_other_star(): """ return function - - @legacy_function def refresh_memory(): """ @@ -875,6 +962,11 @@ def define_methods(self, handler): (units.Myr,), (handler.ERROR_CODE,) ) + handler.add_method( + "new_advanced_particle", + (units.MSun, units.MSun, units.stellar_type, units.Myr, units.MSun, units.MSun, units.RSun), + (handler.INDEX, handler.ERROR_CODE) + ) handler.add_method( "new_binary", (units.RSun, handler.NO_UNIT, handler.LINK('particles'), handler.LINK('particles')), @@ -895,6 +987,16 @@ def define_methods(self, handler): (handler.INDEX,), (units.RSun, handler.ERROR_CODE,) ) + handler.add_method( + "get_binary_type", + (handler.INDEX,), + (handler.NO_UNIT, handler.ERROR_CODE,) + ) + handler.add_method( + "get_mass_transfer_type", + (handler.INDEX,), + (handler.NO_UNIT, handler.ERROR_CODE,) + ) handler.add_method( "get_core_mass", (handler.INDEX,), @@ -1075,14 +1177,16 @@ def define_parameters(self, handler): def define_particle_sets(self, handler): handler.define_set('particles', 'index_of_the_star') - handler.set_new('particles', 'new_particle') +# handler.set_new('particles', 'new_particle') + handler.set_new('particles', 'new_advanced_particle') handler.set_delete('particles', 'delete_star') - + + handler.add_getter('particles', 'get_radius', names = ('radius',)) handler.add_getter('particles', 'get_stellar_type', names = ('stellar_type',)) handler.add_getter('particles', 'get_mass', names = ('mass',)) handler.add_getter('particles', 'get_core_mass', names = ('core_mass',)) - handler.add_getter('particles', 'get_COcore_mass', names = ('CO_core_mass',)) + handler.add_getter('particles', 'get_COcore_mass', names = ('COcore_mass',)) handler.add_getter('particles', 'get_envelope_mass', names = ('envelope_mass',)) handler.add_getter('particles', 'get_core_radius', names = ('core_radius',)) handler.add_getter('particles', 'get_age', names = ('age',)) @@ -1091,6 +1195,7 @@ def define_particle_sets(self, handler): handler.add_getter('particles', 'get_luminosity', names = ('luminosity',)) handler.add_getter('particles', 'get_temperature', names = ('temperature',)) handler.add_getter('particles', 'get_natal_kick_velocity', names = ('natal_kick_x','natal_kick_y','natal_kick_z')) + handler.add_getter('particles', 'get_convective_envelope_mass', names = ('convective_envelope_mass',)) handler.add_getter('particles', 'get_convective_envelope_radius', names = ('convective_envelope_radius',)) handler.add_getter('particles', 'get_gyration_radius', names = ('gyration_radius',)) @@ -1120,13 +1225,17 @@ def define_particle_sets(self, handler): handler.set_delete('binaries', 'delete_binary') handler.add_getter('binaries', 'get_semi_major_axis', names = ('semi_major_axis',)) + handler.add_setter('binaries', 'set_semi_major_axis', names = ('semi_major_axis',)) handler.add_getter('binaries', 'get_eccentricity', names = ('eccentricity',)) + handler.add_setter('binaries', 'set_eccentricity', names = ('eccentricity',)) + handler.add_getter('binaries', 'get_mass', names = ('mass',)) handler.add_getter('binaries', 'get_time_step', names = ('time_step',)) handler.add_getter('binaries', 'get_age', names = ('age',)) handler.add_getter("binaries", 'get_children_of_binary') - handler.add_setter('binaries', 'set_semi_major_axis', names = ('semi_major_axis',)) - handler.add_setter('binaries', 'set_eccentricity', names = ('eccentricity',)) + handler.add_getter('binaries', 'get_binary_type', names = ('binary_type',)) + handler.add_getter('binaries', 'get_mass_transfer_type', names = ('mass_transfer_type',)) + handler.add_method('binaries', 'merge_the_binary') @@ -1135,6 +1244,11 @@ def define_state(self, handler): se.StellarEvolution.define_state(self, handler) self.stopping_conditions.define_state(handler) + + handler.add_method('EDIT', 'new_advanced_particle') + handler.add_method('UPDATE', 'new_advanced_particle') + handler.add_transition('RUN', 'UPDATE', 'new_advanced_particle', False) + diff --git a/src/amuse/community/simplex/src/Makefile b/src/amuse/community/simplex/src/Makefile index 2235291bcf..737c1a5b03 100644 --- a/src/amuse/community/simplex/src/Makefile +++ b/src/amuse/community/simplex/src/Makefile @@ -27,7 +27,7 @@ OBJ=./obj/ LIB=./lib/ BIN=./bin/ -CXXCFLAGS_NO_C = $(CXXFLAGS) -Wall -ansi -O2 -g -ffast-math -fomit-frame-pointer +CXXCFLAGS_NO_C = $(CXXFLAGS) -ansi -std=c++11 -ffast-math -fomit-frame-pointer CXXCFLAGS := $(CXXCFLAGS_NO_C) -c export CXXCFLAGS diff --git a/src/amuse/config.py b/src/amuse/config.py index 51d0f076b1..e60c45b346 100644 --- a/src/amuse/config.py +++ b/src/amuse/config.py @@ -6,27 +6,28 @@ import os import warnings - -def parse_configmk(filename): - configfile = open(filename, "r") - lines = configfile.readlines() - configfile.close() +def parse_configmk_lines(lines,label): cfgvars = dict() if "amuse configuration" not in lines[0]: raise Exception( - "file: {0} is not an amuse configuration file".format(filename) + f"{label} is not an amuse configuration file" ) for line in lines: if "=" in line: var, value = line.split("=", 1) if value.startswith("@") and value.endswith("@"): warnings.warn( - "possible configuration error/ unconfigured variable in" - " {0}".format(filename) + f"possible configuration error/ unconfigured variable in" + f" {label}" ) cfgvars[var] = value.strip() return cfgvars +def parse_configmk(filename): + configfile = open(filename, "r") + lines = configfile.readlines() + configfile.close() + return parse_configmk_lines(lines, "file " + filename) try: configmk = parse_configmk("config.mk") diff --git a/src/amuse/datamodel/grids.py b/src/amuse/datamodel/grids.py index 7f9365d729..8e6946cf5f 100644 --- a/src/amuse/datamodel/grids.py +++ b/src/amuse/datamodel/grids.py @@ -268,6 +268,9 @@ def get_axes_names(self): raise Exception("do not know how to find axes_names") + def set_axes_names(self, value): + self.add_vector_attribute('position', value) + class UnstructuredGrid(BaseGrid): GLOBAL_DERIVED_ATTRIBUTES=CompositeDictionary(BaseGrid.GLOBAL_DERIVED_ATTRIBUTES) class StructuredBaseGrid(BaseGrid): @@ -555,13 +558,15 @@ def indices(self): return [x[self._private.indices] for x in self._original_set().indices()] def __eq__(self, other): - if self._private.grid!=other._private.grid: - return False - else: - if numpy.all(numpy.array(self.indices())==numpy.array(other.indices())): - return True - else: + if self._private.grid != other._private.grid: + return False + elif self.shape != other.shape: return False + else: + if numpy.all(numpy.array(self.indices())==numpy.array(other.indices())): + return True + else: + return False def __ne__(self,other): return not(self==other) diff --git a/src/amuse/datamodel/incode_storage.py b/src/amuse/datamodel/incode_storage.py index 2d72a7bcd2..b9ce1fd68a 100644 --- a/src/amuse/datamodel/incode_storage.py +++ b/src/amuse/datamodel/incode_storage.py @@ -1134,7 +1134,7 @@ def get_values_in_store(self, indices, attributes): elif len(array_of_indices[0].shape) == 0: value = returned_value[0] else: - if len(returned_value)!=numpy.product(array_of_indices[0].shape): + if len(returned_value)!=numpy.prod(array_of_indices[0].shape): raise Exception("unexpected mismatch of array shapes") if isinstance(returned_value,list): returned_value=numpy.asarray(returned_value) diff --git a/src/amuse/datamodel/particles.py b/src/amuse/datamodel/particles.py index 3cc26db73b..40c1bd5431 100644 --- a/src/amuse/datamodel/particles.py +++ b/src/amuse/datamodel/particles.py @@ -386,6 +386,7 @@ def copy(self, memento = None, keep_structure = False, filter_attributes = lambd converted.append(x) result.add_particles_to_store(keys, attributes, converted) + object.__setattr__(result, "_derived_attributes", CompositeDictionary(self._derived_attributes)) result._private.collection_attributes = self._private.collection_attributes._copy_for_collection(result) return result @@ -425,6 +426,7 @@ def copy_to_new_particles(self, keys = None, keys_generator = None, memento = No result.add_particles_to_store(particle_keys, attributes, converted) + object.__setattr__(result, "_derived_attributes", CompositeDictionary(self._derived_attributes)) result._private.collection_attributes = self._private.collection_attributes._copy_for_collection(result) return result diff --git a/src/amuse/ext/grid_remappers.py b/src/amuse/ext/grid_remappers.py index 575ce59565..cee18897fa 100644 --- a/src/amuse/ext/grid_remappers.py +++ b/src/amuse/ext/grid_remappers.py @@ -2,266 +2,318 @@ from amuse.units import units -from amuse.units.quantities import is_quantity, value_in, to_quantity +from amuse.units.quantities import value_in, to_quantity -from amuse.datamodel import UnstructuredGrid, StructuredGrid, StructuredBaseGrid, RegularBaseGrid +from amuse.datamodel import ( + UnstructuredGrid, + StructuredBaseGrid, + RegularBaseGrid, +) try: - import matplotlib - from matplotlib import tri - if not hasattr(tri, "LinearTriInterpolator"): - raise Exception("LinearTriInterpolator not in matplotlib.tri") - matplotlib_available=True + import matplotlib + from matplotlib import tri + + if not hasattr(tri, "LinearTriInterpolator"): + raise Exception("LinearTriInterpolator not in matplotlib.tri") + matplotlib_available = True except: - matplotlib_available=False + matplotlib_available = False from warnings import warn + class interpolating_2D_remapper(object): - def __init__(self, source, target,axes_names=None): - """ this class maps a source grid to a target grid using linear - interpolation on a triangulation generated by adding a - midpoint to every cell (source should be a structured grid) - and thus generating 4 triangles for each cell. Values of the - midpoints are averaged from the corners. + def __init__(self, source, target, axes_names=None): + """this class maps a source grid to a target grid using linear + interpolation on a triangulation generated by adding a + midpoint to every cell (source should be a structured grid) + and thus generating 4 triangles for each cell. Values of the + midpoints are averaged from the corners. """ - if len(source.shape) !=2: + if len(source.shape) != 2: raise Exception("source grid is not 2D") if not isinstance(source, StructuredBaseGrid): raise Exception("source grid is not instance of StructuredBaseGrid") - self.source=source - self.target=target - self._axes_names=list(axes_names or source.get_axes_names()) + self.source = source + self.target = target + self._axes_names = list(axes_names or source.get_axes_names()) self.generate_triangulation() - def _generate_nodes(self,grid,attributes): + def _generate_nodes(self, grid, attributes): - Nx,Ny=grid.shape + Nx, Ny = grid.shape - x,y=numpy.mgrid[0:Nx,0:Ny] - x1,y1=numpy.mgrid[0:Nx-1,0:Ny-1] - - x_=x.flatten() - y_=y.flatten() - x1_=x1.flatten() - y1_=y1.flatten() + x, y = numpy.mgrid[0:Nx, 0:Ny] + x1, y1 = numpy.mgrid[0:Nx - 1, 0:Ny - 1] - l1=Nx*Ny + x_ = x.flatten() + y_ = y.flatten() + x1_ = x1.flatten() + y1_ = y1.flatten() - i=numpy.arange(Nx*Ny).reshape((Nx,Ny)) - i1=(numpy.arange((Nx-1)*(Ny-1))+l1).reshape((Nx-1,Ny-1)) + l1 = Nx * Ny - - nodes=UnstructuredGrid(len(x_)+len(x1_)) + nodes = UnstructuredGrid(len(x_) + len(x1_)) for name in attributes: - values1=getattr(grid,name)[x_,y_] - values2=getattr(grid,name)[x1_,y1_]+getattr(grid,name)[x1_+1,y1_]+\ - getattr(grid,name)[x1_,y1_+1]+getattr(grid,name)[x1_+1,y1_+1] - setattr(nodes[0], name, 0.*values1[0]) - setattr(nodes[:l1], name, 1.*values1) - setattr(nodes[l1:], name, values2/4) + values1 = getattr(grid, name)[x_, y_] + values2 = ( + getattr(grid, name)[x1_, y1_] + + getattr(grid, name)[x1_ + 1, y1_] + + getattr(grid, name)[x1_, y1_ + 1] + + getattr(grid, name)[x1_ + 1, y1_ + 1] + ) + setattr(nodes[0], name, 0.0 * values1[0]) + setattr(nodes[:l1], name, 1.0 * values1) + setattr(nodes[l1:], name, values2 / 4) return nodes - def _generate_elements_and_boundaries(self,grid): - Nx,Ny=grid.shape - - l1=Nx*Ny - - i=numpy.arange(Nx*Ny).reshape((Nx,Ny)) - i1=(numpy.arange((Nx-1)*(Ny-1))+l1).reshape((Nx-1,Ny-1)) - - e1=numpy.zeros(((Nx-1)*(Ny-1),3),dtype='i') - e2=numpy.zeros(((Nx-1)*(Ny-1),3),dtype='i') - e3=numpy.zeros(((Nx-1)*(Ny-1),3),dtype='i') - e4=numpy.zeros(((Nx-1)*(Ny-1),3),dtype='i') - - e1[:,0]=i[:-1,:-1].flatten() - e1[:,1]=i[1:,:-1].flatten() - e1[:,2]=i1[:,:].flatten() - - e2[:,0]=i[1:,:-1].flatten() - e2[:,1]=i[1:,1:].flatten() - e2[:,2]=i1[:,:].flatten() - - e3[:,0]=i[1:,1:].flatten() - e3[:,1]=i[:-1,1:].flatten() - e3[:,2]=i1[:,:].flatten() - - e4[:,0]=i[:-1,:-1].flatten() - e4[:,1]=i1[:,:].flatten() - e4[:,2]=i[:-1,1:].flatten() - - elements=numpy.zeros((4*(Nx-1)*(Ny-1),3),dtype='i8') - elements[0::4,:]=e1 - elements[1::4,:]=e2 - elements[2::4,:]=e3 - elements[3::4,:]=e4 - - boundaries=[xx.flatten() for xx in [i[:,0],i[-1,:],i[::-1,-1],i[0,::-1]] ] - - elem=UnstructuredGrid(len(elements)) - elem.nodes=elements - - return elem,boundaries + def _generate_elements_and_boundaries(self, grid): + Nx, Ny = grid.shape + + l1 = Nx * Ny + + i = numpy.arange(Nx * Ny).reshape((Nx, Ny)) + i1 = (numpy.arange((Nx - 1) * (Ny - 1)) + l1).reshape((Nx - 1, Ny - 1)) + + e1 = numpy.zeros(((Nx - 1) * (Ny - 1), 3), dtype="i") + e2 = numpy.zeros(((Nx - 1) * (Ny - 1), 3), dtype="i") + e3 = numpy.zeros(((Nx - 1) * (Ny - 1), 3), dtype="i") + e4 = numpy.zeros(((Nx - 1) * (Ny - 1), 3), dtype="i") + + e1[:, 0] = i[:-1, :-1].flatten() + e1[:, 1] = i[1:, :-1].flatten() + e1[:, 2] = i1[:, :].flatten() + + e2[:, 0] = i[1:, :-1].flatten() + e2[:, 1] = i[1:, 1:].flatten() + e2[:, 2] = i1[:, :].flatten() + + e3[:, 0] = i[1:, 1:].flatten() + e3[:, 1] = i[:-1, 1:].flatten() + e3[:, 2] = i1[:, :].flatten() + + e4[:, 0] = i[:-1, :-1].flatten() + e4[:, 1] = i1[:, :].flatten() + e4[:, 2] = i[:-1, 1:].flatten() + + elements = numpy.zeros((4 * (Nx - 1) * (Ny - 1), 3), dtype="i8") + elements[0::4, :] = e1 + elements[1::4, :] = e2 + elements[2::4, :] = e3 + elements[3::4, :] = e4 + + boundaries = [ + xx.flatten() for xx in [i[:, 0], i[-1, :], i[::-1, -1], i[0, ::-1]] + ] + + elem = UnstructuredGrid(len(elements)) + elem.nodes = elements + + return elem, boundaries def convert_grid_to_nodes_and_elements(self, grid, attributes=None): - + if attributes is None: - attributes=grid.get_attribute_names_defined_in_store() + attributes = grid.get_attribute_names_defined_in_store() + + nodes = self._generate_nodes(grid, attributes) + elements, boundaries = self._generate_elements_and_boundaries(grid) - nodes=self._generate_nodes(grid, attributes) - elements,boundaries=self._generate_elements_and_boundaries(grid) - - return nodes,elements,boundaries + return nodes, elements, boundaries def generate_triangulation(self): - nodes,elements,boundaries=self.convert_grid_to_nodes_and_elements(self.source, self._axes_names) + nodes, elements, boundaries = self.convert_grid_to_nodes_and_elements( + self.source, self._axes_names + ) + + xpos = to_quantity(getattr(nodes, self._axes_names[0])) + ypos = to_quantity(getattr(nodes, self._axes_names[1])) + + self._xpos_unit = xpos.unit + xpos = xpos.number + self._ypos_unit = ypos.unit + ypos = ypos.number - xpos=to_quantity(getattr(nodes,self._axes_names[0])) - ypos=to_quantity(getattr(nodes,self._axes_names[1])) - - self._xpos_unit=xpos.unit - xpos=xpos.number - self._ypos_unit=ypos.unit - ypos=ypos.number + n1 = elements.nodes[:, 0] + n2 = elements.nodes[:, 1] + n3 = elements.nodes[:, 2] + elem = numpy.column_stack((n1, n2, n3)) - n1=elements.nodes[:,0] - n2=elements.nodes[:,1] - n3=elements.nodes[:,2] - elem=numpy.column_stack((n1,n2,n3)) + self._triangulation = tri.Triangulation(xpos, ypos, elem) - self._triangulation=tri.Triangulation(xpos,ypos,elem) - def sample(self, values, xpos, ypos): - interpolator=tri.LinearTriInterpolator(self._triangulation,values) - return interpolator(xpos,ypos) + interpolator = tri.LinearTriInterpolator(self._triangulation, values) + return interpolator(xpos, ypos) def forward_mapping(self, attributes, target_names=None): if attributes is None: - attributes=self.source.get_attribute_names_defined_in_store() + attributes = self.source.get_attribute_names_defined_in_store() if target_names is None: - target_names=attributes - - source=self.source.empty_copy() - channel1=self.source.new_channel_to(source) - target=self.target.empty_copy() - channel2=self.target.new_channel_to(target) - channel3=target.new_channel_to(self.target) - + target_names = attributes + + source = self.source.empty_copy() + channel1 = self.source.new_channel_to(source) + target = self.target.empty_copy() + channel2 = self.target.new_channel_to(target) + channel3 = target.new_channel_to(self.target) + channel1.copy_attributes(attributes) channel2.copy_attributes(self._axes_names) - - nodes=self._generate_nodes(source,attributes) - - xpos=value_in( getattr(target,self._axes_names[0]), self._xpos_unit) - ypos=value_in( getattr(target,self._axes_names[1]), self._ypos_unit) - + + nodes = self._generate_nodes(source, attributes) + + xpos = value_in(getattr(target, self._axes_names[0]), self._xpos_unit) + ypos = value_in(getattr(target, self._axes_names[1]), self._ypos_unit) + for attribute, target_name in zip(attributes, target_names): - values=to_quantity( getattr(nodes,attribute) ) - unit=values.unit - values=values.number - samples=self.sample(values,xpos,ypos) - setattr(target, target_name, (samples if unit is units.none else (samples | unit))) + values = to_quantity(getattr(nodes, attribute)) + unit = values.unit + values = values.number + samples = self.sample(values, xpos, ypos) + setattr( + target, + target_name, + (samples if unit is units.none else (samples | unit)), + ) + + channel3.copy_attributes(target_names) - channel3.copy_attributes(target_names) class bilinear_2D_remapper(object): - def __init__(self, source, target, check_inside=True, do_slices=False): - """ this class maps a source grid to a target grid using bilinear - interpolation. If check_inside=True, raise exception if any - target point outside source grid. If the grids are 3 dimensional - it can be used to do a 2D interpolation of each level if shapes - are the same and positions are the same in the 3rd dimension. + def __init__( + self, source, target, check_inside=True, do_slices=False, x_periodic=False + ): + """this class maps a source grid to a target grid using bilinear + interpolation. If check_inside=True, raise exception if any + target point outside source grid. If the grids are 3 dimensional + it can be used to do a 2D interpolation of each level if shapes + are the same and positions are the same in the 3rd dimension. """ - if len(source.shape)!=2 and not do_slices: - raise Exception("source grid is not 2D, set do_slices=True remapping by slices") - if len(source.shape)!=len(target.shape): + if len(source.shape) != 2 and not do_slices: + raise Exception( + "source grid is not 2D, set do_slices=True remapping by slices" + ) + if len(source.shape) != len(target.shape): raise Exception("incompatible shapes") - if len(source.shape)!=2: - if numpy.any(source.shape[2:]!=target.shape[2:]): + if len(source.shape) != 2: + if numpy.any(source.shape[2:] != target.shape[2:]): raise Exception("source and target need same shapes (after dim 2)") if not isinstance(source, RegularBaseGrid): - raise Exception(f"source grid ({type(source)}) is not instance of RegularBaseGrid") - - self.source=source - self.target=target - self._axes_names=source.get_axes_names() - if len(source.shape)!=2: + raise Exception( + f"source grid ({type(source)}) is not instance of RegularBaseGrid" + ) + + self.source = source + self.target = target + self._axes_names = source.get_axes_names() + if len(source.shape) != 2: for x in self._axes_names[2:]: - if numpy.any(getattr(source[0,0],x)!=getattr(target[0,0],x)): - print(getattr(source[0,0],x)) - print(getattr(target[0,0],x)) + if numpy.any(getattr(source[0, 0], x) != getattr(target[0, 0], x)): + print(getattr(source[0, 0], x)) + print(getattr(target[0, 0], x)) warn(f"positions (possibly) not the same on axes {x}") - self.check_inside=check_inside - self._weights=None - self._indices=None + self.check_inside = check_inside + self.x_periodic = x_periodic + self._weights = None + self._indices = None def _calculate_weights(self): - x0=to_quantity( getattr(self.source[0,0], self._axes_names[0]) ) - x1=to_quantity( getattr(self.source[1,1], self._axes_names[0]) ) - y0=to_quantity( getattr(self.source[0,0], self._axes_names[1]) ) - y1=to_quantity( getattr(self.source[1,1], self._axes_names[1]) ) + x0 = to_quantity(getattr(self.source[0, 0], self._axes_names[0])) + x1 = to_quantity(getattr(self.source[1, 1], self._axes_names[0])) + y0 = to_quantity(getattr(self.source[0, 0], self._axes_names[1])) + y1 = to_quantity(getattr(self.source[1, 1], self._axes_names[1])) # guaranteed by grid being RegularBaseGrid - assert x0.max()==x0.min() - assert x1.max()==x1.min() - assert y0.max()==y0.min() - assert y1.max()==y1.min() - - x0=x0.min() - x1=x1.min() - y0=y0.min() - y1=y1.min() - - dx=x1-x0 - dy=y1-y0 - - x=getattr(self.target, self._axes_names[0]) - y=getattr(self.target, self._axes_names[1]) - - ix=numpy.floor((x-x0)/dx).astype(int) - iy=numpy.floor((y-y0)/dy).astype(int) + assert x0.max() == x0.min() + assert x1.max() == x1.min() + assert y0.max() == y0.min() + assert y1.max() == y1.min() + + x0 = x0.min() + x1 = x1.min() + y0 = y0.min() + y1 = y1.min() + + dx = x1 - x0 + dy = y1 - y0 + + x = getattr(self.target, self._axes_names[0]) + y = getattr(self.target, self._axes_names[1]) + + ix = numpy.floor((x - x0) / dx).astype(int) + iy = numpy.floor((y - y0) / dy).astype(int) + + ix2 = ix + 1 + iy2 = iy + 1 + + if self.x_periodic: + numpy.place(ix, ix == -1, self.source.shape[0] - 1) + numpy.place(ix, ix == self.source.shape[0], 0) + numpy.place(ix2, ix2 == self.source.shape[0], 0) + if self.check_inside: - if numpy.any(ix<0) or numpy.any(ix>self.source.shape[0]-2) or \ - numpy.any(iy<0) or numpy.any(iy>self.source.shape[1]-2): - raise Exception("target not fully inside (restricted) source grid as required") - ix=numpy.clip(ix,0, self.source.shape[0]-2) - iy=numpy.clip(iy,0, self.source.shape[1]-2) - - wx=(x0+(ix+1)*dx-x)/dx - wy=(y0+(iy+1)*dy-y)/dy - wx=numpy.clip(wx,0.,1.) - wy=numpy.clip(wy,0.,1.) - - self._weights=[wx,wy] - - while(len(ix.shape)>2): - ix=numpy.amax(ix,axis=-1) - iy=numpy.amax(iy,axis=-1) - - self._indices=[ix,iy] - + if ( + numpy.any(ix < 0) + or numpy.any(ix > self.source.shape[0] - 1) + or numpy.any(iy < 0) + or numpy.any(iy > self.source.shape[1] - 1) + or numpy.any(ix2 < 0) + or numpy.any(ix2 > self.source.shape[0] - 1) + or numpy.any(iy2 < 0) + or numpy.any(iy2 > self.source.shape[1] - 1) + ): + raise Exception( + "target not fully inside (restricted) source grid as required" + ) + + if not self.x_periodic: + ix = numpy.clip(ix, 0, self.source.shape[0] - 1) + ix2 = numpy.clip(ix2, 0, self.source.shape[0] - 1) + + iy = numpy.clip(iy, 0, self.source.shape[1] - 1) + iy2 = numpy.clip(iy2, 0, self.source.shape[1] - 1) + + wx = (x0 + (ix + 1) * dx - x) / dx + wy = (y0 + (iy + 1) * dy - y) / dy + wx = numpy.clip(wx, 0.0, 1.0) + wy = numpy.clip(wy, 0.0, 1.0) + + self._weights = [wx, wy] + + while len(ix.shape) > 2: + ix = numpy.amax(ix, axis=-1) + iy = numpy.amax(iy, axis=-1) + ix2 = numpy.amax(ix2, axis=-1) + iy2 = numpy.amax(iy2, axis=-1) + + self._indices = [ix, ix2, iy, iy2] + def _evaluate(self, values): - ix,iy=self._indices - wx,wy=self._weights - result=wx*wy*values[ix,iy]+(1.-wx)*wy*values[ix+1,iy]+ \ - wx*(1.-wy)*values[ix,iy+1]+(1.-wx)*(1.-wy)*values[ix+1,iy+1] + ix, ix2, iy, iy2 = self._indices + wx, wy = self._weights + result = ( + wx * wy * values[ix, iy] + + (1.0 - wx) * wy * values[ix2, iy] + + wx * (1.0 - wy) * values[ix, iy2] + + (1.0 - wx) * (1.0 - wy) * values[ix2, iy2] + ) return result def forward_mapping(self, attributes, target_names=None): if attributes is None: - attributes=self.source.get_attribute_names_defined_in_store() + attributes = self.source.get_attribute_names_defined_in_store() if target_names is None: - target_names=attributes + target_names = attributes if self._weights is None: self._calculate_weights() - - mapped_values=[] + + mapped_values = [] for attribute, target_name in zip(attributes, target_names): - values=getattr(self.source,attribute) - samples=self._evaluate(values) + values = getattr(self.source, attribute) + samples = self._evaluate(values) mapped_values.append(samples) self.target.set_values_in_store(None, target_names, mapped_values) @@ -269,58 +321,62 @@ def forward_mapping(self, attributes, target_names=None): class nearest_2D_remapper(object): def __init__(self, source, target, check_inside=True): - """ this class maps a source grid to a target grid getting closest - grid value. If check_inside=True, raise exception if any - target point outside source grid. + """this class maps a source grid to a target grid getting closest + grid value. If check_inside=True, raise exception if any + target point outside source grid. """ - if len(source.shape) !=2: + if len(source.shape) != 2: raise Exception("source grid is not 2D") if not isinstance(source, RegularBaseGrid): raise Exception("source grid is not instance of RegularBaseGrid") - self.source=source - self.target=target - self._axes_names=source.get_axes_names() - self.check_inside=check_inside - self._indices=None + self.source = source + self.target = target + self._axes_names = source.get_axes_names() + self.check_inside = check_inside + self._indices = None - def _calculate_weights(self): - x=getattr(self.target, self._axes_names[0]) - y=getattr(self.target, self._axes_names[1]) + def _calculate_weights(self): + x = getattr(self.target, self._axes_names[0]) + y = getattr(self.target, self._axes_names[1]) - kwargs={self._axes_names[0]: x, self._axes_names[1]:y} - indices=self.source.get_index(**kwargs) + kwargs = {self._axes_names[0]: x, self._axes_names[1]: y} + indices = self.source.get_index(**kwargs) - ix=indices[...,0] - iy=indices[...,1] + ix = indices[..., 0] + iy = indices[..., 1] if self.check_inside: - if numpy.any(ix<0) or numpy.any(ix>self.source.shape[0]-1) or \ - numpy.any(iy<0) or numpy.any(iy>self.source.shape[1]-1): - raise Exception("target not fully inside source grid as required") - ix=numpy.clip(ix,0, self.source.shape[0]-1) - iy=numpy.clip(iy,0, self.source.shape[1]-1) - - self._indices=[ix,iy] + if ( + numpy.any(ix < 0) + or numpy.any(ix > self.source.shape[0] - 1) + or numpy.any(iy < 0) + or numpy.any(iy > self.source.shape[1] - 1) + ): + raise Exception("target not fully inside source grid as required") + ix = numpy.clip(ix, 0, self.source.shape[0] - 1) + iy = numpy.clip(iy, 0, self.source.shape[1] - 1) + + self._indices = [ix, iy] def _evaluate(self, values): return values[self._indices[0], self._indices[1]] def forward_mapping(self, attributes, target_names=None): if attributes is None: - attributes=self.source.get_attribute_names_defined_in_store() + attributes = self.source.get_attribute_names_defined_in_store() if target_names is None: - target_names=attributes + target_names = attributes if self._indices is None: self._calculate_weights() - mapped_values=[] + mapped_values = [] for attribute, target_name in zip(attributes, target_names): - values=getattr(self.source,attribute) - samples=self._evaluate(values) + values = getattr(self.source, attribute) + samples = self._evaluate(values) mapped_values.append(samples) self.target.set_values_in_store(None, target_names, mapped_values) -def conservative_spherical_remapper(*args,**kwargs): +def conservative_spherical_remapper(*args, **kwargs): raise Exception("conservative_spherical_remapper has moved to omuse.ext") diff --git a/src/amuse/ic/brokenimf.py b/src/amuse/ic/brokenimf.py index fc19b34f8c..9966f03ac8 100644 --- a/src/amuse/ic/brokenimf.py +++ b/src/amuse/ic/brokenimf.py @@ -117,7 +117,7 @@ def calculate_fraction_per_bin(self): result.append(factor) total = sum(result, 0.0) - return numpy.array(result)/total + return numpy.array(result)/total if bool(total) else numpy.array(result) def mass_mean(self): result = 0 | units.MSun diff --git a/src/amuse/io/starlab.py b/src/amuse/io/starlab.py index bc82ac2291..ad2fbee668 100644 --- a/src/amuse/io/starlab.py +++ b/src/amuse/io/starlab.py @@ -351,7 +351,7 @@ def load_string(self, string): xml2particles.dynamics_length_units = self.dynamics_length_units xml2particles.parse_xml(xml_string) unit_converter = None - if not self.nbody_to_si_converter is None: + if self.nbody_to_si_converter is not None: unit_converter = self.nbody_to_si_converter elif self.must_scale: if not self._is_valid_scaling_factor(xml2particles.mass_scale): diff --git a/src/amuse/io/store_v2.py b/src/amuse/io/store_v2.py index 8fd39dd369..f6e15c4329 100644 --- a/src/amuse/io/store_v2.py +++ b/src/amuse/io/store_v2.py @@ -23,6 +23,8 @@ from amuse.datamodel import Grid from amuse.datamodel import GridPoint from amuse.datamodel import AbstractSet +from amuse.datamodel.base import VectorAttribute + from amuse.io import store_v1 @@ -738,11 +740,11 @@ def __init__( if append_to_file: if os.access(filename, os.F_OK) and not os.access(filename, os.W_OK): raise Exception("Opening file for append but file {0} is not writeable".format(filename)) - self.hdf5file = h5py.File(filename,'a') + self.hdf5file = h5py.File(filename,'a',libver='latest') elif open_for_writing: - self.hdf5file = h5py.File(filename,'w') + self.hdf5file = h5py.File(filename,'w',libver='latest') else: - self.hdf5file = h5py.File(filename,'r') + self.hdf5file = h5py.File(filename,'r',libver='latest') self.copy_history = copy_history self.mapping_from_groupid_to_set = {} @@ -847,6 +849,7 @@ def store_particles(self, particles, extra_attributes = {}, parent=None, mapping self.hdf5file.flush() self.store_collection_attributes(particles, group, extra_attributes, links) self.store_values(particles, group, links) + self.store_selected_derived_attributes(particles,group) mapping_from_setid_to_group[id(particles)] = group @@ -868,6 +871,7 @@ def store_grid(self, grid, extra_attributes = {}, parent=None, mapping_from_seti compression_opts=self.compression_opts, ) + self.store_selected_derived_attributes(grid, group) self.store_collection_attributes(grid, group, extra_attributes, links) self.store_values(grid, group, links) @@ -924,8 +928,15 @@ def store_values(self, container, group, links = []): ) dataset.attrs["units"] = "none".encode('ascii') + def store_selected_derived_attributes(self, container, group): + saving=dict() + for key in container._derived_attributes.keys(): + attr=container._derived_attributes[key] + if key not in container.GLOBAL_DERIVED_ATTRIBUTES and isinstance(attr, VectorAttribute): + saving[key]=attr + if len(saving): + group.attrs["extra_vector_attributes"]=pickle_to_string(saving) - def store_linked_array(self, attribute, attributes_group, quantity, group, links): subgroup = attributes_group.create_group(attribute) shape = quantity.shape @@ -1127,8 +1138,9 @@ def load_particles_from_group(self, group): self.mapping_from_groupid_to_set[group.id] = particles self.load_collection_attributes(particles, group) - - + if "extra_vector_attributes" in group.attrs.keys(): + self.load_extra_derived_attributes(particles, group) + return particles def load_grid_from_group(self, group): @@ -1143,9 +1155,16 @@ def load_grid_from_group(self, group): container._private.attribute_storage = HDF5GridAttributeStorage(shape, group, self) self.mapping_from_groupid_to_set[group.id] = container self.load_collection_attributes(container, group) + if "extra_vector_attributes" in group.attrs.keys(): + self.load_extra_derived_attributes(container, group) return container + def load_extra_derived_attributes(self, container, group): + attrs=unpickle_from_string(group.attrs["extra_vector_attributes"]) + for key, attr in attrs.items(): + container._derived_attributes[key]=attr + def load_from_group(self, group): container_type = group.attrs['type'] if isinstance(group.attrs['type'], str) else group.attrs['type'].decode('ascii') diff --git a/src/amuse/rfi/channel.py b/src/amuse/rfi/channel.py index 64decbe682..09fcebc3b2 100644 --- a/src/amuse/rfi/channel.py +++ b/src/amuse/rfi/channel.py @@ -35,8 +35,9 @@ from amuse.support.options import OptionalAttributes, option, GlobalOptions from amuse.support.core import late from amuse.support import exceptions -from amuse.support import get_amuse_root_dir +from amuse.support import get_amuse_root_dir, get_amuse_package_dir from amuse.rfi import run_command_redirected +from amuse.config import parse_configmk_lines from amuse.rfi import slurm @@ -509,9 +510,10 @@ def XTERM(cls, full_name_of_the_worker, channel, interpreter_executable=None, im @classmethod - def REDIRECT(cls, full_name_of_the_worker, stdoutname, stderrname, command=None, interpreter_executable=None, **options): + def REDIRECT(cls, full_name_of_the_worker, stdoutname, stderrname, command=None, + interpreter_executable=None, run_command_redirected_file=None ): - fname = run_command_redirected.__file__ + fname = run_command_redirected_file or run_command_redirected.__file__ arguments = [fname , stdoutname, stderrname] if not interpreter_executable is None: @@ -806,6 +808,8 @@ def split_message(self, call_id, function_id, call_count, dtype_to_arguments, en self._communicated_splitted_message = True self._merged_results_splitted_message = dtype_to_result + def makedirs(self,directory): + os.makedirs(directory) AbstractMessageChannel.DEBUGGERS = { @@ -1247,17 +1251,11 @@ def __setstate__(self, state): self._is_inuse = False self._communicated_splitted_message = False self.inuse_semaphore = threading.Semaphore() - - - @option(sections=("channel",)) def job_scheduler(self): """Name of the job scheduler to use when starting the code, if given will use job scheduler to find list of hostnames for spawning""" return "" - - - def get_info_from_job_scheduler(self, name, number_of_workers = 1): if name == "slurm": @@ -1277,7 +1275,7 @@ def get_info_from_slurm(cls, number_of_workers): for _ in range(tasks): all_nodes.append(node) cls._scheduler_nodes = all_nodes - cls._scheduler_index = 1 # start at 1 assumes that the python script is running on the first node as the first task + cls._scheduler_index = 1 # start at 1 assumes that the python script is running on the first node as the first task cls._scheduler_initialized = True print("NODES:", cls._scheduler_nodes) hostnames = [] @@ -1291,7 +1289,7 @@ def get_info_from_slurm(cls, number_of_workers): host = ','.join(hostnames) print("HOST:", host, cls._scheduler_index, os.environ['SLURM_TASKS_PER_NODE']) info = MPI.Info.Create() - info['host'] = host #actually in mpich and openmpi, the host parameter is interpreted as a comma separated list of host names, + info['host'] = host # actually in mpich and openmpi, the host parameter is interpreted as a comma separated list of host names, return info @@ -1473,21 +1471,17 @@ def _extra_path_item(self, path_of_the_module): if len(x) > len(result): result = x return result - - - @option(choices=AbstractMessageChannel.DEBUGGERS.keys(), sections=("channel",)) def debugger(self): """Name of the debugger to use when starting the code""" return "none" - - @option(type="boolean") def check_mpi(self): return True + class SocketMessage(AbstractMessage): def _receive_all(self, nbytes, thesocket): @@ -1679,7 +1673,6 @@ def send(self, socket): self.send_doubles(socket, self.encoded_units) # logger.debug("message send") - def send_doubles(self, socket, array): if len(array) > 0: @@ -1717,10 +1710,12 @@ def send_longs(self, socket, array): if len(array) > 0: data_buffer = numpy.array(array, dtype='int64') socket.sendall(data_buffer.tobytes()) - + + class SocketChannel(AbstractMessageChannel): - def __init__(self, name_of_the_worker, legacy_interface_type=None, interpreter_executable=None, **options): + def __init__(self, name_of_the_worker, legacy_interface_type=None, interpreter_executable=None, + remote_env=None, **options): AbstractMessageChannel.__init__(self, **options) #logging.getLogger().setLevel(logging.DEBUG) @@ -1731,10 +1726,16 @@ def __init__(self, name_of_the_worker, legacy_interface_type=None, interpreter_e self.name_of_the_worker = name_of_the_worker self.interpreter_executable = interpreter_executable - - if self.hostname != None and self.hostname not in ['localhost',socket.gethostname()]: - raise exceptions.CodeException("can only run codes on local machine using SocketChannel, not on %s", self.hostname) - + + if self.hostname == None: + self.hostname="localhost" + + if self.hostname not in ['localhost',socket.gethostname()]: + self.remote=True + self.must_check_if_worker_is_up_to_date=False + else: + self.remote=False + self.id = 0 if not legacy_interface_type is None: @@ -1748,7 +1749,7 @@ def __init__(self, name_of_the_worker, legacy_interface_type=None, interpreter_e self._communicated_splitted_message = False self.socket = None - + self.remote_env=remote_env @option(sections=("channel",)) def mpiexec(self): @@ -1761,10 +1762,6 @@ def mpiexec(self): def mpiexec_number_of_workers_flag(self): """flag to use, so that the number of workers are defined""" return '-n' - - - - @late def debugger_method(self): @@ -1787,28 +1784,9 @@ def accept_worker_connection(self, server_socket, process): raise exceptions.CodeException('worker still not started after 60 seconds') - - - def start(self): - server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - - server_socket.bind(('', 0)) - server_socket.settimeout(1.0) - server_socket.listen(1) - - logger.debug("starting socket worker process, listening for worker connection on %s", server_socket.getsockname()) - - #this option set by CodeInterface - logger.debug("mpi_enabled: %s", str(self.initialize_mpi)) - - # set arguments to name of the worker, and port number we listen on - - - self.stdout = None - self.stderr = None - + def generate_command_and_arguments(self,server_address,port): arguments = [] - + if not self.debugger_method is None: command, arguments = self.debugger_method(self.full_name_of_the_worker, self, interpreter_executable=self.interpreter_executable) else: @@ -1835,25 +1813,152 @@ def start(self): command = mpiexec[0] #append with port and hostname where the worker should connect - arguments.append(str(server_socket.getsockname()[1])) + arguments.append(port) #hostname of this machine - arguments.append(str(socket.gethostname())) - + arguments.append(server_address) + #initialize MPI inside worker executable arguments.append('true') else: #append arguments with port and socket where the worker should connect - arguments.append(str(server_socket.getsockname()[1])) + arguments.append(port) #local machine - arguments.append('localhost') + arguments.append(server_address) #do not initialize MPI inside worker executable arguments.append('false') + + return command,arguments + + def remote_env_string(self, hostname): + if self.remote_env is None: + if hostname in self.remote_envs.keys(): + return "source "+self.remote_envs[hostname]+"\n" + else: + return "" + else: + return "source "+self.remote_env +"\n" + + def generate_remote_command_and_arguments(self,hostname, server_address,port): + + # get remote config + args=["ssh","-T", hostname] + + command=self.remote_env_string(self.hostname)+ \ + "amusifier --get-amuse-config" +"\n" + + proc=Popen(args,stdout=PIPE, stdin=PIPE, executable="ssh") + out,err=proc.communicate(command.encode()) + + try: + remote_config=parse_configmk_lines(out.decode().split("\n"),"remote config at "+self.hostname ) + except: + raise Exception(f"failed getting remote config from {self.hostname} - please check remote_env argument ({self.remote_env})") + + # get remote amuse package dir + command=self.remote_env_string(self.hostname)+ \ + "amusifier --get-amuse-package-dir" +"\n" + + proc=Popen(args,stdout=PIPE, stdin=PIPE, executable="ssh") + out,err=proc.communicate(command.encode()) + + remote_package_dir=out.decode().strip(" \n\t") + local_package_dir=get_amuse_package_dir() + + mpiexec=remote_config["MPIEXEC"] + initialize_mpi=remote_config["MPI_ENABLED"] == 'yes' + run_command_redirected_file=run_command_redirected.__file__.replace(local_package_dir,remote_package_dir) + interpreter_executable=None if self.interpreter_executable==None else remote_config["PYTHON"] + # dynamic python workers? (should be send over) + full_name_of_the_worker=self.full_name_of_the_worker.replace(local_package_dir,remote_package_dir) + python_exe_for_redirection=remote_config["PYTHON"] + + if not self.debugger_method is None: + raise Exception("remote socket channel debugging not yet supported") + #command, arguments = self.debugger_method(self.full_name_of_the_worker, self, interpreter_executable=self.interpreter_executable) + else: + if self.redirect_stdout_file == 'none' and self.redirect_stderr_file == 'none': + + if interpreter_executable is None: + command = full_name_of_the_worker + arguments = [] + else: + command = interpreter_executable + arguments = [full_name_of_the_worker] + else: + command, arguments = self.REDIRECT(full_name_of_the_worker, self.redirect_stdout_file, + self.redirect_stderr_file, command=python_exe_for_redirection, + interpreter_executable=interpreter_executable, + run_command_redirected_file=run_command_redirected_file) + + #start arguments with command + arguments.insert(0, command) + + if initialize_mpi and len(mpiexec) > 0: + mpiexec = shlex.split(mpiexec) + # prepend with mpiexec and arguments back to front + arguments.insert(0, str(self.number_of_workers)) + arguments.insert(0, self.mpiexec_number_of_workers_flag) + arguments[:0] = mpiexec + command = mpiexec[0] + + #append with port and hostname where the worker should connect + arguments.append(port) + #hostname of this machine + arguments.append(server_address) - logger.debug("starting process with command `%s`, arguments `%s` and environment '%s'", command, arguments, os.environ) - self.process = Popen(arguments, executable=command, stdin=PIPE, stdout=None, stderr=None, close_fds=self.close_fds) - logger.debug("waiting for connection from worker") + #initialize MPI inside worker executable + arguments.append('true') + else: + #append arguments with port and socket where the worker should connect + arguments.append(port) + #local machine + arguments.append(server_address) + + #do not initialize MPI inside worker executable + arguments.append('false') + + return command,arguments + def start(self): + + server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + + server_address=self.get_host_ip(self.hostname) + + server_socket.bind((server_address , 0)) + server_socket.settimeout(1.0) + server_socket.listen(1) + + logger.debug("starting socket worker process, listening for worker connection on %s", server_socket.getsockname()) + + #this option set by CodeInterface + logger.debug("mpi_enabled: %s", str(self.initialize_mpi)) + + # set arguments to name of the worker, and port number we listen on + + self.stdout = None + self.stderr = None + + if self.remote: + command,arguments=self.generate_remote_command_and_arguments(self.hostname,server_address,str(server_socket.getsockname()[1])) + else: + command,arguments=self.generate_command_and_arguments(server_address,str(server_socket.getsockname()[1])) + + if self.remote: + logger.debug("starting remote process on %s with command `%s`, arguments `%s` and environment '%s'", self.hostname, command, arguments, os.environ) + ssh_command=self.remote_env_string(self.hostname)+" ".join(arguments) + arguments=["ssh","-T", self.hostname] + command="ssh" + self.process = Popen(arguments, executable=command, stdin=PIPE, stdout=None, stderr=None, close_fds=self.close_fds) + self.process.stdin.write(ssh_command.encode()) + self.process.stdin.close() + else: + logger.debug("starting process with command `%s`, arguments `%s` and environment '%s'", command, arguments, os.environ) + # ~ print(arguments) + self.process = Popen(arguments, executable=command, stdin=PIPE, stdout=None, stderr=None, close_fds=self.close_fds) + + logger.debug("waiting for connection from worker") self.socket, address = self.accept_worker_connection(server_socket, self.process) self.socket.setblocking(1) @@ -1870,7 +1975,12 @@ def start(self): @option(type="boolean", sections=("sockets_channel",)) def close_fds(self): """close open file descriptors when spawning child process""" - return True + return False + + @option(type="dict", sections=("sockets_channel",)) + def remote_envs(self): + """ dict of remote machine - enviroment (source ..) pairs """ + return dict() @option(choices=AbstractMessageChannel.DEBUGGERS.keys(), sections=("channel",)) def debugger(self): @@ -1889,6 +1999,9 @@ def stop(self): self.socket.close() self.socket = None + + if not self.process.stdin is None: + self.process.stdin.close() # should lookinto using poll with a timeout or some other mechanism # when debugger method is on, no killing @@ -1952,8 +2065,6 @@ def send_message(self, call_id, function_id, dtype_to_arguments={}, encoded_unit message.send(self.socket) self._is_inuse = True - - def recv_message(self, call_id, function_id, handle_as_array, has_units=False): @@ -1965,7 +2076,6 @@ def recv_message(self, call_id, function_id, handle_as_array, has_units=False): del self._merged_results_splitted_message return x - message = SocketMessage() message.receive(self.socket) @@ -1988,8 +2098,6 @@ def recv_message(self, call_id, function_id, handle_as_array, has_units=False): return message.to_result(handle_as_array), message.encoded_units else: return message.to_result(handle_as_array) - - def nonblocking_recv_message(self, call_id, function_id, handle_as_array, has_units=False): request = SocketMessage().nonblocking_receive(self.socket) @@ -2031,6 +2139,27 @@ def max_message_length(self): """ return 1000000 + def sanitize_host(self,hostname): + if "@" in hostname: + return hostname.split("@")[1] + return hostname + + def get_host_ip(self, client): + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.connect((self.sanitize_host(client), 80)) + ip=s.getsockname()[0] + s.close() + return ip + + def makedirs(self,directory): + if self.remote: + args=["ssh","-T", self.hostname] + command=f"mkdir -p {directory}\n" + proc=Popen(args,stdout=PIPE, stdin=PIPE, executable="ssh") + out,err=proc.communicate(command.encode()) + else: + os.makedirs(directory) + class OutputHandler(threading.Thread): @@ -2078,6 +2207,7 @@ def run(self): self.stream.write(data) + class DistributedChannel(AbstractMessageChannel): default_distributed_instance = None @@ -2161,8 +2291,6 @@ def __init__(self, name_of_the_worker, legacy_interface_type=None, interpreter_e logger.debug("worker dir is %s", self.worker_dir) self._is_inuse = False - - def check_if_worker_is_up_to_date(self, object): # if self.hostname != 'localhost': diff --git a/src/amuse/rfi/core.py b/src/amuse/rfi/core.py index 04b8645b11..fcd81d48e6 100644 --- a/src/amuse/rfi/core.py +++ b/src/amuse/rfi/core.py @@ -960,7 +960,9 @@ def channel_factory(self): if self.channel_type == 'mpi': if MpiChannel.is_supported(): return MpiChannel - else: + else: + warnings.warn("MPI (unexpectedly?) not available, falling back to sockets channel") + self.channel_type="sockets" return SocketChannel elif self.channel_type == 'remote': @@ -1064,15 +1066,17 @@ class CodeWithDataDirectories(object): def __init__(self): - if not self.channel_type == 'distributed': + if self.channel_type == 'distributed': + warnings.warn("Code with DistributedChannel wants to make output directory, check..") + else: self.ensure_data_directory_exists(self.get_output_directory()) def ensure_data_directory_exists(self, directory): directory = os.path.expanduser(directory) directory = os.path.expandvars(directory) - + try: - os.makedirs(directory) + self.channel.makedirs(directory) except OSError as ex: if ex.errno == errno.EEXIST and os.path.isdir(directory): pass diff --git a/src/amuse/rfi/gencode.py b/src/amuse/rfi/gencode.py index 0e222f9857..ee5d930bd0 100755 --- a/src/amuse/rfi/gencode.py +++ b/src/amuse/rfi/gencode.py @@ -25,7 +25,7 @@ from amuse.rfi.tools import create_dir from amuse.rfi.tools import create_python_worker -from amuse.support import get_amuse_root_dir +from amuse.support import get_amuse_root_dir, get_amuse_package_dir from amuse.support.literature import TrackLiteratureReferences def get_amuse_directory(): @@ -46,14 +46,6 @@ def get_amuse_directory(): #~ else: #~ return os.path.abspath(directory_of_this_script) -def get_amuse_directory_root(): - filename_of_this_script = __file__ - directory_of_this_script = os.path.dirname(os.path.dirname(filename_of_this_script)) - if os.path.isabs(directory_of_this_script): - return directory_of_this_script - else: - return os.path.abspath(directory_of_this_script) - def setup_sys_path(): amuse_directory = os.environ["AMUSE_DIR"] sys.path.insert(0, amuse_directory) @@ -171,6 +163,12 @@ def __init__(self): default=False, dest="get_amuse_dir", help="Only output amuse directory") + self.parser.add_option( + "--get-amuse-package-dir", + action="store_true", + default=False, + dest="get_amuse_package_dir", + help="Only output the amuse package root directory") self.parser.add_option( "--get-amuse-configmk", action="store_true", @@ -201,7 +199,7 @@ def parse_options(self): def parse_arguments(self): - if self.options.get_amuse_dir or self.options.get_amuse_configmk: + if self.options.get_amuse_dir or self.options.get_amuse_package_dir or self.options.get_amuse_configmk: return if self.options.mode == 'dir': if len(self.arguments) != 1: @@ -385,6 +383,9 @@ def amusifier(): if uc.options.get_amuse_dir: print(get_amuse_root_dir()) exit(0) + elif uc.options.get_amuse_package_dir: + print(get_amuse_package_dir()) + exit(0) elif uc.options.get_amuse_configmk: with open(os.path.join(get_amuse_root_dir(), "config.mk")) as f: print(f.read()) diff --git a/src/amuse/support/__init__.py b/src/amuse/support/__init__.py index 913bfde447..11fa96d2a1 100644 --- a/src/amuse/support/__init__.py +++ b/src/amuse/support/__init__.py @@ -26,3 +26,11 @@ def get_amuse_root_dir(): def get_amuse_data_dir(): return _Defaults().amuse_root_dir + +def get_amuse_package_dir(): + filename_of_this_script = __file__ + directory_of_this_script = os.path.dirname(os.path.dirname(filename_of_this_script)) + if os.path.isabs(directory_of_this_script): + return directory_of_this_script + else: + return os.path.abspath(directory_of_this_script) diff --git a/src/amuse/support/literature.py b/src/amuse/support/literature.py index ad9c28b837..e7a3418651 100644 --- a/src/amuse/support/literature.py +++ b/src/amuse/support/literature.py @@ -18,7 +18,7 @@ from docutils import nodes from amuse.support import exceptions try: - from amuse.version import version as amuse_version + from amuse._version import version as amuse_version except ImportError: amuse_version = "unknown version" @@ -281,14 +281,15 @@ def __init__(self): def version(cls): try: version = importlib.import_module( - '..version', + '.._version', cls.__module__ ).version except (ImportError, ValueError): try: from amuse.version import version + version = f"framework {version}" except ImportError: - version = "unknown" + version = "unknown version" return version @classmethod diff --git a/src/amuse/test/amusetest.py b/src/amuse/test/amusetest.py index 51cdf92c50..4f980cb6b8 100644 --- a/src/amuse/test/amusetest.py +++ b/src/amuse/test/amusetest.py @@ -302,8 +302,8 @@ class TestDefaults(_Defaults): @late def temporarydir(self): - dirname=tempfile.mkdtemp() - print(("generating temporary dir for test results: {0}". format(dirname))) + dirname = tempfile.mkdtemp(dir="./") + print(f"generating temporary dir for test results: {dirname}") return dirname @options.option(sections=['test']) @@ -317,7 +317,7 @@ def path_to_results(self): test_results_dir = os.path.join(amuse_root_dir, self.name_of_testresults_directory) if os.path.exists(test_results_dir): try: - f = open(os.path.join(test_results_dir,'test.txt'),'w') + f = open(os.path.join(test_results_dir, 'test.txt'), 'w') f.close() return test_results_dir except IOError as ex: @@ -327,9 +327,9 @@ def path_to_results(self): @options.option(sections=['test']) def name_of_testresults_directory(self): - return 'test_results' + return self.temporarydir - @options.option(type='boolean',sections=['test']) + @options.option(type='boolean', sections=['test']) def can_run_tests_to_compile_modules(self): return True diff --git a/src/amuse/test/suite/codes_tests/gd_tests.py b/src/amuse/test/suite/codes_tests/gd_tests.py index fcaa86387a..a1c308786f 100644 --- a/src/amuse/test/suite/codes_tests/gd_tests.py +++ b/src/amuse/test/suite/codes_tests/gd_tests.py @@ -305,9 +305,9 @@ def test7(self): # if they are implemented for the code, otherwise will call # get_state multiple times # todo, fi fails, need to check with inti - #self.assertAlmostRelativeEqual(instance.particles[-1].mass, new_particles[0].mass) - #self.assertAlmostRelativeEqual(instance.particles[-1].velocity, new_particles[0].velocity) - #self.assertAlmostRelativeEqual(instance.particles[-1].position, new_particles[0].position) + # self.assertAlmostRelativeEqual(instance.particles[-1].mass, new_particles[0].mass) + # self.assertAlmostRelativeEqual(instance.particles[-1].velocity, new_particles[0].velocity) + # self.assertAlmostRelativeEqual(instance.particles[-1].position, new_particles[0].position) instance.particles.synchronize_to(particles) self.assertEqual(len(particles), 99) self.assertEqual(particles[-1], new_particles[0]) diff --git a/src/amuse/test/suite/codes_tests/legacy_support.py b/src/amuse/test/suite/codes_tests/legacy_support.py index 8b13789179..e69de29bb2 100644 --- a/src/amuse/test/suite/codes_tests/legacy_support.py +++ b/src/amuse/test/suite/codes_tests/legacy_support.py @@ -1 +0,0 @@ - diff --git a/src/amuse/test/suite/codes_tests/test_aarsethzare.py b/src/amuse/test/suite/codes_tests/test_aarsethzare.py index 64bef81dff..e2d7a242ec 100644 --- a/src/amuse/test/suite/codes_tests/test_aarsethzare.py +++ b/src/amuse/test/suite/codes_tests/test_aarsethzare.py @@ -22,103 +22,103 @@ class TestAarsethZareInterface(TestWithMPI): def test0(self): instance = AarsethZareInterface() instance.stop() - + def test1(self): - + instance = AarsethZareInterface() time, x, y, z, vx, vy, vz, error = instance.evolve_triple( - [0,0,0], - [1,1,1], + [0, 0, 0], + [1, 1, 1], [-10, 0, 10], - [0,0,0], - [0,0,0], - [0,0,0], - [0,0,0], - [0,0,0], - [1.0,1.0,1.0] + [0, 0, 0], + [0, 0, 0], + [0, 0, 0], + [0, 0, 0], + [0, 0, 0], + [1.0, 1.0, 1.0] ) - + print(time, x, y, z, vx, vy, vz, error) self.assertEqual(error, 0) - self.assertAlmostRelativeEquals(y, [0,0,0]) - self.assertAlmostRelativeEquals(z, [0,0,0]) + self.assertAlmostRelativeEquals(y, [0, 0, 0]) + self.assertAlmostRelativeEquals(z, [0, 0, 0]) self.assertAlmostRelativeEquals(x[-1], -x[0], 10) self.assertAlmostRelativeEquals(x[1], 0, 10) self.assertAlmostRelativeEquals(vx[-1], -vx[0], 10) self.assertAlmostRelativeEquals(vx[1], 0, 10) - self.assertAlmostRelativeEquals(vy, [0,0,0]) - self.assertAlmostRelativeEquals(vz, [0,0,0]) - - + self.assertAlmostRelativeEquals(vy, [0, 0, 0]) + self.assertAlmostRelativeEquals(vz, [0, 0, 0]) + def test2(self): - + instance = AarsethZareInterface() time, x, y, z, vx, vy, vz, error = instance.evolve_triple( - [0,0], - [1,1], + [0, 0], + [1, 1], [-10, 0], - [0,0], - [0,0], - [0,0], - [0,0], - [0,0], + [0, 0], + [0, 0], + [0, 0], + [0, 0], + [0, 0], [1.0] ) - + self.assertEqual(error, -1) + class TestAarsethZare(TestWithMPI): def new_system_of_sun_and_earth_and_moon(self): stars = datamodel.Stars(3) sun = stars[0] sun.mass = units.MSun(1.0) - sun.position = units.m(numpy.array((0.0,0.0,0.0))) - sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) + sun.position = units.m(numpy.array((0.0, 0.0, 0.0))) + sun.velocity = units.ms(numpy.array((0.0, 0.0, 0.0))) sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) - earth.radius = units.km(6371) - earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) - earth.velocity = units.ms(numpy.array((0.0,29800,0.0))) - + earth.radius = units.km(6371) + earth.position = units.km(numpy.array((149.5e6, 0.0, 0.0))) + earth.velocity = units.ms(numpy.array((0.0, 29800, 0.0))) + moon = stars[2] - moon.mass = units.kg(7.3477e22 ) - moon.radius = units.km(1737.10) - moon.position = units.km(numpy.array((149.5e6 + 384399.0 ,0.0,0.0))) - moon.velocity = ([0.0,1.022,0] | units.km/units.s) + earth.velocity + moon.mass = units.kg(7.3477e22) + moon.radius = units.km(1737.10) + moon.position = units.km(numpy.array((149.5e6 + 384399.0, 0.0, 0.0))) + moon.velocity = ([0.0, 1.022, 0] | units.km/units.s) + earth.velocity return stars - + def test0(self): instance = AarsethZare() instance.stop() - + def test1(self): instance = AarsethZare() time, x, y, z, vx, vy, vz = instance.evolve_triple( - [0,0,0] | nbody_system.time, - [1,1,1] | nbody_system.mass, + [0, 0, 0] | nbody_system.time, + [1, 1, 1] | nbody_system.mass, [-10, 0, 10] | nbody_system.length, - [0,0,0] | nbody_system.length, - [0,0,0] | nbody_system.length, - [0,0,0] | nbody_system.speed, - [0,0,0] | nbody_system.speed, - [0,0,0] | nbody_system.speed, - [1.0,1.0,1.0]| nbody_system.time + [0, 0, 0] | nbody_system.length, + [0, 0, 0] | nbody_system.length, + [0, 0, 0] | nbody_system.speed, + [0, 0, 0] | nbody_system.speed, + [0, 0, 0] | nbody_system.speed, + [1.0, 1.0, 1.0] | nbody_system.time ) - - self.assertAlmostRelativeEquals(y, [0,0,0] | nbody_system.length) - self.assertAlmostRelativeEquals(z, [0,0,0] | nbody_system.length ) - self.assertAlmostRelativeEquals(x[-1], -x[0], 10 ) - self.assertAlmostRelativeEquals(x[1], 0 | nbody_system.length , 10) + + self.assertAlmostRelativeEquals(y, [0, 0, 0] | nbody_system.length) + self.assertAlmostRelativeEquals(z, [0, 0, 0] | nbody_system.length) + self.assertAlmostRelativeEquals(x[-1], -x[0], 10) + self.assertAlmostRelativeEquals(x[1], 0 | nbody_system.length, 10) self.assertAlmostRelativeEquals(vx[-1], -vx[0], 10) self.assertAlmostRelativeEquals(vx[1], 0 | nbody_system.speed, 10) - self.assertAlmostRelativeEquals(vy, [0,0,0] | nbody_system.speed) - self.assertAlmostRelativeEquals(vz, [0,0,0] | nbody_system.speed) - + self.assertAlmostRelativeEquals(vy, [0, 0, 0] | nbody_system.speed) + self.assertAlmostRelativeEquals(vz, [0, 0, 0] | nbody_system.speed) + def test2(self): instance = AarsethZare() - + particles = datamodel.Particles(3) particles.mass = 1.0 | nbody_system.mass particles.position = [ @@ -127,49 +127,45 @@ def test2(self): [10.0, 0.0, 0.0], ] | nbody_system.length particles.velocity = [0.0, 0.0, 0.0] | nbody_system.speed - + instance.particles.add_particles(particles) instance.evolve_model(1.0 | nbody_system.time) - - - self.assertAlmostRelativeEquals(instance.particles.y, [0,0,0] | nbody_system.length) - self.assertAlmostRelativeEquals(instance.particles.z, [0,0,0] | nbody_system.length ) - self.assertAlmostRelativeEquals(instance.particles.x[-1], -instance.particles.x[0], 10 ) - self.assertAlmostRelativeEquals(instance.particles.x[1], 0 | nbody_system.length , 10) + + self.assertAlmostRelativeEquals(instance.particles.y, [0, 0, 0] | nbody_system.length) + self.assertAlmostRelativeEquals(instance.particles.z, [0, 0, 0] | nbody_system.length) + self.assertAlmostRelativeEquals(instance.particles.x[-1], -instance.particles.x[0], 10) + self.assertAlmostRelativeEquals(instance.particles.x[1], 0 | nbody_system.length, 10) self.assertAlmostRelativeEquals(instance.particles.vx[-1], -instance.particles.vx[0], 10) self.assertAlmostRelativeEquals(instance.particles.vx[1], 0 | nbody_system.speed, 10) - self.assertAlmostRelativeEquals(instance.particles.vy, [0,0,0] | nbody_system.speed) - self.assertAlmostRelativeEquals(instance.particles.vz, [0,0,0] | nbody_system.speed) - - - + self.assertAlmostRelativeEquals(instance.particles.vy, [0, 0, 0] | nbody_system.speed) + self.assertAlmostRelativeEquals(instance.particles.vz, [0, 0, 0] | nbody_system.speed) + def test3(self): instance = AarsethZare(nbody_system.nbody_to_si(1.0 | units.yr, 1.0 | units.MSun)) - + particles = self.new_system_of_sun_and_earth_and_moon() instance.particles.add_particles(particles) - + earth = instance.particles[1] - + position_at_start = earth.position[0] - + instance.evolve_model(365.0 | units.day) - + position_after_full_rotation = earth.position[0] - + self.assertAlmostRelativeEquals(position_at_start, position_after_full_rotation, 4) instance.evolve_model(1.5 | units.yr) - + position_after_half_a_rotation = earth.position[0] - + self.assertAlmostRelativeEquals(-position_at_start, position_after_half_a_rotation, 2) - + instance.evolve_model(1.75 | units.yr) - + position_after_quarter_a_rotation = earth.position[1] - + self.assertAlmostRelativeEquals(position_at_start, position_after_quarter_a_rotation, 2) - + instance.stop() - diff --git a/src/amuse/test/suite/codes_tests/test_adaptb.py b/src/amuse/test/suite/codes_tests/test_adaptb.py index 5877827fe7..3d22a3dfee 100644 --- a/src/amuse/test/suite/codes_tests/test_adaptb.py +++ b/src/amuse/test/suite/codes_tests/test_adaptb.py @@ -12,7 +12,7 @@ class TestAdaptbInterface(TestWithMPI): - + def test1(self): print("Test AdaptbInterface initialization") instance = self.new_instance_of_an_optional_code(AdaptbInterface) @@ -24,74 +24,74 @@ def test1(self): def test2(self): print("Test AdaptbInterface new_particle / get_state") - instance = self.new_instance_of_an_optional_code(AdaptbInterface) + instance = self.new_instance_of_an_optional_code(AdaptbInterface) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.set_adaptb_output_directory(instance.output_directory)) self.assertEqual(0, instance.commit_parameters()) - - id, error = instance.new_particle(mass = 11.0, radius = 2.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) + + id, error = instance.new_particle(mass=11.0, radius=2.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) self.assertEqual(0, error) self.assertEqual(0, id) - id, error = instance.new_particle(mass = 21.0, radius = 5.0, x = 10.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) + id, error = instance.new_particle(mass=21.0, radius=5.0, x=10.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) self.assertEqual(0, error) self.assertEqual(1, id) self.assertEqual(0, instance.commit_particles()) - + retrieved_state1 = instance.get_state(0) retrieved_state2 = instance.get_state(1) self.assertEqual(0, retrieved_state1['__result']) self.assertEqual(0, retrieved_state2['__result']) self.assertEqual(11.0, retrieved_state1['mass']) self.assertEqual(21.0, retrieved_state2['mass']) - self.assertEqual( 0.0, retrieved_state1['x']) + self.assertEqual(0.0, retrieved_state1['x']) self.assertEqual(10.0, retrieved_state2['x']) - + self.assertEqual(0, instance.cleanup_code()) instance.stop() - + def test4(self): print("Test AdaptbInterface particle property getters/setters") - instance = self.new_instance_of_an_optional_code(AdaptbInterface) + instance = self.new_instance_of_an_optional_code(AdaptbInterface) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.set_adaptb_output_directory(instance.output_directory)) self.assertEqual(0, instance.commit_parameters()) self.assertEqual([0, 0], list(instance.new_particle(0.01, 1, 0, 0, 0, 1, 0, 0.1).values())) - self.assertEqual([1, 0], list(instance.new_particle(0.02, -1, 0, 0, 0,-1, 0, 0.1).values())) + self.assertEqual([1, 0], list(instance.new_particle(0.02, -1, 0, 0, 0, -1, 0, 0.1).values())) self.assertEqual(0, instance.commit_particles()) - + # getters mass, result = instance.get_mass(0) self.assertAlmostEqual(0.01, mass) - self.assertEqual(0,result) + self.assertEqual(0, result) radius, result = instance.get_radius(1) self.assertAlmostEqual(0.1, radius) - self.assertEqual(0,result) - self.assertEqual(-3, instance.get_mass(2)['__result']) # Particle not found - self.assertEqual([ 1, 0, 0, 0], list(instance.get_position(0).values())) + self.assertEqual(0, result) + self.assertEqual(-3, instance.get_mass(2)['__result']) # Particle not found + self.assertEqual([1, 0, 0, 0], list(instance.get_position(0).values())) self.assertEqual([-1, 0, 0, 0], list(instance.get_position(1).values())) - self.assertEqual([ 0, 1, 0, 0], list(instance.get_velocity(0).values())) - self.assertEqual([ 0,-1, 0, 0], list(instance.get_velocity(1).values())) - + self.assertEqual([0, 1, 0, 0], list(instance.get_velocity(0).values())) + self.assertEqual([0, -1, 0, 0], list(instance.get_velocity(1).values())) + # setters - self.assertEqual(0, instance.set_state(0, 0.01, 1,2,3, 4,5,6, 0.1)) - self.assertEqual([0.01, 1.0,2.0,3.0, 4.0,5.0,6.0, 0.1, 0], list(instance.get_state(0).values())) + self.assertEqual(0, instance.set_state(0, 0.01, 1, 2, 3, 4, 5, 6, 0.1)) + self.assertEqual([0.01, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.1, 0], list(instance.get_state(0).values())) self.assertEqual(0, instance.set_mass(0, 0.02)) - self.assertEqual([0.02, 1.0,2.0,3.0, 4.0,5.0,6.0, 0.1, 0], list(instance.get_state(0).values())) + self.assertEqual([0.02, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.1, 0], list(instance.get_state(0).values())) self.assertEqual(0, instance.set_radius(0, 0.2)) - self.assertEqual([0.02, 1.0,2.0,3.0, 4.0,5.0,6.0, 0.2, 0], list(instance.get_state(0).values())) - self.assertEqual(0, instance.set_position(0, 10,20,30)) - self.assertEqual([0.02, 10.0,20.0,30.0, 4.0,5.0,6.0, 0.2, 0], list(instance.get_state(0).values())) - self.assertEqual(0, instance.set_velocity(0, 40,50,60)) - self.assertEqual([0.02, 10.0,20.0,30.0, 40.0,50.0,60.0, 0.2, 0], list(instance.get_state(0).values())) + self.assertEqual([0.02, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.2, 0], list(instance.get_state(0).values())) + self.assertEqual(0, instance.set_position(0, 10, 20, 30)) + self.assertEqual([0.02, 10.0, 20.0, 30.0, 4.0, 5.0, 6.0, 0.2, 0], list(instance.get_state(0).values())) + self.assertEqual(0, instance.set_velocity(0, 40, 50, 60)) + self.assertEqual([0.02, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 0.2, 0], list(instance.get_state(0).values())) self.assertEqual(0, instance.cleanup_code()) instance.stop() def test5(self): print("Test AdaptbInterface parameters") - instance = self.new_instance_of_an_optional_code(AdaptbInterface) + instance = self.new_instance_of_an_optional_code(AdaptbInterface) self.assertEqual(0, instance.initialize_code()) - + # word length self.assertEqual([64, 0], list(instance.get_word_length().values())) self.assertEqual(0, instance.set_word_length(80)) @@ -104,15 +104,15 @@ def test5(self): # bs tolerance, string implementation for values requiring higher precision (note: actual accuracy depends on word_length) self.assertEqual(1e-8, eval(instance.get_bs_tolerance_string()["bs_tolerance"])) self.assertEqual(0, instance.set_bs_tolerance_string("1e-10")) - self.assertEqual([1e-10,0], list(instance.get_bs_tolerance_float64().values())) + self.assertEqual([1e-10, 0], list(instance.get_bs_tolerance_float64().values())) # new mpreal 1e-10 prints as 9.99999...e-11 # self.assertEquals(["1e-10", 0], instance.get_bs_tolerance_string().values()) - + # softening self.assertEqual([0.0, 0], list(instance.get_eps2().values())) self.assertEqual(0, instance.set_eps2(2e-1)) self.assertEqual([0.2, 0], list(instance.get_eps2().values())) - + # print intervals self.assertEqual([1e-1, 0], list(instance.get_dt_print().values())) self.assertEqual(0, instance.set_dt_print(1e-2)) @@ -122,46 +122,46 @@ def test5(self): self.assertEqual([3600, 0], list(instance.get_max_cpu_time().values())) self.assertEqual(0, instance.set_max_cpu_time(120)) self.assertEqual([120, 0], list(instance.get_max_cpu_time().values())) - + # output dir self.assertEqual(["./", 0], list(instance.get_adaptb_output_directory().values())) self.assertEqual(0, instance.set_adaptb_output_directory("./out")) self.assertEqual(["./out/", 0], list(instance.get_adaptb_output_directory().values())) self.assertEqual(0, instance.set_adaptb_output_directory(instance.output_directory)) self.assertEqual([instance.output_directory+"/", 0], list(instance.get_adaptb_output_directory().values())) - + self.assertEqual(0, instance.commit_parameters()) self.assertEqual(0, instance.cleanup_code()) instance.stop() - + def test6(self): print("Test AdaptbInterface evolve_model, equal-mass binary") - instance = self.new_instance_of_an_optional_code(AdaptbInterface) + instance = self.new_instance_of_an_optional_code(AdaptbInterface) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.set_dt_print(1e-1)) self.assertEqual(0, instance.set_word_length(64)) self.assertEqual(0, instance.set_bs_tolerance_float64(1.0e-8)) self.assertEqual(0, instance.set_adaptb_output_directory(instance.output_directory)) self.assertEqual(0, instance.commit_parameters()) - + self.assertEqual([0, 0], list(instance.new_particle(0.5, 0.5, 0, 0, 0, 0.5, 0).values())) - self.assertEqual([1, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0,-0.5, 0).values())) + self.assertEqual([1, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0, -0.5, 0).values())) self.assertEqual(0, instance.commit_particles()) - - self.assertEqual(0, instance.evolve_model(math.pi)) # half an orbit + + self.assertEqual(0, instance.evolve_model(math.pi)) # half an orbit for result, expected in zip(list(instance.get_position(0).values()), [-0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 5) - - self.assertEqual(0, instance.evolve_model(2 * math.pi)) # full orbit + + self.assertEqual(0, instance.evolve_model(2 * math.pi)) # full orbit for result, expected in zip(list(instance.get_position(0).values()), [0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 5) - + self.assertEqual(0, instance.cleanup_code()) instance.stop() def test7(self): print("Test AdaptbInterface evolve_model, pythagorean problem") - instance = self.new_instance_of_an_optional_code(AdaptbInterface) + instance = self.new_instance_of_an_optional_code(AdaptbInterface) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.set_dt_print(10.0)) self.assertEqual(0, instance.set_bs_tolerance_float64(1.0e-2)) @@ -174,17 +174,17 @@ def test7(self): self.assertEqual([2, 0], list(instance.new_particle("5", "1", "-1", "0", "0", "0", "0").values())) self.assertEqual(0, instance.commit_particles()) self.assertEqual(0, instance.evolve_model(100)) - + self.assertEqual(0, instance.cleanup_code()) instance.stop() def slowtest8(self): print("Test AdaptbInterface evolve_model, pythagorean problem, show convergence") tolerance = [1e-0, 1e-2, 1e-4, 1e-6, 1e-8, 1e-10, 1e-12, 1e-14, 1e-16, 1e-18, 1e-20, 1e-22, 1e-24] - word_length = [64, 64, 64 , 64, 64, 64, 80, 80, 96, 96, 112, 112, 128] - + word_length = [64, 64, 64, 64, 64, 64, 80, 80, 96, 96, 112, 112, 128] + for tol, word_len in zip(tolerance, word_length): - instance = self.new_instance_of_an_optional_code(AdaptbInterface) + instance = self.new_instance_of_an_optional_code(AdaptbInterface) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.set_dt_print(0.1)) self.assertEqual(0, instance.set_bs_tolerance_float64(tol)) @@ -198,7 +198,7 @@ def slowtest8(self): self.assertEqual(0, instance.evolve_model(100)) self.assertEqual(0, instance.cleanup_code()) instance.stop() - + data_log = read_log(os.path.join(instance.output_directory, "file.log")) data_out = read_out(os.path.join(instance.output_directory, "file.out")) tcpu = data_log[9] @@ -210,56 +210,56 @@ def slowtest8(self): print("CPU time for calculation:", tcpu) print("Relative energy error:", dE) print("Final x position and velocity of first particle:", x0, vx0) - + def xtest9(self): print("Test AdaptbInterface evolve_model, pythagorean problem, plot orbits") - tolerance = ["1e-4", "1e-8"] #, "1e-12", "1e-16"] - word_length = [64 , 64] #, 80, 96] - + tolerance = ["1e-4", "1e-8"] # , "1e-12", "1e-16"] + word_length = [64, 64] # , 80, 96] + x1 = [] y1 = [] x2 = [] y2 = [] x3 = [] y3 = [] - - i=0 - while i 1.0: potential = 0.0 if py < 0 or py > 1.0: potential = 0.0 - #print potential + # print potential potential_grid.potential[i][j][0] = -0.001 * generic_unit_system.potential.new_quantity([potential]) - #instance.potential_grid[i][j][0].potential = -0.001 * generic_unit_system.potential.new_quantity([potential]) + # instance.potential_grid[i][j][0].potential = -0.001 * generic_unit_system.potential.new_quantity([potential]) channel = potential_grid.new_channel_to(instance.potential_grid) channel.copy() print(2) result = instance.initialize_grid() - + self.assertEqual(instance.grid[1][1][0].rho, 0.1 | density) for x in instance.grid[1].rho.value_in(density).flatten(): self.assertAlmostRelativeEquals(x, 0.1) - #print instance.potential_grid[...,0].potential + # print instance.potential_grid[...,0].potential instance.evolve_model(1.0 | generic_unit_system.time) - #print "--------------------------" - #print instance.grid.rho[...,0] - z = instance.grid.rho[...,0] - #z = instance.potential_grid.potential[...,0] - #z = z.value_in(generic_unit_system.potential) + # print "--------------------------" + # print instance.grid.rho[...,0] + z = instance.grid.rho[..., 0] + # z = instance.potential_grid.potential[...,0] + # z = z.value_in(generic_unit_system.potential) z = z.value_in(density) - #from matplotlib import pyplot - #x = instance.potential_grid[...,50,0].x - ##y = instance.potential_grid[...,50,0].y - #z = instance.potential_grid[...,50,0].z - #pyplot.plot(x.value_in(generic_unit_system.length), instance.potential_grid[...,50,0].potential.value_in(generic_unit_system.potential)) - - #dx = x[1] - x[0] - #x += 1.5 * dx - #interpolated = instance.get_interpolated_gravitational_potential(x,y,z) - #pyplot.plot(x.value_in(generic_unit_system.length), interpolated.value_in(generic_unit_system.potential)) - - #img = pyplot.imshow(z) - #img.set_interpolation('none') - - #pyplot.savefig("bla.png") + # from matplotlib import pyplot + # x = instance.potential_grid[...,50,0].x + ## y = instance.potential_grid[...,50,0].y + # z = instance.potential_grid[...,50,0].z + # pyplot.plot(x.value_in(generic_unit_system.length), instance.potential_grid[...,50,0].potential.value_in(generic_unit_system.potential)) + + # dx = x[1] - x[0] + # x += 1.5 * dx + # interpolated = instance.get_interpolated_gravitational_potential(x,y,z) + # pyplot.plot(x.value_in(generic_unit_system.length), interpolated.value_in(generic_unit_system.potential)) + + # img = pyplot.imshow(z) + # img.set_interpolation('none') + + # pyplot.savefig("bla.png") for x in instance.grid.rho.value_in(density).flatten(): self.assertNotEqual(x, 0.1) instance.stop() - - def test5(self): - instance=self.new_instance(Athena) + instance = self.new_instance(Athena) self.assertAlmostRelativeEquals(instance.parameters.isothermal_sound_speed, 0.0 | generic_unit_system.speed) instance.parameters.isothermal_sound_speed = 0.1 | generic_unit_system.speed self.assertAlmostRelativeEquals(instance.parameters.isothermal_sound_speed, 0.1 | generic_unit_system.speed) @@ -1709,219 +1634,209 @@ def test5(self): self.assertAlmostRelativeEquals(instance.parameters.courant_number, 0.3) instance.parameters.courant_number = 0.1 self.assertAlmostRelativeEquals(instance.parameters.courant_number, 0.1) - + print(instance.parameters) instance.stop() - - def test6(self): - instance=self.new_instance(Athena) + instance = self.new_instance(Athena) instance.set_gamma(1.6666666666666667) instance.set_courant_friedrichs_lewy_number(0.3) - instance.setup_mesh(10 , 20, 40, 1.0 | generic_unit_system.length, 1.0 | generic_unit_system.length, 1.0 | generic_unit_system.length) - instance.set_boundary("periodic","periodic","periodic","periodic","periodic","periodic") - - + instance.setup_mesh(10, 20, 40, 1.0 | generic_unit_system.length, 1.0 | generic_unit_system.length, 1.0 | generic_unit_system.length) + instance.set_boundary("periodic", "periodic", "periodic", "periodic", "periodic", "periodic") + density = generic_unit_system.mass / (generic_unit_system.length ** 3) - momentum = generic_unit_system.mass / (generic_unit_system.time * (generic_unit_system.length**2)) - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - - grid = datamodel.new_regular_grid((10,10,10), [10.0, 10.0, 10.0] | units.m) - + momentum = generic_unit_system.mass / (generic_unit_system.time * (generic_unit_system.length**2)) + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + + grid = datamodel.new_regular_grid((10, 10, 10), [10.0, 10.0, 10.0] | units.m) + grid.rho = 0.4 | density grid.rhovx = 0.1 | momentum grid.rhovy = 0.2 | momentum grid.rhovz = 0.3 | momentum grid.energy = 0.5 | energy - + channel = grid.new_channel_to(instance.grid) channel.copy() self.assertEqual(instance.grid[0][0][0].rho, 0.4 | density) self.assertEqual(instance.grid.rho.number.ndim, 3) - + self.assertEqual(len(list(instance.itergrids())), 1) - + instance.stop() def test7(self): - instance=self.new_instance(Athena) + instance = self.new_instance(Athena) instance.parameters.isothermal_sound_speed = 0.1 | generic_unit_system.speed instance.parameters.gamma = 0.1 instance.parameters.courant_number = 0.1 - + instance.parameters.nx = 10 instance.parameters.ny = 20 instance.parameters.nz = 40 - + instance.parameters.length_x = 10 | generic_unit_system.length instance.parameters.length_y = 20 | generic_unit_system.length instance.parameters.length_z = 30 | generic_unit_system.length - + print(instance.parameters) instance.commit_parameters() - - mini,maxi, minj,maxj, mink,maxk = instance.get_index_range_inclusive() - + + mini, maxi, minj, maxj, mink, maxk = instance.get_index_range_inclusive() + self.assertEqual(mini, 0) self.assertEqual(maxi, 9) self.assertEqual(minj, 0) self.assertEqual(maxj, 19) self.assertEqual(mink, 0) self.assertEqual(maxk, 39) - self.assertEqual(instance.parameters.mesh_size, (10,20,40)) + self.assertEqual(instance.parameters.mesh_size, (10, 20, 40)) print(instance.parameters) instance.stop() - + def test8(self): - instance=self.new_instance(Athena) + instance = self.new_instance(Athena) instance.parameters.stopping_conditions_number_of_steps = 10 self.assertEqual(instance.parameters.stopping_conditions_number_of_steps, 10) instance.stop() def test8a(self): - instance=self.new_instance(Athena) + instance = self.new_instance(Athena) instance.parameters.stopping_conditions_timeout = 10 | units.s - self.assertEqual(instance.parameters.stopping_conditions_timeout, 10|units.s) + self.assertEqual(instance.parameters.stopping_conditions_timeout, 10 | units.s) instance.stop() def test9(self): - instance=self.new_instance(Athena) - instance.parameters.x_boundary_conditions = "periodic","periodic" - instance.parameters.y_boundary_conditions = "periodic","periodic" - instance.parameters.z_boundary_conditions = "periodic","periodic" + instance = self.new_instance(Athena) + instance.parameters.x_boundary_conditions = "periodic", "periodic" + instance.parameters.y_boundary_conditions = "periodic", "periodic" + instance.parameters.z_boundary_conditions = "periodic", "periodic" self.assertEqual(instance.parameters.xbound1, "periodic") instance.stop() def xtest10(self): - instance=self.new_instance(Athena) + instance = self.new_instance(Athena) instance.parameters.gamma = 5/3.0 - instance.parameters.courant_number=0.3 - + instance.parameters.courant_number = 0.3 + n = 100 - + instance.parameters.nx = n instance.parameters.ny = n instance.parameters.nz = n - + instance.parameters.length_x = 1 | generic_unit_system.length instance.parameters.length_y = 1 | generic_unit_system.length instance.parameters.length_z = 1 | generic_unit_system.length - - instance.x_boundary_conditions = ("periodic","periodic") - instance.y_boundary_conditions = ("periodic","periodic") - instance.z_boundary_conditions = ("periodic","periodic") - + + instance.x_boundary_conditions = ("periodic", "periodic") + instance.y_boundary_conditions = ("periodic", "periodic") + instance.z_boundary_conditions = ("periodic", "periodic") + result = instance.commit_parameters() - + density = generic_unit_system.mass / (generic_unit_system.length**3) - + density = generic_unit_system.density - momentum = generic_unit_system.speed * generic_unit_system.density - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - - grid = datamodel.Grid(n,n,n) - grid.rho = 0.0 | generic_unit_system.density + momentum = generic_unit_system.speed * generic_unit_system.density + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + + grid = datamodel.Grid(n, n, n) + grid.rho = 0.0 | generic_unit_system.density grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum grid.energy = 0.0 | energy - + halfway = n/2 - 1 - grid[:halfway].rho = 4.0 | generic_unit_system.density - grid[:halfway].energy = (1.0 | energy)/ (instance.parameters.gamma - 1) - grid[halfway:].rho = 1.0 | generic_unit_system.density - grid[halfway:].energy = (0.1795 | energy)/ (instance.parameters.gamma - 1) - + grid[:halfway].rho = 4.0 | generic_unit_system.density + grid[:halfway].energy = (1.0 | energy) / (instance.parameters.gamma - 1) + grid[halfway:].rho = 1.0 | generic_unit_system.density + grid[halfway:].energy = (0.1795 | energy) / (instance.parameters.gamma - 1) + channel = grid.new_channel_to(instance.grid) channel.copy() - - #from amuse import plot - #from matplotlib import pyplot - #print grid.rho[...,0,0] - #plot.plot(instance.grid.x[...,0,0], grid.rho[...,0,0]) - #pyplot.savefig("bla1.png") - + + # from amuse import plot + # from matplotlib import pyplot + # print grid.rho[...,0,0] + # plot.plot(instance.grid.x[...,0,0], grid.rho[...,0,0]) + # pyplot.savefig("bla1.png") + error = instance.initialize_grid() - + instance.evolve_model(0.12 | generic_unit_system.time) - - + channel = instance.grid.new_channel_to(grid) channel.copy() - - #print grid.rho[...,0,0] - #plot.plot(instance.grid.x[...,0,0], grid.rho[...,0,0]) - #pyplot.savefig("bla2.png") + + # print grid.rho[...,0,0] + # plot.plot(instance.grid.x[...,0,0], grid.rho[...,0,0]) + # pyplot.savefig("bla2.png") instance.stop() - - + def test11(self): - instance=self.new_instance(Athena, mode=AthenaInterface.MODE_SELF_GRAVITY) #, redirection = "none") #, debugger="gdb") + instance = self.new_instance(Athena, mode=AthenaInterface.MODE_SELF_GRAVITY) # , redirection = "none") #, debugger="gdb") instance.parameters.gamma = 5/3.0 - instance.parameters.courant_number=0.3 - + instance.parameters.courant_number = 0.3 + density = generic_unit_system.mass / (generic_unit_system.length ** 3) - momentum = generic_unit_system.mass / (generic_unit_system.time * (generic_unit_system.length**2)) - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - - - instance.parameters.four_pi_G = 4 * numpy.pi * (1|(generic_unit_system.length**3) / (generic_unit_system.mass * (generic_unit_system.time**2))) # G = 1, like nbody + momentum = generic_unit_system.mass / (generic_unit_system.time * (generic_unit_system.length**2)) + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + + instance.parameters.four_pi_G = 4 * numpy.pi * (1 | (generic_unit_system.length**3) / (generic_unit_system.mass * (generic_unit_system.time**2))) # G = 1, like nbody instance.parameters.gravity_mean_rho = 0.0 | density - - datamodel.Grid.add_global_vector_attribute("position", ["x","y","z"]) + datamodel.Grid.add_global_vector_attribute("position", ["x", "y", "z"]) n = 10 - + instance.parameters.nx = n instance.parameters.ny = n instance.parameters.nz = n - + instance.parameters.length_x = 4.0 | generic_unit_system.length instance.parameters.length_y = 4.0 | generic_unit_system.length instance.parameters.length_z = 4.0 | generic_unit_system.length - - instance.x_boundary_conditions = ("periodic","periodic") - instance.y_boundary_conditions = ("periodic","periodic") - instance.z_boundary_conditions = ("periodic","periodic") - + + instance.x_boundary_conditions = ("periodic", "periodic") + instance.y_boundary_conditions = ("periodic", "periodic") + instance.z_boundary_conditions = ("periodic", "periodic") + result = instance.commit_parameters() - - grid = datamodel.new_regular_grid((n,n,n), [4.0 , 4.0, 4.0] | generic_unit_system.length) - + + grid = datamodel.new_regular_grid((n, n, n), [4.0, 4.0, 4.0] | generic_unit_system.length) + grid.rho = 0.0 | generic_unit_system.density grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum grid.energy = 0.001 | energy - + scaled_radius = 1.0 / 1.695 | generic_unit_system.length total_mass = 1.0 | generic_unit_system.mass - + radii = (grid.position - ([2.0, 2.0, 2.0] | generic_unit_system.length)).lengths() - - rho_sphere = ((0.75 * total_mass / (numpy.pi * (scaled_radius ** 3)))) - grid.rho = (rho_sphere * ((1 + (radii ** 2) / (scaled_radius ** 2))**(-5.0/2.0))) - - internal_energy = (0.25 | generic_unit_system.time ** -2 * generic_unit_system.mass ** -1 * generic_unit_system.length **3) * total_mass / scaled_radius + + rho_sphere = ((0.75 * total_mass / (numpy.pi * (scaled_radius ** 3)))) + grid.rho = (rho_sphere * ((1 + (radii ** 2) / (scaled_radius ** 2))**(-5.0/2.0))) + + internal_energy = (0.25 | generic_unit_system.time ** -2 * generic_unit_system.mass ** -1 * generic_unit_system.length ** 3) * total_mass / scaled_radius grid.energy = grid.rho * internal_energy/(1+(radii/scaled_radius)**2)**(1.0/2.0) - - - + channel = grid.new_channel_to(instance.grid) channel.copy() - + instance.initialize_grid() - + instance.evolve_model(0.01 | generic_unit_system.time) - G = 1.0 | generic_unit_system.length **3 * generic_unit_system.mass**-1 * generic_unit_system.time**-2 + G = 1.0 | generic_unit_system.length ** 3 * generic_unit_system.mass**-1 * generic_unit_system.time**-2 a = instance.grid[5][5].gravitational_potential - b = (-1 * G * total_mass / (radii**2+scaled_radius**2).sqrt()) [5][5] - + b = (-1 * G * total_mass / (radii**2+scaled_radius**2).sqrt())[5][5] + for x in a: self.assertTrue(x < 0 | generic_unit_system.potential) - - + a = instance.grid[5][5].gravitational_acceleration_z for index, x in enumerate(a): if index < 5: @@ -1929,10 +1844,10 @@ def test11(self): else: self.assertTrue(x < 0 | generic_unit_system.acceleration) instance.stop() - + def test12(self): print("Testing Athena grid setters") - instance=self.new_instance(Athena) + instance = self.new_instance(Athena) instance.parameters.isothermal_sound_speed = 0.1 | generic_unit_system.speed instance.parameters.gamma = 5/3.0 instance.parameters.courant_number = 0.3 @@ -1941,80 +1856,78 @@ def test12(self): instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.z_boundary_conditions = ("periodic", "periodic") - - instance.grid.rho = 1.0 | generic_unit_system.density - self.assertAlmostEqual(instance.grid.rho, - numpy.ones((2,2,2)) | generic_unit_system.density) - + + instance.grid.rho = 1.0 | generic_unit_system.density + self.assertAlmostEqual(instance.grid.rho, + numpy.ones((2, 2, 2)) | generic_unit_system.density) + instance.grid.momentum = numpy.reshape( - numpy.arange(0.0, 3.0, 0.125), (2,2,2,3)) | generic_unit_system.momentum_density - self.assertAlmostEqual(instance.grid.rhovx, - numpy.reshape(numpy.arange(0.000, 3.0, 0.375), (2,2,2)) | generic_unit_system.momentum_density) - self.assertAlmostEqual(instance.grid.rhovy, - numpy.reshape(numpy.arange(0.125, 3.0, 0.375), (2,2,2)) | generic_unit_system.momentum_density) - self.assertAlmostEqual(instance.grid.rhovz, - numpy.reshape(numpy.arange(0.250, 3.0, 0.375), (2,2,2)) | generic_unit_system.momentum_density) - + numpy.arange(0.0, 3.0, 0.125), (2, 2, 2, 3)) | generic_unit_system.momentum_density + self.assertAlmostEqual(instance.grid.rhovx, + numpy.reshape(numpy.arange(0.000, 3.0, 0.375), (2, 2, 2)) | generic_unit_system.momentum_density) + self.assertAlmostEqual(instance.grid.rhovy, + numpy.reshape(numpy.arange(0.125, 3.0, 0.375), (2, 2, 2)) | generic_unit_system.momentum_density) + self.assertAlmostEqual(instance.grid.rhovz, + numpy.reshape(numpy.arange(0.250, 3.0, 0.375), (2, 2, 2)) | generic_unit_system.momentum_density) + momentum = instance.grid.momentum rhovx = -momentum.x rhovy = 2 * momentum.z rhovz = -0.5 * momentum.y - instance.grid.momentum = VectorQuantity.new_from_scalar_quantities(rhovx,rhovy,rhovz).transpose(axes=(1,2,3,0)) - self.assertAlmostEqual(instance.grid.rhovx, - numpy.reshape(numpy.arange(0.000, -3.0, -0.375), (2,2,2)) | generic_unit_system.momentum_density) - self.assertAlmostEqual(instance.grid.rhovy, - numpy.reshape(numpy.arange(0.5, 6.0, 0.75), (2,2,2)) | generic_unit_system.momentum_density) - self.assertAlmostEqual(instance.grid.rhovz, - numpy.reshape(numpy.arange(-0.0625, -1.5, -0.1875), (2,2,2)) | generic_unit_system.momentum_density) - - instance.grid[...,0,...].momentum = [12.0, 13.0, 14.0] | generic_unit_system.momentum_density - self.assertAlmostEqual(instance.grid[0,...].rhovx, + instance.grid.momentum = VectorQuantity.new_from_scalar_quantities(rhovx, rhovy, rhovz).transpose(axes=(1, 2, 3, 0)) + self.assertAlmostEqual(instance.grid.rhovx, + numpy.reshape(numpy.arange(0.000, -3.0, -0.375), (2, 2, 2)) | generic_unit_system.momentum_density) + self.assertAlmostEqual(instance.grid.rhovy, + numpy.reshape(numpy.arange(0.5, 6.0, 0.75), (2, 2, 2)) | generic_unit_system.momentum_density) + self.assertAlmostEqual(instance.grid.rhovz, + numpy.reshape(numpy.arange(-0.0625, -1.5, -0.1875), (2, 2, 2)) | generic_unit_system.momentum_density) + + instance.grid[..., 0, ...].momentum = [12.0, 13.0, 14.0] | generic_unit_system.momentum_density + self.assertAlmostEqual(instance.grid[0, ...].rhovx, [[12.0, 12.0], [-0.75, -1.125]] | generic_unit_system.momentum_density) - self.assertAlmostEqual(instance.grid[0,...].rhovy, + self.assertAlmostEqual(instance.grid[0, ...].rhovy, [[13.0, 13.0], [2.0, 2.75]] | generic_unit_system.momentum_density) - self.assertAlmostEqual(instance.grid[...,0].rhovz, + self.assertAlmostEqual(instance.grid[..., 0].rhovz, [[14.0, -0.4375], [14.0, -1.1875]] | generic_unit_system.momentum_density) - - instance.grid.energy = numpy.reshape(numpy.arange(0.0, 1.0, 0.125), (2,2,2)) | generic_unit_system.energy_density - self.assertAlmostEqual(instance.grid[...,0,0].energy, + + instance.grid.energy = numpy.reshape(numpy.arange(0.0, 1.0, 0.125), (2, 2, 2)) | generic_unit_system.energy_density + self.assertAlmostEqual(instance.grid[..., 0, 0].energy, [0.0, 0.5] | generic_unit_system.energy_density) - self.assertAlmostEqual(instance.grid[0,...,0].energy, + self.assertAlmostEqual(instance.grid[0, ..., 0].energy, [0.0, 0.25] | generic_unit_system.energy_density) - self.assertAlmostEqual(instance.grid[0,0,...].energy, + self.assertAlmostEqual(instance.grid[0, 0, ...].energy, [0.0, 0.125] | generic_unit_system.energy_density) instance.initialize_grid() instance.stop() - - - def test13(self): + + def test13(self): converter = generic_unit_converter.ConvertBetweenGenericAndSiUnits( 1 | units.parsec, 1 | units.Myr, 1 | units.MSun ) - instance=self.new_instance(Athena, unit_converter = converter) + instance = self.new_instance(Athena, unit_converter=converter) instance.set_gamma(1.6666666666666667) instance.set_courant_friedrichs_lewy_number(0.3) - - instance.parameters.mesh_size = (10 , 20, 40) + + instance.parameters.mesh_size = (10, 20, 40) instance.parameters.mesh_length = [1.0, 1.0, 1.0] | units.parsec instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.z_boundary_conditions = ("periodic", "periodic") - - + density = units.MSun / (units.parsec ** 3) - momentum = units.MSun / (units.Myr * units.parsec ** 2 ) - energy = units.MSun / (units.parsec * units.Myr ** 2) - - grid = datamodel.new_regular_grid((10,20,40), [1.0, 1.0, 1.0] | units.parsec ) - + momentum = units.MSun / (units.Myr * units.parsec ** 2) + energy = units.MSun / (units.parsec * units.Myr ** 2) + + grid = datamodel.new_regular_grid((10, 20, 40), [1.0, 1.0, 1.0] | units.parsec) + grid.rho = 0.4 | density grid.rhovx = 0.1 | momentum grid.rhovy = 0.2 | momentum grid.rhovz = 0.3 | momentum grid.energy = 0.5 | energy - + channel = grid.new_channel_to(instance.grid) channel.copy() print(instance.grid[0].rho) @@ -2024,476 +1937,456 @@ def test13(self): self.assertAlmostRelativeEquals(instance.grid[0].rhovz, 0.3 | momentum) self.assertAlmostRelativeEquals(instance.grid[0].energy, 0.5 | energy) self.assertEqual(instance.grid.rho.number.ndim, 3) - + self.assertEqual(len(list(instance.itergrids())), 1) - + instance.stop() - - def test14(self): - instance=self.new_instance(Athena) - instance.parameters.mesh_size = (10 , 1, 1) + def test14(self): + instance = self.new_instance(Athena) + instance.parameters.mesh_size = (10, 1, 1) instance.parameters.mesh_length = [1.0, 1.0, 1.0] | generic_unit_system.length instance.parameters.x_boundary_conditions = ("interface", "outflow") instance.parameters.stopping_conditions_number_of_steps = 1 - - - grid = datamodel.new_regular_grid((10,1,1), [1.0, 1.0, 1.0] | generic_unit_system.length ) - + + grid = datamodel.new_regular_grid((10, 1, 1), [1.0, 1.0, 1.0] | generic_unit_system.length) + density = generic_unit_system.density - momentum = generic_unit_system.speed * generic_unit_system.density - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - - + momentum = generic_unit_system.speed * generic_unit_system.density + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + grid.rho = 0.01 | density grid.rhovx = 0.1 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum - + p = 1.0 | (generic_unit_system.mass / (generic_unit_system.length * generic_unit_system.time**2)) - - grid.energy = p / (instance.parameters.gamma - 1) - grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho - + + grid.energy = p / (instance.parameters.gamma - 1) + grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho + channel = grid.new_channel_to(instance.grid) channel.copy() instance.stopping_conditions.number_of_steps_detection.enable() - - #instance.grid.boundaries.left. + + # instance.grid.boundaries.left. xbound1 = instance.get_boundary_grid('xbound1') - self.assertEqual(xbound1.shape, (4,1,1)) + self.assertEqual(xbound1.shape, (4, 1, 1)) memxbound1 = xbound1.copy() memxbound1.rho = 0.02 | density memxbound1.rhovx = 0.2 | momentum memxbound1.rhovy = 0.0 | momentum memxbound1.rhovz = 0.0 | momentum - memxbound1.energy = p / (instance.parameters.gamma - 1) - memxbound1.energy += 0.5 * (memxbound1.rhovx ** 2 + memxbound1.rhovy ** 2 + memxbound1.rhovz ** 2) / memxbound1.rho + memxbound1.energy = p / (instance.parameters.gamma - 1) + memxbound1.energy += 0.5 * (memxbound1.rhovx ** 2 + memxbound1.rhovy ** 2 + memxbound1.rhovz ** 2) / memxbound1.rho channel = memxbound1.new_channel_to(xbound1) channel.copy() - + instance.evolve_model(1.0 | generic_unit_system.time) print(instance.stopping_conditions.number_of_steps_detection.is_set()) - rho = instance.grid.rho[...,0,0] + rho = instance.grid.rho[..., 0, 0] self.assertAlmostRelativeEquals(rho[-1], 0.01 | density) self.assertTrue(rho[0] > 0.01 | density) - self.assertTrue(instance.grid.rhovx[0,0,0] > 0.1 | momentum) - self.assertAlmostRelativeEquals(instance.grid.rhovx[-1,0,0] , 0.1 | momentum) + self.assertTrue(instance.grid.rhovx[0, 0, 0] > 0.1 | momentum) + self.assertAlmostRelativeEquals(instance.grid.rhovx[-1, 0, 0], 0.1 | momentum) print(instance.model_time) - + instance.stopping_conditions.number_of_steps_detection.disable() instance.evolve_model(1.0 | generic_unit_system.time) - rho = instance.grid.rho[...,0,0] + rho = instance.grid.rho[..., 0, 0] self.assertAlmostRelativeEquals(rho, 0.02 | density, 8) - self.assertAlmostRelativeEquals(instance.grid.rhovx[...,0,0], 0.2 | momentum, 8) + self.assertAlmostRelativeEquals(instance.grid.rhovx[..., 0, 0], 0.2 | momentum, 8) print(instance.model_time) - + instance.stop() - + def test15(self): - instance=self.new_instance(Athena) + instance = self.new_instance(Athena) instance.initialize_code() instance.stop() - - def test16(self): - instance=self.new_instance(Athena) - instance.parameters.mesh_size = (10 , 1, 1) + + def test16(self): + instance = self.new_instance(Athena) + instance.parameters.mesh_size = (10, 1, 1) instance.parameters.mesh_length = [1.0, 1.0, 1.0] | generic_unit_system.length instance.parameters.x_boundary_conditions = ("outflow", "interface") instance.parameters.stopping_conditions_number_of_steps = 1 - - - grid = datamodel.new_regular_grid((10,1,1), [1.0, 1.0, 1.0] | generic_unit_system.length ) - + + grid = datamodel.new_regular_grid((10, 1, 1), [1.0, 1.0, 1.0] | generic_unit_system.length) + density = generic_unit_system.density - momentum = generic_unit_system.speed * generic_unit_system.density - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - - + momentum = generic_unit_system.speed * generic_unit_system.density + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + grid.rho = 0.01 | density grid.rhovx = -0.1 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum - + p = 1.0 | (generic_unit_system.mass / (generic_unit_system.length * generic_unit_system.time**2)) - - grid.energy = p / (instance.parameters.gamma - 1) - grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho - + + grid.energy = p / (instance.parameters.gamma - 1) + grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho + channel = grid.new_channel_to(instance.grid) channel.copy() instance.stopping_conditions.number_of_steps_detection.enable() - - #instance.grid.boundaries.left. + + # instance.grid.boundaries.left. xbound = instance.get_boundary_grid('xbound2') - self.assertEqual(xbound.shape, (4,1,1)) + self.assertEqual(xbound.shape, (4, 1, 1)) memxbound = xbound.copy() memxbound.rho = 0.02 | density memxbound.rhovx = -0.2 | momentum memxbound.rhovy = 0.0 | momentum memxbound.rhovz = 0.0 | momentum - memxbound.energy = p / (instance.parameters.gamma - 1) - memxbound.energy += 0.5 * (memxbound.rhovx ** 2 + memxbound.rhovy ** 2 + memxbound.rhovz ** 2) / memxbound.rho + memxbound.energy = p / (instance.parameters.gamma - 1) + memxbound.energy += 0.5 * (memxbound.rhovx ** 2 + memxbound.rhovy ** 2 + memxbound.rhovz ** 2) / memxbound.rho channel = memxbound.new_channel_to(xbound) channel.copy() - + instance.evolve_model(1.0 | generic_unit_system.time) print(instance.stopping_conditions.number_of_steps_detection.is_set()) - rho = instance.grid.rho[...,0,0] + rho = instance.grid.rho[..., 0, 0] self.assertAlmostRelativeEquals(rho[0], 0.01 | density) self.assertTrue(rho[-1] > 0.01 | density) - self.assertTrue(instance.grid.rhovx[-1,0,0] < -0.1 | momentum) - self.assertAlmostRelativeEquals(instance.grid.rhovx[0,0,0] , -0.1 | momentum) + self.assertTrue(instance.grid.rhovx[-1, 0, 0] < -0.1 | momentum) + self.assertAlmostRelativeEquals(instance.grid.rhovx[0, 0, 0], -0.1 | momentum) print(instance.model_time) - + instance.stopping_conditions.number_of_steps_detection.disable() instance.evolve_model(1.0 | generic_unit_system.time) - rho = instance.grid.rho[...,0,0] + rho = instance.grid.rho[..., 0, 0] self.assertAlmostRelativeEquals(rho, 0.02 | density, 8) - self.assertAlmostRelativeEquals(instance.grid.rhovx[...,0,0], -0.2 | momentum, 8) + self.assertAlmostRelativeEquals(instance.grid.rhovx[..., 0, 0], -0.2 | momentum, 8) print(instance.model_time) - + instance.stop() - - - def test17(self): - instance=self.new_instance(Athena, number_of_workers = 2) - instance.set_parallel_decomposition(1,2,1) - instance.parameters.mesh_size = (10,4,1) + + def test17(self): + instance = self.new_instance(Athena, number_of_workers=2) + instance.set_parallel_decomposition(1, 2, 1) + instance.parameters.mesh_size = (10, 4, 1) instance.parameters.mesh_length = [1.0, 1.0, 1.0] | generic_unit_system.length instance.parameters.x_boundary_conditions = ("interface", "outflow") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.stopping_conditions_number_of_steps = 1 - - - grid = datamodel.new_regular_grid((10,4,1), [1.0, 1.0, 1.0] | generic_unit_system.length ) - + + grid = datamodel.new_regular_grid((10, 4, 1), [1.0, 1.0, 1.0] | generic_unit_system.length) + density = generic_unit_system.density - momentum = generic_unit_system.speed * generic_unit_system.density - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - - + momentum = generic_unit_system.speed * generic_unit_system.density + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + grid.rho = 0.01 | density grid.rhovx = 0.1 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum - + p = 1.0 | (generic_unit_system.mass / (generic_unit_system.length * generic_unit_system.time**2)) - - grid.energy = p / (instance.parameters.gamma - 1) - grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho - + + grid.energy = p / (instance.parameters.gamma - 1) + grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho + channel = grid.new_channel_to(instance.grid) channel.copy() instance.stopping_conditions.number_of_steps_detection.enable() - + xbound = instance.get_boundary_grid('xbound1') - self.assertEqual(xbound.shape, (4,4,1)) + self.assertEqual(xbound.shape, (4, 4, 1)) memxbound = xbound.copy() memxbound.rho = 0.02 | density memxbound.rhovx = 0.2 | momentum memxbound.rhovy = 0.0 | momentum memxbound.rhovz = 0.0 | momentum - memxbound.energy = p / (instance.parameters.gamma - 1) - memxbound.energy += 0.5 * (memxbound.rhovx ** 2 + memxbound.rhovy ** 2 + memxbound.rhovz ** 2) / memxbound.rho + memxbound.energy = p / (instance.parameters.gamma - 1) + memxbound.energy += 0.5 * (memxbound.rhovx ** 2 + memxbound.rhovy ** 2 + memxbound.rhovz ** 2) / memxbound.rho channel = memxbound.new_channel_to(xbound) channel.copy() - + instance.evolve_model(1.0 | generic_unit_system.time) print(instance.stopping_conditions.number_of_steps_detection.is_set()) print(instance.grid.rho) - rho = instance.grid.rho[...,0,0] + rho = instance.grid.rho[..., 0, 0] self.assertAlmostRelativeEquals(rho[-1], 0.01 | density) self.assertTrue(rho[0] > 0.01 | density) - self.assertTrue(instance.grid.rhovx[0,0,0] > 0.1 | momentum) - self.assertAlmostRelativeEquals(instance.grid.rhovx[-1,0,0] , 0.1 | momentum) + self.assertTrue(instance.grid.rhovx[0, 0, 0] > 0.1 | momentum) + self.assertAlmostRelativeEquals(instance.grid.rhovx[-1, 0, 0], 0.1 | momentum) print(instance.model_time) - + instance.stopping_conditions.number_of_steps_detection.disable() instance.evolve_model(1.0 | generic_unit_system.time) - rho = instance.grid.rho[...,0,0] + rho = instance.grid.rho[..., 0, 0] self.assertAlmostRelativeEquals(rho, 0.02 | density, 8) - self.assertAlmostRelativeEquals(instance.grid.rhovx[...,0,0], 0.2 | momentum, 8) + self.assertAlmostRelativeEquals(instance.grid.rhovx[..., 0, 0], 0.2 | momentum, 8) print(instance.model_time) - + instance.stop() - - def test18(self): - instance=self.new_instance(Athena, number_of_workers = 2) - instance.set_parallel_decomposition(2,1,1) - instance.parameters.mesh_size = (4,10,1) + def test18(self): + instance = self.new_instance(Athena, number_of_workers=2) + instance.set_parallel_decomposition(2, 1, 1) + instance.parameters.mesh_size = (4, 10, 1) instance.parameters.mesh_length = [1.0, 1.0, 1.0] | generic_unit_system.length instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.y_boundary_conditions = ("interface", "outflow") instance.parameters.stopping_conditions_number_of_steps = 1 - - - grid = datamodel.new_regular_grid((4,10,1), [1.0, 1.0, 1.0] | generic_unit_system.length ) - + + grid = datamodel.new_regular_grid((4, 10, 1), [1.0, 1.0, 1.0] | generic_unit_system.length) + density = generic_unit_system.density - momentum = generic_unit_system.speed * generic_unit_system.density - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - - + momentum = generic_unit_system.speed * generic_unit_system.density + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + grid.rho = 0.01 | density grid.rhovx = 0.0 | momentum grid.rhovy = 0.1 | momentum grid.rhovz = 0.0 | momentum - + p = 1.0 | (generic_unit_system.mass / (generic_unit_system.length * generic_unit_system.time**2)) - - grid.energy = p / (instance.parameters.gamma - 1) - grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho - + + grid.energy = p / (instance.parameters.gamma - 1) + grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho + channel = grid.new_channel_to(instance.grid) channel.copy() instance.stopping_conditions.number_of_steps_detection.enable() - + ybound = instance.get_boundary_grid('ybound1') - self.assertEqual(ybound.shape, (4+8,4,1)) + self.assertEqual(ybound.shape, (4+8, 4, 1)) memybound = ybound.copy() memybound.rho = 0.02 | density memybound.rhovx = 0.0 | momentum memybound.rhovy = 0.2 | momentum memybound.rhovz = 0.0 | momentum - memybound.energy = p / (instance.parameters.gamma - 1) - memybound.energy += 0.5 * (memybound.rhovx ** 2 + memybound.rhovy ** 2 + memybound.rhovz ** 2) / memybound.rho - + memybound.energy = p / (instance.parameters.gamma - 1) + memybound.energy += 0.5 * (memybound.rhovx ** 2 + memybound.rhovy ** 2 + memybound.rhovz ** 2) / memybound.rho + channel = memybound.new_channel_to(ybound) channel.copy() - + instance.evolve_model(1.0 | generic_unit_system.time) print(instance.stopping_conditions.number_of_steps_detection.is_set()) print(instance.grid.rho) - rho = instance.grid.rho[0,...,0] + rho = instance.grid.rho[0, ..., 0] self.assertAlmostRelativeEquals(rho[-1], 0.01 | density) self.assertTrue(rho[0] > 0.01 | density) - self.assertTrue(instance.grid.rhovy[0,0,0] > 0.1 | momentum) - self.assertAlmostRelativeEquals(instance.grid.rhovy[0,-1,0] , 0.1 | momentum) + self.assertTrue(instance.grid.rhovy[0, 0, 0] > 0.1 | momentum) + self.assertAlmostRelativeEquals(instance.grid.rhovy[0, -1, 0], 0.1 | momentum) print(instance.model_time) - + instance.stopping_conditions.number_of_steps_detection.disable() instance.evolve_model(1.0 | generic_unit_system.time) - rho = instance.grid.rho[0,...,0] + rho = instance.grid.rho[0, ..., 0] self.assertAlmostRelativeEquals(rho, 0.02 | density, 8) - self.assertAlmostRelativeEquals(instance.grid.rhovy[0,...,0], 0.2 | momentum, 8) + self.assertAlmostRelativeEquals(instance.grid.rhovy[0, ..., 0], 0.2 | momentum, 8) print(instance.model_time) - + instance.stop() - - - def test19(self): - instance=self.new_instance(Athena, number_of_workers = 1) - instance.set_parallel_decomposition(1,1,1) - instance.parameters.mesh_size = (4,5,6) + + def test19(self): + instance = self.new_instance(Athena, number_of_workers=1) + instance.set_parallel_decomposition(1, 1, 1) + instance.parameters.mesh_size = (4, 5, 6) instance.parameters.mesh_length = [1.0, 1.0, 1.0] | generic_unit_system.length instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.z_boundary_conditions = ("interface", "outflow") instance.parameters.stopping_conditions_number_of_steps = 1 - - - grid = datamodel.new_regular_grid((4,5,6), [1.0, 1.0, 1.0] | generic_unit_system.length ) - + + grid = datamodel.new_regular_grid((4, 5, 6), [1.0, 1.0, 1.0] | generic_unit_system.length) + density = generic_unit_system.density - momentum = generic_unit_system.speed * generic_unit_system.density - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - - + momentum = generic_unit_system.speed * generic_unit_system.density + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + grid.rho = 0.01 | density grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.1 | momentum - + p = 1.0 | (generic_unit_system.mass / (generic_unit_system.length * generic_unit_system.time**2)) - - grid.energy = p / (instance.parameters.gamma - 1) - grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho - + + grid.energy = p / (instance.parameters.gamma - 1) + grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho + channel = grid.new_channel_to(instance.grid) channel.copy() instance.stopping_conditions.number_of_steps_detection.enable() - + zbound = instance.get_boundary_grid('zbound1') - self.assertEqual(zbound.shape, (4+8,5+8,4)) + self.assertEqual(zbound.shape, (4+8, 5+8, 4)) memzbound = zbound.copy() memzbound.rho = 0.02 | density memzbound.rhovx = 0.0 | momentum memzbound.rhovy = 0.0 | momentum memzbound.rhovz = 0.2 | momentum - memzbound.energy = p / (instance.parameters.gamma - 1) - memzbound.energy += 0.5 * (memzbound.rhovx ** 2 + memzbound.rhovy ** 2 + memzbound.rhovz ** 2) / memzbound.rho - + memzbound.energy = p / (instance.parameters.gamma - 1) + memzbound.energy += 0.5 * (memzbound.rhovx ** 2 + memzbound.rhovy ** 2 + memzbound.rhovz ** 2) / memzbound.rho + channel = memzbound.new_channel_to(zbound) channel.copy() - + instance.evolve_model(1.0 | generic_unit_system.time) - rho = instance.grid.rho[0,0,...] + rho = instance.grid.rho[0, 0, ...] self.assertAlmostRelativeEquals(rho[-1], 0.01 | density) self.assertTrue(rho[0] > 0.01 | density) - self.assertTrue(instance.grid.rhovz[0,0,0] > 0.1 | momentum) - self.assertAlmostRelativeEquals(instance.grid.rhovz[0,0,-1] , 0.1 | momentum) + self.assertTrue(instance.grid.rhovz[0, 0, 0] > 0.1 | momentum) + self.assertAlmostRelativeEquals(instance.grid.rhovz[0, 0, -1], 0.1 | momentum) print(instance.model_time) - + instance.stopping_conditions.number_of_steps_detection.disable() instance.evolve_model(1.0 | generic_unit_system.time) - rho = instance.grid.rho[0,...,0] + rho = instance.grid.rho[0, ..., 0] self.assertAlmostRelativeEquals(rho, 0.02 | density, 8) - self.assertAlmostRelativeEquals(instance.grid.rhovz[0,0,...], 0.2 | momentum, 8) + self.assertAlmostRelativeEquals(instance.grid.rhovz[0, 0, ...], 0.2 | momentum, 8) print(instance.model_time) - + instance.stop() - - - def test20(self): - instance=self.new_instance(Athena, number_of_workers = 4) - instance.parameters.parallel_decomposition = (2,2,1) - instance.parameters.mesh_size = (4,5,6) + + def test20(self): + instance = self.new_instance(Athena, number_of_workers=4) + instance.parameters.parallel_decomposition = (2, 2, 1) + instance.parameters.mesh_size = (4, 5, 6) instance.parameters.mesh_length = [1.0, 1.0, 1.0] | generic_unit_system.length instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.z_boundary_conditions = ("outflow", "interface") instance.parameters.stopping_conditions_number_of_steps = 1 - - - grid = datamodel.new_regular_grid((4,5,6), [1.0, 1.0, 1.0] | generic_unit_system.length ) - + + grid = datamodel.new_regular_grid((4, 5, 6), [1.0, 1.0, 1.0] | generic_unit_system.length) + density = generic_unit_system.density - momentum = generic_unit_system.speed * generic_unit_system.density - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - - + momentum = generic_unit_system.speed * generic_unit_system.density + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + grid.rho = 0.01 | density grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = -0.1 | momentum - + p = 1.0 | (generic_unit_system.mass / (generic_unit_system.length * generic_unit_system.time**2)) - - grid.energy = p / (instance.parameters.gamma - 1) - grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho - + + grid.energy = p / (instance.parameters.gamma - 1) + grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho + channel = grid.new_channel_to(instance.grid) channel.copy() instance.stopping_conditions.number_of_steps_detection.enable() - + zbound = instance.get_boundary_grid('zbound2') - self.assertEqual(zbound.shape, (4+8,5+8,4)) + self.assertEqual(zbound.shape, (4+8, 5+8, 4)) memzbound = zbound.copy() memzbound.rho = 0.02 | density memzbound.rhovx = 0.0 | momentum memzbound.rhovy = 0.0 | momentum memzbound.rhovz = -0.2 | momentum - memzbound.energy = p / (instance.parameters.gamma - 1) - memzbound.energy += 0.5 * (memzbound.rhovx ** 2 + memzbound.rhovy ** 2 + memzbound.rhovz ** 2) / memzbound.rho - + memzbound.energy = p / (instance.parameters.gamma - 1) + memzbound.energy += 0.5 * (memzbound.rhovx ** 2 + memzbound.rhovy ** 2 + memzbound.rhovz ** 2) / memzbound.rho + channel = memzbound.new_channel_to(zbound) channel.copy() - + instance.evolve_model(1.0 | generic_unit_system.time) - rho = instance.grid.rho[0,0,...] + rho = instance.grid.rho[0, 0, ...] self.assertAlmostRelativeEquals(rho[0], 0.01 | density) self.assertTrue(rho[-1] > 0.01 | density) - self.assertTrue(instance.grid.rhovz[0,0,-1] < -0.1 | momentum) - self.assertAlmostRelativeEquals(instance.grid.rhovz[0,0,0] , -0.1 | momentum) + self.assertTrue(instance.grid.rhovz[0, 0, -1] < -0.1 | momentum) + self.assertAlmostRelativeEquals(instance.grid.rhovz[0, 0, 0], -0.1 | momentum) print(instance.model_time) - + instance.stopping_conditions.number_of_steps_detection.disable() instance.evolve_model(1.0 | generic_unit_system.time) - rho = instance.grid.rho[0,...,0] + rho = instance.grid.rho[0, ..., 0] self.assertAlmostRelativeEquals(rho, 0.02 | density, 8) - self.assertAlmostRelativeEquals(instance.grid.rhovz[0,0,...], -0.2 | momentum, 8) + self.assertAlmostRelativeEquals(instance.grid.rhovz[0, 0, ...], -0.2 | momentum, 8) print(instance.model_time) - + instance.stop() - - + def test21(self): - - instance=self.new_instance(Athena) - instance.parameters.x_boundary_conditions = ("periodic","periodic") + + instance = self.new_instance(Athena) + instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.mesh_length = (20.0, 1, 1) | generic_unit_system.length instance.parameters.mesh_size = (20, 1, 1) - + for x in instance.itergrids(): inmem = x.copy() - inmem.rho = inmem.x/(1| generic_unit_system.length) | generic_unit_system.density + inmem.rho = inmem.x/(1 | generic_unit_system.length) | generic_unit_system.density inmem.rhovx = 0.0 | generic_unit_system.momentum_density - inmem.energy = 1.0 | generic_unit_system.energy_density + inmem.energy = 1.0 | generic_unit_system.energy_density from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() print(inmem.rho) - rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5| generic_unit_system.length,0.0| generic_unit_system.length,0.0| generic_unit_system.length) - - self.assertEqual(rho , 0.5 | generic_unit_system.density) - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5 | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length) + + self.assertEqual(rho, 0.5 | generic_unit_system.density) + for value in numpy.arange(0.5, 19.6, 0.1): - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( value | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length ) - - self.assertAlmostRelativeEquals(rho , value | generic_unit_system.density) - + + self.assertAlmostRelativeEquals(rho, value | generic_unit_system.density) + for value in numpy.arange(0.0, 0.6, 0.1): rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( value | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length ) - self.assertAlmostRelativeEquals(rho , ((0.5 + value) * 0.5 + (0.5-value) * 19.5) | generic_unit_system.density) - - + self.assertAlmostRelativeEquals(rho, ((0.5 + value) * 0.5 + (0.5-value) * 19.5) | generic_unit_system.density) + for value in numpy.arange(0.0, 0.5, 0.1): rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( - value + 19.5| generic_unit_system.length, + value + 19.5 | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length ) - self.assertAlmostRelativeEquals(rho , (19.5 - (value * 19)) | generic_unit_system.density, 9) - + self.assertAlmostRelativeEquals(rho, (19.5 - (value * 19)) | generic_unit_system.density, 9) + # out of range rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( - 20.0| generic_unit_system.length, + 20.0 | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length ) - self.assertAlmostRelativeEquals(rho , 0.0 | generic_unit_system.density, 9) + self.assertAlmostRelativeEquals(rho, 0.0 | generic_unit_system.density, 9) - def test22(self): - - instance=self.new_instance(Athena, number_of_workers=2) - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") + + instance = self.new_instance(Athena, number_of_workers=2) + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.mesh_length = (20.0, 20.0, 1) | generic_unit_system.length instance.parameters.mesh_size = (20, 20, 1) - + for x in instance.itergrids(): inmem = x.copy() - inmem.rho = (inmem.x + ((inmem.y - (0.5| generic_unit_system.length))* 20.0))/(1| generic_unit_system.length) | generic_unit_system.density + inmem.rho = (inmem.x + ((inmem.y - (0.5 | generic_unit_system.length)) * 20.0))/(1 | generic_unit_system.length) | generic_unit_system.density inmem.rhovx = 0.0 | generic_unit_system.momentum_density - inmem.energy = 1.0 | generic_unit_system.energy_density + inmem.energy = 1.0 | generic_unit_system.energy_density from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() print(inmem.rho[0], inmem.y[0], inmem.x[0]) - rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5| generic_unit_system.length,0.5| generic_unit_system.length,0.0| generic_unit_system.length) - - self.assertEqual(rho , 0.5 | generic_unit_system.density) - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5 | generic_unit_system.length, 0.5 | generic_unit_system.length, 0.0 | generic_unit_system.length) + + self.assertEqual(rho, 0.5 | generic_unit_system.density) + for value in numpy.arange(0.5, 19.6, 0.1): - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( value | generic_unit_system.length, 0.5 | generic_unit_system.length, 0.0 | generic_unit_system.length ) - - self.assertAlmostRelativeEquals(rho , value | generic_unit_system.density) - + + self.assertAlmostRelativeEquals(rho, value | generic_unit_system.density) + for x in numpy.arange(8.5, 11.5, 0.25): for y in numpy.arange(0.5, 19.6, 0.25): rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( @@ -2501,47 +2394,47 @@ def test22(self): y | generic_unit_system.length, 0.0 | generic_unit_system.length ) - - self.assertAlmostRelativeEquals(rho , x + (20 * (y-0.5)) | generic_unit_system.density) - + + self.assertAlmostRelativeEquals(rho, x + (20 * (y-0.5)) | generic_unit_system.density) + def test23(self): - - instance=self.new_instance(Athena, number_of_workers=3) - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") - instance.parameters.z_boundary_conditions = ("periodic","periodic") + + instance = self.new_instance(Athena, number_of_workers=3) + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") + instance.parameters.z_boundary_conditions = ("periodic", "periodic") instance.parameters.mesh_length = (20.0, 20.0, 20.0) | generic_unit_system.length instance.parameters.mesh_length = (20.0, 20.0, 20.0) | generic_unit_system.length instance.parameters.mesh_size = (20, 20, 20) - + for x in instance.itergrids(): inmem = x.copy() inmem.rho = ( ( - inmem.x + - ((inmem.y - (0.5| generic_unit_system.length))* 20.0) + - ((inmem.z - (0.5| generic_unit_system.length))* 400.0) + inmem.x + + ((inmem.y - (0.5 | generic_unit_system.length)) * 20.0) + + ((inmem.z - (0.5 | generic_unit_system.length)) * 400.0) ) - /(1| generic_unit_system.length) | generic_unit_system.density + / (1 | generic_unit_system.length) | generic_unit_system.density ) inmem.rhovx = 0.0 | generic_unit_system.momentum_density - inmem.energy = 1.0 | generic_unit_system.energy_density + inmem.energy = 1.0 | generic_unit_system.energy_density from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() - rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5| generic_unit_system.length,0.5| generic_unit_system.length,0.5| generic_unit_system.length) - - self.assertEqual(rho , 0.5 | generic_unit_system.density) - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5 | generic_unit_system.length, 0.5 | generic_unit_system.length, 0.5 | generic_unit_system.length) + + self.assertEqual(rho, 0.5 | generic_unit_system.density) + for value in numpy.arange(0.5, 19.6, 0.1): - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( value | generic_unit_system.length, 0.5 | generic_unit_system.length, 0.5 | generic_unit_system.length ) - - self.assertAlmostRelativeEquals(rho , value | generic_unit_system.density) - + + self.assertAlmostRelativeEquals(rho, value | generic_unit_system.density) + sample = sample = datamodel.new_regular_grid( (4, 4, 76), (2, 2, 19) | generic_unit_system.length @@ -2552,63 +2445,60 @@ def test23(self): x = sample.x.flatten() y = sample.y.flatten() z = sample.z.flatten() - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( x, y, z ) half = 0.5 | generic_unit_system.length - - self.assertAlmostRelativeEquals(rho , (x + (20 * (y-half)) + (400 * (z-half)))/(1| generic_unit_system.length) | generic_unit_system.density ) - + + self.assertAlmostRelativeEquals(rho, (x + (20 * (y-half)) + (400 * (z-half)))/(1 | generic_unit_system.length) | generic_unit_system.density) def test24(self): - - instance=self.new_instance(Athena, number_of_workers=1) - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") - instance.parameters.z_boundary_conditions = ("periodic","periodic") + + instance = self.new_instance(Athena, number_of_workers=1) + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") + instance.parameters.z_boundary_conditions = ("periodic", "periodic") instance.parameters.mesh_length = (10.0, 1, 1) | generic_unit_system.length instance.parameters.mesh_size = (20, 1, 1) instance.set_has_external_gravitational_potential(1) instance.commit_parameters() potential_grid = instance.potential_grid - factor = (2 | generic_unit_system.length / generic_unit_system.time**2) + factor = (2 | generic_unit_system.length / generic_unit_system.time**2) potential_grid.potential = potential_grid.x * factor - - x = numpy.arange(0,10.25, 0.1) | generic_unit_system.length - y = 0.5 |generic_unit_system.length - z = 0.5 |generic_unit_system.length - interpolated = instance.get_interpolated_gravitational_potential(x,y,z) + + x = numpy.arange(0, 10.25, 0.1) | generic_unit_system.length + y = 0.5 | generic_unit_system.length + z = 0.5 | generic_unit_system.length + interpolated = instance.get_interpolated_gravitational_potential(x, y, z) self.assertAlmostRelativeEquals(interpolated, x * factor) - - + def test25(self): - - instance=self.new_instance(Athena, number_of_workers=1) - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") - instance.parameters.z_boundary_conditions = ("periodic","periodic") + + instance = self.new_instance(Athena, number_of_workers=1) + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") + instance.parameters.z_boundary_conditions = ("periodic", "periodic") instance.parameters.mesh_length = (5.0, 10.0, 1) | generic_unit_system.length instance.parameters.mesh_size = (20, 20, 1) instance.set_has_external_gravitational_potential(1) instance.commit_parameters() potential_grid = instance.potential_grid - factor = (2 | generic_unit_system.length / generic_unit_system.time**2) + factor = (2 | generic_unit_system.length / generic_unit_system.time**2) potential_grid.potential = potential_grid.y * factor print(potential_grid.y * factor) - y = numpy.arange(0,10.25, 0.1) | generic_unit_system.length - x = (y * 0) + (2 |generic_unit_system.length) - z = 0.5 |generic_unit_system.length - interpolated = instance.get_interpolated_gravitational_potential(x,y,z) + y = numpy.arange(0, 10.25, 0.1) | generic_unit_system.length + x = (y * 0) + (2 | generic_unit_system.length) + z = 0.5 | generic_unit_system.length + interpolated = instance.get_interpolated_gravitational_potential(x, y, z) print(y*factor) self.assertAlmostRelativeEquals(interpolated, y * factor) - - + def test26(self): n = 4 - instance=self.new_instance(Athena) + instance = self.new_instance(Athena) instance.set_gamma(1.6666666666666667) instance.set_courant_friedrichs_lewy_number(0.3) instance.parameters.nx = n @@ -2617,61 +2507,60 @@ def test26(self): instance.parameters.length_x = n | generic_unit_system.length instance.parameters.length_y = n | generic_unit_system.length instance.parameters.length_z = n | generic_unit_system.length - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") - instance.parameters.z_boundary_conditions = ("periodic","periodic") + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") + instance.parameters.z_boundary_conditions = ("periodic", "periodic") instance.set_has_external_gravitational_potential(1) instance.commit_parameters() - + density = generic_unit_system.mass / (generic_unit_system.length ** 3) - momentum = generic_unit_system.mass / (generic_unit_system.time * (generic_unit_system.length**2)) - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - + momentum = generic_unit_system.mass / (generic_unit_system.time * (generic_unit_system.length**2)) + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + potential_grid = datamodel.Grid(n + 2, n + 2, n + 2) potential_grid.potential = 0.0 | generic_unit_system.potential x = instance.potential_grid.x y = instance.potential_grid.y z = instance.potential_grid.z - potential_grid.potential = (1 | generic_unit_system.potential) * ( (x + y + z) / (1 | generic_unit_system.length)) + potential_grid.potential = (1 | generic_unit_system.potential) * ((x + y + z) / (1 | generic_unit_system.length)) channel = potential_grid.new_channel_to(instance.potential_grid) channel.copy() result = instance.initialize_grid() - print(x[...,0,0]) - print(instance.grid.x[...,0,0]) - print(instance.potential_grid.potential[...,0,0]) - print(potential_grid.potential[...,0,0]) - self.assertAlmostRelativeEquals(potential_grid.potential[...,0,0], instance.potential_grid.potential[...,0,0]) - interpolated_inside = instance.get_interpolated_gravitational_potential(x[0,0,0], y[0,0,0], z[0,0,0]) - interpolated_outside = instance.get_interpolated_gravitational_potential(x[0,0,0] - (1.0 |generic_unit_system.length), y[0,0,0], z[0,0,0]) + print(x[..., 0, 0]) + print(instance.grid.x[..., 0, 0]) + print(instance.potential_grid.potential[..., 0, 0]) + print(potential_grid.potential[..., 0, 0]) + self.assertAlmostRelativeEquals(potential_grid.potential[..., 0, 0], instance.potential_grid.potential[..., 0, 0]) + interpolated_inside = instance.get_interpolated_gravitational_potential(x[0, 0, 0], y[0, 0, 0], z[0, 0, 0]) + interpolated_outside = instance.get_interpolated_gravitational_potential(x[0, 0, 0] - (1.0 | generic_unit_system.length), y[0, 0, 0], z[0, 0, 0]) print(interpolated_inside, interpolated_outside) self.assertAlmostRelativeEquals(interpolated_inside, interpolated_outside) - interpolated_inside = instance.get_interpolated_gravitational_potential(x[0,0,0], y[0,0,0], z[0,0,0]) - interpolated_outside = instance.get_interpolated_gravitational_potential(x[0,0,0] , y[0,0,0] - (2.0 |generic_unit_system.length), z[0,0,0]) + interpolated_inside = instance.get_interpolated_gravitational_potential(x[0, 0, 0], y[0, 0, 0], z[0, 0, 0]) + interpolated_outside = instance.get_interpolated_gravitational_potential(x[0, 0, 0], y[0, 0, 0] - (2.0 | generic_unit_system.length), z[0, 0, 0]) print(interpolated_inside, interpolated_outside) self.assertAlmostRelativeEquals(interpolated_inside, interpolated_outside) - interpolated_inside = instance.get_interpolated_gravitational_potential(x[0,0,0], y[0,0,0], z[0,0,0]) - interpolated_outside = instance.get_interpolated_gravitational_potential(x[0,0,0] , y[0,0,0], z[0,0,0] - (2.0 |generic_unit_system.length)) + interpolated_inside = instance.get_interpolated_gravitational_potential(x[0, 0, 0], y[0, 0, 0], z[0, 0, 0]) + interpolated_outside = instance.get_interpolated_gravitational_potential(x[0, 0, 0], y[0, 0, 0], z[0, 0, 0] - (2.0 | generic_unit_system.length)) print(interpolated_inside, interpolated_outside) self.assertAlmostRelativeEquals(interpolated_inside, interpolated_outside) - interpolated_inside = instance.get_interpolated_gravitational_potential(x[5,0,0], y[0,0,0], z[0,0,0]) - interpolated_outside = instance.get_interpolated_gravitational_potential(x[5,0,0] + (2.0 |generic_unit_system.length), y[0,0,0], z[0,0,0]) + interpolated_inside = instance.get_interpolated_gravitational_potential(x[5, 0, 0], y[0, 0, 0], z[0, 0, 0]) + interpolated_outside = instance.get_interpolated_gravitational_potential(x[5, 0, 0] + (2.0 | generic_unit_system.length), y[0, 0, 0], z[0, 0, 0]) print(interpolated_inside, interpolated_outside) self.assertAlmostRelativeEquals(interpolated_inside, interpolated_outside) - interpolated_inside = instance.get_interpolated_gravitational_potential(x[5,0,0], y[0,5,0], z[0,0,0]) - interpolated_outside = instance.get_interpolated_gravitational_potential(x[5,0,0], y[0,5,0] + (2.0 |generic_unit_system.length), z[0,0,0]) + interpolated_inside = instance.get_interpolated_gravitational_potential(x[5, 0, 0], y[0, 5, 0], z[0, 0, 0]) + interpolated_outside = instance.get_interpolated_gravitational_potential(x[5, 0, 0], y[0, 5, 0] + (2.0 | generic_unit_system.length), z[0, 0, 0]) self.assertAlmostRelativeEquals(interpolated_inside, interpolated_outside) - interpolated_inside = instance.get_interpolated_gravitational_potential(x[5,0,0], y[0,5,0], z[0,0,5]) - interpolated_outside = instance.get_interpolated_gravitational_potential(x[5,0,0], y[0,5,0] , z[0,0,5] + (2.0 |generic_unit_system.length)) + interpolated_inside = instance.get_interpolated_gravitational_potential(x[5, 0, 0], y[0, 5, 0], z[0, 0, 5]) + interpolated_outside = instance.get_interpolated_gravitational_potential(x[5, 0, 0], y[0, 5, 0], z[0, 0, 5] + (2.0 | generic_unit_system.length)) self.assertAlmostRelativeEquals(interpolated_inside, interpolated_outside) - interpolated_inside = instance.get_interpolated_gravitational_potential(x[0,0,0], y[0,0,0], z[0,0,0]) - interpolated_outside = instance.get_interpolated_gravitational_potential(x[0,0,0] - (2.0 |generic_unit_system.length) , y[0,0,0] - (2.0 |generic_unit_system.length), z[0,0,0] - (2.0 |generic_unit_system.length)) + interpolated_inside = instance.get_interpolated_gravitational_potential(x[0, 0, 0], y[0, 0, 0], z[0, 0, 0]) + interpolated_outside = instance.get_interpolated_gravitational_potential(x[0, 0, 0] - (2.0 | generic_unit_system.length), y[0, 0, 0] - (2.0 | generic_unit_system.length), z[0, 0, 0] - (2.0 | generic_unit_system.length)) print(interpolated_inside, interpolated_outside) - - + def test27(self): n = 4 - instance=self.new_instance(Athena) + instance = self.new_instance(Athena) instance.set_gamma(1.6666666666666667) instance.set_courant_friedrichs_lewy_number(0.3) instance.parameters.nx = n @@ -2680,49 +2569,49 @@ def test27(self): instance.parameters.length_x = n | generic_unit_system.length instance.parameters.length_y = n | generic_unit_system.length instance.parameters.length_z = 0 | generic_unit_system.length - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") - instance.parameters.z_boundary_conditions = ("periodic","periodic") + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") + instance.parameters.z_boundary_conditions = ("periodic", "periodic") instance.set_has_external_gravitational_potential(1) instance.commit_parameters() - + density = generic_unit_system.mass / (generic_unit_system.length ** 3) - momentum = generic_unit_system.mass / (generic_unit_system.time * (generic_unit_system.length**2)) - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - + momentum = generic_unit_system.mass / (generic_unit_system.time * (generic_unit_system.length**2)) + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + potential_grid = datamodel.Grid(n + 2, n + 2, 1) potential_grid.potential = 0.0 | generic_unit_system.potential x = instance.potential_grid.x y = instance.potential_grid.y z = instance.potential_grid.z - potential_grid.potential = (1 | generic_unit_system.potential) * ( (x + y) / (1 | generic_unit_system.length)) + potential_grid.potential = (1 | generic_unit_system.potential) * ((x + y) / (1 | generic_unit_system.length)) channel = potential_grid.new_channel_to(instance.potential_grid) channel.copy() result = instance.initialize_grid() - self.assertAlmostRelativeEquals(potential_grid.potential[...,0,0], instance.potential_grid.potential[...,0,0]) - interpolated_inside = instance.get_interpolated_gravitational_potential(x[0,0,0], y[0,0,0], z[0,0,0]) - interpolated_outside = instance.get_interpolated_gravitational_potential(x[0,0,0] - (1.0 |generic_unit_system.length), y[0,0,0], z[0,0,0]) + self.assertAlmostRelativeEquals(potential_grid.potential[..., 0, 0], instance.potential_grid.potential[..., 0, 0]) + interpolated_inside = instance.get_interpolated_gravitational_potential(x[0, 0, 0], y[0, 0, 0], z[0, 0, 0]) + interpolated_outside = instance.get_interpolated_gravitational_potential(x[0, 0, 0] - (1.0 | generic_unit_system.length), y[0, 0, 0], z[0, 0, 0]) print(interpolated_inside, interpolated_outside) self.assertAlmostRelativeEquals(interpolated_inside, interpolated_outside) - interpolated_inside = instance.get_interpolated_gravitational_potential(x[0,0,0], y[0,0,0], z[0,0,0]) - interpolated_outside = instance.get_interpolated_gravitational_potential(x[0,0,0] , y[0,0,0] - (2.0 |generic_unit_system.length), z[0,0,0]) + interpolated_inside = instance.get_interpolated_gravitational_potential(x[0, 0, 0], y[0, 0, 0], z[0, 0, 0]) + interpolated_outside = instance.get_interpolated_gravitational_potential(x[0, 0, 0], y[0, 0, 0] - (2.0 | generic_unit_system.length), z[0, 0, 0]) print(interpolated_inside, interpolated_outside) self.assertAlmostRelativeEquals(interpolated_inside, interpolated_outside) - interpolated_inside = instance.get_interpolated_gravitational_potential(x[5,0,0], y[0,0,0], z[0,0,0]) - interpolated_outside = instance.get_interpolated_gravitational_potential(x[5,0,0] + (2.0 |generic_unit_system.length), y[0,0,0], z[0,0,0]) + interpolated_inside = instance.get_interpolated_gravitational_potential(x[5, 0, 0], y[0, 0, 0], z[0, 0, 0]) + interpolated_outside = instance.get_interpolated_gravitational_potential(x[5, 0, 0] + (2.0 | generic_unit_system.length), y[0, 0, 0], z[0, 0, 0]) print(interpolated_inside, interpolated_outside) self.assertAlmostRelativeEquals(interpolated_inside, interpolated_outside) - interpolated_inside = instance.get_interpolated_gravitational_potential(x[5,0,0], y[0,5,0], z[0,0,0]) - interpolated_outside = instance.get_interpolated_gravitational_potential(x[5,0,0], y[0,5,0] + (2.0 |generic_unit_system.length), z[0,0,0]) + interpolated_inside = instance.get_interpolated_gravitational_potential(x[5, 0, 0], y[0, 5, 0], z[0, 0, 0]) + interpolated_outside = instance.get_interpolated_gravitational_potential(x[5, 0, 0], y[0, 5, 0] + (2.0 | generic_unit_system.length), z[0, 0, 0]) self.assertAlmostRelativeEquals(interpolated_inside, interpolated_outside) - interpolated_inside = instance.get_interpolated_gravitational_potential(x[0,0,0], y[0,0,0], z[0,0,0]) - interpolated_outside = instance.get_interpolated_gravitational_potential(x[0,0,0] - (2.0 |generic_unit_system.length) , y[0,0,0] - (2.0 |generic_unit_system.length), z[0,0,0]) + interpolated_inside = instance.get_interpolated_gravitational_potential(x[0, 0, 0], y[0, 0, 0], z[0, 0, 0]) + interpolated_outside = instance.get_interpolated_gravitational_potential(x[0, 0, 0] - (2.0 | generic_unit_system.length), y[0, 0, 0] - (2.0 | generic_unit_system.length), z[0, 0, 0]) print(interpolated_inside, interpolated_outside) def test28(self): n = 4 - instance=self.new_instance(Athena) + instance = self.new_instance(Athena) instance.set_gamma(1.6666666666666667) instance.set_courant_friedrichs_lewy_number(0.3) instance.parameters.nx = n @@ -2731,59 +2620,56 @@ def test28(self): instance.parameters.length_x = n | generic_unit_system.length instance.parameters.length_y = n | generic_unit_system.length instance.parameters.length_z = 0 | generic_unit_system.length - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") - instance.parameters.z_boundary_conditions = ("periodic","periodic") + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") + instance.parameters.z_boundary_conditions = ("periodic", "periodic") instance.set_has_external_gravitational_potential(1) instance.commit_parameters() - + density = generic_unit_system.mass / (generic_unit_system.length ** 3) - momentum = generic_unit_system.mass / (generic_unit_system.time * (generic_unit_system.length**2)) - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - + momentum = generic_unit_system.mass / (generic_unit_system.time * (generic_unit_system.length**2)) + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + potential_grid = datamodel.Grid(n + 2, n + 2, 1) potential_grid.potential = 0.0 | generic_unit_system.potential x = instance.potential_grid.x y = instance.potential_grid.y z = instance.potential_grid.z - potential_grid.potential = (1 | generic_unit_system.potential) * ( (x + y) / (1 | generic_unit_system.length)) + potential_grid.potential = (1 | generic_unit_system.potential) * ((x + y) / (1 | generic_unit_system.length)) channel = potential_grid.new_channel_to(instance.potential_grid) channel.copy() result = instance.initialize_grid() - self.assertAlmostRelativeEquals(potential_grid.potential[...,0,0], instance.potential_grid.potential[...,0,0]) - interpolated_inside = instance.get_interpolated_gravitational_potential(x[0,0,0], y[0,0,0], z[0,0,0]) - interpolated_outside = instance.get_interpolated_gravitational_potential(x[0,0,0] - (0.5 |generic_unit_system.length), y[0,0,0], z[0,0,0]) - - self.assertAlmostRelativeEquals(potential_grid.potential[...,0,0], instance.potential_grid.potential[...,0,0]) - interpolated_inside = instance.get_interpolated_gravitational_potential(x[5,0,0], y[0,0,0], z[0,0,0]) - interpolated_outside = instance.get_interpolated_gravitational_potential(x[5,0,0] + (0.5 |generic_unit_system.length), y[0,0,0], z[0,0,0]) + self.assertAlmostRelativeEquals(potential_grid.potential[..., 0, 0], instance.potential_grid.potential[..., 0, 0]) + interpolated_inside = instance.get_interpolated_gravitational_potential(x[0, 0, 0], y[0, 0, 0], z[0, 0, 0]) + interpolated_outside = instance.get_interpolated_gravitational_potential(x[0, 0, 0] - (0.5 | generic_unit_system.length), y[0, 0, 0], z[0, 0, 0]) + + self.assertAlmostRelativeEquals(potential_grid.potential[..., 0, 0], instance.potential_grid.potential[..., 0, 0]) + interpolated_inside = instance.get_interpolated_gravitational_potential(x[5, 0, 0], y[0, 0, 0], z[0, 0, 0]) + interpolated_outside = instance.get_interpolated_gravitational_potential(x[5, 0, 0] + (0.5 | generic_unit_system.length), y[0, 0, 0], z[0, 0, 0]) print(interpolated_inside, interpolated_outside) self.assertAlmostRelativeEquals(interpolated_inside, interpolated_outside) - - - def test29(self): - - instance=self.new_instance(Athena) - instance.parameters.x_boundary_conditions = ("periodic","periodic") + + instance = self.new_instance(Athena) + instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.mesh_length = (20.0, 1, 1) | generic_unit_system.length instance.parameters.mesh_size = (20, 1, 1) - + for x in instance.itergrids(): inmem = x.copy() - inmem.rho = inmem.x/(1| generic_unit_system.length) | generic_unit_system.density + inmem.rho = inmem.x/(1 | generic_unit_system.length) | generic_unit_system.density inmem.rhovx = 0.0 | generic_unit_system.momentum_density - inmem.energy = 1.0 | generic_unit_system.energy_density + inmem.energy = 1.0 | generic_unit_system.energy_density from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() print(inmem.rho) - rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5| generic_unit_system.length,0.0| generic_unit_system.length,0.0| generic_unit_system.length) - - self.assertEqual(rho , 0.5 | generic_unit_system.density) - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5 | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length) + + self.assertEqual(rho, 0.5 | generic_unit_system.density) + for value in numpy.arange(0.5, 19.6, 0.1): - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_for_cell( value | generic_unit_system.length, 0.0 | generic_unit_system.length, @@ -2792,8 +2678,8 @@ def test29(self): 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length ) - self.assertAlmostRelativeEquals(rho , value | generic_unit_system.density, 9) - + self.assertAlmostRelativeEquals(rho, value | generic_unit_system.density, 9) + for value in numpy.arange(0.0, 0.6, 0.1): rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_for_cell( value | generic_unit_system.length, @@ -2803,70 +2689,63 @@ def test29(self): 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length ) - self.assertAlmostRelativeEquals(rho , ((0.5 + value) * 0.5 + (0.5-value) * 19.5) | generic_unit_system.density, 9) - - + self.assertAlmostRelativeEquals(rho, ((0.5 + value) * 0.5 + (0.5-value) * 19.5) | generic_unit_system.density, 9) + for value in numpy.arange(0.0, 0.5, 0.1): rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_for_cell( - value + 19.5| generic_unit_system.length, + value + 19.5 | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length, 1.0 | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length ) - self.assertAlmostRelativeEquals(rho , (19.5 - (value * 19)) | generic_unit_system.density, 9) - + self.assertAlmostRelativeEquals(rho, (19.5 - (value * 19)) | generic_unit_system.density, 9) + # out of range rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_for_cell( - 21.0| generic_unit_system.length, + 21.0 | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length, 1.0 | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length ) - self.assertAlmostRelativeEquals(rho , 0.0 | generic_unit_system.density, 9) - - - + self.assertAlmostRelativeEquals(rho, 0.0 | generic_unit_system.density, 9) + def test29(self): - - instance=self.new_instance(Athena) - instance.parameters.x_boundary_conditions = ("periodic","periodic") + + instance = self.new_instance(Athena) + instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.mesh_length = (20.0, 1, 1) | generic_unit_system.length instance.parameters.mesh_size = (20, 1, 1) - + for x in instance.itergrids(): inmem = x.copy() - inmem.rho = inmem.x/(1| generic_unit_system.length) | generic_unit_system.density + inmem.rho = inmem.x/(1 | generic_unit_system.length) | generic_unit_system.density inmem.rhovx = 0.0 | generic_unit_system.momentum_density - inmem.energy = 1.0 | generic_unit_system.energy_density + inmem.energy = 1.0 | generic_unit_system.energy_density from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() print(inmem.rho) - - - + def test30(self): - - instance=self.new_instance(Athena) - instance.parameters.x_boundary_conditions = ("periodic","periodic") + + instance = self.new_instance(Athena) + instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.mesh_length = (8, 1, 1) | generic_unit_system.length instance.parameters.mesh_size = (8, 1, 1) - + for x in instance.itergrids(): inmem = x.copy() - inmem.rho = inmem.x/(1| generic_unit_system.length) | generic_unit_system.density + inmem.rho = inmem.x/(1 | generic_unit_system.length) | generic_unit_system.density inmem.rhovx = 0.0 | generic_unit_system.momentum_density - inmem.energy = 1.0 | generic_unit_system.energy_density + inmem.energy = 1.0 | generic_unit_system.energy_density from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() print(inmem.rho) - + grid = instance.get_extended_grid() - self.assertEqual(grid.shape, (12,1,1)) + self.assertEqual(grid.shape, (12, 1, 1)) instance.initialize_grid() - self.assertEqual(grid.rho[...,0,0] , [6.5,7.5,0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,0.5,1.5] | generic_unit_system.density) - - + self.assertEqual(grid.rho[..., 0, 0], [6.5, 7.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 0.5, 1.5] | generic_unit_system.density) diff --git a/src/amuse/test/suite/codes_tests/test_bhtree.py b/src/amuse/test/suite/codes_tests/test_bhtree.py index 13e7613a92..d2bf2acc9d 100644 --- a/src/amuse/test/suite/codes_tests/test_bhtree.py +++ b/src/amuse/test/suite/codes_tests/test_bhtree.py @@ -29,14 +29,14 @@ def test0(self): instance = BHTreeInterface() self.assertTrue("Barnes" in instance.all_literature_references_string()) instance.stop() - + def test1(self): instance = BHTreeInterface() instance.initialize_code() instance.commit_parameters() - res1 = instance.new_particle(mass = 11.0, radius = 2.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) - res2 = instance.new_particle(mass = 21.0, radius = 5.0, x = 10.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) - + res1 = instance.new_particle(mass=11.0, radius=2.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) + res2 = instance.new_particle(mass=21.0, radius=5.0, x=10.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) + instance.commit_particles() self.assertEqual(1, res1['index_of_the_particle']) self.assertEqual(2, res2['index_of_the_particle']) @@ -50,8 +50,8 @@ def test1(self): self.assertEqual(10.0, retrieved_state2['x']) self.assertEqual(1, instance.get_index_of_first_particle()['index_of_the_particle']) - self.assertEqual(2, instance.get_index_of_next_particle(1)['index_of_the_next_particle']) - + self.assertEqual(2, instance.get_index_of_next_particle(1)['index_of_the_next_particle']) + instance.cleanup_code() instance.stop() @@ -61,119 +61,114 @@ def test2(self): instance.commit_parameters() for i in [1, 2, 3]: - temp_particle = instance.new_particle(mass = i, radius = 1.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) + temp_particle = instance.new_particle(mass=i, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) self.assertEqual(i, temp_particle['index_of_the_particle']) - + instance.commit_particles() self.assertEqual(1, instance.get_index_of_first_particle()['index_of_the_particle']) - self.assertEqual(2, instance.get_index_of_next_particle(1)['index_of_the_next_particle']) + self.assertEqual(2, instance.get_index_of_next_particle(1)['index_of_the_next_particle']) self.assertEqual(3, instance.get_index_of_next_particle(2)['index_of_the_next_particle']) - + instance.delete_particle(1) - + self.assertEqual(2, instance.get_number_of_particles()['number_of_particles']) - - #the deletion does a swap, so 3 is copied to 1, (overwriting old 1 and treesize -> treesize-1 + + # the deletion does a swap, so 3 is copied to 1, (overwriting old 1 and treesize -> treesize-1 self.assertEqual(3, instance.get_index_of_first_particle()['index_of_the_particle']) - + self.assertEqual(1, instance.get_index_of_next_particle(2)['__result']) instance.cleanup_code() instance.stop() - + def test5(self): interface = BHTreeInterface() interface.initialize_code() - + interface.commit_parameters() - interface.new_particle([10,20],[0,0],[0,0], [0,0], [0,0], [0,0], [0,0],[1,1]) + interface.new_particle([10, 20], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 1]) interface.commit_particles() retrieved_state = interface.get_state(1) - + self.assertEqual(10.0, retrieved_state['mass']) self.assertEqual(1, retrieved_state['radius']) - retrieved_state = interface.get_state([1,2]) + retrieved_state = interface.get_state([1, 2]) self.assertEqual(20.0, retrieved_state['mass'][1]) self.assertEqual(interface.get_number_of_particles()['number_of_particles'], 2) interface.cleanup_code() interface.stop() - - + def test6(self): instance = BHTreeInterface() instance.initialize_code() instance.commit_parameters() - + ids = [] for i in [1, 2, 3]: - id, error = instance.new_particle(mass = i, radius = 1.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) + id, error = instance.new_particle(mass=i, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) ids.append(id) - - + print(ids) - + instance.commit_particles() - - + instance.delete_particle(ids[0]) - id, error = instance.new_particle(mass = 4, radius = 1.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) + id, error = instance.new_particle(mass=4, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) self.assertNotEqual(id, ids[-1]) - + instance.cleanup_code() instance.stop() - - def test7(self): - interface = BHTreeInterface()#channel_type="remote") #, debugger="xterm") + interface = BHTreeInterface() # channel_type="remote") #, debugger="xterm") interface.initialize_code() - + interface.commit_parameters() - interface.new_particle([10,20],[0,0],[0,0], [0,0], [0,0], [0,0], [0,0],[1,1]) + interface.new_particle([10, 20], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 1]) interface.commit_particles() retrieved_state = interface.get_state(1) - + self.assertEqual(10.0, retrieved_state['mass']) self.assertEqual(1, retrieved_state['radius']) - - retrieved_state = interface.get_state([1,2]) + + retrieved_state = interface.get_state([1, 2]) self.assertEqual(20.0, retrieved_state['mass'][1]) self.assertEqual(interface.get_number_of_particles()['number_of_particles'], 2) interface.cleanup_code() interface.stop() - + def test8(self): instance = BHTreeInterface() instance.initialize_code() instance.set_epsilon_squared(0.1 * 0.1) instance.commit_parameters() - id1,errorcode = instance.new_particle(mass = 10.0, radius = 1.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) - id2,errorcode = instance.new_particle(mass = 10.0, radius = 1.0, x = 2.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) - + id1, errorcode = instance.new_particle(mass=10.0, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) + id2, errorcode = instance.new_particle(mass=10.0, radius=1.0, x=2.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) + instance.commit_particles() potential, errorcode = instance.get_potential(id1) self.assertEqual(errorcode, 0) self.assertAlmostRelativeEquals(potential, -10.0 / numpy.sqrt(2.0**2 + 0.1**2), 8) instance.cleanup_code() instance.stop() - - + + class TestBHTree(TestWithMPI): def new_system_of_sun_and_earth(self): stars = datamodel.Stars(2) sun = stars[0] sun.mass = units.MSun(1.0) - sun.position = units.m(numpy.array((0.0,0.0,0.0))) - sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) + sun.position = units.m(numpy.array((0.0, 0.0, 0.0))) + sun.velocity = units.ms(numpy.array((0.0, 0.0, 0.0))) sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) - earth.radius = units.km(6371) - earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) - earth.velocity = units.ms(numpy.array((0.0,29800,0.0))) - + earth.radius = units.km(6371) + earth.position = units.km(numpy.array((149.5e6, 0.0, 0.0))) + earth.velocity = units.ms(numpy.array((0.0, 29800, 0.0))) + return stars def test1(self): @@ -181,104 +176,102 @@ def test1(self): instance = BHTree(convert_nbody) instance.parameters.epsilon_squared = 0.001 | units.AU**2 - + stars = datamodel.Stars(2) - + sun = stars[0] sun.mass = units.MSun(1.0) - sun.position = [0.0,0.0,0.0] | units.m - sun.velocity = [0.0,0.0,0.0] | units.ms + sun.position = [0.0, 0.0, 0.0] | units.m + sun.velocity = [0.0, 0.0, 0.0] | units.ms sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) - earth.radius = units.km(6371) + earth.radius = units.km(6371) earth.position = [149.5e6, 0.0, 0.0] | units.km earth.velocity = [0.0, 29800, 0.0] | units.ms - #instance.particles.add_particles(stars) + # instance.particles.add_particles(stars) instance.particles.add_particles(stars) - + postion_at_start = earth.position.value_in(units.AU)[0] - + instance.evolve_model(365.0 | units.day) instance.particles.copy_values_of_all_attributes_to(stars) - + postion_after_full_rotation = earth.position.value_in(units.AU)[0] - + self.assertAlmostEqual(postion_at_start, postion_after_full_rotation, 3) - + instance.evolve_model(365.0 + (365.0 / 2) | units.day) - + instance.particles.copy_values_of_all_attributes_to(stars) - + postion_after_half_a_rotation = earth.position.value_in(units.AU)[0] self.assertAlmostEqual(-postion_at_start, postion_after_half_a_rotation, 2) - - - instance.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) - + + instance.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) + instance.particles.copy_values_of_all_attributes_to(stars) - + postion_after_half_a_rotation = earth.position.value_in(units.AU)[1] - + self.assertAlmostEqual(-postion_at_start, postion_after_half_a_rotation, 1) instance.cleanup_code() instance.stop() - + def test2(self): - #not completed + # not completed convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) instance = BHTree(convert_nbody) - #instance.dt_dia = 1 + # instance.dt_dia = 1 instance.parameters.epsilon_squared = 0.001 | units.AU**2 - #instance.timestep = 0.0001 - #instance.use_self_gravity = 0 + # instance.timestep = 0.0001 + # instance.use_self_gravity = 0 instance.commit_parameters() - + stars = datamodel.Stars(2) sun = stars[0] sun.mass = units.MSun(1.0) - sun.position = units.m(numpy.array((0.0,0.0,0.0))) - sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) + sun.position = units.m(numpy.array((0.0, 0.0, 0.0))) + sun.velocity = units.ms(numpy.array((0.0, 0.0, 0.0))) sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) - earth.radius = units.km(6371) - earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) - earth.velocity = units.ms(numpy.array((0.0,29800,0.0))) + earth.radius = units.km(6371) + earth.position = units.km(numpy.array((149.5e6, 0.0, 0.0))) + earth.velocity = units.ms(numpy.array((0.0, 29800, 0.0))) instance.particles.add_particles(stars) instance.commit_particles() self.assertAlmostRelativeEquals(sun.radius, instance.particles[0].radius) - - for x in range(1,2000,10): + + for x in range(1, 2000, 10): instance.evolve_model(x | units.day) instance.particles.copy_values_of_all_attributes_to(stars) stars.savepoint() - + if HAS_MATPLOTLIB: figure = pyplot.figure() - plot = figure.add_subplot(1,1,1) - + plot = figure.add_subplot(1, 1, 1) + x_points = earth.get_timeline_of_attribute("x") y_points = earth.get_timeline_of_attribute("y") - + x_points_in_AU = [t_x[1].value_in(units.AU) for t_x in x_points] y_points_in_AU = [t_x1[1].value_in(units.AU) for t_x1 in y_points] - - plot.scatter(x_points_in_AU,y_points_in_AU, color = "b", marker = 'o') - + + plot.scatter(x_points_in_AU, y_points_in_AU, color="b", marker='o') + plot.set_xlim(-1.5, 1.5) plot.set_ylim(-1.5, 1.5) - - + test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "bhtree-earth-sun.svg") - figure.savefig(output_file) - + figure.savefig(output_file) + instance.cleanup_code() instance.stop() @@ -286,64 +279,63 @@ def test3(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) instance = BHTree(convert_nbody) - #instance.dt_dia = 1 + # instance.dt_dia = 1 instance.parameters.epsilon_squared = 0.001 | units.AU**2 - #instance.timestep = 0.0001 - #instance.use_self_gravity = 0 + # instance.timestep = 0.0001 + # instance.use_self_gravity = 0 instance.commit_parameters() - - + stars = datamodel.Stars(2) star1 = stars[0] star2 = stars[1] star1.mass = units.MSun(1.0) - star1.position = units.AU(numpy.array((-.10,0.0,0.0))) - star1.velocity = units.AUd(numpy.array((0.0,0.0,0.0))) + star1.position = units.AU(numpy.array((-.10, 0.0, 0.0))) + star1.velocity = units.AUd(numpy.array((0.0, 0.0, 0.0))) star1.radius = units.RSun(1.0) star2.mass = units.MSun(1.0) - star2.position = units.AU(numpy.array((.10,0.0,0.0))) - star2.velocity = units.AUd(numpy.array((0.0,0.0,0.0))) + star2.position = units.AU(numpy.array((.10, 0.0, 0.0))) + star2.velocity = units.AUd(numpy.array((0.0, 0.0, 0.0))) star2.radius = units.RSun(100.0) - + instance.particles.add_particles(stars) instance.commit_particles() - - for x in range(1,200,1): + + for x in range(1, 200, 1): instance.evolve_model(x | units.day) instance.particles.copy_values_of_all_attributes_to(stars) - #instance.get_indices_of_colliding_particles() - #print stars[0].position-stars[1].position + # instance.get_indices_of_colliding_particles() + # print stars[0].position-stars[1].position stars.savepoint() - + instance.cleanup_code() instance.stop() - + def test4(self): convert_nbody = nbody_system.nbody_to_si(5.0 | units.kg, 10.0 | units.m) instance = BHTree(convert_nbody) instance.commit_parameters() - + index = instance.new_particle( 15.0 | units.kg, 10.0 | units.m, 20.0 | units.m, 30.0 | units.m, - #1.0 | units.m/units.s, 1.0 | units.m/units.s, 3.0 | units.m/units.s + # 1.0 | units.m/units.s, 1.0 | units.m/units.s, 3.0 | units.m/units.s 0.0 | units.m/units.s, 0.0 | units.m/units.s, 0.0 | units.m/units.s, 10.0 | units.m ) instance.commit_particles() - self.assertEqual(instance.get_mass(index), 15.0| units.kg) - self.assertEqual(instance.get_radius(index), 10.0| units.m) + self.assertEqual(instance.get_mass(index), 15.0 | units.kg) + self.assertEqual(instance.get_radius(index), 10.0 | units.m) instance.cleanup_code() instance.stop() - + def test5(self): instance = BHTree() instance.commit_parameters() - + index = instance.new_particle( 15.0 | nbody_system.mass, 10.0 | nbody_system.length, 20.0 | nbody_system.length, 30.0 | nbody_system.length, @@ -351,101 +343,97 @@ def test5(self): 10.0 | nbody_system.length ) instance.commit_particles() - self.assertEqual(instance.get_mass(index), 15.0| nbody_system.mass) - self.assertEqual(instance.get_radius(index), 10.0| nbody_system.length) - + self.assertEqual(instance.get_mass(index), 15.0 | nbody_system.mass) + self.assertEqual(instance.get_radius(index), 10.0 | nbody_system.length) + instance.cleanup_code() instance.stop() - + def test6(self): convert_nbody = nbody_system.nbody_to_si(5.0 | units.kg, 10.0 | units.m) instance = BHTree(convert_nbody) instance.commit_parameters() - + indices = instance.new_particle( [15.0, 30.0] | units.kg, [10.0, 20.0] | units.m, [20.0, 40.0] | units.m, [30.0, 50.0] | units.m, - #1.0 | units.m/units.s, 1.0 | units.m/units.s, 3.0 | units.m/units.s + # 1.0 | units.m/units.s, 1.0 | units.m/units.s, 3.0 | units.m/units.s [0.0, 0.01] | units.m/units.s, [0.0, 0.01] | units.m/units.s, [0.0, 0.01] | units.m/units.s, [10.0, 20.0] | units.m ) instance.commit_particles() - - self.assertEqual(instance.get_mass(indices[0]), 15.0| units.kg) - self.assertEqual(instance.get_mass(indices)[0], 15.0| units.kg) - - self.assertRaises(AmuseException, instance.get_mass, [4,5], - expected_message = "Error when calling 'get_mass' of a '', errorcode is -1") - + + self.assertEqual(instance.get_mass(indices[0]), 15.0 | units.kg) + self.assertEqual(instance.get_mass(indices)[0], 15.0 | units.kg) + + self.assertRaises(AmuseException, instance.get_mass, [4, 5], + expected_message="Error when calling 'get_mass' of a '', errorcode is -1") + instance.cleanup_code() instance.stop() - + def test7(self): convert_nbody = nbody_system.nbody_to_si(5.0 | units.kg, 10.0 | units.m) - + instance = BHTree(convert_nbody) instance.commit_parameters() - + particles = datamodel.Particles(2) self.assertEqual(len(instance.particles), 0) - + particles.mass = [15.0, 30.0] | units.kg - particles.radius = [10.0, 20.0] | units.m + particles.radius = [10.0, 20.0] | units.m particles.position = [[10.0, 20.0, 30.0], [20.0, 40.0, 60.0]] | units.m particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.m / units.s - - + instance.particles.add_particles(particles) instance.commit_particles() - - self.assertEqual(instance.get_mass(1), 15.0| units.kg) - self.assertAlmostRelativeEquals(instance.get_position(1)[2], 30.0| units.m) - + + self.assertEqual(instance.get_mass(1), 15.0 | units.kg) + self.assertAlmostRelativeEquals(instance.get_position(1)[2], 30.0 | units.m) + self.assertEqual(len(instance.particles), 2) - - + self.assertAlmostRelativeEquals(instance.particles.mass[1], 30.0 | units.kg) - self.assertAlmostRelativeEquals(instance.particles.position[1][2], 60.0 | units.m) + self.assertAlmostRelativeEquals(instance.particles.position[1][2], 60.0 | units.m) instance.cleanup_code() instance.stop() - + def test8(self): convert_nbody = nbody_system.nbody_to_si(5.0 | units.kg, 10.0 | units.m) instance = BHTree(convert_nbody) instance.commit_parameters() - + particles = datamodel.Particles(2) self.assertEqual(len(instance.particles), 0) - + particles.mass = [15.0, 30.0] | units.kg - particles.radius = [10.0, 20.0] | units.m + particles.radius = [10.0, 20.0] | units.m particles.position = [[10.0, 20.0, 30.0], [20.0, 40.0, 60.0]] | units.m particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.m / units.s - instance.particles.add_particles(particles) instance.commit_particles() - - instance.particles.mass = [17.0, 33.0] | units.kg - - - self.assertEqual(instance.get_mass(1), 17.0| units.kg) + + instance.particles.mass = [17.0, 33.0] | units.kg + + self.assertEqual(instance.get_mass(1), 17.0 | units.kg) instance.cleanup_code() instance.stop() - + def test9(self): instance = BHTree() instance.initialize_code() instance.parameters.epsilon_squared = 0.00001 | nbody_system.length**2 - + particles = datamodel.Particles(2) particles.mass = [1.0, 1.0] | nbody_system.mass - particles.radius = [0.0001, 0.0001] | nbody_system.length - particles.position = [[0.0,0.0,0.0], [2.0,0.0,0.0]] | nbody_system.length + particles.radius = [0.0001, 0.0001] | nbody_system.length + particles.position = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]] | nbody_system.length particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed instance.particles.add_particles(particles) - + zero = 0.0 | nbody_system.length fx, fy, fz = instance.get_gravity_at_point(zero, 1.0 | nbody_system.length, zero, zero) self.assertAlmostEqual(fx, 0.0 | nbody_system.acceleration, 3) @@ -459,41 +447,39 @@ def test9(self): potential1 = instance.get_potential_at_point(zero, x1, zero, zero) fx0, fy0, fz0 = instance.get_gravity_at_point(zero, x0, zero, zero) fx1, fy1, fz1 = instance.get_gravity_at_point(zero, x1, zero, zero) - + self.assertAlmostEqual(fy0, 0.0 | nbody_system.acceleration, 3) self.assertAlmostEqual(fz0, 0.0 | nbody_system.acceleration, 3) self.assertAlmostEqual(fy1, 0.0 | nbody_system.acceleration, 3) self.assertAlmostEqual(fz1, 0.0 | nbody_system.acceleration, 3) - + self.assertAlmostEqual(fx0, -1.0 * fx1, 5) fx = (-1.0 / (x0**2) + 1.0 / (x1**2)) * (1.0 | nbody_system.length ** 3 / nbody_system.time ** 2) self.assertAlmostEqual(fx, fx0, 2) self.assertAlmostEqual(potential0, potential1, 5) instance.cleanup_code() instance.stop() - + def test10(self): instance = BHTree() instance.initialize_code() instance.parameters.epsilon_squared = 0.00001 | nbody_system.length**2 instance.commit_parameters() - - + particles = datamodel.Particles(6) particles.mass = 1.0 | nbody_system.mass - particles.radius = 0.00001 | nbody_system.length - particles.position = [[-1.0,0.0,0.0],[1.0,0.0,0.0],[0.0,-1.0,0.0],[0.0,1.0,0.0],[0.0,0.0,-1.0],[0.0,0.0,1.0]] | nbody_system.length - particles.velocity = [[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0]] | nbody_system.speed + particles.radius = 0.00001 | nbody_system.length + particles.position = [[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0], [0.0, 0.0, 1.0]] | nbody_system.length + particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed instance.particles.add_particles(particles) instance.commit_particles() - + zero = 0.0 | nbody_system.length fx, fy, fz = instance.get_gravity_at_point(zero, zero, zero, zero) self.assertAlmostEqual(fx, 0.0 | nbody_system.acceleration, 3) self.assertAlmostEqual(fy, 0.0 | nbody_system.acceleration, 3) self.assertAlmostEqual(fz, 0.0 | nbody_system.acceleration, 3) - - + for position in (0.25, 0.5, 0.75): p0 = position | nbody_system.length p1 = -position | nbody_system.length @@ -504,120 +490,118 @@ def test10(self): args1[1 + i] = p1 f0 = instance.get_gravity_at_point(*args0) f1 = instance.get_gravity_at_point(*args1) - + for j in range(3): if j != i: self.assertAlmostEqual(f0[j], 0.0 | nbody_system.acceleration, 3) self.assertAlmostEqual(f1[j], 0.0 | nbody_system.acceleration, 3) else: self.assertAlmostEqual(f0[j], -1.0 * f1[j], 5) - + instance.stop() - + def test11(self): - + convert_nbody = nbody_system.nbody_to_si(5.0 | units.kg, 10.0 | units.m) instance = BHTree(convert_nbody) - + particles = datamodel.Particles(2) self.assertEqual(len(instance.particles), 0) - + particles.mass = [15.0, 30.0] | units.kg - particles.radius = [10.0, 20.0] | units.m + particles.radius = [10.0, 20.0] | units.m particles.position = [[10.0, 20.0, 30.0], [20.0, 40.0, 60.0]] | units.m particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.m / units.s - instance.particles.add_particles(particles) - - copyof = instance.particles.copy() - + + copyof = instance.particles.copy() + self.assertAlmostEqual(30 | units.kg, copyof[1].mass, 6) - + copyof[1].mass = 35 | units.kg - + copyof.copy_values_of_all_attributes_to(instance.particles) - + self.assertAlmostEqual(35 | units.kg, instance.particles[1].mass, 6) instance.stop() def test12(self): - + convert_nbody = nbody_system.nbody_to_si(5.0 | units.kg, 10.0 | units.m) instance = BHTree(convert_nbody) instance.commit_parameters() - + particles = datamodel.Particles(2) self.assertEqual(len(instance.particles), 0) - + particles.mass = [15.0, 30.0] | units.kg - particles.radius = [10.0, 20.0] | units.m + particles.radius = [10.0, 20.0] | units.m particles.position = [[10.0, 20.0, 30.0], [20.0, 40.0, 60.0]] | units.m particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.m / units.s - instance.particles.add_particles(particles) instance.commit_particles() - - copyof = instance.particles.copy() - - instance.set_state(1, 16|units.kg, 20.0|units.m, 40.0|units.m, 60.0|units.m, - 1.0|units.ms, 1.0|units.ms, 1.0|units.ms) - - curr_state = instance.get_state(1) - for expected, actual in zip((16|units.kg, 20.0|units.m, 40.0|units.m, 60.0|units.m, - 1.0|units.ms, 1.0|units.ms, 1.0|units.ms, 0 | units.m), curr_state): - self.assertAlmostRelativeEquals(actual,expected) - - instance.set_state(1, 16|units.kg, 20.0|units.m, 40.0|units.m, 60.0|units.m, - 1.0|units.ms, 1.0|units.ms, 1.0|units.ms , 20.0|units.m) - - curr_state = instance.get_state(1) - for expected, actual in zip((16|units.kg, 20.0|units.m, 40.0|units.m, 60.0|units.m, - 1.0|units.ms, 1.0|units.ms, 1.0|units.ms, 20 | units.m), curr_state): - self.assertAlmostRelativeEquals(actual,expected) - + + copyof = instance.particles.copy() + + instance.set_state(1, 16 | units.kg, 20.0 | units.m, 40.0 | units.m, 60.0 | units.m, + 1.0 | units.ms, 1.0 | units.ms, 1.0 | units.ms) + + curr_state = instance.get_state(1) + for expected, actual in zip((16 | units.kg, 20.0 | units.m, 40.0 | units.m, 60.0 | units.m, + 1.0 | units.ms, 1.0 | units.ms, 1.0 | units.ms, 0 | units.m), curr_state): + self.assertAlmostRelativeEquals(actual, expected) + + instance.set_state(1, 16 | units.kg, 20.0 | units.m, 40.0 | units.m, 60.0 | units.m, + 1.0 | units.ms, 1.0 | units.ms, 1.0 | units.ms, 20.0 | units.m) + + curr_state = instance.get_state(1) + for expected, actual in zip((16 | units.kg, 20.0 | units.m, 40.0 | units.m, 60.0 | units.m, + 1.0 | units.ms, 1.0 | units.ms, 1.0 | units.ms, 20 | units.m), curr_state): + self.assertAlmostRelativeEquals(actual, expected) + instance.stop() def test13(self): - + convert_nbody = nbody_system.nbody_to_si(1.0 | units.kg, 1.0 | units.m) - + instance = BHTree(convert_nbody) instance.commit_parameters() - + particles = datamodel.Particles(2) self.assertEqual(len(instance.particles), 0) - + particles.mass = [30.0, 30.0] | units.kg - particles.radius = [1.0, 1.0] | units.m + particles.radius = [1.0, 1.0] | units.m particles.position = [[-10.0, 0.0, 0.0], [10.0, 0.0, 0.0]] | units.m particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.m / units.s - + instance.particles.add_particles(particles) instance.commit_particles() - - copyof = instance.particles.copy() - + + copyof = instance.particles.copy() + com = instance.center_of_mass_position self.assertAlmostEqual(com[0], quantities.new_quantity(0.0, units.m), constants.precision) instance.stop() - + def test14(self): print("Test14: Testing BHTree parameters (I)") convert_nbody = nbody_system.nbody_to_si(1.0 | units.yr, 1.0 | units.AU) instance = BHTree(convert_nbody) - - value,error = instance.legacy_interface.get_epsilon_squared() + + value, error = instance.legacy_interface.get_epsilon_squared() self.assertEqual(0, error) self.assertEqual(0.125, value) self.assertAlmostEqual(0.125 | units.AU**2, instance.parameters.epsilon_squared, in_units=units.AU**2) for x in [0.01, 0.1, 0.2]: instance.parameters.epsilon_squared = x | units.AU**2 self.assertAlmostEqual(x | units.AU**2, instance.parameters.epsilon_squared, in_units=units.AU**2) - + (value, error) = instance.legacy_interface.get_time_step() self.assertEqual(0, error) self.assertEqual(0.015625, value) @@ -625,7 +609,7 @@ def test14(self): for x in [0.001, 0.01, 0.1]: instance.parameters.timestep = x | units.yr self.assertAlmostEqual(x | units.yr, instance.parameters.timestep, in_units=units.yr) - + (value, error) = instance.legacy_interface.get_theta_for_tree() self.assertEqual(0, error) self.assertEqual(0.75, value) @@ -633,7 +617,7 @@ def test14(self): for x in [0.2, 0.5, 0.7]: instance.parameters.opening_angle = x self.assertEqual(x, instance.parameters.opening_angle) - + (value, error) = instance.legacy_interface.get_use_self_gravity() self.assertEqual(0, error) self.assertEqual(1, value) @@ -641,7 +625,7 @@ def test14(self): for x in [0, 1]: instance.parameters.use_self_gravity = x self.assertEqual(x, instance.parameters.use_self_gravity) - + (value, error) = instance.legacy_interface.get_ncrit_for_tree() self.assertEqual(0, error) self.assertEqual(12, value) @@ -649,7 +633,7 @@ def test14(self): for x in [512, 2048, 4096]: instance.parameters.ncrit_for_tree = x self.assertEqual(x, instance.parameters.ncrit_for_tree) - + (value, error) = instance.legacy_interface.get_dt_dia() self.assertEqual(0, error) self.assertEqual(1.0, value) @@ -658,11 +642,11 @@ def test14(self): instance.parameters.dt_dia = x | units.yr self.assertAlmostEqual(x | units.yr, instance.parameters.dt_dia, in_units=units.yr) instance.stop() - + def test15(self): print("Test15: Testing effect of BHTree parameter epsilon_squared") convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) - + particles = datamodel.Particles(2) sun = particles[0] sun.mass = 1.0 | units.MSun @@ -675,17 +659,17 @@ def test15(self): earth.radius = 6371.0 | units.km earth.position = [0.0, 1.0, 0.0] | units.AU earth.velocity = [2.0*numpy.pi, -0.0001, 0.0] | units.AU / units.yr - + initial_direction = math.atan((earth.velocity[0]/earth.velocity[1])) final_direction = [] - for log_eps2 in range(-9,10,2): + for log_eps2 in range(-9, 10, 2): instance = BHTree(convert_nbody) instance.initialize_code() instance.parameters.epsilon_squared = 10.0**log_eps2 | units.AU ** 2 instance.particles.add_particles(particles) instance.commit_particles() instance.evolve_model(0.25 | units.yr) - final_direction.append(math.atan((instance.particles[1].velocity[0]/ + final_direction.append(math.atan((instance.particles[1].velocity[0] / instance.particles[1].velocity[1]))) instance.stop() # Small values of epsilon_squared should result in normal earth-sun dynamics: rotation of 90 degrees @@ -694,16 +678,15 @@ def test15(self): self.assertAlmostEqual(final_direction[-1], initial_direction, 2) # Outcome is most sensitive to epsilon_squared when epsilon_squared = d(earth, sun)^2 delta = [abs(final_direction[i+1]-final_direction[i]) for i in range(len(final_direction)-1)] - self.assertEqual(delta[len(final_direction)//2 -1], max(delta)) - - + self.assertEqual(delta[len(final_direction)//2 - 1], max(delta)) + def test16(self): numpy.random.seed(0) number_of_stars = 2 stars = plummer.new_plummer_model(number_of_stars) stars.radius = 0.00001 | nbody_system.length stars.scale_to_standard() - + instance = BHTree() instance.initialize_code() instance.parameters.epsilon_squared = (1.0 / 20.0 / (number_of_stars**0.33333) | nbody_system.length)**2 @@ -717,11 +700,11 @@ def test16(self): request = instance.evolve_model.asynchronous(1.0 | nbody_system.time) request.result() energy_total_t1 = instance.potential_energy + instance.kinetic_energy - + self.assertAlmostRelativeEqual(energy_total_t0, energy_total_t1, 3) instance.stop() numpy.random.seed() - + def test17(self): print("Testing BHTree collision_detection") particles = datamodel.Particles(7) @@ -731,42 +714,42 @@ def test17(self): particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.velocity = [[2, 0, 0], [-2, 0, 0]]*3 + [[-4, 0, 0]] | nbody_system.speed - + instance = BHTree(redirection='none') instance.initialize_code() instance.parameters.set_defaults() - + # Uncommenting any of the following two lines will suppress collision detection -#~ instance.parameters.use_self_gravity = 0 -#~ instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2 - +# ~ instance.parameters.use_self_gravity = 0 +# ~ instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2 + instance.parameters.opening_angle = 0.1 instance.particles.add_particles(particles) collisions = instance.stopping_conditions.collision_detection collisions.enable() instance.evolve_model(1.0 | nbody_system.time) - + self.assertTrue(collisions.is_set()) self.assertTrue(instance.model_time < 0.5 | nbody_system.time) self.assertEqual(len(collisions.particles(0)), 3) self.assertEqual(len(collisions.particles(1)), 3) self.assertEqual(len(particles - collisions.particles(0) - collisions.particles(1)), 1) - self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < + self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < (collisions.particles(0).radius + collisions.particles(1).radius), [True, True, True]) - + sticky_merged = datamodel.Particles(len(collisions.particles(0))) sticky_merged.mass = collisions.particles(0).mass + collisions.particles(1).mass sticky_merged.radius = collisions.particles(0).radius for p1, p2, merged in zip(collisions.particles(0), collisions.particles(1), sticky_merged): merged.position = (p1 + p2).center_of_mass() merged.velocity = (p1 + p2).center_of_mass_velocity() - + print(instance.model_time) print(instance.particles) instance.particles.remove_particles(collisions.particles(0) + collisions.particles(1)) instance.particles.add_particles(sticky_merged) - + instance.evolve_model(1.0 | nbody_system.time) print() print(instance.model_time) @@ -776,28 +759,28 @@ def test17(self): self.assertEqual(len(collisions.particles(0)), 1) self.assertEqual(len(collisions.particles(1)), 1) self.assertEqual(len(instance.particles - collisions.particles(0) - collisions.particles(1)), 2) - self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < + self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < (collisions.particles(0).radius + collisions.particles(1).radius), [True]) instance.stop() - + def test18(self): particles = datamodel.Particles(2) - particles.x = [0.0,10.0] | nbody_system.length + particles.x = [0.0, 10.0] | nbody_system.length particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.radius = 0.005 | nbody_system.length - particles.vx = 0 | nbody_system.speed - particles.vy = 0 | nbody_system.speed - particles.vz = 0 | nbody_system.speed + particles.vx = 0 | nbody_system.speed + particles.vy = 0 | nbody_system.speed + particles.vz = 0 | nbody_system.speed particles.mass = 1.0 | nbody_system.mass - + instance = BHTree() instance.initialize_code() instance.parameters.stopping_conditions_number_of_steps = 2 self.assertEqual(instance.parameters.stopping_conditions_number_of_steps, 2) instance.parameters.epsilon_squared = (0.01 | nbody_system.length)**2 - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.stopping_conditions.number_of_steps_detection.enable() instance.evolve_model(10 | nbody_system.time) self.assertTrue(instance.stopping_conditions.number_of_steps_detection.is_set()) @@ -806,144 +789,141 @@ def test18(self): def test19(self): particles = datamodel.Particles(2) - particles.x = [0.0,10.0] | nbody_system.length + particles.x = [0.0, 10.0] | nbody_system.length particles.y = 0.0 | nbody_system.length particles.z = 0.0 | nbody_system.length particles.radius = 0.005 | nbody_system.length - particles.vx = 0.0 | nbody_system.speed - particles.vy = 0.0 | nbody_system.speed - particles.vz = 0.0 | nbody_system.speed + particles.vx = 0.0 | nbody_system.speed + particles.vy = 0.0 | nbody_system.speed + particles.vz = 0.0 | nbody_system.speed particles.mass = 1.0 | nbody_system.mass very_short_time_to_evolve = 1 | units.s very_long_time_to_evolve = 1e9 | nbody_system.time - + instance = BHTree() instance.initialize_code() - instance.parameters.stopping_conditions_timeout = very_short_time_to_evolve + instance.parameters.stopping_conditions_timeout = very_short_time_to_evolve self.assertEqual(instance.parameters.stopping_conditions_timeout, very_short_time_to_evolve) instance.parameters.epsilon_squared = (0.01 | nbody_system.length)**2 - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.stopping_conditions.timeout_detection.enable() start = time.time() instance.evolve_model(very_long_time_to_evolve) end = time.time() self.assertTrue(instance.stopping_conditions.timeout_detection.is_set()) - self.assertTrue((end-start) < very_short_time_to_evolve.value_in(units.s) + 2)#2 = some overhead compensation + self.assertTrue((end-start) < very_short_time_to_evolve.value_in(units.s) + 2) # 2 = some overhead compensation instance.stop() - + def test20(self): particles = datamodel.Particles(2) - particles.x = [0.0,10.0] | nbody_system.length + particles.x = [0.0, 10.0] | nbody_system.length particles.y = 0.0 | nbody_system.length particles.z = 0.0 | nbody_system.length particles.radius = 0.005 | nbody_system.length - particles.vx = 0.0 | nbody_system.speed - particles.vy = 0.0 | nbody_system.speed - particles.vz = 0.0 | nbody_system.speed + particles.vx = 0.0 | nbody_system.speed + particles.vy = 0.0 | nbody_system.speed + particles.vz = 0.0 | nbody_system.speed particles.mass = 1.0 | nbody_system.mass very_short_time_to_evolve = 1 | units.s very_long_time_to_evolve = 1e9 | nbody_system.time - + instance = BHTree() instance.initialize_code() - instance.parameters.stopping_conditions_timeout = very_short_time_to_evolve + instance.parameters.stopping_conditions_timeout = very_short_time_to_evolve self.assertEqual(instance.parameters.stopping_conditions_timeout, very_short_time_to_evolve) instance.parameters.epsilon_squared = (0.01 | nbody_system.length)**2 - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) codeparticles1 = instance.particles instance.particles.add_particle(datamodel.Particle( - position = [0,1,2] | nbody_system.length, - velocity = [0,0,0] | nbody_system.speed, - radius = 0.005 | nbody_system.length, - mass = 1 | nbody_system.mass + position=[0, 1, 2] | nbody_system.length, + velocity=[0, 0, 0] | nbody_system.speed, + radius=0.005 | nbody_system.length, + mass=1 | nbody_system.mass )) codeparticles2 = instance.particles self.assertTrue(codeparticles1 is codeparticles2) instance.cleanup_code() codeparticles3 = instance.particles self.assertFalse(codeparticles1 is codeparticles3) - + instance.stop() - + def test21(self): particles = datamodel.Particles(2) - particles.x = [0.0,10.0] | nbody_system.length + particles.x = [0.0, 10.0] | nbody_system.length particles.y = 0.0 | nbody_system.length particles.z = 0.0 | nbody_system.length particles.radius = 0.005 | nbody_system.length - particles.vx = 0.0 | nbody_system.speed - particles.vy = 0.0 | nbody_system.speed - particles.vz = 0.0 | nbody_system.speed + particles.vx = 0.0 | nbody_system.speed + particles.vy = 0.0 | nbody_system.speed + particles.vz = 0.0 | nbody_system.speed particles.mass = 1.0 | nbody_system.mass very_short_time_to_evolve = 1 | units.s very_long_time_to_evolve = 1e9 | nbody_system.time - + instance = BHTree() instance.initialize_code() instance.parameters.epsilon_squared = (1e-5 | nbody_system.length)**2 - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.commit_particles() self.assertAlmostRelativeEquals(instance.potential_energy, -0.1 | nbody_system.energy, 5) instance.stop() - - def test22(self): particles = datamodel.Particles(2) - particles.x = [0.0,10.0] | nbody_system.length + particles.x = [0.0, 10.0] | nbody_system.length particles.y = 0.0 | nbody_system.length particles.z = 0.0 | nbody_system.length - particles.vx = 0.0 | nbody_system.speed - particles.vy = 0.0 | nbody_system.speed - particles.vz = 0.0 | nbody_system.speed + particles.vx = 0.0 | nbody_system.speed + particles.vy = 0.0 | nbody_system.speed + particles.vz = 0.0 | nbody_system.speed particles.mass = 1.0 | nbody_system.mass instance = BHTree() - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.commit_particles() self.assertEqual(instance.particles[0].radius, 0.0 | nbody_system.length) p = datamodel.Particle( - x = 1.0 | nbody_system.length, - y = 2.0 | nbody_system.length, - z = 3.0 | nbody_system.length, - vx = 1.0 | nbody_system.speed, - vy = 2.0 | nbody_system.speed, - vz = 3.0 | nbody_system.speed, - mass = 1.0 | nbody_system.mass, - radius = 4.0 | nbody_system.length, + x=1.0 | nbody_system.length, + y=2.0 | nbody_system.length, + z=3.0 | nbody_system.length, + vx=1.0 | nbody_system.speed, + vy=2.0 | nbody_system.speed, + vz=3.0 | nbody_system.speed, + mass=1.0 | nbody_system.mass, + radius=4.0 | nbody_system.length, ) - instance.particles.add_particle(p) + instance.particles.add_particle(p) self.assertEqual(instance.particles[0].radius, 0.0 | nbody_system.length) self.assertEqual(instance.particles[1].radius, 0.0 | nbody_system.length) self.assertEqual(instance.particles[2].radius, 4.0 | nbody_system.length) - + instance.stop() - def test23(self): particles = datamodel.Particles(2) - particles.x = [0.0,10.0] | nbody_system.length + particles.x = [0.0, 10.0] | nbody_system.length particles.y = 0.0 | nbody_system.length particles.z = 0.0 | nbody_system.length - particles.vx = 1.0 | nbody_system.speed - particles.vy = 0.0 | nbody_system.speed - particles.vz = 0.0 | nbody_system.speed + particles.vx = 1.0 | nbody_system.speed + particles.vy = 0.0 | nbody_system.speed + particles.vz = 0.0 | nbody_system.speed particles.mass = 0.1 | nbody_system.mass instance = BHTree(redirection="none") - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.commit_particles() instance.evolve_model(0.1 | nbody_system.time) - self.assertFalse(instance.particles[0].vy > 0| nbody_system.speed) - self.assertAlmostRelativeEquals(instance.particles[0].x , 0.1 | nbody_system.length, 4) + self.assertFalse(instance.particles[0].vy > 0 | nbody_system.speed) + self.assertAlmostRelativeEquals(instance.particles[0].x, 0.1 | nbody_system.length, 4) instance.particles.new_channel_to(particles).copy() - particles.vy = 1| nbody_system.speed + particles.vy = 1 | nbody_system.speed particles.new_channel_to(instance.particles).copy() - + instance.evolve_model(0.2 | nbody_system.time) - self.assertTrue(instance.particles[0].vy > 0| nbody_system.speed) - self.assertAlmostRelativeEquals(instance.particles[0].y , 0.1 | nbody_system.length, 4) + self.assertTrue(instance.particles[0].vy > 0 | nbody_system.speed) + self.assertAlmostRelativeEquals(instance.particles[0].y, 0.1 | nbody_system.length, 4) instance.stop() diff --git a/src/amuse/test/suite/codes_tests/test_bonsai.py b/src/amuse/test/suite/codes_tests/test_bonsai.py index d5eb460ef5..56b70643ac 100644 --- a/src/amuse/test/suite/codes_tests/test_bonsai.py +++ b/src/amuse/test/suite/codes_tests/test_bonsai.py @@ -4,7 +4,7 @@ from amuse.community.bonsai.interface import BonsaiInterface, Bonsai import os -import sys +import sys import numpy from amuse.units import nbody_system @@ -15,42 +15,40 @@ from amuse.support.exceptions import AmuseException default_options = dict() -#default_options = dict(redirection="none") -#default_options = dict(redirection="none", debugger="gdb") +# default_options = dict(redirection="none") +# default_options = dict(redirection="none", debugger="gdb") class TestBonsaiInterface(TestWithMPI): - - + def test1(self): plummer_size = 500 - plummer = new_plummer_model(plummer_size) - mass=plummer.mass.number - radius=plummer.radius.number - x=plummer.x.number - y=plummer.y.number - z=plummer.z.number - vx=plummer.vx.number - vy=plummer.vy.number - vz=plummer.vz.number - + plummer = new_plummer_model(plummer_size) + mass = plummer.mass.number + radius = plummer.radius.number + x = plummer.x.number + y = plummer.y.number + z = plummer.z.number + vx = plummer.vx.number + vy = plummer.vy.number + vz = plummer.vz.number instance = self.new_instance_of_an_optional_code(BonsaiInterface, **default_options) self.assertEqual(0, instance.initialize_code()) self.assertEqual([0, 0], list(instance.get_number_of_particles().values())) - ids, errors = instance.new_particle(mass,x,y,z,vx,vy,vz,radius) + ids, errors = instance.new_particle(mass, x, y, z, vx, vy, vz, radius) self.assertEqual(0, errors) self.assertEqual(list(range(plummer_size)), ids) self.assertEqual(0, instance.commit_particles()) - + self.assertEqual([500, 0], list(instance.get_number_of_particles().values())) masses, errors = instance.get_mass(range(500)) self.assertEqual(0, errors) self.assertAlmostEqual(0.002, masses) - masses,xs,ys,zs,vxs,vys,vzs,radii, errors = instance.get_state(range(500)) + masses, xs, ys, zs, vxs, vys, vzs, radii, errors = instance.get_state(range(500)) self.assertEqual(0, errors) self.assertAlmostRelativeEquals(xs, x, 6) - + self.assertEqual(0, instance.evolve_model(0.00001)) energy_total_init = instance.get_potential_energy()["potential_energy"] + instance.get_kinetic_energy()["kinetic_energy"] self.assertEqual(0, instance.evolve_model(1)) @@ -60,7 +58,7 @@ def test1(self): class TestBonsai(TestWithMPI): - + def test1(self): print("Testing Bonsai initialization") instance = self.new_instance_of_an_optional_code(Bonsai, **default_options) @@ -69,7 +67,7 @@ def test1(self): instance.cleanup_code() print("done") instance.stop() - + def test2(self): print("Testing Bonsai parameters") instance = self.new_instance_of_an_optional_code(Bonsai, **default_options) @@ -82,7 +80,7 @@ def test2(self): self.assertAlmostEqual(instance.parameters.epsilon_squared, 0.01 | nbody_system.length**2) self.assertAlmostEqual(instance.parameters.timestep, 0.001 | nbody_system.time) instance.stop() - + def test3(self): print("Testing Bonsai, N-body units") instance = self.new_instance_of_an_optional_code(Bonsai, **default_options) @@ -93,36 +91,36 @@ def test3(self): instance.evolve_model(1.0 | nbody_system.time) self.assertAlmostEqual(instance.model_time, 1.0 | nbody_system.time) instance.stop() - + def test4(self): print("Testing Bonsai, SI units") convert_nbody = nbody_system.nbody_to_si(100.0 | units.MSun, 1.0 | units.parsec) instance = self.new_instance_of_an_optional_code(Bonsai, convert_nbody, **default_options) instance.initialize_code() - plummer = new_plummer_model(500, convert_nbody = convert_nbody) + plummer = new_plummer_model(500, convert_nbody=convert_nbody) instance.particles.add_particles(plummer) instance.commit_particles() instance.evolve_model(1 | nbody_system.time) instance.stop() - + def test5(self): print("Testing Bonsai remove_particle") convert_nbody = nbody_system.nbody_to_si(100.0 | units.MSun, 1.0 | units.parsec) instance = self.new_instance_of_an_optional_code(Bonsai, convert_nbody, **default_options) instance.initialize_code() - plummer = new_plummer_model(500, convert_nbody = convert_nbody) + plummer = new_plummer_model(500, convert_nbody=convert_nbody) instance.particles.add_particles(plummer) instance.commit_particles() instance.particles.remove_particle(plummer[0]) -# self.assertRaises(AmuseException, instance.particles.remove_particle, plummer[0], +# self.assertRaises(AmuseException, instance.particles.remove_particle, plummer[0], # expected_message = "Error when calling 'delete_particle' of a 'Bonsai', errorcode is -2") print(instance.particles[0].mass) instance.stop() - + def test6(self): print("Testing Bonsai states") plummer = new_plummer_model(500) - + print("First do everything manually:") instance = self.new_instance_of_an_optional_code(Bonsai, **default_options) self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') @@ -154,34 +152,31 @@ def test6(self): self.assertEqual(instance.get_name_of_current_state(), 'EVOLVED') instance.stop() self.assertEqual(instance.get_name_of_current_state(), 'STOPPED') - + def test7(self): print("Testing Bonsai properties") numpy.random.seed(12345) plummer = new_plummer_model(500) instance = self.new_instance_of_an_optional_code(Bonsai, **default_options) instance.particles.add_particles(plummer) - + self.assertEqual(instance.model_time, 0.0 | nbody_system.time) instance.evolve_model(0.0001 | nbody_system.time) print(instance.model_time) self.assertTrue(instance.model_time >= 0.0001 | nbody_system.time) self.assertEqual(instance.model_time, 1.0 * instance.parameters.timestep) - + self.assertAlmostEqual(instance.potential_energy, -0.486261308193 | nbody_system.energy) self.assertAlmostEqual(instance.kinetic_energy, 0.244612112641 | nbody_system.energy) self.assertAlmostEqual(instance.total_mass, 1.0 | nbody_system.mass) - + E0 = instance.kinetic_energy + instance.potential_energy - self.assertRaises(AmuseException, getattr, instance, "total_radius", expected_message = - "Error when calling 'get_total_radius' of a 'Bonsai', errorcode is -2, " + self.assertRaises(AmuseException, getattr, instance, "total_radius", expected_message="Error when calling 'get_total_radius' of a 'Bonsai', errorcode is -2, " "error is 'Called function is not implemented.'") - self.assertRaises(AmuseException, getattr, instance, "center_of_mass_position", expected_message = - "Error when calling 'get_center_of_mass_position' of a 'Bonsai', " + self.assertRaises(AmuseException, getattr, instance, "center_of_mass_position", expected_message="Error when calling 'get_center_of_mass_position' of a 'Bonsai', " "errorcode is -2, error is 'Called function is not implemented.'") - self.assertRaises(AmuseException, getattr, instance, "center_of_mass_velocity", expected_message = - "Error when calling 'get_center_of_mass_velocity' of a 'Bonsai', " + self.assertRaises(AmuseException, getattr, instance, "center_of_mass_velocity", expected_message="Error when calling 'get_center_of_mass_velocity' of a 'Bonsai', " "errorcode is -2, error is 'Called function is not implemented.'") instance.evolve_model(1.0 | nbody_system.time) @@ -189,7 +184,7 @@ def test7(self): self.assertAlmostEqual(instance.potential_energy, -0.4915 | nbody_system.energy, 4) self.assertAlmostEqual(instance.kinetic_energy, 0.2499 | nbody_system.energy, 4) self.assertAlmostEqual( - instance.kinetic_energy + instance.potential_energy, + instance.kinetic_energy + instance.potential_energy, E0, 4) instance.particles.remove_particle(plummer[2]) instance.evolve_model(2.0 | nbody_system.time) @@ -199,8 +194,6 @@ def test7(self): instance.particles.remove_particle(plummer[35]) instance.stop() - - def test8(self): print("Testing Bonsai collision_detection") particles = datamodel.Particles(7) @@ -210,7 +203,7 @@ def test8(self): particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.velocity = [[2, 0, 0], [-2, 0, 0]]*3 + [[-4, 0, 0]] | nbody_system.speed - + instance = self.new_instance_of_an_optional_code(Bonsai) instance.initialize_code() instance.parameters.set_defaults() @@ -218,28 +211,28 @@ def test8(self): collisions = instance.stopping_conditions.collision_detection collisions.enable() instance.evolve_model(1.0 | nbody_system.time) - + self.assertTrue(collisions.is_set()) self.assertTrue(instance.model_time < 0.5 | nbody_system.time) self.assertEqual(len(collisions.particles(0)), 3) self.assertEqual(len(collisions.particles(1)), 3) self.assertEqual(len(particles - collisions.particles(0) - collisions.particles(1)), 1) - self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < + self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < (collisions.particles(0).radius + collisions.particles(1).radius), [True, True, True]) - + sticky_merged = datamodel.Particles(len(collisions.particles(0))) sticky_merged.mass = collisions.particles(0).mass + collisions.particles(1).mass sticky_merged.radius = collisions.particles(0).radius for p1, p2, merged in zip(collisions.particles(0), collisions.particles(1), sticky_merged): merged.position = (p1 + p2).center_of_mass() merged.velocity = (p1 + p2).center_of_mass_velocity() - + print(instance.model_time) print(instance.particles) instance.particles.remove_particles(collisions.particles(0) + collisions.particles(1)) instance.particles.add_particles(sticky_merged) - + instance.evolve_model(1.0 | nbody_system.time) print() print(instance.model_time) @@ -249,24 +242,21 @@ def test8(self): self.assertEqual(len(collisions.particles(0)), 1) self.assertEqual(len(collisions.particles(1)), 1) self.assertEqual(len(instance.particles - collisions.particles(0) - collisions.particles(1)), 2) - self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < + self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < (collisions.particles(0).radius + collisions.particles(1).radius), [True]) instance.stop() - + def test9(self): print("Testing Bonsai tree build exception") plummer = new_plummer_model(50) instance = self.new_instance_of_an_optional_code(Bonsai, **default_options) instance.particles.add_particles(plummer) - + instance.particles[0].position -= [1e9, 0, 0] | nbody_system.length - self.assertRaises(AmuseException, instance.evolve_model, 1.0 | nbody_system.time, expected_message = - "Error when calling 'evolve_model' of a 'Bonsai', errorcode is -4, error is " + self.assertRaises(AmuseException, instance.evolve_model, 1.0 | nbody_system.time, expected_message="Error when calling 'evolve_model' of a 'Bonsai', errorcode is -4, error is " "'The tree has become too deep, consider the removal of far away particles to prevent a too large box.'") - + instance.particles.remove_particle(instance.particles[0]) instance.evolve_model(0.1 | nbody_system.time) instance.stop() - - diff --git a/src/amuse/test/suite/codes_tests/test_bonsai2.py b/src/amuse/test/suite/codes_tests/test_bonsai2.py index f3e154fe00..06ea16fc42 100644 --- a/src/amuse/test/suite/codes_tests/test_bonsai2.py +++ b/src/amuse/test/suite/codes_tests/test_bonsai2.py @@ -13,42 +13,40 @@ from amuse.support.exceptions import AmuseException default_options = dict() -#default_options = dict(redirection="none") -#default_options = dict(redirection="none", debugger="gdb") +# default_options = dict(redirection="none") +# default_options = dict(redirection="none", debugger="gdb") class TestBonsaiInterface(TestWithMPI): - - + def test1(self): plummer_size = 500 - plummer = new_plummer_model(plummer_size) - mass=plummer.mass.number - radius=plummer.radius.number - x=plummer.x.number - y=plummer.y.number - z=plummer.z.number - vx=plummer.vx.number - vy=plummer.vy.number - vz=plummer.vz.number - + plummer = new_plummer_model(plummer_size) + mass = plummer.mass.number + radius = plummer.radius.number + x = plummer.x.number + y = plummer.y.number + z = plummer.z.number + vx = plummer.vx.number + vy = plummer.vy.number + vz = plummer.vz.number instance = self.new_instance_of_an_optional_code(Bonsai2Interface, **default_options) self.assertEqual(0, instance.initialize_code()) self.assertEqual([0, 0], list(instance.get_number_of_particles().values())) - ids, errors = instance.new_particle(mass,x,y,z,vx,vy,vz,radius) + ids, errors = instance.new_particle(mass, x, y, z, vx, vy, vz, radius) self.assertEqual(0, errors) self.assertEqual(list(range(plummer_size)), ids) self.assertEqual(0, instance.commit_particles()) - + self.assertEqual([500, 0], list(instance.get_number_of_particles().values())) masses, errors = instance.get_mass(range(500)) self.assertEqual(0, errors) self.assertAlmostEqual(0.002, masses) - masses,xs,ys,zs,vxs,vys,vzs,radii, errors = instance.get_state(range(500)) + masses, xs, ys, zs, vxs, vys, vzs, radii, errors = instance.get_state(range(500)) self.assertEqual(0, errors) self.assertAlmostRelativeEquals(xs, x, 6) - + self.assertEqual(0, instance.evolve_model(0.00001)) energy_total_init = instance.get_potential_energy()["potential_energy"] + instance.get_kinetic_energy()["kinetic_energy"] self.assertEqual(0, instance.evolve_model(1)) @@ -58,7 +56,7 @@ def test1(self): class TestBonsai(TestWithMPI): - + def test1(self): print("Testing Bonsai initialization") instance = self.new_instance_of_an_optional_code(Bonsai2, **default_options) @@ -67,7 +65,7 @@ def test1(self): instance.cleanup_code() print("done") instance.stop() - + def test2(self): print("Testing Bonsai parameters") instance = self.new_instance_of_an_optional_code(Bonsai2, **default_options) @@ -82,7 +80,7 @@ def test2(self): self.assertAlmostEqual(instance.parameters.epsilon_squared, 0.01 | nbody_system.length**2) self.assertAlmostEqual(instance.parameters.timestep, 0.001 | nbody_system.time) instance.stop() - + def test3(self): print("Testing Bonsai, N-body units") instance = self.new_instance_of_an_optional_code(Bonsai2, **default_options) @@ -93,36 +91,36 @@ def test3(self): instance.evolve_model(1.0 | nbody_system.time) self.assertAlmostEqual(instance.model_time, 1.0 | nbody_system.time) instance.stop() - + def test4(self): print("Testing Bonsai, SI units") convert_nbody = nbody_system.nbody_to_si(100.0 | units.MSun, 1.0 | units.parsec) instance = self.new_instance_of_an_optional_code(Bonsai2, convert_nbody, **default_options) instance.initialize_code() - plummer = new_plummer_model(500, convert_nbody = convert_nbody) + plummer = new_plummer_model(500, convert_nbody=convert_nbody) instance.particles.add_particles(plummer) instance.commit_particles() instance.evolve_model(1 | nbody_system.time) instance.stop() - + def test5(self): print("Testing Bonsai remove_particle") convert_nbody = nbody_system.nbody_to_si(100.0 | units.MSun, 1.0 | units.parsec) instance = self.new_instance_of_an_optional_code(Bonsai2, convert_nbody, **default_options) instance.initialize_code() - plummer = new_plummer_model(500, convert_nbody = convert_nbody) + plummer = new_plummer_model(500, convert_nbody=convert_nbody) instance.particles.add_particles(plummer) instance.commit_particles() instance.particles.remove_particle(plummer[0]) -# self.assertRaises(AmuseException, instance.particles.remove_particle, plummer[0], +# self.assertRaises(AmuseException, instance.particles.remove_particle, plummer[0], # expected_message = "Error when calling 'delete_particle' of a 'Bonsai', errorcode is -2") print(instance.particles[0].mass) instance.stop() - + def test6(self): print("Testing Bonsai states") plummer = new_plummer_model(500) - + print("First do everything manually:") instance = self.new_instance_of_an_optional_code(Bonsai2, **default_options) self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') @@ -154,34 +152,31 @@ def test6(self): self.assertEqual(instance.get_name_of_current_state(), 'EVOLVED') instance.stop() self.assertEqual(instance.get_name_of_current_state(), 'STOPPED') - + def test7(self): print("Testing Bonsai properties") numpy.random.seed(12345) plummer = new_plummer_model(500) instance = self.new_instance_of_an_optional_code(Bonsai2, **default_options) instance.particles.add_particles(plummer) - + self.assertEqual(instance.model_time, 0.0 | nbody_system.time) instance.evolve_model(0.0001 | nbody_system.time) print(instance.model_time) self.assertTrue(instance.model_time >= 0.0001 | nbody_system.time) self.assertEqual(instance.model_time, 1.0 * instance.parameters.timestep) - + self.assertAlmostEqual(instance.potential_energy, -0.50625962019 | nbody_system.energy) self.assertAlmostEqual(instance.kinetic_energy, 0.244611829519 | nbody_system.energy) self.assertAlmostEqual(instance.total_mass, 1.0 | nbody_system.mass) - + E0 = instance.kinetic_energy + instance.potential_energy - self.assertRaises(AmuseException, getattr, instance, "total_radius", expected_message = - "Error when calling 'get_total_radius' of a 'Bonsai2', errorcode is -2, " + self.assertRaises(AmuseException, getattr, instance, "total_radius", expected_message="Error when calling 'get_total_radius' of a 'Bonsai2', errorcode is -2, " "error is 'Called function is not implemented.'") - self.assertRaises(AmuseException, getattr, instance, "center_of_mass_position", expected_message = - "Error when calling 'get_center_of_mass_position' of a 'Bonsai2', " + self.assertRaises(AmuseException, getattr, instance, "center_of_mass_position", expected_message="Error when calling 'get_center_of_mass_position' of a 'Bonsai2', " "errorcode is -2, error is 'Called function is not implemented.'") - self.assertRaises(AmuseException, getattr, instance, "center_of_mass_velocity", expected_message = - "Error when calling 'get_center_of_mass_velocity' of a 'Bonsai2', " + self.assertRaises(AmuseException, getattr, instance, "center_of_mass_velocity", expected_message="Error when calling 'get_center_of_mass_velocity' of a 'Bonsai2', " "errorcode is -2, error is 'Called function is not implemented.'") instance.evolve_model(1.0 | nbody_system.time) @@ -189,7 +184,7 @@ def test7(self): self.assertAlmostEqual(instance.potential_energy, -0.5115 | nbody_system.energy, 4) self.assertAlmostEqual(instance.kinetic_energy, 0.24986 | nbody_system.energy, 4) self.assertAlmostEqual( - instance.kinetic_energy + instance.potential_energy, + instance.kinetic_energy + instance.potential_energy, E0, 4) instance.particles.remove_particle(plummer[2]) instance.evolve_model(2.0 | nbody_system.time) @@ -269,5 +264,4 @@ def test9(self): instance.particles.remove_particle(instance.particles[0]) instance.evolve_model(0.1 | nbody_system.time) instance.stop() -""" - +""" diff --git a/src/amuse/test/suite/codes_tests/test_bridge.py b/src/amuse/test/suite/codes_tests/test_bridge.py index ddc0b7aab9..38fb3e0a5e 100644 --- a/src/amuse/test/suite/codes_tests/test_bridge.py +++ b/src/amuse/test/suite/codes_tests/test_bridge.py @@ -1,4 +1,4 @@ -import numpy +import numpy from amuse.test.amusetest import TestWithMPI from amuse.community.fi.interface import Fi @@ -10,50 +10,49 @@ from amuse.units import units from amuse.ic.kingmodel import new_king_model -def sys_from_parts(base_class,parts,converter,eps=None): - interface=base_class(converter) + +def sys_from_parts(base_class, parts, converter, eps=None): + interface = base_class(converter) interface.initialize_code() if eps is not None: - interface.parameters.epsilon_squared = eps**2 + interface.parameters.epsilon_squared = eps**2 interface.particles.add_particles(parts) return interface + class TestBridge(TestWithMPI): def test1(self): convert = nbody_system.nbody_to_si(1.e5 | units.MSun, 1.0 | units.parsec) - eps=2.e-4 | nbody_system.length + eps = 2.e-4 | nbody_system.length - test_class=PhiGRAPE + test_class = PhiGRAPE number_of_particles = 50 stars = new_king_model(number_of_particles, W0=7, convert_nbody=convert) stars.radius = 0.0 | units.RSun - cluster=test_class(convert) - cluster.parameters.epsilon_squared = eps**2 + cluster = test_class(convert) + cluster.parameters.epsilon_squared = eps**2 cluster.particles.add_particles(stars) cluster.synchronize_model() - Ep1=convert.to_nbody(cluster.potential_energy).number - Ek1=convert.to_nbody(cluster.kinetic_energy).number + Ep1 = convert.to_nbody(cluster.potential_energy).number + Ek1 = convert.to_nbody(cluster.kinetic_energy).number - parts=cluster.particles.copy() - parts1=parts.select_array(lambda x: (x > 0 | units.m), ['x'] ) - parts2=parts.select_array(lambda x: (x < 0 | units.m), ['x'] ) - cluster1=sys_from_parts(test_class, parts1, convert, eps) - cluster2=sys_from_parts(test_class, parts2, convert, eps) + parts = cluster.particles.copy() + parts1 = parts.select_array(lambda x: (x > 0 | units.m), ['x']) + parts2 = parts.select_array(lambda x: (x < 0 | units.m), ['x']) + cluster1 = sys_from_parts(test_class, parts1, convert, eps) + cluster2 = sys_from_parts(test_class, parts2, convert, eps) cluster1.synchronize_model() cluster2.synchronize_model() - bridgesys=bridge() - bridgesys.add_system(cluster1, (cluster2,) ) - bridgesys.add_system(cluster2, (cluster1,) ) - - Ep2=convert.to_nbody(bridgesys.potential_energy).number - Ek2=convert.to_nbody(bridgesys.kinetic_energy).number - self.assertAlmostEqual(Ek1,Ek2,12) - self.assertAlmostEqual(Ep1,Ep2,12) - - - + bridgesys = bridge() + bridgesys.add_system(cluster1, (cluster2,)) + bridgesys.add_system(cluster2, (cluster1,)) + + Ep2 = convert.to_nbody(bridgesys.potential_energy).number + Ek2 = convert.to_nbody(bridgesys.kinetic_energy).number + self.assertAlmostEqual(Ek1, Ek2, 12) + self.assertAlmostEqual(Ep1, Ep2, 12) diff --git a/src/amuse/test/suite/codes_tests/test_brutus.py b/src/amuse/test/suite/codes_tests/test_brutus.py index 25fed5d608..17440d59b3 100644 --- a/src/amuse/test/suite/codes_tests/test_brutus.py +++ b/src/amuse/test/suite/codes_tests/test_brutus.py @@ -13,16 +13,16 @@ try: import mpmath - HAS_MPMATH=True + HAS_MPMATH = True except ImportError: - HAS_MPMATH=False + HAS_MPMATH = False class TestBrutusInterface(TestWithMPI): - + def test1(self): print("Test BrutusInterface initialization") - instance = self.new_instance_of_an_optional_code(BrutusInterface) + instance = self.new_instance_of_an_optional_code(BrutusInterface) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.set_brutus_output_directory(instance.output_directory)) self.assertEqual(0, instance.commit_parameters()) @@ -31,75 +31,75 @@ def test1(self): def test2(self): print("Test BrutusInterface new_particle / get_state") - instance = self.new_instance_of_an_optional_code(BrutusInterface) + instance = self.new_instance_of_an_optional_code(BrutusInterface) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.set_brutus_output_directory(instance.output_directory)) self.assertEqual(0, instance.commit_parameters()) - - id, error = instance.new_particle(mass = 11.0, radius = 2.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) + + id, error = instance.new_particle(mass=11.0, radius=2.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) self.assertEqual(0, error) self.assertEqual(0, id) - id, error = instance.new_particle(mass = 21.0, radius = 5.0, x = 10.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) + id, error = instance.new_particle(mass=21.0, radius=5.0, x=10.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) self.assertEqual(0, error) self.assertEqual(1, id) self.assertEqual(0, instance.commit_particles()) - + retrieved_state1 = instance.get_state(0) retrieved_state2 = instance.get_state(1) self.assertEqual(0, retrieved_state1['__result']) self.assertEqual(0, retrieved_state2['__result']) self.assertEqual(11.0, retrieved_state1['mass']) self.assertEqual(21.0, retrieved_state2['mass']) - self.assertEqual( 0.0, retrieved_state1['x']) + self.assertEqual(0.0, retrieved_state1['x']) self.assertEqual(10.0, retrieved_state2['x']) - + self.assertEqual(0, instance.cleanup_code()) instance.stop() def test4(self): print("Test BrutusInterface particle property getters/setters") - instance = self.new_instance_of_an_optional_code(BrutusInterface) + instance = self.new_instance_of_an_optional_code(BrutusInterface) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.set_brutus_output_directory(instance.output_directory)) self.assertEqual(0, instance.commit_parameters()) self.assertEqual([0, 0], list(instance.new_particle(0.01, 1, 0, 0, 0, 1, 0, 0.1).values())) - self.assertEqual([1, 0], list(instance.new_particle(0.02, -1, 0, 0, 0,-1, 0, 0.1).values())) + self.assertEqual([1, 0], list(instance.new_particle(0.02, -1, 0, 0, 0, -1, 0, 0.1).values())) self.assertEqual(0, instance.commit_particles()) - + # getters mass, result = instance.get_mass(0) self.assertAlmostEqual(0.01, mass) - self.assertEqual(0,result) + self.assertEqual(0, result) radius, result = instance.get_radius(1) self.assertAlmostEqual(0.1, radius) - self.assertEqual(0,result) - #self.assertEquals(-3, instance.get_mass(2)['__result']) # Particle not found - self.assertEqual([ 1, 0, 0, 0], list(instance.get_position(0).values())) + self.assertEqual(0, result) + # self.assertEquals(-3, instance.get_mass(2)['__result']) # Particle not found + self.assertEqual([1, 0, 0, 0], list(instance.get_position(0).values())) self.assertEqual([-1, 0, 0, 0], list(instance.get_position(1).values())) - self.assertEqual([ 0, 1, 0, 0], list(instance.get_velocity(0).values())) - self.assertEqual([ 0,-1, 0, 0], list(instance.get_velocity(1).values())) - + self.assertEqual([0, 1, 0, 0], list(instance.get_velocity(0).values())) + self.assertEqual([0, -1, 0, 0], list(instance.get_velocity(1).values())) + # setters - self.assertEqual(0, instance.set_state(0, 0.01, 1,2,3, 4,5,6, 0.1)) - self.assertEqual([0.01, 1.0,2.0,3.0, 4.0,5.0,6.0, 0.1, 0], list(instance.get_state(0).values())) + self.assertEqual(0, instance.set_state(0, 0.01, 1, 2, 3, 4, 5, 6, 0.1)) + self.assertEqual([0.01, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.1, 0], list(instance.get_state(0).values())) self.assertEqual(0, instance.set_mass(0, 0.02)) - self.assertEqual([0.02, 1.0,2.0,3.0, 4.0,5.0,6.0, 0.1, 0], list(instance.get_state(0).values())) + self.assertEqual([0.02, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.1, 0], list(instance.get_state(0).values())) self.assertEqual(0, instance.set_radius(0, 0.2)) - self.assertEqual([0.02, 1.0,2.0,3.0, 4.0,5.0,6.0, 0.2, 0], list(instance.get_state(0).values())) - self.assertEqual(0, instance.set_position(0, 10,20,30)) - self.assertEqual([0.02, 10.0,20.0,30.0, 4.0,5.0,6.0, 0.2, 0], list(instance.get_state(0).values())) - self.assertEqual(0, instance.set_velocity(0, 40,50,60)) - self.assertEqual([0.02, 10.0,20.0,30.0, 40.0,50.0,60.0, 0.2, 0], list(instance.get_state(0).values())) + self.assertEqual([0.02, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.2, 0], list(instance.get_state(0).values())) + self.assertEqual(0, instance.set_position(0, 10, 20, 30)) + self.assertEqual([0.02, 10.0, 20.0, 30.0, 4.0, 5.0, 6.0, 0.2, 0], list(instance.get_state(0).values())) + self.assertEqual(0, instance.set_velocity(0, 40, 50, 60)) + self.assertEqual([0.02, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 0.2, 0], list(instance.get_state(0).values())) self.assertEqual(0, instance.cleanup_code()) instance.stop() def test5(self): print("Test BrutusInterface parameters") - instance = self.new_instance_of_an_optional_code(BrutusInterface) + instance = self.new_instance_of_an_optional_code(BrutusInterface) self.assertEqual(0, instance.initialize_code()) - + # word length self.assertEqual([64, 0], list(instance.get_word_length().values())) self.assertEqual(0, instance.set_word_length(80)) @@ -111,9 +111,9 @@ def test5(self): self.assertEqual([1.0e-8, 0], list(instance.get_bs_tolerance().values())) # bs tolerance, string implementation for values requiring higher precision (note: actual accuracy depends on word_length) - #self.assertEquals(1e-8, eval(instance.get_bs_tolerance_string()[""])) - #self.assertEquals(0, instance.set_bs_tolerance_string("1e-10")) - #self.assertEquals(["1e-10", 0], instance.get_bs_tolerance_string().values()) + # self.assertEquals(1e-8, eval(instance.get_bs_tolerance_string()[""])) + # self.assertEquals(0, instance.set_bs_tolerance_string("1e-10")) + # self.assertEquals(["1e-10", 0], instance.get_bs_tolerance_string().values()) # eta, float64 self.assertEqual([0.24, 0], list(instance.get_eta().values())) @@ -121,17 +121,17 @@ def test5(self): self.assertEqual([0.10, 0], list(instance.get_eta().values())) # eta, string - #self.assertEquals(["0.10", 0], instance.get_eta_string().values()) + # self.assertEquals(["0.10", 0], instance.get_eta_string().values()) self.assertEqual(0, instance.set_eta_string("123")) self.assertEqual(["123", 0], list(instance.get_eta_string().values())) # output dir - #self.assertEquals(["./", 0], instance.get_brutus_output_directory().values()) + # self.assertEquals(["./", 0], instance.get_brutus_output_directory().values()) self.assertEqual(0, instance.set_brutus_output_directory("./out")) self.assertEqual(["./out/", 0], list(instance.get_brutus_output_directory().values())) self.assertEqual(0, instance.set_brutus_output_directory(instance.output_directory)) self.assertEqual([instance.output_directory+"/", 0], list(instance.get_brutus_output_directory().values())) - + self.assertEqual(0, instance.commit_parameters()) self.assertEqual(0, instance.cleanup_code()) instance.stop() @@ -139,23 +139,23 @@ def test5(self): def test6(self): print("Test BrutusInterface evolve_model, equal-mass binary") - instance = self.new_instance_of_an_optional_code(BrutusInterface) + instance = self.new_instance_of_an_optional_code(BrutusInterface) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.set_bs_tolerance(1.0e-10)) self.assertEqual(0, instance.set_word_length(72)) self.assertEqual(0, instance.commit_parameters()) - + self.assertEqual([0, 0], list(instance.new_particle(0.5, 0.5, 0, 0, 0, 0.5, 0).values())) - self.assertEqual([1, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0,-0.5, 0).values())) + self.assertEqual([1, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0, -0.5, 0).values())) self.assertEqual(0, instance.commit_particles()) - self.assertEqual(0, instance.evolve_model(math.pi)) # half an orbit + self.assertEqual(0, instance.evolve_model(math.pi)) # half an orbit for result, expected in zip(instance.get_position(0).values(), [-0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 5) - self.assertEqual(0, instance.evolve_model(2 * math.pi)) # full orbit + self.assertEqual(0, instance.evolve_model(2 * math.pi)) # full orbit for result, expected in zip(instance.get_position(0).values(), [0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 5) @@ -165,7 +165,7 @@ def test6(self): def test7(self): print("Test BrutusInterface evolve_model, pythagorean problem") - instance = self.new_instance_of_an_optional_code(BrutusInterface) + instance = self.new_instance_of_an_optional_code(BrutusInterface) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.set_bs_tolerance(1.0e-6)) @@ -180,7 +180,7 @@ def test7(self): self.assertEqual(0, instance.commit_particles()) self.assertEqual(0, instance.evolve_model(10)) - + ## add a check for assertequal final coordinates for result, expected in zip(instance.get_position(0).values(), [0.778480410138085492274810667212415, 0.141392300290086165745727207379442, 0, 0]): self.assertAlmostEqual(result, expected, 3) @@ -190,26 +190,26 @@ def test7(self): def test8(self): print("Test BrutusInterface string parameters") - instance = self.new_instance_of_an_optional_code(BrutusInterface) + instance = self.new_instance_of_an_optional_code(BrutusInterface) instance.initialize_code() - + instance.set_word_length(128) - + for i in range(100): - x=random.random() - x=str(x) - instance.set_eta_string(x) - x_,err=instance.get_eta_string() - instance.set_eta_string(x_) - x__,err=instance.get_eta_string() - #~ assert x==x_ - self.assertEqual(x_,x__) - + x = random.random() + x = str(x) + instance.set_eta_string(x) + x_, err = instance.get_eta_string() + instance.set_eta_string(x_) + x__, err = instance.get_eta_string() + # ~ assert x==x_ + self.assertEqual(x_, x__) + instance.stop() - + class TestBrutus(TestWithMPI): - + def new_sun_earth_system(self): particles = Particles(2) particles.mass = [1.0, 3.0037e-6] | units.MSun @@ -222,7 +222,7 @@ def new_sun_earth_system(self): def test1(self): print("Testing Brutus initialization") convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) - instance = self.new_instance_of_an_optional_code(Brutus, convert_nbody) + instance = self.new_instance_of_an_optional_code(Brutus, convert_nbody) instance.initialize_code() instance.commit_parameters() instance.cleanup_code() @@ -233,54 +233,54 @@ def test2(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) - instance = self.new_instance_of_an_optional_code(Brutus,convert_nbody) + instance = self.new_instance_of_an_optional_code(Brutus, convert_nbody) instance.initialize_code() - + # print instance.parameters self.assertEqual(instance.parameters.bs_tolerance, 1.0e-6) instance.parameters.bs_tolerance = 1.0e-9 self.assertEqual(instance.parameters.bs_tolerance, 1.0e-9) - + self.assertEqual(instance.parameters.word_length, 64) instance.parameters.word_length = 128 self.assertEqual(instance.parameters.word_length, 128) - + self.assertEqual(instance.parameters.dt_param, 0.24) instance.parameters.dt_param = 0.10 - self.assertEqual(instance.parameters.dt_param, 0.10) + self.assertEqual(instance.parameters.dt_param, 0.10) self.assertEqual(instance.parameters.brutus_output_directory, instance.output_directory + os.sep) instance.parameters.brutus_output_directory = "./out" self.assertEqual(instance.parameters.brutus_output_directory, "./out/") instance.parameters.brutus_output_directory = instance.output_directory self.assertEqual(instance.parameters.brutus_output_directory, instance.output_directory + os.sep) - + instance.cleanup_code() instance.stop() - + def test3(self): print("Testing Brutus particles") convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) - instance = self.new_instance_of_an_optional_code(Brutus,convert_nbody) + instance = self.new_instance_of_an_optional_code(Brutus, convert_nbody) instance.initialize_code() instance.commit_parameters() instance.particles.add_particles(self.new_sun_earth_system()) instance.commit_particles() - + self.assertAlmostEqual(instance.particles.mass, [1.0, 3.0037e-6] | units.MSun) self.assertAlmostEqual(instance.particles.radius, 1.0 | units.RSun) - self.assertAlmostEqual(instance.particles.position, + self.assertAlmostEqual(instance.particles.position, [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]] | units.AU) - self.assertAlmostEqual(instance.particles.velocity, + self.assertAlmostEqual(instance.particles.velocity, [[0.0, 0.0, 0.0], [0.0, 29.7885, 0.0]] | units.km / units.s, 3) - + instance.cleanup_code() instance.stop() - + def test4(self): print("Testing Brutus evolve_model, 2 particles") @@ -291,7 +291,7 @@ def test4(self): particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.km / units.s particles[1].vy = (constants.G * (1.0 | units.MSun) / (1.0 | units.AU)).sqrt() particles.move_to_center() - + convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) instance = self.new_instance_of_an_optional_code(Brutus, convert_nbody) @@ -307,25 +307,25 @@ def test4(self): instance.commit_particles() primary = instance.particles[0] - + P = 2 * math.pi * primary.x / primary.vy - + position_at_start = primary.position.x instance.evolve_model(P / 4.0) self.assertAlmostRelativeEqual(position_at_start, primary.position.y, 6) - + instance.evolve_model(P / 2.0) self.assertAlmostRelativeEqual(position_at_start, -primary.position.x, 6) - + instance.evolve_model(P) self.assertAlmostRelativeEqual(position_at_start, primary.position.x, 6) - + instance.cleanup_code() instance.stop() - + def sun_and_planets(self): particles = Particles(9) - sun = particles[0] + sun = particles[0] mercury = particles[1] venus = particles[2] earth = particles[3] @@ -334,52 +334,52 @@ def sun_and_planets(self): saturn = particles[6] uranus = particles[7] neptune = particles[8] - - sun.mass = 1047.517| units.MJupiter - sun.radius = 1.0 | units.RSun - sun.position = ( 0.005717 , -0.00538 , -2.130e-5 ) | units.AU - sun.velocity = ( 0.007893 , 0.01189 , 0.0002064 ) | units.kms - - mercury.mass = 0.000174 | units.MJupiter - mercury.radius = 0 | units.RSun - mercury.position = ( -0.31419 , 0.14376 , 0.035135 ) | units.AU - mercury.velocity = ( -30.729 , -41.93 , -2.659 ) | units.kms - - venus.mass = 0.002564 | units.MJupiter - venus.radius = 0 | units.RSun - venus.position = ( -0.3767 , 0.60159 , 0.0393 ) | units.AU - venus.velocity = ( -29.7725 , -18.849 , 0.795 ) | units.kms - - earth.mass = 0.003185 | units.MJupiter - earth.radius = 0 | units.RSun - earth.position = ( -0.98561 , 0.0762 , -7.847e-5 ) | units.AU - earth.velocity = ( -2.927 , -29.803 , -0.000533 ) | units.kms - - mars.mass = 0.000338 | units.MJupiter - mars.radius = 0 | units.RSun - mars.position = ( -1.2895 , -0.9199 , -0.048494 ) | units.AU - mars.velocity = ( 14.9 , -17.721 , 0.2979 ) | units.kms - - jupiter.mass = 1 | units.MJupiter - jupiter.radius = 0 | units.RSun - jupiter.position = ( -4.9829 , 2.062 , -0.10990 ) | units.AU - jupiter.velocity = ( -5.158 , -11.454 , -0.13558 ) | units.kms - - saturn.mass = 0.29947 | units.MJupiter - saturn.radius = 0 | units.RSun - saturn.position = ( -2.075 , 8.7812 , 0.3273 ) | units.AU - saturn.velocity = ( -9.9109 , -2.236 , -0.2398 ) | units.kms - - uranus.mass = 0.045737 | units.MJupiter - uranus.radius = 0 | units.RSun - uranus.position = ( -12.0872 , -14.1917 , 0.184214 ) | units.AU - uranus.velocity = ( 5.1377 , -4.7387 , -0.06108 ) | units.kms - - neptune.mass = 0.053962 | units.MJupiter - neptune.radius = 0 | units.RSun - neptune.position = ( 3.1652 , 29.54882 , 0.476391 ) | units.AU - neptune.velocity = ( -5.443317 , 0.61054 , -0.144172 ) | units.kms - + + sun.mass = 1047.517 | units.MJupiter + sun.radius = 1.0 | units.RSun + sun.position = (0.005717, -0.00538, -2.130e-5) | units.AU + sun.velocity = (0.007893, 0.01189, 0.0002064) | units.kms + + mercury.mass = 0.000174 | units.MJupiter + mercury.radius = 0 | units.RSun + mercury.position = (-0.31419, 0.14376, 0.035135) | units.AU + mercury.velocity = (-30.729, -41.93, -2.659) | units.kms + + venus.mass = 0.002564 | units.MJupiter + venus.radius = 0 | units.RSun + venus.position = (-0.3767, 0.60159, 0.0393) | units.AU + venus.velocity = (-29.7725, -18.849, 0.795) | units.kms + + earth.mass = 0.003185 | units.MJupiter + earth.radius = 0 | units.RSun + earth.position = (-0.98561, 0.0762, -7.847e-5) | units.AU + earth.velocity = (-2.927, -29.803, -0.000533) | units.kms + + mars.mass = 0.000338 | units.MJupiter + mars.radius = 0 | units.RSun + mars.position = (-1.2895, -0.9199, -0.048494) | units.AU + mars.velocity = (14.9, -17.721, 0.2979) | units.kms + + jupiter.mass = 1 | units.MJupiter + jupiter.radius = 0 | units.RSun + jupiter.position = (-4.9829, 2.062, -0.10990) | units.AU + jupiter.velocity = (-5.158, -11.454, -0.13558) | units.kms + + saturn.mass = 0.29947 | units.MJupiter + saturn.radius = 0 | units.RSun + saturn.position = (-2.075, 8.7812, 0.3273) | units.AU + saturn.velocity = (-9.9109, -2.236, -0.2398) | units.kms + + uranus.mass = 0.045737 | units.MJupiter + uranus.radius = 0 | units.RSun + uranus.position = (-12.0872, -14.1917, 0.184214) | units.AU + uranus.velocity = (5.1377, -4.7387, -0.06108) | units.kms + + neptune.mass = 0.053962 | units.MJupiter + neptune.radius = 0 | units.RSun + neptune.position = (3.1652, 29.54882, 0.476391) | units.AU + neptune.velocity = (-5.443317, 0.61054, -0.144172) | units.kms + particles.move_to_center() return particles @@ -388,25 +388,22 @@ def test5(self): self.skip("mpmath not available") print("MPmath available -> Doing tests") bodies = self.sun_and_planets() - convert_nbody = nbody_system.nbody_to_si(bodies.mass.sum(),bodies[1].position.length()) - gravity = Brutus(convert_nbody,number_of_workers=1) + convert_nbody = nbody_system.nbody_to_si(bodies.mass.sum(), bodies[1].position.length()) + gravity = Brutus(convert_nbody, number_of_workers=1) gravity.parameters.bs_tolerance = 1e-30 gravity.parameters.word_length = 180 gravity.parameters.dt_param = 0.0000000000010 gravity.particles.add_particles(bodies) Etot_init = gravity.kinetic_energy + gravity.potential_energy Ein = gravity.get_total_energy_p_si() - gravity.evolve_model(gravity.model_time + (30| units.day)) + gravity.evolve_model(gravity.model_time + (30 | units.day)) Eout = gravity.get_total_energy_p_si() - Ekin = gravity.kinetic_energy + Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot Loss_double = ((Etot_init-Etot)/gravity.get_time()) Loss_mp = (Ein - Eout)/gravity.get_time_p_si() - print("Loss with \"normal\" double =",Loss_double.number," (W)") - print("Loss with multiprecision =",Loss_mp," (W)") + print("Loss with \"normal\" double =", Loss_double.number, " (W)") + print("Loss with multiprecision =", Loss_mp, " (W)") gravity.stop() self.assertTrue((Loss_mp <= 0.0000007) and (Loss_mp > 0.0000006)) - - - diff --git a/src/amuse/test/suite/codes_tests/test_bse.py b/src/amuse/test/suite/codes_tests/test_bse.py index 95a3a4960f..da464514e2 100644 --- a/src/amuse/test/suite/codes_tests/test_bse.py +++ b/src/amuse/test/suite/codes_tests/test_bse.py @@ -7,8 +7,9 @@ import numpy + class TestBSEInterface(TestWithMPI): - + class state(object): def __init__(self): self.type1 = 0.0 @@ -19,8 +20,8 @@ def __init__(self): self.mass2 = 0.0 self.radius1 = 0.0 self.radius2 = 0.0 - self.luminosity1 = 0.0 - self.luminosity2 = 0.0 + self.luminosity1 = 0.0 + self.luminosity2 = 0.0 self.core_mass1 = 0.0 self.core_mass2 = 0.0 self.core_radius1 = 0.0 @@ -38,28 +39,28 @@ def __init__(self): self.bse_age = 0.0 self.orbital_period = 0.0 self.eccentricity = 0.0 - + def test1(self): print("Test initialization...") instance = BSEInterface() metallicity = 0.02 neta = 0.5 - bwind = 0.0 - hewind = 0.5 + bwind = 0.0 + hewind = 0.5 alpha1 = 1.0 CElambda = 0.5 ceflag = 0 tflag = 1 ifflag = 0 - wdflag = 1 - bhflag = 0 - nsflag = 1 - mxns = 3.0 + wdflag = 1 + bhflag = 0 + nsflag = 1 + mxns = 3.0 idum = 29769 pts1 = 0.05 pts2 = 0.01 pts3 = 0.02 - sigma = 190.0 + sigma = 190.0 beta = 1.0/8.0 xi = 1.0 acc2 = 3.0/2.0 @@ -71,16 +72,16 @@ def test1(self): neta, bwind, hewind, alpha1, CElambda, ceflag, tflag, ifflag, wdflag, bhflag, nsflag, mxns, idum, pts1, pts2, pts3, - sigma,beta,xi,acc2,epsnov,eddfac,gamma) - self.assertEqual(status,0) + sigma, beta, xi, acc2, epsnov, eddfac, gamma) + self.assertEqual(status, 0) instance.stop() - + def test2(self): print("Test basic operations (legacy functions evolve & get_time_step)...") instance = BSEInterface() - status = instance.initialize(0.02, 0.5, 0.0, 0.5, 1.0, 0.5, 0, 1, 0, 1, 0, 1, 3.0, + status = instance.initialize(0.02, 0.5, 0.0, 0.5, 1.0, 0.5, 0, 1, 0, 1, 0, 1, 3.0, 29769, 0.05, 0.01, 0.02, 190.0, 1.0/8.0, 1.0, 3.0/2.0, 0.001, 1.0, -1.0) - + new_state = self.state() new_state.mass1 = 3.0 new_state.mass2 = 1.0 @@ -91,49 +92,49 @@ def test2(self): new_state.end_time = 1e-06 new_state.orbital_period = 200.0 new_state.eccentricity = 0.5 - + result = instance.evolve_binary( - new_state.type1,new_state.type2,new_state.initial_mass1,new_state.initial_mass2, - new_state.mass1, new_state.mass2, new_state.radius1, new_state.radius2, - new_state.luminosity1, new_state.luminosity2, new_state.core_mass1, + new_state.type1, new_state.type2, new_state.initial_mass1, new_state.initial_mass2, + new_state.mass1, new_state.mass2, new_state.radius1, new_state.radius2, + new_state.luminosity1, new_state.luminosity2, new_state.core_mass1, new_state.core_mass2, new_state.core_radius1, new_state.core_radius2, new_state.envelope_mass1, new_state.envelope_mass2, new_state.envelope_radius1, new_state.envelope_radius2, new_state.spin1, new_state.spin2, new_state.epoch1, new_state.epoch2, new_state.t_ms1, new_state.t_ms2, new_state.bse_age, new_state.orbital_period, new_state.eccentricity, new_state.end_time ) - + updated_state = self.state() - (updated_state.type1,updated_state.type2,updated_state.initial_mass1,updated_state.initial_mass2, - updated_state.mass1, updated_state.mass2, updated_state.radius1, updated_state.radius2, + (updated_state.type1, updated_state.type2, updated_state.initial_mass1, updated_state.initial_mass2, + updated_state.mass1, updated_state.mass2, updated_state.radius1, updated_state.radius2, updated_state.luminosity1, updated_state.luminosity2, updated_state.core_mass1, updated_state.core_mass2, updated_state.core_radius1, updated_state.core_radius2, - updated_state.envelope_mass1,updated_state.envelope_mass2,updated_state.envelope_radius1, + updated_state.envelope_mass1, updated_state.envelope_mass2, updated_state.envelope_radius1, updated_state.envelope_radius2, updated_state.spin1, updated_state.spin2, updated_state.epoch1, updated_state.epoch2, updated_state.t_ms1, updated_state.t_ms2, updated_state.bse_age, updated_state.orbital_period, - updated_state.eccentricity, updated_state.end_time) = result - + updated_state.eccentricity, updated_state.end_time) = result + expected = { - 'radius2' : '0x1.c6c8a1c793bcep-1', - 'luminosity2' : '0x1.653b1b2d0333bp-1', - 'core_mass2' : '0x0.0p+0', - 'bse_age' : '0x1.0c6f7a0b5ed8dp-20', - 'end_time' : '0x1.0c6f7a0b5ed8dp-20', - 'envelope_mass2' : '0x1.0d6fc100ab510p-5', - 'mass2' : '0x1.0000000000000p+0', - 'initial_mass2' : '0x1.0000000000000p+0', - 'envelope_radius2' : '0x1.db27631ba0e5ap-3', - 'core_radius2' : '0x0.0p+0', - 'epoch2' : '0x0.0p+0', - 't_ms2' : '0x1.57d90abe54643p+13', - 'spin2' : '0x1.07413b0522aebp+10', - }; + 'radius2': '0x1.c6c8a1c793bcep-1', + 'luminosity2': '0x1.653b1b2d0333bp-1', + 'core_mass2': '0x0.0p+0', + 'bse_age': '0x1.0c6f7a0b5ed8dp-20', + 'end_time': '0x1.0c6f7a0b5ed8dp-20', + 'envelope_mass2': '0x1.0d6fc100ab510p-5', + 'mass2': '0x1.0000000000000p+0', + 'initial_mass2': '0x1.0000000000000p+0', + 'envelope_radius2': '0x1.db27631ba0e5ap-3', + 'core_radius2': '0x0.0p+0', + 'epoch2': '0x0.0p+0', + 't_ms2': '0x1.57d90abe54643p+13', + 'spin2': '0x1.07413b0522aebp+10', + } for x in expected: - #print "'%s' : '%s'," % (x, getattr(updated_state, x).hex()) - self.assertAlmostRelativeEqual(float.fromhex(expected[x]),getattr(updated_state, x)) - + # print "'%s' : '%s'," % (x, getattr(updated_state, x).hex()) + self.assertAlmostRelativeEqual(float.fromhex(expected[x]), getattr(updated_state, x)) + self.assertEqual(updated_state.end_time, 1e-06) dt = instance.get_time_step(updated_state.type1, updated_state.type2, updated_state.initial_mass1, updated_state.initial_mass2, updated_state.mass1, @@ -141,25 +142,25 @@ def test2(self): updated_state.epoch1, updated_state.epoch2, updated_state.bse_age) self.assertAlmostEqual(dt, 18.8768, 3) instance.stop() - + def test3(self): print("Test whether the interface can handle arrays...") instance = BSEInterface() - status = instance.initialize(0.02, 0.5, 0.0, 0.5, 1.0, 0.5, 0, 1, 0, 1, 0, 1, 3.0, + status = instance.initialize(0.02, 0.5, 0.0, 0.5, 1.0, 0.5, 0, 1, 0, 1, 0, 1, 3.0, 29769, 0.05, 0.01, 0.02, 190.0, 1.0/8.0, 1.0, 3.0/2.0, 0.001, 1.0, -1.0) - masses1 = [10.0,5.0,4.0] - masses2 = [1.0,1.0,1.0] - types1 = types2 = [1,1,1] - orbital_periods = [100.0,200.0,300.0] - eccentricities = [0.5,0.6,0.7] - - radii1 = luminosity1 = core_mass1 = core_radius1 = envelope_mass1 =\ - envelope_radius1 = spin1 = epoch1 = t_ms1 = [0.0,0.0,0.0] - radii2 = luminosity2 = core_mass2 = core_radius2 = envelope_mass2 =\ - envelope_radius2 = spin2 = epoch2 = t_ms2 = [0.0,0.0,0.0] + masses1 = [10.0, 5.0, 4.0] + masses2 = [1.0, 1.0, 1.0] + types1 = types2 = [1, 1, 1] + orbital_periods = [100.0, 200.0, 300.0] + eccentricities = [0.5, 0.6, 0.7] + + radii1 = luminosity1 = core_mass1 = core_radius1 = envelope_mass1 =\ + envelope_radius1 = spin1 = epoch1 = t_ms1 = [0.0, 0.0, 0.0] + radii2 = luminosity2 = core_mass2 = core_radius2 = envelope_mass2 =\ + envelope_radius2 = spin2 = epoch2 = t_ms2 = [0.0, 0.0, 0.0] init_mass1 = masses1 init_mass2 = masses2 - bse_age = [0.0,0.0,0.0] + bse_age = [0.0, 0.0, 0.0] end_time = [10.0, 10.0, 10.0] result = instance.evolve_binary( types1, types2, init_mass1, init_mass2, @@ -167,50 +168,50 @@ def test3(self): luminosity1, luminosity2, core_mass1, core_mass2, core_radius1, core_radius2, envelope_mass1, envelope_mass2, envelope_radius1, envelope_radius2, spin1, spin2, - epoch1, epoch2, t_ms1, t_ms2, + epoch1, epoch2, t_ms1, t_ms2, bse_age, orbital_periods, eccentricities, end_time ) self.assertAlmostEqual(result['mass1'][0], 9.977, 2) self.assertAlmostEqual(result['mass1'][1], 5.0, 2) self.assertAlmostEqual(result['mass1'][2], 4.0, 2) instance.stop() - + def test4(self): print("Test large number of particles...") number_of_particles = 2000 instance = BSEInterface() - status = instance.initialize(0.02, 0.5, 0.0, 0.5, 1.0, 0.5, 0, 1, 0, 1, 0, 1, 3.0, + status = instance.initialize(0.02, 0.5, 0.0, 0.5, 1.0, 0.5, 0, 1, 0, 1, 0, 1, 3.0, 29769, 0.05, 0.01, 0.02, 190.0, 1.0/8.0, 1.0, 3.0/2.0, 0.001, 1.0, -1.0) - masses1 = [1.0 + ((x / 1.0*number_of_particles) * 10.0) for x in range(1,number_of_particles+1)] - masses2 = [2.0 + ((x / 1.0*number_of_particles) * 5.0) for x in range(1,number_of_particles+1)] - orbital_periods = [100.0 + ((x / 1.0*number_of_particles) * 900.0) for x in range(1,number_of_particles+1)] - eccentricities = [0.5 + ((x / 1.0*number_of_particles) * 0.4) for x in range(1,number_of_particles+1)] - - types1 = types2 = [1 for x in range(1,number_of_particles+1)] - radii1 = luminosity1 = core_mass1 = core_radius1 = envelope_mass1 =\ - envelope_radius1 = spin1 = epoch1 = t_ms1 =\ - radii2 = luminosity2 = core_mass2 = core_radius2 = envelope_mass2 =\ - envelope_radius2 = spin2 = epoch2 = t_ms2 =\ - bse_age = [0.0 for x in range(1,number_of_particles+1)] - end_time = [1.0 for x in range(1,number_of_particles+1)] + masses1 = [1.0 + ((x / 1.0*number_of_particles) * 10.0) for x in range(1, number_of_particles+1)] + masses2 = [2.0 + ((x / 1.0*number_of_particles) * 5.0) for x in range(1, number_of_particles+1)] + orbital_periods = [100.0 + ((x / 1.0*number_of_particles) * 900.0) for x in range(1, number_of_particles+1)] + eccentricities = [0.5 + ((x / 1.0*number_of_particles) * 0.4) for x in range(1, number_of_particles+1)] + + types1 = types2 = [1 for x in range(1, number_of_particles+1)] + radii1 = luminosity1 = core_mass1 = core_radius1 = envelope_mass1 =\ + envelope_radius1 = spin1 = epoch1 = t_ms1 =\ + radii2 = luminosity2 = core_mass2 = core_radius2 = envelope_mass2 =\ + envelope_radius2 = spin2 = epoch2 = t_ms2 =\ + bse_age = [0.0 for x in range(1, number_of_particles+1)] + end_time = [1.0 for x in range(1, number_of_particles+1)] init_mass1 = masses1 init_mass2 = masses2 - + result = instance.evolve_binary( types1, types2, init_mass1, init_mass2, masses1, masses2, radii1, radii2, luminosity1, luminosity2, core_mass1, core_mass2, core_radius1, core_radius2, envelope_mass1, envelope_mass2, envelope_radius1, envelope_radius2, spin1, spin2, - epoch1, epoch2, t_ms1, t_ms2, + epoch1, epoch2, t_ms1, t_ms2, bse_age, orbital_periods, eccentricities, end_time ) self.assertEqual(len(result['mass1']), number_of_particles) instance.stop() - + class TestBSE(TestWithMPI): - + def test1(self): print("Testing evolution of a close binary system...") instance = BSE() @@ -219,35 +220,35 @@ def test1(self): instance.parameters.common_envelope_efficiency = 3.0 instance.parameters.Eddington_mass_transfer_limit_factor = 10.0 instance.commit_parameters() - stars = Particles(2) + stars = Particles(2) stars[0].mass = 3.0 | units.MSun stars[1].mass = 0.3 | units.MSun - + orbital_period = 200.0 | units.day - semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass , stars[1].mass) - + semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass, stars[1].mass) + instance.particles.add_particles(stars) - - binaries = Particles(1) - + + binaries = Particles(1) + binary = binaries[0] binary.semi_major_axis = semi_major_axis binary.eccentricity = 0.5 binary.child1 = stars[0] binary.child2 = stars[1] - + instance.binaries.add_particles(binaries) - + from_bse_to_model = instance.particles.new_channel_to(stars) from_bse_to_model.copy() from_bse_to_model_binaries = instance.binaries.new_channel_to(binaries) from_bse_to_model_binaries.copy() - + previous_type = binary.child1.stellar_type results = [] current_time = 0 | units.Myr - + while current_time < (480 | units.Myr): instance.update_time_steps() # The next line appears a bit weird, but saves time for this simple test. @@ -258,9 +259,9 @@ def test1(self): if not binary.child1.stellar_type == previous_type: results.append((binary.age, binary.child1.mass, binary.child1.stellar_type)) previous_type = binary.child1.stellar_type - + self.assertEqual(len(results), 6) - + types = ( "Hertzsprung Gap", "First Giant Branch", @@ -269,34 +270,34 @@ def test1(self): "Hertzsprung Gap Naked Helium star", "Carbon/Oxygen White Dwarf", ) - + for result, expected in zip(results, types): self.assertEqual(str(result[2]), expected) - - times = ( - 284.8516 | units.Myr, - 287.0595 | units.Myr, - 287.7848 | units.Myr, - 331.1454 | units.Myr, - 331.3983 | units.Myr, + + times = ( + 284.8516 | units.Myr, + 287.0595 | units.Myr, + 287.7848 | units.Myr, + 331.1454 | units.Myr, + 331.3983 | units.Myr, 332.2786 | units.Myr, ) for result, expected in zip(results, times): self.assertAlmostEqual(result[0].value_in(units.Myr), expected.value_in(units.Myr), 0) - - masses = ( - 3.000 | units.MSun, - 3.000 | units.MSun, - 2.999 | units.MSun, + + masses = ( + 3.000 | units.MSun, + 3.000 | units.MSun, + 2.999 | units.MSun, 2.956 | units.MSun, 0.888 | units.MSun, 0.707 | units.MSun, ) for result, expected in zip(results, masses): self.assertAlmostEqual(result[1].value_in(units.MSun), expected.value_in(units.MSun), 2) - + instance.stop() - + def test2(self): print("Testing evolution of a wide binary system.") instance = BSE() @@ -304,35 +305,35 @@ def test2(self): instance.parameters.common_envelope_efficiency = 3.0 instance.parameters.Eddington_mass_transfer_limit_factor = 10.0 instance.commit_parameters() - - stars = Particles(2) + + stars = Particles(2) stars[0].mass = 3.0 | units.MSun stars[1].mass = 0.3 | units.MSun - orbital_period = 2.0e5 | units.day - semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass , stars[1].mass) - + orbital_period = 2.0e5 | units.day + semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass, stars[1].mass) + instance.particles.add_particles(stars) - - binaries = Particles(1) - + + binaries = Particles(1) + binary = binaries[0] binary.semi_major_axis = semi_major_axis binary.eccentricity = 0.5 binary.child1 = stars[0] binary.child2 = stars[1] - + instance.binaries.add_particles(binaries) - + from_bse_to_model = instance.particles.new_channel_to(stars) from_bse_to_model.copy() from_bse_to_model_binaries = instance.binaries.new_channel_to(binaries) from_bse_to_model_binaries.copy() - + previous_type = binary.child1.stellar_type results = [] current_time = 0 | units.Myr - + while current_time < (335 | units.Myr): instance.update_time_steps() # The next line appears a bit weird, but saves time for this simple test. @@ -345,29 +346,29 @@ def test2(self): previous_type = binary.child1.stellar_type print(results) self.assertEqual(len(results), 6) - - times = ( - 284.8516 | units.Myr, - 287.0595 | units.Myr, - 287.7848 | units.Myr, + + times = ( + 284.8516 | units.Myr, + 287.0595 | units.Myr, + 287.7848 | units.Myr, 331.1454 | units.Myr, 332.7407 | units.Myr, 333.4146 | units.Myr ) for result, expected in zip(results, times): self.assertAlmostEqual(result[0].value_in(units.Myr), expected.value_in(units.Myr), 0) - - masses = ( - 3.000 | units.MSun, - 3.000 | units.MSun, - 2.999 | units.MSun, + + masses = ( + 3.000 | units.MSun, + 3.000 | units.MSun, + 2.999 | units.MSun, 2.956 | units.MSun, 2.919 | units.MSun, 0.928 | units.MSun ) for result, expected in zip(results, masses): self.assertAlmostEqual(result[1].value_in(units.MSun), expected.value_in(units.MSun), 2) - + types = ( "Hertzsprung Gap", "First Giant Branch", @@ -376,72 +377,71 @@ def test2(self): "Second Asymptotic Giant Branch", "Carbon/Oxygen White Dwarf", ) - + for result, expected in zip(results, types): self.assertEqual(str(result[2]), expected) - + instance.stop() - + def test3(self): print("Testing standard BSE example 2...") instance = BSE() instance.parameters.common_envelope_efficiency = 3.0 instance.parameters.Eddington_mass_transfer_limit_factor = 10.0 instance.commit_parameters() - - stars = Particles(2) + + stars = Particles(2) stars[0].mass = 7.816 | units.MSun stars[1].mass = 4.387 | units.MSun - - orbital_period = 1964.18453 | units.day - semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass , stars[1].mass) + + orbital_period = 1964.18453 | units.day + semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass, stars[1].mass) instance.particles.add_particles(stars) - - binaries = Particles(1) - + + binaries = Particles(1) + binary = binaries[0] binary.semi_major_axis = semi_major_axis binary.eccentricity = 0.0 binary.child1 = stars[0] binary.child2 = stars[1] - + instance.binaries.add_particles(binaries) - + from_bse_to_model = instance.particles.new_channel_to(stars) from_bse_to_model.copy() from_bse_to_model_binaries = instance.binaries.new_channel_to(binaries) from_bse_to_model_binaries.copy() - + previous_type1 = binary.child1.stellar_type previous_type2 = binary.child2.stellar_type results = [] current_time = 0 | units.Myr - + while current_time < (170 | units.Myr): instance.update_time_steps() # The next line appears a bit weird, but saves time for this simple test. current_time = current_time + max(2.0*instance.binaries[0].time_step, 0.04 | units.Myr) instance.evolve_model(current_time) from_bse_to_model.copy() - from_bse_to_model_binaries.copy() - if not (binary.child1.stellar_type == previous_type1 and binary.child2.stellar_type == previous_type2): + from_bse_to_model_binaries.copy() + if not (binary.child1.stellar_type == previous_type1 and binary.child2.stellar_type == previous_type2): results.append((binary.age, str(binary.child1.stellar_type)+" and "+str(binary.child2.stellar_type))) previous_type1 = binary.child1.stellar_type previous_type2 = binary.child2.stellar_type - - + print('\n'.join(map(str, results))) self.assertEqual(len(results), 13) - times = ( - 38.9708 | units.Myr, - 39.0897 | units.Myr, - 39.1213 | units.Myr, + times = ( + 38.9708 | units.Myr, + 39.0897 | units.Myr, + 39.1213 | units.Myr, 43.8025 | units.Myr, 43.9923 | units.Myr, 44.0686 | units.Myr, - 141.7077 | units.Myr, - 142.3448 | units.Myr, + 141.7077 | units.Myr, + 142.3448 | units.Myr, 142.7827 | units.Myr, 166.1043 | units.Myr, 166.5795 | units.Myr, @@ -450,7 +450,7 @@ def test3(self): ) for result, expected in zip(results, times): self.assertAlmostEqual(result[0].value_in(units.Myr), expected.value_in(units.Myr), 0) - + types = ( "Hertzsprung Gap and Main Sequence star", "First Giant Branch and Main Sequence star", @@ -466,46 +466,46 @@ def test3(self): "Neutron Star and Hertzsprung Gap Naked Helium star", "Neutron Star and Carbon/Oxygen White Dwarf", ) - + for result, expected in zip(results, types): self.assertEqual(result[1], expected) - + self.assertAlmostEqual(binary.child1.mass.value_in(units.MSun), 1.304, 3) self.assertAlmostEqual(binary.child2.mass.value_in(units.MSun), 0.800, 3) - + instance.stop() - + def test4(self): print("Quick testing standard BSE example 2...") instance = BSE() instance.parameters.common_envelope_efficiency = 3.0 instance.parameters.Eddington_mass_transfer_limit_factor = 10.0 instance.commit_parameters() - - stars = Particles(2) + + stars = Particles(2) stars[0].mass = 7.816 | units.MSun stars[1].mass = 4.387 | units.MSun - + instance.particles.add_particles(stars) - - binaries = Particles(1) - + + binaries = Particles(1) + binary = binaries[0] - orbital_period = 1964.18453 | units.day - semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass , stars[1].mass) + orbital_period = 1964.18453 | units.day + semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass, stars[1].mass) binary.semi_major_axis = semi_major_axis binary.eccentricity = 0.0 binary.child1 = stars[0] binary.child2 = stars[1] - + instance.binaries.add_particles(binaries) - + from_bse_to_model = instance.particles.new_channel_to(stars) from_bse_to_model.copy() from_bse_to_model_binaries = instance.binaries.new_channel_to(binaries) from_bse_to_model_binaries.copy() - + instance.evolve_model(170 | units.Myr) from_bse_to_model.copy() from_bse_to_model_binaries.copy() @@ -516,7 +516,7 @@ def test4(self): self.assertEqual(str(binary.child2.stellar_type), "Carbon/Oxygen White Dwarf") instance.stop() - + def test5(self): print("Testing stellar collision...") instance = BSE() @@ -524,32 +524,32 @@ def test5(self): instance.parameters.Eddington_mass_transfer_limit_factor = 10.0 instance.commit_parameters() - stars = Particles(2) - stars[0].mass = 3.0 | units.MSun + stars = Particles(2) + stars[0].mass = 3.0 | units.MSun stars[1].mass = 0.3 | units.MSun - + instance.particles.add_particles(stars) - - binaries = Particles(1) - + + binaries = Particles(1) + binary = binaries[0] - orbital_period = 200.0 | units.day - semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass , stars[1].mass) + orbital_period = 200.0 | units.day + semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass, stars[1].mass) binary.semi_major_axis = semi_major_axis binary.eccentricity = 0.99 binary.child1 = stars[0] binary.child2 = stars[1] - + instance.binaries.add_particles(binaries) - + from_bse_to_model = instance.particles.new_channel_to(stars) from_bse_to_model.copy() from_bse_to_model_binaries = instance.binaries.new_channel_to(binaries) from_bse_to_model_binaries.copy() - + instance.evolve_model(170 | units.Myr) - + from_bse_to_model.copy() from_bse_to_model_binaries.copy() print(binaries) @@ -559,8 +559,7 @@ def test5(self): self.assertEqual(str(binary.child2.stellar_type), "Massless Supernova") instance.stop() - - + def test6(self): print("Testing additional parameters for initialization...") instance = BSE() @@ -572,7 +571,7 @@ def test6(self): instance.commit_parameters() self.assertEqual(instance.parameters.reimers_mass_loss_coefficient, myvalue) instance.stop() - + instance = BSE() self.assertEqual(instance.parameters.reimers_mass_loss_coefficient, 0.5) myvalue = 0.7 @@ -581,121 +580,118 @@ def test6(self): instance.commit_parameters() self.assertEqual(instance.parameters.reimers_mass_loss_coefficient, 0.5) instance.stop() - + def test7(self): print("Test evolve_model optional arguments: end_time and keep_synchronous") instance = BSE() instance.commit_parameters() - - stars = Particles(6) - stars.mass = [1.0,2.0,3.0, 0.1, 0.2, 0.3] | units.MSun - - binaries = Particles(3) + + stars = Particles(6) + stars.mass = [1.0, 2.0, 3.0, 0.1, 0.2, 0.3] | units.MSun + + binaries = Particles(3) binaries.eccentricity = 0.0 for i in range(3): binaries[i].child1 = stars[i] binaries[i].child2 = stars[i+3] - orbital_period = 200.0 | units.day + orbital_period = 200.0 | units.day semi_major_axis = instance.orbital_period_to_semi_major_axis( - orbital_period, - binaries.child1.as_set().mass , + orbital_period, + binaries.child1.as_set().mass, binaries.child2.as_set().mass ) binaries.semi_major_axis = semi_major_axis - - - instance.particles.add_particles(stars) instance.binaries.add_particles(binaries) - + self.assertAlmostEqual(instance.binaries.age, [0.0, 0.0, 0.0] | units.yr) self.assertAlmostEqual(instance.binaries.time_step, [550.1565, 58.2081, 18.8768] | units.Myr, 3) - + print("evolve_model without arguments: use shared timestep = min(particles.time_step)") instance.evolve_model() self.assertAlmostEqual(instance.binaries.age, [18.8768, 18.8768, 18.8768] | units.Myr, 3) self.assertAlmostEqual(instance.binaries.time_step, [550.1565, 58.2081, 18.8768] | units.Myr, 3) self.assertAlmostEqual(instance.model_time, 18.8768 | units.Myr, 3) - + print("evolve_model with end_time: take timesteps, until end_time is reached exactly") instance.evolve_model(100 | units.Myr) self.assertAlmostEqual(instance.binaries.age, [100.0, 100.0, 100.0] | units.Myr, 3) self.assertAlmostEqual(instance.binaries.time_step, [550.1565, 58.2081, 18.8768] | units.Myr, 3) self.assertAlmostEqual(instance.model_time, 100.0 | units.Myr, 3) - + print("evolve_model with keep_synchronous: use non-shared timestep, particle ages will typically diverge") - instance.evolve_model(keep_synchronous = False) + instance.evolve_model(keep_synchronous=False) self.assertAlmostEqual(instance.binaries.age, (100 | units.Myr) + ([550.1565, 58.2081, 18.8768] | units.Myr), 3) self.assertAlmostEqual(instance.binaries.time_step, [550.1565, 58.2081, 18.8768] | units.Myr, 3) - self.assertAlmostEqual(instance.model_time, 100.0 | units.Myr, 3) # Unchanged! + self.assertAlmostEqual(instance.model_time, 100.0 | units.Myr, 3) # Unchanged! instance.stop() - + def test8(self): print("Testing adding and removing particles from stellar evolution code...") - + instance = BSE() instance.initialize_code() - - stars = Particles(6) - stars.mass = [1.0,1.0, 1.0, 0.2, 0.2, 0.2] | units.MSun - - binaries = Particles(3) + + stars = Particles(6) + stars.mass = [1.0, 1.0, 1.0, 0.2, 0.2, 0.2] | units.MSun + + binaries = Particles(3) binaries.eccentricity = 0.0 for i in range(3): binaries[i].child1 = stars[i] binaries[i].child2 = stars[i+3] - orbital_period = 200.0 | units.day + orbital_period = 200.0 | units.day semi_major_axis = instance.orbital_period_to_semi_major_axis( - orbital_period, - binaries.child1.as_set().mass , + orbital_period, + binaries.child1.as_set().mass, binaries.child2.as_set().mass ) binaries.semi_major_axis = semi_major_axis instance.commit_parameters() self.assertEqual(len(instance.particles), 0) - self.assertEqual(len(instance.binaries), 0) # before creation + self.assertEqual(len(instance.binaries), 0) # before creation instance.particles.add_particles(stars) instance.binaries.add_particles(binaries[:-1]) instance.commit_particles() instance.evolve_model(1.0 | units.Myr) - self.assertEqual(len(instance.binaries), 2) # before remove + self.assertEqual(len(instance.binaries), 2) # before remove self.assertAlmostEqual(instance.binaries.age, 1.0 | units.Myr) - + instance.binaries.remove_particle(binaries[0]) self.assertEqual(len(instance.binaries), 1) instance.evolve_model(2.0 | units.Myr) self.assertAlmostEqual(instance.binaries[0].age, 2.0 | units.Myr) - + instance.binaries.add_particles(binaries[::2]) - self.assertEqual(len(instance.binaries), 3) # it's back... + self.assertEqual(len(instance.binaries), 3) # it's back... self.assertAlmostEqual(instance.binaries[0].age, 2.0 | units.Myr) self.assertAlmostEqual(instance.binaries[1].age, 0.0 | units.Myr) - self.assertAlmostEqual(instance.binaries[2].age, 0.0 | units.Myr) # ... and rejuvenated. - - instance.evolve_model(3.0 | units.Myr) # The young stars keep their age offset from the old star + self.assertAlmostEqual(instance.binaries[2].age, 0.0 | units.Myr) # ... and rejuvenated. + + instance.evolve_model(3.0 | units.Myr) # The young stars keep their age offset from the old star self.assertAlmostEqual(instance.binaries.age, [3.0, 1.0, 1.0] | units.Myr) instance.evolve_model(4.0 | units.Myr) self.assertAlmostEqual(instance.binaries.age, [4.0, 2.0, 2.0] | units.Myr) instance.stop() - + def test9(self): print("Testing BSE states") instance = BSE() - - stars = Particles(2) - stars.mass = [1.0, 0.2] | units.MSun - - binaries = Particles(1) - orbital_period = 200.0 | units.day - semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass , stars[1].mass) + + stars = Particles(2) + stars.mass = [1.0, 0.2] | units.MSun + + binaries = Particles(1) + orbital_period = 200.0 | units.day + semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass, stars[1].mass) binaries.semi_major_axis = semi_major_axis binaries.eccentricity = 0.0 binaries[0].child1 = stars[0] binaries[0].child2 = stars[1] - + print("First do everything manually:", end=' ') self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') instance.initialize_code() @@ -707,7 +703,7 @@ def test9(self): instance.stop() print("ok") - print("initialize_code(), commit_parameters(), " \ + print("initialize_code(), commit_parameters(), " "and cleanup_code() should be called automatically:", end=' ') instance = BSE() self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') @@ -719,4 +715,3 @@ def test9(self): instance.stop() self.assertEqual(instance.get_name_of_current_state(), 'STOPPED') print("ok") - diff --git a/src/amuse/test/suite/codes_tests/test_capreole.py b/src/amuse/test/suite/codes_tests/test_capreole.py index 9f0b80e789..afedd08749 100644 --- a/src/amuse/test/suite/codes_tests/test_capreole.py +++ b/src/amuse/test/suite/codes_tests/test_capreole.py @@ -11,235 +11,234 @@ from amuse.units import units from amuse import datamodel + class TestCapreoleInterface(TestWithMPI): - + def test0(self): - instance=CapreoleInterface() + instance = CapreoleInterface() instance.initialize_code() instance.stop() - - + def test1(self): - instance=CapreoleInterface() + instance = CapreoleInterface() instance.initialize_code() - instance.setup_mesh(50,40,30,1.,1.,1.) - nx,ny,nz, error = instance.get_mesh_size() + instance.setup_mesh(50, 40, 30, 1., 1., 1.) + nx, ny, nz, error = instance.get_mesh_size() self.assertEqual(nx, 50) self.assertEqual(ny, 40) self.assertEqual(nz, 30) instance.stop() - + def test2(self): - instance=CapreoleInterface() + instance = CapreoleInterface() instance.initialize_code() - instance.setup_mesh(50,50,50,1.,1.,1.) + instance.setup_mesh(50, 50, 50, 1., 1., 1.) instance.commit_parameters() - instance.set_grid_state(1,1,1,1.,0.1,0.1,0.1,1.) - rho, err=instance.get_grid_density(1,1,1) - self.assertEqual(rho,1.) - rhovx,rhovy,rhovz,err=instance.get_grid_momentum_density(1,1,1) - self.assertEqual(rhovx,0.1) - self.assertEqual(rhovy,0.1) - self.assertEqual(rhovz,0.1) - en,err=instance.get_grid_energy_density(1,1,1) - self.assertEqual(en,1.) - rho,rhovx,rhovy,rhovz,en,err=instance.get_grid_state(1,1,1) - self.assertEqual(rho,1.) - self.assertEqual(rhovx,0.1) - self.assertEqual(rhovy,0.1) - self.assertEqual(rhovz,0.1) - self.assertEqual(en,1.) + instance.set_grid_state(1, 1, 1, 1., 0.1, 0.1, 0.1, 1.) + rho, err = instance.get_grid_density(1, 1, 1) + self.assertEqual(rho, 1.) + rhovx, rhovy, rhovz, err = instance.get_grid_momentum_density(1, 1, 1) + self.assertEqual(rhovx, 0.1) + self.assertEqual(rhovy, 0.1) + self.assertEqual(rhovz, 0.1) + en, err = instance.get_grid_energy_density(1, 1, 1) + self.assertEqual(en, 1.) + rho, rhovx, rhovy, rhovz, en, err = instance.get_grid_state(1, 1, 1) + self.assertEqual(rho, 1.) + self.assertEqual(rhovx, 0.1) + self.assertEqual(rhovy, 0.1) + self.assertEqual(rhovz, 0.1) + self.assertEqual(en, 1.) instance.stop() - + def test3(self): - instance=CapreoleInterface() + instance = CapreoleInterface() instance.initialize_code() - instance.setup_mesh(50,50,50,1.,1.,1.) + instance.setup_mesh(50, 50, 50, 1., 1., 1.) instance.commit_parameters() - x,y,z=numpy.indices( (50,50,50) ) - x=x.flatten()+1 - y=y.flatten()+1 - z=z.flatten()+1 - rho=0.25*numpy.ones_like(x) - rhvx=0.*numpy.ones_like(x) - rhvy=0.*numpy.ones_like(x) - rhvz=0.*numpy.ones_like(x) - en=2.*numpy.ones_like(x) - instance.set_grid_state(x,y,z,rho,rhvx,rhvy,rhvz,en) - rho,rhovx,rhovy,rhovz,en,err=instance.get_grid_state(1,1,1) - self.assertEqual(rho,0.25) - self.assertEqual(rhovx,0.) - self.assertEqual(rhovy,0.) - self.assertEqual(rhovz,0.) - self.assertEqual(en,2.) + x, y, z = numpy.indices((50, 50, 50)) + x = x.flatten()+1 + y = y.flatten()+1 + z = z.flatten()+1 + rho = 0.25*numpy.ones_like(x) + rhvx = 0.*numpy.ones_like(x) + rhvy = 0.*numpy.ones_like(x) + rhvz = 0.*numpy.ones_like(x) + en = 2.*numpy.ones_like(x) + instance.set_grid_state(x, y, z, rho, rhvx, rhvy, rhvz, en) + rho, rhovx, rhovy, rhovz, en, err = instance.get_grid_state(1, 1, 1) + self.assertEqual(rho, 0.25) + self.assertEqual(rhovx, 0.) + self.assertEqual(rhovy, 0.) + self.assertEqual(rhovz, 0.) + self.assertEqual(en, 2.) instance.stop() - + def test4(self): - instance=CapreoleInterface() + instance = CapreoleInterface() instance.initialize_code() - instance.setup_mesh(50,50,50,1.,1.,1.) + instance.setup_mesh(50, 50, 50, 1., 1., 1.) instance.commit_parameters() - x,y,z=numpy.indices( (50,50,50) ) - x=x.flatten()+1 - y=y.flatten()+1 - z=z.flatten()+1 - rho=0.1*numpy.ones_like(x) - rhvx=0.*numpy.ones_like(x) - rhvy=0.*numpy.ones_like(x) - rhvz=0.*numpy.ones_like(x) - en=0.1*numpy.ones_like(x) - instance.set_grid_state(x,y,z,rho,rhvx,rhvy,rhvz,en) + x, y, z = numpy.indices((50, 50, 50)) + x = x.flatten()+1 + y = y.flatten()+1 + z = z.flatten()+1 + rho = 0.1*numpy.ones_like(x) + rhvx = 0.*numpy.ones_like(x) + rhvy = 0.*numpy.ones_like(x) + rhvz = 0.*numpy.ones_like(x) + en = 0.1*numpy.ones_like(x) + instance.set_grid_state(x, y, z, rho, rhvx, rhvy, rhvz, en) instance.initialize_grid() instance.stop() - + def test5(self): - instance=CapreoleInterface() + instance = CapreoleInterface() instance.initialize_code() - instance.setup_mesh(40,40,40,1.,1.,1.) + instance.setup_mesh(40, 40, 40, 1., 1., 1.) instance.commit_parameters() - x,y,z=numpy.indices( (40,40,40) ) - x=x.flatten()+1 - y=y.flatten()+1 - z=z.flatten()+1 - rho=0.1*numpy.ones_like(x) - rhvx=0.*numpy.ones_like(x) - rhvy=0.*numpy.ones_like(x) - rhvz=0.*numpy.ones_like(x) - en=0.1*numpy.ones_like(x) - instance.set_grid_state(x,y,z,rho,rhvx,rhvy,rhvz,en) + x, y, z = numpy.indices((40, 40, 40)) + x = x.flatten()+1 + y = y.flatten()+1 + z = z.flatten()+1 + rho = 0.1*numpy.ones_like(x) + rhvx = 0.*numpy.ones_like(x) + rhvy = 0.*numpy.ones_like(x) + rhvz = 0.*numpy.ones_like(x) + en = 0.1*numpy.ones_like(x) + instance.set_grid_state(x, y, z, rho, rhvx, rhvy, rhvz, en) instance.initialize_grid() instance.evolve_model(0.01) - tnow,err=instance.get_time() - self.assertAlmostEqual(tnow,0.01,15) + tnow, err = instance.get_time() + self.assertAlmostEqual(tnow, 0.01, 15) instance.evolve_model(0.025) - tnow,err=instance.get_time() - self.assertAlmostEqual(tnow,0.025,15) + tnow, err = instance.get_time() + self.assertAlmostEqual(tnow, 0.025, 15) instance.evolve_model(0.025001) - tnow,err=instance.get_time() - self.assertAlmostEqual(tnow,0.025001,15) + tnow, err = instance.get_time() + self.assertAlmostEqual(tnow, 0.025001, 15) instance.evolve_model(0.0321) - tnow,err=instance.get_time() - self.assertAlmostEqual(tnow,0.0321,15) + tnow, err = instance.get_time() + self.assertAlmostEqual(tnow, 0.0321, 15) instance.evolve_model(0.0321) - tnow,err=instance.get_time() - self.assertAlmostEqual(tnow,0.0321,15) + tnow, err = instance.get_time() + self.assertAlmostEqual(tnow, 0.0321, 15) instance.evolve_model(0.07) - tnow,err=instance.get_time() - self.assertAlmostEqual(tnow,0.07,15) + tnow, err = instance.get_time() + self.assertAlmostEqual(tnow, 0.07, 15) instance.stop() - + def test6(self): - instance=CapreoleInterface(number_of_workers=1) + instance = CapreoleInterface(number_of_workers=1) instance.initialize_code() - instance.setup_mesh(150,10,30,1.,1.,1.) + instance.setup_mesh(150, 10, 30, 1., 1., 1.) instance.commit_parameters() - x,y,z=numpy.indices( (150,10,30) ) - x=x.flatten()+1 - y=y.flatten()+1 - z=z.flatten()+1 - rho=0.1*numpy.ones_like(x) - rhvx=0.*numpy.ones_like(x) - rhvy=0.*numpy.ones_like(x) - rhvz=0.*numpy.ones_like(x) - en=0.1*numpy.ones_like(x) - instance.set_grid_state(x,y,z,rho,rhvx,rhvy,rhvz,en) + x, y, z = numpy.indices((150, 10, 30)) + x = x.flatten()+1 + y = y.flatten()+1 + z = z.flatten()+1 + rho = 0.1*numpy.ones_like(x) + rhvx = 0.*numpy.ones_like(x) + rhvy = 0.*numpy.ones_like(x) + rhvz = 0.*numpy.ones_like(x) + en = 0.1*numpy.ones_like(x) + instance.set_grid_state(x, y, z, rho, rhvx, rhvy, rhvz, en) instance.initialize_grid() instance.evolve_model(0.01) - x,y,z,err=instance.get_position_of_index(15,5,20) - self.assertAlmostEqual(x,15/150.-1/300.,15) - self.assertAlmostEqual(y,5/10.-1/20.,15) - self.assertAlmostEqual(z,20/30.-1/60.,15) - i,j,k,err=instance.get_index_of_position(x,y,z) - self.assertEqual([i,j,k],[15,5,20]) + x, y, z, err = instance.get_position_of_index(15, 5, 20) + self.assertAlmostEqual(x, 15/150.-1/300., 15) + self.assertAlmostEqual(y, 5/10.-1/20., 15) + self.assertAlmostEqual(z, 20/30.-1/60., 15) + i, j, k, err = instance.get_index_of_position(x, y, z) + self.assertEqual([i, j, k], [15, 5, 20]) instance.stop() def test7(self): - instance=CapreoleInterface() + instance = CapreoleInterface() instance.initialize_code() - instance.setup_mesh(50,50,50,1.,1.,1.) + instance.setup_mesh(50, 50, 50, 1., 1., 1.) instance.commit_parameters() - err=instance.set_gravity_field(1,2,3,1.,0.5,0.25) - self.assertEqual(err,0) - fx,fy,fz,err=instance.get_gravity_field(1,2,3) - self.assertEqual(fx,1.) - self.assertEqual(fy,0.5) - self.assertEqual(fz,0.25) + err = instance.set_gravity_field(1, 2, 3, 1., 0.5, 0.25) + self.assertEqual(err, 0) + fx, fy, fz, err = instance.get_gravity_field(1, 2, 3) + self.assertEqual(fx, 1.) + self.assertEqual(fy, 0.5) + self.assertEqual(fz, 0.25) instance.stop() def test8(self): - instance=CapreoleInterface() + instance = CapreoleInterface() instance.initialize_code() - err=instance.set_boundary("periodic","reflective", - "periodic","reflective", - "periodic","reflective") - self.assertEqual(err,-1) + err = instance.set_boundary("periodic", "reflective", + "periodic", "reflective", + "periodic", "reflective") + self.assertEqual(err, -1) instance.stop() - - instance=CapreoleInterface() + + instance = CapreoleInterface() instance.initialize_code() - err=instance.set_boundary("reflective","periodic", - "periodic","reflective", - "periodic","reflective") - self.assertEqual(err,-2) + err = instance.set_boundary("reflective", "periodic", + "periodic", "reflective", + "periodic", "reflective") + self.assertEqual(err, -2) instance.stop() - - instance=CapreoleInterface() + + instance = CapreoleInterface() instance.initialize_code() - err=instance.set_boundary("periodic","periodic", - "periodic","periodic", - "periodic","periodic") - self.assertEqual(err,0) + err = instance.set_boundary("periodic", "periodic", + "periodic", "periodic", + "periodic", "periodic") + self.assertEqual(err, 0) instance.stop() def test9(self): - instance=CapreoleInterface(number_of_workers=2) + instance = CapreoleInterface(number_of_workers=2) instance.initialize_code() - instance.setup_mesh(50,50,50,1.,1.,1.) + instance.setup_mesh(50, 50, 50, 1., 1., 1.) instance.commit_parameters() - instance.set_grid_state(1,1,1,1.,0.1,0.1,0.1,1.) - instance.set_grid_state(50,50,50,2.,0.2,0.2,0.2,2.) - - rho, err=instance.get_grid_density(1,1,1) - self.assertEqual(rho,1.) - rhovx,rhovy,rhovz,err=instance.get_grid_momentum_density(1,1,1) - self.assertEqual(rhovx,0.1) - self.assertEqual(rhovy,0.1) - self.assertEqual(rhovz,0.1) - en,err=instance.get_grid_energy_density(1,1,1) - self.assertEqual(en,1.) - rho,rhovx,rhovy,rhovz,en,err=instance.get_grid_state(1,1,1) - self.assertEqual(rho,1.) - self.assertEqual(rhovx,0.1) - self.assertEqual(rhovy,0.1) - self.assertEqual(rhovz,0.1) - self.assertEqual(en,1.) - - rho, err=instance.get_grid_density(50,50,50) - self.assertEqual(err,0) - self.assertEqual(rho,2.) - rhovx,rhovy,rhovz,err=instance.get_grid_momentum_density(50,50,50) - self.assertEqual(rhovx,0.2) - self.assertEqual(rhovy,0.2) - self.assertEqual(rhovz,0.2) - en,err=instance.get_grid_energy_density(50,50,50) - self.assertEqual(en,2.) - rho,rhovx,rhovy,rhovz,en,err=instance.get_grid_state(50,50,50) - self.assertEqual(rho,2.) - self.assertEqual(rhovx,0.2) - self.assertEqual(rhovy,0.2) - self.assertEqual(rhovz,0.2) - self.assertEqual(en,2.) + instance.set_grid_state(1, 1, 1, 1., 0.1, 0.1, 0.1, 1.) + instance.set_grid_state(50, 50, 50, 2., 0.2, 0.2, 0.2, 2.) + + rho, err = instance.get_grid_density(1, 1, 1) + self.assertEqual(rho, 1.) + rhovx, rhovy, rhovz, err = instance.get_grid_momentum_density(1, 1, 1) + self.assertEqual(rhovx, 0.1) + self.assertEqual(rhovy, 0.1) + self.assertEqual(rhovz, 0.1) + en, err = instance.get_grid_energy_density(1, 1, 1) + self.assertEqual(en, 1.) + rho, rhovx, rhovy, rhovz, en, err = instance.get_grid_state(1, 1, 1) + self.assertEqual(rho, 1.) + self.assertEqual(rhovx, 0.1) + self.assertEqual(rhovy, 0.1) + self.assertEqual(rhovz, 0.1) + self.assertEqual(en, 1.) + rho, err = instance.get_grid_density(50, 50, 50) + self.assertEqual(err, 0) + self.assertEqual(rho, 2.) + rhovx, rhovy, rhovz, err = instance.get_grid_momentum_density(50, 50, 50) + self.assertEqual(rhovx, 0.2) + self.assertEqual(rhovy, 0.2) + self.assertEqual(rhovz, 0.2) + en, err = instance.get_grid_energy_density(50, 50, 50) + self.assertEqual(en, 2.) + rho, rhovx, rhovy, rhovz, en, err = instance.get_grid_state(50, 50, 50) + self.assertEqual(rho, 2.) + self.assertEqual(rhovx, 0.2) + self.assertEqual(rhovy, 0.2) + self.assertEqual(rhovz, 0.2) + self.assertEqual(en, 2.) instance.stop() - + def test10(self): - instance=self.new_instance(CapreoleInterface) + instance = self.new_instance(CapreoleInterface) instance.initialize_code() - instance.setup_mesh(100,5,5,100.0,0,0) - instance.set_boundary("interface","periodic","periodic","periodic","periodic","periodic") + instance.setup_mesh(100, 5, 5, 100.0, 0, 0) + instance.set_boundary("interface", "periodic", "periodic", "periodic", "periodic", "periodic") instance.commit_parameters() - + minx, maxx, miny, maxy, minz, maxz, error = instance.get_boundary_index_range_inclusive(1) self.assertEqual(error, 0) self.assertEqual(minx, 1) @@ -248,8 +247,8 @@ def test10(self): self.assertEqual(maxy, 5) self.assertEqual(minz, 1) self.assertEqual(maxz, 5) - - for i in range(2,7): + + for i in range(2, 7): minx, maxx, miny, maxy, minz, maxz, error = instance.get_boundary_index_range_inclusive(i) self.assertEqual(error, 0) self.assertEqual(minx, 1) @@ -258,16 +257,15 @@ def test10(self): self.assertEqual(maxy, 1) self.assertEqual(minz, 1) self.assertEqual(maxz, 1) - + def test11(self): - instance=self.new_instance(CapreoleInterface) + instance = self.new_instance(CapreoleInterface) instance.initialize_code() - instance.setup_mesh(100,5,6,100.0,0,0) - instance.set_boundary("interface","interface","interface","interface","interface","interface") + instance.setup_mesh(100, 5, 6, 100.0, 0, 0) + instance.set_boundary("interface", "interface", "interface", "interface", "interface", "interface") instance.commit_parameters() - - - for i in range(1,7): + + for i in range(1, 7): minx, maxx, miny, maxy, minz, maxz, error = instance.get_boundary_index_range_inclusive(i) self.assertEqual(error, 0), self.assertEqual(minx, 1) @@ -285,115 +283,115 @@ def test11(self): self.assertEqual(maxx, 100+4) self.assertEqual(maxy, 5+4) self.assertEqual(maxz, 2) - + def test12(self): - instance=self.new_instance(CapreoleInterface) + instance = self.new_instance(CapreoleInterface) instance.initialize_code() - instance.setup_mesh(100,2,2,100.0,100.0,100.0) - instance.set_boundary("interface","periodic","periodic","periodic","periodic","periodic") + instance.setup_mesh(100, 2, 2, 100.0, 100.0, 100.0) + instance.set_boundary("interface", "periodic", "periodic", "periodic", "periodic", "periodic") instance.commit_parameters() - - for i in [1,2]: + + for i in [1, 2]: error = instance.set_boundary_state( - i,1,1, # index - 1.0 * (i+1), # density - 2.0 * (i+1), 3.0 * (i+1), 4.0 * (i+1), # momentum - 5.0 * (i+1), # energy - 1 # boundary + i, 1, 1, # index + 1.0 * (i+1), # density + 2.0 * (i+1), 3.0 * (i+1), 4.0 * (i+1), # momentum + 5.0 * (i+1), # energy + 1 # boundary ) self.assertEqual(error, 0) rho, rhovx, rhovy, rhovz, rhoen, error = instance.get_boundary_state( i, 1, 1, 1 ) - print(rho, rhovx, rhovy, rhovz, rhoen, error) + print(rho, rhovx, rhovy, rhovz, rhoen, error) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(rho, 1.0 * (i+1)) self.assertAlmostRelativeEquals(rhovx, 2.0 * (i+1)) self.assertAlmostRelativeEquals(rhovy, 3.0 * (i+1)) self.assertAlmostRelativeEquals(rhovz, 4.0 * (i+1)) self.assertAlmostRelativeEquals(rhoen, 5.0 * (i+1)) - + def test13(self): - instance=self.new_instance(CapreoleInterface) + instance = self.new_instance(CapreoleInterface) instance.initialize_code() - instance.setup_mesh(100,2,2,100.0,0,0) - instance.set_boundary("interface","interface","periodic","periodic","periodic","periodic") + instance.setup_mesh(100, 2, 2, 100.0, 0, 0) + instance.set_boundary("interface", "interface", "periodic", "periodic", "periodic", "periodic") instance.commit_parameters() - - for i in [1,2]: - for j in [1,2]: + + for i in [1, 2]: + for j in [1, 2]: error = instance.set_boundary_state( - i,1,1, # index - 1.0 * (i+1), # density - 2.0 * (i+1), 3.0 * (i+1), 4.0 * (i+1), # momentum - 5.0 * (i+1), # energy - j # boundary + i, 1, 1, # index + 1.0 * (i+1), # density + 2.0 * (i+1), 3.0 * (i+1), 4.0 * (i+1), # momentum + 5.0 * (i+1), # energy + j # boundary ) self.assertEqual(error, 0) rho, rhovx, rhovy, rhovz, rhoen, error = instance.get_boundary_state( - i, 1,1, + i, 1, 1, j ) print(j) self.assertEqual(error, 0) - + self.assertAlmostRelativeEquals(rho, 1.0 * (i+1)) self.assertAlmostRelativeEquals(rhovx, 2.0 * (i+1)) self.assertAlmostRelativeEquals(rhovy, 3.0 * (i+1)) self.assertAlmostRelativeEquals(rhovz, 4.0 * (i+1)) self.assertAlmostRelativeEquals(rhoen, 5.0 * (i+1)) - + def test14(self): - instance=self.new_instance(CapreoleInterface) + instance = self.new_instance(CapreoleInterface) instance.initialize_code() - instance.setup_mesh(5,6,7,100.0,100.0,100.0) - instance.set_boundary("interface","interface","interface","interface","interface","interface") + instance.setup_mesh(5, 6, 7, 100.0, 100.0, 100.0) + instance.set_boundary("interface", "interface", "interface", "interface", "interface", "interface") instance.commit_parameters() - - x1range = (2,6,7) - x2range = (5+4,2,7) - x3range = (5+4,6+4,2) - - for xrange, j in zip([x1range, x1range, x2range, x2range, x3range, x3range], [1,2,3,4,5,6]): + + x1range = (2, 6, 7) + x2range = (5+4, 2, 7) + x3range = (5+4, 6+4, 2) + + for xrange, j in zip([x1range, x1range, x2range, x2range, x3range, x3range], [1, 2, 3, 4, 5, 6]): for i0 in range(xrange[0]): for j0 in range(xrange[1]): for k0 in range(xrange[2]): i = (i0 * (xrange[2] * xrange[1])) + (j0 * xrange[2]) + k0 print("boundary:", j, i0+1, j0+1, k0+1) error = instance.set_boundary_state( - i0+1, j0+1, k0+1, # index - 1.0 * (i+1), # density - 2.0 * (i+1), 3.0 * (i+1), 4.0 * (i+1), # momentum - 5.0 * (i+1), # energy + i0+1, j0+1, k0+1, # index + 1.0 * (i+1), # density + 2.0 * (i+1), 3.0 * (i+1), 4.0 * (i+1), # momentum + 5.0 * (i+1), # energy j ) self.assertEqual(error, 0) rho, rhovx, rhovy, rhovz, rhoen, error = instance.get_boundary_state( - i0+1, j0+1, k0+1, # index + i0+1, j0+1, k0+1, # index j ) self.assertEqual(error, 0) - + self.assertAlmostRelativeEquals(rho, 1.0 * (i+1)) self.assertAlmostRelativeEquals(rhovx, 2.0 * (i+1)) self.assertAlmostRelativeEquals(rhovy, 3.0 * (i+1)) self.assertAlmostRelativeEquals(rhovz, 4.0 * (i+1)) self.assertAlmostRelativeEquals(rhoen, 5.0 * (i+1)) - + def test15(self): - instance=self.new_instance(CapreoleInterface) + instance = self.new_instance(CapreoleInterface) instance.initialize_code() - instance.setup_mesh(100,5,4,100.0,100.0, 100.0) - instance.set_boundary("interface","interface","periodic","periodic","periodic","periodic") + instance.setup_mesh(100, 5, 4, 100.0, 100.0, 100.0) + instance.set_boundary("interface", "interface", "periodic", "periodic", "periodic", "periodic") instance.commit_parameters() - + dx = 100.0 / 100.0 dy = 100.0 / 5.0 dz = 100.0 / 4.0 - - for i in [1,2]: - x,y,z,error = instance.get_boundary_position_of_index( + + for i in [1, 2]: + x, y, z, error = instance.get_boundary_position_of_index( i, 1, 1, 1 ) @@ -401,140 +399,137 @@ def test15(self): self.assertAlmostRelativeEquals(x, (0.5 * dx) - (i * dx)) self.assertAlmostRelativeEquals(y, (0.5 * dy)) self.assertAlmostRelativeEquals(z, (0.5 * dz)) - + def test16(self): - instance=self.new_instance(CapreoleInterface) + instance = self.new_instance(CapreoleInterface) instance.initialize_code() - instance.setup_mesh(100,5,4,100.0,100.0, 100.0) - instance.set_boundary("interface","interface","periodic","periodic","periodic","periodic") + instance.setup_mesh(100, 5, 4, 100.0, 100.0, 100.0) + instance.set_boundary("interface", "interface", "periodic", "periodic", "periodic", "periodic") instance.commit_parameters() - + dx = 100.0 / 100.0 dy = 100.0 / 5.0 dz = 100.0 / 4.0 - - for i in [1,2]: - x,y,z,error = instance.get_boundary_position_of_index( - i,1,1, + + for i in [1, 2]: + x, y, z, error = instance.get_boundary_position_of_index( + i, 1, 1, 2 ) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(x, 100.0 + (0.5 * dx) + ((i-1) * dx)) self.assertAlmostRelativeEquals(y, (0.5 * dy)) self.assertAlmostRelativeEquals(z, (0.5 * dz)) - + def test17(self): - instance=self.new_instance(CapreoleInterface) + instance = self.new_instance(CapreoleInterface) instance.initialize_code() - instance.setup_mesh(100,5,4,100.0,100.0, 100.0) - instance.set_boundary("interface","interface","interface","interface","periodic","periodic") + instance.setup_mesh(100, 5, 4, 100.0, 100.0, 100.0) + instance.set_boundary("interface", "interface", "interface", "interface", "periodic", "periodic") instance.commit_parameters() - + dx = 100.0 / 100.0 dy = 100.0 / 5.0 dz = 100.0 / 4.0 - - for i in [1,2]: - for j in range(1,6): - x,y,z,error = instance.get_boundary_position_of_index( - i, j, 1, + + for i in [1, 2]: + for j in range(1, 6): + x, y, z, error = instance.get_boundary_position_of_index( + i, j, 1, 2 ) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(x, 100.0 + (0.5 * dx) + ((i-1) * dx)) self.assertAlmostRelativeEquals(y, (0.5 * dy) + ((j-1) * dy)) self.assertAlmostRelativeEquals(z, (0.5 * dz)) - + for i in range(1, 100 + 4 + 1): - for j in [1,2]: - x,y,z,error = instance.get_boundary_position_of_index( - i, j, 1, + for j in [1, 2]: + x, y, z, error = instance.get_boundary_position_of_index( + i, j, 1, 3 ) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(x, (0.5 * dx) + ((i-2-1) * dx)) self.assertAlmostRelativeEquals(y, 0.0 - ((0.5 * dy) + ((j-1) * dy))) self.assertAlmostRelativeEquals(z, (0.5 * dz)) - - - x,y,z,error = instance.get_boundary_position_of_index( - i, j, 1, + + x, y, z, error = instance.get_boundary_position_of_index( + i, j, 1, 4 ) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(x, (0.5 * dx) + ((i-2-1) * dx)) self.assertAlmostRelativeEquals(y, 100.0 + (0.5 * dy) + ((j-1) * dy)) self.assertAlmostRelativeEquals(z, (0.5 * dz)) - + def test18(self): - instance=self.new_instance(CapreoleInterface) + instance = self.new_instance(CapreoleInterface) instance.initialize_code() - instance.setup_mesh(3, 3, 3, 6,12,18) - instance.set_boundary("interface","interface","interface","interface","interface","interface") + instance.setup_mesh(3, 3, 3, 6, 12, 18) + instance.set_boundary("interface", "interface", "interface", "interface", "interface", "interface") instance.commit_parameters() - + dx = 6.0 / 3.0 dy = 12.0 / 3.0 dz = 18.0 / 3.0 - for i in [1,2]: - for j in range(1,3+1): - for k in range(1,3+1): - x,y,z,error = instance.get_boundary_position_of_index( - i, j, k, + for i in [1, 2]: + for j in range(1, 3+1): + for k in range(1, 3+1): + x, y, z, error = instance.get_boundary_position_of_index( + i, j, k, 2 ) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(x, 6.0 + (0.5 * dx) + ((i-1) * dx)) self.assertAlmostRelativeEquals(y, (0.5 * dy) + ((j-1) * dy)) self.assertAlmostRelativeEquals(z, (0.5 * dz) + ((k-1) * dz)) - - for i in range(1,3 + 4 +1): - for j in [1,2]: - for k in range(1,3+1): - x,y,z,error = instance.get_boundary_position_of_index( - i, j, k, + + for i in range(1, 3 + 4 + 1): + for j in [1, 2]: + for k in range(1, 3+1): + x, y, z, error = instance.get_boundary_position_of_index( + i, j, k, 3 ) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(x, (0.5 * dx) + ((i-2-1) * dx)) self.assertAlmostRelativeEquals(y, 0.0 - ((0.5 * dy) + ((j-1) * dy))) self.assertAlmostRelativeEquals(z, (0.5 * dz) + ((k-1) * dz)) - - - x,y,z,error = instance.get_boundary_position_of_index( - i, j, k, + + x, y, z, error = instance.get_boundary_position_of_index( + i, j, k, 4 ) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(x, (0.5 * dx) + ((i-2-1) * dx)) self.assertAlmostRelativeEquals(y, 12.0 + (0.5 * dy) + ((j-1) * dy)) self.assertAlmostRelativeEquals(z, (0.5 * dz) + ((k-1) * dz)) - - for i in range(1,3 + 4 +1): - for j in range(1,3 + 4 +1): - for k in [1,2]: - x,y,z,error = instance.get_boundary_position_of_index( - i, j, k, - 5 + + for i in range(1, 3 + 4 + 1): + for j in range(1, 3 + 4 + 1): + for k in [1, 2]: + x, y, z, error = instance.get_boundary_position_of_index( + i, j, k, + 5 ) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(x, (0.5 * dx) + ((i-2-1) * dx)) self.assertAlmostRelativeEquals(y, (0.5 * dy) + ((j-2-1) * dy)) self.assertAlmostRelativeEquals(z, 0.0 - ((0.5 * dz) + ((k-1) * dz))) - - - x,y,z,error = instance.get_boundary_position_of_index( - i, j, k, + + x, y, z, error = instance.get_boundary_position_of_index( + i, j, k, 6 ) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(x, (0.5 * dx) + ((i-2-1) * dx)) self.assertAlmostRelativeEquals(y, (0.5 * dy) + ((j-2-1) * dy)) self.assertAlmostRelativeEquals(z, 18.0 + (0.5 * dz) + ((k-1) * dz)) - + def test19(self): results = [] - instance=self.new_instance(CapreoleInterface) + instance = self.new_instance(CapreoleInterface) instance.initialize_code() instance.commit_parameters() nx, ny, nz, error = instance.get_parallel_decomposition() @@ -542,50 +537,48 @@ def test19(self): self.assertEqual(nx, 1) self.assertEqual(ny, 1) self.assertEqual(nz, 1) - error = instance.set_parallel_decomposition(2,1,1) + error = instance.set_parallel_decomposition(2, 1, 1) self.assertEqual(error, -1) - - + def test20(self): results = [] - instance=self.new_instance(CapreoleInterface, number_of_workers = 4) + instance = self.new_instance(CapreoleInterface, number_of_workers=4) instance.initialize_code() nx, ny, nz, error = instance.get_parallel_decomposition() self.assertEqual(error, 0) self.assertEqual(nx, 0) self.assertEqual(ny, 0) self.assertEqual(nz, 0) - error = instance.set_parallel_decomposition(2,1,2) + error = instance.set_parallel_decomposition(2, 1, 2) self.assertEqual(error, 0) nx, ny, nz, error = instance.get_parallel_decomposition() self.assertEqual(error, 0) self.assertEqual(nx, 2) self.assertEqual(ny, 1) self.assertEqual(nz, 2) - error = instance.set_parallel_decomposition(10,3,2) + error = instance.set_parallel_decomposition(10, 3, 2) self.assertEqual(error, -1) - + def test21(self): results = [] - instance=self.new_instance(CapreoleInterface, number_of_workers = 2) + instance = self.new_instance(CapreoleInterface, number_of_workers=2) instance.initialize_code() - error = instance.set_parallel_decomposition(1,2,1) + error = instance.set_parallel_decomposition(1, 2, 1) self.assertEqual(error, 0) - instance.setup_mesh(10,30,10,100.0, 300.0, 100.0) - instance.set_boundary("interface","interface","periodic","periodic","periodic","periodic") + instance.setup_mesh(10, 30, 10, 100.0, 300.0, 100.0) + instance.set_boundary("interface", "interface", "periodic", "periodic", "periodic", "periodic") instance.commit_parameters() - - - for boundary_index in [1,2]: - for i0 in range(1,2): + + for boundary_index in [1, 2]: + for i0 in range(1, 2): for j0 in range(1, 30+1): i = j0 * 30 + i0 error = instance.set_boundary_state( - i0, j0, 1, # index - 1.0 * (i+1), # density - 2.0 * (i+1), 3.0 * (i+1), 4.0 * (i+1), # momentum - 5.0 * (i+1), # energy - boundary_index # boundary + i0, j0, 1, # index + 1.0 * (i+1), # density + 2.0 * (i+1), 3.0 * (i+1), 4.0 * (i+1), # momentum + 5.0 * (i+1), # energy + boundary_index # boundary ) self.assertEqual(error, 0) rho, rhovx, rhovy, rhovz, rhoen, error = instance.get_boundary_state( @@ -593,34 +586,33 @@ def test21(self): boundary_index ) self.assertEqual(error, 0) - + self.assertAlmostRelativeEquals(rho, 1.0 * (i+1)) self.assertAlmostRelativeEquals(rhovx, 2.0 * (i+1)) self.assertAlmostRelativeEquals(rhovy, 3.0 * (i+1)) self.assertAlmostRelativeEquals(rhovz, 4.0 * (i+1)) self.assertAlmostRelativeEquals(rhoen, 5.0 * (i+1)) - + def test22(self): results = [] - instance=self.new_instance(CapreoleInterface, number_of_workers = 2) + instance = self.new_instance(CapreoleInterface, number_of_workers=2) instance.initialize_code() - error = instance.set_parallel_decomposition(2,1,1) + error = instance.set_parallel_decomposition(2, 1, 1) self.assertEqual(error, 0) - instance.setup_mesh(10,30,10,100.0, 300.0, 100.0) - instance.set_boundary("interface","interface","periodic","periodic","periodic","periodic") + instance.setup_mesh(10, 30, 10, 100.0, 300.0, 100.0) + instance.set_boundary("interface", "interface", "periodic", "periodic", "periodic", "periodic") instance.commit_parameters() - - - for boundary_index in [1,2]: - for i0 in range(1,2): + + for boundary_index in [1, 2]: + for i0 in range(1, 2): for j0 in range(1, 30+1): i = j0 * 30 + i0 error = instance.set_boundary_state( - i0, j0, 1, # index - 1.0 * (i+1), # density - 2.0 * (i+1), 3.0 * (i+1), 4.0 * (i+1), # momentum - 5.0 * (i+1), # energy - boundary_index # boundary + i0, j0, 1, # index + 1.0 * (i+1), # density + 2.0 * (i+1), 3.0 * (i+1), 4.0 * (i+1), # momentum + 5.0 * (i+1), # energy + boundary_index # boundary ) self.assertEqual(error, 0) rho, rhovx, rhovy, rhovz, rhoen, error = instance.get_boundary_state( @@ -628,35 +620,34 @@ def test22(self): boundary_index ) self.assertEqual(error, 0) - + self.assertAlmostRelativeEquals(rho, 1.0 * (i+1)) self.assertAlmostRelativeEquals(rhovx, 2.0 * (i+1)) self.assertAlmostRelativeEquals(rhovy, 3.0 * (i+1)) self.assertAlmostRelativeEquals(rhovz, 4.0 * (i+1)) self.assertAlmostRelativeEquals(rhoen, 5.0 * (i+1)) - + def test23(self): results = [] - instance=self.new_instance(CapreoleInterface, number_of_workers = 3) + instance = self.new_instance(CapreoleInterface, number_of_workers=3) instance.initialize_code() - error = instance.set_parallel_decomposition(3,1,1) + error = instance.set_parallel_decomposition(3, 1, 1) self.assertEqual(error, 0) - instance.setup_mesh(12,20,10,100.0, 300.0, 100.0) - - instance.set_boundary("interface","interface","interface","interface","periodic","periodic") + instance.setup_mesh(12, 20, 10, 100.0, 300.0, 100.0) + + instance.set_boundary("interface", "interface", "interface", "interface", "periodic", "periodic") instance.commit_parameters() - - - for boundaryindex in [3,4]: - for i0 in range(1,12+4+1): - for j0 in [1,2]: + + for boundaryindex in [3, 4]: + for i0 in range(1, 12+4+1): + for j0 in [1, 2]: i = (i0 * 15) + j0 error = instance.set_boundary_state( - i0,j0,1, # index - 1.0 * (i+1), # density - 2.0 * (i+1), 3.0 * (i+1), 4.0 * (i+1), # momentum - 5.0 * (i+1), # energy - boundaryindex # boundary + i0, j0, 1, # index + 1.0 * (i+1), # density + 2.0 * (i+1), 3.0 * (i+1), 4.0 * (i+1), # momentum + 5.0 * (i+1), # energy + boundaryindex # boundary ) print(i0, j0) self.assertEqual(error, 0) @@ -665,35 +656,34 @@ def test23(self): boundaryindex ) self.assertEqual(error, 0) - + self.assertAlmostRelativeEquals(rho, 1.0 * (i+1)) self.assertAlmostRelativeEquals(rhovx, 2.0 * (i+1)) self.assertAlmostRelativeEquals(rhovy, 3.0 * (i+1)) self.assertAlmostRelativeEquals(rhovz, 4.0 * (i+1)) self.assertAlmostRelativeEquals(rhoen, 5.0 * (i+1)) - + def test24(self): results = [] - instance=self.new_instance(CapreoleInterface, number_of_workers = 3) + instance = self.new_instance(CapreoleInterface, number_of_workers=3) instance.initialize_code() - error = instance.set_parallel_decomposition(1,3,1) + error = instance.set_parallel_decomposition(1, 3, 1) self.assertEqual(error, 0) - instance.setup_mesh(12,30,10,100.0, 300.0, 100.0) - - instance.set_boundary("interface","interface","interface","interface","periodic","periodic") + instance.setup_mesh(12, 30, 10, 100.0, 300.0, 100.0) + + instance.set_boundary("interface", "interface", "interface", "interface", "periodic", "periodic") instance.commit_parameters() - - - for boundaryindex in [3,4]: - for i0 in range(1,12+4+1): - for j0 in [1,2]: + + for boundaryindex in [3, 4]: + for i0 in range(1, 12+4+1): + for j0 in [1, 2]: i = (i0 * 15) + j0 error = instance.set_boundary_state( - i0,j0,1, # index - 1.0 * (i+1), # density - 2.0 * (i+1), 3.0 * (i+1), 4.0 * (i+1), # momentum - 5.0 * (i+1), # energy - boundaryindex # boundary + i0, j0, 1, # index + 1.0 * (i+1), # density + 2.0 * (i+1), 3.0 * (i+1), 4.0 * (i+1), # momentum + 5.0 * (i+1), # energy + boundaryindex # boundary ) print(i0, j0) self.assertEqual(error, 0) @@ -702,72 +692,70 @@ def test24(self): boundaryindex ) self.assertEqual(error, 0) - + self.assertAlmostRelativeEquals(rho, 1.0 * (i+1)) self.assertAlmostRelativeEquals(rhovx, 2.0 * (i+1)) self.assertAlmostRelativeEquals(rhovy, 3.0 * (i+1)) self.assertAlmostRelativeEquals(rhovz, 4.0 * (i+1)) self.assertAlmostRelativeEquals(rhoen, 5.0 * (i+1)) - + def test25(self): results = [] - instance=self.new_instance(CapreoleInterface, number_of_workers = 3) + instance = self.new_instance(CapreoleInterface, number_of_workers=3) instance.initialize_code() - error = instance.set_parallel_decomposition(1,3,1) + error = instance.set_parallel_decomposition(1, 3, 1) self.assertEqual(error, 0) - instance.setup_mesh(6,5,5,6.0,5.0,5.0) - instance.set_boundary("interface","interface","interface","interface","interface","interface") + instance.setup_mesh(6, 5, 5, 6.0, 5.0, 5.0) + instance.set_boundary("interface", "interface", "interface", "interface", "interface", "interface") instance.commit_parameters() - - - for boundaryindex in [5,6]: + + for boundaryindex in [5, 6]: for i0 in range(1, 6+4+1): for j0 in range(1, 5+4+1): - for z0 in[1,2]: + for z0 in [1, 2]: i = (i0 * (5*4)) + (j0 * 4) + z0 error = instance.set_boundary_state( - i0,j0,z0, # index - 1.0 * (i+1), # density - 2.0 * (i+1), 3.0 * (i+1), 4.0 * (i+1), # momentum - 5.0 * (i+1), # energy - boundaryindex # boundary + i0, j0, z0, # index + 1.0 * (i+1), # density + 2.0 * (i+1), 3.0 * (i+1), 4.0 * (i+1), # momentum + 5.0 * (i+1), # energy + boundaryindex # boundary ) self.assertEqual(error, 0) rho, rhovx, rhovy, rhovz, rhoen, error = instance.get_boundary_state( i0, j0, z0, boundaryindex - + ) self.assertEqual(error, 0) - + self.assertAlmostRelativeEquals(rho, 1.0 * (i+1)) self.assertAlmostRelativeEquals(rhovx, 2.0 * (i+1)) self.assertAlmostRelativeEquals(rhovy, 3.0 * (i+1)) self.assertAlmostRelativeEquals(rhovz, 4.0 * (i+1)) self.assertAlmostRelativeEquals(rhoen, 5.0 * (i+1)) - + def test26(self): results = [] - instance=self.new_instance(CapreoleInterface, number_of_workers = 9) + instance = self.new_instance(CapreoleInterface, number_of_workers=9) instance.initialize_code() - error = instance.set_parallel_decomposition(3,3,1) - instance.setup_mesh(6,6,5,6.0,6.0,5.0) + error = instance.set_parallel_decomposition(3, 3, 1) + instance.setup_mesh(6, 6, 5, 6.0, 6.0, 5.0) self.assertEqual(error, 0) - instance.set_boundary("interface","interface","interface","interface","interface","interface") + instance.set_boundary("interface", "interface", "interface", "interface", "interface", "interface") instance.commit_parameters() - - - for boundaryindex in [5,6]: - for i0 in range(1,6+4+1): - for j0 in range(1,6+4+1): - for z0 in [1,2]: + + for boundaryindex in [5, 6]: + for i0 in range(1, 6+4+1): + for j0 in range(1, 6+4+1): + for z0 in [1, 2]: i = (i0 * (5*4)) + (j0 * 4) + z0 error = instance.set_boundary_state( - i0,j0,z0, # index - 1.0 * (i+1), # density - 2.0 * (i+1), 3.0 * (i+1), 4.0 * (i+1), # momentum - 5.0 * (i+1), # energy - boundaryindex # boundary + i0, j0, z0, # index + 1.0 * (i+1), # density + 2.0 * (i+1), 3.0 * (i+1), 4.0 * (i+1), # momentum + 5.0 * (i+1), # energy + boundaryindex # boundary ) self.assertEqual(error, 0) rho, rhovx, rhovy, rhovz, rhoen, error = instance.get_boundary_state( @@ -775,15 +763,15 @@ def test26(self): boundaryindex ) self.assertEqual(error, 0) - + self.assertAlmostRelativeEquals(rho, 1.0 * (i+1)) self.assertAlmostRelativeEquals(rhovx, 2.0 * (i+1)) self.assertAlmostRelativeEquals(rhovy, 3.0 * (i+1)) self.assertAlmostRelativeEquals(rhovz, 4.0 * (i+1)) self.assertAlmostRelativeEquals(rhoen, 5.0 * (i+1)) - + def test27(self): - instance=CapreoleInterface() + instance = CapreoleInterface() instance.initialize_code() gamma, error = instance.get_gamma() self.assertAlmostRelativeEquals(gamma, 5.0 / 3.0) @@ -792,26 +780,25 @@ def test27(self): self.assertEqual(error, 0) self.assertAlmostRelativeEquals(gamma, 1.3) instance.stop() - - + def test28(self): - instance=CapreoleInterface() + instance = CapreoleInterface() instance.initialize_code() timestep, error = instance.get_timestep() self.assertEqual(timestep, 0.0) self.assertEqual(error, 0) - instance.setup_mesh(10,10,10,1.,1.,1.) + instance.setup_mesh(10, 10, 10, 1., 1., 1.) instance.commit_parameters() - x,y,z=numpy.indices( (10,10,10) ) - x=x.flatten()+1 - y=y.flatten()+1 - z=z.flatten()+1 - rho=0.1*numpy.ones_like(x) - rhvx=0.*numpy.ones_like(x) - rhvy=0.*numpy.ones_like(x) - rhvz=0.*numpy.ones_like(x) - en=0.1*numpy.ones_like(x) - instance.set_grid_state(x,y,z,rho,rhvx,rhvy,rhvz,en) + x, y, z = numpy.indices((10, 10, 10)) + x = x.flatten()+1 + y = y.flatten()+1 + z = z.flatten()+1 + rho = 0.1*numpy.ones_like(x) + rhvx = 0.*numpy.ones_like(x) + rhvy = 0.*numpy.ones_like(x) + rhvz = 0.*numpy.ones_like(x) + en = 0.1*numpy.ones_like(x) + instance.set_grid_state(x, y, z, rho, rhvx, rhvy, rhvz, en) timestep, error = instance.get_timestep() self.assertEqual(timestep, 0.0) self.assertEqual(error, 0) @@ -824,904 +811,871 @@ def test28(self): timestep, error = instance.get_timestep() self.assertEqual(timestep, 0.25) self.assertEqual(error, 0) - + instance.stop() - - + def test29(self): - instance = CapreoleInterface(number_of_workers = 1) + instance = CapreoleInterface(number_of_workers=1) self.check_extended_grid(instance) - + def xtest30(self): print("Broken as capreole cannot do periodic boundaries with multiple workers!") - instance = CapreoleInterface(redirection="none", number_of_workers = 8) + instance = CapreoleInterface(redirection="none", number_of_workers=8) self.check_extended_grid(instance) - - + def check_extended_grid(self, instance): instance.initialize_code() instance.setup_mesh(8, 8, 8, 1.0, 1.0, 1.0) - instance.set_boundary("periodic","periodic","periodic","periodic","periodic","periodic") + instance.set_boundary("periodic", "periodic", "periodic", "periodic", "periodic", "periodic") result = instance.commit_parameters() self.assertEqual(result, 0) time, error = instance.get_time() - self.assertEqual(error,0) + self.assertEqual(error, 0) self.assertEqual(time, 0.0) for i in range(8): - error = instance.set_grid_state(i+1,1,1,0.1 * (i+1), 0.2 * (i+1), 0.3 * (i+1), 0.4 * (i+1), 0.5 * (i+1)) + error = instance.set_grid_state(i+1, 1, 1, 0.1 * (i+1), 0.2 * (i+1), 0.3 * (i+1), 0.4 * (i+1), 0.5 * (i+1)) self.assertEqual(error, 0) - - error = instance.set_grid_state(1,i+1,1,0.1 * (i+1), 0.2 * (i+1), 0.3 * (i+1), 0.4 * (i+1), 0.5 * (i+1)) + + error = instance.set_grid_state(1, i+1, 1, 0.1 * (i+1), 0.2 * (i+1), 0.3 * (i+1), 0.4 * (i+1), 0.5 * (i+1)) self.assertEqual(error, 0) - - error = instance.set_grid_state(1,1,i+1,0.1 * (i+1), 0.2 * (i+1), 0.3 * (i+1), 0.4 * (i+1), 0.5 * (i+1)) + + error = instance.set_grid_state(1, 1, i+1, 0.1 * (i+1), 0.2 * (i+1), 0.3 * (i+1), 0.4 * (i+1), 0.5 * (i+1)) self.assertEqual(error, 0) - + instance.initialize_grid() - - + for i in range(8): - rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(i+1,1,1) + rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(i+1, 1, 1) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(rho, (i+1) * 0.1) - rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(1,i+1,1) + rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(1, i+1, 1) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(rho, (i+1) * 0.1) - rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(1,1,i+1) + rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(1, 1, i+1) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(rho, (i+1) * 0.1) - + for i in range(2): - rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(-(i),1,1) + rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(-(i), 1, 1) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(rho, 0.8 - (i * 0.1)) - - rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(-2,1,1) + + rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(-2, 1, 1) self.assertEqual(error, -1) self.assertAlmostRelativeEquals(rho, 0.0) - - rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(8 + i+1,1,1) + + rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(8 + i+1, 1, 1) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(rho, (i+1) * 0.1) - - rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(8 + 3,1,1) + + rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(8 + 3, 1, 1) self.assertEqual(error, -1) self.assertAlmostRelativeEquals(rho, 0.0) - + # 2 dimension - - rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(1, -i,1) + + rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(1, -i, 1) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(rho, 0.8 - (i * 0.1)) - - rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(1,-3, 1) + + rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(1, -3, 1) self.assertEqual(error, -1) self.assertAlmostRelativeEquals(rho, 0.0) - - - rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(1,8 + i + 1,1) + + rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(1, 8 + i + 1, 1) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(rho, (i+1) * 0.1) - - rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(1,8+3, 1) + + rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(1, 8+3, 1) self.assertEqual(error, -1) self.assertAlmostRelativeEquals(rho, 0.0) - + # 3 dimension rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(1, 1, -i) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(rho, 0.8 - (i * 0.1)) - - rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(1,-3, 1) + + rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(1, -3, 1) self.assertEqual(error, -1) self.assertAlmostRelativeEquals(rho, 0.0) - - - rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(1, 1,8 + i + 1) + + rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(1, 1, 8 + i + 1) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(rho, (i+1) * 0.1) - + rho, rhovx, rhovy, rhovz, energy, error = instance.get_grid_state(1, 1, 8+3) self.assertEqual(error, -1) self.assertAlmostRelativeEquals(rho, 0.0) - - - - + instance.stop() - + + class TestSodShocktube(TestWithMPI): - + def test0(self): - N=100 - gamma=5/3. - g=(gamma-1)/(gamma+1) - b=(gamma-1)/2/gamma - - instance=CapreoleInterface() + N = 100 + gamma = 5/3. + g = (gamma-1)/(gamma+1) + b = (gamma-1)/2/gamma + + instance = CapreoleInterface() instance.initialize_code() - instance.setup_mesh(N,N//10,N//10,1.,0.1,0.1) + instance.setup_mesh(N, N//10, N//10, 1., 0.1, 0.1) instance.commit_parameters() - x,y,z=numpy.indices( (N,N//10,N//10) ) - x=x.flatten()+1 - y=y.flatten()+1 - z=z.flatten()+1 - gamma=5./3. - rho=0.125*numpy.ones_like(x) - rhvx=0.*numpy.ones_like(x) - rhvy=0.*numpy.ones_like(x) - rhvz=0.*numpy.ones_like(x) - en=(0.1/(gamma-1))*numpy.ones_like(x) - instance.set_grid_state(x,y,z,rho,rhvx,rhvy,rhvz,en) - - x,y,z=numpy.indices( (N//2,N//10,N//10) ) - x=x.flatten()+1 - y=y.flatten()+1 - z=z.flatten()+1 - rho=1.*numpy.ones_like(x) - rhvx=0.*numpy.ones_like(x) - rhvy=0.*numpy.ones_like(x) - rhvz=0.*numpy.ones_like(x) - en=(1./(gamma-1))*numpy.ones_like(x) - instance.set_grid_state(x,y,z,rho,rhvx,rhvy,rhvz,en) + x, y, z = numpy.indices((N, N//10, N//10)) + x = x.flatten()+1 + y = y.flatten()+1 + z = z.flatten()+1 + gamma = 5./3. + rho = 0.125*numpy.ones_like(x) + rhvx = 0.*numpy.ones_like(x) + rhvy = 0.*numpy.ones_like(x) + rhvz = 0.*numpy.ones_like(x) + en = (0.1/(gamma-1))*numpy.ones_like(x) + instance.set_grid_state(x, y, z, rho, rhvx, rhvy, rhvz, en) + + x, y, z = numpy.indices((N//2, N//10, N//10)) + x = x.flatten()+1 + y = y.flatten()+1 + z = z.flatten()+1 + rho = 1.*numpy.ones_like(x) + rhvx = 0.*numpy.ones_like(x) + rhvy = 0.*numpy.ones_like(x) + rhvz = 0.*numpy.ones_like(x) + en = (1./(gamma-1))*numpy.ones_like(x) + instance.set_grid_state(x, y, z, rho, rhvx, rhvy, rhvz, en) instance.initialize_grid() instance.evolve_model(0.2) - - x=numpy.array([0.1,0.9,0.6,0.8]) - y=0.05*numpy.ones_like(x) - z=0.05*numpy.ones_like(x) - i,j,k,err=instance.get_index_of_position(x,y,z) - rho,rhovx,rhovy,rhovz,en,err=instance.get_grid_state(i,j,k) - vel=numpy.sqrt((rhovx**2+rhovy**2+rhovz**2))/rho - pres=(gamma-1)*(en-0.5*rho*vel**2) - u=pres/(gamma-1)/rho - rhoexp=numpy.zeros_like(x) - rhoexp[0]=1. - rhoexp[1]=0.125 - rhoexp[2]=rho[0]*(pres[2]/pres[0])**(1/gamma) - rhoexp[3]=rho[1]*(pres[3]+g*pres[1])/(pres[1]+g*pres[3]) - + + x = numpy.array([0.1, 0.9, 0.6, 0.8]) + y = 0.05*numpy.ones_like(x) + z = 0.05*numpy.ones_like(x) + i, j, k, err = instance.get_index_of_position(x, y, z) + rho, rhovx, rhovy, rhovz, en, err = instance.get_grid_state(i, j, k) + vel = numpy.sqrt((rhovx**2+rhovy**2+rhovz**2))/rho + pres = (gamma-1)*(en-0.5*rho*vel**2) + u = pres/(gamma-1)/rho + rhoexp = numpy.zeros_like(x) + rhoexp[0] = 1. + rhoexp[1] = 0.125 + rhoexp[2] = rho[0]*(pres[2]/pres[0])**(1/gamma) + rhoexp[3] = rho[1]*(pres[3]+g*pres[1])/(pres[1]+g*pres[3]) + for i in range(len(rho)): - self.assertAlmostEqual(rhoexp[i],rho[i],2) - - - + self.assertAlmostEqual(rhoexp[i], rho[i], 2) + class TestCapreole(TestWithMPI): - + def test0(self): - instance=self.new_instance(Capreole) + instance = self.new_instance(Capreole) instance.initialize_code() instance.stop() - + def test1(self): - instance=self.new_instance(Capreole) - instance.parameters.mesh_size = (10,10,5) + instance = self.new_instance(Capreole) + instance.parameters.mesh_size = (10, 10, 5) instance.parameters.length_x = 1.0 | generic_unit_system.length instance.parameters.length_y = 1.0 | generic_unit_system.length instance.parameters.length_z = 1.0 | generic_unit_system.length - instance.parameters.x_boundary_conditions = "periodic","periodic" - instance.parameters.y_boundary_conditions = "periodic","periodic" - instance.parameters.z_boundary_conditions = "periodic","periodic" - - - self.assertEqual(len(list(instance.itergrids())),1) - grid = datamodel.Grid(10,10,10) + instance.parameters.x_boundary_conditions = "periodic", "periodic" + instance.parameters.y_boundary_conditions = "periodic", "periodic" + instance.parameters.z_boundary_conditions = "periodic", "periodic" + + self.assertEqual(len(list(instance.itergrids())), 1) + grid = datamodel.Grid(10, 10, 10) grid.rho = 0.4 | generic_unit_system.density grid.rhovx = 0.1 | generic_unit_system.momentum_density - grid.rhovy = 0.0 | generic_unit_system.momentum_density - grid.rhovz = 0.0 | generic_unit_system.momentum_density + grid.rhovy = 0.0 | generic_unit_system.momentum_density + grid.rhovz = 0.0 | generic_unit_system.momentum_density grid.energy = 0.0 | generic_unit_system.energy_density - + channel = grid.new_channel_to(instance.grid) channel.copy() - + instance.initialize_grid() - + channel = instance.grid.new_channel_to(grid) channel.copy() - + self.assertEqual(grid[1][1][0].rho, 0.4 | generic_unit_system.density) for x in grid[1].rho.value_in(generic_unit_system.density).flatten(): self.assertEqual(x, 0.4) - - #instance.evolve_model(0.12 | generic_unit_system.time) - - #for x in instance.grid.rho.value_in(generic_unit_system.density).flatten(): + + # instance.evolve_model(0.12 | generic_unit_system.time) + + # for x in instance.grid.rho.value_in(generic_unit_system.density).flatten(): # self.assertEquals(x, 0.1) - - #instance.evolve_model(10.0 | generic_unit_system.time) - #for x in instance.grid.rho.value_in(generic_unit_system.density).flatten(): + + # instance.evolve_model(10.0 | generic_unit_system.time) + # for x in instance.grid.rho.value_in(generic_unit_system.density).flatten(): # self.assertEquals(x, 0.1) instance.stop() - def test2(self): - instance=self.new_instance(Capreole) - instance.parameters.mesh_size = (3,3,3) + instance = self.new_instance(Capreole) + instance.parameters.mesh_size = (3, 3, 3) instance.parameters.length_x = 1.0 | generic_unit_system.length instance.parameters.length_y = 1.0 | generic_unit_system.length instance.parameters.length_z = 1.0 | generic_unit_system.length - instance.parameters.x_boundary_conditions = "periodic","periodic" - instance.parameters.y_boundary_conditions = "periodic","periodic" - instance.parameters.z_boundary_conditions = "periodic","periodic" - - grid = datamodel.Grid(3,3,3) + instance.parameters.x_boundary_conditions = "periodic", "periodic" + instance.parameters.y_boundary_conditions = "periodic", "periodic" + instance.parameters.z_boundary_conditions = "periodic", "periodic" + + grid = datamodel.Grid(3, 3, 3) grid.rho = 0.1 | generic_unit_system.density grid.rhovx = 0.0 | generic_unit_system.momentum_density - grid.rhovy = 0.0 | generic_unit_system.momentum_density - grid.rhovz = 0.0 | generic_unit_system.momentum_density + grid.rhovy = 0.0 | generic_unit_system.momentum_density + grid.rhovz = 0.0 | generic_unit_system.momentum_density grid.energy = 1.0 | generic_unit_system.energy_density - + channel = grid.new_channel_to(instance.grid) channel.copy() - - + print(instance.grid[1].rho) self.assertEqual(instance.grid[1][1][0].rho, 0.1 | generic_unit_system.density) for x in instance.grid[1].rho.value_in(generic_unit_system.density).flatten(): self.assertEqual(x, 0.1) - + instance.evolve_model(1.0 | generic_unit_system.time) - + for x in instance.grid.rho.value_in(generic_unit_system.density).flatten(): self.assertEqual(x, 0.1) - + instance.evolve_model(10.0 | generic_unit_system.time) for x in instance.grid.rho.value_in(generic_unit_system.density).flatten(): self.assertEqual(x, 0.1) instance.stop() - + def test3(self): - instance=self.new_instance(Capreole) - instance.parameters.mesh_size = (5,5,5) + instance = self.new_instance(Capreole) + instance.parameters.mesh_size = (5, 5, 5) instance.parameters.length_x = 1.0 | generic_unit_system.length instance.parameters.length_y = 1.0 | generic_unit_system.length instance.parameters.length_z = 1.0 | generic_unit_system.length - instance.parameters.x_boundary_conditions = "periodic","periodic" - instance.parameters.y_boundary_conditions = "periodic","periodic" - instance.parameters.z_boundary_conditions = "periodic","periodic" - - - grid = datamodel.Grid(5,5,5) + instance.parameters.x_boundary_conditions = "periodic", "periodic" + instance.parameters.y_boundary_conditions = "periodic", "periodic" + instance.parameters.z_boundary_conditions = "periodic", "periodic" + + grid = datamodel.Grid(5, 5, 5) grid.rho = 0.1 | generic_unit_system.density grid.rhovx = 0.0 | generic_unit_system.momentum_density - grid.rhovy = 0.0 | generic_unit_system.momentum_density - grid.rhovz = 0.0 | generic_unit_system.momentum_density - grid.energy = 1.0 | generic_unit_system.energy_density - + grid.rhovy = 0.0 | generic_unit_system.momentum_density + grid.rhovz = 0.0 | generic_unit_system.momentum_density + grid.energy = 1.0 | generic_unit_system.energy_density + channel = grid.new_channel_to(instance.grid) channel.copy() - - self.assertEqual((5,5,5), instance.acceleration_grid.shape) - - acc_grid = datamodel.Grid(5,5,5) + + self.assertEqual((5, 5, 5), instance.acceleration_grid.shape) + + acc_grid = datamodel.Grid(5, 5, 5) acc_grid.ax = 1 | generic_unit_system.acceleration acc_grid.ay = 1 | generic_unit_system.acceleration acc_grid.az = 1 | generic_unit_system.acceleration - #self.assertEquals(acc_grid.acceleration[0][0][0], ( 1,1,1) | generic_unit_system.acceleration) + # self.assertEquals(acc_grid.acceleration[0][0][0], ( 1,1,1) | generic_unit_system.acceleration) channel = acc_grid.new_channel_to(instance.acceleration_grid) channel.copy() - - + instance.evolve_model(0.1 | generic_unit_system.time) - - self.assertAlmostRelativeEquals(instance.grid.rho, grid.rho); - self.assertAlmostRelativeEquals(instance.grid.rhovx, 0.1 * 1.0 * 0.1 | generic_unit_system.momentum_density); - self.assertAlmostRelativeEquals(instance.grid.rhovy, 0.1 * 1.0 * 0.1 | generic_unit_system.momentum_density); - self.assertAlmostRelativeEquals(instance.grid.rhovz, 0.1 * 1.0 * 0.1 | generic_unit_system.momentum_density); + + self.assertAlmostRelativeEquals(instance.grid.rho, grid.rho) + self.assertAlmostRelativeEquals(instance.grid.rhovx, 0.1 * 1.0 * 0.1 | generic_unit_system.momentum_density) + self.assertAlmostRelativeEquals(instance.grid.rhovy, 0.1 * 1.0 * 0.1 | generic_unit_system.momentum_density) + self.assertAlmostRelativeEquals(instance.grid.rhovz, 0.1 * 1.0 * 0.1 | generic_unit_system.momentum_density) instance.evolve_model(0.3 | generic_unit_system.time) print(instance.model_time) - self.assertAlmostRelativeEquals(instance.grid.rho, grid.rho); - self.assertAlmostRelativeEquals(instance.grid.rhovx, grid.rho * instance.model_time * acc_grid.ax,2); - self.assertAlmostRelativeEquals(instance.grid.rhovy, grid.rho * instance.model_time * acc_grid.ay,2); - self.assertAlmostRelativeEquals(instance.grid.rhovz, grid.rho * instance.model_time * acc_grid.az,2); + self.assertAlmostRelativeEquals(instance.grid.rho, grid.rho) + self.assertAlmostRelativeEquals(instance.grid.rhovx, grid.rho * instance.model_time * acc_grid.ax, 2) + self.assertAlmostRelativeEquals(instance.grid.rhovy, grid.rho * instance.model_time * acc_grid.ay, 2) + self.assertAlmostRelativeEquals(instance.grid.rhovz, grid.rho * instance.model_time * acc_grid.az, 2) instance.stop() - + def test4(self): converter = generic_unit_converter.ConvertBetweenGenericAndSiUnits( 1 | units.parsec, 1 | units.Myr, 1 | units.MSun ) - instance=self.new_instance(Capreole, unit_converter = converter) - instance.parameters.mesh_size = (3,3,3) + instance = self.new_instance(Capreole, unit_converter=converter) + instance.parameters.mesh_size = (3, 3, 3) instance.parameters.length_x = 1.0 | units.parsec instance.parameters.length_y = 1.0 | units.parsec instance.parameters.length_z = 1.0 | units.parsec - instance.parameters.x_boundary_conditions = "periodic","periodic" - instance.parameters.y_boundary_conditions = "periodic","periodic" - instance.parameters.z_boundary_conditions = "periodic","periodic" - + instance.parameters.x_boundary_conditions = "periodic", "periodic" + instance.parameters.y_boundary_conditions = "periodic", "periodic" + instance.parameters.z_boundary_conditions = "periodic", "periodic" + instance.commit_parameters() density = units.MSun / (units.parsec ** 3) - grid = datamodel.Grid(3,3,3) + grid = datamodel.Grid(3, 3, 3) grid.rho = 0.1 | density - grid.rhovx = 0.0 | units.MSun / (units.Myr * units.parsec ** 2 ) - grid.rhovy = 0.0 | units.MSun / (units.Myr * units.parsec ** 2 ) - grid.rhovz = 0.0 | units.MSun / (units.Myr * units.parsec ** 2 ) + grid.rhovx = 0.0 | units.MSun / (units.Myr * units.parsec ** 2) + grid.rhovy = 0.0 | units.MSun / (units.Myr * units.parsec ** 2) + grid.rhovz = 0.0 | units.MSun / (units.Myr * units.parsec ** 2) grid.energy = 1.0 | units.MSun / (units.parsec * units.Myr ** 2) - + channel = grid.new_channel_to(instance.grid) channel.copy() - - + print(instance.grid[1].rho) self.assertAlmostRelativeEquals(instance.grid[1][1][0].rho, 0.1 | density) for x in instance.grid[1].rho.value_in(density).flatten(): self.assertAlmostRelativeEquals(x, 0.1) - + instance.evolve_model(1.0 | units.Myr) - + for x in instance.grid.rho.value_in(density).flatten(): self.assertAlmostRelativeEquals(x, 0.1) - + instance.evolve_model(10.0 | units.Myr) for x in instance.grid.rho.value_in(density).flatten(): self.assertAlmostRelativeEquals(x, 0.1) instance.stop() - - - - def test5(self): - instance=self.new_instance(Capreole) - instance.parameters.mesh_size = (10 , 4, 4) + + def test5(self): + instance = self.new_instance(Capreole) + instance.parameters.mesh_size = (10, 4, 4) instance.parameters.mesh_length = [1.0, 1.0, 1.0] | generic_unit_system.length instance.parameters.x_boundary_conditions = ("interface", "outflow") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.z_boundary_conditions = ("periodic", "periodic") instance.parameters.stopping_conditions_number_of_steps = 1 - + gamma = 5.0 / 3.0 - - grid = datamodel.new_regular_grid((10,4,4), [1.0, 1.0, 1.0] | generic_unit_system.length ) - + + grid = datamodel.new_regular_grid((10, 4, 4), [1.0, 1.0, 1.0] | generic_unit_system.length) + density = generic_unit_system.density - momentum = generic_unit_system.speed * generic_unit_system.density - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - - + momentum = generic_unit_system.speed * generic_unit_system.density + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + grid.rho = 0.01 | density grid.rhovx = 0.1 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum - + p = 1.0 | (generic_unit_system.mass / (generic_unit_system.length * generic_unit_system.time**2)) - - grid.energy = p / (gamma - 1) - grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho - + + grid.energy = p / (gamma - 1) + grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho + channel = grid.new_channel_to(instance.grid) channel.copy() instance.stopping_conditions.number_of_steps_detection.enable() - - #instance.grid.boundaries.left. - + + # instance.grid.boundaries.left. + xbound1 = instance.get_boundary_grid('xbound1') - self.assertEqual(xbound1.shape, (2,4,4)) + self.assertEqual(xbound1.shape, (2, 4, 4)) memxbound1 = xbound1.copy() memxbound1.rho = 0.02 | density memxbound1.rhovx = 0.2 | momentum memxbound1.rhovy = 0.0 | momentum memxbound1.rhovz = 0.0 | momentum - memxbound1.energy = p / (gamma - 1) - memxbound1.energy += 0.5 * (memxbound1.rhovx ** 2 + memxbound1.rhovy ** 2 + memxbound1.rhovz ** 2) / memxbound1.rho + memxbound1.energy = p / (gamma - 1) + memxbound1.energy += 0.5 * (memxbound1.rhovx ** 2 + memxbound1.rhovy ** 2 + memxbound1.rhovz ** 2) / memxbound1.rho channel = memxbound1.new_channel_to(xbound1) channel.copy() - + instance.evolve_model(1.0 | generic_unit_system.time) self.assertTrue(instance.stopping_conditions.number_of_steps_detection.is_set()) - - rho = instance.grid.rho[...,0,0] + + rho = instance.grid.rho[..., 0, 0] print(rho) print(instance.model_time) self.assertAlmostRelativeEquals(rho[-1], 0.01 | density) self.assertTrue(rho[0] > 0.01 | density) - self.assertTrue(instance.grid.rhovx[0,0,0] > 0.1 | momentum) - self.assertAlmostRelativeEquals(instance.grid.rhovx[-1,0,0] , 0.1 | momentum) - + self.assertTrue(instance.grid.rhovx[0, 0, 0] > 0.1 | momentum) + self.assertAlmostRelativeEquals(instance.grid.rhovx[-1, 0, 0], 0.1 | momentum) + instance.stopping_conditions.number_of_steps_detection.disable() instance.evolve_model(1.0 | generic_unit_system.time) print(instance.model_time) - rho = instance.grid.rho[...,0,0] + rho = instance.grid.rho[..., 0, 0] print(rho) self.assertAlmostRelativeEquals(rho, 0.02 | density, 8) - self.assertAlmostRelativeEquals(instance.grid.rhovx[...,0,0], 0.2 | momentum, 8) + self.assertAlmostRelativeEquals(instance.grid.rhovx[..., 0, 0], 0.2 | momentum, 8) print(instance.model_time) - + instance.stop() - - def test6(self): - instance=self.new_instance(Capreole) - instance.parameters.mesh_size = (10 , 4, 4) + + def test6(self): + instance = self.new_instance(Capreole) + instance.parameters.mesh_size = (10, 4, 4) instance.parameters.mesh_length = [1.0, 1.0, 1.0] | generic_unit_system.length instance.parameters.x_boundary_conditions = ("outflow", "interface") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.z_boundary_conditions = ("periodic", "periodic") instance.parameters.stopping_conditions_number_of_steps = 1 - + gamma = 5.0 / 3.0 - - grid = datamodel.new_regular_grid((10,4,4), [1.0, 1.0, 1.0] | generic_unit_system.length ) - + + grid = datamodel.new_regular_grid((10, 4, 4), [1.0, 1.0, 1.0] | generic_unit_system.length) + density = generic_unit_system.density - momentum = generic_unit_system.speed * generic_unit_system.density - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - - + momentum = generic_unit_system.speed * generic_unit_system.density + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + grid.rho = 0.01 | density grid.rhovx = -0.1 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum - + p = 1.0 | (generic_unit_system.mass / (generic_unit_system.length * generic_unit_system.time**2)) - - grid.energy = p / (gamma - 1) - grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho - + + grid.energy = p / (gamma - 1) + grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho + channel = grid.new_channel_to(instance.grid) channel.copy() instance.stopping_conditions.number_of_steps_detection.enable() - - #instance.grid.boundaries.left. + + # instance.grid.boundaries.left. xbound = instance.get_boundary_grid('xbound2') - self.assertEqual(xbound.shape, (2,4,4)) + self.assertEqual(xbound.shape, (2, 4, 4)) memxbound = xbound.copy() memxbound.rho = 0.02 | density memxbound.rhovx = -0.2 | momentum memxbound.rhovy = 0.0 | momentum memxbound.rhovz = 0.0 | momentum - memxbound.energy = p / (gamma - 1) - memxbound.energy += 0.5 * (memxbound.rhovx ** 2 + memxbound.rhovy ** 2 + memxbound.rhovz ** 2) / memxbound.rho + memxbound.energy = p / (gamma - 1) + memxbound.energy += 0.5 * (memxbound.rhovx ** 2 + memxbound.rhovy ** 2 + memxbound.rhovz ** 2) / memxbound.rho channel = memxbound.new_channel_to(xbound) channel.copy() - + instance.evolve_model(1.0 | generic_unit_system.time) - + self.assertTrue(instance.stopping_conditions.number_of_steps_detection.is_set()) - rho = instance.grid.rho[...,0,0] + rho = instance.grid.rho[..., 0, 0] print(rho) print(instance.model_time) self.assertAlmostRelativeEquals(rho[0], 0.01 | density) self.assertTrue(rho[-1] > 0.01 | density) - self.assertTrue(instance.grid.rhovx[-1,0,0] < -0.1 | momentum) - self.assertAlmostRelativeEquals(instance.grid.rhovx[0,0,0] , -0.1 | momentum) - + self.assertTrue(instance.grid.rhovx[-1, 0, 0] < -0.1 | momentum) + self.assertAlmostRelativeEquals(instance.grid.rhovx[0, 0, 0], -0.1 | momentum) + instance.stopping_conditions.number_of_steps_detection.disable() instance.evolve_model(1.0 | generic_unit_system.time) - rho = instance.grid.rho[...,0,0] + rho = instance.grid.rho[..., 0, 0] self.assertAlmostRelativeEquals(rho, 0.02 | density, 8) - self.assertAlmostRelativeEquals(instance.grid.rhovx[...,0,0], -0.2 | momentum, 8) + self.assertAlmostRelativeEquals(instance.grid.rhovx[..., 0, 0], -0.2 | momentum, 8) print(instance.model_time) - + instance.stop() - - def test7(self): - instance=self.new_instance(Capreole, number_of_workers = 2) - instance.set_parallel_decomposition(1,2,1) - instance.parameters.mesh_size = (10,4,4) + + def test7(self): + instance = self.new_instance(Capreole, number_of_workers=2) + instance.set_parallel_decomposition(1, 2, 1) + instance.parameters.mesh_size = (10, 4, 4) instance.parameters.mesh_length = [1.0, 1.0, 1.0] | generic_unit_system.length instance.parameters.x_boundary_conditions = ("interface", "outflow") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.stopping_conditions_number_of_steps = 1 - - + gamma = 5.0 / 3.0 - - grid = datamodel.new_regular_grid((10,4,4), [1.0, 1.0, 1.0] | generic_unit_system.length ) - + + grid = datamodel.new_regular_grid((10, 4, 4), [1.0, 1.0, 1.0] | generic_unit_system.length) + density = generic_unit_system.density - momentum = generic_unit_system.speed * generic_unit_system.density - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - - + momentum = generic_unit_system.speed * generic_unit_system.density + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + grid.rho = 0.01 | density grid.rhovx = 0.1 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum - + p = 1.0 | (generic_unit_system.mass / (generic_unit_system.length * generic_unit_system.time**2)) - - grid.energy = p / (gamma - 1) - grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho - + + grid.energy = p / (gamma - 1) + grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho + channel = grid.new_channel_to(instance.grid) channel.copy() instance.stopping_conditions.number_of_steps_detection.enable() - - #instance.grid.boundaries.left. - + + # instance.grid.boundaries.left. + xbound1 = instance.get_boundary_grid('xbound1') - self.assertEqual(xbound1.shape, (2,4,4)) + self.assertEqual(xbound1.shape, (2, 4, 4)) memxbound1 = xbound1.copy() memxbound1.rho = 0.02 | density memxbound1.rhovx = 0.2 | momentum memxbound1.rhovy = 0.0 | momentum memxbound1.rhovz = 0.0 | momentum - memxbound1.energy = p / (gamma - 1) - memxbound1.energy += 0.5 * (memxbound1.rhovx ** 2 + memxbound1.rhovy ** 2 + memxbound1.rhovz ** 2) / memxbound1.rho + memxbound1.energy = p / (gamma - 1) + memxbound1.energy += 0.5 * (memxbound1.rhovx ** 2 + memxbound1.rhovy ** 2 + memxbound1.rhovz ** 2) / memxbound1.rho channel = memxbound1.new_channel_to(xbound1) channel.copy() - + instance.evolve_model(1.0 | generic_unit_system.time) self.assertTrue(instance.stopping_conditions.number_of_steps_detection.is_set()) - - rho = instance.grid.rho[...,0,0] + + rho = instance.grid.rho[..., 0, 0] print(rho) print(instance.model_time) self.assertAlmostRelativeEquals(rho[-1], 0.01 | density) self.assertTrue(rho[0] > 0.01 | density) - self.assertTrue(instance.grid.rhovx[0,0,0] > 0.1 | momentum) - self.assertAlmostRelativeEquals(instance.grid.rhovx[-1,0,0] , 0.1 | momentum) - + self.assertTrue(instance.grid.rhovx[0, 0, 0] > 0.1 | momentum) + self.assertAlmostRelativeEquals(instance.grid.rhovx[-1, 0, 0], 0.1 | momentum) + instance.stopping_conditions.number_of_steps_detection.disable() instance.evolve_model(1.0 | generic_unit_system.time) print(instance.model_time) - rho = instance.grid.rho[...,0,0] + rho = instance.grid.rho[..., 0, 0] print(rho) self.assertAlmostRelativeEquals(rho, 0.02 | density, 8) - self.assertAlmostRelativeEquals(instance.grid.rhovx[...,0,0], 0.2 | momentum, 8) + self.assertAlmostRelativeEquals(instance.grid.rhovx[..., 0, 0], 0.2 | momentum, 8) print(instance.model_time) - + instance.stop() - def test8(self): - instance=self.new_instance(Capreole, number_of_workers = 1) - #instance.set_parallel_decomposition(2,1,1) - instance.parameters.mesh_size = (4,10,4) + def test8(self): + instance = self.new_instance(Capreole, number_of_workers=1) + # instance.set_parallel_decomposition(2,1,1) + instance.parameters.mesh_size = (4, 10, 4) instance.parameters.mesh_length = [1.0, 1.0, 1.0] | generic_unit_system.length instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.y_boundary_conditions = ("interface", "outflow") instance.parameters.z_boundary_conditions = ("periodic", "periodic") instance.parameters.stopping_conditions_number_of_steps = 1 - - + gamma = 5.0 / 3.0 - - grid = datamodel.new_regular_grid((4,10,4), [1.0, 1.0, 1.0] | generic_unit_system.length ) - + + grid = datamodel.new_regular_grid((4, 10, 4), [1.0, 1.0, 1.0] | generic_unit_system.length) + density = generic_unit_system.density - momentum = generic_unit_system.speed * generic_unit_system.density - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - - + momentum = generic_unit_system.speed * generic_unit_system.density + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + grid.rho = 0.01 | density grid.rhovx = 0.0 | momentum grid.rhovy = 0.1 | momentum grid.rhovz = 0.0 | momentum - + p = 1.0 | (generic_unit_system.mass / (generic_unit_system.length * generic_unit_system.time**2)) - - grid.energy = p / (gamma - 1) - grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho - + + grid.energy = p / (gamma - 1) + grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho + channel = grid.new_channel_to(instance.grid) channel.copy() instance.stopping_conditions.number_of_steps_detection.enable() - + ybound = instance.get_boundary_grid('ybound1') - self.assertEqual(ybound.shape, (4+4,2,4)) + self.assertEqual(ybound.shape, (4+4, 2, 4)) memybound = ybound.copy() memybound.rho = 0.02 | density memybound.rhovx = 0.0 | momentum memybound.rhovy = 0.2 | momentum memybound.rhovz = 0.0 | momentum - memybound.energy = p / (gamma - 1) - memybound.energy += 0.5 * (memybound.rhovx ** 2 + memybound.rhovy ** 2 + memybound.rhovz ** 2) / memybound.rho - + memybound.energy = p / (gamma - 1) + memybound.energy += 0.5 * (memybound.rhovx ** 2 + memybound.rhovy ** 2 + memybound.rhovz ** 2) / memybound.rho + channel = memybound.new_channel_to(ybound) channel.copy() - + instance.evolve_model(1.0 | generic_unit_system.time) print(instance.stopping_conditions.number_of_steps_detection.is_set()) - - print(instance.grid.rho[0,...,0]) - rho = instance.grid.rho[0,...,0] + + print(instance.grid.rho[0, ..., 0]) + rho = instance.grid.rho[0, ..., 0] self.assertAlmostRelativeEquals(rho[-1], 0.01 | density) self.assertTrue(rho[0] > 0.01 | density) - self.assertTrue(instance.grid.rhovy[0,0,0] > 0.1 | momentum) - self.assertAlmostRelativeEquals(instance.grid.rhovy[0,-1,0] , 0.1 | momentum) + self.assertTrue(instance.grid.rhovy[0, 0, 0] > 0.1 | momentum) + self.assertAlmostRelativeEquals(instance.grid.rhovy[0, -1, 0], 0.1 | momentum) print(instance.model_time) - + instance.stopping_conditions.number_of_steps_detection.disable() instance.evolve_model(1.0 | generic_unit_system.time) - rho = instance.grid.rho[0,...,0] + rho = instance.grid.rho[0, ..., 0] self.assertAlmostRelativeEquals(rho, 0.02 | density, 8) - self.assertAlmostRelativeEquals(instance.grid.rhovy[0,...,0], 0.2 | momentum, 8) + self.assertAlmostRelativeEquals(instance.grid.rhovy[0, ..., 0], 0.2 | momentum, 8) print(instance.model_time) - + instance.stop() - - def test9(self): - instance=self.new_instance(Capreole, number_of_workers = 1) - #instance.set_parallel_decomposition(2,1,1) - instance.parameters.mesh_size = (4,10,4) + def test9(self): + instance = self.new_instance(Capreole, number_of_workers=1) + # instance.set_parallel_decomposition(2,1,1) + instance.parameters.mesh_size = (4, 10, 4) instance.parameters.mesh_length = [1.0, 1.0, 1.0] | generic_unit_system.length instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.y_boundary_conditions = ("outflow", "interface") instance.parameters.z_boundary_conditions = ("periodic", "periodic") instance.parameters.stopping_conditions_number_of_steps = 1 - - + gamma = 5.0 / 3.0 - - grid = datamodel.new_regular_grid((4,10,4), [1.0, 1.0, 1.0] | generic_unit_system.length ) - + + grid = datamodel.new_regular_grid((4, 10, 4), [1.0, 1.0, 1.0] | generic_unit_system.length) + density = generic_unit_system.density - momentum = generic_unit_system.speed * generic_unit_system.density - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - - + momentum = generic_unit_system.speed * generic_unit_system.density + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + grid.rho = 0.01 | density grid.rhovx = 0.0 | momentum grid.rhovy = -0.1 | momentum grid.rhovz = 0.0 | momentum - + p = 1.0 | (generic_unit_system.mass / (generic_unit_system.length * generic_unit_system.time**2)) - - grid.energy = p / (gamma - 1) - grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho - + + grid.energy = p / (gamma - 1) + grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho + channel = grid.new_channel_to(instance.grid) channel.copy() instance.stopping_conditions.number_of_steps_detection.enable() - + ybound = instance.get_boundary_grid('ybound2') - self.assertEqual(ybound.shape, (4+4,2,4)) + self.assertEqual(ybound.shape, (4+4, 2, 4)) memybound = ybound.copy() memybound.rho = 0.02 | density memybound.rhovx = 0.0 | momentum memybound.rhovy = -0.2 | momentum memybound.rhovz = 0.0 | momentum - memybound.energy = p / (gamma - 1) - memybound.energy += 0.5 * (memybound.rhovx ** 2 + memybound.rhovy ** 2 + memybound.rhovz ** 2) / memybound.rho - + memybound.energy = p / (gamma - 1) + memybound.energy += 0.5 * (memybound.rhovx ** 2 + memybound.rhovy ** 2 + memybound.rhovz ** 2) / memybound.rho + channel = memybound.new_channel_to(ybound) channel.copy() - + instance.evolve_model(1.0 | generic_unit_system.time) print(instance.stopping_conditions.number_of_steps_detection.is_set()) - print(instance.grid.rho[0,...,0]) - rho = instance.grid.rho[0,...,0] + print(instance.grid.rho[0, ..., 0]) + rho = instance.grid.rho[0, ..., 0] self.assertAlmostRelativeEquals(rho[0], 0.01 | density) self.assertTrue(rho[-1] > 0.01 | density) - self.assertTrue(instance.grid.rhovy[0,-1,0] < 0.1 | momentum) - self.assertAlmostRelativeEquals(instance.grid.rhovy[0,0,0] , -0.1 | momentum) + self.assertTrue(instance.grid.rhovy[0, -1, 0] < 0.1 | momentum) + self.assertAlmostRelativeEquals(instance.grid.rhovy[0, 0, 0], -0.1 | momentum) print(instance.model_time) - + instance.stopping_conditions.number_of_steps_detection.disable() instance.evolve_model(1.0 | generic_unit_system.time) - rho = instance.grid.rho[0,...,0] + rho = instance.grid.rho[0, ..., 0] self.assertAlmostRelativeEquals(rho, 0.02 | density, 8) - self.assertAlmostRelativeEquals(instance.grid.rhovy[0,...,0], -0.2 | momentum, 8) + self.assertAlmostRelativeEquals(instance.grid.rhovy[0, ..., 0], -0.2 | momentum, 8) print(instance.model_time) - + instance.stop() - - def test10(self): - instance=self.new_instance(Capreole, number_of_workers = 1) - #instance.set_parallel_decomposition(2,1,1) - instance.parameters.mesh_size = (4,4,10) + + def test10(self): + instance = self.new_instance(Capreole, number_of_workers=1) + # instance.set_parallel_decomposition(2,1,1) + instance.parameters.mesh_size = (4, 4, 10) instance.parameters.mesh_length = [1.0, 1.0, 1.0] | generic_unit_system.length instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.z_boundary_conditions = ("interface", "outflow") instance.parameters.stopping_conditions_number_of_steps = 1 - - + gamma = 5.0 / 3.0 - - grid = datamodel.new_regular_grid((4,4,10), [1.0, 1.0, 1.0] | generic_unit_system.length ) - + + grid = datamodel.new_regular_grid((4, 4, 10), [1.0, 1.0, 1.0] | generic_unit_system.length) + density = generic_unit_system.density - momentum = generic_unit_system.speed * generic_unit_system.density - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - - + momentum = generic_unit_system.speed * generic_unit_system.density + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + grid.rho = 0.01 | density grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.1 | momentum - + p = 1.0 | (generic_unit_system.mass / (generic_unit_system.length * generic_unit_system.time**2)) - - grid.energy = p / (gamma - 1) - grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho - + + grid.energy = p / (gamma - 1) + grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho + channel = grid.new_channel_to(instance.grid) channel.copy() instance.stopping_conditions.number_of_steps_detection.enable() - + ybound = instance.get_boundary_grid('zbound1') - self.assertEqual(ybound.shape, (4+4,4+4,2)) + self.assertEqual(ybound.shape, (4+4, 4+4, 2)) memybound = ybound.copy() memybound.rho = 0.02 | density memybound.rhovx = 0.0 | momentum memybound.rhovy = 0.0 | momentum memybound.rhovz = 0.2 | momentum - memybound.energy = p / (gamma - 1) - memybound.energy += 0.5 * (memybound.rhovx ** 2 + memybound.rhovy ** 2 + memybound.rhovz ** 2) / memybound.rho - + memybound.energy = p / (gamma - 1) + memybound.energy += 0.5 * (memybound.rhovx ** 2 + memybound.rhovy ** 2 + memybound.rhovz ** 2) / memybound.rho + channel = memybound.new_channel_to(ybound) channel.copy() - + instance.evolve_model(1.0 | generic_unit_system.time) self.assertTrue(instance.stopping_conditions.number_of_steps_detection.is_set()) - - rho = instance.grid.rho[0,0,...] + + rho = instance.grid.rho[0, 0, ...] print(rho) self.assertAlmostRelativeEquals(rho[-1], 0.01 | density) self.assertTrue(rho[0] > 0.01 | density) - self.assertTrue(instance.grid.rhovz[0,0,0] > 0.1 | momentum) - self.assertAlmostRelativeEquals(instance.grid.rhovz[0,0,-1] , 0.1 | momentum) + self.assertTrue(instance.grid.rhovz[0, 0, 0] > 0.1 | momentum) + self.assertAlmostRelativeEquals(instance.grid.rhovz[0, 0, -1], 0.1 | momentum) print(instance.model_time) - + instance.stopping_conditions.number_of_steps_detection.disable() instance.evolve_model(1.0 | generic_unit_system.time) - rho = instance.grid.rho[0,0,...] + rho = instance.grid.rho[0, 0, ...] self.assertAlmostRelativeEquals(rho, 0.02 | density, 8) - self.assertAlmostRelativeEquals(instance.grid.rhovz[0,...,0], 0.2 | momentum, 8) + self.assertAlmostRelativeEquals(instance.grid.rhovz[0, ..., 0], 0.2 | momentum, 8) print(instance.model_time) - + instance.stop() - - def test11(self): - instance=self.new_instance(Capreole, number_of_workers = 2) - instance.set_parallel_decomposition(2,1,1) - instance.parameters.mesh_size = (4,4,10) + def test11(self): + instance = self.new_instance(Capreole, number_of_workers=2) + instance.set_parallel_decomposition(2, 1, 1) + instance.parameters.mesh_size = (4, 4, 10) instance.parameters.mesh_length = [1.0, 1.0, 1.0] | generic_unit_system.length instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.z_boundary_conditions = ("outflow", "interface") instance.parameters.stopping_conditions_number_of_steps = 1 - - + gamma = 5.0 / 3.0 - - grid = datamodel.new_regular_grid((4,4,10), [1.0, 1.0, 1.0] | generic_unit_system.length ) - + + grid = datamodel.new_regular_grid((4, 4, 10), [1.0, 1.0, 1.0] | generic_unit_system.length) + density = generic_unit_system.density - momentum = generic_unit_system.speed * generic_unit_system.density - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - - + momentum = generic_unit_system.speed * generic_unit_system.density + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + grid.rho = 0.01 | density grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = -0.10 | momentum - + p = 1.0 | (generic_unit_system.mass / (generic_unit_system.length * generic_unit_system.time**2)) - - grid.energy = p / (gamma - 1) - grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho - + + grid.energy = p / (gamma - 1) + grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho + channel = grid.new_channel_to(instance.grid) channel.copy() instance.stopping_conditions.number_of_steps_detection.enable() - + ybound = instance.get_boundary_grid('zbound2') - self.assertEqual(ybound.shape, (4+4,4+4,2)) + self.assertEqual(ybound.shape, (4+4, 4+4, 2)) memybound = ybound.copy() memybound.rho = 0.02 | density memybound.rhovx = 0.0 | momentum memybound.rhovy = 0.0 | momentum memybound.rhovz = -0.2 | momentum - memybound.energy = p / (gamma - 1) - memybound.energy += 0.5 * (memybound.rhovx ** 2 + memybound.rhovy ** 2 + memybound.rhovz ** 2) / memybound.rho - + memybound.energy = p / (gamma - 1) + memybound.energy += 0.5 * (memybound.rhovx ** 2 + memybound.rhovy ** 2 + memybound.rhovz ** 2) / memybound.rho + channel = memybound.new_channel_to(ybound) channel.copy() - + instance.evolve_model(1.0 | generic_unit_system.time) self.assertTrue(instance.stopping_conditions.number_of_steps_detection.is_set()) - rho = instance.grid.rho[0,0,...] + rho = instance.grid.rho[0, 0, ...] self.assertAlmostRelativeEquals(rho[0], 0.01 | density) self.assertTrue(rho[-1] > 0.01 | density) - self.assertTrue(instance.grid.rhovz[0,0,-1] < 0.1 | momentum) - self.assertAlmostRelativeEquals(instance.grid.rhovz[0,0,0] , -0.1 | momentum) + self.assertTrue(instance.grid.rhovz[0, 0, -1] < 0.1 | momentum) + self.assertAlmostRelativeEquals(instance.grid.rhovz[0, 0, 0], -0.1 | momentum) print(instance.model_time) - + instance.stopping_conditions.number_of_steps_detection.disable() instance.evolve_model(1.0 | generic_unit_system.time) - rho = instance.grid.rho[0,0,...] + rho = instance.grid.rho[0, 0, ...] self.assertAlmostRelativeEquals(rho, 0.02 | density, 8) - self.assertAlmostRelativeEquals(instance.grid.rhovz[0,0,...], -0.2 | momentum, 8) + self.assertAlmostRelativeEquals(instance.grid.rhovz[0, 0, ...], -0.2 | momentum, 8) print(instance.model_time) - + instance.stop() - - + def test12(self): - - instance=self.new_instance(Capreole) - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") - instance.parameters.z_boundary_conditions = ("periodic","periodic") + + instance = self.new_instance(Capreole) + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") + instance.parameters.z_boundary_conditions = ("periodic", "periodic") instance.parameters.mesh_length = (20.0, 1, 1) | generic_unit_system.length instance.parameters.mesh_size = (20, 2, 2) - + for x in instance.itergrids(): inmem = x.copy() - inmem.rho = inmem.x/(1| generic_unit_system.length) | generic_unit_system.density + inmem.rho = inmem.x/(1 | generic_unit_system.length) | generic_unit_system.density inmem.rhovx = 0.0 | generic_unit_system.momentum_density - inmem.energy = 1.0 | generic_unit_system.energy_density + inmem.energy = 1.0 | generic_unit_system.energy_density from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() print(inmem.rho) - rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5| generic_unit_system.length,0.0| generic_unit_system.length,0.0| generic_unit_system.length) - - self.assertEqual(rho , 0.5 | generic_unit_system.density) - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5 | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length) + + self.assertEqual(rho, 0.5 | generic_unit_system.density) + for value in numpy.arange(0.5, 19.6, 0.1): - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( value | generic_unit_system.length, 0.5 | generic_unit_system.length, 0.5 | generic_unit_system.length ) - - self.assertAlmostRelativeEquals(rho , value | generic_unit_system.density) - + + self.assertAlmostRelativeEquals(rho, value | generic_unit_system.density) + for value in numpy.arange(0.0, 0.6, 0.1): rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( value | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length ) - self.assertAlmostRelativeEquals(rho , ((0.5 + value) * 0.5 + (0.5-value) * 19.5) | generic_unit_system.density) - - + self.assertAlmostRelativeEquals(rho, ((0.5 + value) * 0.5 + (0.5-value) * 19.5) | generic_unit_system.density) + for value in numpy.arange(0.0, 0.5, 0.1): rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( - value + 19.5| generic_unit_system.length, + value + 19.5 | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length ) - self.assertAlmostRelativeEquals(rho , (19.5 - (value * 19)) | generic_unit_system.density, 9) - + self.assertAlmostRelativeEquals(rho, (19.5 - (value * 19)) | generic_unit_system.density, 9) + # out of range rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( - 20.0| generic_unit_system.length, + 20.0 | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length ) - self.assertAlmostRelativeEquals(rho , 0.0 | generic_unit_system.density, 9) + self.assertAlmostRelativeEquals(rho, 0.0 | generic_unit_system.density, 9) def test13(self): - - instance=self.new_instance(Capreole, number_of_workers=2) - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") + + instance = self.new_instance(Capreole, number_of_workers=2) + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.mesh_length = (20.0, 20.0, 4) | generic_unit_system.length instance.parameters.mesh_length = (20.0, 20.0, 4) | generic_unit_system.length instance.parameters.mesh_size = (20, 20, 2) - + for x in instance.itergrids(): inmem = x.copy() - inmem.rho = (inmem.x + ((inmem.y - (0.5| generic_unit_system.length))* 20.0))/(1| generic_unit_system.length) | generic_unit_system.density + inmem.rho = (inmem.x + ((inmem.y - (0.5 | generic_unit_system.length)) * 20.0))/(1 | generic_unit_system.length) | generic_unit_system.density inmem.rhovx = 0.0 | generic_unit_system.momentum_density - inmem.energy = 1.0 | generic_unit_system.energy_density + inmem.energy = 1.0 | generic_unit_system.energy_density from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() print(inmem.rho[0], inmem.y[0], inmem.x[0]) - rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5| generic_unit_system.length,0.5| generic_unit_system.length,0.0| generic_unit_system.length) - - self.assertEqual(rho , 0.5 | generic_unit_system.density) - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5 | generic_unit_system.length, 0.5 | generic_unit_system.length, 0.0 | generic_unit_system.length) + + self.assertEqual(rho, 0.5 | generic_unit_system.density) + for value in numpy.arange(0.5, 19.6, 0.1): - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( value | generic_unit_system.length, 0.5 | generic_unit_system.length, 0.0 | generic_unit_system.length ) - - self.assertAlmostRelativeEquals(rho , value | generic_unit_system.density) - + + self.assertAlmostRelativeEquals(rho, value | generic_unit_system.density) + for x in numpy.arange(8.5, 11.5, 0.25): for y in numpy.arange(0.5, 19.6, 0.25): rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( @@ -1729,47 +1683,47 @@ def test13(self): y | generic_unit_system.length, 0.0 | generic_unit_system.length ) - - self.assertAlmostRelativeEquals(rho , x + (20 * (y-0.5)) | generic_unit_system.density) - + + self.assertAlmostRelativeEquals(rho, x + (20 * (y-0.5)) | generic_unit_system.density) + def test14(self): - - instance=self.new_instance(Capreole, number_of_workers=3) - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") - instance.parameters.z_boundary_conditions = ("periodic","periodic") + + instance = self.new_instance(Capreole, number_of_workers=3) + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") + instance.parameters.z_boundary_conditions = ("periodic", "periodic") instance.parameters.mesh_length = (20.0, 20.0, 20.0) | generic_unit_system.length instance.parameters.mesh_length = (20.0, 20.0, 20.0) | generic_unit_system.length instance.parameters.mesh_size = (20, 20, 20) - + for x in instance.itergrids(): inmem = x.copy() inmem.rho = ( ( - inmem.x + - ((inmem.y - (0.5| generic_unit_system.length))* 20.0) + - ((inmem.z - (0.5| generic_unit_system.length))* 400.0) + inmem.x + + ((inmem.y - (0.5 | generic_unit_system.length)) * 20.0) + + ((inmem.z - (0.5 | generic_unit_system.length)) * 400.0) ) - /(1| generic_unit_system.length) | generic_unit_system.density + / (1 | generic_unit_system.length) | generic_unit_system.density ) inmem.rhovx = 0.0 | generic_unit_system.momentum_density - inmem.energy = 1.0 | generic_unit_system.energy_density + inmem.energy = 1.0 | generic_unit_system.energy_density from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() - rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5| generic_unit_system.length,0.5| generic_unit_system.length,0.5| generic_unit_system.length) - - self.assertEqual(rho , 0.5 | generic_unit_system.density) - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5 | generic_unit_system.length, 0.5 | generic_unit_system.length, 0.5 | generic_unit_system.length) + + self.assertEqual(rho, 0.5 | generic_unit_system.density) + for value in numpy.arange(0.5, 19.6, 0.1): - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( value | generic_unit_system.length, 0.5 | generic_unit_system.length, 0.5 | generic_unit_system.length ) - - self.assertAlmostRelativeEquals(rho , value | generic_unit_system.density) - + + self.assertAlmostRelativeEquals(rho, value | generic_unit_system.density) + sample = datamodel.new_regular_grid( (4, 4, 76), (2, 2, 19) | generic_unit_system.length @@ -1780,48 +1734,42 @@ def test14(self): x = sample.x.flatten() y = sample.y.flatten() z = sample.z.flatten() - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( x, y, z ) half = 0.5 | generic_unit_system.length - - self.assertAlmostRelativeEquals(rho , (x + (20 * (y-half)) + (400 * (z-half)))/(1| generic_unit_system.length) | generic_unit_system.density ) - - - def test15(self): - instance=self.new_instance(Capreole, number_of_workers = 1) + self.assertAlmostRelativeEquals(rho, (x + (20 * (y-half)) + (400 * (z-half)))/(1 | generic_unit_system.length) | generic_unit_system.density) + + def test15(self): + instance = self.new_instance(Capreole, number_of_workers=1) self.assertAlmostRelativeEquals(instance.parameters.gamma, 5.0 / 3.0) instance.parameters.gamma = 1.2 self.assertAlmostRelativeEquals(instance.parameters.gamma, 1.2) - #self.assertAlmostRelativeEquals(instance.parameters.timestep, 0.1 | generic_unit_system.time) - #instance.parameters.timestep = 0.2 | generic_unit_system.time - #self.assertAlmostRelativeEquals(instance.parameters.timestep, 0.2 | generic_unit_system.time) - - + # self.assertAlmostRelativeEquals(instance.parameters.timestep, 0.1 | generic_unit_system.time) + # instance.parameters.timestep = 0.2 | generic_unit_system.time + # self.assertAlmostRelativeEquals(instance.parameters.timestep, 0.2 | generic_unit_system.time) def test16(self): - - instance=self.new_instance(Capreole) - instance.parameters.x_boundary_conditions = ("periodic","periodic") + + instance = self.new_instance(Capreole) + instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.mesh_length = (8, 1, 1) | generic_unit_system.length instance.parameters.mesh_size = (8, 1, 1) - + for x in instance.itergrids(): inmem = x.copy() - inmem.rho = inmem.x/(1| generic_unit_system.length) | generic_unit_system.density + inmem.rho = inmem.x/(1 | generic_unit_system.length) | generic_unit_system.density inmem.rhovx = 0.0 | generic_unit_system.momentum_density - inmem.energy = 1.0 | generic_unit_system.energy_density + inmem.energy = 1.0 | generic_unit_system.energy_density from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() print(inmem.rho) - + grid = instance.get_extended_grid() - self.assertEqual(grid.shape, (12,1,1)) + self.assertEqual(grid.shape, (12, 1, 1)) instance.initialize_grid() - self.assertEqual(grid.rho[...,0,0] , [6.5,7.5,0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,0.5,1.5] | generic_unit_system.density) - - + self.assertEqual(grid.rho[..., 0, 0], [6.5, 7.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 0.5, 1.5] | generic_unit_system.density) diff --git a/src/amuse/test/suite/codes_tests/test_create_dir.py b/src/amuse/test/suite/codes_tests/test_create_dir.py index 01270c2b63..d460dcbf6a 100644 --- a/src/amuse/test/suite/codes_tests/test_create_dir.py +++ b/src/amuse/test/suite/codes_tests/test_create_dir.py @@ -6,161 +6,152 @@ from amuse.rfi.tools import create_dir + class CreateADirectoryAndPopulateItWithFilesForACommunityCodeTest(amusetest.TestWithMPI): - + def setUp(self): - + self.check_can_compile_modules() - - + def test1(self): instance = create_dir.CreateADirectoryAndPopulateItWithFilesForACCode() instance.name_of_the_code_interface_class = 'TestCode' self.assertEqual(instance.name_of_the_community_code, 'testcode') self.assertTrue(instance.path_of_the_community_code.endswith('testcode')) - + def test2(self): root = self.get_path_to_results() working_dir = os.path.join(root, 'testcode') - + print(working_dir) - + if os.path.exists(working_dir): shutil.rmtree(working_dir) - + instance = create_dir.CreateADirectoryAndPopulateItWithFilesForACCode() instance.name_of_the_code_interface_class = 'TestCode' instance.path_of_the_root_directory = root - #~ if create_dir.CreateADirectoryAndPopulateItWithFiles().amuse_root_dir == os.getcwd(): - #~ self.assertEqual(instance.reference_to_amuse_path,'../..') - + # ~ if create_dir.CreateADirectoryAndPopulateItWithFiles().amuse_root_dir == os.getcwd(): + # ~ self.assertEqual(instance.reference_to_amuse_path,'../..') + instance.start() - + self.assertTrue(os.path.exists(working_dir)) - self.assertTrue(os.path.exists(os.path.join(working_dir,'interface.py'))) - self.assertTrue(os.path.exists(os.path.join(working_dir,'Makefile'))) - - - + self.assertTrue(os.path.exists(os.path.join(working_dir, 'interface.py'))) + self.assertTrue(os.path.exists(os.path.join(working_dir, 'Makefile'))) + call = subprocess.Popen( 'make', - cwd=working_dir, + cwd=working_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) outputstring, errorstring = call.communicate() - - + self.assertEqual(call.returncode, 0) - - self.assertTrue(os.path.exists(os.path.join(working_dir,'testcode_worker'))) - + + self.assertTrue(os.path.exists(os.path.join(working_dir, 'testcode_worker'))) + sys.path.insert(0, root) - + try: __import__('testcode.interface') except: self.fail("import of code failed") - + module = sys.modules['testcode.interface'] instance = module.TestCode() result = instance.echo_int(12) - + self.assertEqual(result, 12) - + instance.stop() - + del sys.path[0] - - self.assertTrue(os.path.exists(os.path.join(working_dir,'worker_code.cc'))) + + self.assertTrue(os.path.exists(os.path.join(working_dir, 'worker_code.cc'))) call = subprocess.Popen( ['make', 'clean'], - cwd=working_dir, + cwd=working_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) outputstring, errorstring = call.communicate() - + print(errorstring) - self.assertFalse(os.path.exists(os.path.join(working_dir,'worker_code.cc'))) - + self.assertFalse(os.path.exists(os.path.join(working_dir, 'worker_code.cc'))) + self.assertEqual(call.returncode, 0) - + if os.path.exists(working_dir): shutil.rmtree(working_dir) - + def test3(self): root = self.get_path_to_results() working_dir = os.path.join(root, 'testcodef') - + print(working_dir) - + if os.path.exists(working_dir): shutil.rmtree(working_dir) - + instance = create_dir.CreateADirectoryAndPopulateItWithFilesForAFortranCode() instance.name_of_the_code_interface_class = 'TestCodeF' instance.path_of_the_root_directory = root - #~ if create_dir.CreateADirectoryAndPopulateItWithFiles().amuse_root_dir == os.getcwd(): - #~ self.assertEqual(instance.reference_to_amuse_path,'../..') - + # ~ if create_dir.CreateADirectoryAndPopulateItWithFiles().amuse_root_dir == os.getcwd(): + # ~ self.assertEqual(instance.reference_to_amuse_path,'../..') + instance.start() - + self.assertTrue(os.path.exists(working_dir)) - self.assertTrue(os.path.exists(os.path.join(working_dir,'interface.py'))) - self.assertTrue(os.path.exists(os.path.join(working_dir,'Makefile'))) - + self.assertTrue(os.path.exists(os.path.join(working_dir, 'interface.py'))) + self.assertTrue(os.path.exists(os.path.join(working_dir, 'Makefile'))) + call = subprocess.Popen( 'make', - cwd=working_dir, + cwd=working_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) outputstring, errorstring = call.communicate() - + print(errorstring) - + self.assertEqual(call.returncode, 0) - - self.assertTrue(os.path.exists(os.path.join(working_dir,'testcodef_worker'))) - - + + self.assertTrue(os.path.exists(os.path.join(working_dir, 'testcodef_worker'))) + sys.path.insert(0, root) - + try: __import__('testcodef.interface') except: self.fail("import of code failed") - + module = sys.modules['testcodef.interface'] instance = module.TestCodeF() result = instance.echo_int(12) - + self.assertEqual(result, 12) - + instance.stop() - + del sys.path[0] - - self.assertTrue(os.path.exists(os.path.join(working_dir,'worker_code.f90'))) - + + self.assertTrue(os.path.exists(os.path.join(working_dir, 'worker_code.f90'))) + call = subprocess.Popen( ['make', 'clean'], - cwd=working_dir, + cwd=working_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) outputstring, errorstring = call.communicate() print(errorstring) - - self.assertFalse(os.path.exists(os.path.join(working_dir,'worker_code.f90'))) - + + self.assertFalse(os.path.exists(os.path.join(working_dir, 'worker_code.f90'))) + self.assertEqual(call.returncode, 0) - - + # if os.path.exists(working_dir): # shutil.rmtree(working_dir) - - - - diff --git a/src/amuse/test/suite/codes_tests/test_encounters.py b/src/amuse/test/suite/codes_tests/test_encounters.py index 9e4654f0c6..80ab2df458 100644 --- a/src/amuse/test/suite/codes_tests/test_encounters.py +++ b/src/amuse/test/suite/codes_tests/test_encounters.py @@ -12,15 +12,16 @@ from amuse.couple import encounters -#codes to use +# codes to use from amuse.community.kepler.interface import Kepler from amuse.community.smalln.interface import SmallN + def new_binary( mass1, mass2, semi_major_axis, - eccentricity = 0, keyoffset = 1, - is_at_periapsis = True, - G = nbody_system.G + eccentricity=0, keyoffset=1, + is_at_periapsis=True, + G=nbody_system.G ): total_mass = mass1 + mass2 mass_fraction_particle_1 = mass1 / (total_mass) @@ -30,29 +31,30 @@ def new_binary( binary[1].mass = mass2 binary.child1 = None binary.child2 = None - + mu = G * total_mass if is_at_periapsis: - velocity = numpy.sqrt( mu / semi_major_axis * ((1.0 + eccentricity)/(1.0 - eccentricity))) - radius = semi_major_axis * (1.0 - eccentricity) + velocity = numpy.sqrt(mu / semi_major_axis * ((1.0 + eccentricity)/(1.0 - eccentricity))) + radius = semi_major_axis * (1.0 - eccentricity) else: - velocity = numpy.sqrt( mu / semi_major_axis * ((1.0 - eccentricity)/(1.0 + eccentricity))) - radius = semi_major_axis * (1.0 + eccentricity) - - binary[0].position = ((1.0 - mass_fraction_particle_1) * radius * [1.0,0.0,0.0]) - binary[1].position = -(mass_fraction_particle_1 * radius * [1.0,0.0,0.0]) + velocity = numpy.sqrt(mu / semi_major_axis * ((1.0 - eccentricity)/(1.0 + eccentricity))) + radius = semi_major_axis * (1.0 + eccentricity) - binary[0].velocity = ((1.0 - mass_fraction_particle_1) * velocity * [0.0,1.0,0.0]) - binary[1].velocity = -(mass_fraction_particle_1 * velocity * [0.0,1.0,0.0]) + binary[0].position = ((1.0 - mass_fraction_particle_1) * radius * [1.0, 0.0, 0.0]) + binary[1].position = -(mass_fraction_particle_1 * radius * [1.0, 0.0, 0.0]) + + binary[0].velocity = ((1.0 - mass_fraction_particle_1) * velocity * [0.0, 1.0, 0.0]) + binary[1].velocity = -(mass_fraction_particle_1 * velocity * [0.0, 1.0, 0.0]) return binary - + + class TryHandleEncounter(encounters.AbstractHandleEncounter, encounters.SelectNeighboursByDistanceMixin): - + def __init__(self, kepler_code, - G = nbody_system.G + G=nbody_system.G ): encounters.AbstractHandleEncounter.__init__( self, @@ -60,382 +62,370 @@ def __init__(self, G ) encounters.SelectNeighboursByDistanceMixin.__init__(self) - + + class TestAbstractHandleEncounter(amusetest.TestWithMPI): - + def new_kepler(self): x = Kepler() x.initialize_code() return x - + def test1(self): particles_in_encounter = Particles(2) particles_in_encounter.mass = 1 | nbody_system.mass - particles_in_encounter[0].position = [1,0,0] | nbody_system.length - particles_in_encounter[1].position = [0,0,0] | nbody_system.length - particles_in_encounter.velocity = [0,0.5,0] | nbody_system.speed + particles_in_encounter[0].position = [1, 0, 0] | nbody_system.length + particles_in_encounter[1].position = [0, 0, 0] | nbody_system.length + particles_in_encounter.velocity = [0, 0.5, 0] | nbody_system.speed particles_in_encounter.radius = 0 | nbody_system.length - + particles_in_field = Particles(5) - particles_in_field.mass = [1,2,3,4,5] | nbody_system.mass - particles_in_field[0].position = [2,0,0] | nbody_system.length - particles_in_field[1].position = [1.5,0,0] | nbody_system.length - particles_in_field[2].position = [0.5,1,0] | nbody_system.length - particles_in_field[3].position = [0.5,-0.5,0] | nbody_system.length - particles_in_field[4].position = [0,0,2] | nbody_system.length - particles_in_field.velocity = [0,0.0,0] | nbody_system.speed + particles_in_field.mass = [1, 2, 3, 4, 5] | nbody_system.mass + particles_in_field[0].position = [2, 0, 0] | nbody_system.length + particles_in_field[1].position = [1.5, 0, 0] | nbody_system.length + particles_in_field[2].position = [0.5, 1, 0] | nbody_system.length + particles_in_field[3].position = [0.5, -0.5, 0] | nbody_system.length + particles_in_field[4].position = [0, 0, 2] | nbody_system.length + particles_in_field.velocity = [0, 0.0, 0] | nbody_system.speed particles_in_field.radius = 0 | nbody_system.length - + x = TryHandleEncounter( - G = nbody_system.G, - kepler_code = self.new_kepler() + G=nbody_system.G, + kepler_code=self.new_kepler() ) - + x.particles_in_encounter.add_particles(particles_in_encounter) x.particles_in_field.add_particles(particles_in_field) - + x.execute() - + self.assertAlmostRelativeEqual(x.large_scale_of_particles_in_the_encounter, 1.0 | nbody_system.length) self.assertAlmostRelativeEqual(x.small_scale_of_particles_in_the_encounter, 3.0 | nbody_system.length) - + self.assertEqual(len(x.particles_close_to_encounter), 3) - self.assertAlmostRelativeEqual(x.particles_close_to_encounter.mass, [2,3,4] | nbody_system.mass) - + self.assertAlmostRelativeEqual(x.particles_close_to_encounter.mass, [2, 3, 4] | nbody_system.mass) + def test2(self): - - particles_in_encounter = Particles(keys=(1,2)) + + particles_in_encounter = Particles(keys=(1, 2)) particles_in_encounter.mass = 1 | nbody_system.mass - particles_in_encounter[0].position = [1,0,0] | nbody_system.length - particles_in_encounter[1].position = [0,0,0] | nbody_system.length - particles_in_encounter.velocity = [0,0.5,0] | nbody_system.speed + particles_in_encounter[0].position = [1, 0, 0] | nbody_system.length + particles_in_encounter[1].position = [0, 0, 0] | nbody_system.length + particles_in_encounter.velocity = [0, 0.5, 0] | nbody_system.speed particles_in_encounter.radius = 0 | nbody_system.length - + particles_in_field = Particles(keys=(5,)) particles_in_field.mass = 2 | nbody_system.mass - particles_in_field.position = [-0.5,0,0] | nbody_system.length - particles_in_field.velocity = [0,0.5,0] | nbody_system.speed + particles_in_field.position = [-0.5, 0, 0] | nbody_system.length + particles_in_field.velocity = [0, 0.5, 0] | nbody_system.speed particles_in_field.radius = 0 | nbody_system.length - + particles_in_multiples = Particles() particles_in_multiples.add_particle(particles_in_encounter[0]) multiple = particles_in_multiples[0] - multiple.components = Particles(keys = (3,4)) + multiple.components = Particles(keys=(3, 4)) multiple.components.mass = 0.5 | nbody_system.mass - multiple.components[0].position = [0,0.1,0] | nbody_system.length - multiple.components[1].position = [0,-0.1,0] | nbody_system.length - multiple.components[0].velocity = [0,0,0.2] | nbody_system.speed - multiple.components[1].velocity = [0,0.1,-0.2] | nbody_system.speed + multiple.components[0].position = [0, 0.1, 0] | nbody_system.length + multiple.components[1].position = [0, -0.1, 0] | nbody_system.length + multiple.components[0].velocity = [0, 0, 0.2] | nbody_system.speed + multiple.components[1].velocity = [0, 0.1, -0.2] | nbody_system.speed multiple.components.child1 = None multiple.components.child2 = None - + x = TryHandleEncounter( - G = nbody_system.G, - kepler_code = self.new_kepler() + G=nbody_system.G, + kepler_code=self.new_kepler() ) - + x.particles_in_encounter.add_particles(particles_in_encounter) x.particles_in_field.add_particles(particles_in_field) x.existing_multiples.add_particles(particles_in_multiples) - + x.execute() - + self.assertEqual(len(x.all_singles_in_encounter), 3) self.assertEqual(len(x.all_singles_in_evolve), 4) - - - self.assertAlmostRelativeEqual(x.all_singles_in_evolve.mass, [0.5, 0.5, 1.0, 2.0]| nbody_system.mass) - + + self.assertAlmostRelativeEqual(x.all_singles_in_evolve.mass, [0.5, 0.5, 1.0, 2.0] | nbody_system.mass) + self.assertEqual(len(x.released_singles), 2) print(x.particles_after_encounter) child1 = x.particles_after_encounter[-2] child2 = x.particles_after_encounter[-1] print(child1.position) print(child2.position) - self.assertAlmostRelativeEqual(child1.position, [1,0.1,0]| nbody_system.length) - self.assertAlmostRelativeEqual(child1.velocity, [0,0.5,0.2]| nbody_system.speed) - self.assertAlmostRelativeEqual(child2.position, [1,-0.1,0]| nbody_system.length) - self.assertAlmostRelativeEqual(child2.velocity, [0,0.6,-0.2]| nbody_system.speed) - - + self.assertAlmostRelativeEqual(child1.position, [1, 0.1, 0] | nbody_system.length) + self.assertAlmostRelativeEqual(child1.velocity, [0, 0.5, 0.2] | nbody_system.speed) + self.assertAlmostRelativeEqual(child2.position, [1, -0.1, 0] | nbody_system.length) + self.assertAlmostRelativeEqual(child2.velocity, [0, 0.6, -0.2] | nbody_system.speed) + def test3(self): - - particles_in_encounter = Particles(keys=(1,2)) + + particles_in_encounter = Particles(keys=(1, 2)) particles_in_encounter.mass = 1 | nbody_system.mass - particles_in_encounter[0].position = [1,0,0] | nbody_system.length - particles_in_encounter[1].position = [0,0,0] | nbody_system.length - particles_in_encounter.velocity = [0,0.0,0] | nbody_system.speed + particles_in_encounter[0].position = [1, 0, 0] | nbody_system.length + particles_in_encounter[1].position = [0, 0, 0] | nbody_system.length + particles_in_encounter.velocity = [0, 0.0, 0] | nbody_system.speed particles_in_encounter.radius = 0 | nbody_system.length - - particles_in_field = Particles(keys=(2,4,5,6,7,)) - particles_in_field.mass = [1,2,3,4,5] | nbody_system.mass - particles_in_field[0].position = [2,0,0] | nbody_system.length - particles_in_field[1].position = [1.5,0,0] | nbody_system.length - particles_in_field[2].position = [0.5,1,0] | nbody_system.length - particles_in_field[3].position = [0.5,-0.5,0] | nbody_system.length - particles_in_field[4].position = [0,0,2] | nbody_system.length - particles_in_field.velocity = [0,0,0] | nbody_system.speed + + particles_in_field = Particles(keys=(2, 4, 5, 6, 7,)) + particles_in_field.mass = [1, 2, 3, 4, 5] | nbody_system.mass + particles_in_field[0].position = [2, 0, 0] | nbody_system.length + particles_in_field[1].position = [1.5, 0, 0] | nbody_system.length + particles_in_field[2].position = [0.5, 1, 0] | nbody_system.length + particles_in_field[3].position = [0.5, -0.5, 0] | nbody_system.length + particles_in_field[4].position = [0, 0, 2] | nbody_system.length + particles_in_field.velocity = [0, 0, 0] | nbody_system.speed particles_in_field.radius = 0 | nbody_system.length - + x = TryHandleEncounter( - G = nbody_system.G, - kepler_code = self.new_kepler() + G=nbody_system.G, + kepler_code=self.new_kepler() ) - + x.particles_in_encounter.add_particles(particles_in_encounter) x.particles_in_field.add_particles(particles_in_field) - - + simple_binary = new_binary( - 1 | nbody_system.mass, - 1 | nbody_system.mass, + 1 | nbody_system.mass, + 1 | nbody_system.mass, 0.2 | nbody_system.length ) - + def evolve_singles_in_encounter_until_end_state(): particles = x.singles_and_multiples_after_evolve particles.add_particles(x.all_singles_in_encounter) particles.child1 = None particles.child2 = None - + root_particle = particles.add_particle(Particle( - key = 10, - mass = 2.0 | nbody_system.mass, - position = particles[0:2].center_of_mass(), - velocity = particles[0:2].center_of_mass_velocity(), + key=10, + mass=2.0 | nbody_system.mass, + position=particles[0:2].center_of_mass(), + velocity=particles[0:2].center_of_mass_velocity(), )) root_particle.child1 = particles[0] root_particle.child2 = particles[1] particles[0].position = simple_binary[0].position + root_particle.position particles[1].position = simple_binary[1].position + root_particle.position - + particles[0].velocity = simple_binary[0].velocity + root_particle.velocity particles[1].velocity = simple_binary[1].velocity + root_particle.velocity - + x.evolve_singles_in_encounter_until_end_state = evolve_singles_in_encounter_until_end_state - x.determine_structure_of_the_evolved_state = lambda : 1 - + x.determine_structure_of_the_evolved_state = lambda: 1 + x.execute() self.assertEqual(len(x.new_multiples), 1) self.assertEqual(len(x.new_binaries), 1) multiple = x.new_multiples[0] self.assertEqual(len(multiple.components), 2) - + self.assertAlmostRelativeEqual(multiple.components[0].position, simple_binary[0].position) - self.assertAlmostRelativeEqual(multiple.components[1].position, simple_binary[1].position) - - - + self.assertAlmostRelativeEqual(multiple.components[1].position, simple_binary[1].position) + def test4(self): - - particles_in_encounter = Particles(keys=(1,2)) + + particles_in_encounter = Particles(keys=(1, 2)) particles_in_encounter.mass = 1 | nbody_system.mass - particles_in_encounter[0].position = [1,0,0] | nbody_system.length - particles_in_encounter[1].position = [0,0,0] | nbody_system.length - particles_in_encounter.velocity = [0,0.0,0] | nbody_system.speed + particles_in_encounter[0].position = [1, 0, 0] | nbody_system.length + particles_in_encounter[1].position = [0, 0, 0] | nbody_system.length + particles_in_encounter.velocity = [0, 0.0, 0] | nbody_system.speed particles_in_encounter.radius = 0 | nbody_system.length - - particles_in_field = Particles(keys=(3,4,5,6,7,)) - particles_in_field.mass = [1,2,3,4,5] | nbody_system.mass - particles_in_field[0].position = [2,0,0] | nbody_system.length - particles_in_field[1].position = [1.5,0,0] | nbody_system.length - particles_in_field[2].position = [0.5,1,0] | nbody_system.length - particles_in_field[3].position = [0.5,-0.5,0] | nbody_system.length - particles_in_field[4].position = [0,0,2] | nbody_system.length - particles_in_field.velocity = [0,0,0] | nbody_system.speed + + particles_in_field = Particles(keys=(3, 4, 5, 6, 7,)) + particles_in_field.mass = [1, 2, 3, 4, 5] | nbody_system.mass + particles_in_field[0].position = [2, 0, 0] | nbody_system.length + particles_in_field[1].position = [1.5, 0, 0] | nbody_system.length + particles_in_field[2].position = [0.5, 1, 0] | nbody_system.length + particles_in_field[3].position = [0.5, -0.5, 0] | nbody_system.length + particles_in_field[4].position = [0, 0, 2] | nbody_system.length + particles_in_field.velocity = [0, 0, 0] | nbody_system.speed particles_in_field.radius = 0 | nbody_system.length - + binaries = Particles(keys=(20,)) binaries[0].child1 = particles_in_encounter[0] binaries[0].child2 = particles_in_encounter[1] - + x = TryHandleEncounter( - G = nbody_system.G, - kepler_code = self.new_kepler() + G=nbody_system.G, + kepler_code=self.new_kepler() ) - + x.particles_in_encounter.add_particles(particles_in_encounter) x.particles_in_field.add_particles(particles_in_field) x.existing_binaries.add_particles(binaries) - - + simple_binary = new_binary( - 1 | nbody_system.mass, - 1 | nbody_system.mass, + 1 | nbody_system.mass, + 1 | nbody_system.mass, 0.2 | nbody_system.length ) - + def evolve_singles_in_encounter_until_end_state(): particles = x.singles_and_multiples_after_evolve particles.add_particles(x.all_singles_in_encounter) particles.child1 = None particles.child2 = None - + root_particle = particles.add_particle(Particle( - key = 10, - mass = 2.0 | nbody_system.mass, - position = particles[0:2].center_of_mass(), - velocity = particles[0:2].center_of_mass_velocity(), + key=10, + mass=2.0 | nbody_system.mass, + position=particles[0:2].center_of_mass(), + velocity=particles[0:2].center_of_mass_velocity(), )) root_particle.child1 = particles[0] root_particle.child2 = particles[1] particles[0].position = simple_binary[0].position + root_particle.position particles[1].position = simple_binary[1].position + root_particle.position - + particles[0].velocity = simple_binary[0].velocity + root_particle.velocity particles[1].velocity = simple_binary[1].velocity + root_particle.velocity - + x.evolve_singles_in_encounter_until_end_state = evolve_singles_in_encounter_until_end_state - x.determine_structure_of_the_evolved_state = lambda : 1 - + x.determine_structure_of_the_evolved_state = lambda: 1 + x.execute() self.assertEqual(len(x.new_multiples), 1) self.assertEqual(len(x.new_binaries), 0) self.assertEqual(len(x.updated_binaries), 1) self.assertEqual(x.updated_binaries[0], binaries[0]) - - def test5(self): - - particles_in_encounter = Particles(keys=(1,2)) + + particles_in_encounter = Particles(keys=(1, 2)) particles_in_encounter.mass = 1 | nbody_system.mass - particles_in_encounter[0].position = [1,0,0] | nbody_system.length - particles_in_encounter[1].position = [0,0,0] | nbody_system.length - particles_in_encounter.velocity = [0,0.0,0] | nbody_system.speed + particles_in_encounter[0].position = [1, 0, 0] | nbody_system.length + particles_in_encounter[1].position = [0, 0, 0] | nbody_system.length + particles_in_encounter.velocity = [0, 0.0, 0] | nbody_system.speed particles_in_encounter.radius = 0 | nbody_system.length - - particles_in_field = Particles(keys=(2,4,5,6,7,)) - particles_in_field.mass = [1,2,3,4,5] | nbody_system.mass - particles_in_field[0].position = [2,0,0] | nbody_system.length - particles_in_field[1].position = [1.5,0,0] | nbody_system.length - particles_in_field[2].position = [0.5,1,0] | nbody_system.length - particles_in_field[3].position = [0.5,-0.5,0] | nbody_system.length - particles_in_field[4].position = [0,0,2] | nbody_system.length - particles_in_field.velocity = [0,0,0] | nbody_system.speed + + particles_in_field = Particles(keys=(2, 4, 5, 6, 7,)) + particles_in_field.mass = [1, 2, 3, 4, 5] | nbody_system.mass + particles_in_field[0].position = [2, 0, 0] | nbody_system.length + particles_in_field[1].position = [1.5, 0, 0] | nbody_system.length + particles_in_field[2].position = [0.5, 1, 0] | nbody_system.length + particles_in_field[3].position = [0.5, -0.5, 0] | nbody_system.length + particles_in_field[4].position = [0, 0, 2] | nbody_system.length + particles_in_field.velocity = [0, 0, 0] | nbody_system.speed particles_in_field.radius = 0 | nbody_system.length - + x = TryHandleEncounter( - G = nbody_system.G, - kepler_code = self.new_kepler() + G=nbody_system.G, + kepler_code=self.new_kepler() ) - + x.parameters.hard_binary_factor = 1 x.small_scale_factor = 1 x.particles_in_encounter.add_particles(particles_in_encounter) x.particles_in_field.add_particles(particles_in_field) - + simple_binary = new_binary( - 1 | nbody_system.mass, - 1 | nbody_system.mass, + 1 | nbody_system.mass, + 1 | nbody_system.mass, 2 | nbody_system.length ) - + def evolve_singles_in_encounter_until_end_state(): particles = x.singles_and_multiples_after_evolve particles.add_particles(x.all_singles_in_encounter) particles.child1 = None particles.child2 = None - + root_particle = particles.add_particle(Particle( - key = 10, - mass = 2.0 | nbody_system.mass, - position = particles[0:2].center_of_mass(), - velocity = particles[0:2].center_of_mass_velocity(), + key=10, + mass=2.0 | nbody_system.mass, + position=particles[0:2].center_of_mass(), + velocity=particles[0:2].center_of_mass_velocity(), )) root_particle.child1 = particles[0] root_particle.child2 = particles[1] particles[0].position = simple_binary[0].position + root_particle.position particles[1].position = simple_binary[1].position + root_particle.position - + particles[0].velocity = simple_binary[0].velocity + root_particle.velocity particles[1].velocity = simple_binary[1].velocity + root_particle.velocity - + x.evolve_singles_in_encounter_until_end_state = evolve_singles_in_encounter_until_end_state - x.determine_structure_of_the_evolved_state = lambda : 1 - + x.determine_structure_of_the_evolved_state = lambda: 1 + x.execute() - - # no multiples as the binary is larger than the + + # no multiples as the binary is larger than the # hard binary scale self.assertEqual(len(x.new_multiples), 0) self.assertEqual(len(x.new_binaries), 0) - def test6(self): - - particles_in_encounter = Particles(keys=(1,2,3)) + + particles_in_encounter = Particles(keys=(1, 2, 3)) particles_in_encounter.mass = 1 | nbody_system.mass - particles_in_encounter[0].position = [1,0,0] | nbody_system.length - particles_in_encounter[1].position = [0,0,0] | nbody_system.length - particles_in_encounter[2].position = [0,0.5,0] | nbody_system.length - particles_in_encounter.velocity = [0,0.0,0] | nbody_system.speed + particles_in_encounter[0].position = [1, 0, 0] | nbody_system.length + particles_in_encounter[1].position = [0, 0, 0] | nbody_system.length + particles_in_encounter[2].position = [0, 0.5, 0] | nbody_system.length + particles_in_encounter.velocity = [0, 0.0, 0] | nbody_system.speed particles_in_encounter.radius = 0 | nbody_system.length - - + x = TryHandleEncounter( - G = nbody_system.G, - kepler_code = self.new_kepler() + G=nbody_system.G, + kepler_code=self.new_kepler() ) x.particles_in_encounter.add_particles(particles_in_encounter) x.small_scale_factor = 1.0 - + simple_binary_1 = new_binary( - 1 | nbody_system.mass, - 1 | nbody_system.mass, + 1 | nbody_system.mass, + 1 | nbody_system.mass, 0.4 | nbody_system.length ) simple_binary_top = new_binary( - 2 | nbody_system.mass, - 1 | nbody_system.mass, + 2 | nbody_system.mass, + 1 | nbody_system.mass, 2 | nbody_system.length ) - + def evolve_singles_in_encounter_until_end_state(): particles = x.singles_and_multiples_after_evolve particles.add_particles(x.all_singles_in_encounter) particles.child1 = None particles.child2 = None - + inner_binary_particle = particles.add_particle(Particle( - key = 10, - mass = 2.0 | nbody_system.mass, - position = particles[0:2].center_of_mass(), - velocity = particles[0:2].center_of_mass_velocity(), + key=10, + mass=2.0 | nbody_system.mass, + position=particles[0:2].center_of_mass(), + velocity=particles[0:2].center_of_mass_velocity(), )) inner_binary_particle.child1 = particles[0] inner_binary_particle.child2 = particles[1] particles[0].position = simple_binary_1[0].position + inner_binary_particle.position particles[1].position = simple_binary_1[1].position + inner_binary_particle.position - + particles[0].velocity = simple_binary_1[0].velocity + inner_binary_particle.velocity particles[1].velocity = simple_binary_1[1].velocity + inner_binary_particle.velocity - + root_particle = particles.add_particle(Particle( - key = 11, - mass = 3.0 | nbody_system.mass, - position = particles.center_of_mass(), - velocity = particles.center_of_mass_velocity(), + key=11, + mass=3.0 | nbody_system.mass, + position=particles.center_of_mass(), + velocity=particles.center_of_mass_velocity(), )) - + root_particle.child1 = inner_binary_particle root_particle.child2 = particles[2] inner_binary_particle.position = simple_binary_top[0].position + root_particle.position particles[2].position = simple_binary_top[1].position + root_particle.position - + inner_binary_particle.velocity = simple_binary_top[0].velocity + root_particle.velocity particles[2].velocity = simple_binary_top[1].velocity + root_particle.velocity - - - - + x.evolve_singles_in_encounter_until_end_state = evolve_singles_in_encounter_until_end_state - x.determine_structure_of_the_evolved_state = lambda : 1 - + x.determine_structure_of_the_evolved_state = lambda: 1 + x.execute() - - # no multiples as the binary is larger than the + + # no multiples as the binary is larger than the # hard binary scale self.assertEqual(len(x.new_multiples), 1) self.assertEqual(len(x.new_binaries), 1) @@ -443,55 +433,48 @@ def evolve_singles_in_encounter_until_end_state(): self.assertEqual(len(multiple.components), 2) self.assertAlmostRelativeEqual(multiple.components[0].key, particles_in_encounter[0].key) self.assertAlmostRelativeEqual(multiple.components[1].key, particles_in_encounter[1].key) - - - + def test7(self): - - particles_in_encounter = Particles(keys=(1,2,3)) + + particles_in_encounter = Particles(keys=(1, 2, 3)) particles_in_encounter.mass = 1 | nbody_system.mass - particles_in_encounter[0].position = [1,0,0] | nbody_system.length - particles_in_encounter[1].position = [0,0,0] | nbody_system.length - particles_in_encounter[2].position = [0,0.5,0] | nbody_system.length - particles_in_encounter.velocity = [0,0.0,0] | nbody_system.speed + particles_in_encounter[0].position = [1, 0, 0] | nbody_system.length + particles_in_encounter[1].position = [0, 0, 0] | nbody_system.length + particles_in_encounter[2].position = [0, 0.5, 0] | nbody_system.length + particles_in_encounter.velocity = [0, 0.0, 0] | nbody_system.speed particles_in_encounter.radius = 0 | nbody_system.length - - + x = TryHandleEncounter( - G = nbody_system.G, - kepler_code = self.new_kepler() + G=nbody_system.G, + kepler_code=self.new_kepler() ) x.particles_in_encounter.add_particles(particles_in_encounter) - + multiples = Particles() - particle_in_multiples = multiples.add_particle( particles_in_encounter[2]) - particle_in_multiples.components = Particles(keys=(4,5)) + particle_in_multiples = multiples.add_particle(particles_in_encounter[2]) + particle_in_multiples.components = Particles(keys=(4, 5)) particle_in_multiples.components.mass = 1 | nbody_system.mass - particle_in_multiples.components[0].position = [0,0,0.2] | nbody_system.length - particle_in_multiples.components[1].position = [0,0,-0.2] | nbody_system.length - particle_in_multiples.components.velocity = [0,0.0,0] | nbody_system.speed + particle_in_multiples.components[0].position = [0, 0, 0.2] | nbody_system.length + particle_in_multiples.components[1].position = [0, 0, -0.2] | nbody_system.length + particle_in_multiples.components.velocity = [0, 0.0, 0] | nbody_system.speed particle_in_multiples.components.child1 = None particle_in_multiples.components.child2 = None - x.existing_multiples.add_particles(multiples) - - + x.existing_multiples.add_particles(multiples) + def evolve_singles_in_encounter_until_end_state(): - + particles = x.singles_and_multiples_after_evolve particles.add_particles(x.all_singles_in_encounter) print(particles) particles.child1 = None particles.child2 = None - - - - + x.evolve_singles_in_encounter_until_end_state = evolve_singles_in_encounter_until_end_state - x.determine_structure_of_the_evolved_state = lambda : 1 - + x.determine_structure_of_the_evolved_state = lambda: 1 + x.execute() - - # no multiples as the binary is larger than the + + # no multiples as the binary is larger than the # hard binary scale self.assertEqual(len(x.new_multiples), 0) self.assertEqual(len(x.new_binaries), 0) @@ -499,73 +482,65 @@ def evolve_singles_in_encounter_until_end_state(): self.assertEqual(len(x.released_singles), 2) self.assertTrue(particle_in_multiples.components[0] in x.released_singles) self.assertTrue(particle_in_multiples.components[1] in x.released_singles) - - + def xtest8(self): particles_in_encounter = Particles(3) particles_in_encounter.mass = 1. | nbody_system.mass - particles_in_encounter[0].position = [0.,0.,0.] | nbody_system.length - particles_in_encounter[1].position = [1.,0.,0.] | nbody_system.length - particles_in_encounter[2].position = [2.,0.,0.] | nbody_system.length - particles_in_encounter.velocity = [0.,0.5,0.] | nbody_system.speed + particles_in_encounter[0].position = [0., 0., 0.] | nbody_system.length + particles_in_encounter[1].position = [1., 0., 0.] | nbody_system.length + particles_in_encounter[2].position = [2., 0., 0.] | nbody_system.length + particles_in_encounter.velocity = [0., 0.5, 0.] | nbody_system.speed particles_in_encounter.radius = [0.5, 1., 0.2] | nbody_system.length - + x = TryHandleEncounter( - G = nbody_system.G, - kepler_code = self.new_kepler() + G=nbody_system.G, + kepler_code=self.new_kepler() ) - + x.particles_in_encounter.add_particles(particles_in_encounter) - + x.execute() - + self.assertAlmostRelativeEqual(x.large_scale_of_particles_in_the_encounter, 2.0 | nbody_system.length) self.assertAlmostRelativeEqual(x.small_scale_of_particles_in_the_encounter, 1.5 | nbody_system.length) - - - + def test8b(self): particles_in_encounter = Particles(2) particles_in_encounter.mass = 1 | nbody_system.mass - particles_in_encounter[0].position = [0,0,0] | nbody_system.length - particles_in_encounter[1].position = [1,0,0] | nbody_system.length - particles_in_encounter.velocity = [0,0.5,0] | nbody_system.speed + particles_in_encounter[0].position = [0, 0, 0] | nbody_system.length + particles_in_encounter[1].position = [1, 0, 0] | nbody_system.length + particles_in_encounter.velocity = [0, 0.5, 0] | nbody_system.speed particles_in_encounter.radius = [0.5, 0.5] | nbody_system.length - - + x = TryHandleEncounter( - G = nbody_system.G, - kepler_code = self.new_kepler() + G=nbody_system.G, + kepler_code=self.new_kepler() ) - + x.particles_in_encounter.add_particles(particles_in_encounter) - - + x.execute() - + self.assertAlmostRelativeEqual(x.initial_potential_in_field, 0 | nbody_system.energy) self.assertAlmostRelativeEqual(x.initial_energy, -0.75 | nbody_system.energy) - - + def test9(self): particles_in_encounter = Particles(2) particles_in_encounter.mass = 1 | nbody_system.mass - particles_in_encounter[0].position = [0,0,0] | nbody_system.length - particles_in_encounter[1].position = [1,0,0] | nbody_system.length - particles_in_encounter.velocity = [0,0.5,0] | nbody_system.speed + particles_in_encounter[0].position = [0, 0, 0] | nbody_system.length + particles_in_encounter[1].position = [1, 0, 0] | nbody_system.length + particles_in_encounter.velocity = [0, 0.5, 0] | nbody_system.speed particles_in_encounter.radius = [0.5, 0.5] | nbody_system.length - - + x = TryHandleEncounter( - G = nbody_system.G, - kepler_code = self.new_kepler() + G=nbody_system.G, + kepler_code=self.new_kepler() ) - + x.particles_in_encounter.add_particles(particles_in_encounter) - - + x.execute() - + self.assertAlmostRelativeEqual(x.initial_potential_in_field, 0 | nbody_system.energy) self.assertAlmostRelativeEqual(x.initial_energy, -0.75 | nbody_system.energy) self.assertAlmostRelativeEqual(x.initial_singles_energy, -0.75 | nbody_system.energy) @@ -574,33 +549,30 @@ def test9(self): self.assertAlmostRelativeEqual(x.final_energy, -0.75 | nbody_system.energy) self.assertAlmostRelativeEqual(x.delta_phi_2, 0 | nbody_system.energy) self.assertAlmostRelativeEqual(x.final_multiple_energy, 0 | nbody_system.energy) - - + def test10(self): particles_in_encounter = Particles(2) particles_in_encounter.mass = 1 | nbody_system.mass - particles_in_encounter[0].position = [0,0,0] | nbody_system.length - particles_in_encounter[1].position = [1,0,0] | nbody_system.length - particles_in_encounter.velocity = [0,0.5,0] | nbody_system.speed + particles_in_encounter[0].position = [0, 0, 0] | nbody_system.length + particles_in_encounter[1].position = [1, 0, 0] | nbody_system.length + particles_in_encounter.velocity = [0, 0.5, 0] | nbody_system.speed particles_in_encounter.radius = [0.5, 0.5] | nbody_system.length - - + x = TryHandleEncounter( - G = nbody_system.G, - kepler_code = self.new_kepler() + G=nbody_system.G, + kepler_code=self.new_kepler() ) - + x.particles_in_encounter.add_particles(particles_in_encounter) x.particles_in_field.add_particle(Particle( - mass = 1 | nbody_system.mass, - position = [5,0,0] | nbody_system.length, - velocity = [0,0,0] | nbody_system.speed, - radius = 0 | nbody_system.length + mass=1 | nbody_system.mass, + position=[5, 0, 0] | nbody_system.length, + velocity=[0, 0, 0] | nbody_system.speed, + radius=0 | nbody_system.length )) - - + x.execute() - + self.assertAlmostRelativeEqual(x.initial_potential_in_field, -0.45 | nbody_system.energy) self.assertAlmostRelativeEqual(x.initial_energy, -0.75 | nbody_system.energy) self.assertAlmostRelativeEqual(x.initial_singles_energy, -0.75 | nbody_system.energy) @@ -609,110 +581,105 @@ def test10(self): self.assertAlmostRelativeEqual(x.final_energy, -0.75 | nbody_system.energy) self.assertAlmostRelativeEqual(x.delta_phi_2, 0 | nbody_system.energy) self.assertAlmostRelativeEqual(x.final_multiple_energy, 0 | nbody_system.energy) - + def test11(self): particles_in_encounter = Particles(2) particles_in_encounter.mass = 1 | nbody_system.mass - particles_in_encounter[0].position = [0,0,0] | nbody_system.length - particles_in_encounter[1].position = [1,0,0] | nbody_system.length - particles_in_encounter.velocity = [0,0.5,0] | nbody_system.speed + particles_in_encounter[0].position = [0, 0, 0] | nbody_system.length + particles_in_encounter[1].position = [1, 0, 0] | nbody_system.length + particles_in_encounter.velocity = [0, 0.5, 0] | nbody_system.speed particles_in_encounter.radius = [0.5, 0.5] | nbody_system.length - + particles_in_multiples = Particles() particles_in_multiples.add_particle(particles_in_encounter[0]) multiple = particles_in_multiples[0] - multiple.components = Particles(keys = (3,4)) + multiple.components = Particles(keys=(3, 4)) multiple.components.mass = 0.5 | nbody_system.mass - multiple.components[0].position = [0,0.1,0] | nbody_system.length - multiple.components[1].position = [0,-0.1,0] | nbody_system.length - multiple.components[0].velocity = [0,0,0.2] | nbody_system.speed - multiple.components[1].velocity = [0,0.1,-0.2] | nbody_system.speed + multiple.components[0].position = [0, 0.1, 0] | nbody_system.length + multiple.components[1].position = [0, -0.1, 0] | nbody_system.length + multiple.components[0].velocity = [0, 0, 0.2] | nbody_system.speed + multiple.components[1].velocity = [0, 0.1, -0.2] | nbody_system.speed multiple.components.child1 = None multiple.components.child2 = None - - - + x = TryHandleEncounter( - G = nbody_system.G, - kepler_code = self.new_kepler() + G=nbody_system.G, + kepler_code=self.new_kepler() ) - + x.particles_in_encounter.add_particles(particles_in_encounter) x.particles_in_field.add_particle(Particle( - mass = 1 | nbody_system.mass, - position = [5,0,0] | nbody_system.length, - velocity = [0,0,0] | nbody_system.speed, - radius = 0 | nbody_system.length + mass=1 | nbody_system.mass, + position=[5, 0, 0] | nbody_system.length, + velocity=[0, 0, 0] | nbody_system.speed, + radius=0 | nbody_system.length )) x.existing_multiples.add_particles(particles_in_multiples) - - + x.execute() - + self.assertAlmostRelativeEqual(x.initial_potential_in_field, -0.45 | nbody_system.energy) self.assertAlmostRelativeEqual(x.initial_energy, -0.75 | nbody_system.energy) - self.assertAlmostRelativeEqual(x.initial_singles_energy, -1.912495| nbody_system.energy,4) - self.assertAlmostRelativeEqual(x.delta_phi_1, 0.06500400 | nbody_system.energy,4) - self.assertAlmostRelativeEqual(x.initial_multiple_energy, -1.2275 | nbody_system.energy,4) + self.assertAlmostRelativeEqual(x.initial_singles_energy, -1.912495 | nbody_system.energy, 4) + self.assertAlmostRelativeEqual(x.delta_phi_1, 0.06500400 | nbody_system.energy, 4) + self.assertAlmostRelativeEqual(x.initial_multiple_energy, -1.2275 | nbody_system.energy, 4) self.assertAlmostRelativeEqual(x.final_energy, -1.9124959996 | nbody_system.energy, 4) self.assertAlmostRelativeEqual(x.delta_phi_2, 0 | nbody_system.energy) self.assertAlmostRelativeEqual(x.final_multiple_energy, 0 | nbody_system.energy) - + def test12(self): particles_in_encounter = Particles(2) particles_in_encounter.mass = 1 | nbody_system.mass - particles_in_encounter[0].position = [0,0,0] | nbody_system.length - particles_in_encounter[1].position = [1,0,0] | nbody_system.length - particles_in_encounter.velocity = [0,0.5,0] | nbody_system.speed + particles_in_encounter[0].position = [0, 0, 0] | nbody_system.length + particles_in_encounter[1].position = [1, 0, 0] | nbody_system.length + particles_in_encounter.velocity = [0, 0.5, 0] | nbody_system.speed particles_in_encounter.radius = [0.5, 0.5] | nbody_system.length - - + x = TryHandleEncounter( - G = nbody_system.G, - kepler_code = self.new_kepler() + G=nbody_system.G, + kepler_code=self.new_kepler() ) - + x.particles_in_encounter.add_particles(particles_in_encounter) x.particles_in_field.add_particle(Particle( - mass = 0.1 | nbody_system.mass, - position = [1.5,0,0] | nbody_system.length, - velocity = [0,0,0] | nbody_system.speed, - radius = 1 | nbody_system.length + mass=0.1 | nbody_system.mass, + position=[1.5, 0, 0] | nbody_system.length, + velocity=[0, 0, 0] | nbody_system.speed, + radius=1 | nbody_system.length )) - - + x.execute() - + self.assertAlmostRelativeEqual(x.initial_potential_in_field, 0 | nbody_system.energy) self.assertAlmostRelativeEqual(x.initial_energy, -1.016666 | nbody_system.energy, 4) self.assertAlmostRelativeEqual(x.initial_singles_energy, -1.016666 | nbody_system.energy, 4) self.assertAlmostRelativeEqual(x.delta_phi_1, 0 | nbody_system.energy) self.assertAlmostRelativeEqual(x.initial_multiple_energy, 0 | nbody_system.energy) - - + def test13(self): x = TryHandleEncounter( - G = nbody_system.G, - kepler_code = self.new_kepler() + G=nbody_system.G, + kepler_code=self.new_kepler() ) - + x.parameters.hard_binary_factor = 1 self.assertEqual(x.parameters.hard_binary_factor, 1) self.assertEqual(x.parameters.scatter_factor, 10) x.parameters.scatter_factor = 2 self.assertEqual(x.parameters.scatter_factor, 2) self.assertEqual(x.get_scatter_factor(), 2) - + + class TestKeplerOrbits(amusetest.TestWithMPI): - + def new_kepler(self): x = Kepler() x.initialize_code() return x - + def test1(self): x = encounters.KeplerOrbits(self.new_kepler()) - binary = new_binary( + binary = new_binary( 1 | nbody_system.mass, 0.5 | nbody_system.mass, 1.2 | nbody_system.length, @@ -723,82 +690,81 @@ def test1(self): ) self.assertAlmostRelativeEquals(semimajor_axis, 1.2 | nbody_system.length) self.assertAlmostRelativeEquals(eccentricity, 0) - + def test2(self): x = encounters.KeplerOrbits(self.new_kepler()) - binary = new_binary( + binary = new_binary( 1 | nbody_system.mass, 0.5 | nbody_system.mass, 2.0 | nbody_system.length, 0.5, - is_at_periapsis = False - + is_at_periapsis=False + ) - binary.position += [0.1,0.2,0.3] | nbody_system.length - binary.velocity += [0.4,0.5,0.6] | nbody_system.speed - + binary.position += [0.1, 0.2, 0.3] | nbody_system.length + binary.velocity += [0.4, 0.5, 0.6] | nbody_system.speed + dpos, dvel = x.compress_binary( binary, 1.2 | nbody_system.length ) - + center_of_mass_before = binary.center_of_mass() center_of_mass_velocity_before = binary.center_of_mass_velocity() - + binary.position += dpos binary.velocity += dvel - + center_of_mass_after = binary.center_of_mass() center_of_mass_velocity_after = binary.center_of_mass_velocity() - + self.assertAlmostRelativeEquals(center_of_mass_before, center_of_mass_after) self.assertAlmostRelativeEquals(center_of_mass_velocity_before, center_of_mass_velocity_after) - separation = (binary[0].position - binary[1].position).length() - self.assertAlmostRelativeEquals( separation, 1.2 | nbody_system.length) - + separation = (binary[0].position - binary[1].position).length() + self.assertAlmostRelativeEquals(separation, 1.2 | nbody_system.length) + def test3(self): x = encounters.KeplerOrbits(self.new_kepler()) - binary = new_binary( + binary = new_binary( 1 | nbody_system.mass, 0.5 | nbody_system.mass, 2.0 | nbody_system.length, 0.5, - is_at_periapsis = True - + is_at_periapsis=True + ) - binary.position += [0.1,0.2,0.3] | nbody_system.length - binary.velocity += [0.4,0.5,0.6] | nbody_system.speed - + binary.position += [0.1, 0.2, 0.3] | nbody_system.length + binary.velocity += [0.4, 0.5, 0.6] | nbody_system.speed + dpos, dvel = x.expand_binary( binary, 2.5 | nbody_system.length ) - + center_of_mass_before = binary.center_of_mass() center_of_mass_velocity_before = binary.center_of_mass_velocity() - + binary.position += dpos binary.velocity += dvel - + center_of_mass_after = binary.center_of_mass() center_of_mass_velocity_after = binary.center_of_mass_velocity() - + self.assertAlmostRelativeEquals(center_of_mass_before, center_of_mass_after, 8) self.assertAlmostRelativeEquals(center_of_mass_velocity_before, center_of_mass_velocity_after, 8) - separation = (binary[0].position - binary[1].position).length() - self.assertAlmostRelativeEquals( separation, 2.5 | nbody_system.length) - - + separation = (binary[0].position - binary[1].position).length() + self.assertAlmostRelativeEquals(separation, 2.5 | nbody_system.length) + def test4(self): converter = nbody_system.nbody_to_si(1 | units.MSun, 1 | units.AU) kepler = Kepler(converter) kepler.initialize_code() x = encounters.KeplerOrbits(kepler) - binary = new_binary( + binary = new_binary( 1 | units.MSun, 0.5 | units.MSun, 1.2 | units.AU, - G = constants.G + G=constants.G ) semimajor_axis, eccentricity = x.get_semimajor_axis_and_eccentricity_for_binary_components( binary[0], @@ -807,182 +773,177 @@ def test4(self): self.assertAlmostRelativeEquals(semimajor_axis, 1.2 | units.AU, 8) self.assertAlmostRelativeEquals(eccentricity, 0) + class TestScaleSystem(amusetest.TestWithMPI): - - def new_kepler(self, converter = None): + + def new_kepler(self, converter=None): x = Kepler(converter) x.initialize_code() return x - + def test1(self): kepler = encounters.KeplerOrbits(self.new_kepler()) - binary = new_binary( + binary = new_binary( 1 | nbody_system.mass, 0.5 | nbody_system.mass, 1.2 | nbody_system.length, 0.5, - is_at_periapsis = False + is_at_periapsis=False ) - binary.radius = 0 | nbody_system.length - + binary.radius = 0 | nbody_system.length + x = encounters.ScaleSystem(kepler) self.assertTrue((binary[0].position - binary[1].position).length() > 1.5 | nbody_system.length) x.scale_particles_to_sphere(binary, 0.75 | nbody_system.length) self.assertTrue((binary[0].position - binary[1].position).length() <= 1.6 | nbody_system.length) print((binary[0].position - binary[1].position).length()) - self.assertTrue((binary[0].position - binary[1].position).length() >= (1.5 - 1e-6)| nbody_system.length ) - - - + self.assertTrue((binary[0].position - binary[1].position).length() >= (1.5 - 1e-6) | nbody_system.length) + def test2(self): kepler = encounters.KeplerOrbits(self.new_kepler()) - binary = new_binary( + binary = new_binary( 1 | nbody_system.mass, 0.5 | nbody_system.mass, 1.2 | nbody_system.length, 0.5, - is_at_periapsis = True + is_at_periapsis=True ) - binary.radius = 0 | nbody_system.length - + binary.radius = 0 | nbody_system.length + x = encounters.ScaleSystem(kepler) self.assertTrue((binary[0].position - binary[1].position).length() < 1.5 | nbody_system.length) x.scale_particles_to_sphere(binary, 0.75 | nbody_system.length) self.assertTrue((binary[0].position - binary[1].position).length() <= 1.6 | nbody_system.length) print((binary[0].position - binary[1].position).length()) - self.assertTrue((binary[0].position - binary[1].position).length() >= (1.5 - 1e-6)| nbody_system.length ) - - + self.assertTrue((binary[0].position - binary[1].position).length() >= (1.5 - 1e-6) | nbody_system.length) + def test3(self): kepler = encounters.KeplerOrbits(self.new_kepler()) - - particles= Particles(keys=(1,2)) + + particles = Particles(keys=(1, 2)) particles.mass = 1 | nbody_system.mass particles.child2 = None particles.child1 = None - particles[0].position = [1,0,0] | nbody_system.length - particles[0].velocity = [1,0.0,0] | nbody_system.speed - - particles[1].position = [-1,0,0] | nbody_system.length - particles[1].velocity = [-1,0.0,0] | nbody_system.speed - - particles.radius = 0 | nbody_system.length - + particles[0].position = [1, 0, 0] | nbody_system.length + particles[0].velocity = [1, 0.0, 0] | nbody_system.speed + + particles[1].position = [-1, 0, 0] | nbody_system.length + particles[1].velocity = [-1, 0.0, 0] | nbody_system.speed + + particles.radius = 0 | nbody_system.length + x = encounters.ScaleSystem(kepler) - - print((particles[0].position - particles[1].position).length()) + + print((particles[0].position - particles[1].position).length()) self.assertTrue((particles[0].position - particles[1].position).length() > 1.5 | nbody_system.length) - + x.scale_particles_to_sphere(particles, 0.75 | nbody_system.length) - + self.assertTrue((particles[0].position - particles[1].position).length() <= 1.6 | nbody_system.length) print(particles) - self.assertTrue((particles[0].position - particles[1].position).length() >= (1.5 - 1e-6)| nbody_system.length ) - self.assertAlmostRelativeEquals(particles[0].position, [0.75,0,0] | nbody_system.length) - self.assertAlmostRelativeEquals(particles[1].position, [-0.75,0,0] | nbody_system.length) - - + self.assertTrue((particles[0].position - particles[1].position).length() >= (1.5 - 1e-6) | nbody_system.length) + self.assertAlmostRelativeEquals(particles[0].position, [0.75, 0, 0] | nbody_system.length) + self.assertAlmostRelativeEquals(particles[1].position, [-0.75, 0, 0] | nbody_system.length) + def test4(self): kepler = encounters.KeplerOrbits(self.new_kepler()) - - particles= Particles(keys=(1,2,3,4,5,6)) + + particles = Particles(keys=(1, 2, 3, 4, 5, 6)) particles.child2 = None particles.child1 = None particles.mass = 1 | nbody_system.mass for i in range(3): - position = [0,0,0] | nbody_system.length + position = [0, 0, 0] | nbody_system.length position[i] = 1 | nbody_system.length - particles[i].position = position + particles[i].position = position position[i] = -1 | nbody_system.length - particles[i+3].position = position - - velocity = [0,0,0] | nbody_system.speed + particles[i+3].position = position + + velocity = [0, 0, 0] | nbody_system.speed velocity[i] = 1 | nbody_system.speed - particles[i].velocity = velocity + particles[i].velocity = velocity velocity[i] = -1 | nbody_system.speed - particles[i+3].velocity = velocity + particles[i+3].velocity = velocity + + particles.radius = 0 | nbody_system.length - particles.radius = 0 | nbody_system.length - - x = encounters.ScaleSystem(kepler) - potential_energy0 = particles.potential_energy(G = nbody_system.G) + potential_energy0 = particles.potential_energy(G=nbody_system.G) kinetic_energy0 = particles.kinetic_energy() - + x.scale_particles_to_sphere(particles, 0.5 | nbody_system.length) - - self.assertAlmostRelativeEquals(particles[0].position, [1/numpy.sqrt(2),0,0] | nbody_system.length) - self.assertAlmostRelativeEquals(particles[3].position, [-1/numpy.sqrt(2),0,0] | nbody_system.length) - self.assertAlmostRelativeEquals(particles[0].velocity, [1.542,0,0] | nbody_system.speed, 3) - self.assertAlmostRelativeEquals(particles[3].velocity, [-1.542,0,0] | nbody_system.speed, 3) - - potential_energy1 = particles.potential_energy(G = nbody_system.G) + + self.assertAlmostRelativeEquals(particles[0].position, [1/numpy.sqrt(2), 0, 0] | nbody_system.length) + self.assertAlmostRelativeEquals(particles[3].position, [-1/numpy.sqrt(2), 0, 0] | nbody_system.length) + self.assertAlmostRelativeEquals(particles[0].velocity, [1.542, 0, 0] | nbody_system.speed, 3) + self.assertAlmostRelativeEquals(particles[3].velocity, [-1.542, 0, 0] | nbody_system.speed, 3) + + potential_energy1 = particles.potential_energy(G=nbody_system.G) kinetic_energy1 = particles.kinetic_energy() - - - self.assertAlmostRelativeEquals(potential_energy0 + kinetic_energy0,potential_energy1 + kinetic_energy1) + + self.assertAlmostRelativeEquals(potential_energy0 + kinetic_energy0, potential_energy1 + kinetic_energy1) def test5(self): converter = nbody_system.nbody_to_si(1 | units.MSun, 1 | units.AU) kepler = encounters.KeplerOrbits(self.new_kepler(converter)) - - particles= Particles(keys=(1,2,3)) + + particles = Particles(keys=(1, 2, 3)) particles.child2 = None particles.child1 = None particles.position = [ - [ -1.28230200e-05, -3.69457095e-05, -2.02383488e-05], - [ -2.91749746e-05, -1.21387289e-05, 1.56377986e-07], - [ 2.92123436e-05, 1.22463965e-05, -9.73992061e-08] + [-1.28230200e-05, -3.69457095e-05, -2.02383488e-05], + [-2.91749746e-05, -1.21387289e-05, 1.56377986e-07], + [2.92123436e-05, 1.22463965e-05, -9.73992061e-08] ] | units.parsec particles.velocity = [ - [ -8685.98414414, -413260.30543051, -135268.19175611], - [ 19639.55455979, -30251.55372943, 972.69648982], - [ -19614.24178601, 31455.88066005, -578.49669843] + [-8685.98414414, -413260.30543051, -135268.19175611], + [19639.55455979, -30251.55372943, 972.69648982], + [-19614.24178601, 31455.88066005, -578.49669843] ] | (units.m / units.s) particles.mass = [0.14571045, 50., 50.] | units.MSun particles.radius = [8, 0., 0.0] | units.AU - - x = encounters.ScaleSystem(kepler, G = constants.G) - + + x = encounters.ScaleSystem(kepler, G=constants.G) + potential_energy0 = particles.potential_energy() kinetic_energy0 = particles.kinetic_energy() - + x.scale_particles_to_sphere(particles, 4 | units.AU) - + potential_energy1 = particles.potential_energy() kinetic_energy1 = particles.kinetic_energy() - - self.assertAlmostRelativeEquals(potential_energy0 + kinetic_energy0,potential_energy1 + kinetic_energy1) - - + + self.assertAlmostRelativeEquals(potential_energy0 + kinetic_energy0, potential_energy1 + kinetic_energy1) + + class TestHandleEncounter(amusetest.TestWithMPI): - + def new_kepler(self): x = Kepler() x.initialize_code() return x - + def test1(self): - particles_in_encounter = Particles(keys=(1,2,3)) + particles_in_encounter = Particles(keys=(1, 2, 3)) particles_in_encounter.mass = 1. | nbody_system.mass - particles_in_encounter[0].position = [1.,0.,0.] | nbody_system.length - particles_in_encounter[1].position = [0.,0.,0.] | nbody_system.length - particles_in_encounter[2].position = [0.,0.5,0.] | nbody_system.length - particles_in_encounter.velocity = [0.,0.0,0.] | nbody_system.speed - particles_in_encounter[2].velocity = [0.,0.0,3.] | nbody_system.speed + particles_in_encounter[0].position = [1., 0., 0.] | nbody_system.length + particles_in_encounter[1].position = [0., 0., 0.] | nbody_system.length + particles_in_encounter[2].position = [0., 0.5, 0.] | nbody_system.length + particles_in_encounter.velocity = [0., 0.0, 0.] | nbody_system.speed + particles_in_encounter[2].velocity = [0., 0.0, 3.] | nbody_system.speed particles_in_encounter.radius = 0. | nbody_system.length - + particles_in_field = Particles() - + x = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = SmallN(), - interaction_over_code = None, - G = nbody_system.G + kepler_code=self.new_kepler(), + resolve_collision_code=SmallN(), + interaction_over_code=None, + G=nbody_system.G ) - + x.particles_in_encounter.add_particles(particles_in_encounter) - + x.execute() self.assertEqual(len(x.new_multiples), 1) self.assertEqual(len(x.new_binaries), 1) @@ -991,31 +952,29 @@ def test1(self): self.assertAlmostRelativeEqual(multiple.components[0].key, particles_in_encounter[0].key) self.assertAlmostRelativeEqual(multiple.components[1].key, particles_in_encounter[1].key) self.assertEqual(len(x.captured_singles), 2) - self.assertEqual(x.captured_singles.key, [1,2]) - + self.assertEqual(x.captured_singles.key, [1, 2]) def test2(self): - particles_in_encounter = Particles(keys=(1,2)) + particles_in_encounter = Particles(keys=(1, 2)) particles_in_encounter.mass = 2. | nbody_system.mass - particles_in_encounter[0].position = [1.,0.,0.] | nbody_system.length - particles_in_encounter[1].position = [0.,0.,0.] | nbody_system.length - particles_in_encounter.velocity = [0.,0.0,0.] | nbody_system.speed + particles_in_encounter[0].position = [1., 0., 0.] | nbody_system.length + particles_in_encounter[1].position = [0., 0., 0.] | nbody_system.length + particles_in_encounter.velocity = [0., 0.0, 0.] | nbody_system.speed particles_in_encounter.radius = 0. | nbody_system.length - - + binary1 = new_binary( - 1. | nbody_system.mass, - 1. | nbody_system.mass, + 1. | nbody_system.mass, + 1. | nbody_system.mass, 0.01 | nbody_system.length, - keyoffset = 30 + keyoffset=30 ) binary2 = new_binary( - 1. | nbody_system.mass, - 1. | nbody_system.mass, + 1. | nbody_system.mass, + 1. | nbody_system.mass, 0.01 | nbody_system.length, - keyoffset = 40 + keyoffset=40 ) - binaries = Particles(keys=(20,21)) + binaries = Particles(keys=(20, 21)) binaries[0].child1 = binary1[0] binaries[0].child2 = binary1[1] binaries[1].child1 = binary2[0] @@ -1024,7 +983,7 @@ def test2(self): binary1.child2 = None binary2.child1 = None binary2.child2 = None - + multiples = Particles() multiple = particles_in_encounter[0] multiple.components = binary1 @@ -1032,29 +991,27 @@ def test2(self): multiple = particles_in_encounter[1] multiple.components = binary2 multiples.add_particle(multiple) - + x = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = SmallN(), - interaction_over_code = None, - G = nbody_system.G + kepler_code=self.new_kepler(), + resolve_collision_code=SmallN(), + interaction_over_code=None, + G=nbody_system.G ) - + x.particles_in_encounter.add_particles(particles_in_encounter) x.existing_binaries.add_particles(binaries) x.existing_multiples.add_particles(multiples) - - + x.execute() self.assertEqual(len(x.new_multiples), 2) self.assertEqual(len(x.new_binaries), 2) self.assertEqual(len(x.captured_singles), 0) self.assertEqual(len(x.released_singles), 0) - + multiple = x.new_multiples[0] self.assertEqual(len(multiple.components), 2) - - + self.assertAlmostRelativeEqual(multiple.components[0].key, binaries[0].child1.key) self.assertAlmostRelativeEqual(multiple.components[1].key, binaries[1].child1.key) multiple = x.new_multiples[1] @@ -1063,125 +1020,123 @@ def test2(self): self.assertAlmostRelativeEqual(multiple.components[1].key, binaries[1].child2.key) def test3(self): - particles_in_encounter = Particles(keys=(1,2)) + particles_in_encounter = Particles(keys=(1, 2)) particles_in_encounter.mass = 2. | nbody_system.mass - particles_in_encounter[0].position = [1.,0.,0.] | nbody_system.length - particles_in_encounter[1].position = [0.,0.,0.] | nbody_system.length - particles_in_encounter.velocity = [0.,0.0,0.] | nbody_system.speed + particles_in_encounter[0].position = [1., 0., 0.] | nbody_system.length + particles_in_encounter[1].position = [0., 0., 0.] | nbody_system.length + particles_in_encounter.velocity = [0., 0.0, 0.] | nbody_system.speed particles_in_encounter.radius = 0. | nbody_system.length - - + binary1 = new_binary( - 1. | nbody_system.mass, + 1. | nbody_system.mass, 1. | nbody_system.mass, 0.01 | nbody_system.length, - keyoffset = 30 + keyoffset=30 ) binaries = Particles(keys=(20,)) binaries[0].child1 = binary1[0] binaries[0].child2 = binary1[1] binary1.child1 = None binary1.child2 = None - + multiples = Particles() multiple = particles_in_encounter[0] multiple.components = binary1 multiples.add_particle(multiple) - + x = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = SmallN(), - interaction_over_code = None, - G = nbody_system.G + kepler_code=self.new_kepler(), + resolve_collision_code=SmallN(), + interaction_over_code=None, + G=nbody_system.G ) - + x.particles_in_encounter.add_particles(particles_in_encounter) x.existing_binaries.add_particles(binaries) x.existing_multiples.add_particles(multiples) - + x.execute() - + self.assertEqual(len(x.new_multiples), 1) self.assertEqual(len(x.dissolved_multiples), 1) self.assertEqual(len(x.new_binaries), 1) self.assertEqual(len(x.captured_singles), 1) self.assertEqual(len(x.released_singles), 1) - + multiple = x.new_multiples[0] print(multiple.child1) self.assertEqual(len(multiple.components), 2) print(multiple.components) - + def test4(self): - particles_in_encounter = Particles(keys=(1,2)) - particles_in_encounter.mass = 1.0 /20.0 | nbody_system.mass - + particles_in_encounter = Particles(keys=(1, 2)) + particles_in_encounter.mass = 1.0 / 20.0 | nbody_system.mass + particles_in_encounter[0].position = [0.303976184547589401, 0.273137803329168094, 0.0] | nbody_system.length particles_in_encounter[1].position = [0.290167020486133631, 0.273139253307546515, 0.0] | nbody_system.length particles_in_encounter[0].velocity = [-2.544712989335638387, -1.224759650260411004, 0.0] | nbody_system.speed particles_in_encounter[1].velocity = [0.898326624897966997, 0.870611747842778838, 0.0] | nbody_system.speed particles_in_encounter.radius = 0.007 | nbody_system.length - + x = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = SmallN(), - interaction_over_code = None, - G = nbody_system.G + kepler_code=self.new_kepler(), + resolve_collision_code=SmallN(), + interaction_over_code=None, + G=nbody_system.G ) - + x.particles_in_encounter.add_particles(particles_in_encounter) - + x.execute() - + self.assertEqual(len(x.new_multiples), 0) self.assertEqual(len(x.dissolved_multiples), 0) self.assertEqual(len(x.new_binaries), 0) self.assertEqual(len(x.captured_singles), 0) self.assertEqual(len(x.released_singles), 0) - r_before = (particles_in_encounter[0].position - particles_in_encounter[1].position ).length() + r_before = (particles_in_encounter[0].position - particles_in_encounter[1].position).length() r_after = (x.particles_after_encounter[0].position - x.particles_after_encounter[1].position).length() print(r_before, r_after) self.assertFalse(r_after > (10 * r_before)) - + def test5(self): - particles_in_encounter = Particles(keys=(1,2)) - particles_in_encounter.mass = 1.0 /20.0 | nbody_system.mass - + particles_in_encounter = Particles(keys=(1, 2)) + particles_in_encounter.mass = 1.0 / 20.0 | nbody_system.mass + particles_in_encounter[0].position = [0.0779377282404, -0.559210143918, 0.0] | nbody_system.length - particles_in_encounter[1].position = [0.07802860386, -0.561207706614, 0.0] | nbody_system.length + particles_in_encounter[1].position = [0.07802860386, -0.561207706614, 0.0] | nbody_system.length particles_in_encounter[0].velocity = [-1.79086847491, -4.88551917358, 0.0] | nbody_system.speed particles_in_encounter[1].velocity = [2.13208424698, 4.31403500143, 0.0] | nbody_system.speed particles_in_encounter.radius = 0.001 | nbody_system.length - + x = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = SmallN(), - interaction_over_code = None, - G = nbody_system.G + kepler_code=self.new_kepler(), + resolve_collision_code=SmallN(), + interaction_over_code=None, + G=nbody_system.G ) x.particles_in_encounter.add_particles(particles_in_encounter) - + x.execute() - + self.assertEqual(len(x.new_multiples), 0) self.assertEqual(len(x.dissolved_multiples), 0) self.assertEqual(len(x.new_binaries), 0) self.assertEqual(len(x.captured_singles), 0) self.assertEqual(len(x.released_singles), 0) - r_before = (particles_in_encounter[0].position - particles_in_encounter[1].position ).length() + r_before = (particles_in_encounter[0].position - particles_in_encounter[1].position).length() r_after = (x.particles_after_encounter[0].position - x.particles_after_encounter[1].position).length() print(r_before, r_after) self.assertFalse(r_after > (10 * r_before)) - - + def test6(self): - particles_in_encounter = Particles(keys=(1,2)) + particles_in_encounter = Particles(keys=(1, 2)) particles_in_encounter.mass = 2 | nbody_system.mass - particles_in_encounter[0].position = [1,0,0] | nbody_system.length - particles_in_encounter[1].position = [0,0,0] | nbody_system.length - particles_in_encounter.velocity = [0,0.0,0] | nbody_system.speed + particles_in_encounter[0].position = [1, 0, 0] | nbody_system.length + particles_in_encounter[1].position = [0, 0, 0] | nbody_system.length + particles_in_encounter.velocity = [0, 0.0, 0] | nbody_system.speed particles_in_encounter.radius = 0 | nbody_system.length - + particles_in_field = Particles(10) particles_in_field.mass = 1 | nbody_system.mass for i in range(len(particles_in_field)): @@ -1190,166 +1145,157 @@ def test6(self): else: j = i particles_in_field[i].position = [-10 + (2*j), -10 + (2*j), 0] | nbody_system.length - particles_in_field.velocity = [0,0.0,0] | nbody_system.speed + particles_in_field.velocity = [0, 0.0, 0] | nbody_system.speed particles_in_field.radius = 0 | nbody_system.length - - + x = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = SmallN(), - interaction_over_code = None, - G = nbody_system.G + kepler_code=self.new_kepler(), + resolve_collision_code=SmallN(), + interaction_over_code=None, + G=nbody_system.G ) - + x.particles_in_encounter.add_particles(particles_in_encounter) x.particles_in_field.add_particles(particles_in_field) - + x.execute() - + self.assertEqual(len(x.new_multiples), 1) self.assertEqual(len(x.dissolved_multiples), 0) self.assertEqual(len(x.new_binaries), 1) self.assertEqual(len(x.captured_singles), 2) self.assertEqual(len(x.released_singles), 0) - - + def test7(self): - particles_in_encounter = Particles(keys=(1,2)) + particles_in_encounter = Particles(keys=(1, 2)) particles_in_encounter.mass = 2. | nbody_system.mass - particles_in_encounter[0].position = [1.,0.,0.] | nbody_system.length - particles_in_encounter[1].position = [0.,0.,0.] | nbody_system.length - particles_in_encounter.velocity = [0.,0.0,0.] | nbody_system.speed + particles_in_encounter[0].position = [1., 0., 0.] | nbody_system.length + particles_in_encounter[1].position = [0., 0., 0.] | nbody_system.length + particles_in_encounter.velocity = [0., 0.0, 0.] | nbody_system.speed particles_in_encounter.radius = 0. | nbody_system.length - - + binary1 = new_binary( - 1. | nbody_system.mass, - 1. | nbody_system.mass, + 1. | nbody_system.mass, + 1. | nbody_system.mass, 0.01 | nbody_system.length, - keyoffset = 30 + keyoffset=30 ) - binary_energy = binary1.kinetic_energy() + binary1.potential_energy(G = nbody_system.G) + binary_energy = binary1.kinetic_energy() + binary1.potential_energy(G=nbody_system.G) self.assertAlmostRelativeEqual(binary_energy, -50 | nbody_system.energy) - + binaries = Particles(keys=(20,)) binaries[0].child1 = binary1[0] binaries[0].child2 = binary1[1] binary1.child1 = None binary1.child2 = None - - + multiples = Particles() multiple = particles_in_encounter[0] multiple.components = binary1 multiples.add_particle(multiple) - + x = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = SmallN(), - interaction_over_code = None, - G = nbody_system.G + kepler_code=self.new_kepler(), + resolve_collision_code=SmallN(), + interaction_over_code=None, + G=nbody_system.G ) - + x.particles_in_encounter.add_particles(particles_in_encounter) x.existing_binaries.add_particles(binaries) x.existing_multiples.add_particles(multiples) - - + x.execute() self.assertEqual(len(x.new_multiples), 1) self.assertEqual(len(x.new_binaries), 1) self.assertEqual(len(x.captured_singles), 1) self.assertEqual(len(x.released_singles), 1) - + multiple = x.new_multiples[0] self.assertEqual(len(multiple.components), 2) - + self.assertAlmostRelativeEqual(multiple.components[0].key, binaries[0].child1.key) self.assertAlmostRelativeEqual(multiple.components[1].key, particles_in_encounter[1].key) self.assertAlmostRelativeEqual(x.initial_multiple_energy, -50 | nbody_system.energy) self.assertAlmostRelativeEqual(x.final_multiple_energy, -85.651753404 | nbody_system.energy, 4) - - + def test8(self): - particles_in_encounter = Particles(keys=(1,2)) + particles_in_encounter = Particles(keys=(1, 2)) particles_in_encounter[0].mass = 2. | nbody_system.mass particles_in_encounter[1].mass = 0.1 | nbody_system.mass - particles_in_encounter[0].position = [1.,0.,0.] | nbody_system.length - particles_in_encounter[1].position = [0.,0.,0.] | nbody_system.length - particles_in_encounter.velocity = [0.,0.0,0.] | nbody_system.speed + particles_in_encounter[0].position = [1., 0., 0.] | nbody_system.length + particles_in_encounter[1].position = [0., 0., 0.] | nbody_system.length + particles_in_encounter.velocity = [0., 0.0, 0.] | nbody_system.speed particles_in_encounter.radius = 0. | nbody_system.length - - + binary1 = new_binary( - 1. | nbody_system.mass, - 1. | nbody_system.mass, + 1. | nbody_system.mass, + 1. | nbody_system.mass, 0.01 | nbody_system.length, - keyoffset = 30 + keyoffset=30 ) - binary_energy = binary1.kinetic_energy() + binary1.potential_energy(G = nbody_system.G) + binary_energy = binary1.kinetic_energy() + binary1.potential_energy(G=nbody_system.G) self.assertAlmostRelativeEqual(binary_energy, -50 | nbody_system.energy) - + binaries = Particles(keys=(20,)) binaries[0].child1 = binary1[0] binaries[0].child2 = binary1[1] binary1.child1 = None binary1.child2 = None - - + multiples = Particles() multiple = particles_in_encounter[0] multiple.components = binary1 multiples.add_particle(multiple) - + x = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = SmallN(), - interaction_over_code = None, - G = nbody_system.G + kepler_code=self.new_kepler(), + resolve_collision_code=SmallN(), + interaction_over_code=None, + G=nbody_system.G ) - + x.particles_in_encounter.add_particles(particles_in_encounter) x.existing_binaries.add_particles(binaries) x.existing_multiples.add_particles(multiples) - - + x.execute() self.assertEqual(len(x.new_multiples), 0) self.assertEqual(len(x.updated_multiples), 1) self.assertEqual(len(x.new_binaries), 0) self.assertEqual(len(x.captured_singles), 0) self.assertEqual(len(x.released_singles), 0) - + multiple = x.updated_multiples[0] self.assertEqual(len(multiple.components), 2) self.assertEqual(multiple.key, multiples[0].key) - + self.assertEqual(multiple.components[0].key, binaries[0].child1.key) self.assertEqual(multiple.components[1].key, binaries[0].child2.key) self.assertAlmostRelativeEqual(x.initial_multiple_energy, -50 | nbody_system.energy) self.assertAlmostRelativeEqual(x.final_multiple_energy, -56.2906032319 | nbody_system.energy, 4) - - + + class TestStickyHandleEncounter(amusetest.TestWithMPI): def test1(self): - particles_in_encounter = Particles(keys=(1,2)) + particles_in_encounter = Particles(keys=(1, 2)) particles_in_encounter.mass = 1 | nbody_system.mass - particles_in_encounter[0].position = [1,0,0] | nbody_system.length - particles_in_encounter[1].position = [0,0,0] | nbody_system.length - particles_in_encounter.velocity = [0,0.0,0] | nbody_system.speed - particles_in_encounter[0].velocity = [-1,0.0,0] | nbody_system.speed + particles_in_encounter[0].position = [1, 0, 0] | nbody_system.length + particles_in_encounter[1].position = [0, 0, 0] | nbody_system.length + particles_in_encounter.velocity = [0, 0.0, 0] | nbody_system.speed + particles_in_encounter[0].velocity = [-1, 0.0, 0] | nbody_system.speed particles_in_encounter.radius = 0 | nbody_system.length - + particles_in_field = Particles() - + x = encounters.StickyHandleEncounter( - G = nbody_system.G + G=nbody_system.G ) - + x.particles_in_encounter.add_particles(particles_in_encounter) - + x.execute() self.assertEqual(len(x.new_multiples), 1) self.assertEqual(len(x.new_binaries), 1) @@ -1358,11 +1304,8 @@ def test1(self): self.assertAlmostRelativeEqual(multiple.components[0].key, particles_in_encounter[0].key) self.assertAlmostRelativeEqual(multiple.components[1].key, particles_in_encounter[1].key) self.assertEqual(len(x.captured_singles), 2) - self.assertEqual(x.captured_singles.key, [1,2]) - self.assertAlmostRelativeEqual(multiple.velocity, [-0.5,0.0,0] | nbody_system.speed) - self.assertAlmostRelativeEqual(multiple.mass, 2 | nbody_system.mass) - self.assertAlmostRelativeEqual(multiple.radius, 0.5 | nbody_system.length) - self.assertAlmostRelativeEqual(multiple.position, [0.5,0,0] | nbody_system.length) - - - + self.assertEqual(x.captured_singles.key, [1, 2]) + self.assertAlmostRelativeEqual(multiple.velocity, [-0.5, 0.0, 0] | nbody_system.speed) + self.assertAlmostRelativeEqual(multiple.mass, 2 | nbody_system.mass) + self.assertAlmostRelativeEqual(multiple.radius, 0.5 | nbody_system.length) + self.assertAlmostRelativeEqual(multiple.position, [0.5, 0, 0] | nbody_system.length) diff --git a/src/amuse/test/suite/codes_tests/test_evtwin.py b/src/amuse/test/suite/codes_tests/test_evtwin.py index 43e56454cd..e41bee88a9 100644 --- a/src/amuse/test/suite/codes_tests/test_evtwin.py +++ b/src/amuse/test/suite/codes_tests/test_evtwin.py @@ -87,7 +87,6 @@ def test4(self): self.assertEqual(0, error) instance.stop() - def test5(self): print("Testing basic operations (new_particle_method, evolve_one_step etc.)...") instance = EVtwinInterface() @@ -142,7 +141,7 @@ def test6(self): (value, error) = instance.get_max_age_stop_condition() self.assertEqual(0, error) self.assertEqual(2.0e12, value) - for x in range(10,14): + for x in range(10, 14): error = instance.set_max_age_stop_condition(10 ** x) self.assertEqual(0, error) (value, error) = instance.get_max_age_stop_condition() @@ -152,7 +151,7 @@ def test6(self): (value, error) = instance.get_min_timestep_stop_condition() self.assertEqual(0, error) self.assertAlmostEqual(1.0e6, value, 5) - for x in range(-3,2): + for x in range(-3, 2): error = instance.set_min_timestep_stop_condition(10 ** x) self.assertEqual(0, error) (value, error) = instance.get_min_timestep_stop_condition() @@ -174,7 +173,7 @@ def test7(self): (value, error) = instance.get_number_of_ionization_elements() self.assertEqual(0, error) self.assertEqual(5, value) - for x in range(1,10): + for x in range(1, 10): error = instance.set_number_of_ionization_elements(x) self.assertEqual(0, error) (value, error) = instance.get_number_of_ionization_elements() @@ -236,7 +235,6 @@ def test9(self): self.assertEqual(0, instance.commit_particles()) - for index in indices: self.assertEqual(0, instance.evolve_one_step(index)) (age_after_evolve, error) = instance.get_age(index) @@ -317,7 +315,7 @@ def test3(self): self.assertAlmostEqual(instance.particles.luminosity, 0.7098065 | units.LSun, 6) self.assertAlmostEqual(instance.particles.radius, 0.8892833 | units.RSun, 6) - instance.evolve_model(4.8|units.Gyr) + instance.evolve_model(4.8 | units.Gyr) self.assertAlmostEqual(instance.particles.mass, 0.999921335 | units.MSun, 6) self.assertAlmostEqual(instance.particles.luminosity, 1.04448714 | units.LSun, 6) @@ -397,11 +395,11 @@ def xtest3(self): def test4(self): print("Testing max age stop condition...") - #masses = [.5, 1.0, 1.5] | units.MSun # Test with fewer particles for speed-up. + # masses = [.5, 1.0, 1.5] | units.MSun # Test with fewer particles for speed-up. masses = [.5] | units.MSun max_age = 9.0 | units.Myr - number_of_stars=len(masses) + number_of_stars = len(masses) stars = Particles(number_of_stars) for i, star in enumerate(stars): star.mass = masses[i] @@ -423,7 +421,7 @@ def test4(self): from_code_to_model = instance.particles.new_channel_to(stars) - instance.evolve_model(end_time = 8.0 | units.Myr) + instance.evolve_model(end_time=8.0 | units.Myr) from_code_to_model.copy() for i in range(number_of_stars): @@ -453,16 +451,16 @@ def test5(self): particles = Particles(3) particles.mass = 0.3 | units.MSun - instance = EVtwin()#redirection="none") + instance = EVtwin() # redirection="none") instance.initialize_code() instance.parameters.verbosity = True instance.commit_parameters() stars = instance.particles - self.assertEqual(len(stars), 0) # before creation + self.assertEqual(len(stars), 0) # before creation stars.add_particles(particles[:-1]) instance.commit_particles() instance.evolve_model(1.0 | units.Myr) - self.assertEqual(len(stars), 2) # before remove + self.assertEqual(len(stars), 2) # before remove self.assertAlmostEqual(stars.age, 1.0 | units.Myr) stars.remove_particle(particles[0]) @@ -472,12 +470,12 @@ def test5(self): self.assertAlmostEqual(stars[0].age, 2.0 | units.Myr) stars.add_particles(particles[::2]) - self.assertEqual(len(stars), 3) # it's back... + self.assertEqual(len(stars), 3) # it's back... self.assertAlmostEqual(stars[0].age, 2.0 | units.Myr) self.assertAlmostEqual(stars[1].age, 0.0 | units.Myr) - self.assertAlmostEqual(stars[2].age, 0.0 | units.Myr) # ... and rejuvenated. + self.assertAlmostEqual(stars[2].age, 0.0 | units.Myr) # ... and rejuvenated. - instance.evolve_model(3.0 | units.Myr) # The young stars keep their age offset from the old star + instance.evolve_model(3.0 | units.Myr) # The young stars keep their age offset from the old star self.assertAlmostEqual(stars.age, [3.0, 1.0, 1.0] | units.Myr) instance.evolve_model(4.0 | units.Myr) self.assertAlmostEqual(stars.age, [4.0, 2.0, 2.0] | units.Myr) @@ -495,17 +493,17 @@ def test6(self): self.assertEqual(instance.particles.get_number_of_zones(), [199, 199]) self.assertEqual(len(instance.particles[0].get_radius_profile()), 199) self.assertRaises(AmuseException, instance.particles.get_radius_profile, - expected_message = "Querying radius profiles of more than one particle at a time is not supported.") + expected_message="Querying radius profiles of more than one particle at a time is not supported.") self.assertEqual(len(instance.particles[1].get_density_profile()), 199) self.assertIsOfOrder(instance.particles[0].get_radius_profile()[-1], 1.0 | units.RSun) self.assertIsOfOrder(instance.particles[0].get_temperature_profile()[0], 1.0e7 | units.K) self.assertIsOfOrder(instance.particles[0].get_temperature_profile()[-1], 5.0e3 | units.K) radius1 = instance.particles[0].get_radius_profile() radius2 = radius1[:-1] - radius2.prepend(0|units.m) + radius2.prepend(0 | units.m) delta_radius_cubed = (radius1**3 - radius2**3) total_mass = (4./3. * pi * instance.particles[0].get_density_profile() * delta_radius_cubed).sum() - self.assertAlmostRelativeEqual(total_mass, stars[0].mass, places = 1) + self.assertAlmostRelativeEqual(total_mass, stars[0].mass, places=1) self.assertAlmostEqual(instance.particles[0].get_mu_profile()[:100], [0.62]*100 | units.amu, places=1) instance.stop() @@ -518,10 +516,10 @@ def test7(self): instance.commit_parameters() instance.particles.add_particles(stars) instance.commit_particles() - number_of_zones = instance.particles.get_number_of_zones()[0] + number_of_zones = instance.particles.get_number_of_zones()[0] number_of_species = instance.particles.get_number_of_species()[0] - composition = instance.particles[0].get_chemical_abundance_profiles() - species_names = instance.particles[0].get_names_of_species() + composition = instance.particles[0].get_chemical_abundance_profiles() + species_names = instance.particles[0].get_names_of_species() self.assertEqual(number_of_zones, 199) self.assertEqual(number_of_species, 9) self.assertEqual(len(species_names), number_of_species) @@ -530,7 +528,7 @@ def test7(self): self.assertEqual(species_names, ['h1', 'he4', 'c12', 'n14', 'o16', 'ne20', 'mg24', 'si28', 'fe56']) self.assertAlmostEqual(composition[0, -1], 0.7, 3) self.assertAlmostEqual(composition[1, -1], 0.3 - instance.parameters.metallicity, 3) - self.assertAlmostEqual(composition[2:,-1].sum(), instance.parameters.metallicity, 3) + self.assertAlmostEqual(composition[2:, -1].sum(), instance.parameters.metallicity, 3) self.assertAlmostEqual(composition.sum(axis=0), [1.0]*number_of_zones) instance.stop() @@ -546,11 +544,11 @@ def slowtest8(self): instance.evolve_model(11.7 | units.Gyr) self.assertTrue(instance.particles[0].age >= 11.7 | units.Gyr) print(instance.particles[0].stellar_type) -#~ self.assertTrue(str(instance.particles[0].stellar_type) == "First Giant Branch") - number_of_zones = instance.particles.get_number_of_zones()[0] +# ~ self.assertTrue(str(instance.particles[0].stellar_type) == "First Giant Branch") + number_of_zones = instance.particles.get_number_of_zones()[0] number_of_species = instance.particles.get_number_of_species()[0] - composition = instance.particles[0].get_chemical_abundance_profiles() - species_names = instance.particles[0].get_names_of_species() + composition = instance.particles[0].get_chemical_abundance_profiles() + species_names = instance.particles[0].get_names_of_species() self.assertEqual(number_of_zones, 199) self.assertEqual(number_of_species, 9) self.assertEqual(len(species_names), number_of_species) @@ -559,20 +557,20 @@ def slowtest8(self): self.assertEqual(species_names, ['h1', 'he4', 'c12', 'n14', 'o16', 'ne20', 'mg24', 'si28', 'fe56']) self.assertAlmostRelativeEquals(composition[0, -1], 0.7 | units.none, 1) self.assertAlmostRelativeEquals(composition[1, -1], 0.3 - instance.parameters.metallicity, 1) - self.assertAlmostRelativeEquals(composition[2:,-1].sum(), instance.parameters.metallicity, 1) + self.assertAlmostRelativeEquals(composition[2:, -1].sum(), instance.parameters.metallicity, 1) self.assertAlmostEqual(composition.sum(axis=0), [1.0]*number_of_zones | units.none) self.assertAlmostEqual(composition[0, 0], 0.00 | units.none) self.assertAlmostEqual(composition[1, 0], 1.00 - instance.parameters.metallicity, 3) - self.assertAlmostEqual(composition[2:,0].sum(), instance.parameters.metallicity, 3) + self.assertAlmostEqual(composition[2:, 0].sum(), instance.parameters.metallicity, 3) instance.stop() def test9(self): print("Test for saving and loading the stellar structure model") filenames = ["test1.dump", "test2.dump"] filenames = [os.path.join(get_path_to_results(), name) for name in filenames] - instance = EVtwin()#redirection="none") + instance = EVtwin() # redirection="none") instance.parameters.verbosity = True - instance.particles.add_particles(Particles(mass = [0.5, 0.8] | units.MSun)) + instance.particles.add_particles(Particles(mass=[0.5, 0.8] | units.MSun)) instance.evolve_model() instance.particles.write_star_to_file(filenames) copies = Particles(2) @@ -582,10 +580,10 @@ def test9(self): print(instance.particles) import warnings warnings.warn("this test's precision has been temporarily (2017) decreased") - # the reason for this is that the deviation is compiler dependend (and does only happen + # the reason for this is that the deviation is compiler dependend (and does only happen # on some machine/compiler/OS combinations) # it may have something to do with initialization of variables in evtwin - #~ self.assertAlmostRelativeEquals(instance.particles.temperature, [3644, 4783, 3644, 4783] | units.K, 3) + # ~ self.assertAlmostRelativeEquals(instance.particles.temperature, [3644, 4783, 3644, 4783] | units.K, 3) self.assertAlmostRelativeEquals(instance.particles.temperature, [3644, 4783, 3644, 4783] | units.K, 2) instance.stop() @@ -603,7 +601,7 @@ def xtest9(self): density_profile = instance.particles[0].get_density_profile() self.assertRaises(AmuseException, instance.particles[0].set_density_profile, density_profile[2:], - expected_message = "The length of the supplied vector (197) does not match the number of " + expected_message="The length of the supplied vector (197) does not match the number of " "mesh zones of the star (199).") mass_factor = 1.1 @@ -614,10 +612,10 @@ def xtest9(self): outer_radius = instance.particles[0].get_radius_profile() inner_radius = outer_radius[:-1] - inner_radius.prepend(0|units.m) + inner_radius.prepend(0 | units.m) delta_radius_cubed = (outer_radius**3 - inner_radius**3) integrated_mass = (4./3.*pi*delta_radius_cubed*instance.particles[0].get_density_profile()).sum() - self.assertAlmostRelativeEqual(integrated_mass, star.mass*mass_factor, places = 3) + self.assertAlmostRelativeEqual(integrated_mass, star.mass*mass_factor, places=3) instance.stop() del instance @@ -632,28 +630,28 @@ def xtest10(self): instance.commit_particles() instance.evolve_model() - composition = instance.particles[0].get_chemical_abundance_profiles() + composition = instance.particles[0].get_chemical_abundance_profiles() h1_profile = composition[0] * 1 he4_profile = composition[1] * 1 - k_surface = -1 # index to the outer mesh cell (surface) + k_surface = -1 # index to the outer mesh cell (surface) self.assertAlmostEqual(composition[0, k_surface], 0.7 | units.none, 4) self.assertAlmostEqual(composition[1, k_surface], (0.3 | units.none) - instance.parameters.metallicity, 4) - self.assertAlmostEqual(composition[2: , k_surface].sum(), instance.parameters.metallicity, 4) + self.assertAlmostEqual(composition[2:, k_surface].sum(), instance.parameters.metallicity, 4) composition[0] = he4_profile composition[1] = h1_profile instance.particles[0].set_chemical_abundance_profiles(composition) instance.evolve_model() - composition = instance.particles[0].get_chemical_abundance_profiles() + composition = instance.particles[0].get_chemical_abundance_profiles() self.assertAlmostEqual(composition[0, k_surface], (0.3 | units.none) - instance.parameters.metallicity, 4) self.assertAlmostEqual(composition[1, k_surface], 0.7 | units.none, 4) - self.assertAlmostEqual(composition[2: , k_surface].sum(), instance.parameters.metallicity, 4) + self.assertAlmostEqual(composition[2:, k_surface].sum(), instance.parameters.metallicity, 4) self.assertAlmostEqual(composition.sum(axis=0), 1.0 | units.none) self.assertRaises(AmuseException, instance.particles[0].set_chemical_abundance_profiles, composition[:7], - expected_message = "The length of the supplied vector (7) does not match the number of " + expected_message="The length of the supplied vector (7) does not match the number of " "chemical species of the star (8).") instance.stop() del instance @@ -661,17 +659,17 @@ def xtest10(self): def test11(self): print("Test for importing new stellar models") instance = EVtwin() -#~ instance.parameters.import_model_entropy_force = 1.0 -#~ instance.parameters.import_model_entropy_accuracy = 1.0e-1 +# ~ instance.parameters.import_model_entropy_force = 1.0 +# ~ instance.parameters.import_model_entropy_accuracy = 1.0e-1 instance.parameters.verbosity = True - instance.particles.add_particles(Particles(mass = [0.8] | units.MSun)) + instance.particles.add_particles(Particles(mass=[0.8] | units.MSun)) instance.evolve_model() instance.new_particle_from_model(instance.particles[0].get_internal_structure()) # The above line is equivalent with: - #copy = Particles(1) - #copy.internal_structure = instance.particles[0].get_internal_structure() - #instance.particles.add_particles(copy) + # copy = Particles(1) + # copy.internal_structure = instance.particles[0].get_internal_structure() + # instance.particles.add_particles(copy) number_of_zones = instance.particles[0].get_number_of_zones() self.assertEqual(len(instance.particles), 2) @@ -680,7 +678,7 @@ def test11(self): self.assertIsOfOrder(instance.particles[1].get_temperature_profile()[0], 1.0e7 | units.K) self.assertIsOfOrder(instance.particles[1].get_pressure_profile()[0], 1.0e17 | units.barye) - instance.evolve_model(keep_synchronous = False) + instance.evolve_model(keep_synchronous=False) self.assertAlmostRelativeEqual( instance.particles[0].temperature, instance.particles[1].temperature, 2) self.assertAlmostRelativeEqual( @@ -691,7 +689,7 @@ def slowtest11(self): print("Test for importing new stellar models, also check long-term evolution") instance = EVtwin() instance.parameters.verbosity = True - instance.particles.add_particles(Particles(mass = [0.8] | units.MSun)) + instance.particles.add_particles(Particles(mass=[0.8] | units.MSun)) instance.evolve_model() copy = Particles(1) @@ -705,15 +703,15 @@ def slowtest11(self): self.assertIsOfOrder(instance.particles[1].get_temperature_profile()[0], 1.0e7 | units.K) self.assertIsOfOrder(instance.particles[1].get_pressure_profile()[0], 1.0e17 | units.barye) - t1, l1 = simulate_evolution_tracks(instance.particles[0], end_time=26.5|units.Gyr) - t2, l2 = simulate_evolution_tracks(instance.particles[1], end_time=26.5|units.Gyr) + t1, l1 = simulate_evolution_tracks(instance.particles[0], end_time=26.5 | units.Gyr) + t2, l2 = simulate_evolution_tracks(instance.particles[1], end_time=26.5 | units.Gyr) instance.stop() - i1 = t1.argmax() # Maximum temperature ~ turnoff main sequence + i1 = t1.argmax() # Maximum temperature ~ turnoff main sequence i2 = t2.argmax() self.assertAlmostRelativeEqual(t1[i1], t2[i2], 2) self.assertAlmostRelativeEqual(l1[i1], l2[i2], 2) - #plot_tracks(t1, l1, t2, l2) + # plot_tracks(t1, l1, t2, l2) def xslowtest11(self): print("Test 11: Continue the stellar evolution of a 'merger product' - WIP") @@ -811,21 +809,21 @@ def xtest13(self): print("evolve_model without arguments: use shared timestep = 0.99*min(particles.time_step)") instance.evolve_model() - self.assertAlmostEqual(instance.particles.age, 0.99*([1876.53255132,1876.53255132,1876.53255132] | units.yr), 3) - self.assertAlmostEqual(instance.particles.time_step, [70465.105509,6063.68785133,1876.53255132] | units.yr, 3) + self.assertAlmostEqual(instance.particles.age, 0.99*([1876.53255132, 1876.53255132, 1876.53255132] | units.yr), 3) + self.assertAlmostEqual(instance.particles.time_step, [70465.105509, 6063.68785133, 1876.53255132] | units.yr, 3) self.assertAlmostEqual(instance.model_time, 0.99*1876.53255132 | units.yr, 3) print("evolve_model with end_time: take timesteps, until end_time is reached exactly") instance.evolve_model(15000 | units.yr) self.assertAlmostEqual(instance.particles.age, [15000.0, 15000.0, 15000.0] | units.yr, 3) - self.assertAlmostEqual(instance.particles.time_step, [ 84558.1266108,7276.4254216,2251.83906159] | units.yr, 3) + self.assertAlmostEqual(instance.particles.time_step, [84558.1266108, 7276.4254216, 2251.83906159] | units.yr, 3) self.assertAlmostEqual(instance.model_time, 15000.0 | units.yr, 3) print("evolve_model with keep_synchronous: use non-shared timestep, particle ages will typically diverge") - instance.evolve_model(keep_synchronous = False) - self.assertAlmostEqual(instance.particles.age, (15000 | units.yr) + ([ 84558.1266108,7276.4254216,2251.83906159] | units.yr), 3) - self.assertAlmostRelativeEquals(instance.particles.time_step, [101469.751933,8731.71050591,2702.2068739] | units.yr, 1) - self.assertAlmostEqual(instance.model_time, 15000.0 | units.yr, 3) # Unchanged! + instance.evolve_model(keep_synchronous=False) + self.assertAlmostEqual(instance.particles.age, (15000 | units.yr) + ([84558.1266108, 7276.4254216, 2251.83906159] | units.yr), 3) + self.assertAlmostRelativeEquals(instance.particles.time_step, [101469.751933, 8731.71050591, 2702.2068739] | units.yr, 1) + self.assertAlmostEqual(instance.model_time, 15000.0 | units.yr, 3) # Unchanged! instance.stop() def test14(self): @@ -848,7 +846,7 @@ def test14(self): instance.stop() print("ok") - print("initialize_code(), commit_parameters(), (re)commit_particles(), " \ + print("initialize_code(), commit_parameters(), (re)commit_particles(), " "and cleanup_code() should be called automatically:", end=' ') instance = EVtwin() self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') @@ -869,62 +867,62 @@ def test14(self): def slowtest15(self): print("test evolution of 1000 star sampled over flattish IMF") - number_of_stars=1000 + number_of_stars = 1000 from amuse.ic.salpeter import new_salpeter_mass_distribution import numpy class notsorandom(object): - def random(self,N): + def random(self, N): return numpy.array(range(N))/(N-1.) masses = new_salpeter_mass_distribution( number_of_stars, - mass_min = 0.1 | units.MSun, - mass_max = 100.0 | units.MSun, - alpha = -1.01,random=notsorandom() + mass_min=0.1 | units.MSun, + mass_max=100.0 | units.MSun, + alpha=-1.01, random=notsorandom() ) stars = Particles(mass=masses) - instance=EVtwin() - instance.parameters.maximum_number_of_stars=number_of_stars - instance.parameters.min_timestep_stop_condition=.001 | units.s + instance = EVtwin() + instance.parameters.maximum_number_of_stars = number_of_stars + instance.parameters.min_timestep_stop_condition = .001 | units.s instance.particles.add_particles(stars) - i=0 + i = 0 for p in instance.particles: - print(i,p.mass) - p.evolve_for(0.1 | units.Myr) - i+=1 + print(i, p.mass) + p.evolve_for(0.1 | units.Myr) + i += 1 def xslowtest16(self): print("test full evolution of 1000 star sampled over flattish IMF") - number_of_stars=1000 + number_of_stars = 1000 from amuse.ic.salpeter import new_salpeter_mass_distribution import numpy class notsorandom(object): - def random(self,N): + def random(self, N): return numpy.array(range(N))/(N-1.) masses = new_salpeter_mass_distribution( number_of_stars, - mass_min = 0.1 | units.MSun, - mass_max = 100.0 | units.MSun, - alpha = -1.01,random=notsorandom() + mass_min=0.1 | units.MSun, + mass_max=100.0 | units.MSun, + alpha=-1.01, random=notsorandom() ) stars = Particles(mass=masses) - instance=EVtwin() - instance.parameters.maximum_number_of_stars=number_of_stars + instance = EVtwin() + instance.parameters.maximum_number_of_stars = number_of_stars instance.particles.add_particles(stars) for p in instance.particles: - p.evolve_for(13.2 | units.Gyr) + p.evolve_for(13.2 | units.Gyr) def slowtest17(self): """ @@ -933,53 +931,53 @@ def slowtest17(self): star masses and which star is evolved first. """ exceptions = [] - for i, (masses, indices) in enumerate([ + for i, (masses, indices) in enumerate([ ( [1.21372730283, 1.22207032494, 11.21372730283] | units.MSun, - (0,1) + (0, 1) ), ( [1.21372730283, 1.22207032494, 1.21372730283] | units.MSun, - (0,1) + (0, 1) ), ( [1.21372730283, 1.22207032494, 1.21372730283] | units.MSun, - (1,0) + (1, 0) ), ( [1.21372730283, 1.22207032494] | units.MSun, - (0,1) + (0, 1) ), ( [1.21372730283, 11.22207032494, 1.21372730283] | units.MSun, - (0,1) + (0, 1) ), ( [1.21372730283, 1.21372730283, 1.21372730283] | units.MSun, - (0,1) + (0, 1) ), ( [1.21372730283, 1.22207032494, 1.21372730283] | units.MSun, - (0,1) + (0, 1) ), ( [0.101, 1.22207032494, 1.21372730283] | units.MSun, - (0,1) + (0, 1) ) ]): stars = Particles(mass=masses) - instance=EVtwin() + instance = EVtwin() instance.particles.add_particles(stars) try: index_in_indices = 0 - instance.particles[indices[index_in_indices]].evolve_for(0.1| units.Myr) + instance.particles[indices[index_in_indices]].evolve_for(0.1 | units.Myr) index_in_indices = 1 - instance.particles[indices[index_in_indices]].evolve_for(0.1| units.Myr) + instance.particles[indices[index_in_indices]].evolve_for(0.1 | units.Myr) except AmuseException as ex: - exceptions.append( [i, masses, indices, index_in_indices] ) + exceptions.append([i, masses, indices, index_in_indices]) instance.stop() @@ -996,12 +994,12 @@ def slowtest17(self): def xtest18(self): print("Testing EVtwin calculate_core_mass") - instance = EVtwin()#redirection="none") - star = instance.particles.add_particle(Particle(mass=1|units.MSun)) - instance.evolve_model(0.4|units.Gyr) # VERY short, for test speed up + instance = EVtwin() # redirection="none") + star = instance.particles.add_particle(Particle(mass=1 | units.MSun)) + instance.evolve_model(0.4 | units.Gyr) # VERY short, for test speed up central_hydrogen_abundance = star.get_chemical_abundance_profiles()[0][0] - self.assertTrue(central_hydrogen_abundance < 0.68) # some hydrogen is burned - self.assertTrue(central_hydrogen_abundance > 0.67) # ... but not that much yet + self.assertTrue(central_hydrogen_abundance < 0.68) # some hydrogen is burned + self.assertTrue(central_hydrogen_abundance > 0.67) # ... but not that much yet self.assertEqual(star.calculate_core_mass(core_H_abundance_limit=0.67), 0 | units.MSun) self.assertAlmostEqual(star.calculate_core_mass(core_H_abundance_limit=0.71), 1 | units.MSun, 1) @@ -1033,7 +1031,7 @@ def xtest18(self): def xtest19(self): print("Testing EVtwin central_temperature and central_density") instance = EVtwin() - stars = instance.particles.add_particles(Particles(mass=[0.1, 1, 10]|units.MSun)) + stars = instance.particles.add_particles(Particles(mass=[0.1, 1, 10] | units.MSun)) self.assertIsOfOrder(stars.central_temperature, [4e6, 13e6, 31e6] | units.K) self.assertIsOfOrder(stars.central_density, [400, 77, 9] | units.g * units.cm**-3) instance.stop() @@ -1042,8 +1040,8 @@ def test20(self): print("Testing EVtwin manual mass transfer rate") instance = EVtwin() instance.parameters.verbosity = True - stars = instance.particles.add_particles(Particles(mass=[0.8, 0.8]|units.MSun)) - stars[0].mass_transfer_rate = -1e-8|units.MSun/units.yr + stars = instance.particles.add_particles(Particles(mass=[0.8, 0.8] | units.MSun)) + stars[0].mass_transfer_rate = -1e-8 | units.MSun/units.yr instance.evolve_model() # NOTE! no mass transfer during the initial step: self.assertEqual(stars[0].mass, stars[1].mass) @@ -1053,11 +1051,11 @@ def test20(self): instance.evolve_model() self.assertTrue(stars[0].mass < stars[1].mass) # NOTE 2! actual mass transfer rate 10x lower: - self.assertAlmostRelativeEqual((stars[0].mass-mass) / (stars[0].age-age), -1.0e-9|units.MSun/units.yr, 4) + self.assertAlmostRelativeEqual((stars[0].mass-mass) / (stars[0].age-age), -1.0e-9 | units.MSun/units.yr, 4) instance.stop() -def simulate_evolution_tracks(star, end_time=1|units.Gyr): +def simulate_evolution_tracks(star, end_time=1 | units.Gyr): luminosity_at_time = [] | units.LSun temperature_at_time = [] | units.K while star.age < end_time: @@ -1067,10 +1065,11 @@ def simulate_evolution_tracks(star, end_time=1|units.Gyr): print(star.age) return temperature_at_time, luminosity_at_time + def plot_tracks(temperature1, luminosity1, temperature2, luminosity2): from matplotlib import pyplot from amuse.plot import loglog, xlabel, ylabel - pyplot.figure(figsize = (8, 6)) + pyplot.figure(figsize=(8, 6)) pyplot.title('Hertzsprung-Russell diagram', fontsize=12) loglog(temperature1, luminosity1) loglog(temperature2, luminosity2) @@ -1078,4 +1077,3 @@ def plot_tracks(temperature1, luminosity1, temperature2, luminosity2): ylabel('Luminosity') pyplot.xlim(pyplot.xlim()[::-1]) pyplot.show() - diff --git a/src/amuse/test/suite/codes_tests/test_fastkick.py b/src/amuse/test/suite/codes_tests/test_fastkick.py index f44ab873a5..8ca4ab49ad 100644 --- a/src/amuse/test/suite/codes_tests/test_fastkick.py +++ b/src/amuse/test/suite/codes_tests/test_fastkick.py @@ -14,12 +14,12 @@ class TestFastKickInterface(TestWithMPI): number_of_workers = 2 mode = "cpu" - + def test1(self): instance = FastKickInterface(mode=self.mode, number_of_workers=self.number_of_workers) instance.initialize_code() - id1, error1 = instance.new_particle(mass = 11.0, x = 0.0, y = 0.0, z = 0.0) - id2, error2 = instance.new_particle(mass = 21.0, x = 10.0, y = 0.0, z = 0.0) + id1, error1 = instance.new_particle(mass=11.0, x=0.0, y=0.0, z=0.0) + id2, error2 = instance.new_particle(mass=21.0, x=10.0, y=0.0, z=0.0) self.assertEqual(0, id1) self.assertEqual(0, error1) self.assertEqual(1, id2) @@ -27,7 +27,7 @@ def test1(self): self.assertEqual(0, instance.commit_particles()) self.assertEqual(0, instance.cleanup_code()) instance.stop() - + def test2(self): fastkick = FastKickInterface(mode=self.mode, number_of_workers=self.number_of_workers) self.assertEqual(0, fastkick.set_eps2(0.101)) @@ -36,17 +36,17 @@ def test2(self): self.assertEqual([0.2, 0], list(fastkick.get_eps2().values())) fastkick.cleanup_code() fastkick.stop() - + def test3(self): fastkick = FastKickInterface(mode=self.mode, number_of_workers=self.number_of_workers) fastkick.initialize_code() - fastkick.new_particle([10,10],[-1,1],[0,0], [0,0]) + fastkick.new_particle([10, 10], [-1, 1], [0, 0], [0, 0]) self.assertEqual(0, fastkick.commit_particles()) - self.assertEqual([-20.0, 0], list(fastkick.get_potential_at_point(0, 0,0,0).values())) - self.assertAlmostEqual(-10.0*math.sqrt(2.0), list(fastkick.get_potential_at_point(1.0, 0,0,0).values())[0], 4) + self.assertEqual([-20.0, 0], list(fastkick.get_potential_at_point(0, 0, 0, 0).values())) + self.assertAlmostEqual(-10.0*math.sqrt(2.0), list(fastkick.get_potential_at_point(1.0, 0, 0, 0).values())[0], 4) fastkick.cleanup_code() fastkick.stop() - + def test4(self): numpy.random.seed(12345) plummer = new_plummer_model(100) @@ -55,31 +55,31 @@ def test4(self): fastkick.new_particle([1]*100, plummer.x.number, plummer.y.number, plummer.z.number) self.assertEqual(0, fastkick.commit_particles()) points = new_plummer_model(73) - potential1, error = fastkick.get_potential_at_point([0]*73, + potential1, error = fastkick.get_potential_at_point([0]*73, points.x.number, points.y.number, points.z.number) - ax1, ay1, az1, error = fastkick.get_gravity_at_point([0]*73, + ax1, ay1, az1, error = fastkick.get_gravity_at_point([0]*73, points.x.number, points.y.number, points.z.number) fastkick.cleanup_code() - + fastkick.initialize_code() self.assertEqual(0, fastkick.commit_particles()) - potential0, error = fastkick.get_potential_at_point([0]*73, + potential0, error = fastkick.get_potential_at_point([0]*73, points.x.number, points.y.number, points.z.number) - ax0, ay0, az0, error = fastkick.get_gravity_at_point([0]*73, + ax0, ay0, az0, error = fastkick.get_gravity_at_point([0]*73, points.x.number, points.y.number, points.z.number) self.assertAlmostEqual(potential0, 0) self.assertAlmostEqual(ax0, 0) self.assertAlmostEqual(ay0, 0) self.assertAlmostEqual(az0, 0) fastkick.cleanup_code() - + fastkick.initialize_code() for p in plummer: fastkick.new_particle(1, p.x.number, p.y.number, p.z.number) self.assertEqual(0, fastkick.commit_particles()) - potential2, error = fastkick.get_potential_at_point([0]*73, + potential2, error = fastkick.get_potential_at_point([0]*73, points.x.number, points.y.number, points.z.number) - ax2, ay2, az2, error = fastkick.get_gravity_at_point([0]*73, + ax2, ay2, az2, error = fastkick.get_gravity_at_point([0]*73, points.x.number, points.y.number, points.z.number) self.assertAlmostEqual(potential1, potential2, 4) self.assertAlmostEqual(ax1, ax2, 4) @@ -87,29 +87,29 @@ def test4(self): self.assertAlmostEqual(az1, az2, 4) fastkick.cleanup_code() fastkick.stop() - class TestFastKick(TestWithMPI): - + mode = "cpu" + def new_fastkick_instance(self, convert_nbody=None, number_of_workers=2, **kwargs): return FastKick(convert_nbody, mode=self.mode, number_of_workers=number_of_workers, **kwargs) - + def test1(self): print("Testing FastKick (SI)") sun = Particle() - sun.mass = 1.0|units.MSun + sun.mass = 1.0 | units.MSun sun.position = [0, 0, 0] | units.m convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) fastkick = self.new_fastkick_instance(convert_nbody) fastkick.particles.add_particle(sun) - ax, ay, az = fastkick.get_gravity_at_point(0|units.AU, 1|units.AU, 0|units.AU, 0|units.AU) + ax, ay, az = fastkick.get_gravity_at_point(0 | units.AU, 1 | units.AU, 0 | units.AU, 0 | units.AU) fastkick.stop() self.assertAlmostRelativeEqual(ax, -4*math.pi**2 | units.AU / units.yr**2, 3) self.assertAlmostRelativeEqual(ay, 0 | units.m * units.s**-2, 6) self.assertAlmostRelativeEqual(az, 0 | units.m * units.s**-2, 6) - + def test2(self): print("Testing FastKick reset") particles = new_plummer_model(50) @@ -117,26 +117,26 @@ def test2(self): instance.parameters.epsilon_squared = 0.12345 | nbody_system.length**2 instance.particles.add_particles(particles) self.assertEqual(len(instance.particles), 50) - + instance.reset() - - self.assertAlmostRelativeEquals(instance.parameters.epsilon_squared , 0.12345 | nbody_system.length**2) + + self.assertAlmostRelativeEquals(instance.parameters.epsilon_squared, 0.12345 | nbody_system.length**2) self.assertEqual(len(instance.particles), 0) instance.particles.add_particles(particles) self.assertEqual(len(instance.particles), 50) - + def test3(self): print("Testing FastKick parameters") convert_nbody = nbody_system.nbody_to_si(1.0 | units.yr, 1.0 | units.AU) instance = self.new_fastkick_instance(convert_nbody) - + self.assertAlmostEqual(0.0 | units.AU**2, instance.parameters.epsilon_squared, in_units=units.AU**2) for x in [0.01, 0.1, 0.2]: instance.parameters.epsilon_squared = x | units.AU**2 self.assertAlmostEqual(x | units.AU**2, instance.parameters.epsilon_squared, in_units=units.AU**2) - + instance.stop() - + def test4(self): numpy.random.seed(12345) plummer = new_plummer_model(100) @@ -147,7 +147,7 @@ def test4(self): potential1 = fastkick.get_potential_at_point(0*points.x, points.x, points.y, points.z) ax1, ay1, az1 = fastkick.get_gravity_at_point(0*points.x, points.x, points.y, points.z) fastkick.reset() - + potential0 = fastkick.get_potential_at_point(0*points.x, points.x, points.y, points.z) ax0, ay0, az0 = fastkick.get_gravity_at_point(0*points.x, points.x, points.y, points.z) self.assertAlmostEqual(potential0, 0 | nbody_system.potential) @@ -155,7 +155,7 @@ def test4(self): self.assertAlmostEqual(ay0, 0 | nbody_system.acceleration) self.assertAlmostEqual(az0, 0 | nbody_system.acceleration) fastkick.reset() - + for p in plummer: fastkick.particles.add_particle(p) potential2 = fastkick.get_potential_at_point(0*points.x, points.x, points.y, points.z) @@ -166,11 +166,11 @@ def test4(self): self.assertAlmostEqual(az1, az2, 5) fastkick.cleanup_code() fastkick.stop() - + def test5(self): print("Testing FastKick states") plummer = new_plummer_model(100) - + print("First do everything manually:") instance = self.new_fastkick_instance() self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') @@ -185,7 +185,7 @@ def test5(self): self.assertEqual(instance.get_name_of_current_state(), 'END') instance.stop() - print("commit_parameters(), (re)commit_particles(), and cleanup_code() should be called " \ + print("commit_parameters(), (re)commit_particles(), and cleanup_code() should be called " "automatically before new_xx_particle(), get_xx(), and stop():") instance = self.new_fastkick_instance() self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') @@ -201,7 +201,7 @@ def test5(self): self.assertEqual(instance.get_name_of_current_state(), 'RUN') instance.stop() self.assertEqual(instance.get_name_of_current_state(), 'STOPPED') - + def test6(self): plummer = new_plummer_model(100) points = new_plummer_model(73) @@ -210,7 +210,7 @@ def test6(self): potential1 = instance.get_potential_at_point(0*points.x, points.x, points.y, points.z) ax1, ay1, az1 = instance.get_gravity_at_point(0*points.x, points.x, points.y, points.z) instance.stop() - + expected_accuracy = 13 if self.mode == "cpu" else 5 number_of_workers_range = [2, 3, 4, 5] if self.mode == "cpu" else [2] for n in number_of_workers_range: @@ -219,21 +219,21 @@ def test6(self): potential = instance.get_potential_at_point(0*points.x, points.x, points.y, points.z) ax, ay, az = instance.get_gravity_at_point(0*points.x, points.x, points.y, points.z) instance.stop() - + self.assertAlmostEqual(potential, potential1, expected_accuracy) self.assertAlmostEqual(ax, ax1, expected_accuracy) self.assertAlmostEqual(ay, ay1, expected_accuracy) self.assertAlmostEqual(az, az1, expected_accuracy) - + def test7(self): instance = self.new_fastkick_instance() instance.parameters.epsilon_squared = 0.00001 | nbody_system.length**2 - + particles = Particles(2) particles.mass = [1.0, 1.0] | nbody_system.mass - particles.position = [[0.0,0.0,0.0], [2.0,0.0,0.0]] | nbody_system.length + particles.position = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]] | nbody_system.length instance.particles.add_particles(particles) - + zero = 0.0 | nbody_system.length ax, ay, az = instance.get_gravity_at_point(zero, 1.0 | nbody_system.length, zero, zero) self.assertAlmostEqual(ax, 0.0 | nbody_system.acceleration, 6) @@ -247,25 +247,25 @@ def test7(self): potential1 = instance.get_potential_at_point(zero, x1, zero, zero) ax0, ay0, az0 = instance.get_gravity_at_point(zero, x0, zero, zero) ax1, ay1, az1 = instance.get_gravity_at_point(zero, x1, zero, zero) - + self.assertAlmostEqual(ay0, 0.0 | nbody_system.acceleration, 6) self.assertAlmostEqual(az0, 0.0 | nbody_system.acceleration, 6) self.assertAlmostEqual(ay1, 0.0 | nbody_system.acceleration, 6) self.assertAlmostEqual(az1, 0.0 | nbody_system.acceleration, 6) - + self.assertAlmostEqual(ax0, -ax1, 5) ax = (-1.0 / (x0**2) + 1.0 / (x1**2)) * (1.0 | nbody_system.length**3 / nbody_system.time**2) self.assertAlmostEqual(ax, ax0, 2) self.assertAlmostEqual(potential0, potential1, 5) instance.stop() - + def test8(self): print("Testing FastKick for Bridge: potential energy") numpy.random.seed(12345) stars = new_plummer_model(100) cluster = new_gravity_code(stars) - - first_half = stars.select_array(lambda x: (x > 0 | nbody_system.length), ['x'] ) + + first_half = stars.select_array(lambda x: (x > 0 | nbody_system.length), ['x']) second_half = stars - first_half cluster1 = new_gravity_code(first_half) cluster2 = new_gravity_code(second_half) @@ -274,12 +274,12 @@ def test8(self): bridgesys = Bridge() bridgesys.add_system(cluster1, (kick_from_cluster2,)) bridgesys.add_system(cluster2, (kick_from_cluster1,)) - + self.assertAlmostRelativeEqual(cluster.potential_energy, bridgesys.potential_energy, 7) self.assertAlmostRelativeEqual(cluster.kinetic_energy, bridgesys.kinetic_energy) kick_from_cluster1.code.stop() kick_from_cluster2.code.stop() - + def test9(self): print("Testing FastKick for Bridge: evolving a binary") particles = Particles(2) @@ -289,40 +289,40 @@ def test9(self): particles[1].x = 2.0 | units.AU particles[1].vy = (constants.G * (4.0 | units.MSun) / (2.0 | units.AU)).sqrt() particles.move_to_center() - + primary_sys = new_gravity_code(particles[:1]) secondary_sys = new_gravity_code(particles[1:]) - + primary = primary_sys.particles[0] P = 2 * math.pi * primary.x / primary.vy - + converter = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) kick_from_primary = CalculateFieldForCodesUsingReinitialize(self.new_fastkick_instance(converter), (primary_sys,)) kick_from_secondary = CalculateFieldForCodesUsingReinitialize(self.new_fastkick_instance(converter), (secondary_sys,)) - - bridgesys = Bridge(timestep = P / 64.0) + + bridgesys = Bridge(timestep=P / 64.0) bridgesys.add_system(primary_sys, (kick_from_secondary,)) bridgesys.add_system(secondary_sys, (kick_from_primary,)) - + position_at_start = primary.position.x bridgesys.evolve_model(P / 4.0) self.assertAlmostRelativeEqual(position_at_start, primary.position.y, 2) - + bridgesys.evolve_model(P / 2.0) self.assertAlmostRelativeEqual(position_at_start, -primary.position.x, 2) - + bridgesys.evolve_model(P) kick_from_primary.code.stop() kick_from_secondary.code.stop() self.assertAlmostRelativeEqual(position_at_start, primary.position.x, 2) - + def test10(self): number_of_sources = 10 number_of_points = 1000000 mass, length, G = nbody_system.mass, nbody_system.length, nbody_system.G - sources = Particles(mass=numpy.ones(number_of_sources)|mass, x=0|length, y=0|length, z=0|length) - points = Particles(x=0|length, y=0|length, z=numpy.arange(number_of_points)+1.0|length) - + sources = Particles(mass=numpy.ones(number_of_sources) | mass, x=0 | length, y=0 | length, z=0 | length) + points = Particles(x=0 | length, y=0 | length, z=numpy.arange(number_of_points)+1.0 | length) + instance = self.new_fastkick_instance() instance.particles.add_particles(sources) potential = instance.get_potential_at_point(0*points.x, points.x, points.y, points.z) @@ -332,89 +332,91 @@ def test10(self): self.assertAlmostRelativeEqual(az, -G*sources.total_mass()/points.z**2, 3) self.assertAlmostRelativeEqual(potential, -G*sources.total_mass()/points.z, 3) instance.stop() - + def test11(self): print("Test that a source is not included when calculating gravity on itself.") number_of_sources = 100 mass, length, G = nbody_system.mass, nbody_system.length, nbody_system.G - sources = Particles(mass=numpy.ones(number_of_sources)|mass, x=0|length, y=0|length, z=0|length) - point = Particle(x=0|length, y=0|length, z=1.0|length) - + sources = Particles(mass=numpy.ones(number_of_sources) | mass, x=0 | length, y=0 | length, z=0 | length) + point = Particle(x=0 | length, y=0 | length, z=1.0 | length) + instance = self.new_fastkick_instance() instance.particles.add_particles(sources) - potential = instance.get_potential_at_point(0|length, point.x, point.y, point.z) - ax, ay, az = instance.get_gravity_at_point(0|length, point.x, point.y, point.z) + potential = instance.get_potential_at_point(0 | length, point.x, point.y, point.z) + ax, ay, az = instance.get_gravity_at_point(0 | length, point.x, point.y, point.z) self.assertAlmostEqual(ax, G * (0 | mass/length**2), 5) self.assertAlmostEqual(ay, G * (0 | mass/length**2), 5) self.assertAlmostRelativeEqual(az, -G*sources.total_mass()/point.z**2, 3) self.assertAlmostRelativeEqual(potential, -G*sources.total_mass()/point.z, 3) - + point.mass = 1e6 | mass instance.particles.add_particle(point) - potential = instance.get_potential_at_point(0|length, point.x, point.y, point.z) - ax, ay, az = instance.get_gravity_at_point(0|length, point.x, point.y, point.z) + potential = instance.get_potential_at_point(0 | length, point.x, point.y, point.z) + ax, ay, az = instance.get_gravity_at_point(0 | length, point.x, point.y, point.z) self.assertAlmostEqual(ax, G * (0 | mass/length**2), 5) self.assertAlmostEqual(ay, G * (0 | mass/length**2), 5) self.assertAlmostRelativeEqual(az, -G*sources.total_mass()/point.z**2, 3) self.assertAlmostRelativeEqual(potential, -G*sources.total_mass()/point.z, 3) instance.stop() - + def test12(self): print("Test FastKick potential energy") number_of_sources = 1000 numpy.random.seed(12345) plummer = new_plummer_model(number_of_sources) - + fastkick = self.new_fastkick_instance() fastkick.particles.add_particles(plummer) self.assertAlmostRelativeEqual(fastkick.potential_energy, plummer.potential_energy(G=nbody_system.G), 6) fastkick.cleanup_code() fastkick.stop() - + def test13(self): number_of_sources = 10 mass, length, G = nbody_system.mass, nbody_system.length, nbody_system.G sources = Particles( - mass=numpy.ones(number_of_sources)|mass, - x=0|length, - y=0|length, - z=0|length) - + mass=numpy.ones(number_of_sources) | mass, + x=0 | length, + y=0 | length, + z=0 | length) + instance = self.new_fastkick_instance() instance.particles.add_particles(sources) self.assertAlmostRelativeEqual(instance.particles.mass, 1 | mass) instance.particles.mass = 2 | mass self.assertAlmostRelativeEqual(instance.particles.mass, 2 | mass) + class TestFastKickGPU(TestFastKick): mode = "gpu" + def new_fastkick_instance(self, convert_nbody=None, number_of_workers=1, **kwargs): - return self.new_instance_of_an_optional_code(FastKick, convert_nbody, + return self.new_instance_of_an_optional_code(FastKick, convert_nbody, mode=self.mode, number_of_workers=number_of_workers, **kwargs) + class GravityCodeForTesting(object): - + def __init__(self): self.particles = Particles() self.model_time = quantities.zero - + def evolve_model(self, t_end): self.particles.position += self.particles.velocity * (t_end - self.model_time) self.model_time = t_end - + @property def potential_energy(self): G = nbody_system.G if self.particles.x.unit == nbody_system.length else constants.G return self.particles.potential_energy(G=G) - + @property def kinetic_energy(self): return self.particles.kinetic_energy() - + def new_gravity_code(particles): instance = GravityCodeForTesting() instance.particles.add_particles(particles) return instance - diff --git a/src/amuse/test/suite/codes_tests/test_fi.py b/src/amuse/test/suite/codes_tests/test_fi.py index d2578ac257..ee7d9a1d8e 100644 --- a/src/amuse/test/suite/codes_tests/test_fi.py +++ b/src/amuse/test/suite/codes_tests/test_fi.py @@ -13,72 +13,73 @@ from amuse.rfi import channel from amuse.ic.plummer import new_plummer_model + class TestFiInterface(TestWithMPI): def test1(self): - instance=FiInterface() + instance = FiInterface() instance.initialize_code() instance.stop() - + def test2(self): - instance=FiInterface() + instance = FiInterface() instance.initialize_code() - - for x,l in [('use_hydro',1),('radiate',0),('starform',0),('cosmo',1), - ('sqrttstp',0),('acc_tstp',1),('freetstp',0),('usequad',0), - ('directsum',0),('selfgrav',1),('fixthalo',0), - ('adaptive_eps',0),('gdgop',1),('smoothinput',0), - ('consph',1),('sphinit',1),('uentropy',1),('isotherm',0), - ('eps_is_h',1),('balsara',0),('mingaseps',0)]: - result,err=getattr(instance, 'get_'+x)() - self.assertEqual( (x,result),(x,l)) - err=getattr(instance, 'set_'+x)(1) - result,err=getattr(instance, 'get_'+x)() - self.assertEqual( (x,result),(x,1)) - err=getattr(instance, 'set_'+x)(0) - result,err=getattr(instance, 'get_'+x)() - self.assertEqual((x,result),(x,0)) - - for x,i in [ ('firstsnap',0),('stepout',5),('steplog',5),('max_tbin',4096), - ('minppbin',1),('targetnn',32),('verbosity',0),('nsmooth',64)]: - result,err=getattr(instance, 'get_'+x)() - self.assertEqual( (x,result),(x,i)) - err=getattr(instance, 'set_'+x)(12345) - result,err=getattr(instance, 'get_'+x)() - self.assertEqual((x,result),(x,12345)) - - for x,r in [ ('pboxsize',10000.),('unitl_in_kpc',1.),('unitm_in_msun',1.e9),('dtime',1.), - ('tstepcrit',1.),('tstpcr2',0.25),('freev',0.5),('freea',0.35),('freevexp',0.), - ('freeaexp',-1.),('bh_tol',0.5),('gdgtol',0.01),('nn_tol',0.1), - ('epsgas',0.005),('gamma',1.6666667),('alpha',0.5),('beta',1.0),('epssph',0.01), - ('courant',0.3),('removgas',0.25),('consthsm',0.2),('nsmtol',0.1), - ('graineff',0.05),('crionrate',3.6),('heat_par1',0.),('heat_par2',0.), - ('cool_par',1.),('optdepth',0.),('tcollfac',1.),('masscrit',1.e5), - ('sfeff',0.25),('tbubble',3.e7),('sne_eff',0.),('tsnbeg',3.e6), - ('rhomax',100.),('eps',0.)]: - result,err=getattr(instance, 'get_'+x)() - self.assertAlmostEqual(result,r,7) - err=getattr(instance, 'set_'+x)(0.) - result,err=getattr(instance, 'get_'+x)() - self.assertEqual(result,0.) - err=getattr(instance, 'set_'+x)(0.12345) - result,err=getattr(instance, 'get_'+x)() - self.assertAlmostEqual(result,0.12345,7) - - for x,s in [('halofile','none'),('feedback','fuv'),('sfmode','gerritsen'), - ('hupdatemethod','mass'),('sph_visc','sph')]: - result,err=getattr(instance, 'get_'+x)() - self.assertEqual((x,result),(x,s)) - err=getattr(instance, 'set_'+x)("123") - result,err=getattr(instance, 'get_'+x)() - self.assertEqual((x,result),(x,"123")) - + + for x, l in [('use_hydro', 1), ('radiate', 0), ('starform', 0), ('cosmo', 1), + ('sqrttstp', 0), ('acc_tstp', 1), ('freetstp', 0), ('usequad', 0), + ('directsum', 0), ('selfgrav', 1), ('fixthalo', 0), + ('adaptive_eps', 0), ('gdgop', 1), ('smoothinput', 0), + ('consph', 1), ('sphinit', 1), ('uentropy', 1), ('isotherm', 0), + ('eps_is_h', 1), ('balsara', 0), ('mingaseps', 0)]: + result, err = getattr(instance, 'get_'+x)() + self.assertEqual((x, result), (x, l)) + err = getattr(instance, 'set_'+x)(1) + result, err = getattr(instance, 'get_'+x)() + self.assertEqual((x, result), (x, 1)) + err = getattr(instance, 'set_'+x)(0) + result, err = getattr(instance, 'get_'+x)() + self.assertEqual((x, result), (x, 0)) + + for x, i in [('firstsnap', 0), ('stepout', 5), ('steplog', 5), ('max_tbin', 4096), + ('minppbin', 1), ('targetnn', 32), ('verbosity', 0), ('nsmooth', 64)]: + result, err = getattr(instance, 'get_'+x)() + self.assertEqual((x, result), (x, i)) + err = getattr(instance, 'set_'+x)(12345) + result, err = getattr(instance, 'get_'+x)() + self.assertEqual((x, result), (x, 12345)) + + for x, r in [('pboxsize', 10000.), ('unitl_in_kpc', 1.), ('unitm_in_msun', 1.e9), ('dtime', 1.), + ('tstepcrit', 1.), ('tstpcr2', 0.25), ('freev', 0.5), ('freea', 0.35), ('freevexp', 0.), + ('freeaexp', -1.), ('bh_tol', 0.5), ('gdgtol', 0.01), ('nn_tol', 0.1), + ('epsgas', 0.005), ('gamma', 1.6666667), ('alpha', 0.5), ('beta', 1.0), ('epssph', 0.01), + ('courant', 0.3), ('removgas', 0.25), ('consthsm', 0.2), ('nsmtol', 0.1), + ('graineff', 0.05), ('crionrate', 3.6), ('heat_par1', 0.), ('heat_par2', 0.), + ('cool_par', 1.), ('optdepth', 0.), ('tcollfac', 1.), ('masscrit', 1.e5), + ('sfeff', 0.25), ('tbubble', 3.e7), ('sne_eff', 0.), ('tsnbeg', 3.e6), + ('rhomax', 100.), ('eps', 0.)]: + result, err = getattr(instance, 'get_'+x)() + self.assertAlmostEqual(result, r, 7) + err = getattr(instance, 'set_'+x)(0.) + result, err = getattr(instance, 'get_'+x)() + self.assertEqual(result, 0.) + err = getattr(instance, 'set_'+x)(0.12345) + result, err = getattr(instance, 'get_'+x)() + self.assertAlmostEqual(result, 0.12345, 7) + + for x, s in [('halofile', 'none'), ('feedback', 'fuv'), ('sfmode', 'gerritsen'), + ('hupdatemethod', 'mass'), ('sph_visc', 'sph')]: + result, err = getattr(instance, 'get_'+x)() + self.assertEqual((x, result), (x, s)) + err = getattr(instance, 'set_'+x)("123") + result, err = getattr(instance, 'get_'+x)() + self.assertEqual((x, result), (x, "123")) + instance.stop() - + def test3(self): - instance=FiInterface() + instance = FiInterface() instance.initialize_code() - instance.commit_parameters() + instance.commit_parameters() instance.new_particle(11.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0) retrieved_state = instance.get_state(1) self.assertEqual(11.0, retrieved_state['mass']) @@ -87,9 +88,8 @@ def test3(self): instance.cleanup_code() instance.stop() - def test4(self): - instance=FiInterface() + instance = FiInterface() instance.initialize_code() instance.commit_parameters() instance.new_particle(11.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0) @@ -98,79 +98,79 @@ def test4(self): self.assertEqual(2.0, retrieved_state['time_step']) instance.cleanup_code() instance.stop() - + def test5(self): - instance=FiInterface() + instance = FiInterface() instance.initialize_code() instance.set_eps(0.001) instance.set_directsum(1) instance.commit_parameters() - instance.new_particle( - [1.0,1.0,1.0], - [0.0,0.0,0.0], - [1.0,0.0,-1.0], - [0.0,0.0,0.0], - [0.0,0.0,0.0], - [0.0,1.0,0.0], - [0.0,0.0,0.0], - [0.0,0.0,0.0] ) + instance.new_particle( + [1.0, 1.0, 1.0], + [0.0, 0.0, 0.0], + [1.0, 0.0, -1.0], + [0.0, 0.0, 0.0], + [0.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, 0.0], + [0.0, 0.0, 0.0]) instance.commit_particles() self.assertEqual(instance.get_number_of_particles()['number_of_particles'], 3) instance.synchronize_model() - Ep=instance.get_potential_energy()['potential_energy'] - Ek=instance.get_kinetic_energy()['kinetic_energy'] - - self.assertAlmostEqual( Ek, 0.5,10) - self.assertAlmostEqual( Ep, -2.5,10) + Ep = instance.get_potential_energy()['potential_energy'] + Ek = instance.get_kinetic_energy()['kinetic_energy'] + + self.assertAlmostEqual(Ek, 0.5, 10) + self.assertAlmostEqual(Ep, -2.5, 10) instance.delete_particle(2) instance.recommit_particles() instance.synchronize_model() - n=instance.get_number_of_particles()['number_of_particles'] - Ep=instance.get_potential_energy()['potential_energy'] - Ek=instance.get_kinetic_energy()['kinetic_energy'] - self.assertEqual( n, 2) - self.assertAlmostEqual( Ek, 0.,10) - self.assertAlmostEqual( Ep, -0.5,10) - + n = instance.get_number_of_particles()['number_of_particles'] + Ep = instance.get_potential_energy()['potential_energy'] + Ek = instance.get_kinetic_energy()['kinetic_energy'] + self.assertEqual(n, 2) + self.assertAlmostEqual(Ek, 0., 10) + self.assertAlmostEqual(Ep, -0.5, 10) + instance.cleanup_code() instance.stop() def test5a(self): - instance=FiInterface() - self.assertEqual(0,instance.initialize_code()) - self.assertEqual(0,instance.set_eps(0.001)) - self.assertEqual(0,instance.set_directsum(1)) - instance.new_particle( - [1.0,1.0], - [0.0,0.0], - [1.0,-1.0], - [0.0,0.0], - [0.0,0.0], - [0.0,0.0], - [0.0,0.0], - [0.0,0.0] ) - self.assertEqual(0,instance.commit_particles()) + instance = FiInterface() + self.assertEqual(0, instance.initialize_code()) + self.assertEqual(0, instance.set_eps(0.001)) + self.assertEqual(0, instance.set_directsum(1)) + instance.new_particle( + [1.0, 1.0], + [0.0, 0.0], + [1.0, -1.0], + [0.0, 0.0], + [0.0, 0.0], + [0.0, 0.0], + [0.0, 0.0], + [0.0, 0.0]) + self.assertEqual(0, instance.commit_particles()) self.assertEqual(0, instance.commit_parameters()) - self.assertAlmostEqual(-0.500 , instance.get_potential(1)['potential'], places=1) + self.assertAlmostEqual(-0.500, instance.get_potential(1)['potential'], places=1) print(instance.get_potential([1])) self.assertEqual(0, instance.cleanup_code()) instance.stop() - + def test6(self): print("Testing FiInterface get_hydro_state_at_point") number_sph_particles = 10000 length = 1.0 | units.kpc mass = 1.0e9 | units.MSun - + gas = new_uniform_spherical_particle_distribution(number_sph_particles, length, mass) mass = [1.0 / number_sph_particles] * number_sph_particles - h = [0.01] * number_sph_particles + h = [0.01] * number_sph_particles x, y, z = gas.x.value_in(units.kpc), gas.y.value_in(units.kpc), gas.z.value_in(units.kpc) vx, vy, vz = [[0.0] * number_sph_particles] * 3 u = [0.05] * number_sph_particles - indices = range(1,number_sph_particles+1) - - instance=FiInterface() + indices = range(1, number_sph_particles+1) + + instance = FiInterface() instance.initialize_code() instance.set_unitl_in_kpc(1.0) instance.set_unitm_in_msun(1.e9) @@ -178,13 +178,13 @@ def test6(self): instance.set_nsmtol(0.2) instance.set_uentropy(1) instance.commit_parameters() - instance.new_sph_particle(mass,x, y, z, vx, vy, vz, u, h) + instance.new_sph_particle(mass, x, y, z, vx, vy, vz, u, h) instance.commit_particles() instance.synchronize_model() h = instance.get_smoothing_length(indices)['h_smooth'] self.assertIsOfOrder((instance.get_nsmooth()['nsmooth']*1.0 / number_sph_particles)**(1.0/3), h) - + hydrostate = instance.get_hydro_state_at_point(0, 0, 0) density = 1.0 / (4.0/3.0 * numpy.pi * 1.0**3) self.assertAlmostEqual(hydrostate['rho'], density, places=3) @@ -192,17 +192,13 @@ def test6(self): self.assertAlmostEqual(hydrostate['rhovy'], 0, places=3) self.assertAlmostEqual(hydrostate['rhovz'], 0, places=3) self.assertAlmostEqual(hydrostate['rhoe'], density*u[0], places=3) - - instance.stop() - - - + instance.stop() def test7(self): - instance=FiInterface(mode=FiInterface.MODE_PERIODIC_BOUNDARIES) + instance = FiInterface(mode=FiInterface.MODE_PERIODIC_BOUNDARIES) instance.initialize_code() - #instance.set_periodic(1) + # instance.set_periodic(1) instance.set_use_hydro(0) instance.set_selfgrav(0) print(instance.get_pboxsize()) @@ -210,82 +206,81 @@ def test7(self): print(instance.get_pboxsize()) instance.set_dtime(0.1) instance.commit_parameters() - ids,err=instance.new_particle( - [1.0,1.0,1.0], - [0.5,0.0,0.0], - [0.0,-0.5,0.0], - [0.0,0.0,0.5], - [1.0,0.0,0.0], - [0.0,-1.0,0.0], - [0.0,0.0,1.0]) + ids, err = instance.new_particle( + [1.0, 1.0, 1.0], + [0.5, 0.0, 0.0], + [0.0, -0.5, 0.0], + [0.0, 0.0, 0.5], + [1.0, 0.0, 0.0], + [0.0, -1.0, 0.0], + [0.0, 0.0, 1.0]) instance.commit_particles() - + instance.evolve_model(0.1) - m,x,y,z,vx,vy,vz,r,err=instance.get_state(ids) - self.assertAlmostEqual(x, [0.6,0.,0.], places=7) - self.assertAlmostEqual(y, [0.,-0.6,0.], places=7) - self.assertAlmostEqual(z, [0.,0.,0.6], places=7) + m, x, y, z, vx, vy, vz, r, err = instance.get_state(ids) + self.assertAlmostEqual(x, [0.6, 0., 0.], places=7) + self.assertAlmostEqual(y, [0., -0.6, 0.], places=7) + self.assertAlmostEqual(z, [0., 0., 0.6], places=7) instance.evolve_model(1.0) - m,x,y,z,vx,vy,vz,r,err=instance.get_state(ids) - self.assertAlmostEqual(x, [-0.5,0.,0.], places=7) - self.assertAlmostEqual(y, [0.,0.5,0.], places=7) - self.assertAlmostEqual(z, [0.,0.,-0.5], places=7) + m, x, y, z, vx, vy, vz, r, err = instance.get_state(ids) + self.assertAlmostEqual(x, [-0.5, 0., 0.], places=7) + self.assertAlmostEqual(y, [0., 0.5, 0.], places=7) + self.assertAlmostEqual(z, [0., 0., -0.5], places=7) instance.cleanup_code() instance.stop() - - + def test8(self): - instance=FiInterface(redirection="none") + instance = FiInterface(redirection="none") instance.initialize_code() instance.set_use_hydro(0) instance.set_selfgrav(1) instance.set_pboxsize(1.0) instance.set_dtime(0.2) instance.commit_parameters() - index,err=instance.new_sph_particle( - 0.1, #mass - 0.5, #x,y,z + index, err = instance.new_sph_particle( + 0.1, # mass + 0.5, # x,y,z 0.0, 0.0, - 1.0, #vx,vy,vz + 1.0, # vx,vy,vz 0.0, 0.0, 0.0 ) - index2,err=instance.new_sph_particle( - 0.001, #mass - 0.1, #x,y,z + index2, err = instance.new_sph_particle( + 0.001, # mass + 0.1, # x,y,z 0.0, 0.0, - 1.0, #vx,vy,vz + 1.0, # vx,vy,vz 0.0, 0.0, 0.0 ) instance.commit_particles() instance.evolve_model(0.1) - m,x,y,z,vx,vy,vz,r,err=instance.get_state(index) + m, x, y, z, vx, vy, vz, r, err = instance.get_state(index) self.assertAlmostRelativeEquals(x, 0.5) nremoved, error = instance.get_number_of_sph_particles_removed() - self.assertEqual(error,0) - self.assertEqual(nremoved,0) + self.assertEqual(error, 0) + self.assertEqual(nremoved, 0) instance.evolve_model(0.15) nremoved, error = instance.get_number_of_sph_particles_removed() - self.assertEqual(error,0) - self.assertEqual(nremoved,1) + self.assertEqual(error, 0) + self.assertEqual(nremoved, 1) idremoved, error = instance.get_id_of_removed_sph_particle(0) - self.assertEqual(idremoved,index) - - + self.assertEqual(idremoved, index) + + class TestEvrard(TestWithMPI): def xtest0(self): - evrard=MakeEvrardTest(1000) - mass,x,y,z,vx,vy,vz,u=evrard.new_model() - smooth=numpy.zeros_like(mass) + evrard = MakeEvrardTest(1000) + mass, x, y, z, vx, vy, vz, u = evrard.new_model() + smooth = numpy.zeros_like(mass) nb = FiInterface() nb.initialize_code() - + nb.set_stepout(99999) nb.set_steplog(99999) nb.set_use_hydro(1) @@ -295,36 +290,37 @@ def xtest0(self): nb.set_uentropy(1) nb.set_verbosity(0) nb.commit_parameters() - - ids,error = nb.new_sph_particle(mass,smooth,x,y,z,vx,vy,vz,u) - if [x for x in error if x != 0] != []: raise Exception - + + ids, error = nb.new_sph_particle(mass, smooth, x, y, z, vx, vy, vz, u) + if [x for x in error if x != 0] != []: + raise Exception + nb.initialize_particles(0.0) nb.synchronize_model() - Ek,ret=nb.get_kinetic_energy() - Ep,ret=nb.get_potential_energy() - Eth,ret=nb.get_thermal_energy() - self.assertAlmostEqual( Ek, 0.,3) - self.assertAlmostEqual( Ep, -0.6611,3) - self.assertAlmostEqual( Eth, 0.05,3) - + Ek, ret = nb.get_kinetic_energy() + Ep, ret = nb.get_potential_energy() + Eth, ret = nb.get_thermal_energy() + self.assertAlmostEqual(Ek, 0., 3) + self.assertAlmostEqual(Ep, -0.6611, 3) + self.assertAlmostEqual(Eth, 0.05, 3) + nb.evolve_model(0.5) nb.synchronize_model() - Ek,ret=nb.get_kinetic_energy() - Ep,ret=nb.get_potential_energy() - Eth,ret=nb.get_thermal_energy() - self.assertAlmostEqual( Ek, 0.129577,3) - self.assertAlmostEqual( Ep, -0.831976,3) - self.assertAlmostEqual( Eth,0.08567999,3) - + Ek, ret = nb.get_kinetic_energy() + Ep, ret = nb.get_potential_energy() + Eth, ret = nb.get_thermal_energy() + self.assertAlmostEqual(Ek, 0.129577, 3) + self.assertAlmostEqual(Ep, -0.831976, 3) + self.assertAlmostEqual(Eth, 0.08567999, 3) + del evrard nb.stop() - + class TestFi(TestWithMPI): def test0(self): - instance=Fi(nbody_system.nbody_to_si(1.0e9 | units.MSun, 1.0 | units.kpc)) + instance = Fi(nbody_system.nbody_to_si(1.0e9 | units.MSun, 1.0 | units.kpc)) self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') instance.initialize_code() self.assertEqual(instance.get_name_of_current_state(), 'INITIALIZED') @@ -334,7 +330,7 @@ def test0(self): instance.commit_particles() self.assertEqual(instance.parameters.timestep, 0.5 | units.day) instance.stop() - + def test1(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) instance = Fi(convert_nbody) @@ -343,237 +339,236 @@ def test1(self): instance.parameters.timestep = 0.5 | units.day self.assertEqual(instance.parameters.timestep, 0.5 | units.day) instance.commit_parameters() - + stars = datamodel.Particles(2) - + sun = stars[0] sun.mass = units.MSun(1.0) - sun.position = [0.0,0.0,0.0] | units.m - sun.velocity = [0.0,0.0,0.0] | units.ms + sun.position = [0.0, 0.0, 0.0] | units.m + sun.velocity = [0.0, 0.0, 0.0] | units.ms sun.radius = units.RSun(1.0) - + earth = stars[1] earth.mass = units.kg(5.9736e24) - earth.radius = units.km(6371) + earth.radius = units.km(6371) earth.position = [149.5e6, 0.0, 0.0] | units.km earth.velocity = [0.0, 29800, 0.0] | units.ms - + instance.particles.add_particles(stars) self.assertEqual(instance.parameters.timestep, 0.5 | units.day) - + postion_at_start = earth.position.x - + instance.evolve_model(365.0 | units.day) - + instance.particles.copy_values_of_all_attributes_to(stars) - + postion_after_full_rotation = earth.position.x - + self.assertAlmostRelativeEqual(postion_at_start, postion_after_full_rotation, 4) instance.evolve_model(365.0 + (365.0 / 2) | units.day) - + instance.particles.copy_values_of_all_attributes_to(stars) - + postion_after_half_a_rotation = earth.position.x - + instance.evolve_model(365.0 + (365.0 / 2) | units.day) - + instance.particles.copy_values_of_all_attributes_to(stars) - + postion_after_half_a_rotation = earth.position.x self.assertAlmostRelativeEqual(-postion_at_start, postion_after_half_a_rotation, 3) - - instance.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) - + + instance.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) + instance.particles.copy_values_of_all_attributes_to(stars) - + postion_after_half_a_rotation = earth.position.y - + self.assertAlmostRelativeEqual(-postion_at_start, postion_after_half_a_rotation, 4) - + instance.cleanup_code() instance.stop() - + def test2(self): print("Test 2: testing Fi data directory") convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) instance = Fi(convert_nbody) instance.initialize_code() self.assertTrue('fi/data/input/' in instance.legacy_interface.get_fi_data_directory()['fi_data_directory']) - self.assertEqual(instance.legacy_interface.get_fi_data_directory()['fi_data_directory'], + self.assertEqual(instance.legacy_interface.get_fi_data_directory()['fi_data_directory'], instance.get_data_directory()+'/') - + self.assertEqual(False, instance.parameters.radiation_flag) instance.parameters.radiation_flag = True self.assertEqual(True, instance.parameters.radiation_flag) - + self.assertEqual(False, instance.parameters.star_formation_flag) instance.parameters.star_formation_flag = True self.assertEqual(True, instance.parameters.star_formation_flag) - + instance.commit_parameters() stars = datamodel.Particles(2) stars.mass = [1.0, 3.0e-6] | units.MSun - stars.position = [[0.0,0.0,0.0], [1.0,0.0,0.0]] | units.AU - stars.velocity = [[0.0,0.0,0.0], [0.0,29.8,0.0]] | units.km / units.s + stars.position = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]] | units.AU + stars.velocity = [[0.0, 0.0, 0.0], [0.0, 29.8, 0.0]] | units.km / units.s stars.radius = [1.0, 0.01] | units.RSun - + instance.particles.add_particles(stars) instance.evolve_model(1.0 | nbody_system.time) - + instance.cleanup_code() instance.stop() - + def test3(self): print("Test 3: testing Fi boolean parameters") instance = Fi(nbody_system.nbody_to_si(1.0e9 | units.MSun, 1.0 | units.kpc)) instance.initialize_code() - - for bool_par in ['radiation_flag','star_formation_flag', - 'square_root_timestep_flag','freeform_timestep_flag','quadrupole_moments_flag', - 'direct_sum_flag','fixed_halo_flag','adaptive_smoothing_flag','smooth_input_flag', - 'isothermal_flag','balsara_flag','enforce_min_sph_grav_softening_flag']: + + for bool_par in ['radiation_flag', 'star_formation_flag', + 'square_root_timestep_flag', 'freeform_timestep_flag', 'quadrupole_moments_flag', + 'direct_sum_flag', 'fixed_halo_flag', 'adaptive_smoothing_flag', 'smooth_input_flag', + 'isothermal_flag', 'balsara_flag', 'enforce_min_sph_grav_softening_flag']: self.assertEqual(False, getattr(instance.parameters, bool_par)) setattr(instance.parameters, bool_par, True) self.assertEqual(True, getattr(instance.parameters, bool_par)) - - for bool_par in ['acc_timestep_flag','self_gravity_flag','gadget_cell_opening_flag', - 'use_hydro_flag','conservative_sph_flag','sph_dens_init_flag', - 'integrate_entropy_flag','eps_is_h_flag']: + + for bool_par in ['acc_timestep_flag', 'self_gravity_flag', 'gadget_cell_opening_flag', + 'use_hydro_flag', 'conservative_sph_flag', 'sph_dens_init_flag', + 'integrate_entropy_flag', 'eps_is_h_flag']: self.assertEqual(True, getattr(instance.parameters, bool_par)) setattr(instance.parameters, bool_par, False) self.assertEqual(False, getattr(instance.parameters, bool_par)) - + self.assertEqual(instance.parameters.periodic_boundaries_flag, False) - + instance.cleanup_code() instance.stop() - + def test4(self): print("Test 4: testing Fi integer parameters") instance = Fi(nbody_system.nbody_to_si(1.0e9 | units.MSun, 1.0 | units.kpc)) instance.initialize_code() - - for int_par, value in [('first_snapshot',0),('output_interval',5),('log_interval',5), - ('maximum_time_bin',4096),('minimum_part_per_bin',1),('targetnn',32), - ('verbosity',0),('n_smooth',64)]: - self.assertEqual(value, getattr(instance.parameters,int_par)) + + for int_par, value in [('first_snapshot', 0), ('output_interval', 5), ('log_interval', 5), + ('maximum_time_bin', 4096), ('minimum_part_per_bin', 1), ('targetnn', 32), + ('verbosity', 0), ('n_smooth', 64)]: + self.assertEqual(value, getattr(instance.parameters, int_par)) setattr(instance.parameters, int_par, 1) - self.assertEqual(1, getattr(instance.parameters,int_par)) - + self.assertEqual(1, getattr(instance.parameters, int_par)) + instance.cleanup_code() instance.stop() - + def test5(self): print("Test 5: testing Fi double precision parameters") - conv=nbody_system.nbody_to_si(1.0e9 | units.MSun, 1.0 | units.kpc) + conv = nbody_system.nbody_to_si(1.0e9 | units.MSun, 1.0 | units.kpc) instance = Fi(conv) instance.initialize_code() - - par_names=['epsilon_squared','timestep','periodic_box_size','code_mass_unit','code_length_unit', - 'sqrt_timestep_crit_constant','acc_timestep_crit_constant','free_timestep_crit_constant_v', - 'free_timestep_crit_constant_a','free_timestep_crit_constant_vexp', - 'free_timestep_crit_constant_aexp','opening_angle','gadget_cell_opening_constant', - 'nn_tol','gas_epsilon','gamma','artificial_viscosity_alpha','beta','sph_artificial_viscosity_eps','courant', - 'min_gas_part_mass','sph_h_const','n_smooth_tol','grain_heat_eff','zeta_cr_ion_rate', - 'heat_par1','heat_par2','cool_par','optical_depth','star_form_delay_fac','star_form_mass_crit', - 'star_form_eff','supernova_duration','supernova_eff','t_supernova_start','max_density'] - defaults=[0.0 | nbody_system.length * nbody_system.length, 1.0 | nbody_system.time, 10000.0 | nbody_system.length, - 1.0e9 | units.MSun, 1.0 | units.kpc, 1.0, 0.25, 0.5, 0.35, - 0.0, -1.0, 0.5, 0.01, 0.1, 0.005 | nbody_system.length, 1.6666667, 0.5, 1.0, 0.01, 0.3, - 0.25, 0.2 | nbody_system.length, 0.1, 0.05, 3.6 | 1.8e-17 * units.s**-1, 0.0, 0.0, 1.0, + + par_names = ['epsilon_squared', 'timestep', 'periodic_box_size', 'code_mass_unit', 'code_length_unit', + 'sqrt_timestep_crit_constant', 'acc_timestep_crit_constant', 'free_timestep_crit_constant_v', + 'free_timestep_crit_constant_a', 'free_timestep_crit_constant_vexp', + 'free_timestep_crit_constant_aexp', 'opening_angle', 'gadget_cell_opening_constant', + 'nn_tol', 'gas_epsilon', 'gamma', 'artificial_viscosity_alpha', 'beta', 'sph_artificial_viscosity_eps', 'courant', + 'min_gas_part_mass', 'sph_h_const', 'n_smooth_tol', 'grain_heat_eff', 'zeta_cr_ion_rate', + 'heat_par1', 'heat_par2', 'cool_par', 'optical_depth', 'star_form_delay_fac', 'star_form_mass_crit', + 'star_form_eff', 'supernova_duration', 'supernova_eff', 't_supernova_start', 'max_density'] + defaults = [0.0 | nbody_system.length * nbody_system.length, 1.0 | nbody_system.time, 10000.0 | nbody_system.length, + 1.0e9 | units.MSun, 1.0 | units.kpc, 1.0, 0.25, 0.5, 0.35, + 0.0, -1.0, 0.5, 0.01, 0.1, 0.005 | nbody_system.length, 1.6666667, 0.5, 1.0, 0.01, 0.3, + 0.25, 0.2 | nbody_system.length, 0.1, 0.05, 3.6 | 1.8e-17 * units.s**-1, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0e5 | units.MSun, 0.25, 3.0e7 | units.Myr, 0.0, 3.e6 | units.Myr, conv.to_si(100.0 | nbody_system.density)] - defaults = [instance.unit_converter.to_si(val) if not isinstance(val,float) and nbody_system.is_nbody_unit(val.unit) else val for val in defaults] + defaults = [instance.unit_converter.to_si(val) if not isinstance(val, float) and nbody_system.is_nbody_unit(val.unit) else val for val in defaults] for double_par, value in zip(par_names, defaults): - self.assertAlmostRelativeEquals(getattr(instance.parameters,double_par), value, 7) - setattr(instance.parameters,double_par,2 * value) - self.assertAlmostRelativeEquals(getattr(instance.parameters,double_par), 2*value, 7) + self.assertAlmostRelativeEquals(getattr(instance.parameters, double_par), value, 7) + setattr(instance.parameters, double_par, 2 * value) + self.assertAlmostRelativeEquals(getattr(instance.parameters, double_par), 2*value, 7) instance.cleanup_code() instance.stop() - + def test6(self): print("Test 6: testing Fi string parameters") instance = Fi(nbody_system.nbody_to_si(1.0e9 | units.MSun, 1.0 | units.kpc)) instance.initialize_code() - - par_names=['halofile','feedback','star_formation_mode','h_update_method','sph_viscosity','fi_data_directory'] - defaults=['none','fuv','gerritsen','mass','sph',instance.get_data_directory()+'/'] - new_values=['bct_02_10.halo','pres','nieuw','test','sphv','test'] + + par_names = ['halofile', 'feedback', 'star_formation_mode', 'h_update_method', 'sph_viscosity', 'fi_data_directory'] + defaults = ['none', 'fuv', 'gerritsen', 'mass', 'sph', instance.get_data_directory()+'/'] + new_values = ['bct_02_10.halo', 'pres', 'nieuw', 'test', 'sphv', 'test'] for string_par, value, new_value in zip(par_names, defaults, new_values): - print(instance.get_halofile(), getattr(instance.parameters, string_par), end=' ') + print(instance.get_halofile(), getattr(instance.parameters, string_par), end=' ') self.assertEqual(getattr(instance.parameters, string_par), value) setattr(instance.parameters, string_par, new_value) self.assertEqual(getattr(instance.parameters, string_par), new_value) instance.cleanup_code() instance.stop() - + def test7(self): print("Test 7: testing Fi SPH particles") target_number_of_particles = 1000 - gas = new_evrard_gas_sphere(target_number_of_particles, do_scale=True, seed = 1234) + gas = new_evrard_gas_sphere(target_number_of_particles, do_scale=True, seed=1234) gas.h_smooth = 0.0 | nbody_system.length - + convert_nbody = nbody_system.nbody_to_si(1.0e9 | units.MSun, 1.0 | units.kpc) - instance = Fi(convert_nbody,redirection="none") + instance = Fi(convert_nbody, redirection="none") instance.initialize_code() instance.parameters.timestep = 0.025 | nbody_system.time instance.parameters.integrate_entropy_flag = True instance.gas_particles.add_particles(gas) - + self.assertAlmostEqual(convert_nbody.to_nbody(instance.kinetic_energy), 0.00 | nbody_system.energy) self.assertAlmostEqual(convert_nbody.to_nbody(instance.potential_energy), -0.494 | nbody_system.energy, 2) self.assertAlmostEqual(convert_nbody.to_nbody(instance.thermal_energy), 0.05 | nbody_system.energy) self.assertAlmostEqual(convert_nbody.to_nbody(instance.total_energy), -0.444 | nbody_system.energy, 2) - + instance.evolve_model(10.437 | units.Myr) instance.synchronize_model() self.assertAlmostEqual(convert_nbody.to_nbody(instance.kinetic_energy), 0.0566 | nbody_system.energy, 3) self.assertAlmostEqual(convert_nbody.to_nbody(instance.potential_energy), -0.5661 | nbody_system.energy, 3) self.assertAlmostEqual(convert_nbody.to_nbody(instance.thermal_energy), 0.0635 | nbody_system.energy, 3) self.assertAlmostEqual(convert_nbody.to_nbody(instance.total_energy), -0.444 | nbody_system.energy, 2) - + instance.cleanup_code() instance.stop() - + def test8(self): print("Test 8: testing Fi dark matter + SPH particles") target_number_of_particles = 100 - gas = new_evrard_gas_sphere(target_number_of_particles, do_scale=True, seed = 1234) + gas = new_evrard_gas_sphere(target_number_of_particles, do_scale=True, seed=1234) gas.h_smooth = 0.0 | nbody_system.length - + dark = datamodel.Particles(2) dark.mass = [1.0, 3.0e-6] | units.MSun - dark.position = [[0.0,0.0,0.0], [1.0,0.0,0.0]] | units.AU - dark.velocity = [[0.0,0.0,0.0], [0.0,29.8,0.0]] | units.km / units.s + dark.position = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]] | units.AU + dark.velocity = [[0.0, 0.0, 0.0], [0.0, 29.8, 0.0]] | units.km / units.s dark.radius = [10.0, 0.1] | units.RSun - + convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) instance = Fi(convert_nbody) - instance.parameters.eps_is_h_flag=False - instance.parameters.gas_epsilon=0.4 | units.AU - instance.parameters.timestep=0.001 | units.yr + instance.parameters.eps_is_h_flag = False + instance.parameters.gas_epsilon = 0.4 | units.AU + instance.parameters.timestep = 0.001 | units.yr # instance.parameters.gadget_cell_opening_constant=0.001 instance.dm_particles.add_particles(dark) instance.gas_particles.add_particles(gas) - + print(convert_nbody.to_nbody(instance.kinetic_energy)) print(convert_nbody.to_nbody(instance.potential_energy)) print(convert_nbody.to_nbody(instance.thermal_energy)) print(convert_nbody.to_nbody(instance.total_energy)) - - radius=instance.dm_particles.radius + + radius = instance.dm_particles.radius print(instance.gas_particles.radius[0:10].in_(units.AU)) - self.assertEqual(dark[0].radius,radius[0]) - self.assertEqual(dark[1].radius,radius[1]) - - - self.assertAlmostEqual(convert_nbody.to_nbody(instance.kinetic_energy), + self.assertEqual(dark[0].radius, radius[0]) + self.assertEqual(dark[1].radius, radius[1]) + + self.assertAlmostEqual(convert_nbody.to_nbody(instance.kinetic_energy), convert_nbody.to_nbody(dark.kinetic_energy()), 3) self.assertAlmostEqual(convert_nbody.to_nbody(instance.potential_energy), -1.8656 | nbody_system.energy, 3) - self.assertAlmostEqual(convert_nbody.to_nbody(instance.thermal_energy), 0.0500 | nbody_system.energy,3) + self.assertAlmostEqual(convert_nbody.to_nbody(instance.thermal_energy), 0.0500 | nbody_system.energy, 3) self.assertAlmostEqual(convert_nbody.to_nbody(instance.total_energy), -1.8156 | nbody_system.energy, 3) - - instance.evolve_model(1.| units.yr) + + instance.evolve_model(1. | units.yr) print(instance.gas_particles.radius[0:10].in_(units.AU)) self.assertAlmostRelativeEqual(convert_nbody.to_nbody(instance.kinetic_energy), 0.02507 | nbody_system.energy, 3) @@ -582,51 +577,51 @@ def test8(self): self.assertAlmostRelativeEqual(convert_nbody.to_nbody(instance.total_energy), -1.8156 | nbody_system.energy, 3) print(convert_nbody.to_nbody(instance.total_energy)) - + instance.cleanup_code() instance.stop() - + def test9(self): print("Test 9: testing Fi dark matter + SPH + star particles") target_number_of_particles = 100 - gas = new_evrard_gas_sphere(target_number_of_particles, do_scale=True, seed = 1234) + gas = new_evrard_gas_sphere(target_number_of_particles, do_scale=True, seed=1234) gas.h_smooth = 0.0 | nbody_system.length - + dark = datamodel.Particles(2) dark.mass = [0.4, 0.4] | nbody_system.mass - dark.position = [[0.0,0.0,0.0], [1.0,0.0,0.0]] | units.kpc - dark.velocity = [[100.0,100.0,100.0], [1.0,1.0,1.0]] | units.km / units.s + dark.position = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]] | units.kpc + dark.velocity = [[100.0, 100.0, 100.0], [1.0, 1.0, 1.0]] | units.km / units.s dark.radius = [0.0, 0.0] | units.RSun - + star = datamodel.Particles(2) star.mass = [0.02, 0.02] | nbody_system.mass - star.position = [[0.1,0.2,0.3], [0.4,0.5,0.6]] | units.kpc - star.velocity = [[-300.0,-200.0,-100.0], [-6.0,-5.0,-4.0]] | units.km / units.s + star.position = [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]] | units.kpc + star.velocity = [[-300.0, -200.0, -100.0], [-6.0, -5.0, -4.0]] | units.km / units.s star.radius = [0.0, 0.0] | units.RSun star.tform = [1000.0, 1000.0] | units.Myr - + convert_nbody = nbody_system.nbody_to_si(1.0e9 | units.MSun, 1.0 | units.kpc) instance = Fi(convert_nbody) instance.initialize_code() instance.parameters.verbosity = 0 - instance.parameters.timestep=0.05 | units.Myr - instance.parameters.eps_is_h_flag=False - instance.parameters.gas_epsilon=0.4 | units.kpc + instance.parameters.timestep = 0.05 | units.Myr + instance.parameters.eps_is_h_flag = False + instance.parameters.gas_epsilon = 0.4 | units.kpc instance.dm_particles.add_particles(dark) instance.star_particles.add_particles(star) instance.gas_particles.add_particles(gas) - + print(convert_nbody.to_nbody(instance.kinetic_energy)) print(convert_nbody.to_nbody(instance.potential_energy)) print(convert_nbody.to_nbody(instance.thermal_energy)) print(convert_nbody.to_nbody(instance.total_energy)) - print(convert_nbody.to_nbody( (instance.dm_particles|instance.star_particles|instance.gas_particles).potential_energy(smoothing_length_squared = instance.parameters.epsilon_squared))) + print(convert_nbody.to_nbody((instance.dm_particles | instance.star_particles | instance.gas_particles).potential_energy(smoothing_length_squared=instance.parameters.epsilon_squared))) self.assertAlmostRelativeEqual(convert_nbody.to_nbody(instance.kinetic_energy), 1.7204 | nbody_system.energy, 3) self.assertAlmostRelativeEqual(convert_nbody.to_nbody(instance.potential_energy), -1.3096 | nbody_system.energy, 3) self.assertAlmostRelativeEqual(convert_nbody.to_nbody(instance.thermal_energy), 0.0500 | nbody_system.energy) self.assertAlmostRelativeEqual(convert_nbody.to_nbody(instance.total_energy), 0.461 | nbody_system.energy, 3) - + instance.evolve_model(100*instance.parameters.timestep) print(convert_nbody.to_nbody(instance.kinetic_energy)) print(convert_nbody.to_nbody(instance.potential_energy)) @@ -636,61 +631,61 @@ def test9(self): self.assertAlmostRelativeEqual(convert_nbody.to_nbody(instance.potential_energy), -1.277 | nbody_system.energy, 3) self.assertAlmostRelativeEqual(convert_nbody.to_nbody(instance.thermal_energy), 0.05526 | nbody_system.energy, 3) self.assertAlmostRelativeEqual(convert_nbody.to_nbody(instance.total_energy), 0.461 | nbody_system.energy, 3) - + instance.cleanup_code() instance.stop() - + def test10(self): print("Test 10: testing Fi star particles") stars = datamodel.Particles(2) stars.mass = [1.0, 3.00e-6] | units.MSun - stars.position = [[0.0,0.0,0.0], [1.0,0.0,0.0]] | units.AU - stars.velocity = [[0.0,0.0,0.0], [0.0,29.8,0.0]] | units.km / units.s - stars.radius = [1.0, 1.0] | units.RSun # results are nonsense if not (r1 == r2)... ? + stars.position = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]] | units.AU + stars.velocity = [[0.0, 0.0, 0.0], [0.0, 29.8, 0.0]] | units.km / units.s + stars.radius = [1.0, 1.0] | units.RSun # results are nonsense if not (r1 == r2)... ? stars.tform = [-10.0, -50.0] | units.Myr - - instance = Fi(nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU))#, debugger='xterm') + + instance = Fi(nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU)) # , debugger='xterm') instance.initialize_code() instance.parameters.timestep = 0.5 | units.day instance.commit_parameters() instance.star_particles.add_particles(stars) self.assertAlmostEqual(instance.star_particles.tform, [-10.0, -50.0] | units.Myr) instance.star_particles.tform = [-100.0, -500.0] | units.Myr - + instance.synchronize_model() self.assertAlmostEqual(instance.star_particles.tform, [-100.0, -500.0] | units.Myr) - self.assertAlmostEqual(instance.kinetic_energy, 2.6493e+33|units.J, 3, in_units=1e+33*units.J) - self.assertAlmostEqual(instance.star_particles.kinetic_energy(), 2.6493e+33|units.J, 3, in_units=1e+33*units.J) + self.assertAlmostEqual(instance.kinetic_energy, 2.6493e+33 | units.J, 3, in_units=1e+33*units.J) + self.assertAlmostEqual(instance.star_particles.kinetic_energy(), 2.6493e+33 | units.J, 3, in_units=1e+33*units.J) instance.evolve_model(0.5 | units.yr) - self.assertAlmostEqual(instance.star_particles[1].x, -1.0 | units.AU,2) + self.assertAlmostEqual(instance.star_particles[1].x, -1.0 | units.AU, 2) instance.evolve_model(1.0 | units.yr) - self.assertAlmostEqual(instance.star_particles[1].x, 1.0 | units.AU,3) - self.assertAlmostEqual(instance.kinetic_energy, 2.6493e+33|units.J, 3, in_units=1e+33*units.J) - + self.assertAlmostEqual(instance.star_particles[1].x, 1.0 | units.AU, 3) + self.assertAlmostEqual(instance.kinetic_energy, 2.6493e+33 | units.J, 3, in_units=1e+33*units.J) + instance.cleanup_code() instance.stop() - + def test11(self): print("Test 11: testing Fi (dm+sph+star) particles Superset") target_number_of_particles = 100 - gas = new_evrard_gas_sphere(target_number_of_particles, do_scale=True, seed = 1234) + gas = new_evrard_gas_sphere(target_number_of_particles, do_scale=True, seed=1234) gas.h_smooth = 0.0 | nbody_system.length number_sph_particles = len(gas) - + dark = datamodel.Particles(2) dark.mass = [0.4, 0.4] | nbody_system.mass - dark.position = [[0.0,0.0,0.0], [1.0,0.0,0.0]] | units.kpc - dark.velocity = [[100.0,100.0,100.0], [1.0,1.0,1.0]] | units.km / units.s + dark.position = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]] | units.kpc + dark.velocity = [[100.0, 100.0, 100.0], [1.0, 1.0, 1.0]] | units.km / units.s dark.radius = [0.0, 0.0] | units.RSun - + star = datamodel.Particles(2) star.mass = [0.02, 0.02] | nbody_system.mass - star.position = [[0.1,0.2,0.3], [0.4,0.5,0.6]] | units.kpc - star.velocity = [[-300.0,-200.0,-100.0], [-6.0,-5.0,-4.0]] | units.km / units.s + star.position = [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]] | units.kpc + star.velocity = [[-300.0, -200.0, -100.0], [-6.0, -5.0, -4.0]] | units.km / units.s star.radius = [0.0, 0.0] | units.RSun star.tform = [1000.0, 1000.0] | units.Myr - + convert_nbody = nbody_system.nbody_to_si(1.0e9 | units.MSun, 1.0 | units.kpc) instance = Fi(convert_nbody) instance.initialize_code() @@ -700,15 +695,15 @@ def test11(self): instance.star_particles.add_particles(star) instance.gas_particles.add_particles(gas) self.assertEqual(number_sph_particles+4, len(instance.particles)) - + print("The 'particles' superset can still be used as standard GD 'particles' set.") default = datamodel.Particles(2) default.mass = [0.4, 0.4] | nbody_system.mass - default.position = [[0.5,-0.5,0.04], [1.5,0.5,0.08]] | units.kpc - default.velocity = [[10.0,10.0,10.0], [10.0,10.0,10.0]] | units.km / units.s + default.position = [[0.5, -0.5, 0.04], [1.5, 0.5, 0.08]] | units.kpc + default.velocity = [[10.0, 10.0, 10.0], [10.0, 10.0, 10.0]] | units.km / units.s default.radius = [0.0, 0.0] | units.RSun instance.particles.add_particles(default) - + self.assertEqual(number_sph_particles+6, len(instance.particles)) print("'>>> print instance.particles' only prints those particle attributes the subsets have in common.") string_produced_by_print = instance.particles.__str__() @@ -716,9 +711,9 @@ def test11(self): self.assertTrue("vx" in string_produced_by_print) self.assertTrue("radius" in string_produced_by_print) self.assertFalse("tform" in string_produced_by_print) - + instance.synchronize_model() - self.assertAlmostRelativeEqual(instance.particles.kinetic_energy(), + self.assertAlmostRelativeEqual(instance.particles.kinetic_energy(), instance.dm_particles.kinetic_energy() + instance.star_particles.kinetic_energy() + instance.gas_particles.kinetic_energy()) @@ -726,21 +721,21 @@ def test11(self): instance.evolve_model(1.0 | units.yr) instance.synchronize_model() self.assertAlmostRelativeEqual(instance.particles.kinetic_energy(), instance.kinetic_energy, -1) - + instance.cleanup_code() instance.stop() - + def test12(self): print("Testing Fi states") target_number_of_particles = 100 - gas = new_evrard_gas_sphere(target_number_of_particles, do_scale=True, seed = 1234) + gas = new_evrard_gas_sphere(target_number_of_particles, do_scale=True, seed=1234) gas.h_smooth = 0.0 | nbody_system.length dark = datamodel.Particles(2) dark.mass = [0.4, 0.4] | nbody_system.mass dark.position = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]] | nbody_system.length dark.velocity = [[0.1, 0.1, 0.1], [1.0, 1.0, 1.0]] | nbody_system.speed dark.radius = 0.0 | nbody_system.length - + print("First do everything manually:") convert_nbody = nbody_system.nbody_to_si(1.0e9 | units.MSun, 1.0 | units.kpc) instance = Fi(convert_nbody) @@ -758,8 +753,8 @@ def test12(self): instance.cleanup_code() self.assertEqual(instance.get_name_of_current_state(), 'END') instance.stop() - - print("initialize_code(), commit_parameters(), (re)commit_particles(), and cleanup_code() should be called " \ + + print("initialize_code(), commit_parameters(), (re)commit_particles(), and cleanup_code() should be called " "automatically before setting parameters, new_xx_particle(), get_xx(), and stop():") instance = Fi(convert_nbody) self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') @@ -771,7 +766,7 @@ def test12(self): self.assertEqual(instance.get_name_of_current_state(), 'EDIT') mass = instance.gas_particles[0].mass self.assertEqual(instance.get_name_of_current_state(), 'RUN') - instance.synchronize_model() # model was already synchronized, but fi doesn't seem to get that... + instance.synchronize_model() # model was already synchronized, but fi doesn't seem to get that... instance.dm_particles.remove_particles(dark) self.assertEqual(instance.get_name_of_current_state(), 'UPDATE') mass = instance.gas_particles[0].mass @@ -780,16 +775,16 @@ def test12(self): self.assertEqual(instance.get_name_of_current_state(), 'EVOLVED') instance.stop() self.assertEqual(instance.get_name_of_current_state(), 'STOPPED') - + def test13(self): particles = datamodel.Particles(2) - particles.x = [0.0,10.0] | nbody_system.length + particles.x = [0.0, 10.0] | nbody_system.length particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.radius = 0.005 | nbody_system.length - particles.vx = 0 | nbody_system.speed - particles.vy = 0 | nbody_system.speed - particles.vz = 0 | nbody_system.speed + particles.vx = 0 | nbody_system.speed + particles.vy = 0 | nbody_system.speed + particles.vz = 0 | nbody_system.speed particles.mass = 1.0 | nbody_system.mass instance = Fi(redirection="none") @@ -797,7 +792,7 @@ def test13(self): instance.parameters.stopping_conditions_number_of_steps = 2 self.assertEqual(instance.parameters.stopping_conditions_number_of_steps, 2) instance.parameters.epsilon_squared = (0.01 | nbody_system.length)**2 - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.stopping_conditions.number_of_steps_detection.enable() instance.evolve_model(10 | nbody_system.time) self.assertTrue(instance.stopping_conditions.number_of_steps_detection.is_set()) @@ -807,13 +802,13 @@ def test13(self): def test13a(self): particles = datamodel.Particles(2) - particles.x = [0.0,10.0] | nbody_system.length + particles.x = [0.0, 10.0] | nbody_system.length particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.radius = 0.005 | nbody_system.length - particles.vx = 0 | nbody_system.speed - particles.vy = 0 | nbody_system.speed - particles.vz = 0 | nbody_system.speed + particles.vx = 0 | nbody_system.speed + particles.vy = 0 | nbody_system.speed + particles.vz = 0 | nbody_system.speed particles.mass = 1.0 | nbody_system.mass very_short_time_to_evolve = 1 | units.s @@ -824,13 +819,13 @@ def test13a(self): instance.parameters.stopping_conditions_timeout = very_short_time_to_evolve self.assertEqual(instance.parameters.stopping_conditions_timeout, very_short_time_to_evolve) instance.parameters.epsilon_squared = (0.01 | nbody_system.length)**2 - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.stopping_conditions.timeout_detection.enable() start = time.time() instance.evolve_model(very_long_time_to_evolve) end = time.time() self.assertTrue(instance.stopping_conditions.timeout_detection.is_set()) - self.assertTrue((end-start)= + self.assertEqual(out_of_box_detection.particles().position.lengths() >= 1.0 | nbody_system.length, [True, True, True]) self.assertEqual(len(out_of_box_detection.particles(1)), 0) instance.particles.remove_particles(out_of_box_detection.particles()) - + stopping_conditions_info = str(instance.stopping_conditions).split("\n") self.assertEqual(stopping_conditions_info[0], "Stopping conditions of a 'Fi' object") for i, word in enumerate(["supported", "enabled", "set"]): self.assertTrue(word in stopping_conditions_info[i+1]) self.assertTrue("out_of_box_detection" in stopping_conditions_info[i+1]) - + instance.evolve_model(1.5 | nbody_system.time) self.assertFalse(out_of_box_detection.is_set()) self.assertAlmostEqual(instance.model_time, 1.5 | nbody_system.time, 3) - + instance.evolve_model(3.0 | nbody_system.time) self.assertTrue(out_of_box_detection.is_set()) self.assertAlmostEqual(instance.model_time, 2.0 | nbody_system.time, 3) self.assertEqual(len(out_of_box_detection.particles()), 2) instance.stop() - def test14(self): print("Testing Fi get_hydro_state_at_point") number_sph_particles = 100 convert_nbody = nbody_system.nbody_to_si(1.0 | units.kpc, 1.0e10 | units.MSun) - gas = new_evrard_gas_sphere(number_sph_particles, convert_nbody, seed = 1234) + gas = new_evrard_gas_sphere(number_sph_particles, convert_nbody, seed=1234) gas.h_smooth = 0.01 | nbody_system.length - + instance = Fi(convert_nbody) instance.parameters.n_smooth = 64 instance.parameters.n_smooth_tol = 0.01 instance.gas_particles.add_particles(gas) instance.synchronize_model() - + coords = [0.0 | units.kpc]*3 hydro_state = instance.get_hydro_state_at_point(*coords) - expected = [ 3.5540e-19 | units.kg * units.m**-3, - 0.0 | units.kg * units.m**-2 / units.s, - 0.0 | units.kg * units.m**-2 / units.s, - 0.0 | units.kg * units.m**-2 / units.s, + expected = [3.5540e-19 | units.kg * units.m**-3, + 0.0 | units.kg * units.m**-2 / units.s, + 0.0 | units.kg * units.m**-2 / units.s, + 0.0 | units.kg * units.m**-2 / units.s, 8.445e-10 | units.kg * units.m**-1 * units.s**-2] for value, expect in zip(hydro_state, expected): self.assertAlmostRelativeEqual(value, expect, places=3) - + coords = [0.1 | units.kpc]*3 hydro_state = instance.get_hydro_state_at_point(*coords) - expected = [ 4.1789e-19 | units.kg * units.m**-3, - 0.0 | units.kg * units.m**-2 / units.s, - 0.0 | units.kg * units.m**-2 / units.s, - 0.0 | units.kg * units.m**-2 / units.s, + expected = [4.1789e-19 | units.kg * units.m**-3, + 0.0 | units.kg * units.m**-2 / units.s, + 0.0 | units.kg * units.m**-2 / units.s, + 0.0 | units.kg * units.m**-2 / units.s, 1.0868e-9 | units.kg * units.m**-1 * units.s**-2] for value, expect in zip(hydro_state, expected): self.assertAlmostRelativeEqual(value, expect, places=3) instance.stop() - + def test15(self): print("Testing Fi get_hydro_state_at_point II: uniform sphere") number_sph_particles = 1000 @@ -928,49 +922,48 @@ def test15(self): gas.h_smooth = 0.01 | nbody_system.length gas.u = 0.05 | nbody_system.specific_energy density = (1.0e10 | units.MSun) / (4.0/3.0 * numpy.pi * (1.0 | units.kpc)**3) - + instance = Fi(convert_nbody) instance.parameters.n_smooth = 64 instance.parameters.n_smooth_tol = 0.01 instance.gas_particles.add_particles(gas) instance.synchronize_model() - + coords = [0.0 | units.kpc]*3 rho, rhovx, rhovy, rhovz, rhoe = instance.get_hydro_state_at_point(*coords) self.assertAlmostRelativeEqual(rho, density, places=3) self.assertAlmostRelativeEqual(rho, max(instance.gas_particles.rho), places=2) - self.assertIsOfOrder( rho, instance.gas_particles.rho) + self.assertIsOfOrder(rho, instance.gas_particles.rho) self.assertAlmostRelativeEqual(rhovx, density*instance.gas_particles[0].vx, places=3) self.assertAlmostRelativeEqual(rhovy, density*instance.gas_particles[0].vy, places=3) self.assertAlmostRelativeEqual(rhovz, density*instance.gas_particles[0].vz, places=3) - self.assertAlmostRelativeEqual(rhoe, density * (instance.gas_particles[0].u + + self.assertAlmostRelativeEqual(rhoe, density * (instance.gas_particles[0].u + 0.5 * instance.gas_particles[0].velocity.length_squared()), places=2) - + coords = [0.1 | units.kpc]*3 rho, rhovx, rhovy, rhovz, rhoe = instance.get_hydro_state_at_point(*coords) self.assertAlmostRelativeEqual(rho, density, places=3) self.assertAlmostRelativeEqual(rhovx, density*instance.gas_particles[0].vx, places=3) self.assertAlmostRelativeEqual(rhovy, density*instance.gas_particles[0].vy, places=3) self.assertAlmostRelativeEqual(rhovz, density*instance.gas_particles[0].vz, places=3) - self.assertAlmostRelativeEqual(rhoe, density * (instance.gas_particles[0].u + + self.assertAlmostRelativeEqual(rhoe, density * (instance.gas_particles[0].u + 0.5 * instance.gas_particles[0].velocity.length_squared()), places=2) instance.stop() - - + def test16(self): instance = self.new_instance_of_an_optional_code(Fi) try: particles = new_plummer_model(100) more_particles = new_plummer_model(50) - - particles.h_smooth = 0.1 | nbody_system.length + + particles.h_smooth = 0.1 | nbody_system.length particles.u = 0.1 | nbody_system.speed**2 - more_particles.h_smooth = 0.1 | nbody_system.length + more_particles.h_smooth = 0.1 | nbody_system.length more_particles.u = 0.1 | nbody_system.speed**2 - + particles.move_to_center() more_particles.move_to_center() - + instance.gas_particles.add_particles(particles) instance.commit_particles() self.assertEqual(len(instance.particles), 100) @@ -979,55 +972,54 @@ def test16(self): instance.recommit_particles() self.assertEqual(len(instance.particles), 150) instance.synchronize_model() - selected1 = instance.particles.select_array(lambda x: x<0 | nbody_system.length, ["x",]).copy() + selected1 = instance.particles.select_array(lambda x: x < 0 | nbody_system.length, ["x",]).copy() self.assertEqual(len(instance.particles), 150) instance.particles.remove_particles(selected1) self.assertEqual(len(instance.particles), 150 - len(selected1)) instance.recommit_particles() instance.synchronize_model() - - selected2 = instance.particles.select_array(lambda x: x>0 | nbody_system.length, ["x",]).copy() + + selected2 = instance.particles.select_array(lambda x: x > 0 | nbody_system.length, ["x",]).copy() instance.particles.remove_particles(selected2) self.assertEqual(len(instance.particles), 150 - len(selected1) - len(selected2)) instance.recommit_particles() finally: instance.stop() - + def test17(self): UnitLength = 3.085678e21 | units.cm # ~ 1.0 kpc UnitMass = 1.989e43 | units.g # 1.0e10 solar masses - UnitVelocity = 1e5 | units.cm / units.s # 1 km/sec + UnitVelocity = 1e5 | units.cm / units.s # 1 km/sec convert_nbody = nbody_system.nbody_to_si(UnitLength, UnitMass) - instance = Fi(convert_nbody, mode = FiInterface.MODE_PERIODIC_BOUNDARIES) + instance = Fi(convert_nbody, mode=FiInterface.MODE_PERIODIC_BOUNDARIES) self.assertEqual(instance.parameters.periodic_boundaries_flag, True) instance.parameters.use_hydro_flag = False instance.parameters.self_gravity_flag = False instance.parameters.periodic_box_size = 2.0 | nbody_system.length instance.parameters.timestep = 0.1 | nbody_system.time self.assertAlmostEqual(instance.parameters.periodic_box_size, 2.0 | units.kpc, places=6) - + three_particles_IC = datamodel.Particles(3) - three_particles_IC.position = [[0.5, 0.0, 0.0], [0.0,-0.5, 0.0], [0.0, 0.0, 0.5]] | nbody_system.length - three_particles_IC.velocity =[[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0,-1.0]] | nbody_system.speed + three_particles_IC.position = [[0.5, 0.0, 0.0], [0.0, -0.5, 0.0], [0.0, 0.0, 0.5]] | nbody_system.length + three_particles_IC.velocity = [[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]] | nbody_system.speed three_particles_IC.radius = 0.0 | units.RSun three_particles_IC.mass = 1.0e10 | units.MSun - + instance.dm_particles.add_particles(three_particles_IC) self.assertAlmostEqual(instance.dm_particles.x, [0.5, 0.0, 0.0] | units.kpc, places=6) - self.assertAlmostEqual(instance.dm_particles.y, [0.0,-0.5, 0.0] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.y, [0.0, -0.5, 0.0] | units.kpc, places=6) self.assertAlmostEqual(instance.dm_particles.z, [0.0, 0.0, 0.5] | units.kpc, places=6) - + instance.evolve_model(0.1 | nbody_system.time) self.assertAlmostEqual(instance.dm_particles.x, [0.4, 0.0, 0.0] | units.kpc, places=6) - self.assertAlmostEqual(instance.dm_particles.y, [0.0,-0.4, 0.0] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.y, [0.0, -0.4, 0.0] | units.kpc, places=6) self.assertAlmostEqual(instance.dm_particles.z, [0.0, 0.0, 0.4] | units.kpc, places=6) - + instance.evolve_model(1.0 | nbody_system.time) self.assertAlmostEqual(instance.dm_particles.x, [-0.5, 0.0, 0.0] | units.kpc, places=6) - self.assertAlmostEqual(instance.dm_particles.y, [ 0.0, 0.5, 0.0] | units.kpc, places=6) - self.assertAlmostEqual(instance.dm_particles.z, [ 0.0, 0.0,-0.5] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.y, [0.0, 0.5, 0.0] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.z, [0.0, 0.0, -0.5] | units.kpc, places=6) instance.stop() - def test18(self): particles = datamodel.Particles(10) @@ -1035,165 +1027,164 @@ def test18(self): particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.radius = 0.001 | nbody_system.length - particles.vx = 0 | nbody_system.speed - particles.vy = 0 | nbody_system.speed - particles.vz = 0 | nbody_system.speed + particles.vx = 0 | nbody_system.speed + particles.vy = 0 | nbody_system.speed + particles.vz = 0 | nbody_system.speed particles.mass = 1.0 | nbody_system.mass - + instance = Fi() instance.initialize_code() instance.particles.add_particles(particles) self.assertEqual(len(instance.particles[0:2]), 2) self.assertTrue(str(instance.particles[0:2]).find('key') > 0) instance.stop() - + def test19(self): - + instance = Fi() instance.dm_particles.add_particle(datamodel.Particle( - x = 1.0 | nbody_system.length, - y = 2.0 | nbody_system.length, - z = 3.0 | nbody_system.length, - vx = 1.0 | nbody_system.speed, - vy = 2.0 | nbody_system.speed, - vz = 3.0 | nbody_system.speed, - mass = 1.0 | nbody_system.mass, - )) + x=1.0 | nbody_system.length, + y=2.0 | nbody_system.length, + z=3.0 | nbody_system.length, + vx=1.0 | nbody_system.speed, + vy=2.0 | nbody_system.speed, + vz=3.0 | nbody_system.speed, + mass=1.0 | nbody_system.mass, + )) instance.gas_particles.add_particle(datamodel.Particle( - x = 1.0 | nbody_system.length, - y = 2.0 | nbody_system.length, - z = 4.0 | nbody_system.length, - vx = 1.0 | nbody_system.speed, - vy = 2.0 | nbody_system.speed, - vz = 3.0 | nbody_system.speed, - mass = 1.0 | nbody_system.mass, - u = 1.0 | nbody_system.potential - )) + x=1.0 | nbody_system.length, + y=2.0 | nbody_system.length, + z=4.0 | nbody_system.length, + vx=1.0 | nbody_system.speed, + vy=2.0 | nbody_system.speed, + vz=3.0 | nbody_system.speed, + mass=1.0 | nbody_system.mass, + u=1.0 | nbody_system.potential + )) instance.star_particles.add_particle(datamodel.Particle( - x = 1.0 | nbody_system.length, - y = 2.0 | nbody_system.length, - z = 5.0 | nbody_system.length, - vx = 1.0 | nbody_system.speed, - vy = 2.0 | nbody_system.speed, - vz = 3.0 | nbody_system.speed, - mass = 1.0 | nbody_system.mass, - )) + x=1.0 | nbody_system.length, + y=2.0 | nbody_system.length, + z=5.0 | nbody_system.length, + vx=1.0 | nbody_system.speed, + vy=2.0 | nbody_system.speed, + vz=3.0 | nbody_system.speed, + mass=1.0 | nbody_system.mass, + )) instance.commit_particles() self.assertEqual(instance.dm_particles[0].radius, 8.0 | nbody_system.length) self.assertAlmostRelativeEquals(instance.gas_particles[0].h_smooth, 116.754483949 | nbody_system.length, 6) self.assertEqual(instance.star_particles[0].radius, 8.0 | nbody_system.length) - + instance.stop() instance = Fi() instance.parameters.adaptive_smoothing_flag = False instance.dm_particles.add_particle(datamodel.Particle( - x = 1.0 | nbody_system.length, - y = 2.0 | nbody_system.length, - z = 3.0 | nbody_system.length, - vx = 1.0 | nbody_system.speed, - vy = 2.0 | nbody_system.speed, - vz = 3.0 | nbody_system.speed, - mass = 1.0 | nbody_system.mass, - radius = 0.1 | nbody_system.length, - )) + x=1.0 | nbody_system.length, + y=2.0 | nbody_system.length, + z=3.0 | nbody_system.length, + vx=1.0 | nbody_system.speed, + vy=2.0 | nbody_system.speed, + vz=3.0 | nbody_system.speed, + mass=1.0 | nbody_system.mass, + radius=0.1 | nbody_system.length, + )) instance.gas_particles.add_particle(datamodel.Particle( - x = 1.0 | nbody_system.length, - y = 2.0 | nbody_system.length, - z = 4.0 | nbody_system.length, - vx = 1.0 | nbody_system.speed, - vy = 2.0 | nbody_system.speed, - vz = 3.0 | nbody_system.speed, - mass = 1.0 | nbody_system.mass, - u = 1.0 | nbody_system.potential, - h_smooth = 100 | nbody_system.length, - - )) + x=1.0 | nbody_system.length, + y=2.0 | nbody_system.length, + z=4.0 | nbody_system.length, + vx=1.0 | nbody_system.speed, + vy=2.0 | nbody_system.speed, + vz=3.0 | nbody_system.speed, + mass=1.0 | nbody_system.mass, + u=1.0 | nbody_system.potential, + h_smooth=100 | nbody_system.length, + + )) instance.star_particles.add_particle(datamodel.Particle( - x = 1.0 | nbody_system.length, - y = 2.0 | nbody_system.length, - z = 5.0 | nbody_system.length, - vx = 1.0 | nbody_system.speed, - vy = 2.0 | nbody_system.speed, - vz = 3.0 | nbody_system.speed, - mass = 1.0 | nbody_system.mass, - radius = 0.2 | nbody_system.length, - )) + x=1.0 | nbody_system.length, + y=2.0 | nbody_system.length, + z=5.0 | nbody_system.length, + vx=1.0 | nbody_system.speed, + vy=2.0 | nbody_system.speed, + vz=3.0 | nbody_system.speed, + mass=1.0 | nbody_system.mass, + radius=0.2 | nbody_system.length, + )) instance.commit_particles() self.assertEqual(instance.dm_particles[0].radius, 0.1 | nbody_system.length) self.assertAlmostRelativeEquals(instance.gas_particles[0].h_smooth, 116.754483949 | nbody_system.length, 6) - self.assertEqual(instance.star_particles[0].radius,0.2| nbody_system.length) + self.assertEqual(instance.star_particles[0].radius, 0.2 | nbody_system.length) instance.stop() - + def test20(self): - instance=Fi() + instance = Fi() instance.initialize_code() instance.parameters.use_hydro_flag = 0 instance.parameters.self_gravity_flag = 0 instance.parameters.periodic_box_size = 1 | nbody_system.length instance.parameters.timestep = 0.2 | nbody_system.time - + p1 = instance.gas_particles.add_particle(datamodel.Particle( - x = 0.5 | nbody_system.length, - y = 0.0 | nbody_system.length, - z = 0.0 | nbody_system.length, - vx = 1.0 | nbody_system.speed, - vy = 0.0 | nbody_system.speed, - vz = 0.0 | nbody_system.speed, - mass = 0.1 | nbody_system.mass, - u = 0.0 | nbody_system.potential - - )) + x=0.5 | nbody_system.length, + y=0.0 | nbody_system.length, + z=0.0 | nbody_system.length, + vx=1.0 | nbody_system.speed, + vy=0.0 | nbody_system.speed, + vz=0.0 | nbody_system.speed, + mass=0.1 | nbody_system.mass, + u=0.0 | nbody_system.potential + + )) p2 = instance.gas_particles.add_particle(datamodel.Particle( - x = 0.1 | nbody_system.length, - y = 0.0 | nbody_system.length, - z = 0.0 | nbody_system.length, - vx = 0.0 | nbody_system.speed, - vy = 0.0 | nbody_system.speed, - vz = 0.0 | nbody_system.speed, - mass = 0.001 | nbody_system.mass, - u = 0.0 | nbody_system.potential - - )) - - instance.evolve_model(0.1 |nbody_system.time) + x=0.1 | nbody_system.length, + y=0.0 | nbody_system.length, + z=0.0 | nbody_system.length, + vx=0.0 | nbody_system.speed, + vy=0.0 | nbody_system.speed, + vz=0.0 | nbody_system.speed, + mass=0.001 | nbody_system.mass, + u=0.0 | nbody_system.potential + + )) + + instance.evolve_model(0.1 | nbody_system.time) instance.update_particle_set() self.assertEqual(len(instance.gas_particles), 2) - + self.assertAlmostRelativeEquals(instance.gas_particles[0].x, 0.5 | nbody_system.length) - instance.evolve_model(0.15 |nbody_system.time) + instance.evolve_model(0.15 | nbody_system.time) instance.update_particle_set() self.assertEqual(len(instance.gas_particles), 1) self.assertEqual(instance.gas_particles.mass, [0.001] | nbody_system.mass) self.assertEqual(instance.gas_particles[0].mass, 0.001 | nbody_system.mass) self.assertAlmostRelativeEquals(instance.gas_particles[0].x, 0.1 | nbody_system.length) self.assertAlmostRelativeEquals(instance.gas_particles.x, [0.1] | nbody_system.length) - def test21(self): - instance=Fi() + instance = Fi() instance.parameters.use_hydro_flag = 0 instance.parameters.self_gravity_flag = 0 instance.parameters.periodic_box_size = 1 | nbody_system.length instance.parameters.timestep = 0.2 | nbody_system.time instance.commit_parameters() - instance.parameters.use_hydro_flag =1 + instance.parameters.use_hydro_flag = 1 particles = datamodel.Particles(2) particles.mass = 0.5 | nbody_system.mass - particles[0].position = [1.0,0.0,0.0] | nbody_system.length - particles[1].position = [-1.0,0.0,0.] | nbody_system.length - particles.velocity = [0,0,0] | nbody_system.speed + particles[0].position = [1.0, 0.0, 0.0] | nbody_system.length + particles[1].position = [-1.0, 0.0, 0.] | nbody_system.length + particles.velocity = [0, 0, 0] | nbody_system.speed particles.u = 0.0 | nbody_system.potential print(particles) - + try: - t = instance.model_time + t = instance.model_time self.assertEqual(t, 0 | nbody_system.time) channel = instance.particles.new_channel_to(particles) self.assertEqual(0, len(instance.particles)) particles.synchronize_to(instance.particles) self.assertEqual(2, len(instance.particles)) instance.commit_particles() - + self.assertEqual(2, len(particles)) instance.particles.synchronize_to(particles) self.assertEqual(2, len(particles)) @@ -1201,55 +1192,55 @@ def test21(self): except Exception as ex: print(ex) self.fail("requesting the model time should not trigger a commit_particles") - + def test22(self): - instance=Fi() + instance = Fi() instance.initialize_code() instance.parameters.use_hydro_flag = 0 instance.parameters.self_gravity_flag = 0 instance.parameters.periodic_box_size = 1 | nbody_system.length instance.parameters.timestep = 0.2 | nbody_system.time - + p1 = instance.gas_particles.add_particle(datamodel.Particle( - x = 0.5 | nbody_system.length, - y = 0.0 | nbody_system.length, - z = 0.0 | nbody_system.length, - vx = 1.0 | nbody_system.speed, - vy = 0.0 | nbody_system.speed, - vz = 0.0 | nbody_system.speed, - mass = 0.1 | nbody_system.mass, - u = 0.0 | nbody_system.potential - - )) + x=0.5 | nbody_system.length, + y=0.0 | nbody_system.length, + z=0.0 | nbody_system.length, + vx=1.0 | nbody_system.speed, + vy=0.0 | nbody_system.speed, + vz=0.0 | nbody_system.speed, + mass=0.1 | nbody_system.mass, + u=0.0 | nbody_system.potential + + )) p2 = instance.gas_particles.add_particle(datamodel.Particle( - x = 0.1 | nbody_system.length, - y = 0.0 | nbody_system.length, - z = 0.0 | nbody_system.length, - vx = 0.0 | nbody_system.speed, - vy = 0.0 | nbody_system.speed, - vz = 0.0 | nbody_system.speed, - mass = 0.001 | nbody_system.mass, - u = 0.0 | nbody_system.potential - - )) + x=0.1 | nbody_system.length, + y=0.0 | nbody_system.length, + z=0.0 | nbody_system.length, + vx=0.0 | nbody_system.speed, + vy=0.0 | nbody_system.speed, + vz=0.0 | nbody_system.speed, + mass=0.001 | nbody_system.mass, + u=0.0 | nbody_system.potential + + )) p3 = instance.gas_particles.add_particle(datamodel.Particle( - x = -0.9 | nbody_system.length, - y = 0.0 | nbody_system.length, - z = 0.0 | nbody_system.length, - vx = -2.0 | nbody_system.speed, - vy = 0.0 | nbody_system.speed, - vz = 0.0 | nbody_system.speed, - mass = 0.002 | nbody_system.mass, - u = 0.0 | nbody_system.potential - - )) - - instance.evolve_model(0.1 |nbody_system.time) + x=-0.9 | nbody_system.length, + y=0.0 | nbody_system.length, + z=0.0 | nbody_system.length, + vx=-2.0 | nbody_system.speed, + vy=0.0 | nbody_system.speed, + vz=0.0 | nbody_system.speed, + mass=0.002 | nbody_system.mass, + u=0.0 | nbody_system.potential + + )) + + instance.evolve_model(0.1 | nbody_system.time) instance.update_particle_set() self.assertEqual(len(instance.gas_particles), 3) - + self.assertAlmostRelativeEquals(instance.gas_particles[0].x, 0.5 | nbody_system.length) - instance.evolve_model(0.15 |nbody_system.time) + instance.evolve_model(0.15 | nbody_system.time) instance.update_particle_set() self.assertEqual(instance.gas_particles.mass, [0.001] | nbody_system.mass) self.assertEqual(instance.gas_particles[0].mass, 0.001 | nbody_system.mass) @@ -1257,55 +1248,53 @@ def test22(self): self.assertAlmostRelativeEquals(instance.gas_particles[0].mass, 0.001 | nbody_system.mass) self.assertAlmostRelativeEquals(instance.gas_particles[0].x, 0.1 | nbody_system.length) self.assertAlmostRelativeEquals(instance.gas_particles.x, [0.1] | nbody_system.length) - - def test23(self): - instance=Fi() + instance = Fi() instance.initialize_code() instance.parameters.use_hydro_flag = 0 instance.parameters.self_gravity_flag = 0 instance.parameters.periodic_box_size = 1 | nbody_system.length instance.parameters.timestep = 0.2 | nbody_system.time - + p1 = instance.gas_particles.add_particle(datamodel.Particle( - x = 1.5 | nbody_system.length, - y = 0.0 | nbody_system.length, - z = 0.0 | nbody_system.length, - vx = 1.0 | nbody_system.speed, - vy = 0.0 | nbody_system.speed, - vz = 0.0 | nbody_system.speed, - mass = 0.1 | nbody_system.mass, - u = 0.0 | nbody_system.potential - - )) + x=1.5 | nbody_system.length, + y=0.0 | nbody_system.length, + z=0.0 | nbody_system.length, + vx=1.0 | nbody_system.speed, + vy=0.0 | nbody_system.speed, + vz=0.0 | nbody_system.speed, + mass=0.1 | nbody_system.mass, + u=0.0 | nbody_system.potential + + )) p2 = instance.gas_particles.add_particle(datamodel.Particle( - x = 0.1 | nbody_system.length, - y = 0.0 | nbody_system.length, - z = 0.0 | nbody_system.length, - vx = 0.0 | nbody_system.speed, - vy = 0.0 | nbody_system.speed, - vz = 0.0 | nbody_system.speed, - mass = 0.001 | nbody_system.mass, - u = 0.0 | nbody_system.potential - - )) + x=0.1 | nbody_system.length, + y=0.0 | nbody_system.length, + z=0.0 | nbody_system.length, + vx=0.0 | nbody_system.speed, + vy=0.0 | nbody_system.speed, + vz=0.0 | nbody_system.speed, + mass=0.001 | nbody_system.mass, + u=0.0 | nbody_system.potential + + )) p3 = instance.gas_particles.add_particle(datamodel.Particle( - x = -1.5 | nbody_system.length, - y = 0.0 | nbody_system.length, - z = 0.0 | nbody_system.length, - vx = -2.0 | nbody_system.speed, - vy = 0.0 | nbody_system.speed, - vz = 0.0 | nbody_system.speed, - mass = 0.002 | nbody_system.mass, - u = 0.0 | nbody_system.potential - - )) + x=-1.5 | nbody_system.length, + y=0.0 | nbody_system.length, + z=0.0 | nbody_system.length, + vx=-2.0 | nbody_system.speed, + vy=0.0 | nbody_system.speed, + vz=0.0 | nbody_system.speed, + mass=0.002 | nbody_system.mass, + u=0.0 | nbody_system.potential + + )) instance.commit_particles() self.assertEqual(len(instance.gas_particles), 3) self.assertEqual(instance.gas_particles.mass, [0.1, 0.001, 0.002] | nbody_system.mass) - - instance.evolve_model(0.15 |nbody_system.time) + + instance.evolve_model(0.15 | nbody_system.time) instance.update_particle_set() self.assertEqual(len(instance.gas_particles), 1) self.assertEqual(instance.gas_particles.mass, [0.001] | nbody_system.mass) @@ -1314,46 +1303,46 @@ def test23(self): self.assertAlmostRelativeEquals(instance.gas_particles[0].mass, 0.001 | nbody_system.mass) self.assertAlmostRelativeEquals(instance.gas_particles[0].x, 0.1 | nbody_system.length) self.assertAlmostRelativeEquals(instance.gas_particles.x, [0.1] | nbody_system.length) - + def test24(self): - instance=Fi() + instance = Fi() instance.initialize_code() instance.parameters.use_hydro_flag = 0 instance.parameters.self_gravity_flag = 0 instance.parameters.periodic_box_size = 1 | nbody_system.length instance.parameters.timestep = 0.2 | nbody_system.time - + p1 = instance.gas_particles.add_particle(datamodel.Particle( - x = 0.5 | nbody_system.length, - y = 0.0 | nbody_system.length, - z = 0.0 | nbody_system.length, - vx = 1.0 | nbody_system.speed, - vy = 0.0 | nbody_system.speed, - vz = 0.0 | nbody_system.speed, - mass = 0.1 | nbody_system.mass, - u = 0.0 | nbody_system.potential - - )) + x=0.5 | nbody_system.length, + y=0.0 | nbody_system.length, + z=0.0 | nbody_system.length, + vx=1.0 | nbody_system.speed, + vy=0.0 | nbody_system.speed, + vz=0.0 | nbody_system.speed, + mass=0.1 | nbody_system.mass, + u=0.0 | nbody_system.potential + + )) p2 = instance.gas_particles.add_particle(datamodel.Particle( - x = 0.1 | nbody_system.length, - y = 0.0 | nbody_system.length, - z = 0.0 | nbody_system.length, - vx = 0.0 | nbody_system.speed, - vy = 0.0 | nbody_system.speed, - vz = 0.0 | nbody_system.speed, - mass = 0.001 | nbody_system.mass, - u = 0.0 | nbody_system.potential - - )) - #run more than one innerloop step in fi - instance.evolve_model(1|nbody_system.time) + x=0.1 | nbody_system.length, + y=0.0 | nbody_system.length, + z=0.0 | nbody_system.length, + vx=0.0 | nbody_system.speed, + vy=0.0 | nbody_system.speed, + vz=0.0 | nbody_system.speed, + mass=0.001 | nbody_system.mass, + u=0.0 | nbody_system.potential + + )) + # run more than one innerloop step in fi + instance.evolve_model(1 | nbody_system.time) instance.update_particle_set() self.assertEqual(len(instance.gas_particles), 1) self.assertEqual(instance.gas_particles.mass, [0.001] | nbody_system.mass) self.assertEqual(instance.gas_particles[0].mass, 0.001 | nbody_system.mass) self.assertAlmostRelativeEquals(instance.gas_particles[0].x, 0.1 | nbody_system.length) self.assertAlmostRelativeEquals(instance.gas_particles.x, [0.1] | nbody_system.length) - + def test25(self): print("Testing Fi density_limit_detection") number_gas_particles = 500 @@ -1361,7 +1350,7 @@ def test25(self): UnitMass = 1.989e43 | units.g # 1.0e10 solar masses convert_nbody = nbody_system.nbody_to_si(UnitLength, UnitMass) gas = new_evrard_gas_sphere(number_gas_particles, convert_nbody, do_scale=True, seed=12345) - + instance = Fi(convert_nbody) instance.initialize_code() instance.parameters.stopping_condition_maximum_density = 10.0 * UnitMass / UnitLength**3 @@ -1371,32 +1360,32 @@ def test25(self): stars.x += 1000 * UnitLength instance.dm_particles.add_particles(stars) self.assertIsOfOrder(max(instance.gas_particles.density), UnitMass / UnitLength**3) - + density_limit_detection = instance.stopping_conditions.density_limit_detection density_limit_detection.enable() - + instance.evolve_model(10.0 | units.Myr) print(instance.model_time.as_quantity_in(units.Myr)) print(instance.stopping_conditions) self.assertTrue(density_limit_detection.is_set()) self.assertTrue(instance.model_time < 10.0 | units.Myr) self.assertEqual(len(density_limit_detection.particles()), 1) - self.assertTrue((density_limit_detection.particles().density > + self.assertTrue((density_limit_detection.particles().density > 10 * UnitMass / UnitLength**3).all()) - + instance.particles.remove_particles(density_limit_detection.particles()) - + instance.evolve_model(10.0 | units.Myr) print(instance.model_time.as_quantity_in(units.Myr)) print(instance.stopping_conditions) self.assertTrue(density_limit_detection.is_set()) self.assertTrue(instance.model_time < 10.0 | units.Myr) - + self.assertEqual(len(density_limit_detection.particles()), 1) - self.assertTrue((density_limit_detection.particles().density > + self.assertTrue((density_limit_detection.particles().density > 10 * UnitMass / UnitLength**3).all()) instance.stop() - + def test26(self): print("Testing Fi internal_energy_limit_detection") number_gas_particles = 500 @@ -1405,69 +1394,69 @@ def test26(self): convert_nbody = nbody_system.nbody_to_si(UnitLength, UnitMass) gas = new_evrard_gas_sphere(number_gas_particles, convert_nbody, do_scale=True, seed=12345) initial_internal_energy = 0.05 * constants.G * UnitMass / UnitLength - + instance = Fi(convert_nbody) instance.initialize_code() instance.parameters.timestep = 0.1 | units.Myr instance.parameters.stopping_condition_maximum_internal_energy = 10 * initial_internal_energy instance.gas_particles.add_particles(gas) self.assertAlmostRelativeEquals(instance.gas_particles.u, initial_internal_energy, 8) - + internal_energy_limit_detection = instance.stopping_conditions.internal_energy_limit_detection internal_energy_limit_detection.enable() - + instance.evolve_model(10.0 | units.Myr) print(instance.model_time.as_quantity_in(units.Myr)) print(instance.stopping_conditions) self.assertTrue(internal_energy_limit_detection.is_set()) self.assertTrue(instance.model_time < 10.0 | units.Myr) self.assertEqual(len(internal_energy_limit_detection.particles()), 1) - self.assertTrue((internal_energy_limit_detection.particles().u > + self.assertTrue((internal_energy_limit_detection.particles().u > 10 * initial_internal_energy).all()) - + instance.particles.remove_particles(internal_energy_limit_detection.particles()) - + instance.evolve_model(10.0 | units.Myr) print(instance.model_time.as_quantity_in(units.Myr)) print(instance.stopping_conditions) self.assertTrue(internal_energy_limit_detection.is_set()) self.assertTrue(instance.model_time < 10.0 | units.Myr) self.assertEqual(len(internal_energy_limit_detection.particles()), 6) - self.assertTrue((internal_energy_limit_detection.particles().u > + self.assertTrue((internal_energy_limit_detection.particles().u > 10 * initial_internal_energy).all()) instance.stop() - + def test27(self): print("Testing Fi SPH particle properties") number_sph_particles = 1000 convert_nbody = nbody_system.nbody_to_si(1.0e9 | units.MSun, 1.0 | units.kpc) - - gas = new_evrard_gas_sphere(number_sph_particles, convert_nbody, seed = 1234) + + gas = new_evrard_gas_sphere(number_sph_particles, convert_nbody, seed=1234) instance = Fi(convert_nbody) instance.parameters.timestep = 0.05 | nbody_system.time instance.parameters.integrate_entropy_flag = True instance.gas_particles.add_particles(gas) - self.assertIsOfOrder(instance.gas_particles.h_smooth, - convert_nbody.to_si(0.5 | nbody_system.length) * + self.assertIsOfOrder(instance.gas_particles.h_smooth, + convert_nbody.to_si(0.5 | nbody_system.length) * (instance.parameters.n_smooth*1.0/number_sph_particles)**(1.0/3)) - self.assertAlmostRelativeEqual(instance.gas_particles.u, + self.assertAlmostRelativeEqual(instance.gas_particles.u, convert_nbody.to_si(0.05 | nbody_system.specific_energy)) - + # the density of the cloud scales with 1/r: r_sort, rho_sort = instance.gas_particles.position.lengths().sorted_with(instance.gas_particles.rho) mean_density = convert_nbody.to_si(3.0/(4.0*numpy.pi) | nbody_system.density) - select = slice(number_sph_particles//2) # select 50% particles closest to center to avoid boundaries + select = slice(number_sph_particles//2) # select 50% particles closest to center to avoid boundaries self.assertIsOfOrder(rho_sort[select]/mean_density, r_sort.mean()/r_sort[select]) - - self.assertAlmostEqual(instance.gas_particles.u * instance.gas_particles.rho, + + self.assertAlmostEqual(instance.gas_particles.u * instance.gas_particles.rho, 1.5 * instance.gas_particles.pressure) - + self.assertAlmostEqual(instance.gas_particles.du_dt, 0 | units.m**2 * units.s**-3) u_0 = instance.gas_particles.u.sum() instance.evolve_model(0.1 | nbody_system.time) # Collapsing ==> heating: self.assertTrue(instance.gas_particles.du_dt.sum() >= 0 | units.m**2 * units.s**-3) - self.assertIsOfOrder(instance.gas_particles.du_dt.sum() * convert_nbody.to_si(0.1 | nbody_system.time), + self.assertIsOfOrder(instance.gas_particles.du_dt.sum() * convert_nbody.to_si(0.1 | nbody_system.time), instance.gas_particles.u.sum() - u_0) instance.stop() @@ -1478,204 +1467,202 @@ def test28(self): UnitMass = 1.989e43 | units.g # 1.0e10 solar masses convert_nbody = nbody_system.nbody_to_si(UnitLength, UnitMass) gas = new_evrard_gas_sphere(number_gas_particles, convert_nbody, do_scale=True, seed=12345) - + instance = Fi(convert_nbody) instance.initialize_code() instance.parameters.stopping_condition_maximum_density = 10.0 * UnitMass / UnitLength**3 instance.parameters.timestep = 0.1 | units.Myr instance.gas_particles.add_particles(gas) - u=instance.gas_particles.u - gas_particles=instance.gas_particles.copy() - - self.assertEqual(u,gas_particles.u) - - + u = instance.gas_particles.u + gas_particles = instance.gas_particles.copy() + + self.assertEqual(u, gas_particles.u) + def test29(self): - instance=Fi() + instance = Fi() instance.initialize_code() instance.parameters.use_hydro_flag = 0 instance.parameters.self_gravity_flag = 1 - instance.parameters.epsilon_squared = 0.000000001 | nbody_system.length**2 + instance.parameters.epsilon_squared = 0.000000001 | nbody_system.length**2 instance.parameters.timestep = 0.2 | nbody_system.time - + x0 = 0.5 | nbody_system.length - + p1 = instance.star_particles.add_particle(datamodel.Particle( - x = x0, - y = 0.0 | nbody_system.length, - z = 0.0 | nbody_system.length, - vx = 0.0 | nbody_system.speed, - vy = 0.0 | nbody_system.speed, - vz = 0.0 | nbody_system.speed, - mass = 0.01 | nbody_system.mass, - - )) + x=x0, + y=0.0 | nbody_system.length, + z=0.0 | nbody_system.length, + vx=0.0 | nbody_system.speed, + vy=0.0 | nbody_system.speed, + vz=0.0 | nbody_system.speed, + mass=0.01 | nbody_system.mass, + + )) p2 = instance.star_particles.add_particle(datamodel.Particle( - x = 10| nbody_system.length, - y = 0.0 | nbody_system.length, - z = 0.0 | nbody_system.length, - vx = 0.0 | nbody_system.speed, - vy = 0.0 | nbody_system.speed, - vz = 0.0 | nbody_system.speed, - mass = 100 | nbody_system.mass, - - )) - #run more than one innerloop step in fi + x=10 | nbody_system.length, + y=0.0 | nbody_system.length, + z=0.0 | nbody_system.length, + vx=0.0 | nbody_system.speed, + vy=0.0 | nbody_system.speed, + vz=0.0 | nbody_system.speed, + mass=100 | nbody_system.mass, + + )) + # run more than one innerloop step in fi e0 = instance.kinetic_energy + instance.potential_energy - instance.evolve_model(0.5|nbody_system.time) + instance.evolve_model(0.5 | nbody_system.time) e1 = instance.kinetic_energy + instance.potential_energy self.assertAlmostRelativeEquals(e0, e1, 4) print(instance.star_particles[0].position.x) - - self.assertAlmostRelativeEquals(instance.star_particles[0].position.x, 0.588896329162| nbody_system.length, 12) - + + self.assertAlmostRelativeEquals(instance.star_particles[0].position.x, 0.588896329162 | nbody_system.length, 12) + for i in range(10): p3 = instance.star_particles.add_particle(datamodel.Particle( - x = 100| nbody_system.length, - y = 0.0 | nbody_system.length, - z = 0.0 | nbody_system.length, - vx = 0.0 | nbody_system.speed, - vy = 0.0 | nbody_system.speed, - vz = 0.0 | nbody_system.speed, - mass = 100 | nbody_system.mass, - - )) + x=100 | nbody_system.length, + y=0.0 | nbody_system.length, + z=0.0 | nbody_system.length, + vx=0.0 | nbody_system.speed, + vy=0.0 | nbody_system.speed, + vz=0.0 | nbody_system.speed, + mass=100 | nbody_system.mass, + + )) instance.recommit_particles() instance.star_particles.remove_particle(p3) instance.recommit_particles() - + e11 = instance.kinetic_energy + instance.potential_energy self.assertAlmostRelativeEquals(e1, e1, 8) - instance.evolve_model(1.0|nbody_system.time) + instance.evolve_model(1.0 | nbody_system.time) e2 = instance.kinetic_energy + instance.potential_energy self.assertAlmostRelativeEquals(e0, e1, 4) self.assertAlmostRelativeEquals(instance.star_particles[0].position.x, 1.06498184266 | nbody_system.length, 11) - + def test30(self): - instance=Fi() + instance = Fi() instance.initialize_code() instance.parameters.use_hydro_flag = 0 instance.parameters.self_gravity_flag = 1 - instance.parameters.epsilon_squared = 0.000000001 | nbody_system.length**2 + instance.parameters.epsilon_squared = 0.000000001 | nbody_system.length**2 instance.parameters.timestep = 0.2 | nbody_system.time instance.parameters.verbosity = 0 - + x0 = 0.5 | nbody_system.length - + p1 = instance.star_particles.add_particle(datamodel.Particle( - x = x0, - y = 0.0 | nbody_system.length, - z = 0.0 | nbody_system.length, - vx = 0.0 | nbody_system.speed, - vy = 0.0 | nbody_system.speed, - vz = 0.0 | nbody_system.speed, - mass = 0.01 | nbody_system.mass, - - )) + x=x0, + y=0.0 | nbody_system.length, + z=0.0 | nbody_system.length, + vx=0.0 | nbody_system.speed, + vy=0.0 | nbody_system.speed, + vz=0.0 | nbody_system.speed, + mass=0.01 | nbody_system.mass, + + )) p2 = instance.star_particles.add_particle(datamodel.Particle( - x = 10| nbody_system.length, - y = 0.0 | nbody_system.length, - z = 0.0 | nbody_system.length, - vx = 0.0 | nbody_system.speed, - vy = 0.0 | nbody_system.speed, - vz = 0.0 | nbody_system.speed, - mass = 100 | nbody_system.mass, - - )) + x=10 | nbody_system.length, + y=0.0 | nbody_system.length, + z=0.0 | nbody_system.length, + vx=0.0 | nbody_system.speed, + vy=0.0 | nbody_system.speed, + vz=0.0 | nbody_system.speed, + mass=100 | nbody_system.mass, + + )) instance.commit_particles() e0 = instance.kinetic_energy + instance.potential_energy print("e0:", e0) for i in range(10): p3 = instance.star_particles.add_particle(datamodel.Particle( - x = 100| nbody_system.length, - y = 0.0 | nbody_system.length, - z = 0.0 | nbody_system.length, - vx = 0.0 | nbody_system.speed, - vy = 0.0 | nbody_system.speed, - vz = 0.0 | nbody_system.speed, - mass = 100 | nbody_system.mass, - - )) + x=100 | nbody_system.length, + y=0.0 | nbody_system.length, + z=0.0 | nbody_system.length, + vx=0.0 | nbody_system.speed, + vy=0.0 | nbody_system.speed, + vz=0.0 | nbody_system.speed, + mass=100 | nbody_system.mass, + + )) instance.recommit_particles() instance.star_particles.remove_particle(p3) instance.recommit_particles() - #run more than one innerloop step in fi - instance.evolve_model(0.5|nbody_system.time) - + # run more than one innerloop step in fi + instance.evolve_model(0.5 | nbody_system.time) + e1 = instance.kinetic_energy + instance.potential_energy self.assertAlmostRelativeEquals(e0, e1, 4) print(instance.star_particles[0].position.x) - - self.assertAlmostRelativeEquals(instance.star_particles[0].position.x, 0.588896329162| nbody_system.length, 12) - - instance.evolve_model(1.0|nbody_system.time) + + self.assertAlmostRelativeEquals(instance.star_particles[0].position.x, 0.588896329162 | nbody_system.length, 12) + + instance.evolve_model(1.0 | nbody_system.time) e2 = instance.kinetic_energy + instance.potential_energy - self.assertAlmostRelativeEquals(e0, e2,4) + self.assertAlmostRelativeEquals(e0, e2, 4) self.assertAlmostRelativeEquals(instance.star_particles[0].position.x, 1.06493331332 | nbody_system.length, 11) - - + def test31(self): - instance=Fi() + instance = Fi() instance.initialize_code() instance.parameters.use_hydro_flag = 0 instance.parameters.self_gravity_flag = 0 instance.parameters.periodic_box_size = 1 | nbody_system.length instance.parameters.timestep = 0.2 | nbody_system.time - + p1 = instance.gas_particles.add_particle(datamodel.Particle( - x = 0.5 | nbody_system.length, - y = 0.0 | nbody_system.length, - z = 0.0 | nbody_system.length, - vx = 1.0 | nbody_system.speed, - vy = 0.0 | nbody_system.speed, - vz = 0.0 | nbody_system.speed, - mass = 0.1 | nbody_system.mass, - u = 0.0 | nbody_system.potential - - )) + x=0.5 | nbody_system.length, + y=0.0 | nbody_system.length, + z=0.0 | nbody_system.length, + vx=1.0 | nbody_system.speed, + vy=0.0 | nbody_system.speed, + vz=0.0 | nbody_system.speed, + mass=0.1 | nbody_system.mass, + u=0.0 | nbody_system.potential + + )) p2 = instance.gas_particles.add_particle(datamodel.Particle( - x = 0.1 | nbody_system.length, - y = 0.0 | nbody_system.length, - z = 0.0 | nbody_system.length, - vx = 0.0 | nbody_system.speed, - vy = 0.0 | nbody_system.speed, - vz = 0.0 | nbody_system.speed, - mass = 0.001 | nbody_system.mass, - u = 0.0 | nbody_system.potential - - )) - - instance.evolve_model(0.1 |nbody_system.time) + x=0.1 | nbody_system.length, + y=0.0 | nbody_system.length, + z=0.0 | nbody_system.length, + vx=0.0 | nbody_system.speed, + vy=0.0 | nbody_system.speed, + vz=0.0 | nbody_system.speed, + mass=0.001 | nbody_system.mass, + u=0.0 | nbody_system.potential + + )) + + instance.evolve_model(0.1 | nbody_system.time) instance.synchronize_model() self.assertEqual(len(instance.gas_particles), 2) - + self.assertAlmostRelativeEquals(instance.gas_particles[0].x, 0.5 | nbody_system.length) - instance.evolve_model(0.15 |nbody_system.time) + instance.evolve_model(0.15 | nbody_system.time) instance.synchronize_model() self.assertEqual(len(instance.gas_particles), 1) self.assertEqual(instance.gas_particles.mass, [0.001] | nbody_system.mass) self.assertEqual(instance.gas_particles[0].mass, 0.001 | nbody_system.mass) self.assertAlmostRelativeEquals(instance.gas_particles[0].x, 0.1 | nbody_system.length) self.assertAlmostRelativeEquals(instance.gas_particles.x, [0.1] | nbody_system.length) - + def test32(self): print("Testing Fi get_hydro_state_at_point in periodic mode") gas = datamodel.Particles(8000) gas.mass = 1.0e10/8000 | units.MSun - x,y,z = numpy.mgrid[-1:0.9:20j, -1:0.9:20j, -1:0.9:20j] | units.kpc + x, y, z = numpy.mgrid[-1:0.9:20j, -1:0.9:20j, -1:0.9:20j] | units.kpc gas.x, gas.y, gas.z = x.flatten(), y.flatten(), z.flatten() gas.velocity = [0, 0, 0] | units.m / units.s gas.u = (1 + 0.8 * numpy.sin(gas.x * (numpy.pi | units.kpc**-1))) | nbody_system.specific_energy - - instance = Fi(nbody_system.nbody_to_si(1.0|units.km/units.s, 1.0|units.kpc), mode='periodic', redirection="none") + + instance = Fi(nbody_system.nbody_to_si(1.0 | units.km/units.s, 1.0 | units.kpc), mode='periodic', redirection="none") instance.parameters.self_gravity_flag = False instance.parameters.periodic_box_size = 2.0 | units.kpc instance.gas_particles.add_particles(gas) - + self.assertAlmostRelativeEqual(instance.gas_particles.total_mass(), 1.0e10 | units.MSun, 3) self.assertAlmostRelativeEqual(instance.thermal_energy, 1.0e10 | units.MSun * units.km**2 * units.s**-2, 3) - + number_of_points = 100 in_domain = numpy.linspace(-1.0, 1.0, 100) | units.kpc domain_border = numpy.ones(100) | units.kpc @@ -1683,30 +1670,28 @@ def test32(self): state_right = instance.get_hydro_state_at_point(domain_border, in_domain, in_domain) for var_left, var_right in zip(state_left, state_right): self.assertAlmostRelativeEqual(var_left, var_right, 10) - + state_back = instance.get_hydro_state_at_point(in_domain, -domain_border, in_domain) state_front = instance.get_hydro_state_at_point(in_domain, domain_border, in_domain) for var_front, var_back in zip(state_front, state_back): self.assertAlmostRelativeEqual(var_front, var_back, 10) - + state_bottom = instance.get_hydro_state_at_point(in_domain, in_domain, -domain_border) state_top = instance.get_hydro_state_at_point(in_domain, in_domain, domain_border) for var_top, var_bottom in zip(state_top, state_bottom): self.assertAlmostRelativeEqual(var_top, var_bottom, 10) - + self.assertAlmostRelativeEqual(state_left[0].mean(), 1.25e9 | units.MSun * units.kpc**-3, 2) self.assertAlmostRelativeEqual(state_back[0].mean(), 1.25e9 | units.MSun * units.kpc**-3, 2) self.assertAlmostRelativeEqual(state_bottom[0].mean(), 1.25e9 | units.MSun * units.kpc**-3, 2) - + self.assertAlmostRelativeEqual(state_left[4].mean(), 1.25e9 | units.MSun * units.kpc**-3 * units.km**2 * units.s**-2, 2) self.assertAlmostRelativeEqual(state_back[4].mean(), 1.25e9 | units.MSun * units.kpc**-3 * units.km**2 * units.s**-2, 2) self.assertAlmostRelativeEqual(state_bottom[4].mean(), 1.25e9 | units.MSun * units.kpc**-3 * units.km**2 * units.s**-2, 2) - + # With x=cst, variations in u (and therefore in rhoe) should be small self.assertAlmostEqual(state_left[4].std() / (1.25e9 | units.MSun * units.kpc**-3 * units.km**2 * units.s**-2), 0.0, 2) # Over the entire x domain, variations in rhoe should equal the sine amplitude (=0.8) times the rms(sine) over a whole period (=sqrt(.5)) self.assertAlmostEqual(state_back[4].std() / (1.25e9 | units.MSun * units.kpc**-3 * units.km**2 * units.s**-2), 0.8 * numpy.sqrt(0.5), 1) self.assertAlmostEqual(state_bottom[4].std() / (1.25e9 | units.MSun * units.kpc**-3 * units.km**2 * units.s**-2), 0.8 * numpy.sqrt(0.5), 1) instance.stop() - - diff --git a/src/amuse/test/suite/codes_tests/test_gadget2.py b/src/amuse/test/suite/codes_tests/test_gadget2.py index 36b10ebf2c..8a2db093d5 100644 --- a/src/amuse/test/suite/codes_tests/test_gadget2.py +++ b/src/amuse/test/suite/codes_tests/test_gadget2.py @@ -26,14 +26,15 @@ HAS_MATPLOTLIB = False default_options = dict(number_of_workers=1) -#default_options = dict(number_of_workers=2, redirection="none") +# default_options = dict(number_of_workers=2, redirection="none") # ... but never use (number_of_workers>1) for tests with only a few particles: few_particles_default_options = dict() -#few_particles_default_options = dict(redirection="none") +# few_particles_default_options = dict(redirection="none") testing_isotherm_no_gravity = False + class TestGadget2Interface(TestWithMPI): def test1(self): @@ -61,7 +62,7 @@ def test3(self): self.assertEqual(0, instance.set_gadget_output_directory(instance.get_output_directory())) self.assertEqual(0, instance.commit_parameters()) self.assertEqual([1, 0], list(instance.new_dm_particle(0.01, 1, 0, 0, 0, 1, 0).values())) - self.assertEqual([2, 0], list(instance.new_dm_particle(0.01, -1, 0, 0, 0,-1, 0).values())) + self.assertEqual([2, 0], list(instance.new_dm_particle(0.01, -1, 0, 0, 0, -1, 0).values())) self.assertEqual(-1, instance.get_index_of_first_particle()['__result']) self.assertEqual(0, instance.commit_particles()) self.assertEqual([1, 0], list(instance.get_index_of_first_particle().values())) @@ -75,7 +76,7 @@ def test3a(self): instance = Gadget2Interface(**few_particles_default_options) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.set_gadget_output_directory(instance.get_output_directory())) - #cgs + # cgs instance.set_unit_mass(0.001) instance.set_unit_length(1.0) instance.set_unit_time(122404.614048) @@ -84,9 +85,9 @@ def test3a(self): self.assertEqual([2, 0], list(instance.new_dm_particle(1., -1, 0, 0, 0, 0, 0).values())) self.assertEqual(0, instance.commit_particles()) if testing_isotherm_no_gravity: - self.assertAlmostEqual(0.000 , instance.get_potential(1)['Potential'], places=1) + self.assertAlmostEqual(0.000, instance.get_potential(1)['Potential'], places=1) else: - self.assertAlmostEqual(-0.500 , instance.get_potential(1)['Potential'], places=1) + self.assertAlmostEqual(-0.500, instance.get_potential(1)['Potential'], places=1) self.assertEqual(0, instance.cleanup_code()) instance.stop() @@ -96,33 +97,33 @@ def test4(self): self.assertEqual(0, instance.set_gadget_output_directory(instance.get_output_directory())) self.assertEqual(0, instance.commit_parameters()) self.assertEqual([1, 0], list(instance.new_dm_particle(0.01, 1, 0, 0, 0, 1, 0).values())) - self.assertEqual([2, 0], list(instance.new_dm_particle(0.02, -1, 0, 0, 0,-1, 0).values())) + self.assertEqual([2, 0], list(instance.new_dm_particle(0.02, -1, 0, 0, 0, -1, 0).values())) self.assertEqual(-3, instance.get_mass(1)['__result']) self.assertEqual(0, instance.commit_particles()) mass, result = instance.get_mass(1) - self.assertAlmostEqual(0.01,mass) - self.assertEqual(0,result) + self.assertAlmostEqual(0.01, mass) + self.assertEqual(0, result) mass, result = instance.get_mass(2) - self.assertAlmostEqual(0.02,mass) - self.assertEqual(0,result) + self.assertAlmostEqual(0.02, mass) + self.assertEqual(0, result) self.assertEqual(-3, instance.get_mass(3)['__result']) - for result,expected in zip(instance.get_position(1),[1,0,0, 0]): - self.assertAlmostEqual(result,expected) - for result,expected in zip(instance.get_position(2),[-1,0,0, 0]): - self.assertAlmostEqual(result,expected) - for result,expected in zip(instance.get_velocity(1),[0,1,0, 0]): - self.assertAlmostEqual(result,expected) - for result,expected in zip(instance.get_velocity(2),[0,-1,0, 0]): - self.assertAlmostEqual(result,expected) - - self.assertEqual(0, instance.set_state(1, 0.01, 1,2,3, 4,5,6)) - self.assertEqual([0.01, 1.0,2.0,3.0, 4.0,5.0,6.0, 0], list(instance.get_state(1).values())) + for result, expected in zip(instance.get_position(1), [1, 0, 0, 0]): + self.assertAlmostEqual(result, expected) + for result, expected in zip(instance.get_position(2), [-1, 0, 0, 0]): + self.assertAlmostEqual(result, expected) + for result, expected in zip(instance.get_velocity(1), [0, 1, 0, 0]): + self.assertAlmostEqual(result, expected) + for result, expected in zip(instance.get_velocity(2), [0, -1, 0, 0]): + self.assertAlmostEqual(result, expected) + + self.assertEqual(0, instance.set_state(1, 0.01, 1, 2, 3, 4, 5, 6)) + self.assertEqual([0.01, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0], list(instance.get_state(1).values())) self.assertEqual(0, instance.evolve_model(0.01)) mass, result = instance.get_mass(1) - self.assertAlmostEqual(0.01,mass) - self.assertEqual(0,result) + self.assertAlmostEqual(0.01, mass) + self.assertEqual(0, result) self.assertEqual(0, instance.cleanup_code()) instance.stop() @@ -133,9 +134,9 @@ def test5(self): self.assertEqual(0, instance.commit_parameters()) target_number_of_particles = 100 evrard = MakeEvrardTest(target_number_of_particles) - mass, x,y,z, vx,vy,vz, u = evrard.new_model() + mass, x, y, z, vx, vy, vz, u = evrard.new_model() number_of_particles = len(mass) - indices, results = instance.new_sph_particle(mass,x,y,z,vx,vy,vz,u) + indices, results = instance.new_sph_particle(mass, x, y, z, vx, vy, vz, u) self.assertEqual([0 for i in range(number_of_particles)], list(results)) self.assertEqual([i+1 for i in range(number_of_particles)], list(indices)) self.assertEqual(0, instance.commit_particles()) @@ -150,17 +151,17 @@ def test6(self): self.assertEqual(0, instance.commit_parameters()) target_number_of_particles = 100 evrard = MakeEvrardTest(target_number_of_particles) - mass, x,y,z, vx,vy,vz, u = evrard.new_model() + mass, x, y, z, vx, vy, vz, u = evrard.new_model() number_of_particles = len(mass) first_half = number_of_particles//2 - indices, results = instance.new_sph_particle(mass[:first_half],x[:first_half],y[:first_half],z[:first_half], - vx[:first_half],vy[:first_half],vz[:first_half],u[:first_half]) + indices, results = instance.new_sph_particle(mass[:first_half], x[:first_half], y[:first_half], z[:first_half], + vx[:first_half], vy[:first_half], vz[:first_half], u[:first_half]) self.assertEqual([0 for i in range(first_half)], list(results)) self.assertEqual([i+1 for i in range(first_half)], list(indices)) self.assertEqual([number_of_particles/2+1, 0], list(instance.new_dm_particle(0.01, 1, 0, 0, 0, 1, 0).values())) - self.assertEqual([number_of_particles/2+2, 0], list(instance.new_dm_particle(0.02, -1, 0, 0, 0,-1, 0).values())) - indices, results = instance.new_sph_particle(mass[first_half:],x[first_half:],y[first_half:],z[first_half:], - vx[first_half:],vy[first_half:],vz[first_half:],u[first_half:]) + self.assertEqual([number_of_particles/2+2, 0], list(instance.new_dm_particle(0.02, -1, 0, 0, 0, -1, 0).values())) + indices, results = instance.new_sph_particle(mass[first_half:], x[first_half:], y[first_half:], z[first_half:], + vx[first_half:], vy[first_half:], vz[first_half:], u[first_half:]) self.assertEqual([0 for i in range(number_of_particles-first_half)], list(results)) self.assertEqual([first_half+i+1+2 for i in range(number_of_particles-first_half)], list(indices)) self.assertEqual(0, instance.commit_particles()) @@ -186,25 +187,25 @@ def test7(self): self.assertEqual(0, instance.commit_parameters()) target_number_of_particles = 100 evrard = MakeEvrardTest(target_number_of_particles) - mass, x,y,z, vx,vy,vz, u = evrard.new_model() + mass, x, y, z, vx, vy, vz, u = evrard.new_model() number_of_particles = len(mass) - indices, results = instance.new_sph_particle(mass,x,y,z,vx,vy,vz,u) + indices, results = instance.new_sph_particle(mass, x, y, z, vx, vy, vz, u) self.assertEqual([0 for i in range(number_of_particles)], list(results)) self.assertEqual([i+1 for i in range(number_of_particles)], list(indices)) self.assertEqual([number_of_particles+1, 0], list(instance.new_dm_particle(0.01, 1, 0, 0, 0, 1, 0).values())) - self.assertEqual([number_of_particles+2, 0], list(instance.new_dm_particle(0.02, -1, 0, 0, 0,-1, 0).values())) + self.assertEqual([number_of_particles+2, 0], list(instance.new_dm_particle(0.02, -1, 0, 0, 0, -1, 0).values())) self.assertEqual(0, instance.commit_particles()) self.assertEqual(0, instance.evolve_model(0.001)) self.assertEqual(0, instance.delete_particle(number_of_particles-1)) self.assertEqual(0, instance.delete_particle(number_of_particles+1)) self.assertEqual(-3, instance.delete_particle(number_of_particles-1)) - indices, results = instance.new_sph_particle(mass,x,y,z,vx,vy,vz,u) - self.assertEqual([2*number_of_particles+3, 0], list(instance.new_dm_particle(0.02, -1, 0, 0, 0,-1, 0).values())) + indices, results = instance.new_sph_particle(mass, x, y, z, vx, vy, vz, u) + self.assertEqual([2*number_of_particles+3, 0], list(instance.new_dm_particle(0.02, -1, 0, 0, 0, -1, 0).values())) self.assertEqual(0, instance.recommit_particles()) mass_list = [x for sublist in [mass[:number_of_particles-2], [mass[number_of_particles-1], 0.02], mass, [0.02]] for x in sublist] - index_list = [x for sublist in [list(range(1,number_of_particles-1)), [number_of_particles], - list(range(number_of_particles+2,2*number_of_particles+4))] for x in sublist] + index_list = [x for sublist in [list(range(1, number_of_particles-1)), [number_of_particles], + list(range(number_of_particles+2, 2*number_of_particles+4))] for x in sublist] index, result = list(instance.get_index_of_first_particle().values()) self.assertEqual([index_list[0], 0], [index, result]) for i in range(1, 2*number_of_particles+1): @@ -217,122 +218,120 @@ def test7(self): self.assertEqual(0, instance.evolve_model(0.001)) self.assertEqual(0, instance.cleanup_code()) instance.stop() - + def test8(self): instance = Gadget2Interface(**few_particles_default_options) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.set_gadget_output_directory(instance.get_output_directory())) self.assertEqual(0, instance.commit_parameters()) - for i in range(1,10): + for i in range(1, 10): self.assertEqual([i, 0], list(instance.new_dm_particle(i*0.01, i, -i, 0, -i*10, i*10, 0).values())) self.assertEqual(0, instance.commit_particles()) - - for i in range(1,10): + + for i in range(1, 10): mass, result = instance.get_mass(i) - self.assertAlmostEqual(0.01*i,mass) - self.assertEqual(0,result) - + self.assertAlmostEqual(0.01*i, mass) + self.assertEqual(0, result) + x, y, z, result = instance.get_position(i) self.assertAlmostEqual(i, x) self.assertAlmostEqual(-i, y) self.assertAlmostEqual(0, z) - self.assertEqual(0,result) - + self.assertEqual(0, result) + vx, vy, vz, result = instance.get_velocity(i) self.assertAlmostEqual(-i*10, vx) self.assertAlmostEqual(i*10, vy) self.assertAlmostEqual(0, vz) - self.assertEqual(0,result) - + self.assertEqual(0, result) + self.assertEqual(0, instance.set_mass(i, i*0.1)) mass, result = instance.get_mass(i) - self.assertAlmostEqual(0.1*i,mass) - self.assertEqual(0,result) - + self.assertAlmostEqual(0.1*i, mass) + self.assertEqual(0, result) + self.assertEqual(0, instance.set_position(i, 2*i, -2*i, 0)) x, y, z, result = instance.get_position(i) self.assertAlmostEqual(2*i, x) self.assertAlmostEqual(-2*i, y) self.assertAlmostEqual(0, z) - self.assertEqual(0,result) - + self.assertEqual(0, result) + self.assertEqual(0, instance.set_velocity(i, -i*20, i*20, 0)) vx, vy, vz, result = instance.get_velocity(i) self.assertAlmostEqual(-i*20, vx) self.assertAlmostEqual(i*20, vy) self.assertAlmostEqual(0, vz) - self.assertEqual(0,result) - + self.assertEqual(0, result) + self.assertEqual(0, instance.cleanup_code()) instance.stop() - def test9(self): - instance = Gadget2Interface(mode = Gadget2Interface.MODE_PERIODIC_NOGRAVITY, + instance = Gadget2Interface(mode=Gadget2Interface.MODE_PERIODIC_NOGRAVITY, **few_particles_default_options) instance.initialize_code() instance.set_min_size_timestep(1.0) instance.set_gadget_output_directory(instance.get_output_directory()) - + instance.set_box_size(2.) value, error = instance.get_box_size() self.assertEqual(error, 0) self.assertEqual(value, 2.) - - self.assertEqual(instance.get_periodic_boundaries_flag()['value'], True) - self.assertEqual(instance.set_periodic_boundaries_flag(True),-2) # read-only + + self.assertEqual(instance.get_periodic_boundaries_flag()['value'], True) + self.assertEqual(instance.set_periodic_boundaries_flag(True), -2) # read-only self.assertEqual(instance.get_nogravity()['no_gravity_flag'], True) self.assertEqual(instance.commit_parameters(), 0) - ids,err=instance.new_particle( - [1.0,1.0,1.0], - [0.5,0.0,0.0], - [0.0,-0.5,0.0], - [0.0,0.0,0.5], - [-1.0,0.0,0.0], - [0.0,1.0,0.0], - [0.0,0.0,-1.0]) + ids, err = instance.new_particle( + [1.0, 1.0, 1.0], + [0.5, 0.0, 0.0], + [0.0, -0.5, 0.0], + [0.0, 0.0, 0.5], + [-1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, -1.0]) instance.commit_particles() - m,x,y,z,vx,vy,vz,err=instance.get_state(ids) - self.assertAlmostEqual(x, [0.5,0.,0.], places=6) - self.assertAlmostEqual(y, [0.,-0.5,0.], places=6) - self.assertAlmostEqual(z, [0.,0.,0.5], places=6) + m, x, y, z, vx, vy, vz, err = instance.get_state(ids) + self.assertAlmostEqual(x, [0.5, 0., 0.], places=6) + self.assertAlmostEqual(y, [0., -0.5, 0.], places=6) + self.assertAlmostEqual(z, [0., 0., 0.5], places=6) instance.evolve_model(0.1) - m,x,y,z,vx,vy,vz,err=instance.get_state(ids) - self.assertAlmostEqual(x, [0.4,0.,0.], places=6) - self.assertAlmostEqual(y, [0.,-0.4,0.], places=6) - self.assertAlmostEqual(z, [0.,0.,0.4], places=6) - + m, x, y, z, vx, vy, vz, err = instance.get_state(ids) + self.assertAlmostEqual(x, [0.4, 0., 0.], places=6) + self.assertAlmostEqual(y, [0., -0.4, 0.], places=6) + self.assertAlmostEqual(z, [0., 0., 0.4], places=6) + instance.evolve_model(1.0) - m,x,y,z,vx,vy,vz,err=instance.get_state(ids) - self.assertAlmostEqual(x, [-0.5,0.,0.], places=6) - self.assertAlmostEqual(y, [0.,0.5,0.], places=6) - self.assertAlmostEqual(z, [0.,0.,-0.5], places=6) + m, x, y, z, vx, vy, vz, err = instance.get_state(ids) + self.assertAlmostEqual(x, [-0.5, 0., 0.], places=6) + self.assertAlmostEqual(y, [0., 0.5, 0.], places=6) + self.assertAlmostEqual(z, [0., 0., -0.5], places=6) instance.cleanup_code() instance.stop() - - instance = Gadget2Interface(mode = Gadget2Interface.MODE_NORMAL, - **few_particles_default_options) # MODE_NORMAL is default: non-periodic + + instance = Gadget2Interface(mode=Gadget2Interface.MODE_NORMAL, + **few_particles_default_options) # MODE_NORMAL is default: non-periodic instance.initialize_code() instance.set_gadget_output_directory(instance.get_output_directory()) - - self.assertEqual(instance.get_periodic_boundaries_flag()['value'], False) # default, has to be changed for periodic runs + + self.assertEqual(instance.get_periodic_boundaries_flag()['value'], False) # default, has to be changed for periodic runs self.assertEqual(instance.commit_parameters(), 0) - self.assertEqual(instance.set_periodic_boundaries_flag(True), -2) # read-only + self.assertEqual(instance.set_periodic_boundaries_flag(True), -2) # read-only instance.stop() - - + def test10(self): instance = Gadget2Interface(**few_particles_default_options) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.set_gadget_output_directory(instance.get_output_directory())) self.assertEqual(0, instance.commit_parameters()) - + indices_and_value = [] for i in range(10): - index, error = instance.new_sph_particle(0.1, i,0,0, 0,0,0, 0.0) + index, error = instance.new_sph_particle(0.1, i, 0, 0, 0, 0, 0, 0.0) self.assertEqual(0, error) indices_and_value.append((index, i)) - + instance.commit_particles() for i, value in indices_and_value: x, y, z, error = instance.get_position(i) @@ -340,41 +339,40 @@ def test10(self): self.assertEqual(x, value) self.assertEqual(y, 0) self.assertEqual(z, 0) - - + self.assertEqual(0, error) - for i in range(10,20): - index, error = instance.new_sph_particle(0.1, i,0,0, 0,0,0, 0.0) + for i in range(10, 20): + index, error = instance.new_sph_particle(0.1, i, 0, 0, 0, 0, 0, 0.0) self.assertEqual(0, error) indices_and_value.append((index, i)) - + error = instance.recommit_particles() self.assertEqual(0, error) - + for i, value in indices_and_value: x, y, z, error = instance.get_position(i) self.assertEqual(0, error) self.assertEqual(x, value) self.assertEqual(y, 0) self.assertEqual(z, 0) - + instance.stop() - - + + class TestGadget2(TestWithMPI): classname = "" UnitLength = 3.085678e21 | units.cm # ~ 1.0 kpc UnitMass = 1.989e43 | units.g # 1.0e10 solar masses - UnitVelocity = 1e5 | units.cm / units.s # 1 km/sec + UnitVelocity = 1e5 | units.cm / units.s # 1 km/sec default_converter = generic_unit_converter.ConvertBetweenGenericAndSiUnits(UnitLength, UnitMass, UnitVelocity) default_convert_nbody = nbody_system.nbody_to_si(UnitLength, UnitMass) - + three_particles_IC = Particles(3) - three_particles_IC.position = [[0.5, 0.0, 0.0], [0.0,-0.5, 0.0], [0.0, 0.0, 0.5]] | units.kpc - three_particles_IC.velocity =[[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0,-1.0]] | units.km / units.s + three_particles_IC.position = [[0.5, 0.0, 0.0], [0.0, -0.5, 0.0], [0.0, 0.0, 0.5]] | units.kpc + three_particles_IC.velocity = [[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]] | units.km / units.s three_particles_IC.mass = 1.0e10 | units.MSun - + def test1(self): print("Testing Gadget initialization") instance = Gadget2(self.default_converter, **default_options) @@ -413,8 +411,8 @@ def test3(self): dark = Particles(2) dark.mass = [0.4, 0.4] | generic_unit_system.mass - dark.position = [[0.0,0.0,0.0], [1.0,0.0,0.0]] | units.kpc - dark.velocity = [[100.0,100.0,100.0], [1.0,1.0,1.0]] | units.km / units.s + dark.position = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]] | units.kpc + dark.velocity = [[100.0, 100.0, 100.0], [1.0, 1.0, 1.0]] | units.km / units.s dark.radius = [0.0, 0.0] | units.RSun instance.dm_particles.add_particles(dark) @@ -439,7 +437,7 @@ def test4(self): def test5(self): print("Test 5: testing SPH particles") target_number_sph_particles = 100 - gas = new_evrard_gas_sphere(target_number_sph_particles, self.default_convert_nbody, seed = 1234) + gas = new_evrard_gas_sphere(target_number_sph_particles, self.default_convert_nbody, seed=1234) instance = Gadget2(self.default_converter, **default_options) instance.initialize_code() instance.gas_particles.add_particles(gas) @@ -449,12 +447,12 @@ def test5(self): def test6(self): print("Test 6: testing dark matter + SPH particles") target_number_sph_particles = 100 - gas = new_evrard_gas_sphere(target_number_sph_particles, self.default_convert_nbody, seed = 1234) + gas = new_evrard_gas_sphere(target_number_sph_particles, self.default_convert_nbody, seed=1234) dark = Particles(2) dark.mass = [0.4, 0.4] | generic_unit_system.mass - dark.position = [[0.0,0.0,0.0], [1.0,0.0,0.0]] | units.kpc - dark.velocity = [[100.0,100.0,100.0], [1.0,1.0,1.0]] | units.km / units.s + dark.position = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]] | units.kpc + dark.velocity = [[100.0, 100.0, 100.0], [1.0, 1.0, 1.0]] | units.km / units.s instance = Gadget2(self.default_converter, **default_options) instance.dm_particles.add_particles(dark) @@ -466,63 +464,62 @@ def test7(self): print("Testing more Gadget parameters") instance = Gadget2(self.default_converter, **default_options) instance.initialize_code() - - for par, value in [('gadget_cell_opening_flag', True), - ('comoving_integration_flag', False), + + for par, value in [('gadget_cell_opening_flag', True), + ('comoving_integration_flag', False), ('interpret_kicks_as_feedback', False), ('interpret_heat_as_feedback', True)]: self.assertTrue(value is getattr(instance.parameters, par)) setattr(instance.parameters, par, not value) self.assertFalse(value is getattr(instance.parameters, par)) - + for par, value in [('time_limit_cpu', 36000 | units.s), ('min_gas_temp', 0.0 | units.K)]: self.assertEqual(value, getattr(instance.parameters, par)) setattr(instance.parameters, par, 2 * value) self.assertEqual(2 * value, getattr(instance.parameters, par)) - - for par, value in [('n_smooth_tol',0.1), ('n_smooth',50), ('opening_angle',0.5), - ('gadget_cell_opening_constant',0.005), ('artificial_viscosity_alpha',0.5), - ('courant',0.3), ('type_of_timestep_criterion',0), ('hubble_parameter', 0.7), - ('omega_zero',0.0), ('omega_lambda',0.0), ('omega_baryon',0.0), - ('min_gas_hsmooth_fractional',0.0), ('timestep_accuracy_parameter',0.025), - ('tree_domain_update_frequency',0.05),('artificial_viscosity_beta',1.0)]: + + for par, value in [('n_smooth_tol', 0.1), ('n_smooth', 50), ('opening_angle', 0.5), + ('gadget_cell_opening_constant', 0.005), ('artificial_viscosity_alpha', 0.5), + ('courant', 0.3), ('type_of_timestep_criterion', 0), ('hubble_parameter', 0.7), + ('omega_zero', 0.0), ('omega_lambda', 0.0), ('omega_baryon', 0.0), + ('min_gas_hsmooth_fractional', 0.0), ('timestep_accuracy_parameter', 0.025), + ('tree_domain_update_frequency', 0.05), ('artificial_viscosity_beta', 1.0)]: self.assertEqual(value, getattr(instance.parameters, par)) setattr(instance.parameters, par, 1) self.assertEqual(1, getattr(instance.parameters, par)) - - for par, value in [('gas_epsilon', 0.01 | generic_unit_system.length), - ('begin_time', 0.0 | generic_unit_system.time), - ('time_max', 100.0 | generic_unit_system.time), - ('max_size_timestep', 0.01 | generic_unit_system.time), - ('min_size_timestep', 0.0 | generic_unit_system.time), + + for par, value in [('gas_epsilon', 0.01 | generic_unit_system.length), + ('begin_time', 0.0 | generic_unit_system.time), + ('time_max', 100.0 | generic_unit_system.time), + ('max_size_timestep', 0.01 | generic_unit_system.time), + ('min_size_timestep', 0.0 | generic_unit_system.time), ('periodic_box_size', 1.0 | generic_unit_system.length), ('time_between_statistics', 0.1 | generic_unit_system.time), ('softening_gas_max_phys', 0.0 | generic_unit_system.length), ('softening_halo_max_phys', 0.0 | generic_unit_system.length)]: - self.assertEqual(instance.unit_converter.to_si(value), + self.assertEqual(instance.unit_converter.to_si(value), getattr(instance.parameters, par)) setattr(instance.parameters, par, 3.0 | value.unit) self.assertEqual(instance.unit_converter.to_si(3.0 | value.unit), getattr(instance.parameters, par)) - - for par, value in [('energy_file',"energy.txt"),('info_file',"info.txt"), - ('timings_file',"timings.txt"),('cpu_file',"cpu.txt")]: + + for par, value in [('energy_file', "energy.txt"), ('info_file', "info.txt"), + ('timings_file', "timings.txt"), ('cpu_file', "cpu.txt")]: self.assertEqual(value, getattr(instance.parameters, par)) setattr(instance.parameters, par, 'test.txt') self.assertEqual("test.txt", getattr(instance.parameters, par)) - - + instance.stop() def test8(self): print("Testing read-only Gadget parameters") - + def try_set_parameter(par, value, instance): setattr(instance.parameters, par, value) - + instance = Gadget2(self.default_converter, **default_options) instance.initialize_code() - for par, value in [ ('no_gravity_flag', testing_isotherm_no_gravity), + for par, value in [('no_gravity_flag', testing_isotherm_no_gravity), ('isothermal_flag', testing_isotherm_no_gravity), ('eps_is_h_flag', False), ('periodic_boundaries_flag', False), @@ -533,22 +530,22 @@ def try_set_parameter(par, value, instance): ('polytropic_index_gamma', (1.0 if testing_isotherm_no_gravity else 5.0/3))]: self.assertEqual(value, getattr(instance.parameters, par)) self.assertRaises(AmuseException, try_set_parameter, par, value, instance, - expected_message = "Could not set value for parameter '"+par+"' of a 'Gadget2' object, " + expected_message="Could not set value for parameter '"+par+"' of a 'Gadget2' object, " "parameter is read-only") instance.stop() - + instance = Gadget2(self.default_converter, mode="nogravity", **default_options) instance.initialize_code() self.assertEqual(instance.parameters.no_gravity_flag, True) self.assertRaises(AmuseException, try_set_parameter, 'no_gravity_flag', False, instance, - expected_message = "Could not set value for parameter 'no_gravity_flag' of a 'Gadget2' object, " + expected_message="Could not set value for parameter 'no_gravity_flag' of a 'Gadget2' object, " "parameter is read-only") instance.stop() def test9(self): print("Testing Gadget properties") target_number_of_particles = 100 - gas = new_evrard_gas_sphere(target_number_of_particles, self.default_convert_nbody, do_scale=True, seed = 1234) + gas = new_evrard_gas_sphere(target_number_of_particles, self.default_convert_nbody, do_scale=True, seed=1234) instance = Gadget2(self.default_converter, **default_options) instance.gas_particles.add_particles(gas) self.assertEqual(instance.model_time, 0.0 | units.s) @@ -567,11 +564,11 @@ def test9(self): def test10(self): print("Testing Gadget states") target_number_sph_particles = 100 - gas = new_evrard_gas_sphere(target_number_sph_particles, self.default_convert_nbody, seed = 1234) + gas = new_evrard_gas_sphere(target_number_sph_particles, self.default_convert_nbody, seed=1234) dark = Particles(2) dark.mass = [0.4, 0.4] | generic_unit_system.mass - dark.position = [[0.0,0.0,0.0], [1.0,0.0,0.0]] | units.kpc - dark.velocity = [[100.0,100.0,100.0], [1.0,1.0,1.0]] | units.km / units.s + dark.position = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]] | units.kpc + dark.velocity = [[100.0, 100.0, 100.0], [1.0, 1.0, 1.0]] | units.km / units.s print("First do everything manually:") instance = Gadget2(self.default_converter, **default_options) @@ -590,7 +587,7 @@ def test10(self): self.assertEqual(instance.get_name_of_current_state(), 'END') instance.stop() - print("commit_parameters(), (re)commit_particles(), and cleanup_code() should be called " \ + print("commit_parameters(), (re)commit_particles(), and cleanup_code() should be called " "automatically before new_xx_particle(), get_xx(), and stop():") instance = Gadget2(self.default_converter, **default_options) self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') @@ -612,13 +609,13 @@ def test10(self): def test11(self): particles = Particles(2) - particles.x = [0.0,10.0] | generic_unit_system.length + particles.x = [0.0, 10.0] | generic_unit_system.length particles.y = 0 | generic_unit_system.length particles.z = 0 | generic_unit_system.length particles.radius = 0.005 | generic_unit_system.length - particles.vx = 0 | generic_unit_system.speed - particles.vy = 0 | generic_unit_system.speed - particles.vz = 0 | generic_unit_system.speed + particles.vx = 0 | generic_unit_system.speed + particles.vy = 0 | generic_unit_system.speed + particles.vz = 0 | generic_unit_system.speed particles.mass = 1.0 | generic_unit_system.mass instance = Gadget2(self.default_converter, **few_particles_default_options) @@ -631,42 +628,42 @@ def test11(self): instance.evolve_model(1.0e15 | units.s) self.assertTrue(instance.stopping_conditions.number_of_steps_detection.is_set()) self.assertTrue(instance.model_time < 1.0e15 | units.s) - + instance.stop() - + def test12(self): print("Testing Gadget get_hydro_state_at_point") number_sph_particles = 100 - gas = new_evrard_gas_sphere(number_sph_particles, self.default_convert_nbody, seed = 1234) + gas = new_evrard_gas_sphere(number_sph_particles, self.default_convert_nbody, seed=1234) instance = Gadget2(self.default_converter, **default_options) instance.parameters.n_smooth = 64 instance.parameters.n_smooth_tol = 1.56250e-2 instance.gas_particles.add_particles(gas) - + coords = [0.0 | units.kpc]*3 hydro_state = instance.get_hydro_state_at_point(*coords) - expected = [ 3.5469e-19 | units.kg * units.m**-3, - 0.0 | units.kg * units.m**-2 / units.s, - 0.0 | units.kg * units.m**-2 / units.s, - 0.0 | units.kg * units.m**-2 / units.s, - (7.6297e-10 if testing_isotherm_no_gravity else + expected = [3.5469e-19 | units.kg * units.m**-3, + 0.0 | units.kg * units.m**-2 / units.s, + 0.0 | units.kg * units.m**-2 / units.s, + 0.0 | units.kg * units.m**-2 / units.s, + (7.6297e-10 if testing_isotherm_no_gravity else 8.4252e-10) | units.kg * units.m**-1 * units.s**-2] for value, expect in zip(hydro_state, expected): self.assertAlmostRelativeEqual(value, expect, places=3) - + coords = [0.1 | units.kpc]*3 hydro_state = instance.get_hydro_state_at_point(*coords) - expected = [ 4.1456e-19 | units.kg * units.m**-3, - 0.0 | units.kg * units.m**-2 / units.s, - 0.0 | units.kg * units.m**-2 / units.s, - 0.0 | units.kg * units.m**-2 / units.s, - (8.9175e-10 if testing_isotherm_no_gravity else + expected = [4.1456e-19 | units.kg * units.m**-3, + 0.0 | units.kg * units.m**-2 / units.s, + 0.0 | units.kg * units.m**-2 / units.s, + 0.0 | units.kg * units.m**-2 / units.s, + (8.9175e-10 if testing_isotherm_no_gravity else 1.0742e-09) | units.kg * units.m**-1 * units.s**-2] for value, expect in zip(hydro_state, expected): self.assertAlmostRelativeEqual(value, expect, places=3) - + instance.stop() - + def test13(self): print("Testing Gadget get_hydro_state_at_point II: uniform sphere") number_sph_particles = 1000 @@ -674,71 +671,71 @@ def test13(self): gas.velocity = [10.0, 20.0, 30.0] | units.km / units.s gas.u = 0.05 | generic_unit_system.specific_energy density = (1.0e10 | units.MSun) / (4.0/3.0 * numpy.pi * (1.0 | units.kpc)**3) - + instance = Gadget2(self.default_converter, **default_options) instance.parameters.n_smooth = 64 instance.parameters.n_smooth_tol = 0.01 instance.gas_particles.add_particles(gas) - + coords = [0.0 | units.kpc]*3 rho, rhovx, rhovy, rhovz, rhoe = instance.get_hydro_state_at_point(*coords) self.assertAlmostRelativeEqual(rho, density, places=3) self.assertAlmostRelativeEqual(rho, max(instance.gas_particles.rho), places=2) - self.assertIsOfOrder( rho, instance.gas_particles.rho) + self.assertIsOfOrder(rho, instance.gas_particles.rho) self.assertAlmostRelativeEqual(rhovx, density*instance.gas_particles[0].vx, places=3) self.assertAlmostRelativeEqual(rhovy, density*instance.gas_particles[0].vy, places=3) self.assertAlmostRelativeEqual(rhovz, density*instance.gas_particles[0].vz, places=3) - self.assertAlmostRelativeEqual(rhoe, density * (instance.gas_particles[0].u + + self.assertAlmostRelativeEqual(rhoe, density * (instance.gas_particles[0].u + 0.5 * instance.gas_particles[0].velocity.length_squared()), places=3) - + coords = [0.1 | units.kpc]*3 rho, rhovx, rhovy, rhovz, rhoe = instance.get_hydro_state_at_point(*coords) self.assertAlmostRelativeEqual(rho, density, places=3) self.assertAlmostRelativeEqual(rhovx, density*instance.gas_particles[0].vx, places=3) self.assertAlmostRelativeEqual(rhovy, density*instance.gas_particles[0].vy, places=3) self.assertAlmostRelativeEqual(rhovz, density*instance.gas_particles[0].vz, places=3) - self.assertAlmostRelativeEqual(rhoe, density * (instance.gas_particles[0].u + + self.assertAlmostRelativeEqual(rhoe, density * (instance.gas_particles[0].u + 0.5 * instance.gas_particles[0].velocity.length_squared()), places=3) instance.stop() - + def test14(self): print("Testing Gadget SPH particle properties") number_sph_particles = 1000 - gas = new_evrard_gas_sphere(number_sph_particles, self.default_convert_nbody, seed = 1234) + gas = new_evrard_gas_sphere(number_sph_particles, self.default_convert_nbody, seed=1234) instance = Gadget2(self.default_converter, **default_options) instance.gas_particles.add_particles(gas) - self.assertEqual(instance.gas_particles.num_neighbours >= + self.assertEqual(instance.gas_particles.num_neighbours >= instance.parameters.n_smooth*(1-instance.parameters.n_smooth_tol), True) - self.assertEqual(instance.gas_particles.num_neighbours <= + self.assertEqual(instance.gas_particles.num_neighbours <= instance.parameters.n_smooth*(1+instance.parameters.n_smooth_tol), True) - self.assertIsOfOrder(instance.gas_particles.h_smooth, - self.default_convert_nbody.to_si(1.0 | nbody_system.length) * + self.assertIsOfOrder(instance.gas_particles.h_smooth, + self.default_convert_nbody.to_si(1.0 | nbody_system.length) * (instance.parameters.n_smooth*1.0/number_sph_particles)**(1.0/3)) - self.assertAlmostRelativeEqual(instance.gas_particles.u, + self.assertAlmostRelativeEqual(instance.gas_particles.u, self.default_convert_nbody.to_si(0.05 | nbody_system.specific_energy)) - + # the density of the cloud scales with 1/r: r_sort, rho_sort = instance.gas_particles.position.lengths().sorted_with(instance.gas_particles.rho) mean_density = self.default_convert_nbody.to_si(3.0/(4.0*numpy.pi) | nbody_system.density) - select = slice(number_sph_particles//2) # select 50% particles closest to center to avoid boundaries + select = slice(number_sph_particles//2) # select 50% particles closest to center to avoid boundaries self.assertIsOfOrder(rho_sort[select]/mean_density, r_sort.mean()/r_sort[select]) - self.assertAlmostEqual(instance.gas_particles.u * instance.gas_particles.rho, + self.assertAlmostEqual(instance.gas_particles.u * instance.gas_particles.rho, 1.5 * instance.gas_particles.pressure) - + self.assertAlmostEqual(instance.gas_particles.du_dt, 0 | units.m**2 * units.s**-3) u_0 = instance.gas_particles.u.sum() instance.evolve_model(0.1 | units.Myr) if testing_isotherm_no_gravity: self.assertAlmostEqual(instance.gas_particles.du_dt, 0 | units.m**2 * units.s**-3) - else: # Collapsing ==> heating: + else: # Collapsing ==> heating: self.assertTrue(instance.gas_particles.du_dt.sum() >= 0 | units.m**2 * units.s**-3) - self.assertIsOfOrder(instance.gas_particles.du_dt.sum() * (0.1 | units.Myr), + self.assertIsOfOrder(instance.gas_particles.du_dt.sum() * (0.1 | units.Myr), instance.gas_particles.u.sum() - u_0) instance.stop() - + def test15a(self): print("Test Gadget2 in periodic nogravity mode") - instance = Gadget2(mode = Gadget2Interface.MODE_PERIODIC_NOGRAVITY, + instance = Gadget2(mode=Gadget2Interface.MODE_PERIODIC_NOGRAVITY, **few_particles_default_options) self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') # 'False' is default, but getting parameters implicitly calls initialize_code()... @@ -748,50 +745,50 @@ def test15a(self): instance.parameters.periodic_box_size = 2.0 | generic_unit_system.length self.assertAlmostEqual(instance.parameters.periodic_box_size, 2.0 | units.kpc, places=6) instance.parameters.min_size_timestep = 1.0 | generic_unit_system.time - + instance.dm_particles.add_particles(self.three_particles_IC) - self.assertAlmostEqual(instance.dm_particles.x, [0.5,0.,0.] | units.kpc, places=6) - self.assertAlmostEqual(instance.dm_particles.y, [0.,-0.5,0.] | units.kpc, places=6) - self.assertAlmostEqual(instance.dm_particles.z, [0.,0.,0.5] | units.kpc, places=6) - + self.assertAlmostEqual(instance.dm_particles.x, [0.5, 0., 0.] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.y, [0., -0.5, 0.] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.z, [0., 0., 0.5] | units.kpc, places=6) + instance.evolve_model(0.1 | generic_unit_system.time) - self.assertAlmostEqual(instance.dm_particles.x, [0.4,0.,0.] | units.kpc, places=6) - self.assertAlmostEqual(instance.dm_particles.y, [0.,-0.4,0.] | units.kpc, places=6) - self.assertAlmostEqual(instance.dm_particles.z, [0.,0.,0.4] | units.kpc, places=6) - + self.assertAlmostEqual(instance.dm_particles.x, [0.4, 0., 0.] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.y, [0., -0.4, 0.] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.z, [0., 0., 0.4] | units.kpc, places=6) + instance.evolve_model(1.0 | generic_unit_system.time) - self.assertAlmostEqual(instance.dm_particles.x, [-0.5,0.,0.] | units.kpc, places=6) - self.assertAlmostEqual(instance.dm_particles.y, [0.,0.5,0.] | units.kpc, places=6) - self.assertAlmostEqual(instance.dm_particles.z, [0.,0.,-0.5] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.x, [-0.5, 0., 0.] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.y, [0., 0.5, 0.] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.z, [0., 0., -0.5] | units.kpc, places=6) instance.stop() - + def test15b(self): print("Test Gadget2 in nogravity mode") instance = Gadget2(mode="nogravity", **few_particles_default_options) self.assertEqual(instance.parameters.no_gravity_flag, True) self.assertEqual(instance.parameters.periodic_boundaries_flag, False) instance.parameters.min_size_timestep = 1.0 | generic_unit_system.time - + instance.dm_particles.add_particles(self.three_particles_IC) self.assertAlmostEqual(instance.dm_particles.x, [0.5, 0.0, 0.0] | units.kpc, places=6) - self.assertAlmostEqual(instance.dm_particles.y, [0.0,-0.5, 0.0] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.y, [0.0, -0.5, 0.0] | units.kpc, places=6) self.assertAlmostEqual(instance.dm_particles.z, [0.0, 0.0, 0.5] | units.kpc, places=6) - + instance.evolve_model(0.1 | generic_unit_system.time) self.assertAlmostEqual(instance.dm_particles.x, [0.4, 0.0, 0.0] | units.kpc, places=6) - self.assertAlmostEqual(instance.dm_particles.y, [0.0,-0.4, 0.0] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.y, [0.0, -0.4, 0.0] | units.kpc, places=6) self.assertAlmostEqual(instance.dm_particles.z, [0.0, 0.0, 0.4] | units.kpc, places=6) - + instance.evolve_model(1.0 | generic_unit_system.time) self.assertAlmostEqual(instance.dm_particles.x, [-0.5, 0.0, 0.0] | units.kpc, places=6) - self.assertAlmostEqual(instance.dm_particles.y, [ 0.0, 0.5, 0.0] | units.kpc, places=6) - self.assertAlmostEqual(instance.dm_particles.z, [ 0.0, 0.0,-0.5] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.y, [0.0, 0.5, 0.0] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.z, [0.0, 0.0, -0.5] | units.kpc, places=6) instance.stop() - + def test15c(self): print("Test Gadget2 in periodic mode") - converter = generic_unit_converter.ConvertBetweenGenericAndSiUnits(1.0|units.yr, 1.0|units.MSun, 1.0|units.AU) - instance = Gadget2(converter, mode = Gadget2Interface.MODE_PERIODIC_BOUNDARIES, + converter = generic_unit_converter.ConvertBetweenGenericAndSiUnits(1.0 | units.yr, 1.0 | units.MSun, 1.0 | units.AU) + instance = Gadget2(converter, mode=Gadget2Interface.MODE_PERIODIC_BOUNDARIES, **few_particles_default_options) self.assertEqual(instance.parameters.periodic_boundaries_flag, True) self.assertEqual(instance.parameters.no_gravity_flag, False) @@ -799,43 +796,43 @@ def test15c(self): self.assertAlmostEqual(instance.parameters.periodic_box_size, 20.0 | units.AU, places=6) instance.parameters.max_size_timestep = 0.01 | units.yr instance.parameters.epsilon_squared = 1.0e-16 | units.RSun**2 - + binary = Particles(2) binary.mass = 0.5 | units.MSun binary[1].position = [1.0, 0, 0] | units.AU binary.velocity = [0.0, 0, 0] | units.km / units.s binary[1].vy = (constants.G * binary.total_mass() / binary[1].x).sqrt() binary.move_to_center() - + binary.position += [7, -8, 3] | units.AU binary.velocity += [10, -10, 10] | units.AU / units.yr - + primary, secondary = instance.dm_particles.add_particles(binary) self.assertAlmostEqual(secondary.x - primary.x, 1.0 | units.AU, places=6) self.assertAlmostEqual(instance.dm_particles.center_of_mass(), [7, -8, 3] | units.AU, places=4) self.assertAlmostEqual(instance.dm_particles.center_of_mass_velocity(), [10, -10, 10] | units.AU / units.yr) - + instance.evolve_model(0.5 | units.yr) self.assertAlmostEqual(secondary.x - primary.x, -1.0 | units.AU, places=2) self.assertAlmostEqual(instance.dm_particles.center_of_mass(), [-8, 7, 8] | units.AU, places=4) - + instance.evolve_model(1.0 | units.yr) self.assertAlmostEqual(secondary.x - primary.x, 1.0 | units.AU, places=2) self.assertAlmostEqual(instance.dm_particles.center_of_mass(), [-3, 2, -7] | units.AU, places=4) instance.stop() - + def test16(self): - instance = Gadget2(mode = Gadget2Interface.MODE_PERIODIC_BOUNDARIES, + instance = Gadget2(mode=Gadget2Interface.MODE_PERIODIC_BOUNDARIES, **few_particles_default_options) - self.assertEqual(instance.parameters.periodic_boundaries_flag, True) - instance.commit_parameters() # its ok because read-only + self.assertEqual(instance.parameters.periodic_boundaries_flag, True) + instance.commit_parameters() # its ok because read-only instance.dm_particles.add_particles(self.three_particles_IC) instance.stop() - + def test17(self): print("Testing Gadget parameters further") target_number_of_particles = 100 - gas = new_evrard_gas_sphere(target_number_of_particles, self.default_convert_nbody, seed = 1234) + gas = new_evrard_gas_sphere(target_number_of_particles, self.default_convert_nbody, seed=1234) instance = Gadget2(self.default_converter, **default_options) instance.parameters.time_limit_cpu = 0.001 | units.s instance.gas_particles.add_particles(gas) @@ -843,7 +840,7 @@ def test17(self): AmuseException, instance.evolve_model, 1.0 | generic_unit_system.time, - expected_message=( + expected_message=( f"Error when calling 'evolve_model' of a '{self.classname}', " "errorcode is -5, error is 'CPU-time limit reached.'" ) @@ -853,72 +850,72 @@ def test17(self): AmuseException, instance.evolve_model, 0.5 * instance.model_time, - expected_message=( + expected_message=( f"Error when calling 'evolve_model' of a '{self.classname}', " "errorcode is -6, error is 'Can't evolve backwards in time.'" ) ) instance.stop() - + def test18(self): print("Testing Gadget parameters further") - instance = Gadget2(mode = Gadget2Interface.MODE_PERIODIC_NOGRAVITY, + instance = Gadget2(mode=Gadget2Interface.MODE_PERIODIC_NOGRAVITY, **few_particles_default_options) - instance.parameters.periodic_box_size = 2.0 | generic_unit_system.length # implicitly calls initialize_code()... + instance.parameters.periodic_box_size = 2.0 | generic_unit_system.length # implicitly calls initialize_code()... instance.parameters.begin_time = 10.04 | generic_unit_system.time instance.parameters.time_max = 10.4 | generic_unit_system.time instance.parameters.min_size_timestep = 0.1 | generic_unit_system.time - + self.assertAlmostEqual(instance.model_time, 0.0 | units.s) instance.dm_particles.add_particles(self.three_particles_IC) self.assertAlmostEqual(instance.model_time, instance.parameters.begin_time) - self.assertAlmostEqual(instance.dm_particles.x, [0.5,0.,0.] | units.kpc, places=6) - self.assertAlmostEqual(instance.dm_particles.y, [0.,-0.5,0.] | units.kpc, places=6) - self.assertAlmostEqual(instance.dm_particles.z, [0.,0.,0.5] | units.kpc, places=6) - + self.assertAlmostEqual(instance.dm_particles.x, [0.5, 0., 0.] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.y, [0., -0.5, 0.] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.z, [0., 0., 0.5] | units.kpc, places=6) + instance.evolve_model(10.14 | generic_unit_system.time) - self.assertAlmostRelativeEqual(instance.model_time, + self.assertAlmostRelativeEqual(instance.model_time, instance.parameters.begin_time + instance.parameters.min_size_timestep, 7) - self.assertAlmostEqual(instance.dm_particles.x, [0.4,0.,0.] | units.kpc, places=6) - self.assertAlmostEqual(instance.dm_particles.y, [0.,-0.4,0.] | units.kpc, places=6) - self.assertAlmostEqual(instance.dm_particles.z, [0.,0.,0.4] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.x, [0.4, 0., 0.] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.y, [0., -0.4, 0.] | units.kpc, places=6) + self.assertAlmostEqual(instance.dm_particles.z, [0., 0., 0.4] | units.kpc, places=6) instance.stop() - + def test19(self): particles = new_plummer_model(31) - + instance = Gadget2(self.default_converter, number_of_workers=1) instance.initialize_code() instance.parameters.epsilon_squared = 0.01 | generic_unit_system.length ** 2 instance.particles.add_particles(particles) instance.commit_particles() - + instance.evolve_model(0.001 | generic_unit_system.time) expected_positions = instance.particles.position instance.stop() positions_per_workers = [] - for n in [2,3,4,5]: + for n in [2, 3, 4, 5]: instance = Gadget2(self.default_converter, number_of_workers=n) instance.initialize_code() instance.parameters.epsilon_squared = 0.01 | generic_unit_system.length ** 2 instance.commit_parameters() instance.particles.add_particles(particles) instance.commit_particles() - + instance.evolve_model(0.001 | generic_unit_system.time) positions_per_workers.append(instance.particles.position) instance.stop() - - for index, n in enumerate([2,3,4,5]): - self.assertAlmostRelativeEqual(expected_positions[:,0], positions_per_workers[index][:,0]) - self.assertAlmostRelativeEqual(expected_positions[:,1], positions_per_workers[index][:,1]) - self.assertAlmostRelativeEqual(expected_positions[:,2], positions_per_workers[index][:,2]) - + + for index, n in enumerate([2, 3, 4, 5]): + self.assertAlmostRelativeEqual(expected_positions[:, 0], positions_per_workers[index][:, 0]) + self.assertAlmostRelativeEqual(expected_positions[:, 1], positions_per_workers[index][:, 1]) + self.assertAlmostRelativeEqual(expected_positions[:, 2], positions_per_workers[index][:, 2]) + def test20(self): print("Testing zero timestep exceptions") number_sph_particles = 1000 gas = new_evrard_gas_sphere(number_sph_particles, self.default_convert_nbody, seed=1234) - + wrong_converter = generic_unit_converter.ConvertBetweenGenericAndSiUnits( self.UnitLength, self.UnitMass, @@ -937,24 +934,24 @@ def test20(self): ) ) instance.stop() - + instance = Gadget2(wrong_converter, **default_options) correct_converter = nbody_system.nbody_to_si(self.UnitLength, 1.0e15 * units.yr) gas_compatible_with_wrong_converter = new_evrard_gas_sphere( - number_sph_particles, - correct_converter, - seed = 1234 + number_sph_particles, + correct_converter, + seed=1234 ) instance.gas_particles.add_particles(gas_compatible_with_wrong_converter) instance.evolve_model(1.0e13 | units.yr) instance.stop() - + def test21(self): print("Testing other evolve_model exceptions") number_sph_particles = 1000 - gas = new_evrard_gas_sphere(number_sph_particles, self.default_convert_nbody, seed = 1234) - - wrong_converter = generic_unit_converter.ConvertBetweenGenericAndSiUnits(self.UnitLength, + gas = new_evrard_gas_sphere(number_sph_particles, self.default_convert_nbody, seed=1234) + + wrong_converter = generic_unit_converter.ConvertBetweenGenericAndSiUnits(self.UnitLength, self.UnitMass, 1.0e-15 * units.yr) instance = Gadget2(wrong_converter, **default_options) instance.parameters.max_size_timestep = 3.0e-14 | units.yr @@ -980,91 +977,91 @@ def test21(self): ) ) instance.stop() - + def test22(self): print("Testing Gadget timestep limiter (Durier & Dalla Vecchia 2011)") number_sph_particles = 1000 numpy.random.seed(345672) - gas = new_plummer_gas_model(number_sph_particles, self.default_convert_nbody, base_grid = body_centered_grid_unit_cube) - + gas = new_plummer_gas_model(number_sph_particles, self.default_convert_nbody, base_grid=body_centered_grid_unit_cube) + n_timescales = 0.025 t_end = (n_timescales * self.default_convert_nbody.to_si(1.0 | nbody_system.time)).as_quantity_in(units.Myr) print("Evolving to ("+str(n_timescales), "nbody timescales): ", t_end) n_steps = 5 times = (t_end * (range(1, n_steps+1)) / (1.0 * n_steps)).as_quantity_in(units.Myr) - + instance = Gadget2(self.default_converter, **default_options) instance.parameters.max_size_timestep = t_end gas = instance.gas_particles.add_particles(gas) - - kinetic_energies = [] | units.erg + + kinetic_energies = [] | units.erg potential_energies = [] | units.erg - thermal_energies = [] | units.erg - + thermal_energies = [] | units.erg + for time in times[:3]: instance.evolve_model(time) - potential_energies.append( instance.potential_energy) - kinetic_energies.append( instance.kinetic_energy) - thermal_energies.append( instance.thermal_energy) + potential_energies.append(instance.potential_energy) + kinetic_energies.append(instance.kinetic_energy) + thermal_energies.append(instance.thermal_energy) print(str(time)+": E =", potential_energies[-1] + kinetic_energies[-1] + thermal_energies[-1]) - - central_particle = gas.select_array(lambda x, y, z : (x**2 + y**2 + z**2) == min(x**2 + y**2 + z**2), ["x", "y", "z"]) + + central_particle = gas.select_array(lambda x, y, z: (x**2 + y**2 + z**2) == min(x**2 + y**2 + z**2), ["x", "y", "z"]) print("Initial internal energy central particle:", central_particle[0].u.as_quantity_in(units.erg / units.g)) delta_E = abs(instance.potential_energy) - central_particle[0].u * central_particle[0].mass central_particle.u = abs(instance.potential_energy) / central_particle.mass print("New internal energy central particle:", central_particle[0].u.as_quantity_in(units.erg / units.g)) print("Changed total energy to:", potential_energies[-1] + kinetic_energies[-1] + thermal_energies[-1] + delta_E) - + self.assertAlmostRelativeEqual( - instance.potential_energy + instance.kinetic_energy + instance.thermal_energy, + instance.potential_energy + instance.kinetic_energy + instance.thermal_energy, potential_energies[-1] + kinetic_energies[-1] + thermal_energies[-1] + delta_E, 7) potential_energies[-1] = instance.potential_energy - kinetic_energies[-1] = instance.kinetic_energy - thermal_energies[-1] = instance.thermal_energy - + kinetic_energies[-1] = instance.kinetic_energy + thermal_energies[-1] = instance.thermal_energy + for i_step, time in enumerate(times[3:]): instance.evolve_model(time) - potential_energies.append( instance.potential_energy) - kinetic_energies.append( instance.kinetic_energy) - thermal_energies.append( instance.thermal_energy) + potential_energies.append(instance.potential_energy) + kinetic_energies.append(instance.kinetic_energy) + thermal_energies.append(instance.thermal_energy) print(str(time)+": E =", potential_energies[-1] + kinetic_energies[-1] + thermal_energies[-1]) instance.stop() - + total_energies = potential_energies + kinetic_energies + thermal_energies self.assertAlmostRelativeEqual(total_energies[1], total_energies[0], 3) self.assertAlmostRelativeEqual(total_energies[2], total_energies[1] + delta_E, 3) self.assertIsOfOrder(total_energies[3], total_energies[2]) self.assertIsOfOrder(total_energies[4], total_energies[3]) - + def slowtest22b(self): print("Testing Gadget timestep limiter (Durier & Dalla Vecchia 2011)") number_sph_particles = 10000 numpy.random.seed(345672) - gas = new_plummer_gas_model(number_sph_particles, self.default_convert_nbody, base_grid = body_centered_grid_unit_cube) - + gas = new_plummer_gas_model(number_sph_particles, self.default_convert_nbody, base_grid=body_centered_grid_unit_cube) + n_pixels = 100 n_timescales = 0.5 t_end = (n_timescales * self.default_convert_nbody.to_si(1.0 | nbody_system.time)).as_quantity_in(units.Myr) print("Evolving to ("+str(n_timescales), "nbody timescales): ", t_end) n_steps = 100 times = (t_end * (range(1, n_steps+1)) / (1.0 * n_steps)).as_quantity_in(units.Myr) - + instance = Gadget2(self.default_converter, **default_options) instance.parameters.max_size_timestep = t_end gas = instance.gas_particles.add_particles(gas) - - kinetic_energies = [] | units.erg + + kinetic_energies = [] | units.erg potential_energies = [] | units.erg - thermal_energies = [] | units.erg - + thermal_energies = [] | units.erg + for time in times[:3]: instance.evolve_model(time) - potential_energies.append( instance.potential_energy) - kinetic_energies.append( instance.kinetic_energy) - thermal_energies.append( instance.thermal_energy) + potential_energies.append(instance.potential_energy) + kinetic_energies.append(instance.kinetic_energy) + thermal_energies.append(instance.thermal_energy) print(time, potential_energies[-1] + kinetic_energies[-1] + thermal_energies[-1]) - - view = ([-0.5, 0.5, -0.5, 0.5] * (2.0 | units.none) * + + view = ([-0.5, 0.5, -0.5, 0.5] * (2.0 | units.none) * self.default_convert_nbody.to_si(1.0 | nbody_system.length)).as_quantity_in(units.kpc) print("Physical size of window for hydro_plot:", view) hydro_plot( @@ -1073,7 +1070,7 @@ def slowtest22b(self): (n_pixels, n_pixels), "gadget2_slowtest22b_hydro_image{0:=03}.png".format(0) ) - central_particle = gas.select_array(lambda x, y, z : (x**2 + y**2 + z**2) == min(x**2 + y**2 + z**2), ["x", "y", "z"]) + central_particle = gas.select_array(lambda x, y, z: (x**2 + y**2 + z**2) == min(x**2 + y**2 + z**2), ["x", "y", "z"]) print("Position central particle:", central_particle.position.as_quantity_in(units.kpc)) print("Center of mass, virial radius of system:", gas.center_of_mass().as_quantity_in(units.kpc), gas.virial_radius().as_quantity_in(units.kpc)) print("Initial internal energy central particle:", central_particle[0].u.as_quantity_in(units.erg / units.g)) @@ -1081,15 +1078,15 @@ def slowtest22b(self): central_particle.u = abs(instance.potential_energy) / central_particle.mass print("New internal energy central particle:", central_particle[0].u.as_quantity_in(units.erg / units.g)) print("Changed total energy to:", potential_energies[-1] + kinetic_energies[-1] + thermal_energies[-1] + delta_E) - + self.assertAlmostRelativeEqual( - instance.potential_energy + instance.kinetic_energy + instance.thermal_energy, + instance.potential_energy + instance.kinetic_energy + instance.thermal_energy, potential_energies[-1] + kinetic_energies[-1] + thermal_energies[-1] + delta_E, 7) potential_energies[-1] = instance.potential_energy - kinetic_energies[-1] = instance.kinetic_energy - thermal_energies[-1] = instance.thermal_energy + kinetic_energies[-1] = instance.kinetic_energy + thermal_energies[-1] = instance.thermal_energy print(potential_energies[-1] + kinetic_energies[-1] + thermal_energies[-1]) - + for i_step, time in enumerate(times[3:]): if i_step < 20: hydro_plot( @@ -1099,12 +1096,12 @@ def slowtest22b(self): "gadget2_slowtest22b_hydro_image{0:=03}.png".format(i_step+1) ) instance.evolve_model(time) - potential_energies.append( instance.potential_energy) - kinetic_energies.append( instance.kinetic_energy) - thermal_energies.append( instance.thermal_energy) + potential_energies.append(instance.potential_energy) + kinetic_energies.append(instance.kinetic_energy) + thermal_energies.append(instance.thermal_energy) print(time, potential_energies[-1] + kinetic_energies[-1] + thermal_energies[-1]) instance.stop() - + total_energies = potential_energies + kinetic_energies + thermal_energies self.assertAlmostRelativeEqual(total_energies[1], total_energies[0], 3) self.assertAlmostRelativeEqual(total_energies[2], total_energies[1] + delta_E, 3) @@ -1112,15 +1109,15 @@ def slowtest22b(self): self.assertIsOfOrder(total_energies[4], total_energies[3]) for i in range(5, n_steps): self.assertAlmostRelativeEqual(total_energies[i], total_energies[i-1], 1) - - energy_evolution_plot(times, kinetic_energies, potential_energies, thermal_energies, - figname = "gadget2_slowtest22b_energy.png") - + + energy_evolution_plot(times, kinetic_energies, potential_energies, thermal_energies, + figname="gadget2_slowtest22b_energy.png") + def test23(self): print("Testing Gadget2 density_limit_detection") number_gas_particles = 1000 gas = new_evrard_gas_sphere(number_gas_particles, self.default_convert_nbody, do_scale=True, seed=12345) - + instance = Gadget2(self.default_converter, **default_options) instance.initialize_code() instance.parameters.stopping_condition_maximum_density = 10 * self.UnitMass / self.UnitLength**3 @@ -1129,68 +1126,68 @@ def test23(self): stars.x += 1000 * self.UnitLength instance.dm_particles.add_particles(stars) self.assertIsOfOrder(max(instance.gas_particles.density), self.UnitMass / self.UnitLength**3) - + density_limit_detection = instance.stopping_conditions.density_limit_detection density_limit_detection.enable() - + instance.evolve_model(10.0 | units.Myr) print(instance.model_time.as_quantity_in(units.Myr)) print(instance.stopping_conditions) self.assertTrue(density_limit_detection.is_set()) self.assertTrue(instance.model_time < 10.0 | units.Myr) self.assertEqual(len(density_limit_detection.particles()), 1) - self.assertTrue(density_limit_detection.particles().density > + self.assertTrue(density_limit_detection.particles().density > 10 * self.UnitMass / self.UnitLength**3) - + instance.particles.remove_particles(density_limit_detection.particles()) - + instance.evolve_model(10.0 | units.Myr) print(instance.model_time.as_quantity_in(units.Myr)) print(instance.stopping_conditions) self.assertTrue(density_limit_detection.is_set()) self.assertTrue(instance.model_time < 10.0 | units.Myr) - + self.assertEqual(len(density_limit_detection.particles()), 2) - self.assertEqual((density_limit_detection.particles().density > + self.assertEqual((density_limit_detection.particles().density > 10 * self.UnitMass / self.UnitLength**3), [True, True]) instance.stop() - + def test24(self): print("Testing Gadget2 internal_energy_limit_detection") number_gas_particles = 1000 gas = new_evrard_gas_sphere(number_gas_particles, self.default_convert_nbody, do_scale=True, seed=12345) initial_internal_energy = 0.05 * constants.G * self.UnitMass / self.UnitLength - + instance = Gadget2(self.default_converter, **default_options) instance.initialize_code() instance.parameters.stopping_condition_maximum_internal_energy = 10 * initial_internal_energy instance.gas_particles.add_particles(gas) self.assertAlmostRelativeEquals(instance.gas_particles.u, initial_internal_energy, 8) - + internal_energy_limit_detection = instance.stopping_conditions.internal_energy_limit_detection internal_energy_limit_detection.enable() - + instance.evolve_model(10.0 | units.Myr) print(instance.model_time.as_quantity_in(units.Myr)) print(instance.stopping_conditions) self.assertTrue(internal_energy_limit_detection.is_set()) self.assertTrue(instance.model_time < 10.0 | units.Myr) self.assertEqual(len(internal_energy_limit_detection.particles()), 4) - self.assertEqual((internal_energy_limit_detection.particles().u > + self.assertEqual((internal_energy_limit_detection.particles().u > 10 * initial_internal_energy), [True, True, True, True]) - + instance.particles.remove_particles(internal_energy_limit_detection.particles()) - + instance.evolve_model(10.0 | units.Myr) print(instance.model_time.as_quantity_in(units.Myr)) print(instance.stopping_conditions) self.assertTrue(internal_energy_limit_detection.is_set()) self.assertTrue(instance.model_time < 10.0 | units.Myr) self.assertEqual(len(internal_energy_limit_detection.particles()), 3) - self.assertEqual((internal_energy_limit_detection.particles().u > + self.assertEqual((internal_energy_limit_detection.particles().u > 10 * initial_internal_energy), [True, True, True]) instance.stop() - + def test25(self): print("Testing Gadget2 comoving_integration_flag") particles = new_plummer_model(100, self.default_convert_nbody, do_scale=True) @@ -1206,7 +1203,7 @@ def test25(self): instance.parameters.epsilon_squared = (1.0 | generic_unit_system.length)**2 instance.parameters.softening_halo_max_phys = 1.0 | generic_unit_system.length instance.dm_particles.add_particles(particles) - + instance.evolve_to_redshift(19.9) self.assertRaises( AmuseException, @@ -1218,7 +1215,7 @@ def test25(self): "with the current value of comoving_integration_flag'" ) ) - + self.assertAlmostEqual(instance.model_redshift, 19.9, 5) self.assertRaises( AmuseException, @@ -1232,7 +1229,7 @@ def test25(self): ) ) instance.stop() - + def xtest26(self): print("Testing Gadget2 comoving_integration_flag validation (WIP)") particles = read_set_from_file("cluster_littleendian.dat", "gadget") @@ -1262,19 +1259,19 @@ def xtest26(self): instance.evolve_to_redshift(0.0) write_set_to_file(instance.particles, "z0", "hdf5") instance.stop() - + def xtest27(self): print("Testing Gadget2 comoving_integration_flag validation II (WIP)") particles = read_set_from_file("lcdm_gas_littleendian.dat", "gadget") gas = particles[0] mu = constants.proton_mass * 4.0 / (1.0 + 3.0 * 0.76) gas.u = self.default_converter.to_generic(3 * constants.kB * (1000 | units.K) / (2 * mu)) - gas.velocity /= 11.0**-0.5 # velocities in Gadget files are in w=sqrt(a)*dx/dt + gas.velocity /= 11.0**-0.5 # velocities in Gadget files are in w=sqrt(a)*dx/dt halo = particles[1] - halo.velocity /= 11.0**-0.5 # velocities in Gadget files are in w=sqrt(a)*dx/dt + halo.velocity /= 11.0**-0.5 # velocities in Gadget files are in w=sqrt(a)*dx/dt gas = convert_comoving_to_physical(gas, redshift=10.0) halo = convert_comoving_to_physical(halo, redshift=10.0) - + instance = Gadget2(self.default_converter, mode="periodic", redirection="none", number_of_workers=1) instance.parameters.comoving_integration_flag = True instance.parameters.n_smooth = 33.0 @@ -1285,7 +1282,7 @@ def xtest27(self): instance.parameters.omega_zero = 0.3 instance.parameters.omega_lambda = 0.7 instance.parameters.omega_baryon = 0.04 - instance.parameters.hubble_parameter = 1.0 # coordinates in input file are already in kpc/h + instance.parameters.hubble_parameter = 1.0 # coordinates in input file are already in kpc/h instance.parameters.artificial_viscosity_alpha = 0.8 instance.parameters.min_gas_temp = 50.0 | units.K instance.parameters.gas_epsilon = 600.0 | generic_unit_system.length @@ -1308,23 +1305,23 @@ def xtest27(self): instance.evolve_to_redshift(0.0) write_set_to_file(instance.particles, "z0", "hdf5") instance.stop() - + def test28(self): print("Testing Gadget get_hydro_state_at_point in periodic mode") gas = Particles(8000) gas.mass = 1.0/8000 | generic_unit_system.mass - x,y,z = numpy.mgrid[-1:0.9:20j, -1:0.9:20j, -1:0.9:20j] | units.kpc + x, y, z = numpy.mgrid[-1:0.9:20j, -1:0.9:20j, -1:0.9:20j] | units.kpc gas.x, gas.y, gas.z = x.flatten(), y.flatten(), z.flatten() gas.velocity = [0, 0, 0] | units.m / units.s gas.u = (1 + 0.8 * numpy.sin(gas.x * (numpy.pi | units.kpc**-1))) | generic_unit_system.specific_energy - + instance = Gadget2(self.default_converter, mode='periodic', **default_options) instance.parameters.periodic_box_size = 2.0 | units.kpc instance.gas_particles.add_particles(gas) - + self.assertAlmostRelativeEqual(instance.total_mass, 1.0e10 | units.MSun, 3) self.assertAlmostRelativeEqual(instance.thermal_energy, 1.0e10 | units.MSun * units.km**2 * units.s**-2, 3) - + number_of_points = 100 in_domain = numpy.linspace(-1.0, 1.0, 100) | units.kpc domain_border = numpy.ones(100) | units.kpc @@ -1332,49 +1329,48 @@ def test28(self): state_right = instance.get_hydro_state_at_point(domain_border, in_domain, in_domain) for var_left, var_right in zip(state_left, state_right): self.assertEqual(var_left, var_right) - + state_back = instance.get_hydro_state_at_point(in_domain, -domain_border, in_domain) state_front = instance.get_hydro_state_at_point(in_domain, domain_border, in_domain) for var_front, var_back in zip(state_front, state_back): self.assertEqual(var_front, var_back) - + state_bottom = instance.get_hydro_state_at_point(in_domain, in_domain, -domain_border) state_top = instance.get_hydro_state_at_point(in_domain, in_domain, domain_border) for var_top, var_bottom in zip(state_top, state_bottom): self.assertEqual(var_top, var_bottom) - + self.assertAlmostRelativeEqual(state_left[0].mean(), 1.25e9 | units.MSun * units.kpc**-3, 2) self.assertAlmostRelativeEqual(state_back[0].mean(), 1.25e9 | units.MSun * units.kpc**-3, 2) self.assertAlmostRelativeEqual(state_bottom[0].mean(), 1.25e9 | units.MSun * units.kpc**-3, 2) - + self.assertAlmostRelativeEqual(state_left[4].mean(), 1.25e9 | units.MSun * units.kpc**-3 * units.km**2 * units.s**-2, 2) self.assertAlmostRelativeEqual(state_back[4].mean(), 1.25e9 | units.MSun * units.kpc**-3 * units.km**2 * units.s**-2, 2) self.assertAlmostRelativeEqual(state_bottom[4].mean(), 1.25e9 | units.MSun * units.kpc**-3 * units.km**2 * units.s**-2, 2) - + # With x=cst, variations in u (and therefore in rhoe) should be small self.assertAlmostEqual(state_left[4].std() / (1.25e9 | units.MSun * units.kpc**-3 * units.km**2 * units.s**-2), 0.0, 2) # Over the entire x domain, variations in rhoe should equal the sine amplitude (=0.8) times the rms(sine) over a whole period (=sqrt(.5)) self.assertAlmostEqual(state_back[4].std() / (1.25e9 | units.MSun * units.kpc**-3 * units.km**2 * units.s**-2), 0.8 * numpy.sqrt(0.5), 1) self.assertAlmostEqual(state_bottom[4].std() / (1.25e9 | units.MSun * units.kpc**-3 * units.km**2 * units.s**-2), 0.8 * numpy.sqrt(0.5), 1) instance.stop() - def energy_evolution_plot(time, kinetic, potential, thermal, figname): if not HAS_MATPLOTLIB: return - pyplot.figure(figsize = (5, 5)) + pyplot.figure(figsize=(5, 5)) plot(time, kinetic, label='K') plot(time, potential, label='U') plot(time, thermal, label='Q') plot(time, kinetic + potential + thermal, label='E') xlabel('Time') ylabel('Energy') - pyplot.legend(prop={'size':"x-small"}, loc=4) + pyplot.legend(prop={'size': "x-small"}, loc=4) pyplot.savefig(figname) print("\nPlot of energy evolution was saved to:", figname) pyplot.close() - + def hydro_plot(view, hydro_code, image_size, figname): """ @@ -1393,34 +1389,34 @@ def hydro_plot(view, hydro_code, image_size, figname): grid.x += view[0] grid.y += view[2] speed = grid.z.reshape(size) * (0 | 1/units.s) - rho, rhovx, rhovy, rhovz, rhoe = hydro_code.get_hydro_state_at_point(grid.x.reshape(size), + rho, rhovx, rhovy, rhovz, rhoe = hydro_code.get_hydro_state_at_point(grid.x.reshape(size), grid.y.reshape(size), grid.z.reshape(size)) - - min_v = 800.0 | units.km / units.s + + min_v = 800.0 | units.km / units.s max_v = 3000.0 | units.km / units.s min_rho = rho.amin() max_rho = rho.amax() fade_rho = min_rho * (max_rho / min_rho)**0.1 min_E = 1.0e11 | units.J / units.kg max_E = 1.0e13 | units.J / units.kg - + v_sqr = (rhovx**2 + rhovy**2 + rhovz**2) / rho**2 E = rhoe / rho log_v = numpy.log((v_sqr / min_v**2)) / numpy.log((max_v**2 / min_v**2)) log_rho = numpy.log((rho / min_rho)) / numpy.log((max_rho / min_rho)) log_E = numpy.log((E / min_E)) / numpy.log((max_E / min_E)) - - red = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum(numpy.zeros_like(rho.number), log_rho)).reshape(shape) + + red = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum(numpy.zeros_like(rho.number), log_rho)).reshape(shape) green = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum(numpy.zeros_like(rho.number), log_v)).reshape(shape) - blue = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum(numpy.zeros_like(rho.number), log_E)).reshape(shape) - alpha = numpy.minimum(numpy.ones_like(log_v), numpy.maximum(numpy.zeros_like(log_v), - numpy.log((rho / min_rho)) / numpy.log((fade_rho / min_rho)) )).reshape(shape) - - rgba = numpy.concatenate((red, green, blue, alpha), axis = 2) - - pyplot.figure(figsize = (image_size[0]/100.0, image_size[1]/100.0), dpi = 100) + blue = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum(numpy.zeros_like(rho.number), log_E)).reshape(shape) + alpha = numpy.minimum(numpy.ones_like(log_v), numpy.maximum(numpy.zeros_like(log_v), + numpy.log((rho / min_rho)) / numpy.log((fade_rho / min_rho)))).reshape(shape) + + rgba = numpy.concatenate((red, green, blue, alpha), axis=2) + + pyplot.figure(figsize=(image_size[0]/100.0, image_size[1]/100.0), dpi=100) im = pyplot.figimage(rgba, origin='lower') - - pyplot.savefig(figname, transparent=True, dpi = 100) + + pyplot.savefig(figname, transparent=True, dpi=100) print("\nHydroplot was saved to: ", figname) pyplot.close() diff --git a/src/amuse/test/suite/codes_tests/test_galactics.py b/src/amuse/test/suite/codes_tests/test_galactics.py index 8a81311351..1f44657806 100644 --- a/src/amuse/test/suite/codes_tests/test_galactics.py +++ b/src/amuse/test/suite/codes_tests/test_galactics.py @@ -9,10 +9,11 @@ # Change the default for some GalactICs(-Interface) keyword arguments: default_options = dict() -#default_options = dict(redirection = "none") +# default_options = dict(redirection = "none") + class GalactICsInterfaceTests(TestWithMPI): - + def test1(self): print("Testing GalactICsInterface initialization") instance = GalactICsInterface(**default_options) @@ -24,37 +25,37 @@ def test1(self): self.assertEqual(instance.commit_parameters(), 0) self.assertEqual(instance.cleanup_code(), 0) instance.stop() - + def test2(self): print("Testing GalactICsInterface parameters") instance = GalactICsInterface(**default_options) self.assertEqual(instance.initialize_code(), 0) self.assertEqual(instance.set_output_path(os.path.join(instance.get_output_directory(), "test")), 0) - + self.assertEqual(instance.set_generate_halo_flag(False), 0) self.assertEqual(instance.set_disk_do_center_flag(False), 0) self.assertEqual(instance.set_number_of_grid_intervals(50000), 0) self.assertEqual(instance.set_disk_random_seed(-1234), 0) self.assertEqual(instance.set_halo_outer_radius(250.0), 0) self.assertEqual(instance.set_bulge_streaming_fraction(0.4), 0) - + self.assertEqual([False, 0], list(instance.get_generate_halo_flag().values())) self.assertEqual([False, 0], list(instance.get_disk_do_center_flag().values())) self.assertEqual([50000, 0], list(instance.get_number_of_grid_intervals().values())) self.assertEqual([-1234, 0], list(instance.get_disk_random_seed().values())) self.assertEqual([250.0, 0], list(instance.get_halo_outer_radius().values())) self.assertEqual([0.4, 0], list(instance.get_bulge_streaming_fraction().values())) - + self.assertEqual(instance.cleanup_code(), 0) instance.stop() - + def slowtest3(self): print("Testing GalactICsInterface generate_particles") n_particles_halo = 100 n_particles_bulge = 100 n_particles_disk = 100 number_of_particles = n_particles_disk + n_particles_bulge + n_particles_halo - + instance = GalactICsInterface(**default_options) self.assertEqual(instance.initialize_code(), 0) self.assertEqual(instance.set_output_path(instance.get_output_directory()), 0) @@ -62,59 +63,58 @@ def slowtest3(self): self.assertEqual(instance.set_bulge_number_of_particles(n_particles_bulge), 0) self.assertEqual(instance.set_disk_number_of_particles(n_particles_disk), 0) self.assertEqual(instance.commit_parameters(), 0) - + self.assertEqual(list(instance.get_number_of_particles_updated().values()), [0, 0]) self.assertEqual(instance.generate_particles(), 0) self.assertEqual(list(instance.get_number_of_particles_updated().values()), [number_of_particles, 0]) - + mass_disk, mass_bulge, mass_halo = 26.578816771507263, 14.632800221443176, 1184.2350006103516 masses, errors = instance.get_mass(range(number_of_particles)) self.assertEqual(errors, numpy.zeros(number_of_particles)) self.assertAlmostRelativeEquals(masses, numpy.concatenate(( - numpy.ones(n_particles_disk)*mass_disk/n_particles_disk, + numpy.ones(n_particles_disk)*mass_disk/n_particles_disk, numpy.ones(n_particles_bulge)*mass_bulge/n_particles_bulge, numpy.ones(n_particles_halo)*mass_halo/n_particles_halo, )), 3) - + x_positions, y_positions, z_positions, errors = instance.get_position(range(number_of_particles)) self.assertEqual(errors, numpy.zeros(number_of_particles)) - self.assertAlmostEqual(numpy.array([numpy.mean(x_positions), numpy.mean(y_positions), + self.assertAlmostEqual(numpy.array([numpy.mean(x_positions), numpy.mean(y_positions), numpy.mean(z_positions)]), numpy.array([0.0]*3), 5) self.assertAlmostRelativeEquals(numpy.array([ - numpy.mean(abs(x_positions[:n_particles_disk])), - numpy.mean(abs(y_positions[:n_particles_disk])), - numpy.mean(abs(z_positions[:n_particles_disk]))]), + numpy.mean(abs(x_positions[:n_particles_disk])), + numpy.mean(abs(y_positions[:n_particles_disk])), + numpy.mean(abs(z_positions[:n_particles_disk]))]), numpy.array([7.3994484072923656, 7.1570298135280606, 0.33854196755215527]), 3) self.assertAlmostRelativeEquals(numpy.array([ - numpy.mean(abs(x_positions[n_particles_disk:n_particles_disk+n_particles_bulge])), - numpy.mean(abs(y_positions[n_particles_disk:n_particles_disk+n_particles_bulge])), - numpy.mean(abs(z_positions[n_particles_disk:n_particles_disk+n_particles_bulge]))]), - numpy.array([1.244429082274437,1.1639373835548759 , 0.8550614269822836]), 3) + numpy.mean(abs(x_positions[n_particles_disk:n_particles_disk+n_particles_bulge])), + numpy.mean(abs(y_positions[n_particles_disk:n_particles_disk+n_particles_bulge])), + numpy.mean(abs(z_positions[n_particles_disk:n_particles_disk+n_particles_bulge]))]), + numpy.array([1.244429082274437, 1.1639373835548759, 0.8550614269822836]), 3) self.assertAlmostRelativeEquals(numpy.array([ - numpy.mean(abs(x_positions[-n_particles_halo:])), - numpy.mean(abs(y_positions[-n_particles_halo:])), - numpy.mean(abs(z_positions[-n_particles_halo:]))]), - numpy.array([94.242819476127622,88.41320479869843 , 85.234394512176507]), 3) + numpy.mean(abs(x_positions[-n_particles_halo:])), + numpy.mean(abs(y_positions[-n_particles_halo:])), + numpy.mean(abs(z_positions[-n_particles_halo:]))]), + numpy.array([94.242819476127622, 88.41320479869843, 85.234394512176507]), 3) - x_velocities, y_velocities, z_velocities, errors = instance.get_velocity(range(number_of_particles)) self.assertEqual(errors, numpy.zeros(number_of_particles)) - self.assertAlmostEqual(numpy.array([numpy.mean(x_velocities), numpy.mean(y_velocities), + self.assertAlmostEqual(numpy.array([numpy.mean(x_velocities), numpy.mean(y_velocities), numpy.mean(z_velocities)]), numpy.array([0.0]*3)) self.assertAlmostRelativeEquals(numpy.array([ - numpy.mean(abs(x_velocities[:n_particles_disk])), - numpy.mean(abs(y_velocities[:n_particles_disk])), - numpy.mean(abs(z_velocities[:n_particles_disk]))]), + numpy.mean(abs(x_velocities[:n_particles_disk])), + numpy.mean(abs(y_velocities[:n_particles_disk])), + numpy.mean(abs(z_velocities[:n_particles_disk]))]), numpy.array([1.5026254250109197, 1.5649469271302223, 0.20230436498299242]), 5) self.assertAlmostRelativeEquals(numpy.array([ - numpy.mean(abs(x_velocities[n_particles_disk:])), - numpy.mean(abs(y_velocities[n_particles_disk:])), + numpy.mean(abs(x_velocities[n_particles_disk:])), + numpy.mean(abs(y_velocities[n_particles_disk:])), numpy.mean(abs(z_velocities[n_particles_disk:]))]), - numpy.array([0.99470628838986164,0.95913934175856408 , 0.9359876788407564]), 5) - + numpy.array([0.99470628838986164, 0.95913934175856408, 0.9359876788407564]), 5) + self.assertEqual(instance.cleanup_code(), 0) instance.stop() - + def test4(self): print("Testing GalactICsInterface generate_particles") number_of_particles_halo = 1000 @@ -126,18 +126,16 @@ def test4(self): self.assertEqual(instance.set_generate_disk_flag(False), 0) self.assertEqual(instance.set_order_of_multipole_expansion(0), 0) self.assertEqual(instance.commit_parameters(), 0) - + self.assertEqual(list(instance.get_number_of_particles_updated().values()), [0, 0]) self.assertEqual(instance.generate_particles(), 0) self.assertEqual(list(instance.get_number_of_particles_updated().values()), [number_of_particles_halo, 0]) - - masses, errors = instance.get_mass(range(number_of_particles_halo)) self.assertEqual(errors, numpy.zeros(number_of_particles_halo)) self.assertAlmostRelativeEquals(masses, numpy.ones(number_of_particles_halo)*masses[0]) - total_mass = masses.sum() - + total_mass = masses.sum() + if platform.processor() == 'ppc64le': # on ppc64le, the model generation has small differences from intel # change expected pos @@ -146,30 +144,29 @@ def test4(self): expected_mean_pos = numpy.array([73.768384103536604, 76.03533643054962, 75.176319462463255]) expected_mean_vel = numpy.array([0.92904859858192501, 0.94953939936682585, 0.92897711758688095]) - + x_positions, y_positions, z_positions, errors = instance.get_position(range(number_of_particles_halo)) self.assertEqual(errors, numpy.zeros(number_of_particles_halo)) - self.assertAlmostEqual(numpy.array([numpy.mean(x_positions), numpy.mean(y_positions), + self.assertAlmostEqual(numpy.array([numpy.mean(x_positions), numpy.mean(y_positions), numpy.mean(z_positions)]), numpy.array([0.0]*3), 5) - self.assertAlmostRelativeEquals(numpy.array([numpy.mean(abs(x_positions)), numpy.mean(abs(y_positions)), + self.assertAlmostRelativeEquals(numpy.array([numpy.mean(abs(x_positions)), numpy.mean(abs(y_positions)), numpy.mean(abs(z_positions))]), expected_mean_pos, 3) - + x_velocities, y_velocities, z_velocities, errors = instance.get_velocity(range(number_of_particles_halo)) self.assertEqual(errors, numpy.zeros(number_of_particles_halo)) - self.assertAlmostEqual(numpy.array([numpy.mean(x_velocities), numpy.mean(y_velocities), + self.assertAlmostEqual(numpy.array([numpy.mean(x_velocities), numpy.mean(y_velocities), numpy.mean(z_velocities)]), numpy.array([0.0]*3)) - self.assertAlmostRelativeEquals(numpy.array([numpy.mean(abs(x_velocities)), numpy.mean(abs(y_velocities)), + self.assertAlmostRelativeEquals(numpy.array([numpy.mean(abs(x_velocities)), numpy.mean(abs(y_velocities)), numpy.mean(abs(z_velocities))]), expected_mean_vel, 2) - + self.assertEqual(instance.cleanup_code(), 0) instance.stop() - class GalactICsTests(TestWithMPI): - + default_unit_converter = nbody_system.nbody_to_si(1.0 | units.kpc, 1.0e6 | units.MSun) - + def test1(self): print("Testing GalactICs initialization") instance = GalactICs(**default_options) @@ -180,67 +177,67 @@ def test1(self): instance.commit_parameters() instance.cleanup_code() instance.stop() - + def test2(self): print("Testing GalactICs parameters (with unit converter)") instance = GalactICs(self.default_unit_converter, **default_options) instance.initialize_code() - - for par, value in [('generate_halo_flag', True), ('generate_disk_flag', True), - ('generate_bulge_flag', True), ('halo_do_center_flag', True), + + for par, value in [('generate_halo_flag', True), ('generate_disk_flag', True), + ('generate_bulge_flag', True), ('halo_do_center_flag', True), ('bulge_do_center_flag', True), ('disk_do_center_flag', True)]: self.assertTrue(value is getattr(instance.parameters, par)) setattr(instance.parameters, par, not value) self.assertFalse(value is getattr(instance.parameters, par)) - - for par, value in [('number_of_grid_intervals', 90000), ('order_of_multipole_expansion', 10), + + for par, value in [('number_of_grid_intervals', 90000), ('order_of_multipole_expansion', 10), ('number_of_radial_steps_correction_fns_disk_df', 10), - ('number_of_iterations_disk_df', 50), ('halo_number_of_particles', 200000), - ('bulge_number_of_particles', 50000), ('disk_number_of_particles', 100000), + ('number_of_iterations_disk_df', 50), ('halo_number_of_particles', 200000), + ('bulge_number_of_particles', 50000), ('disk_number_of_particles', 100000), ('halo_random_seed', -1), ('bulge_random_seed', -1), ('disk_random_seed', -1)]: self.assertEqual(value, getattr(instance.parameters, par)) setattr(instance.parameters, par, 1) self.assertEqual(1, getattr(instance.parameters, par)) - - for par, value in [('halo_outer_radius', 300.0 | nbody_system.length), - ('halo_scale_velocity', 3.26331115 | nbody_system.speed), - ('halo_scale_radius', 6.06699419 | nbody_system.length), + + for par, value in [('halo_outer_radius', 300.0 | nbody_system.length), + ('halo_scale_velocity', 3.26331115 | nbody_system.speed), + ('halo_scale_radius', 6.06699419 | nbody_system.length), ('halo_truncation_width', 100.0 | nbody_system.length)]: - self.assertEqual(instance.unit_converter.to_si(value), + self.assertEqual(instance.unit_converter.to_si(value), getattr(instance.parameters, par)) setattr(instance.parameters, par, 3.0 | value.unit) self.assertEqual(instance.unit_converter.to_si(3.0 | value.unit), getattr(instance.parameters, par)) - + self.assertEqual(os.path.join(instance.get_output_directory()), instance.parameters.output_directory) instance.parameters.output_directory = 'test' self.assertEqual("test", instance.parameters.output_directory) - + instance.cleanup_code() instance.stop() - + def test3(self): print("Testing GalactICs parameters (nbody units, no converter)") instance = GalactICs(**default_options) instance.initialize_code() - - for par, value in [('halo_outer_radius', 300.0 | nbody_system.length), - ('halo_scale_velocity', 3.26331115 | nbody_system.speed), - ('halo_scale_radius', 6.06699419 | nbody_system.length), + + for par, value in [('halo_outer_radius', 300.0 | nbody_system.length), + ('halo_scale_velocity', 3.26331115 | nbody_system.speed), + ('halo_scale_radius', 6.06699419 | nbody_system.length), ('halo_truncation_width', 100.0 | nbody_system.length)]: self.assertEqual(value, getattr(instance.parameters, par)) setattr(instance.parameters, par, 3.0 | value.unit) self.assertEqual(3.0 | value.unit, getattr(instance.parameters, par)) instance.cleanup_code() instance.stop() - + def slowtest4(self): print("Testing GalactICs generate_particles") n_particles_halo = 100 n_particles_bulge = 100 n_particles_disk = 100 number_of_particles = n_particles_disk + n_particles_bulge + n_particles_halo - + instance = GalactICs(**default_options) instance.initialize_code() instance.parameters.disk_number_of_particles = n_particles_disk @@ -251,12 +248,12 @@ def slowtest4(self): self.assertEqual(len(instance.particles), number_of_particles) self.assertAlmostRelativeEquals(instance.particles.total_mass(), 1225.4466176 | nbody_system.mass, 3) self.assertAlmostRelativeEquals(instance.particles.kinetic_energy(), 2564.69894361 | nbody_system.energy, 3) - self.assertAlmostRelativeEquals(instance.particles.potential_energy(G = nbody_system.G), -4531.58416742 | nbody_system.energy, 3) + self.assertAlmostRelativeEquals(instance.particles.potential_energy(G=nbody_system.G), -4531.58416742 | nbody_system.energy, 3) self.assertAlmostRelativeEquals(instance.particles.virial_radius(), 165.694750127 | nbody_system.length, 3) - + instance.cleanup_code() instance.stop() - + def test5(self): print("Testing GalactICs generate_particles") instance = GalactICs(**default_options) @@ -273,15 +270,14 @@ def test5(self): expected_kinetic_energy = 2418.49730735 | nbody_system.energy self.assertAlmostRelativeEquals(instance.particles.total_mass(), mass_halo, accuracy) self.assertAlmostRelativeEquals(instance.particles.kinetic_energy(), expected_kinetic_energy, accuracy) - - self.assertEqual(len(instance.halo_particles),1000) - self.assertEqual(len(instance.disk_particles),0) - self.assertEqual(len(instance.bulge_particles),0) - - + + self.assertEqual(len(instance.halo_particles), 1000) + self.assertEqual(len(instance.disk_particles), 0) + self.assertEqual(len(instance.bulge_particles), 0) + instance.cleanup_code() instance.stop() - + def test6(self): print("Testing GalactICs generate_particles: generate multiple sets") number_of_particles = 1000 @@ -293,11 +289,11 @@ def test6(self): instance.parameters.order_of_multipole_expansion = 0 instance.parameters.halo_random_seed = -1.0 instance.commit_parameters() - + instance.generate_particles() set1 = instance.particles.copy() self.assertEqual(len(set1), number_of_particles) - + instance.generate_particles() set2 = instance.particles.copy() self.assertEqual(len(set2), number_of_particles) @@ -305,7 +301,7 @@ def test6(self): # each time, and the result should be the same: for attribute in ["mass", "x", "y", "z", "vx", "vy", "vz"]: self.assertEqual(getattr(set1, attribute), getattr(set2, attribute)) - + instance.parameters.halo_random_seed = -42.0 instance.generate_particles() # halo_random_seed changed: draw a different random set of particles @@ -315,10 +311,10 @@ def test6(self): self.assertRaises(self.failureException, self.assertEqual, set1.x, set3.x) self.assertAlmostRelativeEquals(abs(set1.x).median(), abs(set3.x).median(), 1) self.assertAlmostRelativeEquals(abs(set1.vy).median(), abs(set3.vy).median(), 1) - + instance.cleanup_code() instance.stop() - + def test7(self): print("Testing GalactICs state") number_of_particles = 1000 @@ -343,7 +339,7 @@ def test7(self): self.assertEqual(instance.get_name_of_current_state(), 'END') instance.stop() - print("initialize_code(), (re)commit_parameters(), update_particle_set(), " \ + print("initialize_code(), (re)commit_parameters(), update_particle_set(), " "and cleanup_code() should be called automatically:") instance = GalactICs(**default_options) self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') @@ -364,4 +360,3 @@ def test7(self): self.assertEqual(instance.get_number_of_particles_updated(), 0) instance.stop() self.assertEqual(instance.get_name_of_current_state(), 'STOPPED') - diff --git a/src/amuse/test/suite/codes_tests/test_galaxia.py b/src/amuse/test/suite/codes_tests/test_galaxia.py index 69dd508fa8..a4741c7d2b 100644 --- a/src/amuse/test/suite/codes_tests/test_galaxia.py +++ b/src/amuse/test/suite/codes_tests/test_galaxia.py @@ -3,14 +3,15 @@ from amuse.community.galaxia.interface import BarAndSpirals3D + class TestBarAndSpirals3D(amusetest.TestCase): def test1(self): - galaxy= BarAndSpirals3D() - self.assertEqual(galaxy.model_time, 0. | units.yr) + galaxy = BarAndSpirals3D() + self.assertEqual(galaxy.model_time, 0. | units.yr) def test2(self): - galaxy= BarAndSpirals3D() - vc1= galaxy.get_velcirc(10. | units.kpc, 0. | units.kpc,0. | units.kpc) - vc2= galaxy.get_velcirc(0. | units.kpc, 10. | units.kpc,0. | units.kpc) - self.assertEqual(vc1,vc2) - self.assertAlmostEqual(vc1, 219.324003066 | units.kms) + galaxy = BarAndSpirals3D() + vc1 = galaxy.get_velcirc(10. | units.kpc, 0. | units.kpc, 0. | units.kpc) + vc2 = galaxy.get_velcirc(0. | units.kpc, 10. | units.kpc, 0. | units.kpc) + self.assertEqual(vc1, vc2) + self.assertAlmostEqual(vc1, 219.324003066 | units.kms) diff --git a/src/amuse/test/suite/codes_tests/test_gravity_codes.py b/src/amuse/test/suite/codes_tests/test_gravity_codes.py index 6ed09af8a1..ca17fd0b0e 100644 --- a/src/amuse/test/suite/codes_tests/test_gravity_codes.py +++ b/src/amuse/test/suite/codes_tests/test_gravity_codes.py @@ -14,23 +14,25 @@ from amuse.units import nbody_system from amuse import datamodel from amuse.ic.plummer import new_plummer_model + + class _TestGravityCodes(TestWithMPI): length_unit = nbody_system.length speed_unit = nbody_system.speed mass_unit = nbody_system.mass time_unit = nbody_system.time - + @property def nbody_converter(self): return None - + def gravity_code_factory(self): self.skip("abstract test") - + def test1(self): factory = self.gravity_code_factory() instance = self.new_instance_of_an_optional_code(factory) - particles = new_plummer_model(100, convert_nbody = self.nbody_converter) + particles = new_plummer_model(100, convert_nbody=self.nbody_converter) particles.radius = 0 | self.length_unit particles.move_to_center() instance.particles.add_particles(particles) @@ -47,9 +49,9 @@ def test1(self): number_of_particles_in_module = instance.legacy_interface.get_number_of_particles()['number_of_particles'] self.assertEqual(number_of_particles_in_module, 100-len(outer)) instance.stop() - + def getset_attribute(self, attributename, attributevalue1, attributevalue2): - + factory = self.gravity_code_factory() instance = self.new_instance_of_an_optional_code(factory) try: @@ -67,30 +69,30 @@ def getset_attribute(self, attributename, attributevalue1, attributevalue2): self.assertAlmostRelativeEqual(actual, attributevalue2) finally: instance.stop() - + def test2(self): self.getset_attribute("radius", 1.0 | self.length_unit, 2.0 | self.length_unit) - + def test3(self): self.getset_attribute("position", [1.0, 2.0, 3.0] | self.length_unit, [5.0, 6.0, 7.0] | self.length_unit) - + def test4(self): self.getset_attribute("velocity", [1.0, 2.0, 3.0] | self.speed_unit, [5.0, 6.0, 7.0] | self.speed_unit) - + def test5(self): self.getset_attribute("mass", 1.0 | self.mass_unit, 2.0 | self.mass_unit) - + def test6(self): factory = self.gravity_code_factory() instance = self.new_instance_of_an_optional_code(factory) try: - particles = new_plummer_model(100, convert_nbody = self.nbody_converter) - more_particles = new_plummer_model(50, convert_nbody = self.nbody_converter) + particles = new_plummer_model(100, convert_nbody=self.nbody_converter) + more_particles = new_plummer_model(50, convert_nbody=self.nbody_converter) particles.radius = 0 | self.length_unit more_particles.radius = 1.0 | self.length_unit particles.move_to_center() more_particles.move_to_center() - + instance.particles.add_particles(particles) instance.commit_particles() self.assertEqual(len(instance.particles), 100) @@ -110,17 +112,16 @@ def test6(self): self.assertEqual(number_of_particles_in_module, 50) finally: instance.stop() - def test7(self): factory = self.gravity_code_factory() instance = self.new_instance_of_an_optional_code(factory) try: - particles = new_plummer_model(100, convert_nbody = self.nbody_converter) - new_particles = new_plummer_model(50, convert_nbody = self.nbody_converter) + particles = new_plummer_model(100, convert_nbody=self.nbody_converter) + new_particles = new_plummer_model(50, convert_nbody=self.nbody_converter) instance.particles.add_particles(particles) instance.commit_particles() - + self.assertEqual(len(instance.particles), 100) instance.synchronize_model() instance.particles.remove_particle(particles[40]) @@ -132,21 +133,20 @@ def test7(self): # if they are implemented for the code, otherwise will call # get_state multiple times # todo, fi fails, need to check with inti - #self.assertAlmostRelativeEqual(instance.particles[-1].mass, new_particles[0].mass) - #self.assertAlmostRelativeEqual(instance.particles[-1].velocity, new_particles[0].velocity) - #self.assertAlmostRelativeEqual(instance.particles[-1].position, new_particles[0].position) + # self.assertAlmostRelativeEqual(instance.particles[-1].mass, new_particles[0].mass) + # self.assertAlmostRelativeEqual(instance.particles[-1].velocity, new_particles[0].velocity) + # self.assertAlmostRelativeEqual(instance.particles[-1].position, new_particles[0].position) instance.particles.synchronize_to(particles) self.assertEqual(len(particles), 99) self.assertEqual(particles[-1], new_particles[0]) finally: instance.stop() - def test8(self): factory = self.gravity_code_factory() instance = self.new_instance_of_an_optional_code(factory) random = numpy.random.mtrand.RandomState(3456) - particles = new_plummer_model(10, convert_nbody = self.nbody_converter, random = random) + particles = new_plummer_model(10, convert_nbody=self.nbody_converter, random=random) particles.radius = 0.2 | self.length_unit particles.move_to_center() instance.particles.add_particles(particles) @@ -156,7 +156,7 @@ def test8(self): instance.evolve_model(1 | self.time_unit) self.assertTrue(collision_detection.is_set()) instance.stop() - + def test9(self): factory = self.gravity_code_factory() instance = self.new_instance_of_an_optional_code(factory) @@ -179,7 +179,7 @@ def test9(self): print((instance.particles.position - instance.particles.center_of_mass()).lengths()) self.assertTrue(stopping_condition.is_set()) instance.stop() - + def test10(self): factory = self.gravity_code_factory() instance = self.new_instance_of_an_optional_code(factory) @@ -188,7 +188,7 @@ def test10(self): particle.velocity = [1, -2, 3.0] | self.speed_unit particle.mass = 1 | self.mass_unit particle.radius = 0.0 | self.length_unit - + instance.particles.add_particle(particle) instance.evolve_model(1 | self.time_unit) self.assertAlmostEqual(instance.model_time, 1 | self.time_unit) @@ -199,65 +199,72 @@ def test10(self): def new_gravity_code(self): self.gravity_code_factory() - - + + class TestBHTreeGravityCode(_TestGravityCodes): - + def gravity_code_factory(self): return BHTree def test9(self): self.skip("no support for out of box detection") + class TestHermiteGravityCode(_TestGravityCodes): - + def gravity_code_factory(self): return Hermite - + def test10(self): self.skip("no support for single particle") - + + class TestPH4GravityCode(_TestGravityCodes): - + def gravity_code_factory(self): return ph4 - + def test9(self): self.skip("no support for out of box detection") + + class TestMI6GravityCode(_TestGravityCodes): - + def gravity_code_factory(self): return MI6 + def test6(self): self.skip("MI6 crashes on removal and addition of particles") + def test7(self): self.skip("MI6 crashes on removal and addition of particles") + def test9(self): self.skip("no support for out of box detection") + def test10(self): self.skip("no support for single particle") - class TestPhiGRAPEGravityCode(_TestGravityCodes): - + def gravity_code_factory(self): return PhiGRAPE - + def slowtestextra0(self): factory = self.gravity_code_factory() instance = self.new_instance_of_an_optional_code(factory, mode='gpu') try: sc = instance.stopping_conditions.collision_detection - + n = 1000 - instance.parameters.initialize_gpu_once=1 + instance.parameters.initialize_gpu_once = 1 sc.enable() - - particles = new_plummer_model(n, convert_nbody = self.nbody_converter) + + particles = new_plummer_model(n, convert_nbody=self.nbody_converter) particles.radius = 1.0 / n | self.length_unit particles.move_to_center() - + instance.particles.add_particles(particles) instance.commit_particles() self.assertEqual(len(instance.particles), n) @@ -267,37 +274,38 @@ def slowtestextra0(self): print(sc.is_set()) if sc.is_set(): particle1 = sc.particles(0)[0] - particle2 = sc.particles(1)[0] + particle2 = sc.particles(1)[0] newparticle = datamodel.Particles(1) newparticle.mass = particle1.mass + particle2.mass newparticle.radius = particle2.radius - newparticle.position = (particle1.position + particle2.position) /2 - newparticle.velocity = (particle1.velocity + particle2.velocity) /2 + newparticle.position = (particle1.position + particle2.position) / 2 + newparticle.velocity = (particle1.velocity + particle2.velocity) / 2 instance.particles.remove_particle(particle1) instance.particles.remove_particle(particle2) merged = instance.particles.add_particles(newparticle) - print('Remnant:\n',merged) - + print('Remnant:\n', merged) + finally: instance.stop() def test9(self): self.skip("no support for out of box detection") - + + class TestFiGravityCode(_TestGravityCodes): - + def gravity_code_factory(self): return Fi def test8(self): self.skip("no support for collision detection") - + def test9(self): self.skip("no support for out of box detection") - + def test10(self): self.skip("no support for single particle") - + class TestGadget2GravityCode(_TestGravityCodes): length_unit = units.parsec @@ -307,20 +315,18 @@ class TestGadget2GravityCode(_TestGravityCodes): @property def nbody_converter(self): return nbody_system.nbody_to_si(1.0 | units.parsec, 100.0 | units.MSun) - + def gravity_code_factory(self): return Gadget2 - - def test2(self): self.skip("no support for setting of radius") - + def test8(self): self.skip("no support for collision detection") - + def test9(self): self.skip("no support for out of box detection") - + def test10(self): self.skip("no support for single particle") diff --git a/src/amuse/test/suite/codes_tests/test_hacs64.py b/src/amuse/test/suite/codes_tests/test_hacs64.py index 38918e1f48..b1b1f8f509 100644 --- a/src/amuse/test/suite/codes_tests/test_hacs64.py +++ b/src/amuse/test/suite/codes_tests/test_hacs64.py @@ -26,19 +26,19 @@ def test0(self): instance = self.new_instance_of_an_optional_code( Hacs64Interface, **default_options) instance.stop() - + def test1(self): instance = self.new_instance_of_an_optional_code( Hacs64Interface, **default_options) instance.initialize_code() instance.commit_parameters() - - res1 = instance.new_particle(mass = 11.0, radius = 2.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) - res2 = instance.new_particle(mass = 21.0, radius = 5.0, x = 10.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) - + + res1 = instance.new_particle(mass=11.0, radius=2.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) + res2 = instance.new_particle(mass=21.0, radius=5.0, x=10.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) + self.assertEqual(0, res1['index_of_the_particle']) self.assertEqual(1, res2['index_of_the_particle']) - + error = instance.commit_particles() self.assertEqual(0, error) retrieved_state1 = instance.get_state(0) @@ -50,7 +50,7 @@ def test1(self): self.assertEqual(0.0, retrieved_state1['x']) self.assertEqual(10.0, retrieved_state2['x']) self.assertEqual(5.0, retrieved_state2['radius']) - + instance.cleanup_code() instance.stop() @@ -61,83 +61,83 @@ def test2(self): instance.commit_parameters() for i in [1, 2, 3]: - temp_particle = instance.new_particle(mass = i, radius = 1.0, x = i * 1.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) + temp_particle = instance.new_particle(mass=i, radius=1.0, x=i * 1.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) self.assertEqual(i-1, temp_particle['index_of_the_particle']) - + error = instance.commit_particles() self.assertEqual(0, error) error = instance.delete_particle(1) self.assertEqual(0, error) error = instance.recommit_particles() self.assertEqual(0, error) - + self.assertEqual(2, instance.get_number_of_particles()['number_of_particles']) - + self.assertEqual(0, instance.get_index_of_first_particle()['index_of_the_particle']) self.assertEqual(2, instance.get_index_of_next_particle(0)['index_of_the_next_particle']) self.assertEqual(0, instance.get_index_of_next_particle(0)['__result']) self.assertEqual(-1, instance.get_index_of_next_particle(1)['__result']) self.assertEqual(1, instance.get_index_of_next_particle(2)['__result']) instance.stop() - + def test3(self): instance = self.new_instance_of_an_optional_code( Hacs64Interface, **default_options) instance.initialize_code() self.assertEqual(0, instance.set_nmax(10)) - self.assertEqual((10,0), tuple(instance.get_nmax())) + self.assertEqual((10, 0), tuple(instance.get_nmax())) self.assertEqual(0, instance.set_dtmax(4)) - self.assertEqual((4,0), tuple(instance.get_dtmax())) + self.assertEqual((4, 0), tuple(instance.get_dtmax())) self.assertEqual(0, instance.set_eps2(2)) - self.assertEqual((2,0), tuple(instance.get_eps2())) - - self.assertEqual(0,instance.commit_parameters()) - + self.assertEqual((2, 0), tuple(instance.get_eps2())) + + self.assertEqual(0, instance.commit_parameters()) + self.assertEqual(-1, instance.set_nmax(11)) - self.assertEqual((10,0), tuple(instance.get_nmax())) + self.assertEqual((10, 0), tuple(instance.get_nmax())) self.assertEqual(-1, instance.set_dtmax(6)) - self.assertEqual((4,0), tuple(instance.get_dtmax())) - - instance.cleanup_code() + self.assertEqual((4, 0), tuple(instance.get_dtmax())) + + instance.cleanup_code() instance.stop() - + def test4(self): instance = self.new_instance_of_an_optional_code( Hacs64Interface, **default_options) instance.initialize_code() self.assertEqual(0, instance.set_h2max(0.1)) - self.assertEqual((0.1,0), tuple(instance.get_h2max())) - - self.assertEqual((0.14,0), tuple(instance.get_eta_reg())) + self.assertEqual((0.1, 0), tuple(instance.get_h2max())) + + self.assertEqual((0.14, 0), tuple(instance.get_eta_reg())) self.assertEqual(0, instance.set_eta_reg(0.4)) - self.assertEqual((0.4,0), tuple(instance.get_eta_reg())) - - self.assertEqual((0.8,0), tuple(instance.get_eta_irr())) + self.assertEqual((0.4, 0), tuple(instance.get_eta_reg())) + + self.assertEqual((0.8, 0), tuple(instance.get_eta_irr())) self.assertEqual(0, instance.set_eta_irr(0.6)) - self.assertEqual((0.6,0), tuple(instance.get_eta_irr())) - - self.assertEqual(0,instance.commit_parameters()) - - instance.cleanup_code() + self.assertEqual((0.6, 0), tuple(instance.get_eta_irr())) + + self.assertEqual(0, instance.commit_parameters()) + + instance.cleanup_code() instance.stop() - + def test5(self): instance = self.new_instance_of_an_optional_code( Hacs64Interface, **default_options) instance.initialize_code() instance.commit_parameters() - - instance.new_particle([10,20],[0,1],[0,0], [0,0], [0,0], [0,0], [0,0],[1,1]) + + instance.new_particle([10, 20], [0, 1], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 1]) instance.commit_particles() retrieved_state = instance.get_state(0) - + self.assertEqual(10.0, retrieved_state['mass']) self.assertEqual(1, retrieved_state['radius']) - - retrieved_state = instance.get_state([0,1]) + + retrieved_state = instance.get_state([0, 1]) self.assertEqual(20.0, retrieved_state['mass'][1]) self.assertEqual(instance.get_number_of_particles()['number_of_particles'], 2) - instance.cleanup_code() + instance.cleanup_code() instance.stop() def test6(self): @@ -145,43 +145,42 @@ def test6(self): Hacs64Interface, **default_options) instance.initialize_code() instance.commit_parameters() - - instance.new_particle([10,10],[-1,1],[0,0], [0,0], [0,0], [0,0], [0,0],[1,1]) + + instance.new_particle([10, 10], [-1, 1], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 1]) instance.commit_particles() - + self.assertFalse(hasattr(instance, "get_potential_at_point")) - #retr, error = instance.get_potential_at_point(0.01, 0,0,0) - #@print retr - #self.assertEqual(error, -1) # TODO: Not IMPLEMENTED yet - - #self.assertEqual(retr['phi'], -20.0) + # retr, error = instance.get_potential_at_point(0.01, 0,0,0) + # @print retr + # self.assertEqual(error, -1) # TODO: Not IMPLEMENTED yet + + # self.assertEqual(retr['phi'], -20.0) instance.cleanup_code() instance.stop() - + def test7(self): instance = self.new_instance_of_an_optional_code( Hacs64Interface, **default_options) instance.initialize_code() instance.set_eps2(0.1 * 0.1) instance.commit_parameters() - id1,errorcode = instance.new_particle(mass = 10.0, radius = 1.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) - id2,errorcode = instance.new_particle(mass = 10.0, radius = 1.0, x = 2.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) - + id1, errorcode = instance.new_particle(mass=10.0, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) + id2, errorcode = instance.new_particle(mass=10.0, radius=1.0, x=2.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) + instance.commit_particles() potential, errorcode = instance.get_potential(id1) self.assertEqual(errorcode, 0) self.assertAlmostRelativeEquals(potential, -10.0 / numpy.sqrt(2.0**2 + 0.1**2), 8) - + potential, errorcode = instance.get_potential(id2) self.assertEqual(errorcode, 0) self.assertAlmostRelativeEquals(potential, -10.0 / numpy.sqrt(2.0**2 + 0.1**2), 8) - + total_potential, errorcode = instance.get_potential_energy() potentials, errorcode = instance.get_potential([id1, id2]) instance.stop() - + self.assertAlmostRelativeEquals(total_potential, numpy.sum(potentials * [10.0, 10.0]) / 2.0) - def test8(self): instance = self.new_instance_of_an_optional_code( @@ -189,9 +188,9 @@ def test8(self): instance.initialize_code() instance.set_eps2(0) instance.commit_parameters() - id1,errorcode = instance.new_particle(mass = 10.0, radius = 1.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) - id2,errorcode = instance.new_particle(mass = 1.0, radius = 1.0, x = 2.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) - + id1, errorcode = instance.new_particle(mass=10.0, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) + id2, errorcode = instance.new_particle(mass=1.0, radius=1.0, x=2.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) + instance.commit_particles() potential, errorcode = instance.get_potential(id1) self.assertEqual(errorcode, 0) @@ -199,38 +198,36 @@ def test8(self): total_potential, errorcode = instance.get_potential_energy() potentials, errorcode = instance.get_potential([id1, id2]) instance.stop() - + self.assertAlmostRelativeEquals(total_potential, numpy.sum(potentials * [10.0, 1.0]) / 2.0) - - + def test9(self): print("Test Hacs64Interface evolve_model") instance = self.new_instance_of_an_optional_code( Hacs64Interface, **default_options) self.assertEqual(0, instance.initialize_code()) - #self.assertEquals(0, instance.set_eta_irr(0.14)) - #self.assertEquals(0, instance.set_eta_reg(0.001)) + # self.assertEquals(0, instance.set_eta_irr(0.14)) + # self.assertEquals(0, instance.set_eta_reg(0.001)) self.assertEqual(0, instance.commit_parameters()) - + # Set up an equal-mass binary on a circular orbit: self.assertEqual([0, 0], list(instance.new_particle(0.5, 0.5, 0, 0, 0, 0.5, 0, 0.01).values())) - self.assertEqual([1, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0,-0.5, 0, 0.01).values())) + self.assertEqual([1, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0, -0.5, 0, 0.01).values())) self.assertEqual(0, instance.commit_particles()) self.assertEqual(0, instance.evolve_model(math.pi)) for result, expected in zip(list(instance.get_position(0).values()), [-0.5, -0.007, 0.0, 0]): self.assertAlmostEqual(result, expected, 3) for result, expected in zip(list(instance.get_position(1).values()), [0.5, 0.007, 0.0, 0]): self.assertAlmostEqual(result, expected, 3) - + self.assertEqual(0, instance.evolve_model(2 * math.pi)) for result, expected in zip(list(instance.get_position(0).values()), [0.5, 0.0147, 0.0, 0]): self.assertAlmostEqual(result, expected, 3) for result, expected in zip(list(instance.get_position(1).values()), [-0.5, -0.0147, 0.0, 0]): self.assertAlmostEqual(result, expected, 3) - + self.assertEqual(0, instance.cleanup_code()) instance.stop() - class _TestHacs64(TestWithMPI): @@ -238,97 +235,92 @@ def new_system_of_sun_and_earth(self): stars = datamodel.Stars(2) sun = stars[0] sun.mass = units.MSun(1.0) - sun.position = units.m(numpy.array((0.0,0.0,0.0))) - sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) + sun.position = units.m(numpy.array((0.0, 0.0, 0.0))) + sun.velocity = units.ms(numpy.array((0.0, 0.0, 0.0))) sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) - earth.radius = units.km(6371) - earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) - earth.velocity = units.ms(numpy.array((0.0,29800,0.0))) - + earth.radius = units.km(6371) + earth.position = units.km(numpy.array((149.5e6, 0.0, 0.0))) + earth.velocity = units.ms(numpy.array((0.0, 29800, 0.0))) + return stars - - + def test1(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) - + instance = self.new_instance_of_an_optional_code( Hacs64, convert_nbody, **default_options) instance.initialize_code() instance.parameters.epsilon_squared = 0.0 | units.AU**2 instance.dt_dia = 5000 - + stars = self.new_system_of_sun_and_earth() earth = stars[1] - + instance.particles.add_particles(stars) - + instance.evolve_model(365.0 | units.day) instance.particles.copy_values_of_all_attributes_to(stars) - + position_at_start = earth.position.value_in(units.AU)[0] position_after_full_rotation = earth.position.value_in(units.AU)[0] self.assertAlmostEqual(position_at_start, position_after_full_rotation, 6) - + instance.evolve_model(365.0 + (365.0 / 2) | units.day) - + instance.particles.copy_values_of_all_attributes_to(stars) position_after_half_a_rotation = earth.position.value_in(units.AU)[0] self.assertAlmostEqual(-position_at_start, position_after_half_a_rotation, 2) - - instance.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) - + + instance.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) + instance.particles.copy_values_of_all_attributes_to(stars) position_after_half_a_rotation = earth.position.value_in(units.AU)[1] self.assertAlmostEqual(-position_at_start, position_after_half_a_rotation, 3) - + instance.cleanup_code() - + instance.stop() - def test2(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) - + instance = self.new_instance_of_an_optional_code( Hacs64, convert_nbody, **default_options) instance.initialize_code() instance.parameters.epsilon_squared = 0.0 | units.AU**2 instance.dt_dia = 5000 - + stars = self.new_system_of_sun_and_earth() earth = stars[1] instance.particles.add_particles(stars) - - for x in range(1,2000,10): + + for x in range(1, 2000, 10): instance.evolve_model(x | units.day) instance.particles.copy_values_of_all_attributes_to(stars) stars.savepoint() - + if HAS_MATPLOTLIB: figure = pyplot.figure() - plot = figure.add_subplot(1,1,1) - + plot = figure.add_subplot(1, 1, 1) + x_points = earth.get_timeline_of_attribute("x") y_points = earth.get_timeline_of_attribute("y") - + x_points_in_AU = [t_x[1].value_in(units.AU) for t_x in x_points] y_points_in_AU = [t_x1[1].value_in(units.AU) for t_x1 in y_points] - - plot.scatter(x_points_in_AU,y_points_in_AU, color = "b", marker = 'o') - + + plot.scatter(x_points_in_AU, y_points_in_AU, color="b", marker='o') + plot.set_xlim(-1.5, 1.5) plot.set_ylim(-1.5, 1.5) - - + test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "instance-earth-sun2.svg") figure.savefig(output_file) - - - + instance.cleanup_code() instance.stop() @@ -340,54 +332,52 @@ def test3(self): instance.initialize_code() instance.parameters.epsilon_squared = 0.00001 | units.AU**2 instance.dt_dia = 5000 - + stars = datamodel.Stars(2) star1 = stars[0] star2 = stars[1] star1.mass = units.MSun(1.0) - star1.position = units.AU(numpy.array((-1.0,0.0,0.0))) - star1.velocity = units.AUd(numpy.array((0.0,0.0,0.0))) + star1.position = units.AU(numpy.array((-1.0, 0.0, 0.0))) + star1.velocity = units.AUd(numpy.array((0.0, 0.0, 0.0))) star1.radius = units.RSun(1.0) star2.mass = units.MSun(1.0) - star2.position = units.AU(numpy.array((1.0,0.0,0.0))) - star2.velocity = units.AUd(numpy.array((0.0,0.0,0.0))) + star2.position = units.AU(numpy.array((1.0, 0.0, 0.0))) + star2.velocity = units.AUd(numpy.array((0.0, 0.0, 0.0))) star2.radius = units.RSun(100.0) - + instance.particles.add_particles(stars) - - for x in range(1,2000,10): + + for x in range(1, 2000, 10): instance.evolve_model(x | units.day) instance.particles.copy_values_of_all_attributes_to(stars) stars.savepoint() - + instance.stop() - + def test4(self): convert_nbody = nbody_system.nbody_to_si(5.0 | units.kg, 10.0 | units.m) instance = self.new_instance_of_an_optional_code( Hacs64, convert_nbody, **default_options) instance.initialize_code() - + particles = datamodel.Particles(2) self.assertEqual(len(instance.particles), 0) - + particles.mass = [15.0, 30.0] | units.kg - particles.radius = [10.0, 20.0] | units.m + particles.radius = [10.0, 20.0] | units.m particles.position = [[10.0, 20.0, 30.0], [20.0, 40.0, 60.0]] | units.m particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.m / units.s - instance.particles.add_particles(particles) self.assertEqual(len(instance.particles), 2) - - instance.particles.mass = [17.0, 33.0] | units.kg - - - self.assertEqual(instance.get_mass(0), 17.0| units.kg) - self.assertEqual(instance.get_mass(1), 33.0| units.kg) + + instance.particles.mass = [17.0, 33.0] | units.kg + + self.assertEqual(instance.get_mass(0), 17.0 | units.kg) + self.assertEqual(instance.get_mass(1), 33.0 | units.kg) instance.stop() def test5(self): @@ -396,66 +386,65 @@ def test5(self): instance = self.new_instance_of_an_optional_code( Hacs64, convert_nbody, **default_options) instance.initialize_code() - + particles = datamodel.Particles(2) self.assertEqual(len(instance.particles), 0) - + particles.mass = [15.0, 30.0] | units.kg - particles.radius = [10.0, 20.0] | units.m + particles.radius = [10.0, 20.0] | units.m particles.position = [[10.0, 20.0, 30.0], [20.0, 40.0, 60.0]] | units.m particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.m / units.s - instance.particles.add_particles(particles) self.assertEqual(len(instance.particles), 2) - instance.set_state(1, 16|units.kg, 20.0|units.m, - 20.0|units.m, 40.0|units.m, 60.0|units.m, - 1.0|units.ms, 1.0|units.ms, 1.0|units.ms) - - curr_state = instance.get_state(1) + instance.set_state(1, 16 | units.kg, 20.0 | units.m, + 20.0 | units.m, 40.0 | units.m, 60.0 | units.m, + 1.0 | units.ms, 1.0 | units.ms, 1.0 | units.ms) + + curr_state = instance.get_state(1) instance.stop() - - self.assertEqual(curr_state[0], 16|units.kg, 8) - + + self.assertEqual(curr_state[0], 16 | units.kg, 8) + def test6(self): print("Test6: Testing Hacs64 parameters") convert_nbody = nbody_system.nbody_to_si(1.0 | units.yr, 1.0 | units.AU) instance = self.new_instance_of_an_optional_code( Hacs64, convert_nbody, **default_options) - + value = instance.get_eps2() - self.assertEqual(0.0 | units.AU**2 , value) + self.assertEqual(0.0 | units.AU**2, value) self.assertAlmostEqual(0.0 | units.AU**2, instance.parameters.epsilon_squared, in_units=units.AU**2) for x in [0.01, 0.1, 0.2]: instance.parameters.epsilon_squared = x | units.AU**2 self.assertAlmostEqual(x | units.AU**2, instance.parameters.epsilon_squared, in_units=units.AU**2) - + value = instance.get_dt_param() self.assertEqual(0.03, value) self.assertAlmostEqual(0.03, instance.parameters.dt_param, in_units=units.none) for x in [0.001, 0.01, 0.1]: instance.parameters.dt_param = x self.assertAlmostEqual(x, instance.parameters.dt_param, in_units=units.none) - + value = instance.get_dt_dia() self.assertAlmostEqual(1.0 | units.yr, value) self.assertAlmostEqual(1.0 | units.yr, instance.parameters.dt_dia, in_units=units.yr) for x in [0.1, 10.0, 100.0]: instance.parameters.dt_dia = x | units.yr self.assertAlmostEqual(x | units.yr, instance.parameters.dt_dia, in_units=units.yr) - + value = instance.get_time() - self.assertEqual(0.0| units.yr, value) + self.assertEqual(0.0 | units.yr, value) self.assertAlmostEqual(0.0 | units.yr, instance.parameters.time, in_units=units.yr) for x in [1.0, 10.0, 100.0]: instance.parameters.time = x | units.yr self.assertAlmostEqual(x | units.yr, instance.parameters.time, in_units=units.yr) instance.stop() - + def test7(self): print("Test7: Testing effect of Hacs64 parameter epsilon_squared") convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) - + particles = datamodel.Particles(2) sun = particles[0] sun.mass = 1.0 | units.MSun @@ -468,10 +457,10 @@ def test7(self): earth.radius = 6371.0 | units.km earth.position = [0.0, 1.0, 0.0] | units.AU earth.velocity = [2.0*numpy.pi, -0.0001, 0.0] | units.AU / units.yr - + initial_direction = math.atan((earth.velocity[0]/earth.velocity[1])) final_direction = [] - for log_eps2 in range(-9,10,2): + for log_eps2 in range(-9, 10, 2): instance = self.new_instance_of_an_optional_code( Hacs64, convert_nbody, **default_options) instance.initialize_code() @@ -479,7 +468,7 @@ def test7(self): instance.particles.add_particles(particles) instance.commit_particles() instance.evolve_model(0.25 | units.yr) - final_direction.append(math.atan((instance.particles[1].velocity[0]/ + final_direction.append(math.atan((instance.particles[1].velocity[0] / instance.particles[1].velocity[1]))) instance.stop() # Small values of epsilon_squared should result in normal earth-sun dynamics: rotation of 90 degrees @@ -488,8 +477,8 @@ def test7(self): self.assertAlmostEqual(final_direction[-1], initial_direction, 2) # Outcome is most sensitive to epsilon_squared when epsilon_squared = d(earth, sun)^2 delta = [abs(final_direction[i+1]-final_direction[i]) for i in range(len(final_direction)-1)] - self.assertEqual(delta[len(final_direction)/2 -1], max(delta)) - + self.assertEqual(delta[len(final_direction)/2 - 1], max(delta)) + def test8(self): print("Testing Hacs64 collision_detection") particles = datamodel.Particles(7) @@ -499,7 +488,7 @@ def test8(self): particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.velocity = [[2, 0, 0], [-2, 0, 0]]*3 + [[-4, 0, 0]] | nbody_system.speed - + instance = self.new_instance_of_an_optional_code( Hacs64, **default_options) instance.initialize_code() @@ -508,28 +497,28 @@ def test8(self): collisions = instance.stopping_conditions.collision_detection collisions.enable() instance.evolve_model(1.0 | nbody_system.time) - + self.assertTrue(collisions.is_set()) self.assertTrue(instance.model_time < 0.5 | nbody_system.time) self.assertEqual(len(collisions.particles(0)), 3) self.assertEqual(len(collisions.particles(1)), 3) self.assertEqual(len(particles - collisions.particles(0) - collisions.particles(1)), 1) - self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < + self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < (collisions.particles(0).radius + collisions.particles(1).radius), [True, True, True]) - + sticky_merged = datamodel.Particles(len(collisions.particles(0))) sticky_merged.mass = collisions.particles(0).mass + collisions.particles(1).mass sticky_merged.radius = collisions.particles(0).radius for p1, p2, merged in zip(collisions.particles(0), collisions.particles(1), sticky_merged): merged.position = (p1 + p2).center_of_mass() merged.velocity = (p1 + p2).center_of_mass_velocity() - + print(instance.model_time) print(instance.particles) instance.particles.remove_particles(collisions.particles(0) + collisions.particles(1)) instance.particles.add_particles(sticky_merged) - + instance.evolve_model(1.0 | nbody_system.time) print() print(instance.model_time) @@ -539,14 +528,14 @@ def test8(self): self.assertEqual(len(collisions.particles(0)), 1) self.assertEqual(len(collisions.particles(1)), 1) self.assertEqual(len(instance.particles - collisions.particles(0) - collisions.particles(1)), 2) - self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < + self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < (collisions.particles(0).radius + collisions.particles(1).radius), [True]) instance.stop() - + def test9(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) - + instance = self.new_instance_of_an_optional_code( Hacs64, convert_nbody, **default_options) instance.initialize_code() @@ -554,139 +543,138 @@ def test9(self): instance.parameters.pair_factor = 1e14 stars = self.new_system_of_sun_and_earth() earth = stars[1] - + instance.particles.add_particles(stars) instance.stopping_conditions.pair_detection.enable() instance.evolve_model(365.0 | units.day) self.assertTrue(instance.stopping_conditions.pair_detection.is_set()) instance.particles.copy_values_of_all_attributes_to(stars) - + position_at_start = earth.position.value_in(units.AU)[0] position_after_full_rotation = earth.position.value_in(units.AU)[0] self.assertAlmostEqual(position_at_start, position_after_full_rotation, 6) - + print(instance.model_time) - + print(instance.stopping_conditions.pair_detection.particles(0).key) print(instance.stopping_conditions.pair_detection.particles(1).key) - + instance.cleanup_code() - + instance.stop() - + def test10(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) - + instance = self.new_instance_of_an_optional_code( Hacs64, convert_nbody, **default_options) instance.initialize_code() instance.parameters.epsilon_squared = 0.0 | units.AU**2 instance.parameters.stopping_conditions_number_of_steps = 10 - self.assertEqual(instance.parameters.stopping_conditions_number_of_steps,10) - + self.assertEqual(instance.parameters.stopping_conditions_number_of_steps, 10) + stars = self.new_system_of_sun_and_earth() earth = stars[1] - + instance.particles.add_particles(stars) instance.stopping_conditions.number_of_steps_detection.enable() instance.evolve_model(365.0 | units.day) self.assertTrue(instance.stopping_conditions.number_of_steps_detection.is_set()) instance.particles.copy_values_of_all_attributes_to(stars) - + instance.cleanup_code() - + instance.stop() def test11(self): particles = datamodel.Particles(2) - particles.x = [0.0,10.0] | nbody_system.length + particles.x = [0.0, 10.0] | nbody_system.length particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.radius = 0.005 | nbody_system.length - particles.vx = 0 | nbody_system.speed - particles.vy = 0 | nbody_system.speed - particles.vz = 0 | nbody_system.speed + particles.vx = 0 | nbody_system.speed + particles.vy = 0 | nbody_system.speed + particles.vz = 0 | nbody_system.speed particles.mass = 1.0 | nbody_system.mass - + instance = self.new_instance_of_an_optional_code( Hacs64, **default_options) instance.initialize_code() instance.parameters.stopping_conditions_number_of_steps = 2 self.assertEqual(instance.parameters.stopping_conditions_number_of_steps, 2) - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.stopping_conditions.number_of_steps_detection.enable() instance.evolve_model(10 | nbody_system.time) self.assertTrue(instance.stopping_conditions.number_of_steps_detection.is_set()) self.assertTrue(instance.model_time < 10 | nbody_system.time) - + instance.stop() def test12(self): particles = datamodel.Particles(2) - particles.x = [0.0,1.00] | nbody_system.length - particles.y = [0.0,0.0] | nbody_system.length - particles.z = [0.0,0.0] | nbody_system.length + particles.x = [0.0, 1.00] | nbody_system.length + particles.y = [0.0, 0.0] | nbody_system.length + particles.z = [0.0, 0.0] | nbody_system.length particles.radius = 0.005 | nbody_system.length - particles.vx = [5.1,0.0] | nbody_system.speed - particles.vy = [0.0,0.0] | nbody_system.speed - particles.vz = [0.0,0.0]| nbody_system.speed - particles.mass = [0.1,0.1] | nbody_system.mass - + particles.vx = [5.1, 0.0] | nbody_system.speed + particles.vy = [0.0, 0.0] | nbody_system.speed + particles.vz = [0.0, 0.0] | nbody_system.speed + particles.mass = [0.1, 0.1] | nbody_system.mass + instance = self.new_instance_of_an_optional_code( Hacs64, **default_options) instance.initialize_code() instance.parameters.stopping_conditions_out_of_box_size = .5 | nbody_system.length self.assertEqual(instance.parameters.stopping_conditions_out_of_box_size, .5 | nbody_system.length) - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.stopping_conditions.out_of_box_detection.enable() instance.evolve_model(0.1 | nbody_system.time) self.assertTrue(instance.stopping_conditions.out_of_box_detection.is_set()) - self.assertAlmostEqual(instance.stopping_conditions.out_of_box_detection.particles(0).x, 1.0 |nbody_system.length, 3) + self.assertAlmostEqual(instance.stopping_conditions.out_of_box_detection.particles(0).x, 1.0 | nbody_system.length, 3) instance.stop() def test13(self): particles = plummer.new_plummer_model(31) - + instance = self.new_instance_of_an_optional_code( Hacs64, number_of_workers=1, **default_options) instance.initialize_code() instance.parameters.epsilon_squared = 0.01 | nbody_system.length ** 2 instance.particles.add_particles(particles) - + instance.evolve_model(0.1 | nbody_system.time) instance.synchronize_model() expected_positions = instance.particles.position instance.stop() positions_per_workers = [] - for n in [2,3,4,5]: + for n in [2, 3, 4, 5]: instance = self.new_instance_of_an_optional_code( Hacs64, number_of_workers=n, **default_options) instance.initialize_code() instance.parameters.epsilon_squared = 0.01 | nbody_system.length ** 2 instance.particles.add_particles(particles) - + instance.evolve_model(0.1 | nbody_system.time) instance.synchronize_model() positions_per_workers.append(instance.particles.position) instance.stop() - - - for index, n in enumerate([2,3,4,5]): + + for index, n in enumerate([2, 3, 4, 5]): self.assertAlmostEqual(expected_positions, positions_per_workers[index], 15) - + def test14(self): instance = self.new_instance_of_an_optional_code( Hacs64, **default_options) instance.initialize_code() instance.parameters.epsilon_squared = 0.00001 | nbody_system.length**2 - + particles = datamodel.Particles(2) particles.mass = [1.0, 1.0] | nbody_system.mass - particles.radius = [0.0001, 0.0001] | nbody_system.length - particles.position = [[0.0,0.0,0.0], [2.0,0.0,0.0]] | nbody_system.length + particles.radius = [0.0001, 0.0001] | nbody_system.length + particles.position = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]] | nbody_system.length particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed instance.particles.add_particles(particles) - + zero = 0.0 | nbody_system.length fx, fy, fz = instance.get_gravity_at_point(zero, 1.0 | nbody_system.length, zero, zero) self.assertAlmostEqual(fx, 0.0 | nbody_system.acceleration, 6) @@ -700,15 +688,14 @@ def test14(self): potential1 = instance.get_potential_at_point(zero, x1, zero, zero) fx0, fy0, fz0 = instance.get_gravity_at_point(zero, x0, zero, zero) fx1, fy1, fz1 = instance.get_gravity_at_point(zero, x1, zero, zero) - + self.assertAlmostEqual(fy0, 0.0 | nbody_system.acceleration, 6) self.assertAlmostEqual(fz0, 0.0 | nbody_system.acceleration, 6) self.assertAlmostEqual(fy1, 0.0 | nbody_system.acceleration, 6) self.assertAlmostEqual(fz1, 0.0 | nbody_system.acceleration, 6) - + self.assertAlmostEqual(fx0, -1.0 * fx1, 5) fx = (-1.0 / (x0**2) + 1.0 / (x1**2)) * (1.0 | nbody_system.length ** 3 / nbody_system.time ** 2) self.assertAlmostEqual(fx, fx0, 2) self.assertAlmostEqual(potential0, potential1, 5) instance.stop() - diff --git a/src/amuse/test/suite/codes_tests/test_halogen.py b/src/amuse/test/suite/codes_tests/test_halogen.py index 0ae2fd740e..bf4ea5a645 100644 --- a/src/amuse/test/suite/codes_tests/test_halogen.py +++ b/src/amuse/test/suite/codes_tests/test_halogen.py @@ -8,10 +8,11 @@ # Change the default for some Halogen(-Interface) keyword arguments: default_options = dict() -#default_options = dict(redirection = "none") +# default_options = dict(redirection = "none") + class HalogenInterfaceTests(TestWithMPI): - + def test1(self): print("Testing HalogenInterface initialization") instance = HalogenInterface(**default_options) @@ -23,12 +24,12 @@ def test1(self): self.assertEqual(instance.commit_parameters(), 0) self.assertEqual(instance.cleanup_code(), 0) instance.stop() - + def test2(self): print("Testing HalogenInterface parameters") instance = HalogenInterface(**default_options) self.assertEqual(instance.initialize_code(), 0) - + self.assertEqual(instance.set_model_alpha(2.0), 0) self.assertEqual(instance.set_model_beta(5.0), 0) self.assertEqual(instance.set_model_gamma(0.0), 0) @@ -39,7 +40,7 @@ def test2(self): self.assertEqual(instance.set_cutoff_radius(9.0), 0) self.assertEqual(instance.set_black_hole_mass(9.0), 0) self.assertEqual(instance.set_do_exact_virial_radius_flag(1.0), 0) - + self.assertEqual([2.0, 0], list(instance.get_model_alpha().values())) self.assertEqual([5.0, 0], list(instance.get_model_beta().values())) self.assertEqual([0.0, 0], list(instance.get_model_gamma().values())) @@ -50,10 +51,10 @@ def test2(self): self.assertEqual([9.0, 0], list(instance.get_cutoff_radius().values())) self.assertEqual([9.0, 0], list(instance.get_black_hole_mass().values())) self.assertEqual([1.0, 0], list(instance.get_do_exact_virial_radius_flag().values())) - + self.assertEqual(instance.cleanup_code(), 0) instance.stop() - + def test3(self): print("Testing HalogenInterface generate_particles") number_of_particles = 100000 @@ -66,100 +67,96 @@ def test3(self): self.assertEqual(instance.set_random_seed(1), 0) self.assertEqual(instance.set_output_path(instance.get_output_directory()), 0) self.assertEqual(instance.commit_parameters(), 0) - + self.assertEqual(list(instance.get_number_of_particles_updated().values()), [0, 0]) self.assertEqual(instance.generate_particles(), 0) self.assertEqual(list(instance.get_number_of_particles_updated().values()), [number_of_particles, 0]) - + masses, errors = instance.get_mass(range(number_of_particles)) self.assertEqual(errors, numpy.zeros(number_of_particles)) self.assertEqual(masses, numpy.ones(number_of_particles)/number_of_particles) - + x_positions, y_positions, z_positions, errors = instance.get_position(range(number_of_particles)) self.assertEqual(errors, numpy.zeros(number_of_particles)) - self.assertAlmostEqual(numpy.array([numpy.mean(x_positions), numpy.mean(y_positions), + self.assertAlmostEqual(numpy.array([numpy.mean(x_positions), numpy.mean(y_positions), numpy.mean(z_positions)]), numpy.array([0.0]*3)) - self.assertAlmostEqual(numpy.array([numpy.mean(abs(x_positions)), numpy.mean(abs(y_positions)), + self.assertAlmostEqual(numpy.array([numpy.mean(abs(x_positions)), numpy.mean(abs(y_positions)), numpy.mean(abs(z_positions))]), numpy.array([1.0]*3), 1) - + x_velocities, y_velocities, z_velocities, errors = instance.get_velocity(range(number_of_particles)) self.assertEqual(errors, numpy.zeros(number_of_particles)) - self.assertAlmostEqual(numpy.array([numpy.mean(x_velocities), numpy.mean(y_velocities), + self.assertAlmostEqual(numpy.array([numpy.mean(x_velocities), numpy.mean(y_velocities), numpy.mean(z_velocities)]), numpy.array([0.0]*3)) - self.assertAlmostEqual(numpy.array([numpy.mean(abs(x_velocities)), numpy.mean(abs(y_velocities)), + self.assertAlmostEqual(numpy.array([numpy.mean(abs(x_velocities)), numpy.mean(abs(y_velocities)), numpy.mean(abs(z_velocities))]), numpy.array([0.25]*3), 1) - + self.assertEqual(instance.cleanup_code(), 0) instance.stop() - + def test4(self): print("Testing HalogenInterface output file name and directory") instance = HalogenInterface(**default_options) self.assertEqual(instance.initialize_code(), 0) - + self.assertEqual(instance.set_model_alpha(2.0), 0) self.assertEqual(instance.set_model_beta(5.0), 0) self.assertEqual(instance.set_model_gamma(0.0), 0) self.assertEqual(instance.set_target_number_of_particles(1000), 0) self.assertEqual(instance.set_random_seed(1), 0) self.assertEqual(instance.set_write_output_flag(1.0), 0) - + self.assertEqual(list(instance.get_output_basename().values()), ["halogen", 0]) self.assertEqual(list(instance.get_output_path().values()), ["./", 0]) - + self.assertEqual(instance.set_output_basename("oops_this_output_basename_is_way_too_long"*2), -1) self.assertEqual(list(instance.get_output_basename().values()), ["halogen", 0]) self.assertEqual(instance.set_output_path("/oops/this/output/path/has/way/too/many/subdirs"*6), -1) self.assertEqual(list(instance.get_output_path().values()), ["./", 0]) - + self.assertEqual(instance.set_output_basename("test"), 0) self.assertEqual(instance.set_output_path(instance.get_output_directory()), 0) - + self.assertEqual(list(instance.get_output_basename().values()), ["test", 0]) - self.assertEqual(list(instance.get_output_path().values()), + self.assertEqual(list(instance.get_output_path().values()), [os.path.join(instance.get_output_directory(), ""), 0]) - + self.assertEqual(instance.commit_parameters(), 0) outputfile = os.path.join(instance.get_output_directory(), "test.IC.ascii") if os.path.exists(outputfile): os.remove(outputfile) self.assertEqual(instance.generate_particles(), 0) self.assertTrue(os.path.exists(outputfile)) - - + halogen4muse_path = os.path.join(os.path.dirname(amuse.community.halogen.__file__), 'src', 'halogen4muse') - + if not os.path.exists(halogen4muse_path) or not os.access(halogen4muse_path, os.X_OK): return - + process = subprocess.Popen([ - halogen4muse_path, - '-a', '2', - '-b', '5', - '-c', '0', - '-N', '1000', - '-name', 'test_stand_alone', + halogen4muse_path, + '-a', '2', + '-b', '5', + '-c', '0', + '-N', '1000', + '-name', 'test_stand_alone', '-randomseed', '1' - ] - , cwd = instance.get_output_directory() - , stdout = subprocess.PIPE - , stderr = subprocess.PIPE + ], cwd=instance.get_output_directory(), stdout=subprocess.PIPE, stderr=subprocess.PIPE ) process.communicate() - + self.compare_files( os.path.join(instance.get_output_directory(), "test.IC.ascii"), os.path.join(instance.get_output_directory(), "test_stand_alone.IC.ascii") ) - stdoutput = subprocess.Popen(["diff", "test.out", "test_stand_alone.out"], - cwd = instance.get_output_directory(), stdout = subprocess.PIPE).communicate()[0] - stdoutput=stdoutput.decode() + stdoutput = subprocess.Popen(["diff", "test.out", "test_stand_alone.out"], + cwd=instance.get_output_directory(), stdout=subprocess.PIPE).communicate()[0] + stdoutput = stdoutput.decode() self.assertTrue("< N/A (executed by AMUSE)" in stdoutput) self.assertTrue("halogen4muse -a 2 -b 5 -c 0 -N 1000 -name test_stand_alone -randomseed 1" in stdoutput) - + self.assertEqual(instance.cleanup_code(), 0) instance.stop() - + def compare_files(self, filename1, filename2): with open(filename1) as stream1: lines1 = stream1.readlines() @@ -180,78 +177,78 @@ def compare_files(self, filename1, filename2): float(column2), 8 ) - - + + class HalogenTests(TestWithMPI): - + default_unit_converter = nbody_system.nbody_to_si(1.0 | units.kpc, 1.0e6 | units.MSun) - + def test1(self): print("Testing Halogen initialization") instance = Halogen(**default_options) instance.initialize_code() instance.cleanup_code() instance.stop() - + def test2(self): print("Testing Halogen parameters (with unit converter)") instance = Halogen(self.default_unit_converter, **default_options) instance.initialize_code() - - for par, value in [('do_exact_virial_radius_flag', False), - ('outputgridr_flag', False), ('outputgriddf_flag', False), + + for par, value in [('do_exact_virial_radius_flag', False), + ('outputgridr_flag', False), ('outputgriddf_flag', False), ('write_output_flag', False)]: self.assertTrue(value is getattr(instance.parameters, par)) setattr(instance.parameters, par, not value) self.assertFalse(value is getattr(instance.parameters, par)) - + for par, value in [('alpha', -1.0), ('beta', -1.0), ('gamma', -1.0), ('number_of_particles', -1), ('random_seed', 42)]: self.assertEqual(value, getattr(instance.parameters, par)) setattr(instance.parameters, par, 1) self.assertEqual(1, getattr(instance.parameters, par)) - - for par, value in [('total_mass', 1.0 | nbody_system.mass), - ('scale_radius', 1.0 | nbody_system.length), - ('cutoff_radius', -1.0 | nbody_system.length), + + for par, value in [('total_mass', 1.0 | nbody_system.mass), + ('scale_radius', 1.0 | nbody_system.length), + ('cutoff_radius', -1.0 | nbody_system.length), ('black_hole_mass', 0.0 | nbody_system.mass)]: - self.assertEqual(instance.unit_converter.to_si(value), + self.assertEqual(instance.unit_converter.to_si(value), getattr(instance.parameters, par)) setattr(instance.parameters, par, 3.0 | value.unit) self.assertEqual(instance.unit_converter.to_si(3.0 | value.unit), getattr(instance.parameters, par)) - - for par, value in [('output_directory', os.path.join(instance.get_output_directory(), "")), + + for par, value in [('output_directory', os.path.join(instance.get_output_directory(), "")), ('output_basename', "halogen")]: self.assertEqual(value, getattr(instance.parameters, par)) setattr(instance.parameters, par, 'test/') self.assertEqual("test/", getattr(instance.parameters, par)) - + instance.cleanup_code() instance.stop() - + def test3(self): print("Testing Halogen parameters (nbody units, no converter)") instance = Halogen(**default_options) instance.initialize_code() - - for par, value in [('total_mass', 1.0 | nbody_system.mass), - ('scale_radius', 1.0 | nbody_system.length), - ('cutoff_radius', -1.0 | nbody_system.length), + + for par, value in [('total_mass', 1.0 | nbody_system.mass), + ('scale_radius', 1.0 | nbody_system.length), + ('cutoff_radius', -1.0 | nbody_system.length), ('black_hole_mass', 0.0 | nbody_system.mass)]: self.assertEqual(value, getattr(instance.parameters, par)) setattr(instance.parameters, par, 3.0 | value.unit) self.assertEqual(3.0 | value.unit, getattr(instance.parameters, par)) instance.cleanup_code() instance.stop() - + def test4(self): print("Testing Halogen generate_particles") number_of_particles = 100 instance = Halogen(**default_options) instance.initialize_code() instance.parameters.alpha = 2.0 - instance.parameters.beta = 5.0 + instance.parameters.beta = 5.0 instance.parameters.gamma = 0.0 instance.parameters.number_of_particles = number_of_particles instance.parameters.random_seed = 1 @@ -259,32 +256,32 @@ def test4(self): instance.generate_particles() self.assertEqual(len(instance.particles), number_of_particles) self.assertAlmostEqual(instance.particles.total_mass(), 1.0 | nbody_system.mass) - self.assertAlmostEqual(instance.particles.kinetic_energy(), + self.assertAlmostEqual(instance.particles.kinetic_energy(), 0.17345836639 | nbody_system.energy) - self.assertAlmostEqual(instance.particles.potential_energy(G = nbody_system.G), + self.assertAlmostEqual(instance.particles.potential_energy(G=nbody_system.G), -0.310395778644 | nbody_system.energy) - self.assertAlmostEqual(instance.particles.virial_radius(), + self.assertAlmostEqual(instance.particles.virial_radius(), 1.61084664935 | nbody_system.length) - + instance.cleanup_code() instance.stop() - + def test5(self): print("Testing Halogen generate_particles: generate multiple sets") number_of_particles = 1000 instance = Halogen(**default_options) instance.initialize_code() instance.parameters.alpha = 2.0 - instance.parameters.beta = 5.0 + instance.parameters.beta = 5.0 instance.parameters.gamma = 0.0 instance.parameters.number_of_particles = number_of_particles instance.parameters.random_seed = 1 instance.commit_parameters() - + instance.generate_particles() set1 = instance.particles.copy() self.assertEqual(len(set1), number_of_particles) - + instance.parameters.random_seed = 1 instance.generate_particles() set2 = instance.particles.copy() @@ -293,7 +290,7 @@ def test5(self): # called, re-seeding, and the result should be the same: for attribute in ["mass", "x", "y", "z", "vx", "vy", "vz"]: self.assertEqual(getattr(set1, attribute), getattr(set2, attribute)) - + instance.generate_particles() # No parameter change: draw the next random set of particles set3 = instance.particles.copy() @@ -302,10 +299,10 @@ def test5(self): self.assertRaises(self.failureException, self.assertEqual, set1.x, set3.x) self.assertIsOfOrder(abs(set1.x).median(), abs(set3.x).median(), 1) self.assertAlmostEqual(abs(set1.vy).median(), abs(set3.vy).median(), 1) - + instance.cleanup_code() instance.stop() - + def test6(self): print("Testing Halogen state") number_of_particles = 1000 @@ -316,7 +313,7 @@ def test6(self): instance.initialize_code() self.assertEqual(instance.get_name_of_current_state(), 'INITIALIZED') instance.parameters.alpha = 2.0 - instance.parameters.beta = 5.0 + instance.parameters.beta = 5.0 instance.parameters.gamma = 0.0 instance.parameters.number_of_particles = number_of_particles instance.parameters.random_seed = 1 @@ -331,12 +328,12 @@ def test6(self): self.assertEqual(instance.get_name_of_current_state(), 'END') instance.stop() - print("initialize_code(), (re)commit_parameters(), update_particle_set(), " \ + print("initialize_code(), (re)commit_parameters(), update_particle_set(), " "and cleanup_code() should be called automatically:") instance = Halogen(**default_options) self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') instance.parameters.alpha = 2.0 - instance.parameters.beta = 5.0 + instance.parameters.beta = 5.0 instance.parameters.gamma = 0.0 instance.parameters.number_of_particles = number_of_particles instance.parameters.random_seed = 1 @@ -353,36 +350,30 @@ def test6(self): self.assertEqual(instance.get_number_of_particles_updated(), 0) instance.stop() self.assertEqual(instance.get_name_of_current_state(), 'STOPPED') - + def test7(self): print("Testing Halogen error handling") number_of_particles = 1000 instance = Halogen(**default_options) instance.initialize_code() - self.assertRaises(exceptions.AmuseException, instance.commit_parameters, expected_message = - "Error when calling 'commit_parameters' of a 'Halogen', errorcode is -2, error is " + self.assertRaises(exceptions.AmuseException, instance.commit_parameters, expected_message="Error when calling 'commit_parameters' of a 'Halogen', errorcode is -2, error is " "'Missing or bad parameter for halo (see amuse/community/halogen/src/doc for details on required parameters).'") instance.parameters.alpha = 2.0 - instance.parameters.beta = 5.0 + instance.parameters.beta = 5.0 instance.parameters.gamma = 5.0 instance.parameters.number_of_particles = number_of_particles instance.parameters.random_seed = 1 - self.assertRaises(exceptions.AmuseException, instance.commit_parameters, expected_message = - "Error when calling 'commit_parameters' of a 'Halogen', errorcode is -2, error is " + self.assertRaises(exceptions.AmuseException, instance.commit_parameters, expected_message="Error when calling 'commit_parameters' of a 'Halogen', errorcode is -2, error is " "'Missing or bad parameter for halo (see amuse/community/halogen/src/doc for details on required parameters).'") instance.parameters.gamma = -0.5 - self.assertRaises(exceptions.AmuseException, instance.commit_parameters, expected_message = - "Error when calling 'commit_parameters' of a 'Halogen', errorcode is -2, error is " + self.assertRaises(exceptions.AmuseException, instance.commit_parameters, expected_message="Error when calling 'commit_parameters' of a 'Halogen', errorcode is -2, error is " "'Missing or bad parameter for halo (see amuse/community/halogen/src/doc for details on required parameters).'") instance.parameters.gamma = 0.0 - instance.parameters.beta = 2.0 - self.assertRaises(exceptions.AmuseException, instance.commit_parameters, expected_message = - "Error when calling 'commit_parameters' of a 'Halogen', errorcode is -2, error is " + instance.parameters.beta = 2.0 + self.assertRaises(exceptions.AmuseException, instance.commit_parameters, expected_message="Error when calling 'commit_parameters' of a 'Halogen', errorcode is -2, error is " "'Missing or bad parameter for halo (see amuse/community/halogen/src/doc for details on required parameters).'") - instance.parameters.beta = 5.0 + instance.parameters.beta = 5.0 instance.commit_parameters() - + instance.cleanup_code() instance.stop() - - diff --git a/src/amuse/test/suite/codes_tests/test_hermite.py b/src/amuse/test/suite/codes_tests/test_hermite.py index 5846c41b65..3d5cc39e97 100644 --- a/src/amuse/test/suite/codes_tests/test_hermite.py +++ b/src/amuse/test/suite/codes_tests/test_hermite.py @@ -33,10 +33,10 @@ def test6(self): hermite = HermiteInterface() hermite.initialize_code() - hermite.new_particle([10,10],[-1,1],[0,0], [0,0], [0,0], [0,0], [0,0], [1,1]) + hermite.new_particle([10, 10], [-1, 1], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 1]) retrieved_state = hermite.get_state(0) - retr = hermite.get_potential_at_point(0.01, 0,0,0) + retr = hermite.get_potential_at_point(0.01, 0, 0, 0) self.assertEqual(retr['phi'], -20.0) hermite.cleanup_code() hermite.stop() @@ -46,8 +46,8 @@ def test7(self): instance.initialize_code() instance.set_eps2(0.1 * 0.1) instance.commit_parameters() - id1,errorcode = instance.new_particle(mass=10.0, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) - id2,errorcode = instance.new_particle(mass=10.0, radius=1.0, x=2.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) + id1, errorcode = instance.new_particle(mass=10.0, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) + id2, errorcode = instance.new_particle(mass=10.0, radius=1.0, x=2.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) instance.commit_particles() potential, errorcode = instance.get_potential(id1) @@ -65,14 +65,13 @@ def test7(self): self.assertAlmostRelativeEquals(total_potential, numpy.sum(potentials * [10.0, 10.0]) / 2.0) - def test8(self): instance = HermiteInterface() instance.initialize_code() instance.set_eps2(0) instance.commit_parameters() - id1,errorcode = instance.new_particle(mass=10.0, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) - id2,errorcode = instance.new_particle(mass=1.0, radius=1.0, x=2.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) + id1, errorcode = instance.new_particle(mass=10.0, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) + id2, errorcode = instance.new_particle(mass=1.0, radius=1.0, x=2.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) instance.commit_particles() potential, errorcode = instance.get_potential(id1) @@ -85,7 +84,6 @@ def test8(self): self.assertAlmostRelativeEquals(total_potential, numpy.sum(potentials * [10.0, 1.0]) / 2.0) - def test9(self): print("Test HermiteInterface evolve_model") instance = HermiteInterface() @@ -96,7 +94,7 @@ def test9(self): # Set up an equal-mass binary on a circular orbit: self.assertEqual([0, 0], list(instance.new_particle(0.5, 0.5, 0, 0, 0, 0.5, 0, 0.01).values())) - self.assertEqual([1, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0,-0.5, 0, 0.01).values())) + self.assertEqual([1, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0, -0.5, 0, 0.01).values())) self.assertEqual(0, instance.commit_particles()) self.assertEqual(0, instance.evolve_model(math.pi)) @@ -121,19 +119,18 @@ def new_system_of_sun_and_earth(self): stars = datamodel.Stars(2) sun = stars[0] sun.mass = units.MSun(1.0) - sun.position = units.m(numpy.array((0.0,0.0,0.0))) - sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) + sun.position = units.m(numpy.array((0.0, 0.0, 0.0))) + sun.velocity = units.ms(numpy.array((0.0, 0.0, 0.0))) sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) - earth.radius = units.km(6371) - earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) - earth.velocity = units.ms(numpy.array((0.0,29800,0.0))) + earth.radius = units.km(6371) + earth.position = units.km(numpy.array((149.5e6, 0.0, 0.0))) + earth.velocity = units.ms(numpy.array((0.0, 29800, 0.0))) return stars - def test1(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) @@ -161,7 +158,7 @@ def test1(self): position_after_half_a_rotation = earth.position.value_in(units.AU)[0] self.assertAlmostRelativeEqual(-position_at_start, position_after_half_a_rotation, 3) - hermite.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) + hermite.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) hermite.particles.copy_values_of_all_attributes_to(stars) position_after_half_a_rotation = earth.position.value_in(units.AU)[1] @@ -170,7 +167,6 @@ def test1(self): hermite.cleanup_code() hermite.stop() - def test2(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) @@ -190,7 +186,7 @@ def test2(self): if HAS_MATPLOTLIB: figure = pyplot.figure() - plot = figure.add_subplot(1,1,1) + plot = figure.add_subplot(1, 1, 1) x_points = earth.get_timeline_of_attribute("x") y_points = earth.get_timeline_of_attribute("y") @@ -198,18 +194,15 @@ def test2(self): x_points_in_AU = [t_x[1].value_in(units.AU) for t_x in x_points] y_points_in_AU = [t_x1[1].value_in(units.AU) for t_x1 in y_points] - plot.scatter(x_points_in_AU,y_points_in_AU, color="b", marker='o') + plot.scatter(x_points_in_AU, y_points_in_AU, color="b", marker='o') plot.set_xlim(-1.5, 1.5) plot.set_ylim(-1.5, 1.5) - test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "hermite-earth-sun2.svg") figure.savefig(output_file) - - instance.cleanup_code() instance.stop() @@ -226,23 +219,22 @@ def test3(self): star2 = stars[1] star1.mass = units.MSun(1.0) - star1.position = units.AU(numpy.array((-1.0,0.0,0.0))) - star1.velocity = units.AUd(numpy.array((0.0,0.0,0.0))) + star1.position = units.AU(numpy.array((-1.0, 0.0, 0.0))) + star1.velocity = units.AUd(numpy.array((0.0, 0.0, 0.0))) star1.radius = units.RSun(1.0) star2.mass = units.MSun(1.0) - star2.position = units.AU(numpy.array((1.0,0.0,0.0))) - star2.velocity = units.AUd(numpy.array((0.0,0.0,0.0))) + star2.position = units.AU(numpy.array((1.0, 0.0, 0.0))) + star2.velocity = units.AUd(numpy.array((0.0, 0.0, 0.0))) star2.radius = units.RSun(100.0) instance.particles.add_particles(stars) - for x in range(1,2000,10): + for x in range(1, 2000, 10): instance.evolve_model(x | units.day) instance.particles.copy_values_of_all_attributes_to(stars) stars.savepoint() - instance.cleanup_code() instance.stop() @@ -256,19 +248,17 @@ def test4(self): self.assertEqual(len(instance.particles), 0) particles.mass = [15.0, 30.0] | units.kg - particles.radius = [10.0, 20.0] | units.m + particles.radius = [10.0, 20.0] | units.m particles.position = [[10.0, 20.0, 30.0], [20.0, 40.0, 60.0]] | units.m particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.m / units.s - instance.particles.add_particles(particles) self.assertEqual(len(instance.particles), 2) - instance.particles.mass = [17.0, 33.0] | units.kg - + instance.particles.mass = [17.0, 33.0] | units.kg - self.assertEqual(instance.get_mass(0), 17.0| units.kg) - self.assertEqual(instance.get_mass(1), 33.0| units.kg) + self.assertEqual(instance.get_mass(0), 17.0 | units.kg) + self.assertEqual(instance.get_mass(1), 33.0 | units.kg) instance.stop() @@ -282,27 +272,26 @@ def test5(self): self.assertEqual(len(instance.particles), 0) particles.mass = [15.0, 30.0] | units.kg - particles.radius = [10.0, 20.0] | units.m + particles.radius = [10.0, 20.0] | units.m particles.position = [[10.0, 20.0, 30.0], [20.0, 40.0, 60.0]] | units.m particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.m / units.s - instance.particles.add_particles(particles) self.assertEqual(len(instance.particles), 2) - instance.set_state(1, 16|units.kg, - 20.0|units.m, 40.0|units.m, 60.0|units.m, - 1.0|units.ms, 1.0|units.ms, 1.0|units.ms , - 20.0|units.m) - - curr_state = instance.get_state(1) - for expected, actual in zip([16|units.kg, - 20.0|units.m, 40.0|units.m, 60.0|units.m, - 1.0|units.ms, 1.0|units.ms, 1.0|units.ms , - 20.0|units.m], curr_state): + instance.set_state(1, 16 | units.kg, + 20.0 | units.m, 40.0 | units.m, 60.0 | units.m, + 1.0 | units.ms, 1.0 | units.ms, 1.0 | units.ms, + 20.0 | units.m) + + curr_state = instance.get_state(1) + for expected, actual in zip([16 | units.kg, + 20.0 | units.m, 40.0 | units.m, 60.0 | units.m, + 1.0 | units.ms, 1.0 | units.ms, 1.0 | units.ms, + 20.0 | units.m], curr_state): self.assertAlmostRelativeEquals(expected, actual) instance.stop() - self.assertEqual(curr_state[0], 16|units.kg, 8) + self.assertEqual(curr_state[0], 16 | units.kg, 8) def test6(self): print("Test6: Testing Hermite parameters") @@ -310,15 +299,15 @@ def test6(self): instance = Hermite(convert_nbody) value = instance.get_eps2() - self.assertEqual(0.0 | units.AU**2 , value) + self.assertEqual(0.0 | units.AU**2, value) self.assertAlmostEqual(0.0 | units.AU**2, instance.parameters.epsilon_squared, in_units=units.AU**2) for x in [0.01, 0.1, 0.2]: instance.parameters.epsilon_squared = x | units.AU**2 self.assertAlmostEqual(x | units.AU**2, instance.parameters.epsilon_squared, in_units=units.AU**2) value = instance.get_dt_param() - self.assertEqual(0.03 , value) - self.assertAlmostEqual(0.03 , instance.parameters.dt_param) + self.assertEqual(0.03, value) + self.assertAlmostEqual(0.03, instance.parameters.dt_param) for x in [0.001, 0.01, 0.1]: instance.parameters.dt_param = x self.assertAlmostEqual(x, instance.parameters.dt_param) @@ -331,7 +320,7 @@ def test6(self): self.assertAlmostEqual(x | units.yr, instance.parameters.dt_dia, in_units=units.yr) value = instance.get_begin_time() - self.assertEqual(0.0| units.yr, value) + self.assertEqual(0.0 | units.yr, value) self.assertAlmostEqual(0.0 | units.yr, instance.parameters.begin_time, in_units=units.yr) for x in [1.0, 10.0, 100.0]: instance.parameters.begin_time = x | units.yr @@ -357,14 +346,14 @@ def test7(self): initial_direction = math.atan((earth.velocity[0]/earth.velocity[1])) final_direction = [] - for log_eps2 in range(-9,10,2): + for log_eps2 in range(-9, 10, 2): instance = Hermite(convert_nbody) instance.parameters.end_time_accuracy_factor = 0.0 instance.parameters.epsilon_squared = 10.0**log_eps2 | units.AU ** 2 instance.particles.add_particles(particles) instance.commit_particles() instance.evolve_model(0.25 | units.yr) - final_direction.append(math.atan((instance.particles[1].velocity[0]/ + final_direction.append(math.atan((instance.particles[1].velocity[0] / instance.particles[1].velocity[1]))) instance.stop() # Small values of epsilon_squared should result in normal earth-sun dynamics: rotation of 90 degrees @@ -373,7 +362,7 @@ def test7(self): self.assertAlmostEqual(final_direction[-1], initial_direction, 2) # Outcome is most sensitive to epsilon_squared when epsilon_squared = d(earth, sun)^2 delta = [abs(final_direction[i+1]-final_direction[i]) for i in range(len(final_direction)-1)] - self.assertEqual(delta[len(final_direction)//2 -1], max(delta)) + self.assertEqual(delta[len(final_direction)//2 - 1], max(delta)) def test8(self): print("Testing Hermite collision_detection") @@ -398,7 +387,7 @@ def test8(self): self.assertEqual(len(collisions.particles(0)), 3) self.assertEqual(len(collisions.particles(1)), 3) self.assertEqual(len(particles - collisions.particles(0) - collisions.particles(1)), 1) - self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) <= + self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) <= (collisions.particles(0).radius + collisions.particles(1).radius), [True, True, True]) @@ -423,12 +412,11 @@ def test8(self): self.assertEqual(len(collisions.particles(0)), 1) self.assertEqual(len(collisions.particles(1)), 1) self.assertEqual(len(instance.particles - collisions.particles(0) - collisions.particles(1)), 2) - self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) <= + self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) <= (collisions.particles(0).radius + collisions.particles(1).radius), [True]) instance.stop() - def test10(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) @@ -436,7 +424,7 @@ def test10(self): instance.initialize_code() instance.parameters.epsilon_squared = 0.0 | units.AU**2 instance.parameters.stopping_conditions_number_of_steps = 10 - self.assertEqual(instance.parameters.stopping_conditions_number_of_steps,10) + self.assertEqual(instance.parameters.stopping_conditions_number_of_steps, 10) stars = self.new_system_of_sun_and_earth() earth = stars[1] @@ -453,20 +441,20 @@ def test10(self): def test11(self): particles = datamodel.Particles(2) - particles.x = [0.0,10.0] | nbody_system.length + particles.x = [0.0, 10.0] | nbody_system.length particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.radius = 0.005 | nbody_system.length - particles.vx = 0 | nbody_system.speed - particles.vy = 0 | nbody_system.speed - particles.vz = 0 | nbody_system.speed + particles.vx = 0 | nbody_system.speed + particles.vy = 0 | nbody_system.speed + particles.vz = 0 | nbody_system.speed particles.mass = 1.0 | nbody_system.mass instance = Hermite() instance.initialize_code() instance.parameters.stopping_conditions_number_of_steps = 2 self.assertEqual(instance.parameters.stopping_conditions_number_of_steps, 2) - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.stopping_conditions.number_of_steps_detection.enable() instance.evolve_model(10 | nbody_system.time) self.assertTrue(instance.stopping_conditions.number_of_steps_detection.is_set()) @@ -476,30 +464,30 @@ def test11(self): def test12(self): particles = datamodel.Particles(2) - particles.x = [0.0,1.00] | nbody_system.length - particles.y = [0.0,0.0] | nbody_system.length - particles.z = [0.0,0.0] | nbody_system.length + particles.x = [0.0, 1.00] | nbody_system.length + particles.y = [0.0, 0.0] | nbody_system.length + particles.z = [0.0, 0.0] | nbody_system.length particles.radius = 0.005 | nbody_system.length - particles.vx = [5.1,0.0] | nbody_system.speed - particles.vy = [0.0,0.0] | nbody_system.speed - particles.vz = [0.0,0.0]| nbody_system.speed - particles.mass = [0.1,0.1] | nbody_system.mass + particles.vx = [5.1, 0.0] | nbody_system.speed + particles.vy = [0.0, 0.0] | nbody_system.speed + particles.vz = [0.0, 0.0] | nbody_system.speed + particles.mass = [0.1, 0.1] | nbody_system.mass instance = Hermite() instance.initialize_code() instance.parameters.stopping_conditions_out_of_box_size = .5 | nbody_system.length self.assertEqual(instance.parameters.stopping_conditions_out_of_box_size, .5 | nbody_system.length) - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.stopping_conditions.out_of_box_detection.enable() instance.evolve_model(0.1 | nbody_system.time) self.assertTrue(instance.stopping_conditions.out_of_box_detection.is_set()) - self.assertAlmostEqual(instance.stopping_conditions.out_of_box_detection.particles(0).x, 1.0 |nbody_system.length, 3) + self.assertAlmostEqual(instance.stopping_conditions.out_of_box_detection.particles(0).x, 1.0 | nbody_system.length, 3) instance.stop() def test13(self): particles = plummer.new_plummer_model(31) - instance = Hermite(number_of_workers=1)#, debugger="xterm") + instance = Hermite(number_of_workers=1) # , debugger="xterm") instance.initialize_code() instance.parameters.epsilon_squared = 0.01 | nbody_system.length ** 2 instance.particles.add_particles(particles) @@ -509,7 +497,7 @@ def test13(self): expected_positions = instance.particles.position instance.stop() positions_per_workers = [] - for n in [2,3,4,5]: + for n in [2, 3, 4, 5]: instance = Hermite(number_of_workers=n) instance.initialize_code() instance.parameters.epsilon_squared = 0.01 | nbody_system.length ** 2 @@ -520,8 +508,7 @@ def test13(self): positions_per_workers.append(instance.particles.position) instance.stop() - - for index, n in enumerate([2,3,4,5]): + for index, n in enumerate([2, 3, 4, 5]): self.assertAlmostEqual(expected_positions, positions_per_workers[index], 15) def test14(self): @@ -531,8 +518,8 @@ def test14(self): particles = datamodel.Particles(2) particles.mass = [1.0, 1.0] | nbody_system.mass - particles.radius = [0.0001, 0.0001] | nbody_system.length - particles.position = [[0.0,0.0,0.0], [2.0,0.0,0.0]] | nbody_system.length + particles.radius = [0.0001, 0.0001] | nbody_system.length + particles.position = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]] | nbody_system.length particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed instance.particles.add_particles(particles) @@ -563,36 +550,35 @@ def test14(self): def test15(self): particles = datamodel.Particles(2) - particles.x = [0.0,10.0] | nbody_system.length + particles.x = [0.0, 10.0] | nbody_system.length particles.y = 0.0 | nbody_system.length particles.z = 0.0 | nbody_system.length - particles.vx = 0.0 | nbody_system.speed - particles.vy = 0.0 | nbody_system.speed - particles.vz = 0.0 | nbody_system.speed + particles.vx = 0.0 | nbody_system.speed + particles.vy = 0.0 | nbody_system.speed + particles.vz = 0.0 | nbody_system.speed particles.mass = 1.0 | nbody_system.mass instance = Hermite() - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.commit_particles() self.assertEqual(instance.particles[0].radius, 0.0 | nbody_system.length) p = datamodel.Particle( - x=1.0 | nbody_system.length, + x=1.0 | nbody_system.length, y=2.0 | nbody_system.length, z=3.0 | nbody_system.length, - vx=1.0 | nbody_system.speed, + vx=1.0 | nbody_system.speed, vy=2.0 | nbody_system.speed, vz=3.0 | nbody_system.speed, mass=1.0 | nbody_system.mass, radius=4.0 | nbody_system.length, ) - instance.particles.add_particle(p) + instance.particles.add_particle(p) self.assertEqual(instance.particles[0].radius, 0.0 | nbody_system.length) self.assertEqual(instance.particles[1].radius, 0.0 | nbody_system.length) self.assertEqual(instance.particles[2].radius, 4.0 | nbody_system.length) instance.stop() - def test16(self): particles = new_plummer_model(200) particles.scale_to_standard() @@ -601,9 +587,9 @@ def test16(self): instance.parameters.epsilon_squared = 0.00000 | nbody_system.length**2 instance.particles.add_particles(particles) - x = numpy.arange(-1,1,0.1) | nbody_system.length + x = numpy.arange(-1, 1, 0.1) | nbody_system.length zero = numpy.zeros(len(x)) | nbody_system.length - potential0 = instance.get_potential_at_point(zero, x , zero, zero) + potential0 = instance.get_potential_at_point(zero, x, zero, zero) instance.stop() for n in (2, 3, 4): @@ -611,13 +597,11 @@ def test16(self): instance.initialize_code() instance.parameters.epsilon_squared = 0.00000 | nbody_system.length**2 instance.particles.add_particles(particles) - potential = instance.get_potential_at_point(zero, x , zero, zero) + potential = instance.get_potential_at_point(zero, x, zero, zero) self.assertAlmostRelativeEquals(potential0, potential, 8) instance.stop() - - def test17(self): particles = new_plummer_model(50) particles.scale_to_standard() @@ -628,63 +612,61 @@ def test17(self): instance.reset() - self.assertAlmostRelativeEquals(instance.parameters.epsilon_squared , 0.22000 | nbody_system.length**2) + self.assertAlmostRelativeEquals(instance.parameters.epsilon_squared, 0.22000 | nbody_system.length**2) self.assertEqual(len(instance.particles), 0) instance.particles.add_particles(particles) self.assertEqual(len(instance.particles), 50) instance.stop() - def test18(self): particles = datamodel.Particles(2) - particles.x = [0.0,1.0] | nbody_system.length + particles.x = [0.0, 1.0] | nbody_system.length particles.y = 0.0 | nbody_system.length particles.z = 0.0 | nbody_system.length - particles.vx = 0.0 | nbody_system.speed - particles.vy = 0.0 | nbody_system.speed - particles.vz = 0.0 | nbody_system.speed + particles.vx = 0.0 | nbody_system.speed + particles.vy = 0.0 | nbody_system.speed + particles.vz = 0.0 | nbody_system.speed particles.mass = 1.0 | nbody_system.mass instance = Hermite() - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.commit_particles() self.assertEqual(instance.particles[0].radius, 0.0 | nbody_system.length) instance.parameters.end_time_accuracy_factor = 1.0 instance.evolve_model(0.1 | nbody_system.time) - self.assertAlmostRelativeEquals(instance.model_time, 0.10563767746 |nbody_system.time, 5) + self.assertAlmostRelativeEquals(instance.model_time, 0.10563767746 | nbody_system.time, 5) instance.parameters.end_time_accuracy_factor = -1.0 instance.evolve_model(0.3 | nbody_system.time) - self.assertAlmostRelativeEquals(instance.model_time, 0.266758127609 |nbody_system.time, 5) + self.assertAlmostRelativeEquals(instance.model_time, 0.266758127609 | nbody_system.time, 5) instance.parameters.end_time_accuracy_factor = 0.0 instance.evolve_model(0.4 | nbody_system.time) - self.assertAlmostRelativeEquals(instance.model_time, 0.4 |nbody_system.time, 6) + self.assertAlmostRelativeEquals(instance.model_time, 0.4 | nbody_system.time, 6) instance.parameters.end_time_accuracy_factor = -0.5 instance.evolve_model(0.5 | nbody_system.time) - self.assertAlmostRelativeEquals(instance.model_time, 0.48974930698 |nbody_system.time, 6) + self.assertAlmostRelativeEquals(instance.model_time, 0.48974930698 | nbody_system.time, 6) instance.parameters.end_time_accuracy_factor = +0.5 instance.evolve_model(0.6 | nbody_system.time) - self.assertAlmostRelativeEquals(instance.model_time, 0.6042733579 |nbody_system.time, 6) + self.assertAlmostRelativeEquals(instance.model_time, 0.6042733579 | nbody_system.time, 6) instance.stop() - def test19(self): particles = datamodel.Particles(2) - particles.x = [0.0,200.0] | nbody_system.length + particles.x = [0.0, 200.0] | nbody_system.length particles.y = 0.0 | nbody_system.length particles.z = 0.0 | nbody_system.length - particles.vx = 0.0 | nbody_system.speed - particles.vy = 0.0 | nbody_system.speed - particles.vz = 0.0 | nbody_system.speed + particles.vx = 0.0 | nbody_system.speed + particles.vy = 0.0 | nbody_system.speed + particles.vz = 0.0 | nbody_system.speed particles.mass = 1.0 | nbody_system.mass instance = Hermite() - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.commit_particles() self.assertEqual(instance.particles[0].radius, 0.0 | nbody_system.length) instance.parameters.end_time_accuracy_factor = 0.0 instance.evolve_model(0.1 | nbody_system.time) - self.assertAlmostRelativeEquals(instance.model_time, 0.1 |nbody_system.time, 5) + self.assertAlmostRelativeEquals(instance.model_time, 0.1 | nbody_system.time, 5) instance.stop() @@ -730,19 +712,18 @@ def test21(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) hermite = Hermite(convert_nbody) - encoded_interface = pickle.dumps(hermite,0) + encoded_interface = pickle.dumps(hermite, 0) decoded_interface = pickle.loads(encoded_interface) - def test22(self): hermite = Hermite() hermite.parameters.epsilon_squared = 0.0 | nbody_system.length**2 particles = datamodel.Particles(2) - particles.position = ([0,0,0], [1,0,0] )| nbody_system.length - particles.velocity = ([-2,0,0], [2,0,0] )| nbody_system.speed - particles.radius = 0| nbody_system.length - particles.mass = 0.1| nbody_system.mass + particles.position = ([0, 0, 0], [1, 0, 0]) | nbody_system.length + particles.velocity = ([-2, 0, 0], [2, 0, 0]) | nbody_system.speed + particles.radius = 0 | nbody_system.length + particles.mass = 0.1 | nbody_system.mass hermite.particles.add_particles(particles) hermite.stopping_conditions.out_of_box_detection.enable() @@ -757,16 +738,15 @@ def test22(self): self.assertEqual(hermite.stopping_conditions.out_of_box_detection.particles(0)[0].key, particles[1].key) hermite.stop() - def test23(self): hermite = Hermite() hermite.parameters.epsilon_squared = 0.0 | nbody_system.length**2 particles = datamodel.Particles(1) - particles.position = ([0,0,0] )| nbody_system.length - particles.velocity = ([1,0,0] )| nbody_system.speed - particles.radius = 0| nbody_system.length - particles.mass = 0.1| nbody_system.mass + particles.position = ([0, 0, 0]) | nbody_system.length + particles.velocity = ([1, 0, 0]) | nbody_system.speed + particles.radius = 0 | nbody_system.length + particles.mass = 0.1 | nbody_system.mass hermite.particles.add_particles(particles) hermite.evolve_model(1 | nbody_system.time) @@ -779,7 +759,6 @@ def test23(self): self.assertAlmostRelativeEquals(hermite.particles[0].x, 1.5 | nbody_system.length) hermite.stop() - def test24(self): hermite = Hermite(reuse_worker=True) channel1 = hermite.legacy_interface.channel @@ -794,12 +773,12 @@ def test25(self): hermite.parameters.epsilon_squared = 0.0 | nbody_system.length**2 particles = datamodel.Particles(10) - particles.position = ([0,0,0] )| nbody_system.length - particles.velocity = ([1,0,0] )| nbody_system.speed - particles.radius = 0| nbody_system.length - particles.mass = 0.1| nbody_system.mass - particles.x = numpy.linspace(1, 10, 10) | nbody_system.length - particles.vx = numpy.linspace(1, 5, 10) | nbody_system.speed + particles.position = ([0, 0, 0]) | nbody_system.length + particles.velocity = ([1, 0, 0]) | nbody_system.speed + particles.radius = 0 | nbody_system.length + particles.mass = 0.1 | nbody_system.mass + particles.x = numpy.linspace(1, 10, 10) | nbody_system.length + particles.vx = numpy.linspace(1, 5, 10) | nbody_system.speed hermite.particles.add_particles(particles) @@ -816,37 +795,23 @@ def test25(self): channel = hermite.particles.new_channel_to(p) p.x = 0 | nbody_system.length p.vx = 0 | nbody_system.speed - request = channel.copy_attributes_async(("x","vx",), async_get=True) + request = channel.copy_attributes_async(("x", "vx",), async_get=True) request.wait() self.assertEqual(p.x, particles.x) self.assertEqual(p.vx, particles.vx) p.x = 0 | nbody_system.length p.vx = 0 | nbody_system.speed channel = p.new_channel_to(hermite.particles) - request = channel.copy_attributes_async(("x", "y", "z","vx","vy","vz"), async_get=False, async_set=True) + request = channel.copy_attributes_async(("x", "y", "z", "vx", "vy", "vz"), async_get=False, async_set=True) request.wait() self.assertEqual(p.x, hermite.particles.x) self.assertEqual(p.vx, hermite.particles.vx) channel = p.new_channel_to(particles) - request = channel.copy_attributes_async(("x", "y", "z","vx","vy","vz"), async_get=False, async_set=True) + request = channel.copy_attributes_async(("x", "y", "z", "vx", "vy", "vz"), async_get=False, async_set=True) request.wait() self.assertEqual(p.x, particles.x) self.assertEqual(p.vx, particles.vx) - request = channel.copy_attributes_async(("x", "y", "z","vx","vy","vz"), async_get=True, async_set=False) + request = channel.copy_attributes_async(("x", "y", "z", "vx", "vy", "vz"), async_get=True, async_set=False) request.wait() self.assertEqual(p.x, particles.x) self.assertEqual(p.vx, particles.vx) - - - - - - - - - - - - - - diff --git a/src/amuse/test/suite/codes_tests/test_higpus.py b/src/amuse/test/suite/codes_tests/test_higpus.py index bbc0cf0ef8..75a5491c77 100644 --- a/src/amuse/test/suite/codes_tests/test_higpus.py +++ b/src/amuse/test/suite/codes_tests/test_higpus.py @@ -8,15 +8,14 @@ from amuse.ic.plummer import new_plummer_model - class HiGPUsInterfaceTests(TestWithMPI): - + def test0(self): instance = self.new_instance_of_an_optional_code(HiGPUsInterface) instance.initialize_code() instance.cleanup_code() instance.stop() - + def test1(self): instance = self.new_instance_of_an_optional_code(HiGPUsInterface) instance.initialize_code() @@ -38,13 +37,13 @@ def test1(self): self.assertEqual(instance.get_number_of_particles()['number_of_particles'], 2) instance.cleanup_code() instance.stop() - + def test2(self): instance = self.new_instance_of_an_optional_code(HiGPUsInterface) instance.initialize_code() for x in [0.101, 4.0]: error = instance.set_eta4(x) - self.assertEqual(error, 0) + self.assertEqual(error, 0) value, error = instance.get_eta4() self.assertEqual(error, 0) self.assertEqual(x, value) @@ -57,34 +56,34 @@ def test3(self): instance.set_number_of_Threads(32) instance.set_number_of_GPU(1) error = instance.commit_parameters() - - instance.new_particle([11.0,12.0,13.0,14.0], - [2.0,3.0,4.0,5.0], - [2.1,3.1,4.1,5.1], - [2.2,3.2,4.2,5.2], - [2.3,3.3,4.3,5.3], - [2.4,3.4,4.4,5.4], - [2.5,3.5,4.5,5.5], - [2.6,3.6,4.6,5.6]) + + instance.new_particle([11.0, 12.0, 13.0, 14.0], + [2.0, 3.0, 4.0, 5.0], + [2.1, 3.1, 4.1, 5.1], + [2.2, 3.2, 4.2, 5.2], + [2.3, 3.3, 4.3, 5.3], + [2.4, 3.4, 4.4, 5.4], + [2.5, 3.5, 4.5, 5.5], + [2.6, 3.6, 4.6, 5.6]) error = instance.commit_particles() retrieved_state = instance.get_state(0) self.assertEqual(11.0, retrieved_state['mass']) - retrieved_state = instance.get_state([2,3,4]) + retrieved_state = instance.get_state([2, 3, 4]) self.assertEqual(14.0, retrieved_state['mass'][1]) self.assertEqual(instance.get_number_of_particles()['number_of_particles'], 4) instance.cleanup_code() instance.stop() - + def test4(self): instance = self.new_instance_of_an_optional_code(HiGPUsInterface) instance.initialize_code() instance.set_number_of_Threads(128) instance.set_number_of_GPU(1) error = instance.commit_parameters() - + n = 4000 - ids = [i for i in range(1,n)] - values = [1.0 * i for i in range(1,n)] + ids = [i for i in range(1, n)] + values = [1.0 * i for i in range(1, n)] instance.new_particle(values, values, values, values, values, values, values) error = instance.commit_particles() retrieved_state = instance.get_state(0) @@ -93,7 +92,7 @@ def test4(self): self.assertEqual(3999.0, retrieved_state['mass']) instance.cleanup_code() instance.stop() - + def test5(self): instance = self.new_instance_of_an_optional_code(HiGPUsInterface) instance.initialize_code() @@ -102,34 +101,34 @@ def test5(self): instance.set_gpu_name("GeForce GTX 480") instance.set_eps(0.0) error = instance.commit_parameters() - - instance.new_particle( - [1.0,1.0,1.0], - [0.0,0.0,0.0], - [1.0,0.0,-1.0], - [0.0,0.0,0.0], - [0.0,0.0,0.0], - [0.0,1.0,0.0], - [0.0,0.0,0.0], - [0.0,0.0,0.0]) - + + instance.new_particle( + [1.0, 1.0, 1.0], + [0.0, 0.0, 0.0], + [1.0, 0.0, -1.0], + [0.0, 0.0, 0.0], + [0.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, 0.0], + [0.0, 0.0, 0.0]) + instance.commit_particles() - Ep=instance.get_potential_energy()['potential_energy'] - Ek=instance.get_kinetic_energy()['kinetic_energy'] - self.assertEqual( Ek, 0.5) - self.assertEqual( Ep, -2.5) + Ep = instance.get_potential_energy()['potential_energy'] + Ek = instance.get_kinetic_energy()['kinetic_energy'] + self.assertEqual(Ek, 0.5) + self.assertEqual(Ep, -2.5) instance.delete_particle(1) instance.recommit_particles() - n=instance.get_number_of_particles()['number_of_particles'] - Ep=instance.get_potential_energy()['potential_energy'] - Ek=instance.get_kinetic_energy()['kinetic_energy'] - - self.assertEqual( n, 2) - self.assertEqual( Ek, 0.) - self.assertEqual( Ep, -0.5) + n = instance.get_number_of_particles()['number_of_particles'] + Ep = instance.get_potential_energy()['potential_energy'] + Ek = instance.get_kinetic_energy()['kinetic_energy'] + + self.assertEqual(n, 2) + self.assertEqual(Ek, 0.) + self.assertEqual(Ep, -0.5) instance.cleanup_code() instance.stop() - + def test6(self): instance = self.new_instance_of_an_optional_code(HiGPUsInterface) instance.initialize_code() @@ -138,22 +137,21 @@ def test6(self): instance.set_gpu_name("GeForce GTX 480") instance.set_eps(0.0) error = instance.commit_parameters() - - id1,errorcode = instance.new_particle(mass = 10.0, radius = 1.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) - id2,errorcode = instance.new_particle(mass = 10.0, radius = 1.0, x = 2.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) - + + id1, errorcode = instance.new_particle(mass=10.0, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) + id2, errorcode = instance.new_particle(mass=10.0, radius=1.0, x=2.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) + instance.commit_particles() potential, errorcode = instance.get_potential(id1) self.assertEqual(errorcode, 0) self.assertAlmostRelativeEquals(potential, -10.0 / (2.0**2 + 0.1**2)**0.5, 2) total_potential, errorcode = instance.get_potential_energy() potentials, errorcode = instance.get_potential([id1, id2]) - + self.assertAlmostRelativeEquals(total_potential, numpy.sum(potentials * 10.0) / 2.0) instance.cleanup_code() instance.stop() - - + def test7(self): instance = self.new_instance_of_an_optional_code(HiGPUsInterface) instance.initialize_code() @@ -162,26 +160,25 @@ def test7(self): instance.set_gpu_name("GeForce GTX 480") instance.set_eps(0.0) error = instance.commit_parameters() - - id1,errorcode = instance.new_particle(mass = 10.0, radius = 1.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) - id2,errorcode = instance.new_particle(mass = 1.0, radius = 1.0, x = 2.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) - + + id1, errorcode = instance.new_particle(mass=10.0, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) + id2, errorcode = instance.new_particle(mass=1.0, radius=1.0, x=2.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) + instance.commit_particles() potential, errorcode = instance.get_potential(id1) self.assertEqual(errorcode, 0) self.assertAlmostRelativeEquals(potential, -1.0 / numpy.sqrt(2.0**2), 8) - + potential, errorcode = instance.get_potential(id2) self.assertEqual(errorcode, 0) self.assertAlmostRelativeEquals(potential, -10.0 / numpy.sqrt(2.0**2), 8) - + total_potential, errorcode = instance.get_potential_energy() potentials, errorcode = instance.get_potential([id1, id2]) - + self.assertAlmostRelativeEquals(total_potential, numpy.sum(potentials * [10.0, 1.0]) / 2.0) instance.cleanup_code() instance.stop() - class TestHiGPUs(TestWithMPI): @@ -189,19 +186,17 @@ def new_system_of_sun_and_earth(self): stars = datamodel.Stars(2) sun = stars[0] sun.mass = units.MSun(1.0) - sun.position = units.m(numpy.array((0.0,0.0,0.0))) - sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) + sun.position = units.m(numpy.array((0.0, 0.0, 0.0))) + sun.velocity = units.ms(numpy.array((0.0, 0.0, 0.0))) sun.radius = units.RSun(1.0) - earth = stars[1] earth.mass = units.kg(5.9736e24) - earth.radius = units.km(6371.) - earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) - earth.velocity = units.ms(numpy.array((0.0,29800.,0.0))) - - return stars + earth.radius = units.km(6371.) + earth.position = units.km(numpy.array((149.5e6, 0.0, 0.0))) + earth.velocity = units.ms(numpy.array((0.0, 29800., 0.0))) + return stars def test1(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) @@ -209,28 +204,28 @@ def test1(self): stars = self.new_system_of_sun_and_earth() earth = stars[1] - + instance.particles.add_particles(stars) instance.evolve_model(365 | units.day) - + instance.particles.copy_values_of_all_attributes_to(stars) - + position_at_start = earth.position.value_in(units.AU)[0] position_after_full_rotation = earth.position.value_in(units.AU)[0] self.assertAlmostEqual(position_at_start, position_after_full_rotation, 6) - + instance.evolve_model(365.0 + (365.0 / 2) | units.day) - + instance.particles.copy_values_of_all_attributes_to(stars) position_after_half_a_rotation = earth.position.value_in(units.AU)[0] self.assertAlmostEqual(-position_at_start, position_after_half_a_rotation, 2) - - instance.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) - + + instance.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) + instance.particles.copy_values_of_all_attributes_to(stars) position_after_half_a_rotation = earth.position.value_in(units.AU)[1] self.assertAlmostEqual(-position_at_start, position_after_half_a_rotation, 2) - + instance.stop() def test2(self): @@ -240,66 +235,63 @@ def test2(self): instance.initialize_code() instance.commit_parameters() - + particles = datamodel.Particles(2) self.assertEqual(len(instance.particles), 0) - + particles.mass = [15.0, 30.0] | units.kg - particles.radius = [10.0, 20.0] | units.m + particles.radius = [10.0, 20.0] | units.m particles.position = [[10.0, 20.0, 30.0], [20.0, 40.0, 60.0]] | units.m particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.m / units.s - instance.particles.add_particles(particles) self.assertEqual(len(instance.particles), 2) - - instance.particles.mass = [17.0, 33.0] | units.kg - - self.assertEqual(instance.get_mass(0), 17.0| units.kg) - self.assertEqual(instance.get_mass(1), 33.0| units.kg) - + + instance.particles.mass = [17.0, 33.0] | units.kg + + self.assertEqual(instance.get_mass(0), 17.0 | units.kg) + self.assertEqual(instance.get_mass(1), 33.0 | units.kg) + instance.cleanup_code() instance.stop() - + def test3(self): instance = self.new_instance_of_an_optional_code(HiGPUs) instance.initialize_code() instance.parameters.eps = 0.0 | nbody_system.length - instance.commit_parameters() + instance.commit_parameters() particles = datamodel.Particles(4) - particles.mass = nbody_system.mass.new_quantity(range(1,5)) - particles.radius = 0.00001 | nbody_system.length - particles.position = [[-1.0,0.0,0.0],[1.0,0.0,0.0],[0.0,-1.0,0.0],[0.0,1.0,0.0]] | nbody_system.length - particles.velocity = [[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0]] | nbody_system.speed - + particles.mass = nbody_system.mass.new_quantity(range(1, 5)) + particles.radius = 0.00001 | nbody_system.length + particles.position = [[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 1.0, 0.0]] | nbody_system.length + particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed + instance.particles.add_particles(particles) - + instance.commit_particles() copyof = instance.particles.copy() - + instance.cleanup_code() instance.stop() - - self.assertEqual(2 | nbody_system.mass, copyof[1].mass) - - + + self.assertEqual(2 | nbody_system.mass, copyof[1].mass) + def test4(self): self.skip("Need to implement get_gravity_at_point for HiGPUs") instance = self.new_instance_of_an_optional_code(HiGPUs) instance.initialize_code() instance.parameters.eps = 0.0 - instance.commit_parameters() + instance.commit_parameters() particles = datamodel.Particles(2) particles.mass = [1.0, 1.0] | nbody_system.mass - particles.radius = [0.0001, 0.0001] | nbody_system.length - particles.position = [[0.0,0.0,0.0], [2.0,0.0,0.0]] | nbody_system.length + particles.radius = [0.0001, 0.0001] | nbody_system.length + particles.position = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]] | nbody_system.length particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed instance.particles.add_particles(particles) - + instance.commit_particles() - zero = 0.0 | nbody_system.length fx, fy, fz = instance.get_gravity_at_point(0.0000001 | nbody_system.length, 2.0 | nbody_system.length, zero, zero) self.assertAlmostEqual(fx, -0.25 | nbody_system.acceleration) @@ -312,12 +304,12 @@ def test4(self): potential1 = instance.get_potential_at_point(0.0000001 | nbody_system.length, x1, zero, zero) fx0, fy0, fz0 = instance.get_gravity_at_point(0.0000001 | nbody_system.length, x0, zero, zero) fx1, fy1, fz1 = instance.get_gravity_at_point(0.0000001 | nbody_system.length, x1, zero, zero) - + self.assertAlmostEqual(fy0, 0.0 | nbody_system.acceleration) self.assertAlmostEqual(fz0, 0.0 | nbody_system.acceleration) self.assertAlmostEqual(fy1, 0.0 | nbody_system.acceleration) self.assertAlmostEqual(fz1, 0.0 | nbody_system.acceleration) - + self.assertAlmostEqual(fx0, -1.0 * fx1, 5) fx = (-1.0 / (x0**2) + 1.0 / (x1**2)) * (1.0 | nbody_system.length ** 3 / nbody_system.time ** 2) self.assertAlmostEqual(fx, fx0, 2) @@ -325,50 +317,49 @@ def test4(self): instance.cleanup_code() instance.stop() - + def test5(self): instance = self.new_instance_of_an_optional_code(HiGPUs) instance.initialize_code() - + instance.parameters.eta6 = 0.01 instance.commit_parameters() stars = new_plummer_model(64) - + instance.particles.add_particles(stars) instance.commit_particles() - + instance.evolve_model(0.001 | nbody_system.time) - + e0 = instance.get_kinetic_energy() + instance.get_potential_energy() - + stars.mass *= 0.9 - + instance.synchronize_model() - + e1 = instance.get_kinetic_energy() + instance.get_potential_energy() - + instance.cleanup_code() instance.stop() - + delta_e = e1 - e0 - + self.assertTrue(e1 != e0) - - + def test6(self): particles = datamodel.Particles(2) particles.mass = [1.0, 0.000003003] | nbody_system.mass - particles.radius = [0.0001, 0.0001] | nbody_system.length + particles.radius = [0.0001, 0.0001] | nbody_system.length particles.position = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]] | nbody_system.length particles.velocity = [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0]] | nbody_system.speed particle = datamodel.Particles(1) particle.mass = 0.000003003 | nbody_system.mass - particle.radius = 0.0001 | nbody_system.length + particle.radius = 0.0001 | nbody_system.length particle.position = [0.0, 1.0, 0.0] | nbody_system.length particle.velocity = [-1.0, 0.0, 0.0] | nbody_system.speed - + instance = self.new_instance_of_an_optional_code(HiGPUs) self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') instance.initialize_code() @@ -393,69 +384,63 @@ def test6(self): self.assertEqual(instance.get_name_of_current_state(), 'END') instance.stop() - def test7(self): - + instance = self.new_instance_of_an_optional_code(HiGPUs) instance.parameters.eta6 = 0.5 - - instance.commit_parameters() - - self.assertEqual( instance.parameters.eta6 , 0.5 ) - self.assertEqual( instance.parameters.eta4 , 0.01) - self.assertEqual( instance.parameters.begin_time , 0.0 | nbody_system.time) - self.assertEqual( instance.parameters.r_core_plummer , 0.0 | nbody_system.length) - self.assertEqual( instance.parameters.mass_plummer , 0.0 | nbody_system.mass) - self.assertEqual( instance.parameters.Threads , 128) - self.assertEqual( instance.parameters.n_Print , 1000000) - self.assertEqual( instance.parameters.dt_Print , 1000000.0 | nbody_system.time) - self.assertEqual( instance.parameters.max_step , pow(2.,-3.0) | nbody_system.time) - self.assertEqual( instance.parameters.min_step , pow(2.,-30.0) | nbody_system.time) - self.assertEqual( instance.parameters.gpu_name , "") - self.assertEqual( instance.parameters.n_gpu , 1) + + instance.commit_parameters() + + self.assertEqual(instance.parameters.eta6, 0.5) + self.assertEqual(instance.parameters.eta4, 0.01) + self.assertEqual(instance.parameters.begin_time, 0.0 | nbody_system.time) + self.assertEqual(instance.parameters.r_core_plummer, 0.0 | nbody_system.length) + self.assertEqual(instance.parameters.mass_plummer, 0.0 | nbody_system.mass) + self.assertEqual(instance.parameters.Threads, 128) + self.assertEqual(instance.parameters.n_Print, 1000000) + self.assertEqual(instance.parameters.dt_Print, 1000000.0 | nbody_system.time) + self.assertEqual(instance.parameters.max_step, pow(2., -3.0) | nbody_system.time) + self.assertEqual(instance.parameters.min_step, pow(2., -30.0) | nbody_system.time) + self.assertEqual(instance.parameters.gpu_name, "") + self.assertEqual(instance.parameters.n_gpu, 1) instance.cleanup_code() instance.stop() def test8(self): - + instance = self.new_instance_of_an_optional_code(HiGPUs) - - particles=new_plummer_model(128) - + + particles = new_plummer_model(128) + instance.particles.add_particles(particles) - - E0=instance.kinetic_energy+instance.potential_energy - + + E0 = instance.kinetic_energy+instance.potential_energy + instance.evolve_model(1. | nbody_system.time) - E1=instance.kinetic_energy+instance.potential_energy + E1 = instance.kinetic_energy+instance.potential_energy self.assertLess(abs(E1-E0)/abs(E0), 1.e-6) - - + instance.stop() def test9(self): - + instance = self.new_instance_of_an_optional_code(HiGPUs) - - particles=new_plummer_model(128) - - particles[0:64].mass*=0 - particles[64:].mass*=2 - + + particles = new_plummer_model(128) + + particles[0:64].mass *= 0 + particles[64:].mass *= 2 + instance.particles.add_particles(particles) - - E0=instance.kinetic_energy+instance.potential_energy - + + E0 = instance.kinetic_energy+instance.potential_energy + instance.evolve_model(1. | nbody_system.time) - E1=instance.kinetic_energy+instance.potential_energy + E1 = instance.kinetic_energy+instance.potential_energy self.assertLess(abs(E1-E0)/abs(E0), 1.e-6) - - - instance.stop() - - + instance.stop() diff --git a/src/amuse/test/suite/codes_tests/test_hop.py b/src/amuse/test/suite/codes_tests/test_hop.py index 5b07d2c8b0..a5393e1d29 100644 --- a/src/amuse/test/suite/codes_tests/test_hop.py +++ b/src/amuse/test/suite/codes_tests/test_hop.py @@ -8,6 +8,7 @@ from amuse.ic.plummer import new_plummer_model from amuse.community.hop.interface import HopInterface, Hop + class TestHopInterface(TestCase): def test1(self): print("First test: adding particles, setting and getting.") @@ -16,36 +17,36 @@ def test1(self): n, err = hop.get_number_of_particles() self.assertEqual(n, 0) self.assertEqual(err, 0) - + for i in range(6): id, err = hop.new_particle(0, i*i, 0, 0) n, err = hop.get_number_of_particles() self.assertEqual(n, i+1) self.assertEqual(err, 0) - + for i in range(6): x, y, z, err = hop.get_position(i) self.assertEqual(x, i*i) self.assertEqual(y, 0) self.assertEqual(z, 0) self.assertEqual(err, 0) - + hop.set_position(i, x, i*i, 0) - + for i in range(6): - x, y, z, err = hop.get_position(i) + x, y, z, err = hop.get_position(i) self.assertEqual(x, y) self.assertEqual(z, 0) self.assertEqual(err, 0) - + hop.stop() - + def test2(self): random.seed(1001) - + hop = HopInterface() hop.initialize_code() - + particles = new_plummer_model(1000) ids, errors = hop.new_particle( particles.mass.value_in(nbody_system.mass), @@ -53,67 +54,66 @@ def test2(self): particles.y.value_in(nbody_system.length), particles.z.value_in(nbody_system.length) ) - + n, err = hop.get_number_of_particles() self.assertEqual(n, 1000) self.assertEqual(err, 0) - - #distance_to_center = (particles.position - particles.center_of_mass()).lengths() - - #print distance_to_center - ds = {0: 0.482308834791, 1:0.4885137677192688, 2:0.27442726492881775} - for method in [0,1,2]: + + # distance_to_center = (particles.position - particles.center_of_mass()).lengths() + + # print distance_to_center + ds = {0: 0.482308834791, 1: 0.4885137677192688, 2: 0.27442726492881775} + for method in [0, 1, 2]: hop.set_nDens(7) hop.set_density_method(method) hop.calculate_densities() - + d, err = hop.get_density(0) - self.assertAlmostRelativeEquals(d,ds[method], 5) + self.assertAlmostRelativeEquals(d, ds[method], 5) hop.stop() - - def test3(self): - + + def test3(self): + random.seed(1001) - + print("Third test: densest neighbors and groups.") - + hop = HopInterface() hop.initialize_code() - + particles1 = new_plummer_model(10) particles2 = new_plummer_model(10) particles3 = new_plummer_model(10) - - particles2.position += (10,0,0) | nbody_system.length - - particles3.position += (0,20,0) | nbody_system.length - + + particles2.position += (10, 0, 0) | nbody_system.length + + particles3.position += (0, 20, 0) | nbody_system.length + ids1, errors = hop.new_particle( particles1.mass.value_in(nbody_system.mass), particles1.x.value_in(nbody_system.length), particles1.y.value_in(nbody_system.length), particles1.z.value_in(nbody_system.length) ) - + ids2, errors = hop.new_particle( particles2.mass.value_in(nbody_system.mass), particles2.x.value_in(nbody_system.length), particles2.y.value_in(nbody_system.length), particles2.z.value_in(nbody_system.length) ) - + ids3, errors = hop.new_particle( particles3.mass.value_in(nbody_system.mass), particles3.x.value_in(nbody_system.length), particles3.y.value_in(nbody_system.length), particles3.z.value_in(nbody_system.length) ) - - + hop.set_nDens(5) hop.calculate_densities() hop.do_hop() - + n, err = hop.get_group_id(ids1) self.assertEqual(n, 2) self.assertEqual(err, 0) @@ -121,49 +121,50 @@ def test3(self): self.assertEqual(err, 0) n, err = hop.get_group_id(ids3) self.assertEqual(err, 0) - + n, err = hop.get_densest_particle_in_group(2) self.assertEqual(n, 7) for i in range(3): n, err = hop.get_number_of_particles_in_group(0) self.assertEqual(err, 0) self.assertEqual(n, 10) - + n, err = hop.get_number_of_groups() self.assertEqual(n, 3) - + n, err = hop.get_densest_neighbor(ids1) - self.assertEqual(n, [7,7,12,0,7,7,7,7,12,7]) + self.assertEqual(n, [7, 7, 12, 0, 7, 7, 7, 7, 12, 7]) hop.stop() - + def test4(self): hop = HopInterface() hop.initialize_code() value, error = hop.get_nDens() - self.assertEqual(error,0) - self.assertEqual(value,64) + self.assertEqual(error, 0) + self.assertEqual(value, 64) error = hop.set_nDens(7) - self.assertEqual(error,0) + self.assertEqual(error, 0) value, error = hop.get_nDens() - self.assertEqual(value,7) - + self.assertEqual(value, 7) + value, error = hop.get_nHop() - self.assertEqual(error,0) + self.assertEqual(error, 0) self.assertEqual(value, -1) error = hop.set_nHop(7) - self.assertEqual(error,0) + self.assertEqual(error, 0) value, error = hop.get_nHop() - self.assertEqual(value,7) - + self.assertEqual(value, 7) + value, error = hop.get_nBucket() - self.assertEqual(error,0) + self.assertEqual(error, 0) self.assertEqual(value, 16) error = hop.set_nHop(7) - self.assertEqual(error,0) + self.assertEqual(error, 0) value, error = hop.get_nHop() - self.assertEqual(value,7) + self.assertEqual(value, 7) hop.stop() - + + class TestHop(TestCase): def test1(self): print("First test: adding particles, setting and getting.") @@ -173,133 +174,132 @@ def test1(self): particles.x = [i*i for i in range(6)] | nbody_system.length particles.y = 0.0 | nbody_system.length particles.z = 0.0 | nbody_system.length - + hop.particles.add_particles(particles) - + positions = hop.particles.position for i in range(6): x, y, z = positions[i] self.assertEqual(x, i*i | nbody_system.length) self.assertEqual(y, 0 | nbody_system.length) self.assertEqual(z, 0 | nbody_system.length) - + hop.stop() - + def test2(self): random.seed(1001) - + hop = Hop() hop.initialize_code() hop.parameters.number_of_neighbors_for_local_density = 7 hop.commit_parameters() - + particles = new_plummer_model(1000) hop.particles.add_particles(particles) - - - #distance_to_center = (particles.position - particles.center_of_mass()).lengths() - - #print distance_to_center - ds = {0: 0.482308834791, 1:0.4885137677192688, 2:0.27442726492881775} - for method in [0,1,2]: + + # distance_to_center = (particles.position - particles.center_of_mass()).lengths() + + # print distance_to_center + ds = {0: 0.482308834791, 1: 0.4885137677192688, 2: 0.27442726492881775} + for method in [0, 1, 2]: hop.set_density_method(method) hop.calculate_densities() - + d = hop.particles[0].density - + self.assertAlmostRelativeEquals(d, ds[method] | nbody_system.density, 5) hop.stop() - - def test3(self): - + + def test3(self): + random.seed(1001) - + print("Third test: densest neighbors and groups.") - + hop = Hop() hop.parameters.number_of_neighbors_for_local_density = 5 - + particles1 = new_plummer_model(10) particles2 = new_plummer_model(10) particles3 = new_plummer_model(10) - - particles2.position += (10,0,0) | nbody_system.length - - particles3.position += (0,20,0) | nbody_system.length - + + particles2.position += (10, 0, 0) | nbody_system.length + + particles3.position += (0, 20, 0) | nbody_system.length + hop.particles.add_particles(particles1) hop.particles.add_particles(particles2) - hop.particles.add_particles(particles3) - + hop.particles.add_particles(particles3) + hop.calculate_densities() hop.do_hop() - + print(hop.particles.group_id) - + groups = list(hop.groups()) - + self.assertEqual(len(groups), 3) - + self.assertEqual(hop.get_number_of_particles_outside_groups(), 0) - - #densities = (0,0,0) | nbody_system.density + + # densities = (0,0,0) | nbody_system.density for index, group in enumerate(groups): self.assertEqual(len(group), 10) self.assertEqual(group.id_of_group(), index) - #self.assertEquals(group.get_density_of_group(), densities[index]) + # self.assertEquals(group.get_density_of_group(), densities[index]) hop.stop() - + def test4(self): random.seed(1001) print("Test 4: complicated density field.") - + # A separate group below peak_density_threshold -> should be dropped particles0 = new_plummer_model(90, convert_nbody=nbody_system.nbody_to_si(0.9 | units.MSun, 1.0 | units.RSun)) - + # A nearby group below peak_density_threshold -> should be attached to proper group particles1 = new_plummer_model(80, convert_nbody=nbody_system.nbody_to_si(0.8 | units.MSun, 1.0 | units.RSun)) particles1.x += 10 | units.RSun - + # A proper group very nearby other proper group -> groups should merge particles2a = new_plummer_model(200, convert_nbody=nbody_system.nbody_to_si(2.0 | units.MSun, 1.0 | units.RSun)) particles2b = new_plummer_model(300, convert_nbody=nbody_system.nbody_to_si(3.0 | units.MSun, 1.0 | units.RSun)) particles2a.x += 11.0 | units.RSun particles2b.x += 11.2 | units.RSun - + # A separate proper group other proper group -> groups should be preserved particles3 = new_plummer_model(400, convert_nbody=nbody_system.nbody_to_si(4.0 | units.MSun, 1.0 | units.RSun)) particles3.x += 20 | units.RSun - + hop = Hop(unit_converter=nbody_system.nbody_to_si(10.7 | units.MSun, 1.0 | units.RSun)) hop.parameters.number_of_neighbors_for_local_density = 100 hop.parameters.saddle_density_threshold_factor = 0.5 hop.parameters.relative_saddle_density_threshold = True hop.commit_parameters() - + for set in [particles0, particles1, particles2a, particles2b, particles3]: hop.particles.add_particles(set) - + hop.calculate_densities() hop.parameters.outer_density_threshold = 0.1 * hop.particles.density.mean() hop.parameters.peak_density_threshold = hop.particles.density.amax() / 4.0 hop.recommit_parameters() hop.do_hop() groups = list(hop.groups()) - + self.assertEqual(len(hop.particles), 1070) self.assertEqual(len(groups), 2) - self.assertEqual(hop.particles.select(lambda x: x < 5|units.RSun, "x").group_id, -1) + self.assertEqual(hop.particles.select(lambda x: x < 5 | units.RSun, "x").group_id, -1) self.assertEqual(hop.get_number_of_particles_outside_groups(), 299) self.assertEqual(1070 - len(groups[0]) - len(groups[1]), 299) - - expected_size = [477, 294] # Less than [580, 400], because particles below outer_density_threshold are excluded + + expected_size = [477, 294] # Less than [580, 400], because particles below outer_density_threshold are excluded expected_average_x = [11.0, 20] | units.RSun for index, group in enumerate(groups): self.assertEqual(group.id_of_group(), index) self.assertAlmostEqual(group.center_of_mass()[0], expected_average_x[index], 1) self.assertEqual(len(group), expected_size[index]) - - if False: # Make a plot + + if False: # Make a plot original = hop.particles.copy() from amuse.plot import scatter, native_plot colors = ["r", "g", "b", "y", "k", "w"]*100 @@ -308,42 +308,39 @@ def test4(self): original -= group scatter(original.x, original.y, c="m", marker="s") native_plot.show() - + hop.stop() - + def test5(self): print("Test error codes") unit_converter = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) particles = new_plummer_model(200, convert_nbody=unit_converter) - hop = Hop(unit_converter=unit_converter)#, redirection="none") + hop = Hop(unit_converter=unit_converter) # , redirection="none") hop.parameters.number_of_neighbors_for_local_density = 100 hop.particles.add_particles(particles[:99]) - self.assertRaises(AmuseException, hop.calculate_densities, expected_message= - "Error when calling 'calculate_densities' of a 'Hop', errorcode is -5, error is 'Too few particles.'") + self.assertRaises(AmuseException, hop.calculate_densities, expected_message="Error when calling 'calculate_densities' of a 'Hop', errorcode is -5, error is 'Too few particles.'") hop.particles.add_particles(particles[99:101]) hop.calculate_densities() hop.parameters.number_of_neighbors_for_hop = 200 - self.assertRaises(AmuseException, hop.calculate_densities, expected_message= - "Error when calling 'calculate_densities' of a 'Hop', errorcode is -5, error is 'Too few particles.'") + self.assertRaises(AmuseException, hop.calculate_densities, expected_message="Error when calling 'calculate_densities' of a 'Hop', errorcode is -5, error is 'Too few particles.'") hop.particles.add_particles(particles[101:]) hop.calculate_densities() - - self.assertRaises(AmuseException, hop.get_mass, 200, expected_message= - "Error when calling 'get_mass' of a 'Hop', errorcode is -3, error is 'A particle with the given index was not found.'") + + self.assertRaises(AmuseException, hop.get_mass, 200, expected_message="Error when calling 'get_mass' of a 'Hop', errorcode is -3, error is 'A particle with the given index was not found.'") hop.stop() - + def test6(self): print("Test with different masses") # Particles on a cubic grid with masses according to a gaussian density profile grid = numpy.mgrid[-1:1:21j, -1:1:21j, -1:1:21j] | units.m particles = Particles(9261, x=grid[0].flatten(), y=grid[1].flatten(), z=grid[2].flatten()) peak_positions = [[0.2, -0.4, 0.3], [-0.6, 0.2, 0.7]] | units.m - particles.mass = 2*numpy.exp(-(particles.position-peak_positions[0]).lengths_squared() / (0.1|units.m**2)) | units.kg - particles.mass += numpy.exp(-(particles.position-peak_positions[1]).lengths_squared() / (0.1|units.m**2)) | units.kg + particles.mass = 2*numpy.exp(-(particles.position-peak_positions[0]).lengths_squared() / (0.1 | units.m**2)) | units.kg + particles.mass += numpy.exp(-(particles.position-peak_positions[1]).lengths_squared() / (0.1 | units.m**2)) | units.kg self.assertAlmostEqual(particles.position[particles.mass.argmax()], peak_positions[0]) self.assertAlmostEqual(particles[:4000].position[particles[:4000].mass.argmax()], peak_positions[1]) - - hop = Hop(unit_converter=nbody_system.nbody_to_si(particles.mass.sum(), 1.0 | units.m))#, redirection="none") + + hop = Hop(unit_converter=nbody_system.nbody_to_si(particles.mass.sum(), 1.0 | units.m)) # , redirection="none") hop.parameters.density_method = 2 hop.parameters.number_of_neighbors_for_local_density = 50 hop.parameters.relative_saddle_density_threshold = True @@ -358,12 +355,12 @@ def test6(self): for group, peak_position in zip(groups, peak_positions): self.assertAlmostEqual(group.center_of_mass(), peak_position, 1) hop.stop() - + def test7(self): print("Testing Hop states") unit_converter = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) particles = new_plummer_model(200, convert_nbody=unit_converter) - + print("First do everything manually:", end=' ') instance = Hop(unit_converter=unit_converter) self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') @@ -379,7 +376,7 @@ def test7(self): instance.stop() print("ok") - print("initialize_code(), commit_parameters(), (re)commit_particles(), " \ + print("initialize_code(), commit_parameters(), (re)commit_particles(), " "and cleanup_code() should be called automatically:", end=' ') instance = Hop(unit_converter=unit_converter) self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') @@ -396,7 +393,7 @@ def test7(self): instance.stop() self.assertEqual(instance.get_name_of_current_state(), 'STOPPED') print("ok") - + def test8(self): random.seed(1001) print("Test 8: SI vs nbody units.") @@ -409,13 +406,13 @@ def test8(self): hop.parameters.outer_density_threshold = 0.1 | nbody_system.mass / nbody_system.length**3 hop.do_hop() groups = list(hop.groups()) - + self.assertEqual(len(hop.particles), 1000) self.assertEqual(len(groups), 1) self.assertEqual(len(groups[0]), 511) self.assertEqual(len(hop.no_group()), 489) hop.stop() - + numpy.random.seed(1234) particles = new_plummer_model(1000) hop = Hop() @@ -424,12 +421,9 @@ def test8(self): hop.parameters.outer_density_threshold = 0.1 | nbody_system.mass / nbody_system.length**3 hop.do_hop() groups = list(hop.groups()) - + self.assertEqual(len(hop.particles), 1000) self.assertEqual(len(groups), 1) self.assertEqual(len(groups[0]), 511) self.assertEqual(len(hop.no_group()), 489) hop.stop() - - - diff --git a/src/amuse/test/suite/codes_tests/test_huayno.py b/src/amuse/test/suite/codes_tests/test_huayno.py index 352dbc6fa7..85cc10b9e5 100644 --- a/src/amuse/test/suite/codes_tests/test_huayno.py +++ b/src/amuse/test/suite/codes_tests/test_huayno.py @@ -16,57 +16,61 @@ except ImportError: HAS_MATPLOTLIB = False -def elements(starmass,x,y,z,vx,vy,vz,G=constants.G): - mu=G*starmass - r=(x**2+y**2+z**2)**0.5 - v2=(vx**2+vy**2+vz**2) - e=v2/2-mu/r +def elements(starmass, x, y, z, vx, vy, vz, G=constants.G): + mu = G*starmass + r = (x**2+y**2+z**2)**0.5 + v2 = (vx**2+vy**2+vz**2) - a=-mu/2/e + e = v2/2-mu/r - hx=y*vz-z*vy - hy=z*vx-x*vz - hz=x*vy-y*vx + a = -mu/2/e - rdotv=x*vx+y*vy+z*vz + hx = y*vz-z*vy + hy = z*vx-x*vz + hz = x*vy-y*vx - ex=v2*x/mu-rdotv*vx/mu-x/r - ey=v2*y/mu-rdotv*vy/mu-y/r - ez=v2*z/mu-rdotv*vz/mu-z/r + rdotv = x*vx+y*vy+z*vz - h2=(hx**2+hy**2+hz**2) + ex = v2*x/mu-rdotv*vx/mu-x/r + ey = v2*y/mu-rdotv*vy/mu-y/r + ez = v2*z/mu-rdotv*vz/mu-z/r - eps=(1-h2/mu/a)**0.5 + h2 = (hx**2+hy**2+hz**2) - return a,eps + eps = (1-h2/mu/a)**0.5 + + return a, eps + + +def energy(mass, eps, orbiters): + return (0.5*orbiters.velocity.lengths()**2-constants.G*mass/(orbiters.position.lengths()**2+eps**2)**0.5) -def energy(mass,eps,orbiters): - return (0.5*orbiters.velocity.lengths()**2-constants.G*mass/(orbiters.position.lengths()**2+eps**2)**0.5) def angular_momentum(orbiters): - return orbiters.position.cross(orbiters.velocity).lengths() + return orbiters.position.cross(orbiters.velocity).lengths() + class TestHuaynoInterface(TestWithMPI): - + def test1(self): instance = HuaynoInterface() instance.initialize_code() - - res1 = instance.new_particle(mass = 11.0, radius = 2.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) - res2 = instance.new_particle(mass = 21.0, radius = 5.0, x = 10.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) - + + res1 = instance.new_particle(mass=11.0, radius=2.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) + res2 = instance.new_particle(mass=21.0, radius=5.0, x=10.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) + self.assertEqual(0, res1['index_of_the_particle']) self.assertEqual(1, res2['index_of_the_particle']) - + retrieved_state1 = instance.get_state(0) retrieved_state2 = instance.get_state(1) - + self.assertEqual(11.0, retrieved_state1['mass']) self.assertEqual(21.0, retrieved_state2['mass']) self.assertEqual(0.0, retrieved_state1['x']) self.assertEqual(10.0, retrieved_state2['x']) - + instance.cleanup_code() instance.stop() @@ -75,27 +79,27 @@ def test2(self): instance.initialize_code() for i in [0, 1, 2]: - temp_particle = instance.new_particle(mass = i, radius = 1.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) + temp_particle = instance.new_particle(mass=i, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) self.assertEqual(i, temp_particle['index_of_the_particle']) - + instance.delete_particle(1) - + self.assertEqual(2, instance.get_number_of_particles()['number_of_particles']) - + self.assertEqual(0, instance.get_index_of_first_particle()['index_of_the_particle']) - + self.assertEqual(2, instance.get_index_of_next_particle(0)['index_of_the_next_particle']) self.assertEqual(0, instance.get_index_of_next_particle(0)['__result']) self.assertEqual(-2, instance.get_index_of_next_particle(1)['__result']) self.assertEqual(1, instance.get_index_of_next_particle(2)['__result']) instance.cleanup_code() instance.stop() - + def test3(self): huayno = HuaynoInterface() huayno.set_eps2(0.101) self.assertEqual(0.101, huayno.get_eps2()['eps2']) - huayno.set_eps2( 0.110) + huayno.set_eps2(0.110) self.assertEqual(0.110, huayno.get_eps2()['eps2']) huayno.cleanup_code() huayno.stop() @@ -103,19 +107,19 @@ def test3(self): def test5(self): huayno = HuaynoInterface() huayno.initialize_code() - - huayno.new_particle([10,20],[0,0],[0,0], [0,0], [0,0], [0,0], [0,0],[1,1]) + + huayno.new_particle([10, 20], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 1]) retrieved_state = huayno.get_state(0) - + self.assertEqual(10.0, retrieved_state['mass']) self.assertEqual(1, retrieved_state['radius']) - - retrieved_state = huayno.get_state([0,1]) + + retrieved_state = huayno.get_state([0, 1]) self.assertEqual(20.0, retrieved_state['mass'][1]) self.assertEqual(huayno.get_number_of_particles()['number_of_particles'], 2) - huayno.cleanup_code() + huayno.cleanup_code() huayno.stop() - + class TestHuayno(TestWithMPI): def new_system_of_sun_and_earth(self): @@ -127,79 +131,77 @@ def new_system_of_sun_and_earth(self): particles[1].vy = (constants.G * particles.total_mass() / (1.0 | units.AU)).sqrt() particles.move_to_center() return particles - + def test1(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) - + huayno = Huayno(convert_nbody) huayno.initialize_code() huayno.parameters.epsilon_squared = 0.0 | units.AU**2 - + stars = self.new_system_of_sun_and_earth() earth = stars[1] - + huayno.particles.add_particles(stars) - + huayno.evolve_model(365.0 | units.day) huayno.particles.copy_values_of_all_attributes_to(stars) - + position_at_start = earth.position.value_in(units.AU)[0] position_after_full_rotation = earth.position.value_in(units.AU)[0] self.assertAlmostEqual(position_at_start, position_after_full_rotation, 6) - + huayno.evolve_model(365.0 + (365.0 / 2) | units.day) - + huayno.particles.copy_values_of_all_attributes_to(stars) position_after_half_a_rotation = earth.position.value_in(units.AU)[0] self.assertAlmostEqual(-position_at_start, position_after_half_a_rotation, 2) - - huayno.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) - + + huayno.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) + huayno.particles.copy_values_of_all_attributes_to(stars) position_after_half_a_rotation = earth.position.value_in(units.AU)[1] self.assertAlmostEqual(-position_at_start, position_after_half_a_rotation, 3) - + huayno.cleanup_code() - + huayno.stop() - def test2(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) - + instance = Huayno(convert_nbody) instance.initialize_code() instance.parameters.epsilon_squared = 0.0 | units.AU**2 - + stars = self.new_system_of_sun_and_earth() earth = stars[1] instance.particles.add_particles(stars) - - for x in range(1,2000,10): + + for x in range(1, 2000, 10): instance.evolve_model(x | units.day) instance.particles.copy_values_of_all_attributes_to(stars) stars.savepoint() - + if HAS_MATPLOTLIB: figure = pyplot.figure() - plot = figure.add_subplot(1,1,1) - + plot = figure.add_subplot(1, 1, 1) + x_points = earth.get_timeline_of_attribute("x") y_points = earth.get_timeline_of_attribute("y") - + x_points_in_AU = [t_x[1].value_in(units.AU) for t_x in x_points] y_points_in_AU = [t_x1[1].value_in(units.AU) for t_x1 in y_points] - - plot.scatter(x_points_in_AU,y_points_in_AU, color = "b", marker = 'o') - + + plot.scatter(x_points_in_AU, y_points_in_AU, color="b", marker='o') + plot.set_xlim(-1.5, 1.5) plot.set_ylim(-1.5, 1.5) - - + test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "huayno-earth-sun2.svg") figure.savefig(output_file) - + instance.cleanup_code() del instance @@ -209,94 +211,88 @@ def test3(self): instance = Huayno(convert_nbody) instance.initialize_code() instance.parameters.epsilon_squared = 0.00001 | units.AU**2 - + stars = datamodel.Stars(2) star1 = stars[0] star2 = stars[1] star1.mass = units.MSun(1.0) - star1.position = units.AU(numpy.array((-1.0,0.0,0.0))) - star1.velocity = units.AUd(numpy.array((0.0,0.0,0.0))) + star1.position = units.AU(numpy.array((-1.0, 0.0, 0.0))) + star1.velocity = units.AUd(numpy.array((0.0, 0.0, 0.0))) star1.radius = units.RSun(1.0) star2.mass = units.MSun(1.0) - star2.position = units.AU(numpy.array((1.0,0.0,0.0))) - star2.velocity = units.AUd(numpy.array((0.0,0.0,0.0))) + star2.position = units.AU(numpy.array((1.0, 0.0, 0.0))) + star2.velocity = units.AUd(numpy.array((0.0, 0.0, 0.0))) star2.radius = units.RSun(100.0) - + instance.particles.add_particles(stars) - - for x in range(1,2000,10): + + for x in range(1, 2000, 10): instance.evolve_model(x | units.day) instance.particles.copy_values_of_all_attributes_to(stars) stars.savepoint() - - + def test4(self): convert_nbody = nbody_system.nbody_to_si(5.0 | units.kg, 10.0 | units.m) instance = Huayno(convert_nbody) instance.initialize_code() - + particles = datamodel.Particles(2) self.assertEqual(len(instance.particles), 0) - + particles.mass = [15.0, 30.0] | units.kg - particles.radius = [10.0, 20.0] | units.m + particles.radius = [10.0, 20.0] | units.m particles.position = [[10.0, 20.0, 30.0], [20.0, 40.0, 60.0]] | units.m particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.m / units.s - instance.particles.add_particles(particles) self.assertEqual(len(instance.particles), 2) - - instance.particles.mass = [17.0, 33.0] | units.kg - - - self.assertEqual(instance.get_mass(0), 17.0| units.kg) - self.assertEqual(instance.get_mass(1), 33.0| units.kg) + + instance.particles.mass = [17.0, 33.0] | units.kg + + self.assertEqual(instance.get_mass(0), 17.0 | units.kg) + self.assertEqual(instance.get_mass(1), 33.0 | units.kg) def test5(self): convert_nbody = nbody_system.nbody_to_si(5.0 | units.kg, 10.0 | units.m) instance = Huayno(convert_nbody) instance.initialize_code() - + particles = datamodel.Particles(2) self.assertEqual(len(instance.particles), 0) - + particles.mass = [15.0, 30.0] | units.kg - particles.radius = [10.0, 20.0] | units.m + particles.radius = [10.0, 20.0] | units.m particles.position = [[10.0, 20.0, 30.0], [20.0, 40.0, 60.0]] | units.m particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.m / units.s - instance.particles.add_particles(particles) self.assertEqual(len(instance.particles), 2) - - instance.set_state(1, 16|units.kg, 20.0|units.m, 40.0|units.m, 60.0|units.m, - 1.0|units.ms, 1.0|units.ms, 1.0|units.ms) - - curr_state = instance.get_state(1) - for expected, actural in zip((16|units.kg, 20.0|units.m, 40.0|units.m, 60.0|units.m, - 1.0|units.ms, 1.0|units.ms, 1.0|units.ms, 0 | units.m), curr_state): - self.assertAlmostRelativeEquals(actural,expected) - - instance.set_state(1, 16|units.kg, 20.0|units.m, 40.0|units.m, 60.0|units.m, - 1.0|units.ms, 1.0|units.ms, 1.0|units.ms , 20.0|units.m) - - curr_state = instance.get_state(1) - for expected, actural in zip((16|units.kg, 20.0|units.m, 40.0|units.m, 60.0|units.m, - 1.0|units.ms, 1.0|units.ms, 1.0|units.ms, 20 | units.m), curr_state): - self.assertAlmostRelativeEquals(actural,expected) - - - + + instance.set_state(1, 16 | units.kg, 20.0 | units.m, 40.0 | units.m, 60.0 | units.m, + 1.0 | units.ms, 1.0 | units.ms, 1.0 | units.ms) + + curr_state = instance.get_state(1) + for expected, actural in zip((16 | units.kg, 20.0 | units.m, 40.0 | units.m, 60.0 | units.m, + 1.0 | units.ms, 1.0 | units.ms, 1.0 | units.ms, 0 | units.m), curr_state): + self.assertAlmostRelativeEquals(actural, expected) + + instance.set_state(1, 16 | units.kg, 20.0 | units.m, 40.0 | units.m, 60.0 | units.m, + 1.0 | units.ms, 1.0 | units.ms, 1.0 | units.ms, 20.0 | units.m) + + curr_state = instance.get_state(1) + for expected, actural in zip((16 | units.kg, 20.0 | units.m, 40.0 | units.m, 60.0 | units.m, + 1.0 | units.ms, 1.0 | units.ms, 1.0 | units.ms, 20 | units.m), curr_state): + self.assertAlmostRelativeEquals(actural, expected) + def test6(self): print("Test6: Testing Huayno parameters") convert_nbody = nbody_system.nbody_to_si(1.0 | units.yr, 1.0 | units.AU) instance = Huayno(convert_nbody) - + (value, error) = instance.legacy_interface.get_eps2() self.assertEqual(0, error) self.assertEqual(0.0, value) @@ -304,7 +300,7 @@ def test6(self): for x in [0.01, 0.1, 0.2]: instance.parameters.epsilon_squared = x | units.AU**2 self.assertAlmostEqual(x | units.AU**2, instance.parameters.epsilon_squared, in_units=units.AU**2) - + (value, error) = instance.legacy_interface.get_time() self.assertEqual(0, error) self.assertEqual(0.0, value) @@ -313,11 +309,11 @@ def test6(self): instance.parameters.begin_time = x | units.yr self.assertAlmostEqual(x | units.yr, instance.parameters.begin_time, in_units=units.yr) instance.stop() - + def test7(self): print("Test7: Testing effect of Huayno parameter epsilon_squared") convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) - + particles = datamodel.Particles(2) sun = particles[0] sun.mass = 1.0 | units.MSun @@ -330,17 +326,17 @@ def test7(self): earth.radius = 6371.0 | units.km earth.position = [0.0, 1.0, 0.0] | units.AU earth.velocity = [2.0*numpy.pi, -0.0001, 0.0] | units.AU / units.yr - + initial_direction = math.atan((earth.velocity[0]/earth.velocity[1])) final_direction = [] - for log_eps2 in range(-9,10,2): + for log_eps2 in range(-9, 10, 2): instance = Huayno(convert_nbody) instance.initialize_code() instance.parameters.epsilon_squared = 10.0**log_eps2 | units.AU ** 2 instance.particles.add_particles(particles) instance.commit_particles() instance.evolve_model(0.25 | units.yr) - final_direction.append(math.atan((instance.particles[1].velocity[0]/ + final_direction.append(math.atan((instance.particles[1].velocity[0] / instance.particles[1].velocity[1]))) instance.stop() # Small values of epsilon_squared should result in normal earth-sun dynamics: rotation of 90 degrees @@ -349,65 +345,63 @@ def test7(self): self.assertAlmostEqual(final_direction[-1], initial_direction, 2) # Outcome is most sensitive to epsilon_squared when epsilon_squared = d(earth, sun)^2 delta = [abs(final_direction[i+1]-final_direction[i]) for i in range(len(final_direction)-1)] - self.assertEqual(delta[len(final_direction)//2 -1], max(delta)) - - + self.assertEqual(delta[len(final_direction)//2 - 1], max(delta)) + def test13(self): particles = plummer.new_plummer_model(31) - - instance = Huayno(number_of_workers=1)#, debugger="xterm") + + instance = Huayno(number_of_workers=1) # , debugger="xterm") instance.initialize_code() instance.parameters.epsilon_squared = 0.01 | nbody_system.length ** 2 instance.particles.add_particles(particles) - + instance.evolve_model(0.1 | nbody_system.time) instance.synchronize_model() expected_positions = instance.particles.position instance.stop() - + def test14(self): import hashlib numpy.random.seed(123456) particles = plummer.new_plummer_model(32) - sha=hashlib.sha1() + sha = hashlib.sha1() - test_set=["CONSTANT", "SHARED2", "EXTRAPOLATE", + test_set = ["CONSTANT", "SHARED2", "EXTRAPOLATE", "PASS_KDK", "PASS_DKD", "HOLD_KDK", "HOLD_DKD", "PPASS_DKD", "BRIDGE_KDK", "BRIDGE_DKD", "CC", "CC_KEPLER", "CC_BS", "CC_BSA", "OK", "SHAREDBS", "SHARED4", "SHARED6", "SHARED8", "SHARED10"] - #~ test_set=["CONSTANT"] + # ~ test_set=["CONSTANT"] - for itype in test_set: - #~ print() - #~ print(itype) + # ~ print() + # ~ print(itype) instance = Huayno() - instance.parameters.inttype_parameter=Huayno.all_inttypes[itype] - #~ instance.parameters.accelerate_zero_mass=False + instance.parameters.inttype_parameter = Huayno.all_inttypes[itype] + # ~ instance.parameters.accelerate_zero_mass=False instance.particles.add_particles(particles) - E1=instance.kinetic_energy+instance.potential_energy + E1 = instance.kinetic_energy+instance.potential_energy instance.evolve_model(0.125 | nbody_system.time) - E2=instance.kinetic_energy+instance.potential_energy - if itype!="CONSTANT": - self.assertLess(abs(E2-E1).number, 1.e-5) - #~ print((E2-E1).number) + E2 = instance.kinetic_energy+instance.potential_energy + if itype != "CONSTANT": + self.assertLess(abs(E2-E1).number, 1.e-5) + # ~ print((E2-E1).number) - part_out= instance.particles.copy() + part_out = instance.particles.copy() position = part_out.position.number - if hasattr(position,'tobytes'): + if hasattr(position, 'tobytes'): as_bytes = position.tobytes() else: as_bytes = numpy.array(position.data, copy=True, order='C') sha.update(as_bytes) - + instance.stop() - + # this result is probably dependent on system architecture hence no good for assert - print() + print() print(sha.hexdigest()) print("4f2aac4d8761f3b07545dcea53f1a65f84a5275b") @@ -417,42 +411,42 @@ def test14b(self): numpy.random.seed(123456) particles = plummer.new_plummer_model(32) p2 = plummer.new_plummer_model(32) - p2.mass*=0 - sha=hashlib.sha1() + p2.mass *= 0 + sha = hashlib.sha1() - test_set=["CONSTANT", "SHARED2", "EXTRAPOLATE", + test_set = ["CONSTANT", "SHARED2", "EXTRAPOLATE", "PASS_KDK", "PASS_DKD", "HOLD_KDK", "HOLD_DKD", "PPASS_DKD", "BRIDGE_KDK", "BRIDGE_DKD", "CC", "CC_KEPLER", "CC_BS", "CC_BSA", "OK", "SHAREDBS", "SHARED4", "SHARED6", "SHARED8", "SHARED10"] - + for itype in test_set: - #~ print() - #~ print(itype) + # ~ print() + # ~ print(itype) instance = Huayno(redirection="none") - instance.parameters.inttype_parameter=Huayno.all_inttypes[itype] - instance.parameters.accelerate_zero_mass=True + instance.parameters.inttype_parameter = Huayno.all_inttypes[itype] + instance.parameters.accelerate_zero_mass = True instance.particles.add_particles(particles) instance.particles.add_particles(p2) - E1=instance.kinetic_energy+instance.potential_energy + E1 = instance.kinetic_energy+instance.potential_energy instance.evolve_model(0.125 | nbody_system.time) - E2=instance.kinetic_energy+instance.potential_energy - if itype!="CONSTANT": - self.assertLess((E2-E1).number, 1.e-5) + E2 = instance.kinetic_energy+instance.potential_energy + if itype != "CONSTANT": + self.assertLess((E2-E1).number, 1.e-5) - part_out= instance.particles.copy() + part_out = instance.particles.copy() position = part_out.position.number - if hasattr(position,'tobytes'): + if hasattr(position, 'tobytes'): as_bytes = position.tobytes() else: as_bytes = numpy.array(position.data, copy=True, order='C') sha.update(as_bytes) - + instance.stop() - + # this result is probably dependent on system architecture hence no good for assert - print() + print() print(sha.hexdigest()) print("f3563453fb9b959d8337c6e57a526e1ff52572a7") @@ -461,65 +455,65 @@ def test14c(self): numpy.random.seed(123456) particles = plummer.new_plummer_model(16) - particles.mass*=0.25 + particles.mass *= 0.25 p2 = plummer.new_plummer_model(16) - p2.mass*=0.75 - sha=hashlib.sha1() + p2.mass *= 0.75 + sha = hashlib.sha1() - test_set=["CONSTANT", "SHARED2", "EXTRAPOLATE", + test_set = ["CONSTANT", "SHARED2", "EXTRAPOLATE", "PASS_KDK", "PASS_DKD", "HOLD_KDK", "HOLD_DKD", "PPASS_DKD", "BRIDGE_KDK", "BRIDGE_DKD", "CC", "CC_KEPLER", "CC_BS", "CC_BSA", "OK", "SHAREDBS", "SHARED4", "SHARED6", "SHARED8", "SHARED10"] - - #~ test_set=["CC_BS"] - + + # ~ test_set=["CC_BS"] + for itype in test_set: - #~ print() - #~ print(itype) + # ~ print() + # ~ print(itype) instance = Huayno(redirection="none") - instance.parameters.inttype_parameter=Huayno.all_inttypes[itype] - instance.parameters.accelerate_zero_mass=True + instance.parameters.inttype_parameter = Huayno.all_inttypes[itype] + instance.parameters.accelerate_zero_mass = True instance.particles.add_particles(particles) instance.particles.add_particles(p2) - E1=instance.kinetic_energy+instance.potential_energy + E1 = instance.kinetic_energy+instance.potential_energy instance.evolve_model(0.125 | nbody_system.time) - E2=instance.kinetic_energy+instance.potential_energy - #~ if itype!="CONSTANT": - #~ self.assertLess(abs(E2-E1).number, 1.e-5) - #~ print((E2-E1).number) - part_out= instance.particles.copy() + E2 = instance.kinetic_energy+instance.potential_energy + # ~ if itype!="CONSTANT": + # ~ self.assertLess(abs(E2-E1).number, 1.e-5) + # ~ print((E2-E1).number) + part_out = instance.particles.copy() position = part_out.position.number - if hasattr(position,'tobytes'): + if hasattr(position, 'tobytes'): as_bytes = position.tobytes() else: as_bytes = numpy.array(position.data, copy=True, order='C') sha.update(as_bytes) - + instance.stop() - + # this result is probably dependent on system architecture hence no good for assert - print() + print() print(sha.hexdigest()) print("0af7eaea472989ea4be1bb0e2b8633d6b9af41e4") - + def test15(self): particles = plummer.new_plummer_model(512) expected_positions = None for mode in ["cpu", "openmp", "opencl"]: try: - instance = Huayno(mode=mode, number_of_workers=1)#, debugger="xterm") + instance = Huayno(mode=mode, number_of_workers=1) # , debugger="xterm") except: print("Running huayno with mode=", mode, " was unsuccessful.") continue else: print("Running huayno with mode=", mode, "... ") - + instance.initialize_code() instance.parameters.epsilon_squared = 0.01 | nbody_system.length ** 2 instance.particles.add_particles(particles) - + instance.evolve_model(0.2 | nbody_system.time) instance.synchronize_model() if expected_positions is None: @@ -531,29 +525,29 @@ def test15(self): def test16(self): instance = Huayno() instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2 - + particles = datamodel.Particles(2) particles.mass = [1.] | nbody_system.mass - particles.radius = [0.0] | nbody_system.length - particles.position = [[0.0,0.0,0.0],[1.0,0.0,0.0]] | nbody_system.length + particles.radius = [0.0] | nbody_system.length + particles.position = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]] | nbody_system.length particles.velocity = [[0.0, 0.0, 0.0]] | nbody_system.speed instance.particles.add_particles(particles) - + zero = 0.0 | nbody_system.length - + for x in (0.25, 0.5, 0.75): x0 = x | nbody_system.length potential0 = instance.get_potential_at_point(zero, x0, zero, zero) fx0, fy0, fz0 = instance.get_gravity_at_point(zero, x0, zero, zero) - - self.assertAlmostEqual(fy0, 0.0 | nbody_system.acceleration,14) - self.assertAlmostEqual(fz0, 0.0 | nbody_system.acceleration,14) - - fx = (-1.0 / (x0**2)+1.0 / (((1.0|nbody_system.length)-x0)**2)) * (1.0 | nbody_system.length ** 3 / nbody_system.time ** 2) - self.assertAlmostEqual(fx, fx0,14) - self.assertAlmostEqual(potential0, -nbody_system.G*(1.|nbody_system.mass)*(1./x0+1./((1.|nbody_system.length)-x0)),14) + + self.assertAlmostEqual(fy0, 0.0 | nbody_system.acceleration, 14) + self.assertAlmostEqual(fz0, 0.0 | nbody_system.acceleration, 14) + + fx = (-1.0 / (x0**2)+1.0 / (((1.0 | nbody_system.length)-x0)**2)) * (1.0 | nbody_system.length ** 3 / nbody_system.time ** 2) + self.assertAlmostEqual(fx, fx0, 14) + self.assertAlmostEqual(potential0, -nbody_system.G*(1. | nbody_system.mass)*(1./x0+1./((1. | nbody_system.length)-x0)), 14) instance.stop() - + def _compare_integrator_with_collision_integrator(self, inttype_parameter1, inttype_parameter2): numpy.random.seed(12345) particles = plummer.new_plummer_model(101) @@ -570,7 +564,7 @@ def _compare_integrator_with_collision_integrator(self, inttype_parameter1, intt self.assertAlmostRelativeEquals(expected_position, instance.particles.position, 8) self.assertAlmostRelativeEquals(expected_velocity, instance.particles.velocity, 8) instance.stop() - + def _run_collision_with_integrator(self, inttype_parameter): particles = datamodel.Particles(7) particles.mass = 0.001 | nbody_system.mass @@ -579,74 +573,74 @@ def _run_collision_with_integrator(self, inttype_parameter): particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.velocity = [[2, 0, 0], [-2, 0, 0]]*3 + [[-4, 0, 0]] | nbody_system.speed - + instance = Huayno() instance.parameters.inttype_parameter = inttype_parameter instance.particles.add_particles(particles) collisions = instance.stopping_conditions.collision_detection collisions.enable() instance.evolve_model(1.0 | nbody_system.time) - + self.assertTrue(collisions.is_set()) self.assertTrue(instance.model_time < 0.5 | nbody_system.time) self.assertEqual(len(collisions.particles(0)), 3) self.assertEqual(len(collisions.particles(1)), 3) self.assertEqual(len(particles - collisions.particles(0) - collisions.particles(1)), 1) - self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) <= + self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) <= (collisions.particles(0).radius + collisions.particles(1).radius), [True, True, True]) - + sticky_merged = datamodel.Particles(len(collisions.particles(0))) sticky_merged.mass = collisions.particles(0).mass + collisions.particles(1).mass sticky_merged.radius = collisions.particles(0).radius for p1, p2, merged in zip(collisions.particles(0), collisions.particles(1), sticky_merged): merged.position = (p1 + p2).center_of_mass() merged.velocity = (p1 + p2).center_of_mass_velocity() - + instance.particles.remove_particles(collisions.particles(0) + collisions.particles(1)) instance.particles.add_particles(sticky_merged) - + instance.evolve_model(1.0 | nbody_system.time) self.assertTrue(collisions.is_set()) self.assertTrue(instance.model_time < 1.0 | nbody_system.time) self.assertEqual(len(collisions.particles(0)), 1) self.assertEqual(len(collisions.particles(1)), 1) self.assertEqual(len(instance.particles - collisions.particles(0) - collisions.particles(1)), 2) - self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) <= + self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) <= (collisions.particles(0).radius + collisions.particles(1).radius), [True]) instance.stop() - + def test17(self): print("Compare the SHARED2 integrator with the collision-detection enabled SHARED2_COLLISIONS integrator") self._compare_integrator_with_collision_integrator(Huayno.inttypes.SHARED2_COLLISIONS, Huayno.inttypes.SHARED2) print("Testing Huayno collision_detection with SHARED2_COLLISIONS") self._run_collision_with_integrator(Huayno.inttypes.SHARED2_COLLISIONS) - + def test18(self): print("Compare the SHARED4 integrator with the collision-detection enabled SHARED4_COLLISIONS integrator") self._compare_integrator_with_collision_integrator(Huayno.inttypes.SHARED4_COLLISIONS, Huayno.inttypes.SHARED4) print("Testing Huayno collision_detection with SHARED4_COLLISIONS") self._run_collision_with_integrator(Huayno.inttypes.SHARED4_COLLISIONS) - + def test19(self): print("Compare the SHARED6 integrator with the collision-detection enabled SHARED6_COLLISIONS integrator") self._compare_integrator_with_collision_integrator(Huayno.inttypes.SHARED6_COLLISIONS, Huayno.inttypes.SHARED6) print("Testing Huayno collision_detection with SHARED6_COLLISIONS") self._run_collision_with_integrator(Huayno.inttypes.SHARED6_COLLISIONS) - + def test20(self): print("Compare the SHARED8 integrator with the collision-detection enabled SHARED8_COLLISIONS integrator") self._compare_integrator_with_collision_integrator(Huayno.inttypes.SHARED8_COLLISIONS, Huayno.inttypes.SHARED8) print("Testing Huayno collision_detection with SHARED8_COLLISIONS") self._run_collision_with_integrator(Huayno.inttypes.SHARED8_COLLISIONS) - + def test21(self): print("Compare the SHARED10 integrator with the collision-detection enabled SHARED10_COLLISIONS integrator") self._compare_integrator_with_collision_integrator(Huayno.inttypes.SHARED10_COLLISIONS, Huayno.inttypes.SHARED10) print("Testing Huayno collision_detection with SHARED10_COLLISIONS") self._run_collision_with_integrator(Huayno.inttypes.SHARED10_COLLISIONS) - + def test22(self): print("Testing zero-mass test particles in Huayno, can be used for removing particles when inside recursive evolve loop") sun_and_earth = self.new_system_of_sun_and_earth() @@ -655,8 +649,8 @@ def test22(self): huayno = Huayno(convert_nbody) huayno.parameters.epsilon_squared = 0.0 | units.AU**2 huayno.parameters.inttype_parameter = huayno.inttypes.SHARED8 - - test_particle = datamodel.Particle(mass=0|units.MSun, position=[4,0,0]|units.AU, velocity=[0,0,0]|units.kms) + + test_particle = datamodel.Particle(mass=0 | units.MSun, position=[4, 0, 0] | units.AU, velocity=[0, 0, 0] | units.kms) test_particle.vy = (constants.G * sun_and_earth.total_mass() / (4.0 | units.AU)).sqrt() sun_and_earth.add_particle(test_particle) huayno.particles.add_particles(sun_and_earth) @@ -667,188 +661,187 @@ def test22(self): huayno.evolve_model(8.0 * period) self.assertAlmostRelativeEqual(huayno.particles.x, sun_and_earth.x, 8) huayno.stop() - + def test23(self): print("testing removing and adding particles repeatedly") - N=1100 - p1=plummer.new_plummer_model(N) - p2=plummer.new_plummer_model(N) - h1=Huayno() + N = 1100 + p1 = plummer.new_plummer_model(N) + p2 = plummer.new_plummer_model(N) + h1 = Huayno() h1.particles.add_particles(p1[:N//2]) h1.particles.add_particles(p2[-N//2:]) - h2=Huayno() + h2 = Huayno() h2.particles.add_particles(p1) h2.particles.remove_particles(p1[N//2:]) h2.particles.add_particles(p2) h2.particles.remove_particles(p2[:-N//2]) - - self.assertEqual(len(h1.particles),len(h2.particles)) - self.assertAlmostEqual(h1.kinetic_energy,h2.kinetic_energy,15) - self.assertAlmostEqual(h1.potential_energy,h2.potential_energy,15) - + + self.assertEqual(len(h1.particles), len(h2.particles)) + self.assertAlmostEqual(h1.kinetic_energy, h2.kinetic_energy, 15) + self.assertAlmostEqual(h1.potential_energy, h2.potential_energy, 15) + def test24(self): print("test massless particles/ kepler integrator") - N=20 - tend=2.| units.yr + N = 20 + tend = 2. | units.yr numpy.random.seed(12345) - conv=nbody_system.nbody_to_si(4.| units.MSun, 5.|units.AU) - orbiters=plummer.new_plummer_model(N,conv) - sun=datamodel.Particle(mass=1.|units.MSun) - sun.position=[12.3,1.,-.2]|units.AU - sun.velocity=[10,50.,-20.]|units.kms - orbiters.mass*=0. - - a0,eps0=elements(sun.mass,orbiters.x,orbiters.y,orbiters.z, - orbiters.vx,orbiters.vy,orbiters.vz) - - orbiters.position+=sun.position - orbiters.velocity+=sun.velocity - - pos=dict() - for inttype in [20,14]: - code=Huayno(conv) - code.parameters.inttype_parameter=inttype - code.parameters.timestep_parameter=0.1 - code.particles.add_particle(sun) - orbiters2=code.particles.add_particles(orbiters).copy() - orbiters2.position-=sun.position - orbiters2.velocity-=sun.velocity - code.evolve_model(tend) - a,eps=elements(sun.mass,orbiters2.x,orbiters2.y,orbiters2.z, - orbiters2.vx,orbiters2.vy,orbiters2.vz) - - da=abs((a-a0)/a0) - deps=abs(eps-eps0)/eps0 - - dev=numpy.where(da > 1.e-12)[0] - self.assertEqual( len(dev),0) - dev=numpy.where(deps > 1.e-12)[0] - self.assertEqual( len(dev),0) - pos[inttype]=[orbiters2.x.value_in(units.AU),orbiters2.y.value_in(units.AU),orbiters2.z.value_in(units.AU)] - self.assertAlmostEqual(pos[20][0],pos[14][0],12) - self.assertAlmostEqual(pos[20][1],pos[14][1],12) - self.assertAlmostEqual(pos[20][2],pos[14][2],12) + conv = nbody_system.nbody_to_si(4. | units.MSun, 5. | units.AU) + orbiters = plummer.new_plummer_model(N, conv) + sun = datamodel.Particle(mass=1. | units.MSun) + sun.position = [12.3, 1., -.2] | units.AU + sun.velocity = [10, 50., -20.] | units.kms + orbiters.mass *= 0. + + a0, eps0 = elements(sun.mass, orbiters.x, orbiters.y, orbiters.z, + orbiters.vx, orbiters.vy, orbiters.vz) + + orbiters.position += sun.position + orbiters.velocity += sun.velocity + + pos = dict() + for inttype in [20, 14]: + code = Huayno(conv) + code.parameters.inttype_parameter = inttype + code.parameters.timestep_parameter = 0.1 + code.particles.add_particle(sun) + orbiters2 = code.particles.add_particles(orbiters).copy() + orbiters2.position -= sun.position + orbiters2.velocity -= sun.velocity + code.evolve_model(tend) + a, eps = elements(sun.mass, orbiters2.x, orbiters2.y, orbiters2.z, + orbiters2.vx, orbiters2.vy, orbiters2.vz) + + da = abs((a-a0)/a0) + deps = abs(eps-eps0)/eps0 + + dev = numpy.where(da > 1.e-12)[0] + self.assertEqual(len(dev), 0) + dev = numpy.where(deps > 1.e-12)[0] + self.assertEqual(len(dev), 0) + pos[inttype] = [orbiters2.x.value_in(units.AU), orbiters2.y.value_in(units.AU), orbiters2.z.value_in(units.AU)] + self.assertAlmostEqual(pos[20][0], pos[14][0], 12) + self.assertAlmostEqual(pos[20][1], pos[14][1], 12) + self.assertAlmostEqual(pos[20][2], pos[14][2], 12) def test25(self): print("test massless particles/ kepler integrator, smoothed") - N=10 - tend=20.| units.yr + N = 10 + tend = 20. | units.yr numpy.random.seed(12345) - conv=nbody_system.nbody_to_si(4.| units.MSun, 5.|units.AU) - orbiters=plummer.new_plummer_model(N,conv) - sun=datamodel.Particle(mass=1.|units.MSun) - sun.position=[0,0,0]|units.AU - sun.velocity=[0,0,0]|units.kms - orbiters.mass*=0. - eps=(5. | units.AU) - - e0=energy(sun.mass,eps,orbiters) - l0=angular_momentum(orbiters) - - pos=dict() - for inttype in [20,14]: - code=Huayno(conv) - code.parameters.inttype_parameter=inttype - code.parameters.timestep_parameter=0.1 - code.parameters.epsilon_squared=eps**2 - code.particles.add_particle(sun) - orbiters2=code.particles.add_particles(orbiters) - code.evolve_model(tend) - - e1=energy(sun.mass,eps,orbiters2) - l1=angular_momentum(orbiters2) - de,dl=abs((e1-e0)/e0).max(),abs((l1-l0)/l1).max() - self.assertTrue( numpy.all(de< 1.e-8)) - self.assertTrue( numpy.all(dl< 1.e-8)) - - pos[inttype]=[orbiters2.x.value_in(units.AU),orbiters2.y.value_in(units.AU),orbiters2.z.value_in(units.AU)] - self.assertAlmostRelativeEqual(pos[20][0],pos[14][0],4) # still not clear why 4 - self.assertAlmostRelativeEqual(pos[20][1],pos[14][1],4) - self.assertAlmostRelativeEqual(pos[20][2],pos[14][2],4) - + conv = nbody_system.nbody_to_si(4. | units.MSun, 5. | units.AU) + orbiters = plummer.new_plummer_model(N, conv) + sun = datamodel.Particle(mass=1. | units.MSun) + sun.position = [0, 0, 0] | units.AU + sun.velocity = [0, 0, 0] | units.kms + orbiters.mass *= 0. + eps = (5. | units.AU) + + e0 = energy(sun.mass, eps, orbiters) + l0 = angular_momentum(orbiters) + + pos = dict() + for inttype in [20, 14]: + code = Huayno(conv) + code.parameters.inttype_parameter = inttype + code.parameters.timestep_parameter = 0.1 + code.parameters.epsilon_squared = eps**2 + code.particles.add_particle(sun) + orbiters2 = code.particles.add_particles(orbiters) + code.evolve_model(tend) + + e1 = energy(sun.mass, eps, orbiters2) + l1 = angular_momentum(orbiters2) + de, dl = abs((e1-e0)/e0).max(), abs((l1-l0)/l1).max() + self.assertTrue(numpy.all(de < 1.e-8)) + self.assertTrue(numpy.all(dl < 1.e-8)) + + pos[inttype] = [orbiters2.x.value_in(units.AU), orbiters2.y.value_in(units.AU), orbiters2.z.value_in(units.AU)] + self.assertAlmostRelativeEqual(pos[20][0], pos[14][0], 4) # still not clear why 4 + self.assertAlmostRelativeEqual(pos[20][1], pos[14][1], 4) + self.assertAlmostRelativeEqual(pos[20][2], pos[14][2], 4) def test26(self): print("test massless particles (negative time)") - N=10 - tend=-5.| units.yr + N = 10 + tend = -5. | units.yr numpy.random.seed(12345) - conv=nbody_system.nbody_to_si(4.| units.MSun, 5.|units.AU) - orbiters=plummer.new_plummer_model(N,conv) - sun=datamodel.Particle(mass=1.|units.MSun) - sun.position=[0,0,0]|units.AU - sun.velocity=[0,0,0]|units.kms - orbiters.mass*=0. - - a0,eps0=elements(sun.mass,orbiters.x,orbiters.y,orbiters.z, - orbiters.vx,orbiters.vy,orbiters.vz) - - pos=dict() - for inttype in [20,14]: - code=Huayno(conv) - code.parameters.inttype_parameter=inttype - code.parameters.timestep_parameter=0.1 - code.particles.add_particle(sun) - orbiters2=code.particles.add_particles(orbiters) - code.evolve_model(tend) - a,eps=elements(sun.mass,orbiters2.x,orbiters2.y,orbiters2.z, - orbiters2.vx,orbiters2.vy,orbiters2.vz) - - da=abs((a-a0)/a0) - deps=abs(eps-eps0)/eps0 - - dev=numpy.where(da > 1.e-12)[0] - self.assertEqual( len(dev),0) - dev=numpy.where(deps > 1.e-12)[0] - self.assertEqual( len(dev),0) - pos[inttype]=[orbiters.x.value_in(units.AU),orbiters.y.value_in(units.AU),orbiters.z.value_in(units.AU)] - self.assertAlmostEqual(pos[20][0],pos[14][0],12) - self.assertAlmostEqual(pos[20][1],pos[14][1],12) - self.assertAlmostEqual(pos[20][2],pos[14][2],12) - + conv = nbody_system.nbody_to_si(4. | units.MSun, 5. | units.AU) + orbiters = plummer.new_plummer_model(N, conv) + sun = datamodel.Particle(mass=1. | units.MSun) + sun.position = [0, 0, 0] | units.AU + sun.velocity = [0, 0, 0] | units.kms + orbiters.mass *= 0. + + a0, eps0 = elements(sun.mass, orbiters.x, orbiters.y, orbiters.z, + orbiters.vx, orbiters.vy, orbiters.vz) + + pos = dict() + for inttype in [20, 14]: + code = Huayno(conv) + code.parameters.inttype_parameter = inttype + code.parameters.timestep_parameter = 0.1 + code.particles.add_particle(sun) + orbiters2 = code.particles.add_particles(orbiters) + code.evolve_model(tend) + a, eps = elements(sun.mass, orbiters2.x, orbiters2.y, orbiters2.z, + orbiters2.vx, orbiters2.vy, orbiters2.vz) + + da = abs((a-a0)/a0) + deps = abs(eps-eps0)/eps0 + + dev = numpy.where(da > 1.e-12)[0] + self.assertEqual(len(dev), 0) + dev = numpy.where(deps > 1.e-12)[0] + self.assertEqual(len(dev), 0) + pos[inttype] = [orbiters.x.value_in(units.AU), orbiters.y.value_in(units.AU), orbiters.z.value_in(units.AU)] + self.assertAlmostEqual(pos[20][0], pos[14][0], 12) + self.assertAlmostEqual(pos[20][1], pos[14][1], 12) + self.assertAlmostEqual(pos[20][2], pos[14][2], 12) + def test27(self): particles = plummer.new_plummer_model(31) - tend=0.25| nbody_system.time + tend = 0.25 | nbody_system.time instance = Huayno() - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.evolve_model(tend) expected_positions = instance.particles.position self.assertEqual(instance.model_time, tend) instance.stop() - - particles2=particles.copy() - particles2.velocity*=-1 + + particles2 = particles.copy() + particles2.velocity *= -1 instance = Huayno() - instance.particles.add_particles(particles2) + instance.particles.add_particles(particles2) instance.evolve_model(-tend) positions = instance.particles.position self.assertEqual(instance.model_time, -tend) instance.stop() - self.assertAlmostEqual(positions,expected_positions) + self.assertAlmostEqual(positions, expected_positions) def test28(self): particles = plummer.new_plummer_model(31) instance = Huayno() - instance.particles.add_particles(particles) - self.assertAlmostEqual(particles.total_mass(),instance.total_mass) - self.assertAlmostEqual(particles.center_of_mass(),instance.center_of_mass_position) - self.assertAlmostEqual(particles.center_of_mass_velocity(),instance.center_of_mass_velocity) + instance.particles.add_particles(particles) + self.assertAlmostEqual(particles.total_mass(), instance.total_mass) + self.assertAlmostEqual(particles.center_of_mass(), instance.center_of_mass_position) + self.assertAlmostEqual(particles.center_of_mass_velocity(), instance.center_of_mass_velocity) def test29(self): instance = Huayno() instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2 - + particles = datamodel.Particles(2) - particles.position = ([0,0,0], [1,0,0] )| nbody_system.length - particles.velocity = ([-1,0,0], [2,0,0] )| nbody_system.speed - particles.radius = 0| nbody_system.length - particles.mass = 0.1| nbody_system.mass - + particles.position = ([0, 0, 0], [1, 0, 0]) | nbody_system.length + particles.velocity = ([-1, 0, 0], [2, 0, 0]) | nbody_system.speed + particles.radius = 0 | nbody_system.length + particles.mass = 0.1 | nbody_system.mass + instance.particles.add_particles(particles) instance.stopping_conditions.out_of_box_detection.enable() instance.parameters.stopping_conditions_out_of_box_size = 2 | nbody_system.length @@ -858,5 +851,3 @@ def test29(self): self.assertEqual(len(instance.stopping_conditions.out_of_box_detection.particles(0)), 1) self.assertEqual(instance.stopping_conditions.out_of_box_detection.particles(0)[0].key, particles[1].key) instance.stop() - - diff --git a/src/amuse/test/suite/codes_tests/test_interface.py b/src/amuse/test/suite/codes_tests/test_interface.py index a14b0db47b..5986b0a977 100644 --- a/src/amuse/test/suite/codes_tests/test_interface.py +++ b/src/amuse/test/suite/codes_tests/test_interface.py @@ -6,111 +6,107 @@ from amuse.rfi.tools import create_definition from amuse.rfi.tools.create_definition import CodeDocStringProperty from amuse.rfi.core import LegacyFunctionSpecification + + class TestGravitationalDynamics(TestWithMPI): def test1(self): x = GravitationalDynamicsInterface() - + function = GravitationalDynamicsInterface.new_particle specification = function.specification self.assertTrue(specification.description.startswith("Define a new particle")) - + def test2(self): specification = LegacyFunctionSpecification() - specification.name ='test' - specification.addParameter('one','d',specification.IN, 'first parameter') + specification.name = 'test' + specification.addParameter('one', 'd', specification.IN, 'first parameter') specification.description = 'Example function' - + x = create_definition.CreateDescriptionOfAFunctionSpecification() x.specification = specification x.start() - + self.assertTrue(x.out.string.find('void test(float64 one)') > 0) self.assertTrue(x.out.string.find('Example function') >= 0) self.assertTrue(x.out.string.find(':param one:') > 0) - - def test3(self): specification = LegacyFunctionSpecification() - specification.name ='test' - specification.addParameter('one','d',specification.IN, 'first parameter') + specification.name = 'test' + specification.addParameter('one', 'd', specification.IN, 'first parameter') specification.result_type = 'i' specification.result_doc = 'an integer' specification.description = 'Example function' - + x = create_definition.CreateDescriptionOfAFunctionSpecification() x.specification = specification x.start() - + self.assertTrue(x.out.string.find('int32 test(float64 one)') > 0) self.assertTrue(x.out.string.find(':returns:') > 0) - - - + def test4(self): specification = LegacyFunctionSpecification() - specification.name ='test' - specification.addParameter('one','d',specification.IN, 'first parameter') + specification.name = 'test' + specification.addParameter('one', 'd', specification.IN, 'first parameter') specification.result_type = 'i' specification.result_doc = 'an integer' specification.description = 'Example function' - + x = create_definition.CreateFortranStub() x.specification = specification x.start() - + self.assertTrue(x.out.string.find('FUNCTION test(one)') >= 0) self.assertTrue(x.out.string.find('END FUNCTION') > 0) self.assertTrue(x.out.string.find('DOUBLE PRECISION :: one') > 0) - + def test5(self): class WithLegacyDocStringProperty(object): - + def __init__(self): "orignal doc" pass - + @property def specification(self): specification = LegacyFunctionSpecification() - specification.name ='test' - specification.addParameter('one','d',specification.IN, 'first parameter') + specification.name = 'test' + specification.addParameter('one', 'd', specification.IN, 'first parameter') specification.result_type = 'i' specification.result_doc = 'an integer' specification.description = 'Example function' return specification - + __doc__ = CodeDocStringProperty() - - + self.assertEqual("orignal doc", WithLegacyDocStringProperty.__doc__) instance = WithLegacyDocStringProperty() - instance_documentation = WithLegacyDocStringProperty().__doc__ + instance_documentation = WithLegacyDocStringProperty().__doc__ self.assertTrue(instance_documentation.find('FUNCTION test(one)') >= 0) - + def test6(self): print("Testing description of Legacy Function with output parameter") specification = LegacyFunctionSpecification() - specification.name ='test' - specification.addParameter('one','d',specification.OUT, 'first parameter') + specification.name = 'test' + specification.addParameter('one', 'd', specification.OUT, 'first parameter') specification.result_type = 'i' specification.result_doc = 'an integer' specification.description = 'Example function' - + x = create_definition.CreateDescriptionOfAFunctionSpecification() x.specification = specification x.start() self.assertTrue(x.out.string.find('int32 test(float64 * one)') > 0) self.assertTrue(x.out.string.find(':returns:') > 0) - + def test7(self): print("Testing __str__ of Legacy Function") specification = LegacyFunctionSpecification() - specification.name ='test' - specification.addParameter('one','f',specification.IN, 'first parameter, type: float') - specification.addParameter('two','d',specification.OUT, 'second parameter, type double') + specification.name = 'test' + specification.addParameter('one', 'f', specification.IN, 'first parameter, type: float') + specification.addParameter('two', 'd', specification.OUT, 'second parameter, type double') specification.result_type = 'i' specification.result_doc = 'an integer' specification.description = 'Example function' - self.assertEqual(str(specification),"function: int test(float one)\noutput: double two, int __result") - + self.assertEqual(str(specification), "function: int test(float one)\noutput: double two, int __result") diff --git a/src/amuse/test/suite/codes_tests/test_kepler.py b/src/amuse/test/suite/codes_tests/test_kepler.py index bf99fb1c09..a188ef4a2c 100644 --- a/src/amuse/test/suite/codes_tests/test_kepler.py +++ b/src/amuse/test/suite/codes_tests/test_kepler.py @@ -13,33 +13,34 @@ from amuse.community.kepler_orbiters.interface import Kepler + class TestKeplerOrbiters(TestWithMPI): - + def test0(self): instance = Kepler() instance.stop() + def new_system_of_sun_and_earth(self): stars = datamodel.Stars(2) sun = stars[0] sun.mass = units.MSun(1.0) - sun.position = units.m(numpy.array((0.0,0.0,0.0))) - sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) + sun.position = units.m(numpy.array((0.0, 0.0, 0.0))) + sun.velocity = units.ms(numpy.array((0.0, 0.0, 0.0))) sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) - earth.radius = units.km(6371) - earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) - earth.velocity = units.ms(numpy.array((0.0,29800,0.0))) - + earth.radius = units.km(6371) + earth.position = units.km(numpy.array((149.5e6, 0.0, 0.0))) + earth.velocity = units.ms(numpy.array((0.0, 29800, 0.0))) + return stars def test1(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) - instance = Kepler(convert_nbody)#, redirection="none")#, debugger="xterm") + instance = Kepler(convert_nbody) # , redirection="none")#, debugger="xterm") instance.initialize_code() - stars = self.new_system_of_sun_and_earth() earth = stars[1] @@ -50,40 +51,23 @@ def test1(self): instance.evolve_model(365 | units.day) instance.particles.copy_values_of_all_attributes_to(stars) - + position_at_start = earth.position.value_in(units.AU)[0] position_after_full_rotation = earth.position.value_in(units.AU)[0] self.assertAlmostEqual(position_at_start, position_after_full_rotation, 6) - + instance.evolve_model(365.0 + (365.0 / 2) | units.day) - + instance.particles.copy_values_of_all_attributes_to(stars) position_after_half_a_rotation = earth.position.value_in(units.AU)[0] self.assertAlmostEqual(-position_at_start, position_after_half_a_rotation, 3) - - instance.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) - + + instance.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) + instance.particles.copy_values_of_all_attributes_to(stars) position_after_half_a_rotation = earth.position.value_in(units.AU)[1] self.assertAlmostEqual(-position_at_start, position_after_half_a_rotation, 3) - - instance.cleanup_code() - - instance.stop() - - - - - - - - - - - - - - - + instance.cleanup_code() + instance.stop() diff --git a/src/amuse/test/suite/codes_tests/test_krome.py b/src/amuse/test/suite/codes_tests/test_krome.py index 905c483d8e..e4381c186c 100644 --- a/src/amuse/test/suite/codes_tests/test_krome.py +++ b/src/amuse/test/suite/codes_tests/test_krome.py @@ -2,15 +2,16 @@ import numpy from amuse.test.amusetest import TestWithMPI -from amuse.community.krome.interface import KromeInterface,Krome,solar_abundances +from amuse.community.krome.interface import KromeInterface, Krome, solar_abundances from amuse.units import units from amuse.datamodel import Particles from amuse.io import read_set_from_file -#default_options={} +# default_options={} default_options = dict(redirection="none") -#default_options=dict(debugger="gdb") +# default_options=dict(debugger="gdb") + class TestKromeInterface(TestWithMPI): @@ -30,27 +31,27 @@ def test2(self): self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - dens=1.e5 - t=500. - ion=1.e-11 - id,err=instance.new_particle(dens,t,ion) + dens = 1.e5 + t = 500. + ion = 1.e-11 + id, err = instance.new_particle(dens, t, ion) + + self.assertEqual(err, 0) - self.assertEqual(err,0) - - self.assertEqual(instance.commit_particles(),0) + self.assertEqual(instance.commit_particles(), 0) - dens_,t_,ion_,err=instance.get_state(id) + dens_, t_, ion_, err = instance.get_state(id) - self.assertEqual(err,0) + self.assertEqual(err, 0) - self.assertEqual(dens_,dens) - self.assertEqual(t_,t) - self.assertEqual(ion_,ion) + self.assertEqual(dens_, dens) + self.assertEqual(t_, t) + self.assertEqual(ion_, ion) self.assertEqual(0, instance.cleanup_code()) instance.stop() - + def test3(self): print("Test 1: add 2 particles, get state") @@ -58,23 +59,23 @@ def test3(self): self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - dens=[1.e5,2.e5] - t=[500.,550] - ion=[1.e-11,2.e-11] - id,err=instance.new_particle(dens,t,ion) + dens = [1.e5, 2.e5] + t = [500., 550] + ion = [1.e-11, 2.e-11] + id, err = instance.new_particle(dens, t, ion) - self.assertEqual(err,0) - - self.assertEqual(instance.commit_particles(),0) + self.assertEqual(err, 0) + + self.assertEqual(instance.commit_particles(), 0) for i in range(2): - dens_,t_,ion_,err=instance.get_state(id[i]) + dens_, t_, ion_, err = instance.get_state(id[i]) - self.assertEqual(err,0) + self.assertEqual(err, 0) - self.assertEqual(dens_,dens[i]) - self.assertEqual(t_,t[i]) - self.assertEqual(ion_,ion[i]) + self.assertEqual(dens_, dens[i]) + self.assertEqual(t_, t[i]) + self.assertEqual(ion_, ion[i]) self.assertEqual(0, instance.cleanup_code()) @@ -87,23 +88,23 @@ def test4(self): self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - dens=1.e5*numpy.random.random(100) - t=500.*numpy.random.random(100) - ion=1.e-11*numpy.random.random(100) - id,err=instance.new_particle(dens,t,ion) + dens = 1.e5*numpy.random.random(100) + t = 500.*numpy.random.random(100) + ion = 1.e-11*numpy.random.random(100) + id, err = instance.new_particle(dens, t, ion) + + self.assertEqual(err, 0) - self.assertEqual(err,0) - - self.assertEqual(instance.commit_particles(),0) + self.assertEqual(instance.commit_particles(), 0) for i in range(100): - dens_,t_,ion_,err=instance.get_state(id[i]) + dens_, t_, ion_, err = instance.get_state(id[i]) - self.assertEqual(err,0) + self.assertEqual(err, 0) - self.assertEqual(dens_,dens[i]) - self.assertEqual(t_,t[i]) - self.assertEqual(ion_,ion[i]) + self.assertEqual(dens_, dens[i]) + self.assertEqual(t_, t[i]) + self.assertEqual(ion_, ion[i]) self.assertEqual(0, instance.cleanup_code()) @@ -113,17 +114,17 @@ def test5(self): print("Test 5: can we get species?") instance = self.new_instance_of_an_optional_code(KromeInterface, **default_options) - - first,last,err=instance.get_firstlast_abundance() - self.assertEqual(err,0) + + first, last, err = instance.get_firstlast_abundance() + self.assertEqual(err, 0) self.assertTrue(last-first > 0) - - for i in range(first,last+1): - name,err=instance.get_name_of_species(i) - print(name) - self.assertEqual(err,0) - index,err=instance.get_index_of_species(name) - self.assertEqual(i,index) + + for i in range(first, last+1): + name, err = instance.get_name_of_species(i) + print(name) + self.assertEqual(err, 0) + index, err = instance.get_index_of_species(name) + self.assertEqual(i, index) instance.stop() @@ -134,32 +135,32 @@ def test6(self): self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - dens=1.e5*numpy.random.random(100) - t=500.*numpy.random.random(100) - ion=1.e-11*numpy.random.random(100) - ids,err=instance.new_particle(dens,t,ion) + dens = 1.e5*numpy.random.random(100) + t = 500.*numpy.random.random(100) + ion = 1.e-11*numpy.random.random(100) + ids, err = instance.new_particle(dens, t, ion) - self.assertEqual(err,0) - - self.assertEqual(instance.commit_particles(),0) + self.assertEqual(err, 0) + + self.assertEqual(instance.commit_particles(), 0) for i in ids[:10]: - instance.delete_particle(i) + instance.delete_particle(i) instance.recommit_particles() - for i in range(10,100): - dens_,t_,ion_,err=instance.get_state(ids[i]) + for i in range(10, 100): + dens_, t_, ion_, err = instance.get_state(ids[i]) - self.assertEqual(err,0) + self.assertEqual(err, 0) - self.assertEqual(dens_,dens[i]) - self.assertEqual(t_,t[i]) - self.assertEqual(ion_,ion[i]) + self.assertEqual(dens_, dens[i]) + self.assertEqual(t_, t[i]) + self.assertEqual(ion_, ion[i]) - dens_,t_,ion_,err=instance.get_state(ids[0]) + dens_, t_, ion_, err = instance.get_state(ids[0]) - self.assertEqual(err,-1) + self.assertEqual(err, -1) self.assertEqual(0, instance.cleanup_code()) @@ -172,33 +173,33 @@ def test7(self): self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - dens=1.e5 - t=500. - ion=1.e-11 - id,err=instance.new_particle(dens,t,ion) - + dens = 1.e5 + t = 500. + ion = 1.e-11 + id, err = instance.new_particle(dens, t, ion) + instance.commit_particles() - first,last,err=instance.get_firstlast_abundance() - for i in range(first,last+1): - x,err=instance.get_abundance(id,i) - self.assertTrue((x>=0.) & (x<=1.)) - self.assertEqual(err,0) - x,err=instance.get_abundance(id,last+1) - self.assertEqual(err,-1) - - for s in ["H","HE","C","SI","O"]: - x=solar_abundances[s] - aid,err=instance.get_index_of_species(s) - instance.set_abundance(id,aid,x) - - for s in ["H","HE","C","SI","O"]: - x=solar_abundances[s] - aid,err=instance.get_index_of_species(s) - xx,err=instance.get_abundance(id,aid) - self.assertEqual(x,xx) - self.assertEqual(err,0) - + first, last, err = instance.get_firstlast_abundance() + for i in range(first, last+1): + x, err = instance.get_abundance(id, i) + self.assertTrue((x >= 0.) & (x <= 1.)) + self.assertEqual(err, 0) + x, err = instance.get_abundance(id, last+1) + self.assertEqual(err, -1) + + for s in ["H", "HE", "C", "SI", "O"]: + x = solar_abundances[s] + aid, err = instance.get_index_of_species(s) + instance.set_abundance(id, aid, x) + + for s in ["H", "HE", "C", "SI", "O"]: + x = solar_abundances[s] + aid, err = instance.get_index_of_species(s) + xx, err = instance.get_abundance(id, aid) + self.assertEqual(x, xx) + self.assertEqual(err, 0) + def test8(self): print("evolve test") @@ -206,36 +207,36 @@ def test8(self): self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - dens=1.e2 - t=100. - ion=2.e-17 - id,err=instance.new_particle(dens,t,ion) - - first,last,err=instance.get_firstlast_abundance() - for i in range(first,last+1): - err=instance.set_abundance(id,i,1.e-40) - - for s in ["H","HE","C","SI","O"]: - x=solar_abundances[s] - aid,err=instance.get_index_of_species(s) - instance.set_abundance(id,aid,x) + dens = 1.e2 + t = 100. + ion = 2.e-17 + id, err = instance.new_particle(dens, t, ion) + + first, last, err = instance.get_firstlast_abundance() + for i in range(first, last+1): + err = instance.set_abundance(id, i, 1.e-40) + + for s in ["H", "HE", "C", "SI", "O"]: + x = solar_abundances[s] + aid, err = instance.get_index_of_species(s) + instance.set_abundance(id, aid, x) instance.commit_particles() - yr=365*24*3600. - err=instance.evolve_model(10000.*yr) - self.assertEqual(err,0) - time,err=instance.get_time() - self.assertEqual(err,0) - self.assertEqual(time,10000.*yr) - - first,last,err=instance.get_firstlast_abundance() - for i in range(first,last+1): - x,err=instance.get_abundance(id,i) - self.assertEqual(err,0) - name,err=instance.get_name_of_species(i) - print(i,name,x) - + yr = 365*24*3600. + err = instance.evolve_model(10000.*yr) + self.assertEqual(err, 0) + time, err = instance.get_time() + self.assertEqual(err, 0) + self.assertEqual(time, 10000.*yr) + + first, last, err = instance.get_firstlast_abundance() + for i in range(first, last+1): + x, err = instance.get_abundance(id, i) + self.assertEqual(err, 0) + name, err = instance.get_name_of_species(i) + print(i, name, x) + def test9(self): print("evolve test 2") @@ -243,46 +244,46 @@ def test9(self): self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - dens=1.e2 - t=100. - ion=2.e-17 - id,err=instance.new_particle(dens,t,ion) - - first,last,err=instance.get_firstlast_abundance() - for i in range(first,last+1): - err=instance.set_abundance(id,i,1.e-40) - - for s in ["H","HE","C","SI","O"]: - x=solar_abundances[s] - aid,err=instance.get_index_of_species(s) - instance.set_abundance(id,aid,x) - - aid,err=instance.get_index_of_species("C") - instance.set_abundance(id,aid,1.e-40) - - aid,err=instance.get_index_of_species("C+") - instance.set_abundance(id,aid,solar_abundances["C"]) - - aid,err=instance.get_index_of_species("H2") - instance.set_abundance(id,aid,1.e-6) - aid,err=instance.get_index_of_species("H+") - instance.set_abundance(id,aid,1.e-4) + dens = 1.e2 + t = 100. + ion = 2.e-17 + id, err = instance.new_particle(dens, t, ion) + + first, last, err = instance.get_firstlast_abundance() + for i in range(first, last+1): + err = instance.set_abundance(id, i, 1.e-40) + + for s in ["H", "HE", "C", "SI", "O"]: + x = solar_abundances[s] + aid, err = instance.get_index_of_species(s) + instance.set_abundance(id, aid, x) + + aid, err = instance.get_index_of_species("C") + instance.set_abundance(id, aid, 1.e-40) + + aid, err = instance.get_index_of_species("C+") + instance.set_abundance(id, aid, solar_abundances["C"]) + + aid, err = instance.get_index_of_species("H2") + instance.set_abundance(id, aid, 1.e-6) + aid, err = instance.get_index_of_species("H+") + instance.set_abundance(id, aid, 1.e-4) instance.commit_particles() - yr=365*24*3600. - err=instance.evolve_model(10000.*yr) - self.assertEqual(err,0) - time,err=instance.get_time() - self.assertEqual(err,0) - self.assertEqual(time,10000.*yr) + yr = 365*24*3600. + err = instance.evolve_model(10000.*yr) + self.assertEqual(err, 0) + time, err = instance.get_time() + self.assertEqual(err, 0) + self.assertEqual(time, 10000.*yr) - first,last,err=instance.get_firstlast_abundance() - for i in range(first,last+1): - x,err=instance.get_abundance(id,i) - self.assertEqual(err,0) - name,err=instance.get_name_of_species(i) - print(i,name,x) + first, last, err = instance.get_firstlast_abundance() + for i in range(first, last+1): + x, err = instance.get_abundance(id, i) + self.assertEqual(err, 0) + name, err = instance.get_name_of_species(i) + print(i, name, x) def test10(self): print("check initialization of abundances") @@ -291,24 +292,23 @@ def test10(self): self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - dens=1.e2 - t=100. - ion=2.e-17 - id,err=instance.new_particle(dens,t,ion) - - abundances={"E":0.000369180975425, - "H+":0.0001,"HE":0.0775, - "C+":0.000269180975425, "SI": 3.2362683404e-05, + dens = 1.e2 + t = 100. + ion = 2.e-17 + id, err = instance.new_particle(dens, t, ion) + + abundances = {"E": 0.000369180975425, + "H+": 0.0001, "HE": 0.0775, + "C+": 0.000269180975425, "SI": 3.2362683404e-05, "O": 0.000489828841345} - - first,last,err=instance.get_firstlast_abundance() - for i in range(first,last+1): - x,err=instance.get_abundance(id,i) - self.assertEqual(err,0) - name,err=instance.get_name_of_species(i) - if name in abundances: - self.assertAlmostEqual(x,abundances[name],12) + first, last, err = instance.get_firstlast_abundance() + for i in range(first, last+1): + x, err = instance.get_abundance(id, i) + self.assertEqual(err, 0) + name, err = instance.get_name_of_species(i) + if name in abundances: + self.assertAlmostEqual(x, abundances[name], 12) def test11(self): print("evolve test, comparison") @@ -317,56 +317,56 @@ def test11(self): self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - dens=1.e2 - t=100. - ion=2.e-17 - id,err=instance.new_particle(dens,t,ion) + dens = 1.e2 + t = 100. + ion = 2.e-17 + id, err = instance.new_particle(dens, t, ion) instance.evolve_model(1.e10) - - result1={} - first,last,err=instance.get_firstlast_abundance() - for i in range(first,last+1): - x,err=instance.get_abundance(id,i) - self.assertEqual(err,0) - name,err=instance.get_name_of_species(i) - result1[name]=x + + result1 = {} + first, last, err = instance.get_firstlast_abundance() + for i in range(first, last+1): + x, err = instance.get_abundance(id, i) + self.assertEqual(err, 0) + name, err = instance.get_name_of_species(i) + result1[name] = x instance = self.new_instance_of_an_optional_code(KromeInterface, **default_options) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - dens=1.e2 - t=100. - ion=2.e-17 - id,err=instance.new_particle(dens,t,ion) + dens = 1.e2 + t = 100. + ion = 2.e-17 + id, err = instance.new_particle(dens, t, ion) instance.evolve_model(1.e9) instance.evolve_model(5.e9) instance.evolve_model(1.e10) - - result2={} - first,last,err=instance.get_firstlast_abundance() - for i in range(first,last+1): - x,err=instance.get_abundance(id,i) - self.assertEqual(err,0) - name,err=instance.get_name_of_species(i) - result2[name]=x + + result2 = {} + first, last, err = instance.get_firstlast_abundance() + for i in range(first, last+1): + x, err = instance.get_abundance(id, i) + self.assertEqual(err, 0) + name, err = instance.get_name_of_species(i) + result2[name] = x for x in result1: - self.assertAlmostEqual(result1[x],result2[x]) + self.assertAlmostEqual(result1[x], result2[x]) class TestKrome(TestWithMPI): - def makeparts(self,N): - parts=Particles(N) + def makeparts(self, N): + parts = Particles(N) numpy.random.seed(1234567) - parts.number_density=(numpy.random.random(N)*1.e5+1.e5)| units.cm**-3 - parts.temperature=(numpy.random.random(N)*500+100)| units.K - parts.ionrate=(numpy.random.random(N)*1.e-11+1.e-17)| units.s**-1 + parts.number_density = (numpy.random.random(N)*1.e5+1.e5) | units.cm**-3 + parts.temperature = (numpy.random.random(N)*500+100) | units.K + parts.ionrate = (numpy.random.random(N)*1.e-11+1.e-17) | units.s**-1 return parts def test0(self): print("test1: basic startup and flow") - instance=self.new_instance_of_an_optional_code(Krome) + instance = self.new_instance_of_an_optional_code(Krome) self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') instance.initialize_code() self.assertEqual(instance.get_name_of_current_state(), 'INITIALIZED') @@ -381,67 +381,66 @@ def test0(self): def test1(self): print("test1: adding particles") - instance=self.new_instance_of_an_optional_code(Krome) + instance = self.new_instance_of_an_optional_code(Krome) + + parts = self.makeparts(5) - parts=self.makeparts(5) - - self.assertEqual(len(instance.particles),0) + self.assertEqual(len(instance.particles), 0) instance.particles.add_particles(parts) - self.assertEqual(len(instance.particles),len(parts)) + self.assertEqual(len(instance.particles), len(parts)) self.assertEqual(instance.get_name_of_current_state(), 'EDIT') - part2=instance.particles.copy() + part2 = instance.particles.copy() - self.assertAlmostRelativeEquals(parts.number_density,part2.number_density,12) - self.assertAlmostRelativeEquals(parts.temperature,part2.temperature,12) - self.assertAlmostRelativeEquals(parts.ionrate,part2.ionrate,12) + self.assertAlmostRelativeEquals(parts.number_density, part2.number_density, 12) + self.assertAlmostRelativeEquals(parts.temperature, part2.temperature, 12) + self.assertAlmostRelativeEquals(parts.ionrate, part2.ionrate, 12) for p in part2: - i=instance.species["E"] - self.assertAlmostEqual(p.abundances[i],0.000369180975425) - i=instance.species["H+"] - self.assertAlmostEqual(p.abundances[i],0.0001) - i=instance.species["HE"] - self.assertAlmostEqual(p.abundances[i],0.0775) - i=instance.species["C+"] - self.assertAlmostEqual(p.abundances[i],0.000269180975425) - i=instance.species["SI"] - self.assertAlmostEqual(p.abundances[i],3.2362683404e-05) - i=instance.species["O"] - self.assertAlmostEqual(p.abundances[i],0.000489828841345) - + i = instance.species["E"] + self.assertAlmostEqual(p.abundances[i], 0.000369180975425) + i = instance.species["H+"] + self.assertAlmostEqual(p.abundances[i], 0.0001) + i = instance.species["HE"] + self.assertAlmostEqual(p.abundances[i], 0.0775) + i = instance.species["C+"] + self.assertAlmostEqual(p.abundances[i], 0.000269180975425) + i = instance.species["SI"] + self.assertAlmostEqual(p.abundances[i], 3.2362683404e-05) + i = instance.species["O"] + self.assertAlmostEqual(p.abundances[i], 0.000489828841345) + instance.cleanup_code() instance.stop() - def test2(self): print("test2: adding particles w abund.") - instance=self.new_instance_of_an_optional_code(Krome) + instance = self.new_instance_of_an_optional_code(Krome) - parts=self.makeparts(5) - - N=len(instance.species) + parts = self.makeparts(5) - parts.abundances=numpy.zeros((5,N)) + N = len(instance.species) + + parts.abundances = numpy.zeros((5, N)) for i in range(5): - parts[i].abundances=(numpy.array(range(N))+1)/(N+1.) - + parts[i].abundances = (numpy.array(range(N))+1)/(N+1.) + instance.particles.add_particles(parts) - channel=parts.new_channel_to(instance.particles) - channel.copy() + channel = parts.new_channel_to(instance.particles) + channel.copy() - part2=instance.particles.copy() + part2 = instance.particles.copy() - self.assertAlmostRelativeEquals(parts.number_density,part2.number_density,12) - self.assertAlmostRelativeEquals(parts.temperature,part2.temperature,12) - self.assertAlmostRelativeEquals(parts.ionrate,part2.ionrate,12) + self.assertAlmostRelativeEquals(parts.number_density, part2.number_density, 12) + self.assertAlmostRelativeEquals(parts.temperature, part2.temperature, 12) + self.assertAlmostRelativeEquals(parts.ionrate, part2.ionrate, 12) - for i in range(5): - self.assertAlmostRelativeEquals(part2[i].abundances,parts[i].abundances ,12) + for i in range(5): + self.assertAlmostRelativeEquals(part2[i].abundances, parts[i].abundances, 12) instance.cleanup_code() instance.stop() @@ -449,53 +448,53 @@ def test2(self): def test3(self): print("test3: evolve test") - instance=self.new_instance_of_an_optional_code(Krome,**default_options) + instance = self.new_instance_of_an_optional_code(Krome, **default_options) - parts=Particles(1) - parts.number_density=1.e5 | units.cm**-3 - parts.temperature=50 | units.K - parts.ionrate=2.e-17 | units.s**-1 + parts = Particles(1) + parts.number_density = 1.e5 | units.cm**-3 + parts.temperature = 50 | units.K + parts.ionrate = 2.e-17 | units.s**-1 - Ns=len(instance.species) + Ns = len(instance.species) - parts.abundances=numpy.zeros((1,Ns)) + parts.abundances = numpy.zeros((1, Ns)) instance.particles.add_particles(parts) - - instance.evolve_model( 1. | units.Myr ) - + + instance.evolve_model(1. | units.Myr) + print(instance.particles.abundances) - f=2*instance.particles[0].abundances[instance.species["H2"]] - self.assertTrue(f> 0.95) # not much of a test.. - #~ for x,i in instance.species.items(): - #~ print x, instance.particles[0].abundances[i] - + f = 2*instance.particles[0].abundances[instance.species["H2"]] + self.assertTrue(f > 0.95) # not much of a test.. + # ~ for x,i in instance.species.items(): + # ~ print x, instance.particles[0].abundances[i] + instance.cleanup_code() instance.stop() def test4(self): print("test4: evolve test (10 part)") - instance=self.new_instance_of_an_optional_code(Krome,**default_options) + instance = self.new_instance_of_an_optional_code(Krome, **default_options) - parts=Particles(10) - parts.number_density=1.e5 | units.cm**-3 - parts.temperature=50 | units.K - parts.ionrate=2.e-17 | units.s**-1 + parts = Particles(10) + parts.number_density = 1.e5 | units.cm**-3 + parts.temperature = 50 | units.K + parts.ionrate = 2.e-17 | units.s**-1 - Ns=len(instance.species) - - parts.abundances=numpy.zeros((10,Ns)) + Ns = len(instance.species) + + parts.abundances = numpy.zeros((10, Ns)) instance.particles.add_particles(parts) - - instance.evolve_model( 1. | units.Myr ) - - f=2*instance.particles[0].abundances[instance.species["H2"]] - self.assertTrue(f> 0.95) # not much of a test.. - #~ for x,i in instance.species.items(): - #~ print x, instance.particles[0].abundances[i] - + + instance.evolve_model(1. | units.Myr) + + f = 2*instance.particles[0].abundances[instance.species["H2"]] + self.assertTrue(f > 0.95) # not much of a test.. + # ~ for x,i in instance.species.items(): + # ~ print x, instance.particles[0].abundances[i] + instance.cleanup_code() instance.stop() diff --git a/src/amuse/test/suite/codes_tests/test_lab.py b/src/amuse/test/suite/codes_tests/test_lab.py index 60a2cff62f..21cf42346f 100644 --- a/src/amuse/test/suite/codes_tests/test_lab.py +++ b/src/amuse/test/suite/codes_tests/test_lab.py @@ -8,9 +8,10 @@ from amuse import lab + + class TestCodesInLab(amusetest.TestCase): - def test1(self): codes = ( 'SeBa', @@ -22,7 +23,6 @@ def test1(self): 'Bonsai', 'Octgrav', ) - - for code in codes: - self.assertTrue(hasattr(lab, code), msg = 'excpected class {0} in lab module, but the class was not found'.format(code)) + for code in codes: + self.assertTrue(hasattr(lab, code), msg='excpected class {0} in lab module, but the class was not found'.format(code)) diff --git a/src/amuse/test/suite/codes_tests/test_mercury.py b/src/amuse/test/suite/codes_tests/test_mercury.py index 8b0519aee6..e36ba83e7e 100644 --- a/src/amuse/test/suite/codes_tests/test_mercury.py +++ b/src/amuse/test/suite/codes_tests/test_mercury.py @@ -3,13 +3,13 @@ import numpy as np from amuse.test.amusetest import TestWithMPI -from amuse.community.mercury.interface import MercuryInterface, MercuryWayWard,Mercury -from amuse.ext.solarsystem import new_solar_system_for_mercury,new_solar_system +from amuse.community.mercury.interface import MercuryInterface, MercuryWayWard, Mercury +from amuse.ext.solarsystem import new_solar_system_for_mercury, new_solar_system from amuse.units import nbody_system from amuse.units import units, constants from amuse import datamodel from amuse.ic import plummer -DUMMYID=0 +DUMMYID = 0 try: from matplotlib import pyplot @@ -17,187 +17,187 @@ except ImportError: HAS_MATPLOTLIB = False + class TestMercuryInterface(TestWithMPI): - + def setUp(self): super(TestWithMPI, self).setUp() - + def test1(self): - instance=MercuryInterface() + instance = MercuryInterface() instance.stop() def test2(self): - instance=MercuryInterface() - instance.initialize_code() + instance = MercuryInterface() + instance.initialize_code() instance.stop() def test3(self): - instance=MercuryInterface() - instance.initialize_code() - instance.cleanup_code() + instance = MercuryInterface() + instance.initialize_code() + instance.cleanup_code() instance.stop() def test4(self): - instance=MercuryInterface() - instance.initialize_code() - mass,err=instance.get_central_mass(DUMMYID) - self.assertEqual(mass,1.0) - radius,err=instance.get_central_radius(DUMMYID) - self.assertEqual(radius,.005) - j2,j4,j6,err=instance.get_central_oblateness(DUMMYID) - self.assertEqual(j2,0.0) - self.assertEqual(j4,0.0) - self.assertEqual(j6,0.0) - lx,ly,lz,err=instance.get_central_spin(DUMMYID) - self.assertEqual(lx,0.0) - self.assertEqual(ly,0.0) - self.assertEqual(lz,0.0) + instance = MercuryInterface() + instance.initialize_code() + mass, err = instance.get_central_mass(DUMMYID) + self.assertEqual(mass, 1.0) + radius, err = instance.get_central_radius(DUMMYID) + self.assertEqual(radius, .005) + j2, j4, j6, err = instance.get_central_oblateness(DUMMYID) + self.assertEqual(j2, 0.0) + self.assertEqual(j4, 0.0) + self.assertEqual(j6, 0.0) + lx, ly, lz, err = instance.get_central_spin(DUMMYID) + self.assertEqual(lx, 0.0) + self.assertEqual(ly, 0.0) + self.assertEqual(lz, 0.0) instance.stop() def test5(self): - instance=MercuryInterface() - instance.initialize_code() + instance = MercuryInterface() + instance.initialize_code() instance.set_central_mass(DUMMYID, 2.0) - instance.set_central_radius(DUMMYID,0.0625) - instance.set_central_oblateness(DUMMYID,0.001,0.002,0.003) - instance.set_central_spin(DUMMYID,-0.1,-0.2,-0.3) - - - mass,err=instance.get_central_mass(DUMMYID) - self.assertEqual(mass,2.0) - radius,err=instance.get_central_radius(DUMMYID) - self.assertEqual(radius,.0625) - j2,j4,j6,err=instance.get_central_oblateness(DUMMYID) - self.assertEqual(j2,0.001) - self.assertEqual(j4,0.002) - self.assertEqual(j6,0.003) - lx,ly,lz,err=instance.get_central_spin(DUMMYID) - self.assertEqual(lx,-0.1) - self.assertEqual(ly,-0.2) - self.assertEqual(lz,-0.3) + instance.set_central_radius(DUMMYID, 0.0625) + instance.set_central_oblateness(DUMMYID, 0.001, 0.002, 0.003) + instance.set_central_spin(DUMMYID, -0.1, -0.2, -0.3) + + mass, err = instance.get_central_mass(DUMMYID) + self.assertEqual(mass, 2.0) + radius, err = instance.get_central_radius(DUMMYID) + self.assertEqual(radius, .0625) + j2, j4, j6, err = instance.get_central_oblateness(DUMMYID) + self.assertEqual(j2, 0.001) + self.assertEqual(j4, 0.002) + self.assertEqual(j6, 0.003) + lx, ly, lz, err = instance.get_central_spin(DUMMYID) + self.assertEqual(lx, -0.1) + self.assertEqual(ly, -0.2) + self.assertEqual(lz, -0.3) instance.stop() def test6(self): - instance=MercuryInterface() + instance = MercuryInterface() instance.initialize_code() instance.commit_particles() - instance.cleanup_code() + instance.cleanup_code() instance.stop() def test7(self): - instance=MercuryInterface() - instance.initialize_code() - time,err=instance.get_time() - self.assertEqual(time,0.0) + instance = MercuryInterface() + instance.initialize_code() + time, err = instance.get_time() + self.assertEqual(time, 0.0) instance.stop() def test8(self): - instance=MercuryInterface() - instance.initialize_code() - n,err=instance.get_number_of_orbiters() - self.assertEqual(n,0) + instance = MercuryInterface() + instance.initialize_code() + n, err = instance.get_number_of_orbiters() + self.assertEqual(n, 0) instance.stop() def test9(self): - instance=MercuryInterface() + instance = MercuryInterface() instance.initialize_code() - pid,err=instance.new_orbiter(0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.) - n,err=instance.get_number_of_orbiters() - self.assertEqual(n,1) + pid, err = instance.new_orbiter(0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.) + n, err = instance.get_number_of_orbiters() + self.assertEqual(n, 1) instance.stop() def test10(self): - instance=MercuryInterface() + instance = MercuryInterface() instance.initialize_code() - pid,err=instance.new_orbiter(0.5,1.,2.,3.,4.,5.,6.,7.,1.,2.,3.,8.) - mass,dens,x,y,z,vx,vy,vz,sx,sy,sz,celimit,err=instance.get_orbiter_state(pid) - self.assertEqual(mass,0.5) - self.assertEqual(dens,1.) - self.assertEqual(x,2.) - self.assertEqual(y,3.) - self.assertEqual(z,4.) - self.assertEqual(vx,5.) - self.assertEqual(vy,6.) - self.assertEqual(vz,7.) - self.assertEqual(sx,1.) - self.assertEqual(sy,2.) - self.assertEqual(sz,3.) - self.assertEqual(celimit,8.) + pid, err = instance.new_orbiter(0.5, 1., 2., 3., 4., 5., 6., 7., 1., 2., 3., 8.) + mass, dens, x, y, z, vx, vy, vz, sx, sy, sz, celimit, err = instance.get_orbiter_state(pid) + self.assertEqual(mass, 0.5) + self.assertEqual(dens, 1.) + self.assertEqual(x, 2.) + self.assertEqual(y, 3.) + self.assertEqual(z, 4.) + self.assertEqual(vx, 5.) + self.assertEqual(vy, 6.) + self.assertEqual(vz, 7.) + self.assertEqual(sx, 1.) + self.assertEqual(sy, 2.) + self.assertEqual(sz, 3.) + self.assertEqual(celimit, 8.) instance.stop() def test11(self): - instance=MercuryInterface() + instance = MercuryInterface() instance.initialize_code() - mass=3.04043264264672381E-06 - dens=5.52 - x=2.42093942183383037E-01 - y=-9.87467766698604366E-01 - z=-4.54276292555233496E-06 - vx=1.64294055023289365E-02 - vy=4.03200725816140870E-03 - vz=1.13609607260006795E-08 - sx=sy=sz=0. - celimit=20. - pid,err=instance.new_orbiter(mass,dens,x,y,z,vx,vy,vz,sx,sy,sz,celimit) + mass = 3.04043264264672381E-06 + dens = 5.52 + x = 2.42093942183383037E-01 + y = -9.87467766698604366E-01 + z = -4.54276292555233496E-06 + vx = 1.64294055023289365E-02 + vy = 4.03200725816140870E-03 + vz = 1.13609607260006795E-08 + sx = sy = sz = 0. + celimit = 20. + pid, err = instance.new_orbiter(mass, dens, x, y, z, vx, vy, vz, sx, sy, sz, celimit) instance.commit_particles() - de,err=instance.get_energy_deviation() - self.assertEqual(de,0.0) - etot,err=instance.get_total_energy() - ep,err=instance.get_potential_energy() - ek,err=instance.get_kinetic_energy() - self.assertAlmostEqual(etot,ep+ek,15) + de, err = instance.get_energy_deviation() + self.assertEqual(de, 0.0) + etot, err = instance.get_total_energy() + ep, err = instance.get_potential_energy() + ek, err = instance.get_kinetic_energy() + self.assertAlmostEqual(etot, ep+ek, 15) instance.stop() def test12(self): - instance=MercuryInterface() + instance = MercuryInterface() instance.initialize_code() - mass=3.04043264264672381E-06 - dens=5.52 - x=2.42093942183383037E-01 - y=-9.87467766698604366E-01 - z=-4.54276292555233496E-06 - vx=1.64294055023289365E-02 - vy=4.03200725816140870E-03 - vz=1.13609607260006795E-08 - sx=sy=sz=0. - celimit=20. - pid,err=instance.new_orbiter(mass,dens,x,y,z,vx,vy,vz,sx,sy,sz,celimit) + mass = 3.04043264264672381E-06 + dens = 5.52 + x = 2.42093942183383037E-01 + y = -9.87467766698604366E-01 + z = -4.54276292555233496E-06 + vx = 1.64294055023289365E-02 + vy = 4.03200725816140870E-03 + vz = 1.13609607260006795E-08 + sx = sy = sz = 0. + celimit = 20. + pid, err = instance.new_orbiter(mass, dens, x, y, z, vx, vy, vz, sx, sy, sz, celimit) instance.commit_particles() - etot1,err=instance.get_total_energy() - err=instance.evolve_model(8*100000.) - etot2,err=instance.get_total_energy() - self.assertAlmostEqual(etot1,etot2,7) + etot1, err = instance.get_total_energy() + err = instance.evolve_model(8*100000.) + etot2, err = instance.get_total_energy() + self.assertAlmostEqual(etot1, etot2, 7) instance.stop() def test13(self): - instance=MercuryInterface() + instance = MercuryInterface() instance.initialize_code() - mass=3.04043264264672381E-06 - dens=5.52 - x=2.42093942183383037E-01 - y=-9.87467766698604366E-01 - z=-4.54276292555233496E-06 - vx=1.64294055023289365E-02 - vy=4.03200725816140870E-03 - vz=1.13609607260006795E-08 - sx=sy=sz=0. - celimit=20. - pid,err=instance.new_orbiter(mass,dens,x,y,z,vx,vy,vz,sx,sy,sz,celimit) + mass = 3.04043264264672381E-06 + dens = 5.52 + x = 2.42093942183383037E-01 + y = -9.87467766698604366E-01 + z = -4.54276292555233496E-06 + vx = 1.64294055023289365E-02 + vy = 4.03200725816140870E-03 + vz = 1.13609607260006795E-08 + sx = sy = sz = 0. + celimit = 20. + pid, err = instance.new_orbiter(mass, dens, x, y, z, vx, vy, vz, sx, sy, sz, celimit) instance.commit_particles() instance.enable_stopping_condition(3) instance.set_stopping_condition_timeout_parameter(0.01) - etot1,err=instance.get_total_energy() - err=instance.evolve_model(8*1e100) - self.assertTrue(instance.is_stopping_condition_set(3)['result']==1) - etot2,err=instance.get_total_energy() - self.assertAlmostEqual(etot1,etot2,7) + etot1, err = instance.get_total_energy() + err = instance.evolve_model(8*1e100) + self.assertTrue(instance.is_stopping_condition_set(3)['result'] == 1) + etot2, err = instance.get_total_energy() + self.assertAlmostEqual(etot1, etot2, 7) instance.stop() def test14(self): - instance=MercuryInterface(redirection='none') - instance.initialize_code() - instance.set_central_particle_state(DUMMYID, 1.,2.,3.,4.,5.,6.,7.,8.) - mass,radius,j2,j4,j6,lx,ly,lz,err=instance.get_central_particle_state(DUMMYID) + instance = MercuryInterface(redirection='none') + instance.initialize_code() + instance.set_central_particle_state(DUMMYID, 1., 2., 3., 4., 5., 6., 7., 8.) + mass, radius, j2, j4, j6, lx, ly, lz, err = instance.get_central_particle_state(DUMMYID) self.assertEqual(mass, 1.0) self.assertEqual(radius, 2.0) self.assertEqual(j2, 3.0) @@ -209,89 +209,89 @@ def test14(self): instance.stop() def test15(self): - instance=MercuryInterface(redirection='none') - instance.initialize_code() - i,err=instance.get_integrator() - self.assertEqual(i,10) - err=instance.set_integrator(2) - self.assertEqual(err,0) - i,err=instance.get_integrator() - self.assertEqual(i,2) - err=instance.set_integrator(22) - self.assertEqual(err,-1) + instance = MercuryInterface(redirection='none') + instance.initialize_code() + i, err = instance.get_integrator() + self.assertEqual(i, 10) + err = instance.set_integrator(2) + self.assertEqual(err, 0) + i, err = instance.get_integrator() + self.assertEqual(i, 2) + err = instance.set_integrator(22) + self.assertEqual(err, -1) instance.stop() def test16(self): - instance=MercuryInterface() + instance = MercuryInterface() instance.initialize_code() - err=instance.set_integrator(2) - mass=3.04043264264672381E-06 - dens=5.52 - x=2.42093942183383037E-01 - y=-9.87467766698604366E-01 - z=-4.54276292555233496E-06 - vx=1.64294055023289365E-02 - vy=4.03200725816140870E-03 - vz=1.13609607260006795E-08 - sx=sy=sz=0. - celimit=20. - pid,err=instance.new_orbiter(mass,dens,x,y,z,vx,vy,vz,sx,sy,sz,celimit) + err = instance.set_integrator(2) + mass = 3.04043264264672381E-06 + dens = 5.52 + x = 2.42093942183383037E-01 + y = -9.87467766698604366E-01 + z = -4.54276292555233496E-06 + vx = 1.64294055023289365E-02 + vy = 4.03200725816140870E-03 + vz = 1.13609607260006795E-08 + sx = sy = sz = 0. + celimit = 20. + pid, err = instance.new_orbiter(mass, dens, x, y, z, vx, vy, vz, sx, sy, sz, celimit) instance.commit_particles() instance.enable_stopping_condition(3) instance.set_stopping_condition_timeout_parameter(0.01) - etot1,err=instance.get_total_energy() - err=instance.evolve_model(8*1e100) - self.assertTrue(instance.is_stopping_condition_set(3)['result']==1) - etot2,err=instance.get_total_energy() - self.assertAlmostEqual(etot1,etot2,7) + etot1, err = instance.get_total_energy() + err = instance.evolve_model(8*1e100) + self.assertTrue(instance.is_stopping_condition_set(3)['result'] == 1) + etot2, err = instance.get_total_energy() + self.assertAlmostEqual(etot1, etot2, 7) instance.stop() class TestMercury(TestWithMPI): - + def setUp(self): super(TestWithMPI, self).setUp() - + def sun_and_earth(self): orbiter = datamodel.Particles(1) orbiter.mass = 5.97e24 | units.kg - orbiter.density = 1.0|units.g/units.cm**3 - orbiter.position = [1.0,0.0,0.0] | units.AU + orbiter.density = 1.0 | units.g/units.cm**3 + orbiter.position = [1.0, 0.0, 0.0] | units.AU orbiter.velocity = [0.0, 2.0*3.1415926535*1.0/365, 0.0] | units.AUd - orbiter.angular_momentum = [1.0,0,0] | units.MSun * units.AU**2/units.day + orbiter.angular_momentum = [1.0, 0, 0] | units.MSun * units.AU**2/units.day orbiter.celimit = 0.0 | units.none - + centre = datamodel.Particles(1) centre.mass = 1.0 | units.MSun centre.radius = .0000001 | units.AU - centre.j2 = .0001|units.AU**2 - centre.j4 = .0|units.AU**4 - centre.j6 = .0|units.AU**6 - + centre.j2 = .0001 | units.AU**2 + centre.j4 = .0 | units.AU**4 + centre.j6 = .0 | units.AU**6 + centre.angular_momentum = [0.0, 0.0, 0.0] | units.MSun * units.AU**2/units.day return centre, orbiter def test0(self): centre, orbiter = self.sun_and_earth() - mercury = MercuryWayWard()#,debugger='xterm') + mercury = MercuryWayWard() # ,debugger='xterm') mercury.initialize_code() mercury.central_particle.add_particles(centre) mercury.orbiters.add_particles(orbiter) mercury.commit_particles() - self.assertAlmostEqual(mercury.central_particle.j4, .0|units.AU**4) - self.assertAlmostEqual(mercury.central_particle.mass, 1.98892e+30 |units.kg, 3) - self.assertAlmostEqual(mercury.central_particle.mass, 1.0 |units.MSun, 3) - self.assertEqual(mercury.get_number_of_orbiters(),1) - self.assertEqual(mercury.orbiters.position, [[1,0,0]] | units.AU) - self.assertEqual(mercury.orbiters.density, 1.0|units.g/units.cm**3 ) + self.assertAlmostEqual(mercury.central_particle.j4, .0 | units.AU**4) + self.assertAlmostEqual(mercury.central_particle.mass, 1.98892e+30 | units.kg, 3) + self.assertAlmostEqual(mercury.central_particle.mass, 1.0 | units.MSun, 3) + self.assertEqual(mercury.get_number_of_orbiters(), 1) + self.assertEqual(mercury.orbiters.position, [[1, 0, 0]] | units.AU) + self.assertEqual(mercury.orbiters.density, 1.0 | units.g/units.cm**3) self.assertEqual(mercury.orbiters.angular_momentum, [[1.0, 0.0, 0.0]] | units.MSun*units.AU**2/units.day) mercury.evolve_model(365.24 | units.day) self.assertAlmostEqual(mercury.orbiters.position, [[1.0, 0.0, 0.0]] | units.AU, 1) - self.assertAlmostEqual(mercury.kinetic_energy+mercury.potential_energy,mercury.total_energy,3) + self.assertAlmostEqual(mercury.kinetic_energy+mercury.potential_energy, mercury.total_energy, 3) mercury.stop() @@ -306,7 +306,7 @@ def test1(self): mercury.commit_particles() start_pos = mercury.orbiters[2].position - mercury.evolve_model(365.14|units.day) + mercury.evolve_model(365.14 | units.day) self.assertAlmostEqual(mercury.orbiters[2].position, start_pos, 1) mercury.stop() @@ -321,8 +321,8 @@ def test2(self): mercury.commit_particles() start_pos = mercury.orbiters[2].position - mercury.evolve_model(16.|units.day) - self.assertEqual(mercury.get_time(),16.|units.day) + mercury.evolve_model(16. | units.day) + self.assertEqual(mercury.get_time(), 16. | units.day) mercury.stop() def test3(self): @@ -335,10 +335,10 @@ def test3(self): mercury.commit_particles() start_pos = mercury.orbiters[2].position - mercury.evolve_model(365.14|units.day) + mercury.evolve_model(365.14 | units.day) self.assertAlmostEqual(mercury.orbiters[2].position, start_pos, 1) mercury.stop() - + def test4(self): solsys = new_solar_system() @@ -347,12 +347,12 @@ def test4(self): self.assertEqual(mercury.parameters.timestep, 8 | units.day) mercury.set_initial_timestep(1 | units.day) mercury.parameters.timestep = 1 | units.day - + mercury.particles.add_particles(solsys) mercury.commit_particles() start_pos = mercury.orbiters[2].position - mercury.evolve_model(365.14|units.day) + mercury.evolve_model(365.14 | units.day) self.assertAlmostEqual(mercury.orbiters[2].position, start_pos, 1) mercury.stop() @@ -365,7 +365,7 @@ def test5(self): self.assertEqual(mercury.get_name_of_current_state(), 'INITIALIZED') mercury.commit_parameters() self.assertEqual(mercury.get_name_of_current_state(), 'EDIT') - + mercury.central_particle.add_particles(centre) self.assertEqual(mercury.get_name_of_current_state(), 'EDIT') mercury.orbiters.add_particles(orbiters) @@ -375,7 +375,7 @@ def test5(self): self.assertEqual(mercury.get_name_of_current_state(), 'RUN') start_pos = mercury.orbiters[2].position - mercury.evolve_model(365.14|units.day) + mercury.evolve_model(365.14 | units.day) self.assertEqual(mercury.get_name_of_current_state(), 'EVOLVED') self.assertAlmostEqual(mercury.orbiters[2].position, start_pos, 1) @@ -392,7 +392,7 @@ def test6(self): self.assertEqual(mercury.get_name_of_current_state(), 'INITIALIZED') mercury.commit_parameters() self.assertEqual(mercury.get_name_of_current_state(), 'EDIT') - + mercury.central_particle.add_particles(centre) self.assertEqual(mercury.get_name_of_current_state(), 'EDIT') mercury.orbiters.add_particles(orbiters[4:5]) @@ -401,7 +401,7 @@ def test6(self): self.assertEqual(mercury.get_name_of_current_state(), 'RUN') start_pos = mercury.orbiters[0].position - mercury.evolve_model(11.8618|units.yr) + mercury.evolve_model(11.8618 | units.yr) self.assertEqual(mercury.get_name_of_current_state(), 'EVOLVED') self.assertAlmostEqual(mercury.orbiters[0].position, start_pos, 1) @@ -412,7 +412,7 @@ def test6(self): self.assertAlmostEqual(mercury.orbiters[0].position, start_pos, 1) start_pos = mercury.orbiters[0].position - mercury.evolve_model(2*11.8618|units.yr) + mercury.evolve_model(2*11.8618 | units.yr) self.assertEqual(mercury.get_name_of_current_state(), 'EVOLVED') self.assertAlmostEqual(mercury.orbiters[0].position, start_pos, 1) @@ -423,13 +423,13 @@ def test6(self): def test7(self): centre, orbiters = new_solar_system_for_mercury() - mercury = MercuryWayWard()#debugger="gdb") + mercury = MercuryWayWard() # debugger="gdb") self.assertEqual(mercury.get_name_of_current_state(), 'UNINITIALIZED') mercury.initialize_code() self.assertEqual(mercury.get_name_of_current_state(), 'INITIALIZED') mercury.commit_parameters() self.assertEqual(mercury.get_name_of_current_state(), 'EDIT') - + mercury.central_particle.add_particles(centre) self.assertEqual(mercury.get_name_of_current_state(), 'EDIT') mercury.orbiters.add_particles(orbiters[0:5]) @@ -438,7 +438,7 @@ def test7(self): self.assertEqual(mercury.get_name_of_current_state(), 'RUN') start_pos = mercury.orbiters[4].position - mercury.evolve_model(11.8618|units.yr) + mercury.evolve_model(11.8618 | units.yr) self.assertEqual(mercury.get_name_of_current_state(), 'EVOLVED') self.assertAlmostEqual(mercury.orbiters[4].position, start_pos, 1) @@ -449,7 +449,7 @@ def test7(self): self.assertAlmostEqual(mercury.orbiters[3].position, start_pos, 1) start_pos = mercury.orbiters[3].position - mercury.evolve_model(2*11.8618|units.yr) + mercury.evolve_model(2*11.8618 | units.yr) self.assertEqual(mercury.get_name_of_current_state(), 'EVOLVED') self.assertAlmostEqual(mercury.orbiters[3].position, start_pos, 1) @@ -457,17 +457,16 @@ def test7(self): self.assertEqual(mercury.get_name_of_current_state(), 'END') mercury.stop() - def test8(self): centre, orbiters = new_solar_system_for_mercury() - mercury = MercuryWayWard()#debugger="gdb") + mercury = MercuryWayWard() # debugger="gdb") self.assertEqual(mercury.get_name_of_current_state(), 'UNINITIALIZED') mercury.initialize_code() self.assertEqual(mercury.get_name_of_current_state(), 'INITIALIZED') mercury.commit_parameters() self.assertEqual(mercury.get_name_of_current_state(), 'EDIT') - + mercury.central_particle.add_particles(centre) self.assertEqual(mercury.get_name_of_current_state(), 'EDIT') mercury.orbiters.add_particles(orbiters[0:5]) @@ -476,7 +475,7 @@ def test8(self): self.assertEqual(mercury.get_name_of_current_state(), 'RUN') start_pos = mercury.orbiters[4].position - mercury.evolve_model(11.8618|units.yr) + mercury.evolve_model(11.8618 | units.yr) self.assertEqual(mercury.get_name_of_current_state(), 'EVOLVED') self.assertAlmostEqual(mercury.orbiters[4].position, start_pos, 1) @@ -487,7 +486,7 @@ def test8(self): self.assertAlmostEqual(mercury.orbiters[0].position, start_pos, 1) start_pos = mercury.orbiters[0].position - mercury.evolve_model(2*11.8618|units.yr) + mercury.evolve_model(2*11.8618 | units.yr) self.assertEqual(mercury.get_name_of_current_state(), 'EVOLVED') self.assertAlmostEqual(mercury.orbiters[0].position, start_pos, 1) @@ -498,14 +497,14 @@ def test8(self): def test9(self): centre, orbiters = new_solar_system_for_mercury() - mercury = MercuryWayWard()#debugger="gdb") + mercury = MercuryWayWard() # debugger="gdb") self.assertEqual(mercury.get_name_of_current_state(), 'UNINITIALIZED') mercury.central_particle.add_particles(centre) self.assertEqual(mercury.get_name_of_current_state(), 'EDIT') mercury.orbiters.add_particles(orbiters[0:5]) self.assertEqual(mercury.get_name_of_current_state(), 'EDIT') start_pos = mercury.orbiters[4].position - mercury.evolve_model(11.8618|units.yr) + mercury.evolve_model(11.8618 | units.yr) self.assertEqual(mercury.get_name_of_current_state(), 'EVOLVED') self.assertAlmostEqual(mercury.orbiters[4].position, start_pos, 1) @@ -514,7 +513,7 @@ def test9(self): self.assertAlmostEqual(mercury.orbiters[0].position, start_pos, 1) start_pos = mercury.orbiters[0].position - mercury.evolve_model(2*11.8618|units.yr) + mercury.evolve_model(2*11.8618 | units.yr) self.assertEqual(mercury.get_name_of_current_state(), 'EVOLVED') self.assertAlmostEqual(mercury.orbiters[0].position, start_pos, 1) @@ -527,7 +526,7 @@ def test10(self): mercury.orbiters.add_particles(orbiters[4:5]) self.assertEqual(mercury.get_name_of_current_state(), 'EDIT') start_pos = mercury.orbiters[0].position - mercury.evolve_model(11.8618|units.yr) + mercury.evolve_model(11.8618 | units.yr) self.assertEqual(mercury.get_name_of_current_state(), 'EVOLVED') self.assertAlmostEqual(mercury.orbiters[0].position, start_pos, 1) @@ -535,7 +534,7 @@ def test10(self): self.assertEqual(mercury.get_name_of_current_state(), 'UPDATE') self.assertAlmostEqual(mercury.orbiters[0].position, start_pos, 1) start_pos = mercury.orbiters[0].position - mercury.evolve_model(2*11.8618|units.yr) + mercury.evolve_model(2*11.8618 | units.yr) self.assertEqual(mercury.get_name_of_current_state(), 'EVOLVED') self.assertAlmostEqual(mercury.orbiters[0].position, start_pos, 1) @@ -546,10 +545,10 @@ def test11(self): self.assertEqual(mercury.parameters.timestep, 8 | units.day) mercury.parameters.timestep = 1 | units.day self.assertEqual(mercury.parameters.timestep, 1 | units.day) - + mercury.particles.add_particles(solsys) start_pos = mercury.particles[5].position - mercury.evolve_model(11.8618|units.yr) + mercury.evolve_model(11.8618 | units.yr) self.assertAlmostEqual(mercury.particles[5].position, start_pos, 1) mercury.stop() @@ -558,26 +557,26 @@ def test12(self): mercury = Mercury() mercury.parameters.timestep = 1. | units.day - + mercury.particles.add_particles(solsys) start_pos = mercury.particles[5].position - mercury.evolve_model(11.8618|units.yr) + mercury.evolve_model(11.8618 | units.yr) self.assertAlmostEqual(mercury.particles[5].position, start_pos, 1) mercury.particles.remove_particles(mercury.particles[1:5]) self.assertAlmostEqual(mercury.particles[1].position, start_pos, 1) start_pos = mercury.particles[1].position - mercury.evolve_model(2*11.8618|units.yr) + mercury.evolve_model(2*11.8618 | units.yr) self.assertAlmostEqual(mercury.particles[1].position, start_pos, 1) mercury.stop() def test13(self): solsys = new_solar_system() - mercury = Mercury() + mercury = Mercury() mercury.particles.add_particles(solsys) - idpos1 = [ (p.position - q.position) for p in mercury.particles[1:10] for q in mercury.particles[1:10] ] - mercury.evolve_model(11.8618|units.yr) - edpos1 = [ (p.position - q.position) for p in mercury.particles[1:10] for q in mercury.particles[1:10] ] + idpos1 = [(p.position - q.position) for p in mercury.particles[1:10] for q in mercury.particles[1:10]] + mercury.evolve_model(11.8618 | units.yr) + edpos1 = [(p.position - q.position) for p in mercury.particles[1:10] for q in mercury.particles[1:10]] mercury.stop() centre, orbiters = new_solar_system_for_mercury() @@ -586,15 +585,15 @@ def test13(self): mercury.central_particle.add_particles(centre) mercury.orbiters.add_particles(orbiters) - idpos2 = [ (p.position - q.position) for p in mercury.orbiters[0:9] for q in mercury.orbiters[0:9] ] - mercury.evolve_model(11.8618|units.yr) - edpos2 = [ (p.position - q.position) for p in mercury.orbiters[0:9] for q in mercury.orbiters[0:9] ] + idpos2 = [(p.position - q.position) for p in mercury.orbiters[0:9] for q in mercury.orbiters[0:9]] + mercury.evolve_model(11.8618 | units.yr) + edpos2 = [(p.position - q.position) for p in mercury.orbiters[0:9] for q in mercury.orbiters[0:9]] mercury.stop() - for d1,d2 in zip(idpos1,idpos2): - self.assertAlmostEqual(d1,d2, 7) - for d1,d2 in zip(edpos1,edpos2): - self.assertAlmostEqual(d1,d2, 7) + for d1, d2 in zip(idpos1, idpos2): + self.assertAlmostEqual(d1, d2, 7) + for d1, d2 in zip(edpos1, edpos2): + self.assertAlmostEqual(d1, d2, 7) def test14(self): centre, orbiters = new_solar_system_for_mercury() @@ -612,7 +611,7 @@ def test14(self): central_particles = mercury.central_particle.copy() orbiters = mercury.orbiters.copy() mercury.stop() - + mercury = MercuryWayWard() mercury.initialize_code() mercury.parameters.begin_time = halfyear @@ -627,77 +626,76 @@ def test14(self): def test15(self): solsys = new_solar_system() - solsys.x-=1.| units.AU + solsys.x -= 1. | units.AU - p=datamodel.Particles(3) - p.mass=[1,2,3] | units.MSun - p.x=[1,10,100] | units.AU - p.y=[0,0,-10] | units.AU - p.z=[0,0,10] | units.AU + p = datamodel.Particles(3) + p.mass = [1, 2, 3] | units.MSun + p.x = [1, 10, 100] | units.AU + p.y = [0, 0, -10] | units.AU + p.z = [0, 0, 10] | units.AU - pe=p.potential_energy_in_field(solsys) + pe = p.potential_energy_in_field(solsys) mercury = Mercury() mercury.particles.add_particles(solsys) - pot=mercury.get_potential_at_point(p.x*0.,p.x,p.y,p.z) + pot = mercury.get_potential_at_point(p.x*0., p.x, p.y, p.z) - self.assertAlmostRelativeEqual((pot*p.mass).sum(),pe,12) + self.assertAlmostRelativeEqual((pot*p.mass).sum(), pe, 12) def test16(self): solsys = new_solar_system() - solsys.x-=1.| units.AU + solsys.x -= 1. | units.AU - p=datamodel.Particles(3) - p.mass=[1,2,3] | units.MSun - p.x=[1,10,100] | units.AU - p.y=[0,0,-10] | units.AU - p.z=[0,0,10] | units.AU + p = datamodel.Particles(3) + p.mass = [1, 2, 3] | units.MSun + p.x = [1, 10, 100] | units.AU + p.y = [0, 0, -10] | units.AU + p.z = [0, 0, 10] | units.AU from amuse.community.huayno.interface import Huayno - from amuse.units import nbody_system - conv=nbody_system.nbody_to_si(1. | units.AU, 1.| units.MSun) + from amuse.units import nbody_system + conv = nbody_system.nbody_to_si(1. | units.AU, 1. | units.MSun) h = Huayno(conv) h.particles.add_particles(solsys) - - ax1,ay1,az1=h.get_gravity_at_point(p.x*0.,p.x,p.y,p.z) - - mercury = Mercury() - mercury.particles.add_particles(solsys) - ax2,ay2,az2=mercury.get_gravity_at_point(p.x*0.,p.x,p.y,p.z) + ax1, ay1, az1 = h.get_gravity_at_point(p.x*0., p.x, p.y, p.z) + mercury = Mercury() + mercury.particles.add_particles(solsys) + + ax2, ay2, az2 = mercury.get_gravity_at_point(p.x*0., p.x, p.y, p.z) - self.assertAlmostRelativeEqual(ax1,ax2,12) - self.assertAlmostRelativeEqual(ay1,ay2,12) - self.assertAlmostRelativeEqual(az1,az2,12) + self.assertAlmostRelativeEqual(ax1, ax2, 12) + self.assertAlmostRelativeEqual(ay1, ay2, 12) + self.assertAlmostRelativeEqual(az1, az2, 12) def test17(self): solsys = new_solar_system() mercury = Mercury() mercury.particles.add_particles(solsys) - mercury.evolve_model(5.|units.yr) - mercury.evolve_model(10.|units.yr) + mercury.evolve_model(5. | units.yr) + mercury.evolve_model(10. | units.yr) - dpos1=mercury.particles[0].position-mercury.particles[5].position + dpos1 = mercury.particles[0].position-mercury.particles[5].position mercury.stop() mercury = Mercury() mercury.particles.add_particles(solsys) - mercury.evolve_model(5.|units.yr) - mercury.particles.x+=1 | units.AU - mercury.particles.y+=2 | units.AU - mercury.particles.z+=3 | units.AU - mercury.particles.vx+=10. | units.kms - mercury.particles.vy+=20. | units.kms - mercury.particles.vz+=30. | units.kms - mercury.evolve_model(10.|units.yr) - - dpos2=mercury.particles[0].position-mercury.particles[5].position + mercury.evolve_model(5. | units.yr) + mercury.particles.x += 1 | units.AU + mercury.particles.y += 2 | units.AU + mercury.particles.z += 3 | units.AU + mercury.particles.vx += 10. | units.kms + mercury.particles.vy += 20. | units.kms + mercury.particles.vz += 30. | units.kms + mercury.evolve_model(10. | units.yr) + + dpos2 = mercury.particles[0].position-mercury.particles[5].position mercury.stop() - + self.assertAlmostEqual(dpos1, dpos2, 12) def test18(self): @@ -705,9 +703,9 @@ def test18(self): mercury = Mercury() mercury.initialize_code() - self.assertEqual(mercury.parameters.integrator,10) - mercury.parameters.integrator=2 - self.assertEqual(mercury.parameters.integrator,2) + self.assertEqual(mercury.parameters.integrator, 10) + mercury.parameters.integrator = 2 + self.assertEqual(mercury.parameters.integrator, 2) mercury.stop() def test19(self): @@ -715,28 +713,28 @@ def test19(self): mercury = Mercury() mercury.initialize_code() - mercury.parameters.integrator=1 + mercury.parameters.integrator = 1 mercury.particles.add_particles(solsys) mercury.commit_particles() start_pos = mercury.orbiters[2].position - mercury.evolve_model(365.14|units.day) + mercury.evolve_model(365.14 | units.day) self.assertAlmostEqual(mercury.orbiters[2].position, start_pos, 1) mercury.stop() def test20(self): solsys = new_solar_system() - mercury = Mercury()#debugger="gdb") + mercury = Mercury() # debugger="gdb") mercury.initialize_code() - mercury.parameters.integrator=2 + mercury.parameters.integrator = 2 mercury.particles.add_particles(solsys) mercury.commit_particles() start_pos = mercury.orbiters[2].position - mercury.evolve_model(365.14|units.day) + mercury.evolve_model(365.14 | units.day) self.assertAlmostEqual(mercury.orbiters[2].position, start_pos, 1) mercury.stop() @@ -745,84 +743,83 @@ def test21(self): mercury = Mercury() mercury.initialize_code() - - names=["elements_file","close_encounters_file","info_file", - "bigbody_file","smallbody_file","integration_parameters_file","restart_file"] - + + names = ["elements_file", "close_encounters_file", "info_file", + "bigbody_file", "smallbody_file", "integration_parameters_file", "restart_file"] + for name in names: - self.assertEqual(getattr(mercury.parameters,name),"/dev/null") - + self.assertEqual(getattr(mercury.parameters, name), "/dev/null") + for name in names: - setattr(mercury.parameters,name,os.path.join(mercury.output_directory,name)) + setattr(mercury.parameters, name, os.path.join(mercury.output_directory, name)) for name in names: - self.assertEqual(getattr(mercury.parameters,name),os.path.join(mercury.output_directory,name)) + self.assertEqual(getattr(mercury.parameters, name), os.path.join(mercury.output_directory, name)) mercury.stop() def xtest22(self): """ collision test hangs or fails if internal collision detection is enabled """ - + def collision(): - - M=1.| units.MSun - m=1.| units.MJupiter - r=5. | units.AU - vcirc=(constants.G*(M+m)/r)**0.5 - - sys=datamodel.Particles(4) - sys[0].mass=M - sys[0].radius=1. | units.RSun - sys[0].x=0 | units.AU - sys[0].y=0 | units.AU - sys[0].z=0 | units.AU - sys[0].vx=0 | units.kms - sys[0].vy=0 | units.kms - sys[0].vz=0 | units.kms - - sys[1].mass=m - sys[1].radius=0.01 | units.RSun - sys[1].x=r - sys[1].y=0 | units.AU - sys[1].z=0 | units.AU - sys[1].vx=0 | units.kms - sys[1].vy=vcirc - sys[1].vz=0 | units.kms - - sys[2].mass=m - sys[2].radius=0.01 | units.RSun - sys[2].x=-r - sys[2].y=0 | units.AU - sys[2].z=0 | units.AU - sys[2].vx=0 | units.kms - sys[2].vy=vcirc - sys[2].vz=0 | units.kms - - sys[3].mass=m - sys[3].radius=0.01 | units.RSun - sys[3].x=0 | units.AU - sys[3].y=r - sys[3].z=0 | units.AU - sys[3].vx=0 | units.kms - sys[3].vy=0 | units.kms - sys[3].vz=0 | units.kms - + + M = 1. | units.MSun + m = 1. | units.MJupiter + r = 5. | units.AU + vcirc = (constants.G*(M+m)/r)**0.5 + + sys = datamodel.Particles(4) + sys[0].mass = M + sys[0].radius = 1. | units.RSun + sys[0].x = 0 | units.AU + sys[0].y = 0 | units.AU + sys[0].z = 0 | units.AU + sys[0].vx = 0 | units.kms + sys[0].vy = 0 | units.kms + sys[0].vz = 0 | units.kms + + sys[1].mass = m + sys[1].radius = 0.01 | units.RSun + sys[1].x = r + sys[1].y = 0 | units.AU + sys[1].z = 0 | units.AU + sys[1].vx = 0 | units.kms + sys[1].vy = vcirc + sys[1].vz = 0 | units.kms + + sys[2].mass = m + sys[2].radius = 0.01 | units.RSun + sys[2].x = -r + sys[2].y = 0 | units.AU + sys[2].z = 0 | units.AU + sys[2].vx = 0 | units.kms + sys[2].vy = vcirc + sys[2].vz = 0 | units.kms + + sys[3].mass = m + sys[3].radius = 0.01 | units.RSun + sys[3].x = 0 | units.AU + sys[3].y = r + sys[3].z = 0 | units.AU + sys[3].vx = 0 | units.kms + sys[3].vy = 0 | units.kms + sys[3].vz = 0 | units.kms + return sys - - code=Mercury() - - sys=collision() - + + code = Mercury() + + sys = collision() + code.particles.add_particles(sys) - - tend=3.5| units.yr - dt=100. | units.day - tnow=code.model_time - - while tnow= target_end_time) - + (L_of_the_star, error) = instance.get_luminosity(index_of_the_star) self.assertEqual(0, error) - self.assertAlmostEqual(L_of_the_star,0.725,1) + self.assertAlmostEqual(L_of_the_star, 0.725, 1) (M_of_the_star, error) = instance.get_mass(index_of_the_star) self.assertEqual(0, error) - self.assertAlmostEqual(M_of_the_star,1.000,3) + self.assertAlmostEqual(M_of_the_star, 1.000, 3) (T_of_the_star, error) = instance.get_temperature(index_of_the_star) self.assertEqual(0, error) - self.assertAlmostEqual(T_of_the_star,5650.998,-2) + self.assertAlmostEqual(T_of_the_star, 5650.998, -2) instance.stop() - + def slowtest5(self): print("Testing evolve with varying Z (tests new ZAMS model implicitly)...") - print("If the required starting models do not exist, this test will " \ + print("If the required starting models do not exist, this test will " "take quite some time to generate them.") instance = self.new_instance_of_an_optional_code(MESAInterface) if instance is None: print("MESA was not built. Skipping test.") return - instance.set_MESA_paths(instance.default_path_to_inlist, + instance.set_MESA_paths(instance.default_path_to_inlist, instance.default_path_to_MESA_data, instance.get_output_directory()) status = instance.initialize_code() - self.assertEqual(status,0) + self.assertEqual(status, 0) metallicities = [0.00, 0.01, 0.02, 0.04] luminosities = [1.717, 0.938, 0.725, 0.592] - for (i,(Z,L)) in enumerate(zip(metallicities, luminosities)): + for (i, (Z, L)) in enumerate(zip(metallicities, luminosities)): status = instance.set_metallicity(Z) self.assertEqual(0, status) (index_of_the_star, status) = instance.new_particle(1.0) self.assertEqual(0, status) - self.assertEqual(index_of_the_star,i+1) + self.assertEqual(index_of_the_star, i+1) instance.evolve_for(index_of_the_star, 5.0e5) (L_of_the_star, status) = instance.get_luminosity(index_of_the_star) self.assertEqual(0, status) - self.assertAlmostEqual(L_of_the_star,L,1) + self.assertAlmostEqual(L_of_the_star, L, 1) instance.stop() - + def test6(self): print("Testing MESA stop conditions...") instance = self.new_instance_of_an_optional_code(MESAInterface) @@ -148,9 +149,9 @@ def test6(self): print("MESA was not built. Skipping test.") return (value, error) = instance.get_max_age_stop_condition() - self.assertEqual(0, error) + self.assertEqual(0, error) self.assertEqual(1.0e36, value) - for x in range(10,14): + for x in range(10, 14): error = instance.set_max_age_stop_condition(10 ** x) self.assertEqual(0, error) (value, error) = instance.get_max_age_stop_condition() @@ -159,14 +160,14 @@ def test6(self): (value, error) = instance.get_min_timestep_stop_condition() self.assertEqual(0, error) self.assertEqual(1.0e-6, value) - for x in range(-9,-2): + for x in range(-9, -2): error = instance.set_min_timestep_stop_condition(10.0 ** x) self.assertEqual(0, error) (value, error) = instance.get_min_timestep_stop_condition() self.assertEqual(0, error) self.assertEqual(10.0 ** x, value) instance.stop() - + def test7(self): print("Testing MESA parameters...") instance = self.new_instance_of_an_optional_code(MESAInterface) @@ -174,7 +175,7 @@ def test7(self): print("MESA was not built. Skipping test.") return (value, error) = instance.get_mixing_length_ratio() - self.assertEqual(0, error) + self.assertEqual(0, error) self.assertEqual(2.0, value) for x in [1.0, 1.5, 3.0]: error = instance.set_mixing_length_ratio(x) @@ -192,7 +193,7 @@ def test7(self): self.assertEqual(0, error) self.assertEqual(x, value) instance.stop() - + def test8(self): print("Testing MESA wind parameters...") instance = self.new_instance_of_an_optional_code(MESAInterface) @@ -200,7 +201,7 @@ def test8(self): print("MESA was not built. Skipping test.") return (value, error) = instance.get_RGB_wind_scheme() - self.assertEqual(0, error) + self.assertEqual(0, error) self.assertEqual(1, value) for x in range(6): error = instance.set_RGB_wind_scheme(x) @@ -208,9 +209,9 @@ def test8(self): (value, error) = instance.get_RGB_wind_scheme() self.assertEqual(0, error) self.assertEqual(x, value) - + (value, error) = instance.get_AGB_wind_scheme() - self.assertEqual(0, error) + self.assertEqual(0, error) self.assertEqual(1, value) for x in range(6): error = instance.set_AGB_wind_scheme(x) @@ -218,7 +219,7 @@ def test8(self): (value, error) = instance.get_AGB_wind_scheme() self.assertEqual(0, error) self.assertEqual(x, value) - + (value, error) = instance.get_reimers_wind_efficiency() self.assertEqual(0, error) self.assertEqual(0.5, value) @@ -228,7 +229,7 @@ def test8(self): (value, error) = instance.get_reimers_wind_efficiency() self.assertEqual(0, error) self.assertEqual(x, value) - + (value, error) = instance.get_blocker_wind_efficiency() self.assertEqual(0, error) self.assertEqual(0.1, value) @@ -238,7 +239,7 @@ def test8(self): (value, error) = instance.get_blocker_wind_efficiency() self.assertEqual(0, error) self.assertEqual(x, value) - + (value, error) = instance.get_de_jager_wind_efficiency() self.assertEqual(0, error) self.assertEqual(0.8, value) @@ -248,7 +249,7 @@ def test8(self): (value, error) = instance.get_de_jager_wind_efficiency() self.assertEqual(0, error) self.assertEqual(x, value) - + (value, error) = instance.get_dutch_wind_efficiency() self.assertEqual(0, error) self.assertEqual(0.8, value) @@ -258,19 +259,19 @@ def test8(self): (value, error) = instance.get_dutch_wind_efficiency() self.assertEqual(0, error) self.assertEqual(x, value) - + instance.stop() class TestMESA(TestWithMPI): - + def test1(self): print("Testing initialization and default MESA parameters...") instance = self.new_instance_of_an_optional_code(MESA) if instance is None: print("MESA was not built. Skipping test.") return - instance.set_MESA_paths(instance.default_path_to_inlist, + instance.set_MESA_paths(instance.default_path_to_inlist, instance.default_path_to_MESA_data, instance.get_output_directory()) instance.initialize_code() self.assertEqual(0.02 | units.no_unit, instance.parameters.metallicity) @@ -278,18 +279,18 @@ def test1(self): instance.parameters.max_age_stop_condition = 1.0e2 | units.Myr self.assertEqual(1.0e2 | units.Myr, instance.parameters.max_age_stop_condition) instance.stop() - + def test2(self): print("Testing basic operations: evolve and get_...") instance = self.new_instance_of_an_optional_code(MESA) if instance is None: print("MESA was not built. Skipping test.") return - instance.initialize_code() - instance.commit_parameters() + instance.initialize_code() + instance.commit_parameters() index_of_the_star = instance.new_particle(1.0 | units.MSun) - self.assertEqual(index_of_the_star,1) - + self.assertEqual(index_of_the_star, 1) + initial_dt = 1.0e5 | units.yr dt_factor = 1.2 time_step = instance.get_time_step(index_of_the_star) @@ -297,29 +298,29 @@ def test2(self): instance.evolve_one_step(index_of_the_star) age_of_the_star = instance.get_age(index_of_the_star) self.assertAlmostEqual(age_of_the_star, initial_dt) - + target_end_time = 3.0e5 | units.yr instance.evolve_for(index_of_the_star, target_end_time - age_of_the_star) self.assertAlmostEqual(initial_dt*(1 + dt_factor + dt_factor**2), instance.get_age(index_of_the_star)) self.assertAlmostEqual(initial_dt*dt_factor**3, instance.get_time_step(index_of_the_star)) self.assertTrue(instance.get_age(index_of_the_star) >= target_end_time) - + L_of_the_star = instance.get_luminosity(index_of_the_star) - self.assertAlmostEqual(L_of_the_star,0.725 | units.LSun,1) + self.assertAlmostEqual(L_of_the_star, 0.725 | units.LSun, 1) M_of_the_star = instance.get_mass(index_of_the_star) - self.assertAlmostEqual(M_of_the_star,1.000 | units.MSun,3) + self.assertAlmostEqual(M_of_the_star, 1.000 | units.MSun, 3) T_of_the_star = instance.get_temperature(index_of_the_star) - self.assertAlmostEqual(T_of_the_star,5650.998 | units.K,-2) + self.assertAlmostEqual(T_of_the_star, 5650.998 | units.K, -2) instance.stop() - + def test3(self): print("Testing basic operations: evolve_model and channels...") instance = self.new_instance_of_an_optional_code(MESA) if instance is None: print("MESA was not built. Skipping test.") return - instance.initialize_code() - instance.commit_parameters() + instance.initialize_code() + instance.commit_parameters() stars = Particles(1) mass = 10. | units.MSun stars.mass = mass @@ -327,8 +328,8 @@ def test3(self): instance.commit_particles() from_code_to_model = instance.particles.new_channel_to(stars) from_code_to_model.copy() - #print stars - #instance.evolve_model(end_time = 0.03 | units.Myr) # speeding test up: + # print stars + # instance.evolve_model(end_time = 0.03 | units.Myr) # speeding test up: self.assertEqual(stars[0].mass, mass) self.assertAlmostRelativeEqual(stars[0].luminosity, 5841. | units.LSun, 1) instance.evolve_model() @@ -336,30 +337,30 @@ def test3(self): self.assertAlmostEqual(stars[0].mass, mass, 5) self.assertAlmostRelativeEqual(stars[0].luminosity, 5820.85 | units.LSun, 1) instance.stop() - + def slowtest4(self): print("Testing stellar type...") instance = self.new_instance_of_an_optional_code(MESA) if instance is None: print("MESA was not built. Skipping test.") return - instance.initialize_code() - instance.commit_parameters() - stars = Particles(1) - + instance.initialize_code() + instance.commit_parameters() + stars = Particles(1) + star = stars[0] star.mass = 5.0 | units.MSun - + instance.particles.add_particles(stars) instance.commit_particles() - + from_code_to_model = instance.particles.new_channel_to(stars) from_code_to_model.copy() - + previous_type = 15 | units.stellar_type results = [] current_time = 0 | units.Myr - + while current_time < (101 | units.Myr): if not star.stellar_type == previous_type: print((star.age, star.mass, star.stellar_type)) @@ -368,46 +369,46 @@ def slowtest4(self): instance.evolve_model() from_code_to_model.copy() current_time = star.age - + self.assertEqual(len(results), 4) - - times = ( - 0.0 | units.Myr, - 81.6 | units.Myr, - 99.9 | units.Myr, + + times = ( + 0.0 | units.Myr, + 81.6 | units.Myr, + 99.9 | units.Myr, 100.3 | units.Myr ) for result, expected in zip(results, times): self.assertAlmostEqual(result[0].value_in(units.Myr), expected.value_in(units.Myr), 1) - - masses = ( - 5.000 | units.MSun, - 5.000 | units.MSun, - 5.000 | units.MSun, + + masses = ( + 5.000 | units.MSun, + 5.000 | units.MSun, + 5.000 | units.MSun, 5.000 | units.MSun ) for result, expected in zip(results, masses): self.assertAlmostEqual(result[1].value_in(units.MSun), expected.value_in(units.MSun), 3) - + types = ( "Main Sequence star", "First Giant Branch", "Core Helium Burning", "First Asymptotic Giant Branch" ) - + for result, expected in zip(results, types): self.assertEqual(str(result[2]), expected) - + instance.stop() - + def test5(self): print("Testing evolve_model for particle set...") instance = self.new_instance_of_an_optional_code(MESA) masses = [0.5, 1.0] | units.MSun max_age = 0.6 | units.Myr - number_of_stars=len(masses) - stars = Particles(number_of_stars) + number_of_stars = len(masses) + stars = Particles(number_of_stars) stars.mass = masses instance.initialize_code() self.assertEqual(instance.parameters.max_age_stop_condition, 1e30 | units.Myr) @@ -416,20 +417,20 @@ def test5(self): instance.particles.add_particles(stars) instance.commit_particles() from_code_to_model = instance.particles.new_channel_to(stars) - instance.evolve_model(end_time = 0.5 | units.Myr) + instance.evolve_model(end_time=0.5 | units.Myr) from_code_to_model.copy() - #print stars + # print stars for i in range(number_of_stars): self.assertTrue(stars[i].age.value_in(units.Myr) >= 0.5) self.assertTrue(stars[i].age <= max_age) self.assertTrue(stars[i].mass <= masses[i]) self.assertTrue(stars[i].age+stars[i].time_step <= max_age) - - self.assertRaises(AmuseException, instance.evolve_model, end_time = 2*max_age, - expected_message = "Error when calling 'evolve_for' of a 'MESA', " + + self.assertRaises(AmuseException, instance.evolve_model, end_time=2*max_age, + expected_message="Error when calling 'evolve_for' of a 'MESA', " "errorcode is -12, error is 'Evolve terminated: Maximum age reached.'") instance.stop() - + def test6(self): print("Test for obtaining the stellar structure model") stars = Particles(2) @@ -439,15 +440,15 @@ def test6(self): print("MESA was not built. Skipping test.") return instance.initialize_code() - instance.commit_parameters() + instance.commit_parameters() instance.particles.add_particles(stars) instance.commit_particles() instance.evolve_model() self.assertEqual(instance.particles.get_number_of_zones(), [575, 2262]) self.assertEqual(len(instance.particles[0].get_mass_profile()), 575) self.assertAlmostEqual(instance.particles[0].get_mass_profile().sum(), 1.0) - self.assertRaises(AmuseException, instance.particles.get_mass_profile, - expected_message = "Querying mass profiles of more than one particle at a time is not supported.") + self.assertRaises(AmuseException, instance.particles.get_mass_profile, + expected_message="Querying mass profiles of more than one particle at a time is not supported.") print(instance.particles) self.assertEqual(len(instance.particles[1].get_density_profile()), 2262) self.assertIsOfOrder(instance.particles[0].get_radius_profile()[-1], 1.0 | units.RSun) @@ -457,13 +458,13 @@ def test6(self): delta_mass = instance.particles[0].get_mass_profile() * instance.particles[0].mass radius1 = instance.particles[0].get_radius_profile() radius2 = radius1[:-1] - radius2.prepend(0|units.m) + radius2.prepend(0 | units.m) delta_radius_cubed = (radius1**3 - radius2**3) - self.assertAlmostEqual(instance.particles[0].get_density_profile() / + self.assertAlmostEqual(instance.particles[0].get_density_profile() / (delta_mass/(4./3.*numpy.pi*delta_radius_cubed)), [1]*575, places=3) self.assertAlmostEqual(instance.particles[1].get_mu_profile(), [0.62]*2262 | units.amu, places=1) instance.stop() - + def test7(self): print("Test for obtaining the stellar composition structure") stars = Particles(1) @@ -473,16 +474,16 @@ def test7(self): print("MESA was not built. Skipping test.") return instance.initialize_code() - instance.commit_parameters() + instance.commit_parameters() instance.particles.add_particles(stars) instance.commit_particles() instance.evolve_model() - number_of_zones = instance.particles.get_number_of_zones()[0] + number_of_zones = instance.particles.get_number_of_zones()[0] number_of_species = instance.particles.get_number_of_species()[0] - composition = instance.particles[0].get_chemical_abundance_profiles() - species_names = instance.particles[0].get_names_of_species() - species_IDs = instance.particles[0].get_IDs_of_species() - species_masses = instance.particles[0].get_masses_of_species() + composition = instance.particles[0].get_chemical_abundance_profiles() + species_names = instance.particles[0].get_names_of_species() + species_IDs = instance.particles[0].get_IDs_of_species() + species_masses = instance.particles[0].get_masses_of_species() self.assertEqual(number_of_zones, 575) self.assertEqual(number_of_species, 8) self.assertEqual(len(species_names), number_of_species) @@ -490,14 +491,14 @@ def test7(self): self.assertEqual(len(composition[0]), number_of_zones) self.assertEqual(species_names, ['h1', 'he3', 'he4', 'c12', 'n14', 'o16', 'ne20', 'mg24']) self.assertEqual(species_IDs, [2, 5, 6, 38, 51, 69, 114, 168]) - self.assertAlmostEqual(species_masses, [1.0078250, 3.0160293, 4.0026032, 12.0, + self.assertAlmostEqual(species_masses, [1.0078250, 3.0160293, 4.0026032, 12.0, 14.0030740, 15.9949146, 19.9924401, 23.9850417] | units.amu, places=5) - self.assertAlmostEqual(composition[ :1,-1].sum(), 0.7) - self.assertAlmostEqual(composition[1:3,-1].sum(), (0.3) - instance.parameters.metallicity) - self.assertAlmostEqual(composition[3: ,-1].sum(), instance.parameters.metallicity) + self.assertAlmostEqual(composition[:1, -1].sum(), 0.7) + self.assertAlmostEqual(composition[1:3, -1].sum(), (0.3) - instance.parameters.metallicity) + self.assertAlmostEqual(composition[3:, -1].sum(), instance.parameters.metallicity) self.assertAlmostEqual(composition.sum(axis=0), [1.0]*number_of_zones) instance.stop() - + def slowtest8(self): print("Test for obtaining the stellar composition structure - evolved star with zero metalicity") stars = Particles(1) @@ -508,17 +509,17 @@ def slowtest8(self): return instance.initialize_code() instance.parameters.metallicity = 0.0 - instance.commit_parameters() + instance.commit_parameters() instance.particles.add_particles(stars) instance.commit_particles() instance.evolve_model(5.85 | units.Gyr) self.assertTrue(instance.particles[0].age >= 5.85 | units.Gyr) self.assertTrue(str(instance.particles[0].stellar_type) == "First Giant Branch") - number_of_zones = instance.particles.get_number_of_zones()[0] + number_of_zones = instance.particles.get_number_of_zones()[0] number_of_species = instance.particles.get_number_of_species()[0] - composition = instance.particles[0].get_chemical_abundance_profiles() - species_names = instance.particles[0].get_names_of_species() - species_IDs = instance.particles[0].get_IDs_of_species() + composition = instance.particles[0].get_chemical_abundance_profiles() + species_names = instance.particles[0].get_names_of_species() + species_IDs = instance.particles[0].get_IDs_of_species() self.assertEqual(number_of_zones, 578) self.assertEqual(number_of_species, 8) self.assertEqual(len(species_names), number_of_species) @@ -526,15 +527,15 @@ def slowtest8(self): self.assertEqual(len(composition[0]), number_of_zones) self.assertEqual(species_names, ['h1', 'he3', 'he4', 'c12', 'n14', 'o16', 'ne20', 'mg24']) self.assertEqual(species_IDs, [2, 5, 6, 38, 51, 69, 114, 168]) - self.assertAlmostEqual(composition[ :1,number_of_zones-1].sum(), 0.76 | units.none) - self.assertAlmostEqual(composition[1:3,number_of_zones-1].sum(), 0.24 | units.none) - self.assertAlmostEqual(composition[3: ,number_of_zones-1].sum(), 0.00 | units.none) + self.assertAlmostEqual(composition[:1, number_of_zones-1].sum(), 0.76 | units.none) + self.assertAlmostEqual(composition[1:3, number_of_zones-1].sum(), 0.24 | units.none) + self.assertAlmostEqual(composition[3:, number_of_zones-1].sum(), 0.00 | units.none) self.assertAlmostEqual(composition.sum(axis=0), [1.0]*number_of_zones | units.none) - self.assertAlmostEqual(composition[ :1,0].sum(), 0.00 | units.none) - self.assertAlmostEqual(composition[1:3,0].sum(), 1.00 | units.none) - self.assertAlmostEqual(composition[3: ,0].sum(), 0.00 | units.none) + self.assertAlmostEqual(composition[:1, 0].sum(), 0.00 | units.none) + self.assertAlmostEqual(composition[1:3, 0].sum(), 1.00 | units.none) + self.assertAlmostEqual(composition[3:, 0].sum(), 0.00 | units.none) instance.stop() - + def test9(self): print("Test for changing the stellar structure model") star = Particles(1) @@ -544,52 +545,52 @@ def test9(self): print("MESA was not built. Skipping test.") return instance.initialize_code() - instance.commit_parameters() + instance.commit_parameters() instance.particles.add_particles(star) instance.commit_particles() instance.evolve_model() density_profile = instance.particles[0].get_density_profile() - - self.assertRaises(AmuseException, instance.particles[0].set_density_profile, density_profile[2:], - expected_message = "The length of the supplied vector (573) does not match the number of " + + self.assertRaises(AmuseException, instance.particles[0].set_density_profile, density_profile[2:], + expected_message="The length of the supplied vector (573) does not match the number of " "mesh zones of the star (575).") - + mass_factor = 1.1 instance.particles[0].set_density_profile(mass_factor*density_profile) self.assertAlmostRelativeEqual(instance.particles[0].get_density_profile(), density_profile*mass_factor, places=10) instance.particles.mass *= mass_factor instance.evolve_model() - + outer_radius = instance.particles[0].get_radius_profile() inner_radius = outer_radius[:-1] - inner_radius.prepend(0|units.m) + inner_radius.prepend(0 | units.m) delta_radius_cubed = (outer_radius**3 - inner_radius**3) integrated_mass = (4./3.*numpy.pi*delta_radius_cubed*instance.particles[0].get_density_profile()).sum() - self.assertAlmostRelativeEqual(integrated_mass, star.mass*mass_factor, places = 3) + self.assertAlmostRelativeEqual(integrated_mass, star.mass*mass_factor, places=3) instance.stop() - + def test10(self): print("Test for changing the stellar composition") star = Particles(1) star.mass = 1.0 | units.MSun - instance = self.new_instance_of_an_optional_code(MESA)#, redirection = 'none') + instance = self.new_instance_of_an_optional_code(MESA) # , redirection = 'none') if instance is None: print("MESA was not built. Skipping test.") return instance.initialize_code() - instance.commit_parameters() + instance.commit_parameters() instance.particles.add_particles(star) instance.commit_particles() instance.evolve_model(0.3 | units.Myr) - + composition = instance.particles[0].get_chemical_abundance_profiles() - k_surface = -1 # index to the outer mesh cell (surface) - - self.assertAlmostEqual(composition[ :1, k_surface].sum(), 0.7) + k_surface = -1 # index to the outer mesh cell (surface) + + self.assertAlmostEqual(composition[:1, k_surface].sum(), 0.7) self.assertAlmostEqual(composition[1:3, k_surface].sum(), (0.3) - instance.parameters.metallicity) - self.assertAlmostEqual(composition[3: , k_surface].sum(), instance.parameters.metallicity) - + self.assertAlmostEqual(composition[3:, k_surface].sum(), instance.parameters.metallicity) + # Gradually and consistently increase helium and decrease hydrogen abundances until reversed for alpha in [0.3, 1.0, -0.5, -0.125]: h1_profile = composition[0] * 1 @@ -600,17 +601,17 @@ def test10(self): instance.evolve_model() instance.evolve_model() composition = instance.particles[0].get_chemical_abundance_profiles() - - self.assertAlmostEqual(composition[ :2, k_surface].sum(), (0.3) - instance.parameters.metallicity) + + self.assertAlmostEqual(composition[:2, k_surface].sum(), (0.3) - instance.parameters.metallicity) self.assertAlmostEqual(composition[2:3, k_surface].sum(), 0.7) - self.assertAlmostEqual(composition[3: , k_surface].sum(), instance.parameters.metallicity) + self.assertAlmostEqual(composition[3:, k_surface].sum(), instance.parameters.metallicity) self.assertAlmostEqual(composition.sum(axis=0), 1.0) - - self.assertRaises(AmuseException, instance.particles[0].set_chemical_abundance_profiles, composition[:7], - expected_message = "The length of the supplied vector (7) does not match the number of " + + self.assertRaises(AmuseException, instance.particles[0].set_chemical_abundance_profiles, composition[:7], + expected_message="The length of the supplied vector (7) does not match the number of " "chemical species of the star (8).") instance.stop() - + def test11(self): print("Test evolve_model optional arguments: end_time and keep_synchronous") stars = Particles(3) @@ -620,33 +621,33 @@ def test11(self): print("MESA was not built. Skipping test.") return instance.initialize_code() - instance.commit_parameters() + instance.commit_parameters() instance.particles.add_particles(stars) instance.commit_particles() - + self.assertAlmostEqual(instance.particles.age, [0.0, 0.0, 0.0] | units.yr) self.assertAlmostEqual(instance.particles.time_step, [100000.0, 17677.6695, 6415.0029] | units.yr, 3) - + print("evolve_model without arguments: use shared timestep = 0.99*min(particles.time_step)") instance.evolve_model() self.assertAlmostEqual(instance.particles.age, [100000.0, 17677.6695, 6415.0029] | units.yr, 3) self.assertAlmostRelativeEquals(instance.particles.time_step, 1.2*([100000.0, 17677.6695, 6415.0029] | units.yr), 6) self.assertAlmostEqual(instance.model_time, 0.99 * 6415.0029 | units.yr, 3) - + print("evolve_model with end_time: take timesteps, until end_time is reached exactly") instance.evolve_model(15000 | units.yr) self.assertAlmostEqual(instance.particles.age, [100000.0, 17677.6695, 6415.0029*(1+1.2+1.44)] | units.yr, 3) self.assertAlmostRelativeEquals(instance.particles.time_step, 1.2*([100000.0, 17677.6695, 1.44*6415.0029] | units.yr), 4) self.assertAlmostEqual(instance.model_time, 15000.0 | units.yr, 3) - + print("evolve_model with keep_synchronous: use non-shared timestep, particle ages will typically diverge") - instance.evolve_model(keep_synchronous = False) + instance.evolve_model(keep_synchronous=False) self.assertAlmostRelativeEquals(instance.particles.age, ([100000.0, 17677.6695, 6415.0029*(1+1.2+1.44)] | units.yr) + 1.2*([100000.0, 17677.6695, 1.44*6415.0029] | units.yr), 5) self.assertAlmostRelativeEquals(instance.particles.time_step, 1.44*([100000.0, 17677.6695, 1.44*6415.0029] | units.yr), 4) - self.assertAlmostEqual(instance.model_time, 15000.0 | units.yr, 3) # Unchanged! + self.assertAlmostEqual(instance.model_time, 15000.0 | units.yr, 3) # Unchanged! instance.stop() - + def test12(self): print("Test for importing new stellar models") star = Particles(1) @@ -657,48 +658,48 @@ def test12(self): return instance.initialize_code() instance.parameters.stabilize_new_stellar_model_flag = False - instance.commit_parameters() + instance.commit_parameters() instance.particles.add_particles(star) instance.commit_particles() instance.evolve_model() - + number_of_zones = instance.particles[0].get_number_of_zones() - composition = instance.particles[0].get_chemical_abundance_profiles(number_of_zones = number_of_zones) + composition = instance.particles[0].get_chemical_abundance_profiles(number_of_zones=number_of_zones) instance.new_particle_from_model(dict( - mass = instance.particles[0].get_cumulative_mass_profile(number_of_zones = number_of_zones) * instance.particles[0].mass, - radius = instance.particles[0].get_radius_profile(number_of_zones = number_of_zones), - rho = instance.particles[0].get_density_profile(number_of_zones = number_of_zones), - temperature = instance.particles[0].get_temperature_profile(number_of_zones = number_of_zones), - luminosity = instance.particles[0].get_luminosity_profile(number_of_zones = number_of_zones), - X_H = composition[0], - X_He = composition[1] + composition[2], - X_C = composition[3], - X_N = composition[4], - X_O = composition[5], - X_Ne = composition[6], - X_Mg = composition[7], - X_Si = composition[7]*0.0, - X_Fe = composition[7]*0.0), 10.0 | units.Myr) + mass=instance.particles[0].get_cumulative_mass_profile(number_of_zones=number_of_zones) * instance.particles[0].mass, + radius=instance.particles[0].get_radius_profile(number_of_zones=number_of_zones), + rho=instance.particles[0].get_density_profile(number_of_zones=number_of_zones), + temperature=instance.particles[0].get_temperature_profile(number_of_zones=number_of_zones), + luminosity=instance.particles[0].get_luminosity_profile(number_of_zones=number_of_zones), + X_H=composition[0], + X_He=composition[1] + composition[2], + X_C=composition[3], + X_N=composition[4], + X_O=composition[5], + X_Ne=composition[6], + X_Mg=composition[7], + X_Si=composition[7]*0.0, + X_Fe=composition[7]*0.0), 10.0 | units.Myr) self.assertEqual(len(instance.particles), 2) self.assertEqual(len(instance.imported_stars), 1) self.assertEqual(instance.imported_stars[0].get_number_of_zones(), number_of_zones) self.assertIsOfOrder(instance.imported_stars[0].get_radius_profile()[-1], 1.0 | units.RSun) self.assertIsOfOrder(instance.imported_stars[0].get_temperature_profile()[0], 1.0e7 | units.K) self.assertIsOfOrder(instance.imported_stars[0].get_pressure_profile()[0], 1.0e17 | units.barye) - self.assertAlmostEqual(instance.imported_stars[0].get_mass_profile(), + self.assertAlmostEqual(instance.imported_stars[0].get_mass_profile(), instance.native_stars[0].get_mass_profile()) - self.assertAlmostRelativeEqual(instance.imported_stars[0].get_pressure_profile(), - instance.native_stars[0].get_pressure_profile(),7) - self.assertAlmostEqual(instance.imported_stars[0].get_radius_profile(), + self.assertAlmostRelativeEqual(instance.imported_stars[0].get_pressure_profile(), + instance.native_stars[0].get_pressure_profile(), 7) + self.assertAlmostEqual(instance.imported_stars[0].get_radius_profile(), instance.native_stars[0].get_radius_profile()) - self.assertAlmostEqual(instance.imported_stars[0].get_temperature_profile(), + self.assertAlmostEqual(instance.imported_stars[0].get_temperature_profile(), instance.native_stars[0].get_temperature_profile()) - + print(instance.particles) - instance.evolve_model(keep_synchronous = False) + instance.evolve_model(keep_synchronous=False) print(instance.particles) instance.stop() - + def slowtest13(self): print("Testing MESA wind parameters...") stars = Particles(9) @@ -715,7 +716,7 @@ def slowtest13(self): instance.commit_parameters() for wind_scheme in [0, 1, 2, 3, 4]: instance.parameters.RGB_wind_scheme = wind_scheme - instance.recommit_parameters() + instance.recommit_parameters() instance.particles.add_particle(stars[wind_scheme]) instance.parameters.reimers_wind_efficiency *= 2.0 instance.parameters.blocker_wind_efficiency *= 2.0 @@ -723,19 +724,19 @@ def slowtest13(self): instance.parameters.dutch_wind_efficiency *= 2.0 for wind_scheme in [1, 2, 3, 4]: instance.parameters.RGB_wind_scheme = wind_scheme - instance.recommit_parameters() + instance.recommit_parameters() instance.particles.add_particle(stars[wind_scheme+4]) instance.commit_particles() - instance.evolve_model(keep_synchronous = False) + instance.evolve_model(keep_synchronous=False) from_code_to_model = instance.particles.new_channel_to(stars) from_code_to_model.copy() print(stars) self.assertAlmostEqual(stars[0].wind, 0.0 | units.MSun / units.yr) - self.assertAlmostRelativeEqual(stars[1:5].wind, - [4.59318475897e-10, 5.20742729636e-11, 1.05565558121e-09, 3.62519254311e-09] | units.MSun / units.yr, places = 7) - self.assertAlmostRelativeEqual(stars[5:].wind, 2.0 * stars[1:5].wind, places = 7) + self.assertAlmostRelativeEqual(stars[1:5].wind, + [4.59318475897e-10, 5.20742729636e-11, 1.05565558121e-09, 3.62519254311e-09] | units.MSun / units.yr, places=7) + self.assertAlmostRelativeEqual(stars[5:].wind, 2.0 * stars[1:5].wind, places=7) instance.stop() - + def test14(self): print("Testing MESA wind parameters... (short version of slowtest13)") stars = Particles(3) @@ -754,14 +755,14 @@ def test14(self): instance.recommit_parameters() instance.particles.add_particle(stars[i+1]) instance.commit_particles() - instance.evolve_model(keep_synchronous = False) + instance.evolve_model(keep_synchronous=False) from_code_to_model = instance.particles.new_channel_to(stars) from_code_to_model.copy() self.assertAlmostEqual(stars[0].wind, 0.0 | units.MSun / units.yr) - self.assertAlmostRelativeEqual(stars[1].wind, 4.59318475897e-10 | units.MSun / units.yr, places = 1) - self.assertAlmostRelativeEqual(stars[2].wind, 2.0 * stars[1].wind, places = 7) + self.assertAlmostRelativeEqual(stars[1].wind, 4.59318475897e-10 | units.MSun / units.yr, places=1) + self.assertAlmostRelativeEqual(stars[2].wind, 2.0 * stars[1].wind, places=7) instance.stop() - + def test15(self): print("Testing MESA states") stars = Particles(2) @@ -770,7 +771,7 @@ def test15(self): if instance is None: print("MESA was not built. Skipping test.") return - + print("First do everything manually:", end=' ') self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') instance.initialize_code() @@ -785,7 +786,7 @@ def test15(self): instance.stop() print("ok") - print("initialize_code(), commit_parameters(), (re)commit_particles(), " \ + print("initialize_code(), commit_parameters(), (re)commit_particles(), " "and cleanup_code() should be called automatically:", end=' ') instance = MESA() self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') @@ -803,58 +804,57 @@ def test15(self): instance.stop() self.assertEqual(instance.get_name_of_current_state(), 'STOPPED') print("ok") - + def test16(self): print("Testing basic operations: evolve_one_step and evolve_for") stars = Particles(2) stars.mass = 1.0 | units.MSun - instance = self.new_instance_of_an_optional_code(MESA)#, redirection = 'none') + instance = self.new_instance_of_an_optional_code(MESA) # , redirection = 'none') if instance is None: print("MESA was not built. Skipping test.") return - + se_stars = instance.particles.add_particles(stars) - + for i in range(3): se_stars[0].evolve_one_step() self.assertAlmostEqual(se_stars.age, [364000.0, 0] | units.yr) - + se_stars[1].evolve_for(se_stars[0].age) self.assertAlmostRelativeEqual(se_stars[0].age, se_stars[1].age) self.assertAlmostRelativeEqual(se_stars[0].luminosity, se_stars[1].luminosity, 2) self.assertAlmostRelativeEqual(se_stars[0].radius, se_stars[1].radius, 2) self.assertAlmostRelativeEqual(se_stars[0].temperature, se_stars[1].temperature, 2) instance.stop() - + def test17(self): print("MESA validation") - + mesa_src_path = os.path.join(os.path.dirname(sys.modules[MESA.__module__].__file__), 'src', 'mesa') mesa_star_path = os.path.join(mesa_src_path, 'star', 'test', 'star') - + if not os.path.exists(mesa_star_path) or not os.access(mesa_star_path, os.X_OK): self.skip("no mesa executable in binary distribution, test cannot run") - - number_of_steps = 11#4 + + number_of_steps = 11 # 4 star = Particle() star.mass = 1.0 | units.MSun - + testpath = get_path_to_results() outputfile_name = os.path.join(testpath, "mesa_output") - - instance = self.new_instance_of_an_optional_code(MESA, redirection = 'file', redirect_file = outputfile_name) + + instance = self.new_instance_of_an_optional_code(MESA, redirection='file', redirect_file=outputfile_name) se_star = instance.particles.add_particle(star) for i in range(number_of_steps): se_star.evolve_one_step() instance.stop() - + rfile = open(outputfile_name, 'r') amuse_output = rfile.read() rfile.close() - - - #generate the inlist for the (stand-alone) MESA star run: - instance = self.new_instance_of_an_optional_code(MESA, redirection = 'null') + + # generate the inlist for the (stand-alone) MESA star run: + instance = self.new_instance_of_an_optional_code(MESA, redirection='null') with open(instance.default_path_to_inlist, 'r') as default_inlist: with open(os.path.join(testpath, 'inlist'), 'w') as test_inlist: for one_line in default_inlist.readlines(): @@ -867,46 +867,46 @@ def test17(self): else: test_inlist.write(one_line) instance.stop() - - (stdout, stderr) = Popen([mesa_star_path], cwd = testpath, stdin = PIPE, stdout = PIPE, stderr = PIPE).communicate() + + (stdout, stderr) = Popen([mesa_star_path], cwd=testpath, stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate() self.assertEqual(stderr, b"") for i, line in enumerate(stdout.decode("utf-8").splitlines()): - #print i, line, line in amuse_output + # print i, line, line in amuse_output if i == 52 + 4 * number_of_steps + 8 * (number_of_steps//10) + (3 if number_of_steps > 55 else 0): self.assertEqual(line, "stop because model_number >= max_model_number") break else: self.assertTrue(line in amuse_output) - + def test18(self): print("Testing MESA mass_change (User-specified wind/accretion)") instance = self.new_instance_of_an_optional_code(MESA) - instance.parameters.RGB_wind_scheme = 0 # must be turned off for user-specified rates - instance.parameters.AGB_wind_scheme = 0 # must be turned off for user-specified rates - - star = instance.particles.add_particle(Particle(mass=1|units.MSun)) - star.mass_change = 1.0e-8 | units.MSun / units.yr # positive -> accretion + instance.parameters.RGB_wind_scheme = 0 # must be turned off for user-specified rates + instance.parameters.AGB_wind_scheme = 0 # must be turned off for user-specified rates + + star = instance.particles.add_particle(Particle(mass=1 | units.MSun)) + star.mass_change = 1.0e-8 | units.MSun / units.yr # positive -> accretion star.evolve_one_step() - + self.assertAlmostRelativeEqual(star.mass_change, 1.0e-8 | units.MSun / units.yr) self.assertAlmostRelativeEqual(star.wind, -1.0e-8 | units.MSun / units.yr, 3) self.assertAlmostRelativeEqual(star.age, 1.0e5 | units.yr) self.assertAlmostRelativeEqual(star.mass, 1.0010 | units.MSun) - - star.mass_change = -1.0e-8 | units.MSun / units.yr # negative -> wind + + star.mass_change = -1.0e-8 | units.MSun / units.yr # negative -> wind star.evolve_one_step() - + self.assertAlmostRelativeEqual(star.mass_change, -1.0e-8 | units.MSun / units.yr) self.assertAlmostRelativeEqual(star.wind, 1.0e-8 | units.MSun / units.yr, 3) self.assertAlmostRelativeEqual(star.age, 1.8e5 | units.yr) self.assertAlmostRelativeEqual(star.mass, 1.0002 | units.MSun) print(star.as_set()) instance.stop() - + def slowtest19a(self): print("Testing MESA core mass") instance = self.new_instance_of_an_optional_code(MESA) - star = instance.particles.add_particle(Particle(mass=3|units.MSun)) + star = instance.particles.add_particle(Particle(mass=3 | units.MSun)) star.evolve_for(330 | units.Myr) for i in range(10): star.evolve_for(10 | units.Myr) @@ -915,26 +915,26 @@ def slowtest19a(self): print(h_poor_mass, star.core_mass) self.assertAlmostEqual(star.core_mass, h_poor_mass, 2) instance.stop() - + def test19b(self): print("Testing MESA core mass (short version of slowtest19a)") instance = self.new_instance_of_an_optional_code(MESA) - star = instance.particles.add_particle(Particle(mass=3|units.MSun)) + star = instance.particles.add_particle(Particle(mass=3 | units.MSun)) star.evolve_one_step() index = numpy.searchsorted(star.get_chemical_abundance_profiles(number_of_species=1)[0], 1.0e-4) h_poor_mass = EnclosedMassInterpolator(radii=star.get_radius_profile(), densities=star.get_density_profile()).enclosed_mass[index].as_quantity_in(units.MSun) self.assertAlmostEqual(star.core_mass, h_poor_mass, 2) instance.stop() - + def test20(self): print("Testing MESA pre-main-sequence star") instance = self.new_instance_of_an_optional_code(MESA) - star = instance.pre_ms_stars.add_particle(Particle(mass=1.0|units.MSun)) - + star = instance.pre_ms_stars.add_particle(Particle(mass=1.0 | units.MSun)) + self.assertAlmostEqual(star.time_step, 1.0e-3 | units.yr) star.evolve_one_step() self.assertAlmostEqual(star.age, 1.0e-3 | units.yr) - + instance.evolve_model(1.0 | units.yr) self.assertEqual(star.stellar_type, 17 | units.stellar_type) self.assertEqual(str(star.stellar_type), "Pre-main-sequence Star") @@ -943,19 +943,19 @@ def test20(self): self.assertTrue(star.luminosity > 10 | units.LSun) self.assertTrue(star.radius > 2 | units.RSun) instance.stop() - + def slowtest21(self): print("Testing MESA calculate_core_mass") instance = self.new_instance_of_an_optional_code(MESA) - star = instance.particles.add_particle(Particle(mass=40|units.MSun)) - instance.evolve_model(4.56|units.Myr) + star = instance.particles.add_particle(Particle(mass=40 | units.MSun)) + instance.evolve_model(4.56 | units.Myr) total_core_mass = star.calculate_core_mass() self.assertAlmostRelativeEqual(star.core_mass, total_core_mass, 2) self.assertTrue(star.calculate_core_mass(core_H_abundance_limit=1.0e-2) > total_core_mass) self.assertEqual(star.calculate_core_mass(core_H_abundance_limit=1.0e-4), total_core_mass) self.assertTrue(star.calculate_core_mass(core_H_abundance_limit=1.0e-6) < total_core_mass) self.assertAlmostRelativeEqual(star.calculate_core_mass(core_H_abundance_limit=0.8), star.mass, 2) - + h1_core_mass = star.calculate_core_mass(species=["h1"]) he3_core_mass = star.calculate_core_mass(species=["he3"]) he4_core_mass = star.calculate_core_mass(species=["he4"]) @@ -972,26 +972,26 @@ def slowtest21(self): self.assertAlmostRelativeEqual(total_core_mass, he4_core_mass, 1) self.assertAlmostRelativeEqual(total_core_mass, he4_core_mass + metal_core_mass, 4) self.assertAlmostRelativeEqual(total_core_mass, he4_core_mass + metal_core_mass + h1_core_mass, 7) - self.assertAlmostRelativeEqual(metal_core_mass, + self.assertAlmostRelativeEqual(metal_core_mass, c12_core_mass + n14_core_mass + o16_core_mass + ne20_core_mass + mg24_core_mass, 7) self.assertAlmostEqual(he3_core_mass, 0 | units.MSun) - + def test22(self): print("Testing MESA calculate_core_mass (short version of slowtest21)") instance = self.new_instance_of_an_optional_code(MESA) - star = instance.particles.add_particle(Particle(mass=1|units.MSun)) - instance.evolve_model(0.3|units.Gyr) # VERY short, for test speed up + star = instance.particles.add_particle(Particle(mass=1 | units.MSun)) + instance.evolve_model(0.3 | units.Gyr) # VERY short, for test speed up central_hydrogen_abundance = star.get_chemical_abundance_profiles()[0][0] - self.assertTrue(central_hydrogen_abundance < 0.68) # some hydrogen is burned - self.assertTrue(central_hydrogen_abundance > 0.67) # ... but not that much yet + self.assertTrue(central_hydrogen_abundance < 0.68) # some hydrogen is burned + self.assertTrue(central_hydrogen_abundance > 0.67) # ... but not that much yet self.assertEqual(star.calculate_core_mass(core_H_abundance_limit=0.67), 0 | units.MSun) self.assertAlmostEqual(star.calculate_core_mass(core_H_abundance_limit=0.70), 1 | units.MSun, 3) - + # For test speed up, we use a weird core_H_abundance_limit to define the "hydrogen exhausted core" limit = 0.68 expected_core_mass = 0.01786033709 | units.MSun self.assertAlmostEqual(star.calculate_core_mass(core_H_abundance_limit=limit), expected_core_mass, 3) - + h1_core_mass = star.calculate_core_mass(species=["h1"], core_H_abundance_limit=limit) he3_core_mass = star.calculate_core_mass(species=["he3"], core_H_abundance_limit=limit) he4_core_mass = star.calculate_core_mass(species=["he4"], core_H_abundance_limit=limit) @@ -1006,23 +1006,23 @@ def test22(self): self.assertAlmostRelativeEqual(he4_core_mass, expected_core_mass*0.30, 2) self.assertAlmostRelativeEqual(metal_core_mass, expected_core_mass*0.02, 1) self.assertAlmostRelativeEqual(expected_core_mass, he4_core_mass + he3_core_mass + metal_core_mass + h1_core_mass, 7) - self.assertAlmostRelativeEqual(metal_core_mass, + self.assertAlmostRelativeEqual(metal_core_mass, c12_core_mass + n14_core_mass + o16_core_mass + ne20_core_mass + mg24_core_mass, 7) self.assertAlmostEqual(he3_core_mass, 0 | units.MSun, 5) - + def test23(self): print("Testing MESA central_temperature and central_density") instance = self.new_instance_of_an_optional_code(MESA) - stars = instance.particles.add_particles(Particles(mass=[0.1, 1, 10]|units.MSun)) + stars = instance.particles.add_particles(Particles(mass=[0.1, 1, 10] | units.MSun)) self.assertIsOfOrder(stars.central_temperature, [4e6, 13e6, 31e6] | units.K) self.assertIsOfOrder(stars.central_density, [400, 77, 9] | units.g * units.cm**-3) instance.stop() - + def test24(self): print("Testing MESA calculate_helium_exhausted_core_mass") instance = self.new_instance_of_an_optional_code(MESA) - star = instance.particles.add_particle(Particle(mass=2|units.MSun)) - + star = instance.particles.add_particle(Particle(mass=2 | units.MSun)) + composition = star.get_chemical_abundance_profiles() # Mimic hydrogen exhausted core: composition[2, :100] = composition[2, :100] + composition[0, :100] @@ -1034,17 +1034,17 @@ def test24(self): composition[1:3, :50] = 0 composition[4, :50] = 0 star.set_chemical_abundance_profiles(composition) - - self.assertAlmostRelativeEqual(star.calculate_core_mass(), + + self.assertAlmostRelativeEqual(star.calculate_core_mass(), star.mass * star.get_cumulative_mass_profile()[100], 1) - self.assertAlmostRelativeEqual(star.calculate_helium_exhausted_core_mass(), + self.assertAlmostRelativeEqual(star.calculate_helium_exhausted_core_mass(), star.mass * star.get_cumulative_mass_profile()[50], 1) - + core_mass = star.calculate_helium_exhausted_core_mass(split_species=False) core_mass_by_species = star.calculate_helium_exhausted_core_mass(split_species=True) carbon_mass_in_core, oxygen_mass_in_core = star.calculate_helium_exhausted_core_mass( split_species=True, species=["c12", "o16"]) - + self.assertEqual(len(core_mass_by_species), len(star.get_names_of_species())) instance.stop() self.assertAlmostRelativeEqual(core_mass, core_mass_by_species.sum()) @@ -1052,18 +1052,18 @@ def test24(self): self.assertEqual(core_mass_by_species[4], 0 | units.MSun) self.assertEqual(core_mass_by_species[3], carbon_mass_in_core) self.assertEqual(core_mass_by_species[5], oxygen_mass_in_core) - + def test25(self): print("Testing MESA accretion") instance = self.new_instance_of_an_optional_code(MESA) instance.parameters.RGB_wind_scheme = 0 instance.parameters.AGB_wind_scheme = 0 - star = instance.particles.add_particle(Particle(mass=2|units.MSun)) - + star = instance.particles.add_particle(Particle(mass=2 | units.MSun)) + self.assertEqual(star.get_accrete_same_as_surface(), 1) star.set_accrete_same_as_surface(0) self.assertEqual(star.get_accrete_same_as_surface(), 0) - + self.assertEqual(star.get_accrete_composition_non_metals(), [-1.0, -1.0, -1.0, -1.0]) self.assertEqual(star.get_accrete_composition_metals_identifier(), -1) self.assertEqual(star.get_accrete_composition_metals(), [-1.0]*28) @@ -1072,12 +1072,12 @@ def test25(self): print("and 25% iron") composition_metals = [0]*23 + [1.0] + [0]*4 star.set_accrete_composition_non_metals(*composition_light) - star.set_accrete_composition_metals_identifier(0) # i.e. specified below: + star.set_accrete_composition_metals_identifier(0) # i.e. specified below: star.set_accrete_composition_metals(*composition_metals) self.assertEqual(star.get_accrete_composition_non_metals(), composition_light) self.assertEqual(star.get_accrete_composition_metals_identifier(), 0) self.assertEqual(star.get_accrete_composition_metals(), composition_metals) - + star.mass_change = 1.0e-8 | units.MSun / units.yr star.time_step = 0.1 | units.yr instance.evolve_model(1 | units.yr) @@ -1087,6 +1087,3 @@ def test25(self): print("so have been added to {0} and {1}".format(species[0], species[-1])) self.assertEqual(composition[:, -1], [0.75, 0, 0, 0, 0, 0, 0, 0.25]) instance.stop() - - - diff --git a/src/amuse/test/suite/codes_tests/test_mi6.py b/src/amuse/test/suite/codes_tests/test_mi6.py index c0615e6962..14fa042e54 100644 --- a/src/amuse/test/suite/codes_tests/test_mi6.py +++ b/src/amuse/test/suite/codes_tests/test_mi6.py @@ -11,8 +11,9 @@ default_options = dict() + class TestMI6Interface(TestWithMPI): - + def test1(self): print("Test MI6Interface initialization") instance = MI6Interface(**default_options) @@ -20,121 +21,121 @@ def test1(self): self.assertEqual(0, instance.commit_parameters()) self.assertEqual(0, instance.cleanup_code()) instance.stop() - + def test2(self): print("Test MI6Interface new_particle / get_state") instance = MI6Interface(**default_options) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - - id, error = instance.new_particle(mass = 11.0, radius = 2.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) + + id, error = instance.new_particle(mass=11.0, radius=2.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) self.assertEqual(0, error) self.assertEqual(1, id) - id, error = instance.new_particle(mass = 21.0, radius = 5.0, x = 10.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) + id, error = instance.new_particle(mass=21.0, radius=5.0, x=10.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) self.assertEqual(0, error) self.assertEqual(2, id) self.assertEqual(0, instance.commit_particles()) - + retrieved_state1 = instance.get_state(1) retrieved_state2 = instance.get_state(2) self.assertEqual(0, retrieved_state1['__result']) self.assertEqual(0, retrieved_state2['__result']) self.assertEqual(11.0, retrieved_state1['mass']) self.assertEqual(21.0, retrieved_state2['mass']) - self.assertEqual( 0.0, retrieved_state1['x']) + self.assertEqual(0.0, retrieved_state1['x']) self.assertEqual(10.0, retrieved_state2['x']) - + self.assertEqual(0, instance.cleanup_code()) instance.stop() - + def xtest3(self): print("Test MI6Interface get_index_of_first_particle, get_index_of_next_particle") instance = MI6Interface(**default_options) instance.initialize_code() instance.commit_parameters() for i in [1, 2, 3]: - result = instance.new_particle(mass = i, radius = 1.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) + result = instance.new_particle(mass=i, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) self.assertEqual(i, result['index_of_the_particle']) - + instance.commit_particles() self.assertEqual(1, instance.get_index_of_first_particle()['index_of_the_particle']) - self.assertEqual(2, instance.get_index_of_next_particle(1)['index_of_the_next_particle']) + self.assertEqual(2, instance.get_index_of_next_particle(1)['index_of_the_next_particle']) self.assertEqual(3, instance.get_index_of_next_particle(2)['index_of_the_next_particle']) - + instance.delete_particle(1) - + self.assertEqual(2, instance.get_number_of_particles()['number_of_particles']) - - #the deletion does a swap, so 3 is copied to 1, (overwriting old 1 and treesize -> treesize-1 + + # the deletion does a swap, so 3 is copied to 1, (overwriting old 1 and treesize -> treesize-1 self.assertEqual(3, instance.get_index_of_first_particle()['index_of_the_particle']) - + self.assertEqual(1, instance.get_index_of_next_particle(2)['__result']) instance.cleanup_code() instance.stop() - + def test4(self): print("Test MI6Interface particle property getters/setters") instance = MI6Interface(**default_options) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) self.assertEqual([1, 0], list(instance.new_particle(0.01, 1, 0, 0, 0, 1, 0, 0.1).values())) - self.assertEqual([2, 0], list(instance.new_particle(0.02, -1, 0, 0, 0,-1, 0, 0.1).values())) - self.assertEqual(-3, instance.get_mass(1)['__result']) # Have to commit first + self.assertEqual([2, 0], list(instance.new_particle(0.02, -1, 0, 0, 0, -1, 0, 0.1).values())) + self.assertEqual(-3, instance.get_mass(1)['__result']) # Have to commit first self.assertEqual(0, instance.commit_particles()) - + # getters mass, result = instance.get_mass(1) self.assertAlmostEqual(0.01, mass) - self.assertEqual(0,result) + self.assertEqual(0, result) radius, result = instance.get_radius(2) self.assertAlmostEqual(0.1, radius) - self.assertEqual(0,result) - self.assertEqual(-3, instance.get_mass(3)['__result']) # Particle not found - self.assertEqual([ 1, 0, 0, 0], list(instance.get_position(1).values())) + self.assertEqual(0, result) + self.assertEqual(-3, instance.get_mass(3)['__result']) # Particle not found + self.assertEqual([1, 0, 0, 0], list(instance.get_position(1).values())) self.assertEqual([-1, 0, 0, 0], list(instance.get_position(2).values())) - self.assertEqual([ 0, 1, 0, 0], list(instance.get_velocity(1).values())) - self.assertEqual([ 0,-1, 0, 0], list(instance.get_velocity(2).values())) - + self.assertEqual([0, 1, 0, 0], list(instance.get_velocity(1).values())) + self.assertEqual([0, -1, 0, 0], list(instance.get_velocity(2).values())) + # setters - self.assertEqual(0, instance.set_state(1, 0.01, 1,2,3, 4,5,6, 0.1)) - self.assertEqual([0.01, 1.0,2.0,3.0, 4.0,5.0,6.0, 0.1, 0], list(instance.get_state(1).values())) + self.assertEqual(0, instance.set_state(1, 0.01, 1, 2, 3, 4, 5, 6, 0.1)) + self.assertEqual([0.01, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.1, 0], list(instance.get_state(1).values())) self.assertEqual(0, instance.set_mass(1, 0.02)) - self.assertEqual([0.02, 1.0,2.0,3.0, 4.0,5.0,6.0, 0.1, 0], list(instance.get_state(1).values())) + self.assertEqual([0.02, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.1, 0], list(instance.get_state(1).values())) self.assertEqual(0, instance.set_radius(1, 0.2)) - self.assertEqual([0.02, 1.0,2.0,3.0, 4.0,5.0,6.0, 0.2, 0], list(instance.get_state(1).values())) - self.assertEqual(0, instance.set_position(1, 10,20,30)) - self.assertEqual([0.02, 10.0,20.0,30.0, 4.0,5.0,6.0, 0.2, 0], list(instance.get_state(1).values())) - self.assertEqual(0, instance.set_velocity(1, 40,50,60)) - self.assertEqual([0.02, 10.0,20.0,30.0, 40.0,50.0,60.0, 0.2, 0], list(instance.get_state(1).values())) + self.assertEqual([0.02, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.2, 0], list(instance.get_state(1).values())) + self.assertEqual(0, instance.set_position(1, 10, 20, 30)) + self.assertEqual([0.02, 10.0, 20.0, 30.0, 4.0, 5.0, 6.0, 0.2, 0], list(instance.get_state(1).values())) + self.assertEqual(0, instance.set_velocity(1, 40, 50, 60)) + self.assertEqual([0.02, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 0.2, 0], list(instance.get_state(1).values())) self.assertEqual(0, instance.cleanup_code()) instance.stop() - + def test5(self): print("Test MI6Interface parameters") instance = MI6Interface(**default_options) self.assertEqual(0, instance.initialize_code()) - + # MI6 has separate epsilon_squared parameters for different interactions! self.assertEqual([0, 0], list(instance.get_eps2_fs_fs().values())) self.assertEqual([0, 0], list(instance.get_eps2_fs_bh().values())) self.assertEqual([0, 0], list(instance.get_eps2_bh_bh().values())) - self.assertEqual(-2, instance.get_eps2()['__result']) # Not implemented (would be ambiguous) - + self.assertEqual(-2, instance.get_eps2()['__result']) # Not implemented (would be ambiguous) + self.assertEqual(0, instance.set_eps2_fs_fs(0.2)) self.assertEqual([0.2, 0], list(instance.get_eps2_fs_fs().values())) self.assertEqual(0, instance.set_eps2_fs_bh(0.3)) self.assertEqual([0.3, 0], list(instance.get_eps2_fs_bh().values())) self.assertEqual(0, instance.set_eps2_bh_bh(0.4)) self.assertEqual([0.4, 0], list(instance.get_eps2_bh_bh().values())) - self.assertEqual(-2, instance.set_eps2(0.1)) # Not implemented (would be ambiguous) - + self.assertEqual(-2, instance.set_eps2(0.1)) # Not implemented (would be ambiguous) + self.assertEqual([1.0e-4, 0], list(instance.get_eta_s().values())) self.assertEqual([0.1, 0], list(instance.get_eta_fs().values())) self.assertEqual([0.4, 0], list(instance.get_eta_smbh().values())) self.assertEqual([0.4, 0], list(instance.get_eta_imbh().values())) - + self.assertEqual(0, instance.set_eta_s(0.01)) self.assertEqual([0.01, 0], list(instance.get_eta_s().values())) self.assertEqual(0, instance.set_eta_fs(0.02)) @@ -143,26 +144,26 @@ def test5(self): self.assertEqual([0.03, 0], list(instance.get_eta_smbh().values())) self.assertEqual(0, instance.set_eta_imbh(0.04)) self.assertEqual([0.04, 0], list(instance.get_eta_imbh().values())) - + self.assertEqual(0, instance.set_max_relative_energy_error(1.0e-6)) self.assertEqual([1.0e-6, 0], list(instance.get_max_relative_energy_error().values())) self.assertEqual(0, instance.set_maximum_timestep(1.0e-6)) self.assertEqual([1.0e-6, 0], list(instance.get_maximum_timestep().values())) - + self.assertEqual(0, instance.set_smbh_mass(0.1)) self.assertEqual([0.1, 0], list(instance.get_smbh_mass().values())) - + self.assertEqual([0, 0], list(instance.get_include_smbh_flag().values())) self.assertEqual(0, instance.set_include_smbh_flag(1)) self.assertEqual([1, 0], list(instance.get_include_smbh_flag().values())) self.assertEqual([1, 0], list(instance.get_calculate_postnewtonian().values())) self.assertEqual(0, instance.set_calculate_postnewtonian(0)) self.assertEqual([0, 0], list(instance.get_calculate_postnewtonian().values())) - + self.assertEqual(0, instance.commit_parameters()) self.assertEqual(0, instance.cleanup_code()) instance.stop() - + def test6(self): print("Test MI6Interface evolve_model, single particle (+SMBH)") instance = MI6Interface(**default_options) @@ -170,22 +171,22 @@ def test6(self): self.assertEqual(0, instance.set_include_smbh_flag(1)) self.assertEqual(0, instance.set_calculate_postnewtonian(0)) self.assertEqual(0, instance.commit_parameters()) - + # Set up a light particle on a circular orbit around the SMBH: self.assertEqual([1, 0], list(instance.new_particle(1.0e-4, 1.0, 0, 0, 0, 1.0, 0, 0.001).values())) self.assertEqual(0, instance.commit_particles()) - - self.assertEqual(0, instance.evolve_model(math.pi)) # half an orbit + + self.assertEqual(0, instance.evolve_model(math.pi)) # half an orbit for result, expected in zip(instance.get_position(1).values(), [-1.0, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 4) - - self.assertEqual(0, instance.evolve_model(2 * math.pi)) # full orbit + + self.assertEqual(0, instance.evolve_model(2 * math.pi)) # full orbit for result, expected in zip(instance.get_position(1).values(), [1.0, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 4) - + self.assertEqual(0, instance.cleanup_code()) instance.stop() - + def test7(self): print("Test MI6Interface evolve_model, 2 particles orbiting the SMBH") instance = MI6Interface(**default_options) @@ -197,21 +198,21 @@ def test7(self): mass = 1.0e-4 dv = 0.5 * (math.sqrt(1.0 + 0.5*mass) - 1.0) self.assertEqual([1, 0], list(instance.new_particle(mass, 1.0, 0, 0, 0, 1.0+dv, 0, 0.001).values())) - self.assertEqual([2, 0], list(instance.new_particle(mass, -1.0, 0, 0, 0,-1.0-dv, 0, 0.001).values())) + self.assertEqual([2, 0], list(instance.new_particle(mass, -1.0, 0, 0, 0, -1.0-dv, 0, 0.001).values())) self.assertEqual(0, instance.commit_particles()) - + P = 2 * math.pi / (1 + dv) - self.assertEqual(0, instance.evolve_model(P / 2)) # half an orbit + self.assertEqual(0, instance.evolve_model(P / 2)) # half an orbit for result, expected in zip(instance.get_position(1).values(), [-1.0, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 4) - - self.assertEqual(0, instance.evolve_model(P)) # full orbit + + self.assertEqual(0, instance.evolve_model(P)) # full orbit for result, expected in zip(instance.get_position(1).values(), [1.0, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 4) - + self.assertEqual(0, instance.cleanup_code()) instance.stop() - + def test8(self): print("Test MI6Interface evolve_model, binary (+SMBH) --> accretion!?") instance = MI6Interface(**default_options) @@ -222,24 +223,23 @@ def test8(self): # Set up a light binary on circular orbits around the SMBH: mass = 1.0e-6 self.assertEqual([1, 0], list(instance.new_particle(mass, 1.0, 0, 0, 0, 1.0, 0, 0.001).values())) - self.assertEqual([2, 0], list(instance.new_particle(mass, -1.0, 0, 0, 0,-1.0, 0, 0.001).values())) + self.assertEqual([2, 0], list(instance.new_particle(mass, -1.0, 0, 0, 0, -1.0, 0, 0.001).values())) self.assertEqual(0, instance.commit_particles()) - + self.assertEqual(0, instance.evolve_model(0.00001)) result1 = list(instance.get_position(1).values()) result2 = list(instance.get_position(2).values()) print(result1) print(result2) - + self.assertEqual(0, instance.cleanup_code()) instance.stop() - class TestMI6(TestWithMPI): - + default_converter = nbody_system.nbody_to_si(1.0e4 | units.MSun, 1.0 | units.AU) - + def new_sun_earth_system(self): particles = Particles(2) particles.mass = [1.0, 3.0037e-6] | units.MSun @@ -248,7 +248,7 @@ def new_sun_earth_system(self): particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.km / units.s particles[1].vy = (constants.G * particles.total_mass() / (1.0 | units.AU)).sqrt() return particles - + def test1(self): print("Testing MI6 initialization") instance = MI6(self.default_converter, **default_options) @@ -256,18 +256,18 @@ def test1(self): instance.commit_parameters() instance.cleanup_code() instance.stop() - + def test2(self): print("Testing MI6 parameters") instance = MI6(self.default_converter, **default_options) instance.initialize_code() - - self.assertEqual(instance.parameters.epsilon_squared, + + self.assertEqual(instance.parameters.epsilon_squared, instance.unit_converter.to_si(0.0 | nbody_system.length**2)) self.assertEqual(instance.parameters.timestep_parameter, 0.1) - - for par, value in [('epsilon_squared_star_star', 0.0 | nbody_system.length**2), - ('epsilon_squared_star_blackhole', 0.0 | nbody_system.length**2), + + for par, value in [('epsilon_squared_star_star', 0.0 | nbody_system.length**2), + ('epsilon_squared_star_blackhole', 0.0 | nbody_system.length**2), ('epsilon_squared_blackhole_blackhole', 0.0 | nbody_system.length**2), ('initial_timestep_parameter', 1.0e-4), ('timestep_parameter_stars', 0.1), @@ -277,40 +277,40 @@ def test2(self): ('maximum_timestep', 1.0/1024.0 | nbody_system.time), ('smbh_mass', 1.0 | nbody_system.mass), ('lightspeed', 1.0 | nbody_system.speed)]: - self.assertEqual(instance.unit_converter.to_si(value), + self.assertEqual(instance.unit_converter.to_si(value), getattr(instance.parameters, par)) - + if hasattr(value, 'unit'): new_value = 3.0 | value.unit else: new_value = 3.0 - + setattr(instance.parameters, par, new_value) self.assertEqual(instance.unit_converter.to_si(new_value), getattr(instance.parameters, par)) - + # epsilon_squared is an alias for epsilon_squared_star_star, so epsilon_squared also has become 3: - self.assertEqual(instance.parameters.epsilon_squared, + self.assertEqual(instance.parameters.epsilon_squared, instance.unit_converter.to_si(3.0 | nbody_system.length**2)) instance.parameters.epsilon_squared = 0.1 | nbody_system.length**2 - self.assertEqual(instance.parameters.epsilon_squared, + self.assertEqual(instance.parameters.epsilon_squared, instance.unit_converter.to_si(0.1 | nbody_system.length**2)) # timestep_parameter is an alias for timestep_parameter_stars, so timestep_parameter also has become 3: self.assertEqual(instance.parameters.timestep_parameter, 3.0) instance.parameters.timestep_parameter = 0.01 self.assertEqual(instance.parameters.timestep_parameter, 0.01) - + self.assertEqual(instance.parameters.include_smbh, False) instance.parameters.include_smbh = True self.assertEqual(instance.parameters.include_smbh, True) self.assertEqual(instance.parameters.calculate_postnewtonian, True) instance.parameters.calculate_postnewtonian = False self.assertEqual(instance.parameters.calculate_postnewtonian, False) - + self.assertEqual(instance.parameters.drink, "Vodka martini. Shaken, not stirred.") - + instance.stop() - + def test3(self): print("Testing MI6 particles") instance = MI6(self.default_converter, **default_options) @@ -318,17 +318,17 @@ def test3(self): instance.commit_parameters() instance.particles.add_particles(self.new_sun_earth_system()) instance.commit_particles() - + self.assertAlmostEqual(instance.particles.mass, [1.0, 3.0037e-6] | units.MSun) self.assertAlmostEqual(instance.particles.radius, 1.0 | units.RSun) - self.assertAlmostEqual(instance.particles.position, + self.assertAlmostEqual(instance.particles.position, [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]] | units.AU) - self.assertAlmostEqual(instance.particles.velocity, + self.assertAlmostEqual(instance.particles.velocity, [[0.0, 0.0, 0.0], [0.0, 29.7885, 0.0]] | units.km / units.s, 3) - + instance.cleanup_code() instance.stop() - + def test4(self): print("Testing MI6 evolve_model, 2 particles orbiting the SMBH") particles = Particles(2) @@ -336,11 +336,11 @@ def test4(self): particles.radius = 1.0 | units.RSun particles.position = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]] | units.AU particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.km / units.s - particles[1].vy = ((constants.G * (10001.0 | units.MSun) / (1.0 | units.AU)).sqrt() + + particles[1].vy = ((constants.G * (10001.0 | units.MSun) / (1.0 | units.AU)).sqrt() + (constants.G * (10000.0 | units.MSun) / (1.0 | units.AU)).sqrt()) particles.move_to_center() print(particles) - + instance = MI6(self.default_converter, **default_options) instance.initialize_code() instance.parameters.include_smbh = True @@ -349,23 +349,23 @@ def test4(self): instance.particles.add_particles(particles) instance.commit_particles() primary = instance.particles[0] - + P = 2 * math.pi * primary.x / primary.vy P_corrected = (P) * (2.0 / (1.0 + math.sqrt(1.0001))) - + position_at_start = primary.position.x instance.evolve_model(P_corrected / 4.0) self.assertAlmostRelativeEqual(position_at_start, primary.position.y, 3) - + instance.evolve_model(P_corrected / 2.0) self.assertAlmostRelativeEqual(position_at_start, -primary.position.x, 3) - + instance.evolve_model(P_corrected) self.assertAlmostRelativeEqual(position_at_start, primary.position.x, 3) - + instance.cleanup_code() instance.stop() - + def test5(self): print("Testing MI6 evolve_model, 2 particles, no SMBH") particles = Particles(2) @@ -376,7 +376,7 @@ def test5(self): particles[1].vy = (constants.G * (2.0 | units.MSun) / (2.0 | units.AU)).sqrt() particles.move_to_center() print(particles) - + converter = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) instance = MI6(converter, **default_options) instance.initialize_code() @@ -385,22 +385,22 @@ def test5(self): instance.particles.add_particles(particles) instance.commit_particles() primary = instance.particles[0] - + P = 2 * math.pi * primary.x / primary.vy - + position_at_start = primary.position.x instance.evolve_model(P / 4.0) self.assertAlmostRelativeEqual(position_at_start, primary.position.y, 3) - + instance.evolve_model(P / 2.0) self.assertAlmostRelativeEqual(position_at_start, -primary.position.x, 3) - + instance.evolve_model(P) self.assertAlmostRelativeEqual(position_at_start, primary.position.x, 3) - + instance.cleanup_code() instance.stop() - + def test6(self): print("Testing MI6 evolve_model, earth-sun system, no SMBH") converter = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) @@ -411,40 +411,40 @@ def test6(self): instance.particles.add_particles(self.new_sun_earth_system()) instance.commit_particles() earth = instance.particles[1] - + position_at_start = earth.position.x instance.evolve_model(0.25 | units.yr) self.assertAlmostRelativeEqual(position_at_start, earth.position.y, 3) - + instance.evolve_model(0.5 | units.yr) self.assertAlmostRelativeEqual(position_at_start, -earth.position.x, 3) - + instance.evolve_model(1.0 | units.yr) self.assertAlmostRelativeEqual(position_at_start, earth.position.x, 3) - + instance.cleanup_code() instance.stop() - + def test7(self): print("Testing effect of MI6 parameter epsilon_squared") converter = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) particles = self.new_sun_earth_system() particles.rotate(0.0, 0.0, -math.pi/4) particles.move_to_center() - + tan_initial_direction = particles[1].vy/particles[1].vx self.assertAlmostEqual(tan_initial_direction, math.tan(math.pi/4)) - tan_final_direction = [] - for log_eps2 in range(-9,10,2): + tan_final_direction = [] + for log_eps2 in range(-9, 10, 2): instance = MI6(converter, **default_options) - instance.initialize_code() + instance.initialize_code() instance.parameters.epsilon_squared = 10.0**log_eps2 | units.AU ** 2 instance.parameters.smbh_mass = 0.0 | units.MSun instance.commit_parameters() instance.particles.add_particles(particles) instance.commit_particles() instance.evolve_model(0.25 | units.yr) - tan_final_direction.append(instance.particles[1].velocity[1]/ + tan_final_direction.append(instance.particles[1].velocity[1] / instance.particles[1].velocity[0]) instance.cleanup_code() instance.stop() @@ -454,22 +454,22 @@ def test7(self): self.assertAlmostEqual(tan_final_direction[-1], tan_initial_direction, 2) # Outcome is most sensitive to epsilon_squared when epsilon_squared = d(earth, sun)^2 delta = [abs(tan_final_direction[i+1]-tan_final_direction[i]) for i in range(len(tan_final_direction)-1)] - self.assertEqual(delta[len(tan_final_direction)//2 -1], max(delta)) - + self.assertEqual(delta[len(tan_final_direction)//2 - 1], max(delta)) + def test8(self): print("Testing MI6 get_gravity_at_point and get_potential_at_point") instance = MI6(**default_options) instance.initialize_code() instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2 instance.parameters.smbh_mass = 0.0 | nbody_system.mass - + particles = Particles(2) particles.mass = 1.0 | nbody_system.mass - particles.radius = 0.0 | nbody_system.length - particles.position = [[0.0,0.0,0.0], [2.0,0.0,0.0]] | nbody_system.length + particles.radius = 0.0 | nbody_system.length + particles.position = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]] | nbody_system.length particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed instance.particles.add_particles(particles) - + zero = 0.0 | nbody_system.length fx, fy, fz = instance.get_gravity_at_point(zero, 1.0 | nbody_system.length, zero, zero) self.assertAlmostEqual(fx, 0.0 | nbody_system.acceleration) @@ -483,19 +483,19 @@ def test8(self): potential1 = instance.get_potential_at_point(zero, x1, zero, zero) fx0, fy0, fz0 = instance.get_gravity_at_point(zero, x0, zero, zero) fx1, fy1, fz1 = instance.get_gravity_at_point(zero, x1, zero, zero) - + self.assertAlmostEqual(fy0, 0.0 | nbody_system.acceleration) self.assertAlmostEqual(fz0, 0.0 | nbody_system.acceleration) self.assertAlmostEqual(fy1, 0.0 | nbody_system.acceleration) self.assertAlmostEqual(fz1, 0.0 | nbody_system.acceleration) - + self.assertAlmostEqual(fx0, -1.0 * fx1) fx = (-1.0 / (x0**2) + 1.0 / (x1**2)) * (1.0 | nbody_system.length ** 3 / nbody_system.time ** 2) self.assertAlmostEqual(fx, fx0) self.assertAlmostEqual(potential0, potential1) - + instance.stop() - + def test9(self): print("Testing MI6 evolve_model and getters energy, plummer sphere, no SMBH") converter = nbody_system.nbody_to_si(1.0e2 | units.MSun, 1.0 | units.parsec) @@ -506,24 +506,24 @@ def test9(self): numpy.random.seed(987654321) instance.particles.add_particles(new_plummer_model(100, convert_nbody=converter)) instance.commit_particles() - + kinetic_energy = instance.kinetic_energy potential_energy = instance.potential_energy self.assertAlmostRelativeEqual(kinetic_energy, 2.12292810174e+37 | units.J, 10) self.assertAlmostRelativeEqual(potential_energy, -4.33511391248e+37 | units.J, 10) - + initial_total_energy = kinetic_energy + potential_energy instance.evolve_model(0.1 | nbody_system.time) kinetic_energy = instance.kinetic_energy potential_energy = instance.potential_energy self.assertAlmostRelativeEqual(kinetic_energy, 2.13633848369e+37 | units.J, 5) self.assertAlmostRelativeEqual(potential_energy, -4.34851806763e+37 | units.J, 5) - + self.assertAlmostRelativeEqual(potential_energy + kinetic_energy, initial_total_energy, 5) - + instance.cleanup_code() instance.stop() - + def test10(self): print("Testing MI6 collision_detection") particles = Particles(7) @@ -533,7 +533,7 @@ def test10(self): particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.velocity = [[2, 0, 0], [-2, 0, 0]]*3 + [[-4, 0, 0]] | nbody_system.speed - + instance = MI6(**default_options) instance.initialize_code() instance.parameters.set_defaults() @@ -541,28 +541,28 @@ def test10(self): collisions = instance.stopping_conditions.collision_detection collisions.enable() instance.evolve_model(1.0 | nbody_system.time) - + self.assertTrue(collisions.is_set()) self.assertAlmostEqual(instance.model_time, -(particles[0].x-particles[1].x)/(particles[0].vx-particles[1].vx), 3) self.assertEqual(len(collisions.particles(0)), 3) self.assertEqual(len(collisions.particles(1)), 3) self.assertEqual(len(particles - collisions.particles(0) - collisions.particles(1)), 1) - self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < + self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < (collisions.particles(0).radius + collisions.particles(1).radius), [True, True, True]) - + sticky_merged = Particles(len(collisions.particles(0))) sticky_merged.mass = collisions.particles(0).mass + collisions.particles(1).mass sticky_merged.radius = collisions.particles(0).radius for p1, p2, merged in zip(collisions.particles(0), collisions.particles(1), sticky_merged): merged.position = (p1 + p2).center_of_mass() merged.velocity = (p1 + p2).center_of_mass_velocity() - + print(instance.model_time) print(instance.particles) instance.particles.remove_particles(collisions.particles(0) + collisions.particles(1)) instance.particles.add_particles(sticky_merged) - + instance.evolve_model(1.0 | nbody_system.time) print() print(instance.model_time) @@ -572,11 +572,11 @@ def test10(self): self.assertEqual(len(collisions.particles(0)), 1) self.assertEqual(len(collisions.particles(1)), 1) self.assertEqual(len(instance.particles - collisions.particles(0) - collisions.particles(1)), 2) - self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < + self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < (collisions.particles(0).radius + collisions.particles(1).radius), [True]) instance.stop() - + def test11(self): print("Testing MI6 properties") numpy.random.seed(12345) @@ -585,32 +585,31 @@ def test11(self): cluster_velocity = [4, 5, 6] | nbody_system.speed particles.velocity += cluster_velocity external_kinetic_energy = (0.5 | nbody_system.mass) * cluster_velocity.length_squared() - + instance = MI6(**default_options) instance.particles.add_particles(particles) - + kinetic_energy = instance.kinetic_energy - external_kinetic_energy potential_energy = instance.potential_energy self.assertAlmostRelativeEqual(kinetic_energy, 0.25 | nbody_system.energy, 10) self.assertAlmostRelativeEqual(potential_energy, -0.5 | nbody_system.energy, 10) self.assertAlmostRelativeEqual(instance.total_mass, 1.0 | nbody_system.mass, 10) - self.assertAlmostRelativeEqual(instance.center_of_mass_position, + self.assertAlmostRelativeEqual(instance.center_of_mass_position, [1, 2, 3] | nbody_system.length, 10) - self.assertAlmostRelativeEqual(instance.center_of_mass_velocity, + self.assertAlmostRelativeEqual(instance.center_of_mass_velocity, [4, 5, 6] | nbody_system.speed, 10) initial_total_energy = kinetic_energy + potential_energy - + instance.evolve_model(0.1 | nbody_system.time) self.assertAlmostRelativeEqual(instance.model_time, 0.1 | nbody_system.time) kinetic_energy = instance.kinetic_energy - external_kinetic_energy potential_energy = instance.potential_energy self.assertAlmostRelativeEqual(kinetic_energy+potential_energy, -0.25 | nbody_system.energy, 3) self.assertAlmostRelativeEqual(instance.total_mass, 1.0 | nbody_system.mass, 3) - self.assertAlmostRelativeEqual(instance.center_of_mass_position, + self.assertAlmostRelativeEqual(instance.center_of_mass_position, [1.4, 2.5, 3.6] | nbody_system.length, 3) - self.assertAlmostRelativeEqual(instance.center_of_mass_velocity, + self.assertAlmostRelativeEqual(instance.center_of_mass_velocity, [4, 5, 6] | nbody_system.speed, 3) - + instance.cleanup_code() instance.stop() - diff --git a/src/amuse/test/suite/codes_tests/test_mikkola.py b/src/amuse/test/suite/codes_tests/test_mikkola.py index 71412b3444..5fbe5dc3b2 100644 --- a/src/amuse/test/suite/codes_tests/test_mikkola.py +++ b/src/amuse/test/suite/codes_tests/test_mikkola.py @@ -7,219 +7,217 @@ from amuse.community.mikkola.interface import MikkolaInterface from amuse.community.mikkola.interface import Mikkola + class MikkolaInterfaceTests(TestWithMPI): - + def xtest0(self): instance = MikkolaInterface() - + def test1(self): # instance = MikkolaInterface(debugger="ddd") instance = MikkolaInterface() - #instance = MikkolaInterface() + # instance = MikkolaInterface() instance.initialize_code() instance.set_lightspeed(1e4) instance.commit_parameters() - res1 = instance.new_particle(mass = 1.0, radius = 0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) - res2 = instance.new_particle(mass = 0.001, radius = 0, x = 1.0, y = 0.0, z = 0.0, vx = 0.0, vy = 1.0, vz = 0.0) - + res1 = instance.new_particle(mass=1.0, radius=0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) + res2 = instance.new_particle(mass=0.001, radius=0, x=1.0, y=0.0, z=0.0, vx=0.0, vy=1.0, vz=0.0) + self.assertEqual(1, res1['index_of_the_particle']) self.assertEqual(2, res2['index_of_the_particle']) - + retrieved_state1 = instance.get_state(1) retrieved_state2 = instance.get_state(2) - - end_time = 10.0 + + end_time = 10.0 instance.evolve_model(end_time) instance.cleanup_code() instance.stop() - + def test2(self): instance = MikkolaInterface() instance.initialize_code() instance.set_lightspeed(1e4) instance.commit_parameters() - index1, error = instance.new_particle(mass = 1.0, radius = 0.1, x = 1.0, y = 2.0, z = 3.0, vx = 1.1, vy = 2.2, vz = 3.3) + index1, error = instance.new_particle(mass=1.0, radius=0.1, x=1.0, y=2.0, z=3.0, vx=1.1, vy=2.2, vz=3.3) self.assertEqual(error, 0) - index2, error = instance.new_particle(mass = 0.001, radius = 0.2, x = 3.0, y = 4.0, z = 5.0, vx = 3.3, vy = 4.4, vz = 5.5) + index2, error = instance.new_particle(mass=0.001, radius=0.2, x=3.0, y=4.0, z=5.0, vx=3.3, vy=4.4, vz=5.5) self.assertEqual(error, 0) - + self.assertEqual(1, index1) self.assertEqual(2, index2) - - mass,error = instance.get_mass(1) + + mass, error = instance.get_mass(1) self.assertEqual(error, 0) self.assertEqual(mass, 1.0) - - mass,error = instance.get_mass(2) + + mass, error = instance.get_mass(2) self.assertEqual(error, 0) self.assertEqual(mass, 0.001) - - - radius,error = instance.get_radius(1) + + radius, error = instance.get_radius(1) self.assertEqual(error, 0) self.assertEqual(radius, 0.1) - - radius,error = instance.get_radius(2) + + radius, error = instance.get_radius(2) self.assertEqual(error, 0) self.assertEqual(radius, 0.2) - - - x,y,z,error = instance.get_position(1) + + x, y, z, error = instance.get_position(1) self.assertEqual(error, 0) self.assertEqual(x, 1.0) self.assertEqual(y, 2.0) self.assertEqual(z, 3.0) - - x,y,z,error = instance.get_position(2) + + x, y, z, error = instance.get_position(2) self.assertEqual(error, 0) self.assertEqual(x, 3.0) self.assertEqual(y, 4.0) self.assertEqual(z, 5.0) - - vx,vy,vz,error = instance.get_velocity(1) + + vx, vy, vz, error = instance.get_velocity(1) self.assertEqual(error, 0) self.assertEqual(vx, 1.1) self.assertEqual(vy, 2.2) self.assertEqual(vz, 3.3) - + instance.cleanup_code() instance.stop() - + def test3(self): instance = MikkolaInterface() instance.initialize_code() instance.set_lightspeed(1e4) instance.commit_parameters() - index1, error = instance.new_particle(mass = 1.0, radius = 0, x = 1.0, y = 2.0, z = 3.0, vx = 1.1, vy = 2.2, vz = 3.3) + index1, error = instance.new_particle(mass=1.0, radius=0, x=1.0, y=2.0, z=3.0, vx=1.1, vy=2.2, vz=3.3) self.assertEqual(error, 0) - index2, error = instance.new_particle(mass = 0.001, radius = 0, x = 3.0, y = 4.0, z = 5.0, vx = 3.3, vy = 4.4, vz = 5.5) + index2, error = instance.new_particle(mass=0.001, radius=0, x=3.0, y=4.0, z=5.0, vx=3.3, vy=4.4, vz=5.5) self.assertEqual(error, 0) - + self.assertEqual(1, index1) self.assertEqual(2, index2) - - mass,error = instance.get_mass(1) + + mass, error = instance.get_mass(1) self.assertEqual(error, 0) self.assertEqual(mass, 1.0) - - mass,error = instance.get_mass(2) + + mass, error = instance.get_mass(2) self.assertEqual(error, 0) self.assertEqual(mass, 0.001) - - error = instance.delete_particle(1) - mass,error = instance.get_mass(1) + + error = instance.delete_particle(1) + mass, error = instance.get_mass(1) self.assertEqual(error, -1) - - index1, error = instance.new_particle(mass = 2.0, radius = 0, x = 1.0, y = 2.0, z = 3.0, vx = 1.1, vy = 2.2, vz = 3.3) + + index1, error = instance.new_particle(mass=2.0, radius=0, x=1.0, y=2.0, z=3.0, vx=1.1, vy=2.2, vz=3.3) self.assertEqual(error, 0) self.assertEqual(1, index1) - - mass,error = instance.get_mass(1) + + mass, error = instance.get_mass(1) self.assertEqual(error, 0) self.assertEqual(mass, 2.0) - - mass,error = instance.get_mass(2) + + mass, error = instance.get_mass(2) self.assertEqual(error, 0) self.assertEqual(mass, 0.001) - + def test4(self): instance = MikkolaInterface() instance.initialize_code() instance.set_lightspeed(1e4) instance.commit_parameters() - index1, error = instance.new_particle(mass = 1.0, radius = 0, x = 1.0, y = 2.0, z = 3.0, vx = 1.1, vy = 2.2, vz = 3.3) + index1, error = instance.new_particle(mass=1.0, radius=0, x=1.0, y=2.0, z=3.0, vx=1.1, vy=2.2, vz=3.3) self.assertEqual(error, 0) self.assertEqual(index1, 1) - + instance.commit_particles() - + error = instance.cleanup_code() self.assertEqual(error, 0) - - mass,error = instance.get_mass(1) + + mass, error = instance.get_mass(1) self.assertEqual(error, -1) instance.commit_parameters() - index1, error = instance.new_particle(mass = 1.0, radius = 0, x = 1.0, y = 2.0, z = 3.0, vx = 1.1, vy = 2.2, vz = 3.3) + index1, error = instance.new_particle(mass=1.0, radius=0, x=1.0, y=2.0, z=3.0, vx=1.1, vy=2.2, vz=3.3) self.assertEqual(error, 0) self.assertEqual(index1, 1) instance.commit_particles() error = instance.cleanup_code() self.assertEqual(error, 0) - - - -# run with: + + +# run with: # %>nosetests -v test_mikkola.py:TestMikkola.test1 class TestMikkola(TestWithMPI): def new_system_of_sun_and_earth(self): stars = datamodel.Stars(2) sun = stars[0] sun.mass = units.MSun(1.0) - sun.position = units.m(numpy.array((0.0,0.0,0.0))) - sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) + sun.position = units.m(numpy.array((0.0, 0.0, 0.0))) + sun.velocity = units.ms(numpy.array((0.0, 0.0, 0.0))) sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) - earth.radius = units.km(6371) - earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) - earth.velocity = units.ms(numpy.array((0.0,29800,0.0))) - + earth.radius = units.km(6371) + earth.position = units.km(numpy.array((149.5e6, 0.0, 0.0))) + earth.velocity = units.ms(numpy.array((0.0, 29800, 0.0))) + return stars def test1(self): - convert_nbody=nbody_system.nbody_to_si(1.0|units.MSun, 1.0|units.yr/(2.0*pi)) + convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.yr/(2.0*pi)) instance = Mikkola(convert_nbody) instance.parameters.timestep = 0.5 | units.day stars = self.new_system_of_sun_and_earth() instance.particles.add_particles(stars) Sun = stars[0] earth = stars[1] - + postion_at_start = earth.position.value_in(units.AU)[0] - + # instance.evolve_model(365.0 | units.day) instance.evolve_model(1.0 | units.yr) channel = instance.particles.new_channel_to(stars) channel.copy() self.assertAlmostRelativeEquals(instance.potential_energy * -0.5, instance.kinetic_energy, 3) - self.assertAlmostRelativeEquals(instance.radiated_gravitational_energy, -6222456075.98| units.m**2 * units.kg * units.s**-2, 4) - + self.assertAlmostRelativeEquals(instance.radiated_gravitational_energy, -6222456075.98 | units.m**2 * units.kg * units.s**-2, 4) + postion_after_full_rotation = earth.position.value_in(units.AU)[0] - + self.assertAlmostEqual(postion_at_start, instance.particles[1].position.value_in(units.AU)[0], 3) self.assertAlmostEqual(postion_at_start, postion_after_full_rotation, 3) - + instance.evolve_model(1.5 | units.yr) - + channel.copy() - + postion_after_half_a_rotation = earth.position.value_in(units.AU)[0] self.assertAlmostEqual(-postion_at_start, postion_after_half_a_rotation, 3) - - instance.evolve_model(1.75 | units.yr) - + + instance.evolve_model(1.75 | units.yr) + channel.copy() - + postion_after_half_a_rotation = earth.position.value_in(units.AU)[1] - + self.assertAlmostEqual(-postion_at_start, postion_after_half_a_rotation, 3) instance.cleanup_code() del instance -# run with: +# run with: # %>nosetests -v test_mikkola.py:TestMikkola.test1 def new_system_of_sun_and_mercury(self): stars = datamodel.Stars(2) sun = stars[0] sun.mass = units.MSun(1.0) - sun.position = units.m(numpy.array((0.0,0.0,0.0))) - sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) + sun.position = units.m(numpy.array((0.0, 0.0, 0.0))) + sun.velocity = units.ms(numpy.array((0.0, 0.0, 0.0))) sun.radius = units.RSun(1.0) mercury = stars[1] @@ -230,43 +228,43 @@ def new_system_of_sun_and_mercury(self): return stars def test2(self): - convert_nbody=nbody_system.nbody_to_si(1.0|units.MSun, 1.0|units.yr/(2.0*pi)) + convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.yr/(2.0*pi)) instance = Mikkola(convert_nbody) instance.parameters.timestep = 1 | units.day stars = self.new_system_of_sun_and_mercury() instance.particles.add_particles(stars) Sun = stars[0] mercury = stars[1] - + postion_at_start = mercury.position.value_in(units.AU)[0] - + period_mercury = 87.9691 | units.day instance.evolve_model(period_mercury) channel = instance.particles.new_channel_to(stars) channel.copy() - + postion_after_full_rotation = mercury.position.value_in(units.AU)[0] - + self.assertAlmostEqual(postion_at_start, postion_after_full_rotation, 4) - + instance.evolve_model(1.5 * period_mercury) - + channel.copy() - + postion_after_half_a_rotation = mercury.position.value_in(units.AU)[0] self.assertAlmostEqual(-postion_at_start, postion_after_half_a_rotation, 3) - - instance.evolve_model(1.75 *period_mercury) - + + instance.evolve_model(1.75 * period_mercury) + channel.copy() - + postion_after_half_a_rotation = mercury.position.value_in(units.AU)[1] - + self.assertAlmostEqual(-postion_at_start, postion_after_half_a_rotation, 3) instance.cleanup_code() del instance -# run with: +# run with: # %>nosetests -v test_mikkola.py:TestMikkola.test3 def new_system_of_Hulse_Taylor_pulsar(self): stars = datamodel.Stars(2) @@ -288,83 +286,81 @@ def new_system_of_Hulse_Taylor_pulsar(self): return stars def test3(self): - convert_nbody=nbody_system.nbody_to_si(1.0|units.MSun, 1.0|units.yr/(2.0*pi)) + convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.yr/(2.0*pi)) instance = Mikkola(convert_nbody) instance.parameters.lightspeed = constants.c stars = self.new_system_of_Hulse_Taylor_pulsar() instance.particles.add_particles(stars) Hulse = stars[0] Taylor = stars[1] - + postion_at_start = Taylor.position.value_in(units.AU)[0] - - #orbital period - #see http://www.johnstonsarchive.net/relativity/binpulsar.html + + # orbital period + # see http://www.johnstonsarchive.net/relativity/binpulsar.html period_HTpulsar = 7.75 | units.hour - #period_HTpulsar = 77.51939106 | units.hour + # period_HTpulsar = 77.51939106 | units.hour # period for abseidal motion # period_HTpulsar = 85.0 | units.yr #4.2degrees/year - #period_HTpulsar = 1.0 | units.yr + # period_HTpulsar = 1.0 | units.yr instance.evolve_model(period_HTpulsar) channel = instance.particles.new_channel_to(stars) channel.copy() postion_after_full_rotation = Taylor.position.value_in(units.AU)[0] - + print("Time=", instance.model_time, period_HTpulsar) self.assertAlmostEqual(postion_at_start, postion_after_full_rotation, 3) - + instance.stop() del instance - + def test4(self): - convert_nbody=nbody_system.nbody_to_si(1.0|units.MSun, 1.0|units.yr/(2.0*pi)) + convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.yr/(2.0*pi)) instance = Mikkola(convert_nbody) stars = self.new_system_of_Hulse_Taylor_pulsar() instance.particles.add_particles(stars) - + instance.commit_particles() self.assertEqual(len(instance.particles), 2) instance.cleanup_code() self.assertEqual(len(instance.particles), 0) - + instance.initialize_code() instance.particles.add_particles(stars) self.assertEqual(len(instance.particles), 2) - + instance.commit_particles() self.assertEqual(len(instance.particles), 2) instance.cleanup_code() self.assertEqual(len(instance.particles), 0) def test5(self): - convert_nbody=nbody_system.nbody_to_si(1.0|units.MSun, 1.0|units.yr/(2.0*pi)) - + convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.yr/(2.0*pi)) + instance = Mikkola(convert_nbody) - + stars = datamodel.Stars(3) stars[0].mass = 1.0 | units.MSun - stars[0].radius = 1.0| units.RSun + stars[0].radius = 1.0 | units.RSun stars[0].position = [0.0, 0, 0] | units.km - stars[0].velocity = [0.0,0.0,0.0] | units.km/units.s + stars[0].velocity = [0.0, 0.0, 0.0] | units.km/units.s stars[1].mass = 1.0 | units.MSun - stars[1].radius = 1.0| units.RSun + stars[1].radius = 1.0 | units.RSun stars[1].position = [0.1, 0, 0] | units.RSun stars[1].velocity = [-0.4, 0.0, 0.0] | units.km/units.s - - + stars[2].mass = 0.01 | units.MSun - stars[2].radius = 1.0| units.RSun + stars[2].radius = 1.0 | units.RSun stars[2].position = [6000, 0, 0] | units.RSun stars[2].velocity = [0.0, -10, 0.0] | units.km/units.s - - + instance.particles.add_particles(stars) - + instance.evolve_model(0.25 | units.yr) - + self.assertEqual(instance.get_number_of_particles_added(), 1) self.assertRaises(Exception, instance.get_id_of_added_particle, [2]) self.assertEqual(instance.get_id_of_added_particle(0), 4) @@ -374,7 +370,7 @@ def test5(self): pos1 = quantities.as_vector_quantity(instance.get_position(1)) pos2 = quantities.as_vector_quantity(instance.get_position(2)) posmerger = quantities.as_vector_quantity(instance.get_position(4)) - + print(pos1) print(pos2) print(posmerger) @@ -383,45 +379,44 @@ def test5(self): self.assertTrue(distance > 1e-6 | units.RSun) distance = (pos1-posmerger).length() print(distance.as_quantity_in(units.RSun)) - self.assertAlmostRelativeEquals(distance,0.718548184852 | units.RSun, 5) + self.assertAlmostRelativeEquals(distance, 0.718548184852 | units.RSun, 5) distance = (pos2-posmerger).length() print(distance.as_quantity_in(units.RSun)) - self.assertAlmostRelativeEquals(distance,0.718548184852 | units.RSun, 5) + self.assertAlmostRelativeEquals(distance, 0.718548184852 | units.RSun, 5) instance.update_particle_set() print(instance.particles[0].mass.as_quantity_in(units.MSun)) - #self.assertEquals(len(instance.particles), 4) + # self.assertEquals(len(instance.particles), 4) def test6(self): - convert_nbody=nbody_system.nbody_to_si(1.0|units.MSun, 1.0|units.yr/(2.0*pi)) - + convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.yr/(2.0*pi)) + instance = Mikkola(convert_nbody) - + stars = datamodel.Stars(4) stars[0].mass = 1.0 | units.MSun - stars[0].radius = 1.0| units.RSun + stars[0].radius = 1.0 | units.RSun stars[0].position = [0.0, 0, 0] | units.km - stars[0].velocity = [0.0,0.0,0.0] | units.km/units.s + stars[0].velocity = [0.0, 0.0, 0.0] | units.km/units.s stars[1].mass = 1.0 | units.MSun - stars[1].radius = 1.0| units.RSun + stars[1].radius = 1.0 | units.RSun stars[1].position = [0.1, 0, 0] | units.RSun stars[1].velocity = [-0.4, 0.0, 0.0] | units.km/units.s - + stars[2].mass = 1.0 | units.MSun - stars[2].radius = 1.0| units.RSun + stars[2].radius = 1.0 | units.RSun stars[2].position = [0.3, 0, 0] | units.RSun stars[2].velocity = [-0.4, 0.0, 0.0] | units.km/units.s - + stars[3].mass = 0.01 | units.MSun - stars[3].radius = 1.0| units.RSun + stars[3].radius = 1.0 | units.RSun stars[3].position = [6000, 0, 0] | units.RSun stars[3].velocity = [0.0, -10, 0.0] | units.km/units.s - - + instance.particles.add_particles(stars) - + instance.evolve_model(0.25 | units.yr) - + self.assertEqual(instance.get_number_of_particles_added(), 2) self.assertRaises(Exception, instance.get_id_of_added_particle, [2]) self.assertEqual(instance.get_id_of_added_particle(0), 5) @@ -430,36 +425,33 @@ def test6(self): self.assertAlmostRelativeEquals(instance.get_mass(5), 2 | units.MSun) instance.update_particle_set() print(instance.particles[0].mass.as_quantity_in(units.MSun)) - #self.assertEquals(len(instance.particles), 4) - - + # self.assertEquals(len(instance.particles), 4) + def test7(self): - convert_nbody=nbody_system.nbody_to_si(1.0|units.MSun, 1.0|units.yr/(2.0*pi)) - + convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.yr/(2.0*pi)) + instance = Mikkola(convert_nbody) - + stars = datamodel.Stars(3) stars[0].mass = 1.0 | units.MSun - stars[0].radius = 1.0| units.RSun + stars[0].radius = 1.0 | units.RSun stars[0].position = [0.0, 0, 0] | units.km - stars[0].velocity = [0.0,0.0,0.0] | units.km/units.s + stars[0].velocity = [0.0, 0.0, 0.0] | units.km/units.s stars[1].mass = 1.0 | units.MSun - stars[1].radius = 1.0| units.RSun + stars[1].radius = 1.0 | units.RSun stars[1].position = [0.1, 0, 0] | units.RSun stars[1].velocity = [-0.4, 0.0, 0.0] | units.km/units.s - - + stars[2].mass = 0.01 | units.MSun - stars[2].radius = 1.0| units.RSun + stars[2].radius = 1.0 | units.RSun stars[2].position = [6000, 0, 0] | units.RSun stars[2].velocity = [0.0, -10, 0.0] | units.km/units.s - - + instance.particles.add_particles(stars) - + instance.evolve_model(0.25 | units.yr) - + self.assertEqual(instance.get_number_of_particles_added(), 1) self.assertEqual(instance.get_id_of_added_particle(0), 4) child1, child2 = instance.get_children_of_particle([4]) @@ -469,47 +461,43 @@ def test7(self): child1, child2 = instance.get_children_of_particle([i+1]) self.assertEqual(child1[0], None) self.assertEqual(child2[0], None) - - + def test8(self): - convert_nbody=nbody_system.nbody_to_si(1.0|units.MSun, 1.0|units.yr/(2.0*pi)) - - + convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.yr/(2.0*pi)) + stars = datamodel.Stars(3) stars[0].mass = 1.0 | units.MSun - stars[0].radius = 1.0| units.RSun + stars[0].radius = 1.0 | units.RSun stars[0].position = [0.0, 0, 0] | units.km - stars[0].velocity = [0.0,0.0,0.0] | units.km/units.s + stars[0].velocity = [0.0, 0.0, 0.0] | units.km/units.s stars[1].mass = 1.0 | units.MSun - stars[1].radius = 1.0| units.RSun + stars[1].radius = 1.0 | units.RSun stars[1].position = [0.1, 0, 0] | units.RSun stars[1].velocity = [-0.4, 0.0, 0.0] | units.km/units.s - - + stars[2].mass = 0.01 | units.MSun - stars[2].radius = 1.0| units.RSun + stars[2].radius = 1.0 | units.RSun stars[2].position = [6000, 0, 0] | units.RSun stars[2].velocity = [0.0, -10, 0.0] | units.km/units.s - - + instance1 = Mikkola(convert_nbody) instance1.particles.add_particles(stars) instance1.evolve_model(0.45 | units.yr) - + pos11 = quantities.as_vector_quantity(instance1.get_position(1)) pos12 = quantities.as_vector_quantity(instance1.get_position(2)) posmerger1 = quantities.as_vector_quantity(instance1.get_position(4)) instance1.stop() - + instance2 = Mikkola(convert_nbody) instance2.particles.add_particles(stars) instance2.evolve_model(0.15 | units.yr) - self.assertAlmostRelativeEquals(instance2.model_time,0.15 | units.yr, 3) + self.assertAlmostRelativeEquals(instance2.model_time, 0.15 | units.yr, 3) instance2.evolve_model(0.3 | units.yr) print(instance2.model_time.as_quantity_in(units.yr)) - self.assertAlmostRelativeEquals(instance2.model_time, 0.45| units.yr, 3) - + self.assertAlmostRelativeEquals(instance2.model_time, 0.45 | units.yr, 3) + pos21 = quantities.as_vector_quantity(instance2.get_position(1)) pos22 = quantities.as_vector_quantity(instance2.get_position(2)) posmerger2 = quantities.as_vector_quantity(instance2.get_position(4)) @@ -517,41 +505,40 @@ def test8(self): print(pos12, pos22) print(posmerger1, posmerger2) instance2.stop() - + self.assertAlmostRelativeEquals(pos11, pos21) self.assertAlmostRelativeEquals(pos12, pos22) self.assertAlmostRelativeEquals(posmerger1[0], posmerger2[0], 4) self.assertAlmostRelativeEquals(posmerger1[1], posmerger2[1], 1) - + def test9(self): - convert_nbody=nbody_system.nbody_to_si(1.0|units.MSun, 1.0|units.yr/(2.0*pi)) - + convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.yr/(2.0*pi)) + instance = Mikkola(convert_nbody) - + stars = datamodel.Stars(4) stars[0].mass = 1.0 | units.MSun - stars[0].radius = 1.0| units.RSun + stars[0].radius = 1.0 | units.RSun stars[0].position = [0.0, 0, 0] | units.km - stars[0].velocity = [0.0,0.0,0.0] | units.km/units.s + stars[0].velocity = [0.0, 0.0, 0.0] | units.km/units.s stars[1].mass = 1.0 | units.MSun - stars[1].radius = 1.0| units.RSun + stars[1].radius = 1.0 | units.RSun stars[1].position = [0.1, 0, 0] | units.RSun stars[1].velocity = [-0.4, 0.0, 0.0] | units.km/units.s - + stars[2].mass = 1.0 | units.MSun - stars[2].radius = 1.0| units.RSun + stars[2].radius = 1.0 | units.RSun stars[2].position = [0.3, 0, 0] | units.RSun stars[2].velocity = [-0.4, 0.0, 0.0] | units.km/units.s - + stars[3].mass = 0.01 | units.MSun - stars[3].radius = 1.0| units.RSun + stars[3].radius = 1.0 | units.RSun stars[3].position = [6000, 0, 0] | units.RSun stars[3].velocity = [0.0, -10, 0.0] | units.km/units.s - - + instance.particles.add_particles(stars) - + instance.evolve_model(0.15 | units.yr) instance.update_particle_set() self.assertEqual(instance.get_id_of_added_particle(0), 5) @@ -565,104 +552,98 @@ def test9(self): child1, child2 = instance.get_children_of_particle([6]) self.assertEqual(child2[0], instance.particles[2]) self.assertEqual(child1[0], instance.particles[4]) - + def test10(self): - convert_nbody=nbody_system.nbody_to_si(1.0|units.MSun, 1.0|units.yr/(2.0*pi)) - + convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.yr/(2.0*pi)) + instance = Mikkola(convert_nbody) instance.parameters.maximum_number_of_particles = 2 stars = datamodel.Stars(3) stars[0].mass = 1.0 | units.MSun - stars[0].radius = 1.0| units.RSun + stars[0].radius = 1.0 | units.RSun stars[0].position = [0.0, 0, 0] | units.km - stars[0].velocity = [0.0,0.0,0.0] | units.km/units.s + stars[0].velocity = [0.0, 0.0, 0.0] | units.km/units.s stars[1].mass = 1.0 | units.MSun - stars[1].radius = 1.0| units.RSun + stars[1].radius = 1.0 | units.RSun stars[1].position = [0.1, 0, 0] | units.RSun stars[1].velocity = [-0.4, 0.0, 0.0] | units.km/units.s - - + stars[2].mass = 0.01 | units.MSun - stars[2].radius = 1.0| units.RSun + stars[2].radius = 1.0 | units.RSun stars[2].position = [6000, 0, 0] | units.RSun stars[2].velocity = [0.0, -10, 0.0] | units.km/units.s - - self.assertRaises(exceptions.AmuseException, instance.particles.add_particles, stars) - + + self.assertRaises(exceptions.AmuseException, instance.particles.add_particles, stars) + def test10b(self): - convert_nbody=nbody_system.nbody_to_si(1.0|units.MSun, 1.0|units.yr/(2.0*pi)) - + convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.yr/(2.0*pi)) + instance = Mikkola(convert_nbody) instance.parameters.maximum_number_of_particles = 3 stars = datamodel.Stars(3) stars[0].mass = 1.0 | units.MSun - stars[0].radius = 1.0| units.RSun + stars[0].radius = 1.0 | units.RSun stars[0].position = [0.0, 0, 0] | units.km - stars[0].velocity = [0.0,0.0,0.0] | units.km/units.s + stars[0].velocity = [0.0, 0.0, 0.0] | units.km/units.s stars[1].mass = 1.0 | units.MSun - stars[1].radius = 1.0| units.RSun + stars[1].radius = 1.0 | units.RSun stars[1].position = [0.1, 0, 0] | units.RSun stars[1].velocity = [-0.4, 0.0, 0.0] | units.km/units.s - - + stars[2].mass = 0.01 | units.MSun - stars[2].radius = 1.0| units.RSun + stars[2].radius = 1.0 | units.RSun stars[2].position = [6000, 0, 0] | units.RSun stars[2].velocity = [0.0, -10, 0.0] | units.km/units.s instance.particles.add_particles(stars) - self.assertRaises(exceptions.AmuseException, instance.evolve_model, 0.3 | units.yr) - - + self.assertRaises(exceptions.AmuseException, instance.evolve_model, 0.3 | units.yr) + def test11(self): instance = Mikkola() - + self.assertTrue(instance.parameters.evolve_to_exact_time) instance.parameters.evolve_to_exact_time = False self.assertFalse(instance.parameters.evolve_to_exact_time) - + self.assertEqual(instance.parameters.maximum_number_of_particles, 100) instance.parameters.maximum_number_of_particles = 200 self.assertEqual(instance.parameters.maximum_number_of_particles, 200) - - + self.assertAlmostRelativeEquals(instance.parameters.tolerance, 1e-13, 6) instance.parameters.tolerance = 1e-10 self.assertAlmostRelativeEquals(instance.parameters.tolerance, 1e-10) - + instance.stop() - - + def test12(self): - convert_nbody=nbody_system.nbody_to_si(1.0|units.MSun, 1.0|units.yr/(2.0*pi)) - + convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.yr/(2.0*pi)) + instance = Mikkola(convert_nbody) - + stars = datamodel.Stars(4) stars[0].mass = 1.0 | units.MSun - stars[0].radius = 1.0| units.RSun + stars[0].radius = 1.0 | units.RSun stars[0].position = [0.0, 0, 0] | units.km - stars[0].velocity = [0.0,0.0,0.0] | units.km/units.s + stars[0].velocity = [0.0, 0.0, 0.0] | units.km/units.s stars[1].mass = 1.0 | units.MSun - stars[1].radius = 1.0| units.RSun + stars[1].radius = 1.0 | units.RSun stars[1].position = [0.1, 0, 0] | units.RSun stars[1].velocity = [-0.4, 0.0, 0.0] | units.km/units.s - + stars[2].mass = 1.0 | units.MSun - stars[2].radius = 1.0| units.RSun + stars[2].radius = 1.0 | units.RSun stars[2].position = [2, 0, 0] | units.RSun stars[2].velocity = [-0.1, 0.0, 0.0] | units.km/units.s - + stars[3].mass = 0.01 | units.MSun - stars[3].radius = 1.0| units.RSun + stars[3].radius = 1.0 | units.RSun stars[3].position = [6000, 0, 0] | units.RSun stars[3].velocity = [0.0, -10, 0.0] | units.km/units.s - - + instance.particles.add_particles(stars) - + instance.evolve_model(0.000001 | units.yr) instance.update_particle_set() self.assertEqual(instance.get_number_of_particles_added(), 1) @@ -677,117 +658,111 @@ def test12(self): child1, child2 = instance.get_children_of_particle([6]) self.assertEqual(child1[0], instance.particles[2]) self.assertEqual(child2[0], instance.particles[4]) - - + def test13(self): - convert_nbody=nbody_system.nbody_to_si(1.0|units.MSun, 1.0|units.yr/(2.0*pi)) - + convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.yr/(2.0*pi)) + instance = Mikkola(convert_nbody) stars = datamodel.Stars(2) stars[0].mass = 1.0 | units.MSun - stars[0].radius = 1.0| units.RSun + stars[0].radius = 1.0 | units.RSun stars[0].position = [0.0, 0, 0] | units.km - stars[0].velocity = [0.0,0.0,0.0] | units.km/units.s + stars[0].velocity = [0.0, 0.0, 0.0] | units.km/units.s stars[1].mass = 1.0 | units.MSun - stars[1].radius = 1.0| units.RSun + stars[1].radius = 1.0 | units.RSun stars[1].position = [0.1, 0, 0] | units.RSun stars[1].velocity = [-0.4, 0.0, 0.0] | units.km/units.s - - + instance.particles.add_particles(stars) - self.assertRaises(exceptions.AmuseException, instance.evolve_model, 0.3 | units.yr) - self.assertEqual(instance.get_number_of_particles_added(), 1) + self.assertRaises(exceptions.AmuseException, instance.evolve_model, 0.3 | units.yr) + self.assertEqual(instance.get_number_of_particles_added(), 1) self.assertEqual(instance.get_id_of_added_particle(0), 3) instance.update_particle_set() child1, child2 = instance.get_children_of_particle([3]) self.assertEqual(child1[0], instance.particles[0]) self.assertEqual(child2[0], instance.particles[1]) self.assertAlmostRelativeEquals(instance.get_mass(3), 2 | units.MSun) - + def test14(self): - - convert_nbody=nbody_system.nbody_to_si(1.0|units.MSun, 1.0|units.yr/(2.0*pi)) + + convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.yr/(2.0*pi)) stars = datamodel.Stars(3) stars[0].mass = 1.0 | units.MSun - stars[0].radius = 1.0| units.RSun + stars[0].radius = 1.0 | units.RSun stars[0].position = [0.0, 0, 0] | units.km - stars[0].velocity = [0.0,0.0,0.0] | units.km/units.s + stars[0].velocity = [0.0, 0.0, 0.0] | units.km/units.s stars[1].mass = 1.0 | units.MSun - stars[1].radius = 1.0| units.RSun + stars[1].radius = 1.0 | units.RSun stars[1].position = [0.1, 0, 0] | units.RSun stars[1].velocity = [-0.4, 0.0, 0.0] | units.km/units.s - - + stars[2].mass = 1e-9 | units.MSun - stars[2].radius = 1.0| units.RSun + stars[2].radius = 1.0 | units.RSun stars[2].position = [10000, 0, 0] | units.RSun stars[2].velocity = [0.0, -100, 0.0] | units.km/units.s - - + instance = Mikkola(convert_nbody) instance.particles.add_particles(stars) instance.evolve_model(0.3 | units.yr) - + pos11 = quantities.as_vector_quantity(instance.get_position(1)) pos12 = quantities.as_vector_quantity(instance.get_position(2)) instance.stop() - - convert_nbody=nbody_system.nbody_to_si(1.0|units.MSun, 1.0|units.yr/(2.0*pi)) - + + convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.yr/(2.0*pi)) + instance = Mikkola(convert_nbody) stars = datamodel.Stars(2) stars[0].mass = 1.0 | units.MSun - stars[0].radius = 1.0| units.RSun + stars[0].radius = 1.0 | units.RSun stars[0].position = [0.0, 0, 0] | units.km - stars[0].velocity = [0.0,0.0,0.0] | units.km/units.s + stars[0].velocity = [0.0, 0.0, 0.0] | units.km/units.s stars[1].mass = 1.0 | units.MSun - stars[1].radius = 1.0| units.RSun + stars[1].radius = 1.0 | units.RSun stars[1].position = [0.1, 0, 0] | units.RSun stars[1].velocity = [-0.4, 0.0, 0.0] | units.km/units.s - - + instance.particles.add_particles(stars) - self.assertRaises(exceptions.AmuseException, instance.evolve_model, 0.3 | units.yr) + self.assertRaises(exceptions.AmuseException, instance.evolve_model, 0.3 | units.yr) pos21 = quantities.as_vector_quantity(instance.get_position(1)) pos22 = quantities.as_vector_quantity(instance.get_position(2)) instance.stop() - + # positions will not be the same but distances will be comparable self.assertAlmostRelativeEquals((pos22-pos21).length(), (pos12-pos11).length(), 1) - + def test15(self): - convert_nbody=nbody_system.nbody_to_si(1.0|units.MSun, 1.0|units.yr/(2.0*pi)) - + convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.yr/(2.0*pi)) + instance = Mikkola(convert_nbody) stars = datamodel.Stars(2) stars[0].mass = 1.0 | units.MSun - stars[0].radius = 1.0| units.RSun + stars[0].radius = 1.0 | units.RSun stars[0].position = [0.0, 0, 0] | units.km - stars[0].velocity = [0.0,0.0,0.0] | units.km/units.s + stars[0].velocity = [0.0, 0.0, 0.0] | units.km/units.s stars[1].mass = 1.0 | units.MSun - stars[1].radius = 1.0| units.RSun + stars[1].radius = 1.0 | units.RSun stars[1].position = [0.1, 0, 0] | units.RSun stars[1].velocity = [-0.4, 0.0, 0.0] | units.km/units.s - - + instance.particles.add_particles(stars) try: - instance.evolve_model(0.3 | units.yr) + instance.evolve_model(0.3 | units.yr) except exceptions.AmuseException as ex: self.assertEqual(ex.errorcode, -4) - + def test16(self): particles = datamodel.Particles(3) - particles.mass = [0.1,0.1, 0.0001] | nbody_system.mass + particles.mass = [0.1, 0.1, 0.0001] | nbody_system.mass particles.radius = [0.3, 0.3, 0.1] | nbody_system.length particles.x = [-0.5, 0.5, 10] | nbody_system.length particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length - particles.velocity = [0,0,0] | nbody_system.speed + particles.velocity = [0, 0, 0] | nbody_system.speed particles[-1].vy = 10 | nbody_system.speed instance = Mikkola() instance.initialize_code() diff --git a/src/amuse/test/suite/codes_tests/test_mmams.py b/src/amuse/test/suite/codes_tests/test_mmams.py index 46f4b505ef..264df41367 100644 --- a/src/amuse/test/suite/codes_tests/test_mmams.py +++ b/src/amuse/test/suite/codes_tests/test_mmams.py @@ -13,11 +13,12 @@ from amuse.datamodel import Particles, Particle, ParticlesSubset # Change the default for some MMAMS(-Interface) keyword arguments: -#default_options = dict(redirection="none") +# default_options = dict(redirection="none") default_options = dict() + class TestMMAMSInterface(TestWithMPI): - + def test1(self): print("Test 1: initialization of the interface") instance = MMAMSInterface(**default_options) @@ -26,7 +27,7 @@ def test1(self): error = instance.commit_parameters() self.assertEqual(error, 0) instance.stop() - + def test2(self): print("Test 2: define a new particle") instance = MMAMSInterface(**default_options) @@ -41,17 +42,17 @@ def test2(self): n_particles, error = instance.get_number_of_particles() self.assertEqual(error, 0) self.assertEqual(n_particles, 4) - - error = instance.add_shell([1, 1, 1, 1], [1.0, 2.0, 3.0, 3.0], - [2.0, 4.0, 6.0, 6.0], [3.0, 6.0, 9.0, 9.0], [4.0, 8.0, 12.0, 12.0], - [5.0, 10.0, 15.0, 15.0], [6.0, 12.0, 18.0, 18.0], - [-6.0, -12.0, -18.0, -18.0], [7.0, 14.0, 21.0, 21.0], - [0.4, 0.2, 0.4, 0.4], [0.2, 0.4, 0.2, 0.2], [0.15, 0.1, 0.1, 0.1], - [0.1, 0.15, 0.15, 0.15], [0.05, 0.01, 0.01, 0.01], - [0.04, 0.02, 0.02, 0.02], [0.03, 0.03, 0.03, 0.03], + + error = instance.add_shell([1, 1, 1, 1], [1.0, 2.0, 3.0, 3.0], + [2.0, 4.0, 6.0, 6.0], [3.0, 6.0, 9.0, 9.0], [4.0, 8.0, 12.0, 12.0], + [5.0, 10.0, 15.0, 15.0], [6.0, 12.0, 18.0, 18.0], + [-6.0, -12.0, -18.0, -18.0], [7.0, 14.0, 21.0, 21.0], + [0.4, 0.2, 0.4, 0.4], [0.2, 0.4, 0.2, 0.2], [0.15, 0.1, 0.1, 0.1], + [0.1, 0.15, 0.15, 0.15], [0.05, 0.01, 0.01, 0.01], + [0.04, 0.02, 0.02, 0.02], [0.03, 0.03, 0.03, 0.03], [0.02, 0.04, 0.04, 0.04], [0.01, 0.05, 0.05, 0.05]) self.assertEqual(error, [0, 0, 0, 0]) - + number_of_shells, error = instance.get_number_of_zones(1) self.assertEqual(error, 0) self.assertEqual(number_of_shells, 3) @@ -77,7 +78,7 @@ def test2(self): self.assertEqual(Si28, [0.02, 0.04, 0.04]) self.assertEqual(Fe56, [0.01, 0.05, 0.05]) instance.stop() - + def test3(self): print("Test 3: read a new particle from a usm file") instance = MMAMSInterface(**default_options) @@ -90,15 +91,15 @@ def test3(self): id, error = instance.new_particle([2.0, 3.0]) self.assertEqual(error, [0, 0]) self.assertEqual(id, [1, 2]) - + n_particles, error = instance.get_number_of_particles() self.assertEqual(error, 0) self.assertEqual(n_particles, 3) - + number_of_shells, error = instance.get_number_of_zones([0, 1, 2]) self.assertEqual(error, [0, 0, 0]) self.assertEqual(number_of_shells, [187, 0, 0]) - + d_mass, mass, radius, density, pressure, entropy, temperature, luminosity, \ molecular_weight, H1, He4, C12, N14, O16, Ne20, Mg24, Si28, Fe56, \ error = instance.get_stellar_model_element([0, 186, 0, 0], [0, 0, 1, 3]) @@ -112,7 +113,7 @@ def test3(self): self.assertAlmostEqual(H1[0], 0.0121, 4) self.assertAlmostEqual(H1[1], 0.7, 4) instance.stop() - + def slowtest4(self): print("Test 4: merge particles (from usm files)") instance = MMAMSInterface(**default_options) @@ -123,25 +124,25 @@ def slowtest4(self): id, error = instance.read_usm(usm_file) self.assertEqual(error, 0) self.assertEqual(id, 0) - + usm_file = os.path.join(instance.data_directory, 'secondary.usm') id, error = instance.read_usm(usm_file) self.assertEqual(error, 0) self.assertEqual(id, 1) - + id, error = instance.merge_two_stars(0, 1) self.assertEqual(error, 0) self.assertEqual(id, 2) - + n_particles, error = instance.get_number_of_particles() self.assertEqual(error, 0) self.assertEqual(n_particles, 3) - + number_of_shells, error = instance.get_number_of_zones([0, 1, 2]) self.assertEqual(error, [0, 0, 0]) self.assertEqual(number_of_shells[:2], [187, 181]) self.assertIsOfOrder(number_of_shells[2], 10000) - + d_mass, mass, radius, density, pressure, entropy, temperature, luminosity, \ molecular_weight, H1, He4, C12, N14, O16, Ne20, Mg24, Si28, Fe56, \ error = instance.get_stellar_model_element([0, 10000, 12288], [2, 2, 2]) @@ -151,13 +152,13 @@ def slowtest4(self): self.assertAlmostEqual(temperature, [38998355.9, 3478242.6, 49264.9], 0) self.assertAlmostEqual(H1, [0.61562, 0.69999, 0.70000], 4) instance.stop() - + def test5(self): print("Test 5: parameters") instance = MMAMSInterface(**default_options) self.assertEqual(instance.initialize_code(), 0) self.assertEqual(instance.commit_parameters(), 0) - + dump_mixed_flag, error = instance.get_dump_mixed_flag() self.assertEqual(error, 0) self.assertEqual(dump_mixed_flag, 1) @@ -165,7 +166,7 @@ def test5(self): dump_mixed_flag, error = instance.get_dump_mixed_flag() self.assertEqual(error, 0) self.assertEqual(dump_mixed_flag, 0) - + target_n_shells_mixing, error = instance.get_target_n_shells_mixing() self.assertEqual(error, 0) self.assertEqual(target_n_shells_mixing, 200) @@ -173,7 +174,7 @@ def test5(self): target_n_shells_mixing, error = instance.get_target_n_shells_mixing() self.assertEqual(error, 0) self.assertEqual(target_n_shells_mixing, 300) - + target_n_shells, error = instance.get_target_n_shells() self.assertEqual(error, 0) self.assertEqual(target_n_shells, 10000) @@ -181,7 +182,7 @@ def test5(self): target_n_shells, error = instance.get_target_n_shells() self.assertEqual(error, 0) self.assertEqual(target_n_shells, 5000) - + do_shock_heating_flag, error = instance.get_do_shock_heating_flag() self.assertEqual(error, 0) self.assertEqual(do_shock_heating_flag, 1) @@ -190,10 +191,10 @@ def test5(self): self.assertEqual(error, 0) self.assertEqual(do_shock_heating_flag, 0) instance.stop() - + class TestMMAMS(TestWithMPI): - + def test1(self): print("Test 1: initialization of the interface") instance = MMAMS(**default_options) @@ -202,42 +203,42 @@ def test1(self): instance.recommit_parameters() instance.cleanup_code() instance.stop() - + def test2(self): print("Test 2: define a new particle") stars = Particles(4) stars.mass = [1.0, 2.0, 3.0, 4.0] | units.MSun - + instance = MMAMS(**default_options) instance.initialize_code() instance.commit_parameters() instance.particles.add_particle(stars[0]) instance.particles.add_particles(stars[1:]) self.assertEqual(instance.number_of_particles, 4) - - instance.particles[1].add_shell([1.0, 2.0]|units.MSun, [2.0, 4.0]|units.MSun, [3.0, 6.0]|units.RSun, - [4.0, 8.0]|units.g / units.cm**3, [5.0, 10.0]|units.barye, - [6.0, 12.0]|units.K, [-6.0, -12.0]|units.LSun, [7.0, 14.0]|units.amu, [0.4, 0.2], - [0.2, 0.4], [0.15, 0.1], [0.1, 0.15], - [0.05, 0.01], [0.04, 0.02], [0.03, 0.03], + + instance.particles[1].add_shell([1.0, 2.0] | units.MSun, [2.0, 4.0] | units.MSun, [3.0, 6.0] | units.RSun, + [4.0, 8.0] | units.g / units.cm**3, [5.0, 10.0] | units.barye, + [6.0, 12.0] | units.K, [-6.0, -12.0] | units.LSun, [7.0, 14.0] | units.amu, [0.4, 0.2], + [0.2, 0.4], [0.15, 0.1], [0.1, 0.15], + [0.05, 0.01], [0.04, 0.02], [0.03, 0.03], [0.02, 0.04], [0.01, 0.05]) self.assertEqual(instance.particles[1].number_of_zones, 2) stellar_model = instance.particles[1].get_internal_structure() - self.assertTrue(set(['d_mass', 'mass', 'radius', 'rho', 'pressure', 'entropy', - 'temperature', 'luminosity', 'molecular_weight', 'X_H', 'X_He', 'X_C', + self.assertTrue(set(['d_mass', 'mass', 'radius', 'rho', 'pressure', 'entropy', + 'temperature', 'luminosity', 'molecular_weight', 'X_H', 'X_He', 'X_C', 'X_N', 'X_O', 'X_Ne', 'X_Mg', 'X_Si', 'X_Fe']).issubset( stellar_model.all_attributes() ) ) - self.assertEqual(stellar_model.d_mass, [1.0, 2.0]|units.MSun) - self.assertEqual(stellar_model.mass, [2.0, 4.0]|units.MSun) - self.assertEqual(stellar_model.radius, [3.0, 6.0]|units.RSun) - self.assertEqual(stellar_model.rho, [4.0, 8.0]|units.g / units.cm**3) - self.assertEqual(stellar_model.pressure, [5.0, 10.0]|units.barye) + self.assertEqual(stellar_model.d_mass, [1.0, 2.0] | units.MSun) + self.assertEqual(stellar_model.mass, [2.0, 4.0] | units.MSun) + self.assertEqual(stellar_model.radius, [3.0, 6.0] | units.RSun) + self.assertEqual(stellar_model.rho, [4.0, 8.0] | units.g / units.cm**3) + self.assertEqual(stellar_model.pressure, [5.0, 10.0] | units.barye) self.assertAlmostEqual(stellar_model.entropy, [407038297.689, 256418059.686], 2) - self.assertEqual(stellar_model.temperature, [6.0, 12.0]|units.K) - self.assertEqual(stellar_model.luminosity, [-6.0, -12.0]|units.LSun) - self.assertEqual(stellar_model.molecular_weight, [7.0, 14.0]|units.amu) + self.assertEqual(stellar_model.temperature, [6.0, 12.0] | units.K) + self.assertEqual(stellar_model.luminosity, [-6.0, -12.0] | units.LSun) + self.assertEqual(stellar_model.molecular_weight, [7.0, 14.0] | units.amu) self.assertEqual(stellar_model.X_H, [0.4, 0.2]) self.assertEqual(stellar_model.X_He, [0.2, 0.4]) self.assertEqual(stellar_model.X_C, [0.15, 0.1]) @@ -248,25 +249,25 @@ def test2(self): self.assertEqual(stellar_model.X_Si, [0.02, 0.04]) self.assertEqual(stellar_model.X_Fe, [0.01, 0.05]) instance.stop() - + def test3(self): print("Test 3: read a new particle from a usm file") instance = MMAMS(**default_options) instance.initialize_code() instance.commit_parameters() - + stars = Particles(4) - stars.usm_file = [os.path.join(instance.data_directory, filename) for + stars.usm_file = [os.path.join(instance.data_directory, filename) for filename in ['primary.usm', 'secondary.usm', '', '']] stars[2:].mass = [3.0, 4.0] | units.MSun instance.imported_stars.add_particles(stars[:2]) - + instance.particles.add_particles(stars[2:]) self.assertEqual(instance.number_of_particles, 4) self.assertEqual(instance.native_stars.number_of_zones, [0, 0]) self.assertEqual(instance.imported_stars.number_of_zones, [187, 181]) self.assertEqual(instance.particles.number_of_zones, [0, 0, 187, 181]) - + stellar_model = instance.imported_stars[0].get_internal_structure() self.assertAlmostEqual(stellar_model.mass[0], 0.0 | units.MSun, 3) self.assertAlmostEqual(stellar_model.mass[-1], 20.0 | units.MSun, 0) @@ -278,7 +279,7 @@ def test3(self): self.assertAlmostEqual(stellar_model.X_H[-1], 0.7, 4) self.assertAlmostRelativeEqual(instance.particles.mass, [3.0, 4.0, 20.0, 8.0] | units.MSun, 2) instance.stop() - + def slowtest4(self): print("Test 4: merge particles (from usm files)") # instance = MMAMS(debugger = 'gdb', **default_options) @@ -286,31 +287,31 @@ def slowtest4(self): instance.initialize_code() instance.parameters.dump_mixed_flag = False instance.commit_parameters() - + stars = Particles(2) - stars.usm_file = [os.path.join(instance.data_directory, filename) for + stars.usm_file = [os.path.join(instance.data_directory, filename) for filename in ['primary.usm', 'secondary.usm']] instance.imported_stars.add_particles(stars) - + merge_product = Particle() merge_product.primary = instance.imported_stars[0] merge_product.secondary = instance.imported_stars[1] instance.merge_products.add_particle(merge_product) self.assertEqual(instance.number_of_particles, 3) self.assertEqual(instance.particles.number_of_zones, [187, 181, 12289]) - + stellar_model = instance.merge_products[0].get_internal_structure() self.assertAlmostEqual(stellar_model.mass[[0, 10000, 12288]], [0.0, 24.5169, 25.6762] | units.MSun, 3) self.assertAlmostEqual(stellar_model.radius[[0, 10000, 12288]], [0.0, 10.3786, 19.3713] | units.RSun, 3) self.assertAlmostEqual(stellar_model.temperature[[0, 10000, 12288]], [38998355.9, 3478242.6, 49264.9] | units.K, 0) self.assertAlmostEqual(stellar_model.X_H[[0, 10000, 12288]], [0.61562, 0.69999, 0.70000] | units.none, 4) instance.stop() - + def test5(self): print("Test 5: parameters") instance = MMAMS(**default_options) instance.initialize_code() - + for par, value in [('dump_mixed_flag', True), ('do_shock_heating_flag', True), ('create_new_key', True)]: print("1", instance.parameters) @@ -318,68 +319,68 @@ def test5(self): setattr(instance.parameters, par, not value) print("2", instance.parameters) self.assertFalse(value is getattr(instance.parameters, par)) - + for par, value in [('target_n_shells_mixing', 200), ('target_n_shells', 10000)]: self.assertEqual(value, getattr(instance.parameters, par)) setattr(instance.parameters, par, 1) self.assertEqual(1, getattr(instance.parameters, par)) - + instance.stop() - + def slowtest6(self): print("Test 6: MMAMS with MESA particles - match composition only") stars = Particles(2) stars.mass = [20.0, 8.0] | units.MSun - + instance = MMAMS(**default_options) instance.initialize_code() instance.parameters.dump_mixed_flag = False instance.commit_parameters() instance.particles.add_particles(stars) self.assertEqual(instance.number_of_particles, 2) - + stellar_evolution = self.new_instance(MESA) if stellar_evolution is None: print("MESA was not built. Skipping test.") return - stellar_evolution.initialize_code() + stellar_evolution.initialize_code() stellar_evolution.commit_parameters() stellar_evolution.particles.add_particles(stars) stellar_evolution.commit_particles() stellar_evolution.evolve_model(2 | units.Myr) - + stellar_model = [None, None] for i in [0, 1]: - number_of_zones = stellar_evolution.particles[i].get_number_of_zones() - mass_profile = stellar_evolution.particles[i].get_mass_profile( - number_of_zones = number_of_zones) * stellar_evolution.particles[i].mass - cumul_mass_profile = stellar_evolution.particles[i].get_cumulative_mass_profile( - number_of_zones = number_of_zones) * stellar_evolution.particles[i].mass - density_profile = stellar_evolution.particles[i].get_density_profile(number_of_zones = number_of_zones) - radius_profile = stellar_evolution.particles[i].get_radius_profile(number_of_zones = number_of_zones) - temperature_profile = stellar_evolution.particles[i].get_temperature_profile(number_of_zones = number_of_zones) - pressure_profile = stellar_evolution.particles[i].get_pressure_profile(number_of_zones = number_of_zones) - luminosity_profile = stellar_evolution.particles[i].get_luminosity_profile(number_of_zones = number_of_zones) - mu_profile = stellar_evolution.particles[i].get_mu_profile(number_of_zones = number_of_zones) - composition_profile = stellar_evolution.particles[i].get_chemical_abundance_profiles(number_of_zones = number_of_zones) - species_names = stellar_evolution.particles[i].get_names_of_species() + number_of_zones = stellar_evolution.particles[i].get_number_of_zones() + mass_profile = stellar_evolution.particles[i].get_mass_profile( + number_of_zones=number_of_zones) * stellar_evolution.particles[i].mass + cumul_mass_profile = stellar_evolution.particles[i].get_cumulative_mass_profile( + number_of_zones=number_of_zones) * stellar_evolution.particles[i].mass + density_profile = stellar_evolution.particles[i].get_density_profile(number_of_zones=number_of_zones) + radius_profile = stellar_evolution.particles[i].get_radius_profile(number_of_zones=number_of_zones) + temperature_profile = stellar_evolution.particles[i].get_temperature_profile(number_of_zones=number_of_zones) + pressure_profile = stellar_evolution.particles[i].get_pressure_profile(number_of_zones=number_of_zones) + luminosity_profile = stellar_evolution.particles[i].get_luminosity_profile(number_of_zones=number_of_zones) + mu_profile = stellar_evolution.particles[i].get_mu_profile(number_of_zones=number_of_zones) + composition_profile = stellar_evolution.particles[i].get_chemical_abundance_profiles(number_of_zones=number_of_zones) + species_names = stellar_evolution.particles[i].get_names_of_species() self.assertEqual(species_names, ['h1', 'he3', 'he4', 'c12', 'n14', 'o16', 'ne20', 'mg24']) - - instance.particles[i].add_shell(mass_profile, cumul_mass_profile, radius_profile, density_profile, - pressure_profile, temperature_profile, luminosity_profile, mu_profile, composition_profile[0], - composition_profile[1]+composition_profile[2], composition_profile[3], - composition_profile[4], composition_profile[5], composition_profile[6], + + instance.particles[i].add_shell(mass_profile, cumul_mass_profile, radius_profile, density_profile, + pressure_profile, temperature_profile, luminosity_profile, mu_profile, composition_profile[0], + composition_profile[1]+composition_profile[2], composition_profile[3], + composition_profile[4], composition_profile[5], composition_profile[6], composition_profile[7], composition_profile[7]*0.0, composition_profile[7]*0.0) - + self.assertEqual(instance.particles[i].number_of_zones, number_of_zones) stellar_model[i] = instance.particles[i].get_internal_structure() - self.assertTrue(set(['d_mass', 'mass', 'radius', 'rho', 'pressure', - 'entropy', 'temperature', 'luminosity', 'molecular_weight', 'X_H', 'X_He', 'X_C', + self.assertTrue(set(['d_mass', 'mass', 'radius', 'rho', 'pressure', + 'entropy', 'temperature', 'luminosity', 'molecular_weight', 'X_H', 'X_He', 'X_C', 'X_N', 'X_O', 'X_Ne', 'X_Mg', 'X_Si', 'X_Fe']).issubset( stellar_model[i].all_attributes() ) ) - + self.assertAlmostEqual(stellar_model[0].mass[0], 0.0 | units.MSun, 3) self.assertAlmostEqual(stellar_model[0].mass[-1], 20.0 | units.MSun, 0) self.assertAlmostEqual(stellar_model[0].radius[0], 0.0 | units.RSun, 1) @@ -388,7 +389,7 @@ def slowtest6(self): self.assertAlmostRelativeEqual(stellar_model[0].temperature[-1], 33533.7 | units.K, 2) self.assertAlmostEqual(stellar_model[0].X_H[0], 0.58642 | units.none, 2) self.assertAlmostEqual(stellar_model[0].X_H[-1], 0.7 | units.none, 2) - + self.assertEqual(instance.number_of_particles, 2) merge_product = Particle() merge_product.primary = instance.particles[0] @@ -396,59 +397,59 @@ def slowtest6(self): instance.merge_products.add_particle(merge_product) self.assertEqual(instance.number_of_particles, 3) self.assertIsOfOrder(instance.parameters.target_n_shells, instance.merge_products[0].number_of_zones) - + stellar_model = instance.merge_products[0].get_internal_structure() self.assertAlmostEqual(stellar_model.mass[[0, -1]], [0.0, 25.7] | units.MSun, 1) self.assertAlmostEqual(stellar_model.radius[[0, -1]], [0.0, 8.4] | units.RSun, 1) - + merged = Particle() merged.mass = stellar_model.mass[-1] merged_in_code = stellar_evolution.native_stars.add_particle(merged) - stellar_evolution.evolve_model(keep_synchronous = False) + stellar_evolution.evolve_model(keep_synchronous=False) mass_profile = merged_in_code.get_cumulative_mass_profile()*merged.mass new_composition = instance.match_composition_to_mass_profile(stellar_model, mass_profile) - + cumulative_mass = [0.0] | units.MSun cumulative_mass.extend(stellar_model.mass) original_hydrogen_mass = (stellar_model.X_H * (cumulative_mass[1:] - cumulative_mass[:-1])).sum() instance.stop() - + cumulative_mass = [0.0] | units.MSun cumulative_mass.extend(mass_profile) new_hydrogen_mass = (new_composition[0] * (cumulative_mass[1:] - cumulative_mass[:-1])).sum() - - self.assertEqual(len(new_composition), 8) # MESA species: H, He3, He4, C, N, O, Ne, Mg + + self.assertEqual(len(new_composition), 8) # MESA species: H, He3, He4, C, N, O, Ne, Mg self.assertEqual(len(new_composition[0]), len(mass_profile)) self.assertAlmostEqual(new_composition.sum(axis=0), 1.0) self.assertAlmostEqual(new_hydrogen_mass, original_hydrogen_mass) - + merged_in_code.set_chemical_abundance_profiles(new_composition) for i in range(4): - stellar_evolution.evolve_model(keep_synchronous = False) + stellar_evolution.evolve_model(keep_synchronous=False) print(stellar_evolution.particles) - + stellar_evolution.stop() - + def slowtest7(self): print("Test 7: MMAMS with MESA particles - import product into MESA") stars = Particles(2) stars.mass = [20.0, 8.0] | units.MSun - + stellar_evolution = self.new_instance(MESA) if stellar_evolution is None: print("MESA was not built. Skipping test.") return - stellar_evolution.initialize_code() + stellar_evolution.initialize_code() stellar_evolution.commit_parameters() stellar_evolution.particles.add_particles(stars) stellar_evolution.commit_particles() stellar_evolution.evolve_model(2 | units.Myr) - + if os.path.exists(os.path.join(get_path_to_results(), "test_mmams_7.pkl")): - # Remove the next line to speed-up, and only test MESA loading the merger product - os.remove(os.path.join(get_path_to_results(), "test_mmams_7.pkl")) - print("", end=' ') - + # Remove the next line to speed-up, and only test MESA loading the merger product + os.remove(os.path.join(get_path_to_results(), "test_mmams_7.pkl")) + print("", end=' ') + if os.path.exists(os.path.join(get_path_to_results(), "test_mmams_7.pkl")): with open(os.path.join(get_path_to_results(), "test_mmams_7.pkl"), 'r') as in_file: stellar_model = pickle.load(in_file) @@ -460,39 +461,39 @@ def slowtest7(self): instance.commit_parameters() instance.particles.add_particles(stars) self.assertEqual(instance.number_of_particles, 2) - + stellar_model = [None, None] for i in [0, 1]: - number_of_zones = stellar_evolution.particles[i].get_number_of_zones() - mass_profile = stellar_evolution.particles[i].get_mass_profile( - number_of_zones = number_of_zones) * stellar_evolution.particles[i].mass - cumul_mass_profile = stellar_evolution.particles[i].get_cumulative_mass_profile( - number_of_zones = number_of_zones) * stellar_evolution.particles[i].mass - density_profile = stellar_evolution.particles[i].get_density_profile(number_of_zones = number_of_zones) - radius_profile = stellar_evolution.particles[i].get_radius_profile(number_of_zones = number_of_zones) - temperature_profile = stellar_evolution.particles[i].get_temperature_profile(number_of_zones = number_of_zones) - pressure_profile = stellar_evolution.particles[i].get_pressure_profile(number_of_zones = number_of_zones) - luminosity_profile = stellar_evolution.particles[i].get_luminosity_profile(number_of_zones = number_of_zones) - mu_profile = stellar_evolution.particles[i].get_mu_profile(number_of_zones = number_of_zones) - composition_profile = stellar_evolution.particles[i].get_chemical_abundance_profiles(number_of_zones = number_of_zones) - species_names = stellar_evolution.particles[i].get_names_of_species() + number_of_zones = stellar_evolution.particles[i].get_number_of_zones() + mass_profile = stellar_evolution.particles[i].get_mass_profile( + number_of_zones=number_of_zones) * stellar_evolution.particles[i].mass + cumul_mass_profile = stellar_evolution.particles[i].get_cumulative_mass_profile( + number_of_zones=number_of_zones) * stellar_evolution.particles[i].mass + density_profile = stellar_evolution.particles[i].get_density_profile(number_of_zones=number_of_zones) + radius_profile = stellar_evolution.particles[i].get_radius_profile(number_of_zones=number_of_zones) + temperature_profile = stellar_evolution.particles[i].get_temperature_profile(number_of_zones=number_of_zones) + pressure_profile = stellar_evolution.particles[i].get_pressure_profile(number_of_zones=number_of_zones) + luminosity_profile = stellar_evolution.particles[i].get_luminosity_profile(number_of_zones=number_of_zones) + mu_profile = stellar_evolution.particles[i].get_mu_profile(number_of_zones=number_of_zones) + composition_profile = stellar_evolution.particles[i].get_chemical_abundance_profiles(number_of_zones=number_of_zones) + species_names = stellar_evolution.particles[i].get_names_of_species() self.assertEqual(species_names, ['h1', 'he3', 'he4', 'c12', 'n14', 'o16', 'ne20', 'mg24']) - - instance.particles[i].add_shell(mass_profile, cumul_mass_profile, radius_profile, density_profile, - pressure_profile, temperature_profile, luminosity_profile, mu_profile, composition_profile[0], - composition_profile[1]+composition_profile[2], composition_profile[3], - composition_profile[4], composition_profile[5], composition_profile[6], + + instance.particles[i].add_shell(mass_profile, cumul_mass_profile, radius_profile, density_profile, + pressure_profile, temperature_profile, luminosity_profile, mu_profile, composition_profile[0], + composition_profile[1]+composition_profile[2], composition_profile[3], + composition_profile[4], composition_profile[5], composition_profile[6], composition_profile[7], composition_profile[7]*0.0, composition_profile[7]*0.0) - + self.assertEqual(instance.particles[i].number_of_zones, number_of_zones) stellar_model[i] = instance.particles[i].get_internal_structure() - self.assertTrue(set(['d_mass', 'mass', 'radius', 'rho', 'pressure', - 'entropy', 'temperature', 'luminosity', 'molecular_weight', 'X_H', 'X_He', 'X_C', + self.assertTrue(set(['d_mass', 'mass', 'radius', 'rho', 'pressure', + 'entropy', 'temperature', 'luminosity', 'molecular_weight', 'X_H', 'X_He', 'X_C', 'X_N', 'X_O', 'X_Ne', 'X_Mg', 'X_Si', 'X_Fe']).issubset( stellar_model[i].all_attributes() ) ) - + self.assertAlmostEqual(stellar_model[0].mass[0], 0.0 | units.MSun, 3) self.assertAlmostEqual(stellar_model[0].mass[-1], 20.0 | units.MSun, 0) self.assertAlmostEqual(stellar_model[0].radius[0], 0.0 | units.RSun, 1) @@ -501,7 +502,7 @@ def slowtest7(self): self.assertAlmostRelativeEqual(stellar_model[0].temperature[-1], 33533.7 | units.K, 2) self.assertAlmostEqual(stellar_model[0].X_H[0], 0.58642 | units.none, 2) self.assertAlmostEqual(stellar_model[0].X_H[-1], 0.7 | units.none, 4) - + self.assertEqual(instance.number_of_particles, 2) merge_product = Particle() merge_product.primary = instance.particles[0] @@ -509,28 +510,28 @@ def slowtest7(self): instance.merge_products.add_particle(merge_product) self.assertEqual(instance.number_of_particles, 3) self.assertIsOfOrder(instance.parameters.target_n_shells_mixing, instance.merge_products[0].number_of_zones) - + mmams_merged_model = instance.merge_products[0].get_internal_structure() stellar_model = dict( - mass = mmams_merged_model.mass, - radius = mmams_merged_model.radius, - rho = mmams_merged_model.rho, - temperature = mmams_merged_model.temperature, - luminosity = mmams_merged_model.luminosity, - X_H = mmams_merged_model.X_H, - X_He = mmams_merged_model.X_He, - X_C = mmams_merged_model.X_C, - X_N = mmams_merged_model.X_N, - X_O = mmams_merged_model.X_O, - X_Ne = mmams_merged_model.X_Ne, - X_Mg = mmams_merged_model.X_Mg, - X_Si = mmams_merged_model.X_Si, - X_Fe = mmams_merged_model.X_Fe + mass=mmams_merged_model.mass, + radius=mmams_merged_model.radius, + rho=mmams_merged_model.rho, + temperature=mmams_merged_model.temperature, + luminosity=mmams_merged_model.luminosity, + X_H=mmams_merged_model.X_H, + X_He=mmams_merged_model.X_He, + X_C=mmams_merged_model.X_C, + X_N=mmams_merged_model.X_N, + X_O=mmams_merged_model.X_O, + X_Ne=mmams_merged_model.X_Ne, + X_Mg=mmams_merged_model.X_Mg, + X_Si=mmams_merged_model.X_Si, + X_Fe=mmams_merged_model.X_Fe ) instance.stop() with open(os.path.join(get_path_to_results(), "test_mmams_7.pkl"), 'w') as out_file: pickle.dump(stellar_model, out_file) - + print(stellar_model['mass'][[0, -1]]) print(stellar_model['radius'][[0, -1]]) print(stellar_model['X_H'][[0, -1]]) @@ -540,82 +541,82 @@ def slowtest7(self): stellar_evolution.new_particle_from_model(stellar_model, 10.0 | units.Myr) print(stellar_evolution.particles) for i in range(10): - stellar_evolution.evolve_model(keep_synchronous = False) + stellar_evolution.evolve_model(keep_synchronous=False) print(stellar_evolution.particles) stellar_evolution.stop() - + def slowtest8(self): print("Test 8: MMAMS with MESA particles - multiple mergers") number_of_stars = 4 stars = Particles(number_of_stars) stars.mass = range(20, 20+number_of_stars) | units.MSun - + stellar_evolution = self.new_instance(MESA) if stellar_evolution is None: print("MESA was not built. Skipping test.") return - stellar_evolution.initialize_code() + stellar_evolution.initialize_code() stellar_evolution.commit_parameters() stellar_evolution.particles.add_particles(stars) stellar_evolution.commit_particles() stellar_evolution.evolve_model(0.1 | units.Myr) - + instance = MMAMS(**default_options) instance.initialize_code() instance.commit_parameters() - + while len(stellar_evolution.particles) > 1: to_be_merged = [stellar_evolution.particles[len(stellar_evolution.particles)-1], stellar_evolution.particles[len(stellar_evolution.particles)-2]] print("Merging particles with mass", to_be_merged[0].mass, "and", to_be_merged[1].mass) - + merge_product = Particle() for i in [0, 1]: - number_of_zones = to_be_merged[i].get_number_of_zones() - mass_profile = to_be_merged[i].get_mass_profile() * to_be_merged[i].mass - cumul_mass_profile = to_be_merged[i].get_cumulative_mass_profile() * to_be_merged[i].mass - density_profile = to_be_merged[i].get_density_profile(number_of_zones = number_of_zones) - radius_profile = to_be_merged[i].get_radius_profile(number_of_zones = number_of_zones) - temperature_profile = to_be_merged[i].get_temperature_profile(number_of_zones = number_of_zones) - pressure_profile = to_be_merged[i].get_pressure_profile(number_of_zones = number_of_zones) - luminosity_profile = to_be_merged[i].get_luminosity_profile(number_of_zones = number_of_zones) - mu_profile = to_be_merged[i].get_mu_profile(number_of_zones = number_of_zones) - composition_profile = to_be_merged[i].get_chemical_abundance_profiles(number_of_zones = number_of_zones) - species_names = to_be_merged[i].get_names_of_species() - + number_of_zones = to_be_merged[i].get_number_of_zones() + mass_profile = to_be_merged[i].get_mass_profile() * to_be_merged[i].mass + cumul_mass_profile = to_be_merged[i].get_cumulative_mass_profile() * to_be_merged[i].mass + density_profile = to_be_merged[i].get_density_profile(number_of_zones=number_of_zones) + radius_profile = to_be_merged[i].get_radius_profile(number_of_zones=number_of_zones) + temperature_profile = to_be_merged[i].get_temperature_profile(number_of_zones=number_of_zones) + pressure_profile = to_be_merged[i].get_pressure_profile(number_of_zones=number_of_zones) + luminosity_profile = to_be_merged[i].get_luminosity_profile(number_of_zones=number_of_zones) + mu_profile = to_be_merged[i].get_mu_profile(number_of_zones=number_of_zones) + composition_profile = to_be_merged[i].get_chemical_abundance_profiles(number_of_zones=number_of_zones) + species_names = to_be_merged[i].get_names_of_species() + new_mmams_particle = instance.native_stars.add_particle(to_be_merged[i]) stellar_evolution.particles.remove_particle(to_be_merged[i]) - new_mmams_particle.add_shell(mass_profile, cumul_mass_profile, radius_profile, density_profile, - pressure_profile, temperature_profile, luminosity_profile, mu_profile, composition_profile[0], - composition_profile[1]+composition_profile[2], composition_profile[3], - composition_profile[4], composition_profile[5], composition_profile[6], + new_mmams_particle.add_shell(mass_profile, cumul_mass_profile, radius_profile, density_profile, + pressure_profile, temperature_profile, luminosity_profile, mu_profile, composition_profile[0], + composition_profile[1]+composition_profile[2], composition_profile[3], + composition_profile[4], composition_profile[5], composition_profile[6], composition_profile[7], composition_profile[7]*0.0, composition_profile[7]*0.0) self.assertEqual(new_mmams_particle.number_of_zones, number_of_zones) if i == 0: merge_product.primary = new_mmams_particle else: merge_product.secondary = new_mmams_particle - + self.assertEqual(len(instance.merge_products)+len(stellar_evolution.particles), number_of_stars-2) new_merge_product = instance.merge_products.add_particle(merge_product) print("Successfully merged particles. number_of_zones:", new_merge_product.number_of_zones) self.assertEqual(len(instance.merge_products)+len(stellar_evolution.particles), number_of_stars-1) - + new_merge_product_model = new_merge_product.get_internal_structure() stellar_evolution.new_particle_from_model(new_merge_product_model, 0 | units.yr) print(stellar_evolution.particles) self.assertEqual(len(instance.merge_products)+len(stellar_evolution.particles), number_of_stars) for i in range(10): - stellar_evolution.evolve_model(keep_synchronous = False) + stellar_evolution.evolve_model(keep_synchronous=False) print(stellar_evolution.particles) stellar_evolution.stop() instance.stop() - + def slowtest9(self): print("Test 9: MMAMS with MESA particles - evolved stars") stars = Particles(2) stars.mass = [20.0, 8.0] | units.MSun - + stellar_evolution = self.new_instance(MESA) if stellar_evolution is None: print("MESA was not built. Skipping test.") @@ -631,79 +632,79 @@ def slowtest9(self): stellar_evolution.particles[1].evolve_for(stellar_evolution.particles[0].age) print("Evolved stars to", stellar_evolution.particles.age) print("Radius:", stellar_evolution.particles.radius) - + instance = MMAMS(**default_options) instance.initialize_code() instance.parameters.dump_mixed_flag = True instance.commit_parameters() instance.particles.add_particles(stars) self.assertEqual(instance.number_of_particles, 2) - + stellar_model = [None, None] for i in [0, 1]: - number_of_zones = stellar_evolution.particles[i].get_number_of_zones() - mass_profile = stellar_evolution.particles[i].get_mass_profile( - number_of_zones = number_of_zones) * stellar_evolution.particles[i].mass - cumul_mass_profile = stellar_evolution.particles[i].get_cumulative_mass_profile( - number_of_zones = number_of_zones) * stellar_evolution.particles[i].mass - density_profile = stellar_evolution.particles[i].get_density_profile(number_of_zones = number_of_zones) - radius_profile = stellar_evolution.particles[i].get_radius_profile(number_of_zones = number_of_zones) - temperature_profile = stellar_evolution.particles[i].get_temperature_profile(number_of_zones = number_of_zones) - luminosity_profile = stellar_evolution.particles[i].get_luminosity_profile(number_of_zones = number_of_zones) - mu_profile = stellar_evolution.particles[i].get_mu_profile(number_of_zones = number_of_zones) - pressure_profile = stellar_evolution.particles[i].get_pressure_profile(number_of_zones = number_of_zones) - composition_profile = stellar_evolution.particles[i].get_chemical_abundance_profiles(number_of_zones = number_of_zones) - species_names = stellar_evolution.particles[i].get_names_of_species() + number_of_zones = stellar_evolution.particles[i].get_number_of_zones() + mass_profile = stellar_evolution.particles[i].get_mass_profile( + number_of_zones=number_of_zones) * stellar_evolution.particles[i].mass + cumul_mass_profile = stellar_evolution.particles[i].get_cumulative_mass_profile( + number_of_zones=number_of_zones) * stellar_evolution.particles[i].mass + density_profile = stellar_evolution.particles[i].get_density_profile(number_of_zones=number_of_zones) + radius_profile = stellar_evolution.particles[i].get_radius_profile(number_of_zones=number_of_zones) + temperature_profile = stellar_evolution.particles[i].get_temperature_profile(number_of_zones=number_of_zones) + luminosity_profile = stellar_evolution.particles[i].get_luminosity_profile(number_of_zones=number_of_zones) + mu_profile = stellar_evolution.particles[i].get_mu_profile(number_of_zones=number_of_zones) + pressure_profile = stellar_evolution.particles[i].get_pressure_profile(number_of_zones=number_of_zones) + composition_profile = stellar_evolution.particles[i].get_chemical_abundance_profiles(number_of_zones=number_of_zones) + species_names = stellar_evolution.particles[i].get_names_of_species() self.assertEqual(species_names, ['h1', 'he3', 'he4', 'c12', 'n14', 'o16', 'ne20', 'mg24', 'si28', 's32', ''][:-(1+2*i)]) - - instance.particles[i].add_shell(mass_profile, cumul_mass_profile, radius_profile, density_profile, - pressure_profile, temperature_profile, luminosity_profile, mu_profile, composition_profile[0], - composition_profile[1]+composition_profile[2], composition_profile[3], - composition_profile[4], composition_profile[5], composition_profile[6], + + instance.particles[i].add_shell(mass_profile, cumul_mass_profile, radius_profile, density_profile, + pressure_profile, temperature_profile, luminosity_profile, mu_profile, composition_profile[0], + composition_profile[1]+composition_profile[2], composition_profile[3], + composition_profile[4], composition_profile[5], composition_profile[6], composition_profile[7], composition_profile[7]*0.0, composition_profile[7]*0.0) - + self.assertEqual(instance.particles[i].number_of_zones, number_of_zones) stellar_model[i] = instance.particles[i].get_internal_structure() - self.assertTrue(set(['d_mass', 'mass', 'radius', 'rho', 'pressure', - 'entropy', 'temperature', 'luminosity', 'molecular_weight', 'X_H', 'X_He', 'X_C', + self.assertTrue(set(['d_mass', 'mass', 'radius', 'rho', 'pressure', + 'entropy', 'temperature', 'luminosity', 'molecular_weight', 'X_H', 'X_He', 'X_C', 'X_N', 'X_O', 'X_Ne', 'X_Mg', 'X_Si', 'X_Fe']).issubset( stellar_model[i].all_attributes() ) ) - + print(stellar_model[0].mass[[0, -1]]) print(stellar_model[0].radius[[0, -1]]) print(stellar_model[0].X_H[[0, -1]]) - + self.assertEqual(instance.number_of_particles, 2) merge_product = Particle() merge_product.primary = instance.particles[0] merge_product.secondary = instance.particles[1] instance.merge_products.add_particle(merge_product) self.assertEqual(instance.number_of_particles, 3) - + mmams_merged_model = instance.merge_products[0].get_internal_structure() print(mmams_merged_model.mass[[0, -1]]) print(mmams_merged_model.radius[[0, -1]]) print(mmams_merged_model.X_H[[0, -1]]) stellar_model = dict( - mass = mmams_merged_model.mass, - radius = mmams_merged_model.radius, - rho = mmams_merged_model.rho, - temperature = mmams_merged_model.temperature, - luminosity = mmams_merged_model.luminosity, - X_H = mmams_merged_model.X_H, - X_He = mmams_merged_model.X_He, - X_C = mmams_merged_model.X_C, - X_N = mmams_merged_model.X_N, - X_O = mmams_merged_model.X_O, - X_Ne = mmams_merged_model.X_Ne, - X_Mg = mmams_merged_model.X_Mg, - X_Si = mmams_merged_model.X_Si, - X_Fe = mmams_merged_model.X_Fe + mass=mmams_merged_model.mass, + radius=mmams_merged_model.radius, + rho=mmams_merged_model.rho, + temperature=mmams_merged_model.temperature, + luminosity=mmams_merged_model.luminosity, + X_H=mmams_merged_model.X_H, + X_He=mmams_merged_model.X_He, + X_C=mmams_merged_model.X_C, + X_N=mmams_merged_model.X_N, + X_O=mmams_merged_model.X_O, + X_Ne=mmams_merged_model.X_Ne, + X_Mg=mmams_merged_model.X_Mg, + X_Si=mmams_merged_model.X_Si, + X_Fe=mmams_merged_model.X_Fe ) instance.stop() - + stellar_evolution.parameters.min_timestep_stop_condition = 1.0e-6 | units.s merged_in_code = stellar_evolution.new_particle_from_model(stellar_model, 0.0 | units.Myr) stellar_evolution.particles.remove_particles(stars) @@ -712,38 +713,38 @@ def slowtest9(self): stellar_evolution.evolve_model() print(stellar_evolution.particles) stellar_evolution.stop() - + def xtest10(self): print("Test 10: MMAMS with EVtwin particles - import product into EVtwin (WIP)") stars = Particles(2) stars.mass = [20.0, 8.0] | units.MSun - + instance = MMAMS(**default_options) instance.initialize_code() instance.parameters.dump_mixed_flag = True instance.commit_parameters() instance.particles.add_particles(stars) self.assertEqual(instance.number_of_particles, 2) - + stellar_evolution = EVtwin(redirection="none") - stellar_evolution.initialize_code() + stellar_evolution.initialize_code() stellar_evolution.commit_parameters() stellar_evolution.particles.add_particles(stars) stellar_evolution.commit_particles() stellar_evolution.evolve_model(2 | units.Myr) print(stellar_evolution.particles) - + for i in [0, 1]: stellar_model = stellar_evolution.particles[i].get_internal_structure() instance.particles[i].add_shell( - stellar_model.d_mass, stellar_model.mass, stellar_model.radius, - stellar_model.rho, stellar_model.pressure, stellar_model.temperature, - stellar_model.luminosity, stellar_model.molecular_weight, stellar_model.X_H, - stellar_model.X_He, stellar_model.X_C, stellar_model.X_N, stellar_model.X_O, + stellar_model.d_mass, stellar_model.mass, stellar_model.radius, + stellar_model.rho, stellar_model.pressure, stellar_model.temperature, + stellar_model.luminosity, stellar_model.molecular_weight, stellar_model.X_H, + stellar_model.X_He, stellar_model.X_C, stellar_model.X_N, stellar_model.X_O, stellar_model.X_Ne, stellar_model.X_Mg, stellar_model.X_Si, stellar_model.X_Fe ) self.assertEqual(instance.particles[i].number_of_zones, len(stellar_model)) - + self.assertEqual(instance.number_of_particles, 2) merge_product = Particle() merge_product.primary = instance.particles[0] @@ -752,27 +753,27 @@ def xtest10(self): self.assertEqual(instance.number_of_particles, 3) self.assertEqual(instance.native_stars.number_of_zones, [199, 199]) self.assertIsOfOrder(instance.merge_products[0].number_of_zones, instance.parameters.target_n_shells_mixing) - + stellar_model = instance.merge_products[0].get_internal_structure() print(stellar_model.mass[[0, -1]]) print(stellar_model.radius[[0, -1]]) print(stellar_model.X_H[[0, -1]]) - + stellar_evolution.new_particle_from_model(stellar_model, 10.0 | units.Myr) instance.stop() print(stellar_evolution.particles) for i in range(10): - stellar_evolution.evolve_model(keep_synchronous = False) + stellar_evolution.evolve_model(keep_synchronous=False) print(stellar_evolution.particles) stellar_evolution.stop() - + def slowtest11(self): print("Test 11: MMAMS with MESA particles of various masses/ages") masses = [1.0, 5.0, 20.0, 42.0, 80.0, 200.0] | units.MSun number_of_stars = len(masses) stars = Particles(number_of_stars) stars.mass = masses - + stellar_evolution = self.new_instance(MESA) if stellar_evolution is None: print("MESA was not built. Skipping test.") @@ -780,35 +781,35 @@ def slowtest11(self): stellar_evolution.parameters.metallicity = 0.0 mesa_particles = stellar_evolution.particles.add_particles(stars) stellar_evolution.evolve_model(1.5 | units.Myr) - + mesa_models = [] for i in range(number_of_stars): - number_of_zones = mesa_particles[i].get_number_of_zones() - mass_profile = mesa_particles[i].get_mass_profile( - number_of_zones = number_of_zones) * mesa_particles[i].mass - cumul_mass_profile = mesa_particles[i].get_cumulative_mass_profile( - number_of_zones = number_of_zones) * mesa_particles[i].mass - density_profile = mesa_particles[i].get_density_profile(number_of_zones = number_of_zones) - radius_profile = mesa_particles[i].get_radius_profile(number_of_zones = number_of_zones) - temperature_profile = mesa_particles[i].get_temperature_profile(number_of_zones = number_of_zones) - pressure_profile = mesa_particles[i].get_pressure_profile(number_of_zones = number_of_zones) - luminosity_profile = mesa_particles[i].get_luminosity_profile(number_of_zones = number_of_zones) - mu_profile = mesa_particles[i].get_mu_profile(number_of_zones = number_of_zones) - composition_profile = mesa_particles[i].get_chemical_abundance_profiles(number_of_zones = number_of_zones) - - mesa_models.append((mass_profile, cumul_mass_profile, radius_profile, density_profile, - pressure_profile, temperature_profile, luminosity_profile, mu_profile, composition_profile[0], - composition_profile[1]+composition_profile[2], composition_profile[3], - composition_profile[4], composition_profile[5], composition_profile[6], + number_of_zones = mesa_particles[i].get_number_of_zones() + mass_profile = mesa_particles[i].get_mass_profile( + number_of_zones=number_of_zones) * mesa_particles[i].mass + cumul_mass_profile = mesa_particles[i].get_cumulative_mass_profile( + number_of_zones=number_of_zones) * mesa_particles[i].mass + density_profile = mesa_particles[i].get_density_profile(number_of_zones=number_of_zones) + radius_profile = mesa_particles[i].get_radius_profile(number_of_zones=number_of_zones) + temperature_profile = mesa_particles[i].get_temperature_profile(number_of_zones=number_of_zones) + pressure_profile = mesa_particles[i].get_pressure_profile(number_of_zones=number_of_zones) + luminosity_profile = mesa_particles[i].get_luminosity_profile(number_of_zones=number_of_zones) + mu_profile = mesa_particles[i].get_mu_profile(number_of_zones=number_of_zones) + composition_profile = mesa_particles[i].get_chemical_abundance_profiles(number_of_zones=number_of_zones) + + mesa_models.append((mass_profile, cumul_mass_profile, radius_profile, density_profile, + pressure_profile, temperature_profile, luminosity_profile, mu_profile, composition_profile[0], + composition_profile[1]+composition_profile[2], composition_profile[3], + composition_profile[4], composition_profile[5], composition_profile[6], composition_profile[7], composition_profile[7]*0.0, composition_profile[7]*0.0)) - + stellar_evolution.stop() - - instance = MMAMS(**default_options)#debugger = "gdb", **default_options) + + instance = MMAMS(**default_options) # debugger = "gdb", **default_options) instance.initialize_code() instance.parameters.dump_mixed_flag = True instance.commit_parameters() - + stellar_models = [] crashed = False for (index_1, index_2) in itertools.combinations(range(number_of_stars), 2): @@ -816,12 +817,12 @@ def slowtest11(self): print(masses[index_1], masses[index_2]) print() self.assertEqual(instance.number_of_particles, len(stellar_models)) - + colliding = instance.particles.add_particles(stars[[index_1, index_2]]) colliding[0].add_shell(*(mesa_models[index_1])) colliding[1].add_shell(*(mesa_models[index_2])) self.assertEqual(instance.number_of_particles, 2 + len(stellar_models)) - + merge_product = Particle() merge_product.primary = colliding[0] merge_product.secondary = colliding[1] @@ -835,37 +836,37 @@ def slowtest11(self): print(ex) crashed = True break - + if not crashed: instance.stop() - + for stellar_model in stellar_models: print("mass:", stellar_model.mass[-1]) print("radius:", stellar_model.radius[-1]) print("X_H:", stellar_model.X_H[[0, -1]]) - + print("Storing the merger products in", os.path.join(get_path_to_results(), "test_mmams_11.pkl")) mmams_merged_models = [] for mmams_merged_model in stellar_models: mmams_merged_models.append(dict( - mass = mmams_merged_model.mass, - radius = mmams_merged_model.radius, - rho = mmams_merged_model.rho, - temperature = mmams_merged_model.temperature, - luminosity = mmams_merged_model.luminosity, - X_H = mmams_merged_model.X_H, - X_He = mmams_merged_model.X_He, - X_C = mmams_merged_model.X_C, - X_N = mmams_merged_model.X_N, - X_O = mmams_merged_model.X_O, - X_Ne = mmams_merged_model.X_Ne, - X_Mg = mmams_merged_model.X_Mg, - X_Si = mmams_merged_model.X_Si, - X_Fe = mmams_merged_model.X_Fe + mass=mmams_merged_model.mass, + radius=mmams_merged_model.radius, + rho=mmams_merged_model.rho, + temperature=mmams_merged_model.temperature, + luminosity=mmams_merged_model.luminosity, + X_H=mmams_merged_model.X_H, + X_He=mmams_merged_model.X_He, + X_C=mmams_merged_model.X_C, + X_N=mmams_merged_model.X_N, + X_O=mmams_merged_model.X_O, + X_Ne=mmams_merged_model.X_Ne, + X_Mg=mmams_merged_model.X_Mg, + X_Si=mmams_merged_model.X_Si, + X_Fe=mmams_merged_model.X_Fe )) with open(os.path.join(get_path_to_results(), "test_mmams_11.pkl"), 'w') as out_file: pickle.dump(mmams_merged_models, out_file) - + def slowtest11b(self): print("Test 11b: Continue the stellar evolution of the products from test 11 with MESA") if os.path.exists(os.path.join(get_path_to_results(), "test_mmams_11.pkl")): @@ -874,12 +875,12 @@ def slowtest11b(self): else: return print(len(stellar_models)) - + stellar_evolution = self.new_instance(MESA) if stellar_evolution is None: print("MESA was not built. Skipping test.") return - stellar_evolution.initialize_code() + stellar_evolution.initialize_code() stellar_evolution.parameters.metallicity = 0.0 stellar_evolution.commit_parameters() for i, stellar_model in enumerate(stellar_models): @@ -890,14 +891,14 @@ def slowtest11b(self): print(stellar_evolution.particles) stellar_evolution.evolve_model(1000 | units.yr) print(stellar_evolution.particles) - + stellar_evolution.stop() - + def test12(self): print("Test 12: merge particles, as fast/crude as possible") stars = Particles(2) stars.mass = [1.0, 2.0] | units.MSun - + instance = MMAMS(**default_options) instance.initialize_code() instance.parameters.target_n_shells = 100 @@ -906,7 +907,7 @@ def test12(self): instance.commit_parameters() instance.particles.add_particles(stars) self.assertEqual(instance.number_of_particles, 2) - + d_mass = [0.25]*4 | units.MSun cumul_mass = d_mass.accumulate() radius = ([0.0]+[0.25]*4 | units.RSun).accumulate() @@ -919,15 +920,15 @@ def test12(self): X = [0.75]*4 Y = [0.25]*4 Z = [0.00]*4 - + instance.particles[0].add_shell(d_mass, cumul_mass, radius[1:], density, pressure, temperature, luminosity, mu, X, Y, Z, Z, Z, Z, Z, Z, Z) instance.particles[1].add_shell(d_mass*2, cumul_mass*2, radius[1:], density*2, pressure*4, temperature*2, luminosity, mu, X, Y, Z, Z, Z, Z, Z, Z, Z) self.assertEqual(instance.particles[1].number_of_zones, 4) stellar_model = instance.particles[1].get_internal_structure() - self.assertTrue(set(['d_mass', 'mass', 'radius', 'rho', 'pressure', 'entropy', - 'temperature', 'luminosity', 'molecular_weight', 'X_H', 'X_He', 'X_C', + self.assertTrue(set(['d_mass', 'mass', 'radius', 'rho', 'pressure', 'entropy', + 'temperature', 'luminosity', 'molecular_weight', 'X_H', 'X_He', 'X_C', 'X_N', 'X_O', 'X_Ne', 'X_Mg', 'X_Si', 'X_Fe']).issubset( stellar_model.all_attributes() ) @@ -942,12 +943,13 @@ def test12(self): self.assertTrue(instance.particles[2].number_of_zones > 100) self.assertAlmostEqual(instance.particles[2].mass, 2.7324 | units.MSun, 2) instance.stop() - + class ParticlesForTesting(list): def has_key_in_store(self, key): return key in [x.key for x in self] - def _subset(self, selected, indices = None): + + def _subset(self, selected, indices=None): return ParticlesForTesting([x for x in self if x.key in selected]) def remove_particles(self, particles): @@ -955,6 +957,7 @@ def remove_particles(self, particles): for particle in particles_in_self: self.remove(particle) + class StarParticleWithStructureWithoutGetMassProfile(Particle): def __init__(self, mass, **keyword_arguments): @@ -963,99 +966,100 @@ def __init__(self, mass, **keyword_arguments): def get_number_of_zones(self): return 4 - - def _mass_profile(self, number_of_zones = None): + + def _mass_profile(self, number_of_zones=None): return numpy.asarray([0.25]*4) - - def _cumulative_mass_profile(self, number_of_zones = None): + + def _cumulative_mass_profile(self, number_of_zones=None): return numpy.add.accumulate(self._mass_profile(number_of_zones)) - + def _radii(self): return ([0.0]+[0.25]*4 | units.RSun).accumulate() - def get_radius_profile(self, number_of_zones = None): + + def get_radius_profile(self, number_of_zones=None): return self._radii()[1:] - - def get_density_profile(self, number_of_zones = None): + + def get_density_profile(self, number_of_zones=None): return self._mass_profile() * self.mass / (4.0/3.0 * constants.pi * (self._radii()[1:]**3 - self._radii()[:-1]**3)) - - def get_pressure_profile(self, number_of_zones = None): - return (constants.G * self._cumulative_mass_profile() * self.mass * self.get_density_profile() * + + def get_pressure_profile(self, number_of_zones=None): + return (constants.G * self._cumulative_mass_profile() * self.mass * self.get_density_profile() * (self._radii()[1:] - self._radii()[:-1]) / self._radii()[1:]**2)[::-1].accumulate()[::-1] - - def get_temperature_profile(self, number_of_zones = None): + + def get_temperature_profile(self, number_of_zones=None): return self.get_pressure_profile() * self.get_mu_profile() / (constants.kB * self.get_density_profile()) - - def get_luminosity_profile(self, number_of_zones = None): + + def get_luminosity_profile(self, number_of_zones=None): return [0]*4 | units.LSun - - def get_mu_profile(self, number_of_zones = None): + + def get_mu_profile(self, number_of_zones=None): return (constants.proton_mass * (16.0/27.0)).as_vector_with_length(4) - - def get_chemical_abundance_profiles(self, number_of_zones = None, number_of_species = None): + + def get_chemical_abundance_profiles(self, number_of_zones=None, number_of_species=None): return numpy.asarray([[0.75]*4, [0.25]*4, [0]*4, [0]*4, [0]*4, [0]*4, [0]*4, [0]*4]) + class StarParticleWithStructure(StarParticleWithStructureWithoutGetMassProfile): def __init__(self, mass, **keyword_arguments): Particle.__init__(self, **keyword_arguments) self.mass = mass - - def get_mass_profile(self, number_of_zones = None): + + def get_mass_profile(self, number_of_zones=None): return numpy.asarray([0.25]*4) - - def get_cumulative_mass_profile(self, number_of_zones = None): + + def get_cumulative_mass_profile(self, number_of_zones=None): return numpy.add.accumulate(self.get_mass_profile(number_of_zones)) - + class StellarEvolutionCodeWithInternalStructureForTesting(object): - + def __init__(self, has_get_mass_profile=True): if has_get_mass_profile: self.particles = ParticlesForTesting([ - StarParticleWithStructure(mass=1.0|units.MSun), - StarParticleWithStructure(mass=2.0|units.MSun) + StarParticleWithStructure(mass=1.0 | units.MSun), + StarParticleWithStructure(mass=2.0 | units.MSun) ]) else: self.particles = ParticlesForTesting([ - StarParticleWithStructureWithoutGetMassProfile(mass=1.0|units.MSun), - StarParticleWithStructureWithoutGetMassProfile(mass=2.0|units.MSun) + StarParticleWithStructureWithoutGetMassProfile(mass=1.0 | units.MSun), + StarParticleWithStructureWithoutGetMassProfile(mass=2.0 | units.MSun) ]) - + def new_particle_from_model(self, internal_structure, current_age, key=None): tmp_star = Particle(key=key) tmp_star.mass = internal_structure.mass[-1] tmp_star.radius = internal_structure.radius[-1] self.particles.append(StarParticleWithStructure(mass=tmp_star.mass, key=tmp_star.key)) return tmp_star - + class TestMMAMSWithCollisionHandler(TestWithMPI): - + def test1(self): print("Test 1: MMAMS in CollisionHandler") - self.assertRaises(AmuseException, CollisionHandler, MMAMS, expected_message= - "MMAMS requires a stellar evolution code: CollisionHandler(..., stellar_evolution_code=x)") + self.assertRaises(AmuseException, CollisionHandler, MMAMS, expected_message="MMAMS requires a stellar evolution code: CollisionHandler(..., stellar_evolution_code=x)") handler = CollisionHandler( MMAMS, - stellar_evolution_code = StellarEvolutionCodeWithInternalStructureForTesting(), - verbose = True + stellar_evolution_code=StellarEvolutionCodeWithInternalStructureForTesting(), + verbose=True ) - + def test2(self): print("Test 2: merge particles with CollisionHandler and MMAMS class, as fast/crude as possible") stellar_evolution = StellarEvolutionCodeWithInternalStructureForTesting() self.assertEqual(len(stellar_evolution.particles), 2) handler = CollisionHandler( - MMAMS, - collision_code_parameters = dict( - target_n_shells = 100, - target_n_shells_mixing = 100, - do_shock_heating_flag = False + MMAMS, + collision_code_parameters=dict( + target_n_shells=100, + target_n_shells_mixing=100, + do_shock_heating_flag=False ), - stellar_evolution_code = stellar_evolution, - verbose = True + stellar_evolution_code=stellar_evolution, + verbose=True ) - + merged = handler.handle_collision(stellar_evolution.particles[0], stellar_evolution.particles[1]) self.assertTrue(isinstance(merged, Particles)) self.assertTrue(merged.number_of_zones > 50) @@ -1063,7 +1067,7 @@ def test2(self): self.assertEqual(len(stellar_evolution.particles), 1) self.assertAlmostEqual(stellar_evolution.particles[0].mass, 2.73 | units.MSun, 1) self.assertEqual(handler.collision_code, MMAMS) - + def test3(self): print("Test 3: merge particles with CollisionHandler and MMAMS instance, as fast/crude as possible") stellar_evolution = StellarEvolutionCodeWithInternalStructureForTesting() @@ -1074,11 +1078,11 @@ def test3(self): collision.parameters.do_shock_heating_flag = False collision.commit_parameters() handler = CollisionHandler( - collision, - stellar_evolution_code = stellar_evolution, - verbose = True + collision, + stellar_evolution_code=stellar_evolution, + verbose=True ) - + merged = handler.handle_collision(stellar_evolution.particles[0], stellar_evolution.particles[1]) self.assertTrue(isinstance(merged, ParticlesSubset)) self.assertTrue(merged.number_of_zones > 100) @@ -1089,7 +1093,7 @@ def test3(self): self.assertEqual(handler.collision_code.get_name_of_current_state(), 'INITIALIZED') collision.stop() self.assertEqual(handler.collision_code.get_name_of_current_state(), 'STOPPED') - + def test4(self): print("Test 4: merge particles without get_mass_profile, as fast/crude as possible") stellar_evolution = StellarEvolutionCodeWithInternalStructureForTesting( @@ -1097,16 +1101,16 @@ def test4(self): ) self.assertEqual(len(stellar_evolution.particles), 2) handler = CollisionHandler( - MMAMS, - collision_code_parameters = dict( - target_n_shells = 100, - dump_mixed_flag = False, - do_shock_heating_flag = False + MMAMS, + collision_code_parameters=dict( + target_n_shells=100, + dump_mixed_flag=False, + do_shock_heating_flag=False ), - stellar_evolution_code = stellar_evolution, - verbose = True + stellar_evolution_code=stellar_evolution, + verbose=True ) - + merged = handler.handle_collision(stellar_evolution.particles[0], stellar_evolution.particles[1]) self.assertTrue(isinstance(merged, Particles)) self.assertTrue(merged.number_of_zones > 100) @@ -1114,7 +1118,7 @@ def test4(self): self.assertEqual(len(stellar_evolution.particles), 1) self.assertAlmostRelativeEqual(stellar_evolution.particles[0].mass, 2.73 | units.MSun, 2) self.assertEqual(handler.collision_code, MMAMS) - + def slowtest5(self): print("Test 5: merge MESA particles with CollisionHandler and MMAMS class") stellar_evolution = self.new_instance(MESA) @@ -1122,11 +1126,11 @@ def slowtest5(self): stellar_evolution.evolve_model(2 | units.Myr) self.assertEqual(len(stellar_evolution.particles), 2) handler = CollisionHandler( - MMAMS, - stellar_evolution_code = stellar_evolution, - verbose = True + MMAMS, + stellar_evolution_code=stellar_evolution, + verbose=True ) - + merged = handler.handle_collision(stellar_evolution.particles[0], stellar_evolution.particles[1]) self.assertTrue(isinstance(merged, Particles)) self.assertTrue(merged.number_of_zones > 100) @@ -1136,24 +1140,24 @@ def slowtest5(self): self.assertEqual(handler.collision_code, MMAMS) print(stellar_evolution.particles) for i in range(10): - stellar_evolution.evolve_model(keep_synchronous = False) + stellar_evolution.evolve_model(keep_synchronous=False) print(stellar_evolution.particles) stellar_evolution.stop() - + def slowtest6(self): print("Test 6: merge EVtwin particles with CollisionHandler and MMAMS class") stellar_evolution = EVtwin(redirection="none") stellar_evolution.particles.add_particles(Particles(2, mass=[20.0, 8.0] | units.MSun)) stellar_evolution.evolve_model(2 | units.Myr) self.assertEqual(len(stellar_evolution.particles), 2) - + stellar_evolution.new_particle_from_model = stub handler = CollisionHandler( - MMAMS, - stellar_evolution_code = stellar_evolution, - verbose = True + MMAMS, + stellar_evolution_code=stellar_evolution, + verbose=True ) - + merged = handler.handle_collision(stellar_evolution.particles[0], stellar_evolution.particles[1]) self.assertTrue(isinstance(merged, Particles)) self.assertTrue(merged.number_of_zones > 100) @@ -1163,12 +1167,12 @@ def slowtest6(self): self.assertEqual(handler.collision_code, MMAMS) print(stellar_evolution.particles) for i in range(10): - stellar_evolution.evolve_model(keep_synchronous = False) + stellar_evolution.evolve_model(keep_synchronous=False) print(stellar_evolution.particles) stellar_evolution.stop() - + + def stub(instance, internal_structure, current_age, key=None): tmp_star = Particle(key=key) tmp_star.mass = internal_structure.mass[-1] return instance.native_stars.add_particle(tmp_star) - diff --git a/src/amuse/test/suite/codes_tests/test_mobse.py b/src/amuse/test/suite/codes_tests/test_mobse.py index abc2a218f5..83fa285b13 100644 --- a/src/amuse/test/suite/codes_tests/test_mobse.py +++ b/src/amuse/test/suite/codes_tests/test_mobse.py @@ -7,8 +7,9 @@ import numpy + class TestMOBSEInterface(TestWithMPI): - + class state(object): def __init__(self): self.type1 = 0.0 @@ -19,8 +20,8 @@ def __init__(self): self.mass2 = 0.0 self.radius1 = 0.0 self.radius2 = 0.0 - self.luminosity1 = 0.0 - self.luminosity2 = 0.0 + self.luminosity1 = 0.0 + self.luminosity2 = 0.0 self.core_mass1 = 0.0 self.core_mass2 = 0.0 self.core_radius1 = 0.0 @@ -38,30 +39,30 @@ def __init__(self): self.bse_age = 0.0 self.orbital_period = 0.0 self.eccentricity = 0.0 - + def test1(self): print("Test initialization...") instance = MOBSEInterface() metallicity = 0.02 neta = 0.5 - bwind = 0.0 - hewind = 0.5 + bwind = 0.0 + hewind = 0.5 alpha1 = 1.0 CElambda = 0.1 ceflag = 0 tflag = 1 ifflag = 0 - wdflag = 1 - bhflag = 1 - nsflag = 3 - piflag = 1 - mxns = 3.0 + wdflag = 1 + bhflag = 1 + nsflag = 3 + piflag = 1 + mxns = 3.0 idum = 29769 pts1 = 0.05 pts2 = 0.01 pts3 = 0.02 - sigma1 = 265.0 - sigma2 = 7.0 + sigma1 = 265.0 + sigma2 = 7.0 beta = 1.0/8.0 xi = 1.0 acc2 = 3.0/2.0 @@ -73,16 +74,16 @@ def test1(self): neta, bwind, hewind, alpha1, CElambda, ceflag, tflag, ifflag, wdflag, bhflag, nsflag, piflag, mxns, idum, pts1, pts2, pts3, - sigma1,sigma2,beta,xi,acc2,epsnov,eddfac,gamma) - self.assertEqual(status,0) + sigma1, sigma2, beta, xi, acc2, epsnov, eddfac, gamma) + self.assertEqual(status, 0) instance.stop() - + def test2(self): print("Test basic operations (legacy functions evolve & get_time_step)...") instance = MOBSEInterface() status = instance.initialize(0.02, 0.5, 0.0, 0.5, 1.0, 0.1, 0, 1, 0, 1, 1, 3, 1, 3.0, 29769, 0.05, 0.01, 0.02, 265.0, 7.0, 1.0/8.0, 1.0, 3.0/2.0, 0.001, 1.0, -1.0) - + new_state = self.state() new_state.mass1 = 3.0 new_state.mass2 = 1.0 @@ -93,49 +94,49 @@ def test2(self): new_state.end_time = 1e-06 new_state.orbital_period = 200.0 new_state.eccentricity = 0.5 - + result = instance.evolve_binary( - new_state.type1,new_state.type2,new_state.initial_mass1,new_state.initial_mass2, - new_state.mass1, new_state.mass2, new_state.radius1, new_state.radius2, - new_state.luminosity1, new_state.luminosity2, new_state.core_mass1, + new_state.type1, new_state.type2, new_state.initial_mass1, new_state.initial_mass2, + new_state.mass1, new_state.mass2, new_state.radius1, new_state.radius2, + new_state.luminosity1, new_state.luminosity2, new_state.core_mass1, new_state.core_mass2, new_state.core_radius1, new_state.core_radius2, new_state.envelope_mass1, new_state.envelope_mass2, new_state.envelope_radius1, new_state.envelope_radius2, new_state.spin1, new_state.spin2, new_state.epoch1, new_state.epoch2, new_state.t_ms1, new_state.t_ms2, new_state.bse_age, new_state.orbital_period, new_state.eccentricity, new_state.end_time ) - + updated_state = self.state() - (updated_state.type1,updated_state.type2,updated_state.initial_mass1,updated_state.initial_mass2, - updated_state.mass1, updated_state.mass2, updated_state.radius1, updated_state.radius2, + (updated_state.type1, updated_state.type2, updated_state.initial_mass1, updated_state.initial_mass2, + updated_state.mass1, updated_state.mass2, updated_state.radius1, updated_state.radius2, updated_state.luminosity1, updated_state.luminosity2, updated_state.core_mass1, updated_state.core_mass2, updated_state.core_radius1, updated_state.core_radius2, - updated_state.envelope_mass1,updated_state.envelope_mass2,updated_state.envelope_radius1, + updated_state.envelope_mass1, updated_state.envelope_mass2, updated_state.envelope_radius1, updated_state.envelope_radius2, updated_state.spin1, updated_state.spin2, updated_state.epoch1, updated_state.epoch2, updated_state.t_ms1, updated_state.t_ms2, updated_state.bse_age, updated_state.orbital_period, - updated_state.eccentricity, updated_state.end_time) = result - + updated_state.eccentricity, updated_state.end_time) = result + expected = { - 'radius2' : '0x1.c6c8a1c793bcep-1', - 'luminosity2' : '0x1.653b1b2d0333bp-1', - 'core_mass2' : '0x0.0p+0', - 'bse_age' : '0x1.0c6f7a0b5ed8dp-20', - 'end_time' : '0x1.0c6f7a0b5ed8dp-20', - 'envelope_mass2' : '0x1.0d6fc100ab510p-5', - 'mass2' : '0x1.0000000000000p+0', - 'initial_mass2' : '0x1.0000000000000p+0', - 'envelope_radius2' : '0x1.db27631ba0e5ap-3', - 'core_radius2' : '0x0.0p+0', - 'epoch2' : '0x0.0p+0', - 't_ms2' : '0x1.57d90abe54643p+13', - 'spin2' : '0x1.07413b0522dabp+10', - }; + 'radius2': '0x1.c6c8a1c793bcep-1', + 'luminosity2': '0x1.653b1b2d0333bp-1', + 'core_mass2': '0x0.0p+0', + 'bse_age': '0x1.0c6f7a0b5ed8dp-20', + 'end_time': '0x1.0c6f7a0b5ed8dp-20', + 'envelope_mass2': '0x1.0d6fc100ab510p-5', + 'mass2': '0x1.0000000000000p+0', + 'initial_mass2': '0x1.0000000000000p+0', + 'envelope_radius2': '0x1.db27631ba0e5ap-3', + 'core_radius2': '0x0.0p+0', + 'epoch2': '0x0.0p+0', + 't_ms2': '0x1.57d90abe54643p+13', + 'spin2': '0x1.07413b0522dabp+10', + } for x in expected: print("'%s' : '%s'," % (x, getattr(updated_state, x).hex())) - self.assertAlmostRelativeEqual(float.fromhex(expected[x]),getattr(updated_state, x)) - + self.assertAlmostRelativeEqual(float.fromhex(expected[x]), getattr(updated_state, x)) + self.assertEqual(updated_state.end_time, 1e-06) dt = instance.get_time_step(updated_state.type1, updated_state.type2, updated_state.initial_mass1, updated_state.initial_mass2, updated_state.mass1, @@ -143,25 +144,25 @@ def test2(self): updated_state.epoch1, updated_state.epoch2, updated_state.bse_age) self.assertAlmostEqual(dt, 18.8768, 3) instance.stop() - + def test3(self): print("Test whether the interface can handle arrays...") instance = MOBSEInterface() status = instance.initialize(0.02, 0.5, 0.0, 0.5, 1.0, 0.1, 0, 1, 0, 1, 1, 3, 1, 3.0, 29769, 0.05, 0.01, 0.02, 265.0, 7.0, 1.0/8.0, 1.0, 3.0/2.0, 0.001, 1.0, -1.0) - masses1 = [10.0,5.0,4.0,40.0,130.0] - masses2 = [1.0,1.0,1.0,10.0,60.0] - types1 = types2 = [1,1,1,1,1] - orbital_periods = [100.0,200.0,300.0,500.0,600.0] - eccentricities = [0.5,0.6,0.7,0.3,0.2] - - radii1 = luminosity1 = core_mass1 = core_radius1 = envelope_mass1 =\ - envelope_radius1 = spin1 = epoch1 = t_ms1 = [0.0,0.0,0.0,0.0,0.0] - radii2 = luminosity2 = core_mass2 = core_radius2 = envelope_mass2 =\ - envelope_radius2 = spin2 = epoch2 = t_ms2 = [0.0,0.0,0.0,0.0,0.0] + masses1 = [10.0, 5.0, 4.0, 40.0, 130.0] + masses2 = [1.0, 1.0, 1.0, 10.0, 60.0] + types1 = types2 = [1, 1, 1, 1, 1] + orbital_periods = [100.0, 200.0, 300.0, 500.0, 600.0] + eccentricities = [0.5, 0.6, 0.7, 0.3, 0.2] + + radii1 = luminosity1 = core_mass1 = core_radius1 = envelope_mass1 =\ + envelope_radius1 = spin1 = epoch1 = t_ms1 = [0.0, 0.0, 0.0, 0.0, 0.0] + radii2 = luminosity2 = core_mass2 = core_radius2 = envelope_mass2 =\ + envelope_radius2 = spin2 = epoch2 = t_ms2 = [0.0, 0.0, 0.0, 0.0, 0.0] init_mass1 = masses1 init_mass2 = masses2 - bse_age = [0.0,0.0,0.0,0.0,0.0] + bse_age = [0.0, 0.0, 0.0, 0.0, 0.0] end_time = [10.0, 10.0, 10.0, 10.0, 10.0] result = instance.evolve_binary( types1, types2, init_mass1, init_mass2, @@ -169,7 +170,7 @@ def test3(self): luminosity1, luminosity2, core_mass1, core_mass2, core_radius1, core_radius2, envelope_mass1, envelope_mass2, envelope_radius1, envelope_radius2, spin1, spin2, - epoch1, epoch2, t_ms1, t_ms2, + epoch1, epoch2, t_ms1, t_ms2, bse_age, orbital_periods, eccentricities, end_time ) self.assertAlmostEqual(result['mass1'][0], 9.99356, 2) @@ -178,43 +179,43 @@ def test3(self): self.assertAlmostEqual(result['mass1'][3], 3.07374, 2) self.assertAlmostEqual(result['mass1'][4], 13.61644, 2) instance.stop() - + def test4(self): print("Test large number of particles...") number_of_particles = 2000 instance = MOBSEInterface() status = instance.initialize(0.02, 0.5, 0.0, 0.5, 1.0, 0.1, 0, 1, 0, 1, 1, 3, 1, 3.0, 29769, 0.05, 0.01, 0.02, 265.0, 7.0, 1.0/8.0, 1.0, 3.0/2.0, 0.001, 1.0, -1.0) - masses1 = [1.0 + ((x / 1.0*number_of_particles) * 10.0) for x in range(1,number_of_particles+1)] - masses2 = [2.0 + ((x / 1.0*number_of_particles) * 5.0) for x in range(1,number_of_particles+1)] - orbital_periods = [100.0 + ((x / 1.0*number_of_particles) * 900.0) for x in range(1,number_of_particles+1)] - eccentricities = [0.5 + ((x / 1.0*number_of_particles) * 0.4) for x in range(1,number_of_particles+1)] - - types1 = types2 = [1 for x in range(1,number_of_particles+1)] - radii1 = luminosity1 = core_mass1 = core_radius1 = envelope_mass1 =\ - envelope_radius1 = spin1 = epoch1 = t_ms1 =\ - radii2 = luminosity2 = core_mass2 = core_radius2 = envelope_mass2 =\ - envelope_radius2 = spin2 = epoch2 = t_ms2 =\ - bse_age = [0.0 for x in range(1,number_of_particles+1)] - end_time = [1.0 for x in range(1,number_of_particles+1)] + masses1 = [1.0 + ((x / 1.0*number_of_particles) * 10.0) for x in range(1, number_of_particles+1)] + masses2 = [2.0 + ((x / 1.0*number_of_particles) * 5.0) for x in range(1, number_of_particles+1)] + orbital_periods = [100.0 + ((x / 1.0*number_of_particles) * 900.0) for x in range(1, number_of_particles+1)] + eccentricities = [0.5 + ((x / 1.0*number_of_particles) * 0.4) for x in range(1, number_of_particles+1)] + + types1 = types2 = [1 for x in range(1, number_of_particles+1)] + radii1 = luminosity1 = core_mass1 = core_radius1 = envelope_mass1 =\ + envelope_radius1 = spin1 = epoch1 = t_ms1 =\ + radii2 = luminosity2 = core_mass2 = core_radius2 = envelope_mass2 =\ + envelope_radius2 = spin2 = epoch2 = t_ms2 =\ + bse_age = [0.0 for x in range(1, number_of_particles+1)] + end_time = [1.0 for x in range(1, number_of_particles+1)] init_mass1 = masses1 init_mass2 = masses2 - + result = instance.evolve_binary( types1, types2, init_mass1, init_mass2, masses1, masses2, radii1, radii2, luminosity1, luminosity2, core_mass1, core_mass2, core_radius1, core_radius2, envelope_mass1, envelope_mass2, envelope_radius1, envelope_radius2, spin1, spin2, - epoch1, epoch2, t_ms1, t_ms2, + epoch1, epoch2, t_ms1, t_ms2, bse_age, orbital_periods, eccentricities, end_time ) self.assertEqual(len(result['mass1']), number_of_particles) instance.stop() - + class TestMOBSE(TestWithMPI): - + def test1(self): print("Testing evolution of a close binary system...") instance = MOBSE() @@ -223,35 +224,35 @@ def test1(self): instance.parameters.common_envelope_efficiency = 3.0 instance.parameters.Eddington_mass_transfer_limit_factor = 10.0 instance.commit_parameters() - stars = Particles(2) + stars = Particles(2) stars[0].mass = 3.0 | units.MSun stars[1].mass = 0.3 | units.MSun - + orbital_period = 200.0 | units.day - semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass , stars[1].mass) - + semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass, stars[1].mass) + instance.particles.add_particles(stars) - - binaries = Particles(1) - + + binaries = Particles(1) + binary = binaries[0] binary.semi_major_axis = semi_major_axis binary.eccentricity = 0.5 binary.child1 = stars[0] binary.child2 = stars[1] - + instance.binaries.add_particles(binaries) - + from_mobse_to_model = instance.particles.new_channel_to(stars) from_mobse_to_model.copy() from_mobse_to_model_binaries = instance.binaries.new_channel_to(binaries) from_mobse_to_model_binaries.copy() - + previous_type = binary.child1.stellar_type results = [] current_time = 0 | units.Myr - + while current_time < (480 | units.Myr): instance.update_time_steps() # The next line appears a bit weird, but saves time for this simple test. @@ -262,9 +263,9 @@ def test1(self): if not binary.child1.stellar_type == previous_type: results.append((binary.age, binary.child1.mass, binary.child1.stellar_type)) previous_type = binary.child1.stellar_type - + self.assertEqual(len(results), 6) - + types = ( "Hertzsprung Gap", "First Giant Branch", @@ -273,34 +274,34 @@ def test1(self): "Hertzsprung Gap Naked Helium star", "Carbon/Oxygen White Dwarf", ) - + for result, expected in zip(results, types): self.assertEqual(str(result[2]), expected) - - times = ( - 284.8632 | units.Myr, - 287.0713 | units.Myr, - 287.7967 | units.Myr, - 331.1631 | units.Myr, - 331.4164 | units.Myr, + + times = ( + 284.8632 | units.Myr, + 287.0713 | units.Myr, + 287.7967 | units.Myr, + 331.1631 | units.Myr, + 331.4164 | units.Myr, 332.2864 | units.Myr, ) for result, expected in zip(results, times): self.assertAlmostEqual(result[0].value_in(units.Myr), expected.value_in(units.Myr), 0) - - masses = ( - 3.000 | units.MSun, - 3.000 | units.MSun, - 2.999 | units.MSun, + + masses = ( + 3.000 | units.MSun, + 3.000 | units.MSun, + 2.999 | units.MSun, 2.956 | units.MSun, 0.888 | units.MSun, 0.701 | units.MSun, ) for result, expected in zip(results, masses): self.assertAlmostEqual(result[1].value_in(units.MSun), expected.value_in(units.MSun), 2) - + instance.stop() - + def test2(self): print("Testing evolution of a wide binary system.") instance = MOBSE() @@ -308,35 +309,35 @@ def test2(self): instance.parameters.common_envelope_efficiency = 3.0 instance.parameters.Eddington_mass_transfer_limit_factor = 10.0 instance.commit_parameters() - - stars = Particles(2) + + stars = Particles(2) stars[0].mass = 4.0 | units.MSun stars[1].mass = 0.3 | units.MSun - orbital_period = 2.0e5 | units.day - semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass , stars[1].mass) - + orbital_period = 2.0e5 | units.day + semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass, stars[1].mass) + instance.particles.add_particles(stars) - - binaries = Particles(1) - + + binaries = Particles(1) + binary = binaries[0] binary.semi_major_axis = semi_major_axis binary.eccentricity = 0.5 binary.child1 = stars[0] binary.child2 = stars[1] - + instance.binaries.add_particles(binaries) - + from_mobse_to_model = instance.particles.new_channel_to(stars) from_mobse_to_model.copy() from_mobse_to_model_binaries = instance.binaries.new_channel_to(binaries) from_mobse_to_model_binaries.copy() - + previous_type = binary.child1.stellar_type results = [] current_time = 0 | units.Myr - + while current_time < (170 | units.Myr): instance.update_time_steps() # The next line appears a bit weird, but saves time for this simple test. @@ -349,29 +350,29 @@ def test2(self): previous_type = binary.child1.stellar_type print(results) self.assertEqual(len(results), 6) - - times = ( - 147.1282 | units.Myr, - 148.0345 | units.Myr, - 148.2282 | units.Myr, + + times = ( + 147.1282 | units.Myr, + 148.0345 | units.Myr, + 148.2282 | units.Myr, 167.2811 | units.Myr, 168.0344 | units.Myr, 168.7475 | units.Myr ) for result, expected in zip(results, times): self.assertAlmostEqual(result[0].value_in(units.Myr), expected.value_in(units.Myr), 0) - - masses = ( - 4.000 | units.MSun, - 3.999 | units.MSun, - 3.999 | units.MSun, + + masses = ( + 4.000 | units.MSun, + 3.999 | units.MSun, + 3.999 | units.MSun, 3.942 | units.MSun, 3.906 | units.MSun, 1.016 | units.MSun ) for result, expected in zip(results, masses): self.assertAlmostEqual(result[1].value_in(units.MSun), expected.value_in(units.MSun), 2) - + types = ( "Hertzsprung Gap", "First Giant Branch", @@ -380,73 +381,72 @@ def test2(self): "Second Asymptotic Giant Branch", "Carbon/Oxygen White Dwarf", ) - + for result, expected in zip(results, types): self.assertEqual(str(result[2]), expected) - + instance.stop() - + def test3(self): print("Testing standard MOBSE example 2...") instance = MOBSE() instance.parameters.common_envelope_efficiency = 3.0 - instance.parameters.common_envelope_binding_energy_factor= 0.5 + instance.parameters.common_envelope_binding_energy_factor = 0.5 instance.parameters.Eddington_mass_transfer_limit_factor = 10.0 instance.commit_parameters() - - stars = Particles(2) + + stars = Particles(2) stars[0].mass = 7.816 | units.MSun stars[1].mass = 4.387 | units.MSun - - orbital_period = 1964.18453 | units.day - semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass , stars[1].mass) + + orbital_period = 1964.18453 | units.day + semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass, stars[1].mass) instance.particles.add_particles(stars) - - binaries = Particles(1) - + + binaries = Particles(1) + binary = binaries[0] binary.semi_major_axis = semi_major_axis binary.eccentricity = 0.0 binary.child1 = stars[0] binary.child2 = stars[1] - + instance.binaries.add_particles(binaries) - + from_mobse_to_model = instance.particles.new_channel_to(stars) from_mobse_to_model.copy() from_mobse_to_model_binaries = instance.binaries.new_channel_to(binaries) from_mobse_to_model_binaries.copy() - + previous_type1 = binary.child1.stellar_type previous_type2 = binary.child2.stellar_type results = [] current_time = 0 | units.Myr - + while current_time < (170 | units.Myr): instance.update_time_steps() # The next line appears a bit weird, but saves time for this simple test. current_time = current_time + max(2.0*instance.binaries[0].time_step, 0.04 | units.Myr) instance.evolve_model(current_time) from_mobse_to_model.copy() - from_mobse_to_model_binaries.copy() - if not (binary.child1.stellar_type == previous_type1 and binary.child2.stellar_type == previous_type2): + from_mobse_to_model_binaries.copy() + if not (binary.child1.stellar_type == previous_type1 and binary.child2.stellar_type == previous_type2): results.append((binary.age, str(binary.child1.stellar_type)+" and "+str(binary.child2.stellar_type))) previous_type1 = binary.child1.stellar_type previous_type2 = binary.child2.stellar_type - - + print('\n'.join(map(str, results))) self.assertEqual(len(results), 12) - times = ( - 39.1037 | units.Myr, - 39.2242 | units.Myr, - 39.2565 | units.Myr, + times = ( + 39.1037 | units.Myr, + 39.2242 | units.Myr, + 39.2565 | units.Myr, 43.9911 | units.Myr, 44.1842 | units.Myr, 44.2644 | units.Myr, - 141.8444 | units.Myr, - 142.4835 | units.Myr, + 141.8444 | units.Myr, + 142.4835 | units.Myr, 142.9234 | units.Myr, 166.3238 | units.Myr, 166.8385 | units.Myr, @@ -454,7 +454,7 @@ def test3(self): ) for result, expected in zip(results, times): self.assertAlmostEqual(result[0].value_in(units.Myr), expected.value_in(units.Myr), 0) - + types = ( "Hertzsprung Gap and Main Sequence star", "First Giant Branch and Main Sequence star", @@ -469,47 +469,47 @@ def test3(self): "Oxygen/Neon White Dwarf and Hertzsprung Gap Naked Helium star", "Neutron Star and Carbon/Oxygen White Dwarf", ) - + for result, expected in zip(results, types): self.assertEqual(result[1], expected) - + self.assertAlmostEqual(binary.child1.mass.value_in(units.MSun), 1.26079, 3) self.assertAlmostEqual(binary.child2.mass.value_in(units.MSun), 0.76080, 3) - + instance.stop() - + def test4(self): print("Quick testing standard MOBSE example 2...") instance = MOBSE() instance.parameters.common_envelope_efficiency = 3.0 - instance.parameters.common_envelope_binding_energy_factor= 0.5 + instance.parameters.common_envelope_binding_energy_factor = 0.5 instance.parameters.Eddington_mass_transfer_limit_factor = 10.0 instance.commit_parameters() - - stars = Particles(2) + + stars = Particles(2) stars[0].mass = 7.816 | units.MSun stars[1].mass = 4.387 | units.MSun - + instance.particles.add_particles(stars) - - binaries = Particles(1) - + + binaries = Particles(1) + binary = binaries[0] - orbital_period = 1964.18453 | units.day - semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass , stars[1].mass) + orbital_period = 1964.18453 | units.day + semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass, stars[1].mass) binary.semi_major_axis = semi_major_axis binary.eccentricity = 0.0 binary.child1 = stars[0] binary.child2 = stars[1] - + instance.binaries.add_particles(binaries) - + from_mobse_to_model = instance.particles.new_channel_to(stars) from_mobse_to_model.copy() from_mobse_to_model_binaries = instance.binaries.new_channel_to(binaries) from_mobse_to_model_binaries.copy() - + instance.evolve_model(170 | units.Myr) from_mobse_to_model.copy() from_mobse_to_model_binaries.copy() @@ -520,7 +520,7 @@ def test4(self): self.assertEqual(str(binary.child2.stellar_type), "Carbon/Oxygen White Dwarf") instance.stop() - + def test5(self): print("Testing stellar collision...") instance = MOBSE() @@ -528,32 +528,32 @@ def test5(self): instance.parameters.Eddington_mass_transfer_limit_factor = 10.0 instance.commit_parameters() - stars = Particles(2) - stars[0].mass = 130.0 | units.MSun + stars = Particles(2) + stars[0].mass = 130.0 | units.MSun stars[1].mass = 50 | units.MSun - + instance.particles.add_particles(stars) - - binaries = Particles(1) - + + binaries = Particles(1) + binary = binaries[0] - orbital_period = 300.0 | units.day - semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass , stars[1].mass) + orbital_period = 300.0 | units.day + semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass, stars[1].mass) binary.semi_major_axis = semi_major_axis binary.eccentricity = 0.99 binary.child1 = stars[0] binary.child2 = stars[1] - + instance.binaries.add_particles(binaries) - + from_mobse_to_model = instance.particles.new_channel_to(stars) from_mobse_to_model.copy() from_mobse_to_model_binaries = instance.binaries.new_channel_to(binaries) from_mobse_to_model_binaries.copy() - + instance.evolve_model(170 | units.Myr) - + from_mobse_to_model.copy() from_mobse_to_model_binaries.copy() print(binaries) @@ -575,7 +575,7 @@ def test6(self): instance.commit_parameters() self.assertEqual(instance.parameters.reimers_mass_loss_coefficient, myvalue) instance.stop() - + instance = MOBSE() self.assertEqual(instance.parameters.reimers_mass_loss_coefficient, 0.5) myvalue = 0.7 @@ -584,118 +584,118 @@ def test6(self): instance.commit_parameters() self.assertEqual(instance.parameters.reimers_mass_loss_coefficient, 0.5) instance.stop() - + def test7(self): print("Test evolve_model optional arguments: end_time and keep_synchronous") instance = MOBSE() instance.commit_parameters() - - stars = Particles(6) - stars.mass = [1.0,2.0,3.0, 0.1, 0.2, 0.3] | units.MSun - - binaries = Particles(3) + + stars = Particles(6) + stars.mass = [1.0, 2.0, 3.0, 0.1, 0.2, 0.3] | units.MSun + + binaries = Particles(3) binaries.eccentricity = 0.0 for i in range(3): binaries[i].child1 = stars[i] binaries[i].child2 = stars[i+3] - orbital_period = 200.0 | units.day + orbital_period = 200.0 | units.day semi_major_axis = instance.orbital_period_to_semi_major_axis( - orbital_period, - binaries.child1.as_set().mass , + orbital_period, + binaries.child1.as_set().mass, binaries.child2.as_set().mass ) binaries.semi_major_axis = semi_major_axis - + instance.particles.add_particles(stars) instance.binaries.add_particles(binaries) - + self.assertAlmostEqual(instance.binaries.age, [0.0, 0.0, 0.0] | units.yr) self.assertAlmostEqual(instance.binaries.time_step, [550.1565, 58.2081, 18.8768] | units.Myr, 3) - + print("evolve_model without arguments: use shared timestep = min(particles.time_step)") instance.evolve_model() self.assertAlmostEqual(instance.binaries.age, [18.8768, 18.8768, 18.8768] | units.Myr, 3) self.assertAlmostEqual(instance.binaries.time_step, [550.1565, 58.2081, 18.8768] | units.Myr, 3) self.assertAlmostEqual(instance.model_time, 18.8768 | units.Myr, 3) - + print("evolve_model with end_time: take timesteps, until end_time is reached exactly") instance.evolve_model(100 | units.Myr) self.assertAlmostEqual(instance.binaries.age, [100.0, 100.0, 100.0] | units.Myr, 3) self.assertAlmostEqual(instance.binaries.time_step, [550.1565, 58.2081, 18.8785] | units.Myr, 3) self.assertAlmostEqual(instance.model_time, 100.0 | units.Myr, 3) - + print("evolve_model with keep_synchronous: use non-shared timestep, particle ages will typically diverge") - instance.evolve_model(keep_synchronous = False) + instance.evolve_model(keep_synchronous=False) self.assertAlmostEqual(instance.binaries.age, (100 | units.Myr) + ([550.1565, 58.2081, 18.8785] | units.Myr), 3) self.assertAlmostEqual(instance.binaries.time_step, [550.1565, 58.2081, 18.8785] | units.Myr, 3) - self.assertAlmostEqual(instance.model_time, 100.0 | units.Myr, 3) # Unchanged! + self.assertAlmostEqual(instance.model_time, 100.0 | units.Myr, 3) # Unchanged! instance.stop() - + def test8(self): print("Testing adding and removing particles from stellar evolution code...") - + instance = MOBSE() instance.initialize_code() - - stars = Particles(6) - stars.mass = [1.0,1.0, 1.0, 0.2, 0.2, 0.2] | units.MSun - - binaries = Particles(3) + + stars = Particles(6) + stars.mass = [1.0, 1.0, 1.0, 0.2, 0.2, 0.2] | units.MSun + + binaries = Particles(3) binaries.eccentricity = 0.0 for i in range(3): binaries[i].child1 = stars[i] binaries[i].child2 = stars[i+3] - orbital_period = 200.0 | units.day + orbital_period = 200.0 | units.day semi_major_axis = instance.orbital_period_to_semi_major_axis( - orbital_period, - binaries.child1.as_set().mass , + orbital_period, + binaries.child1.as_set().mass, binaries.child2.as_set().mass ) binaries.semi_major_axis = semi_major_axis instance.commit_parameters() self.assertEqual(len(instance.particles), 0) - self.assertEqual(len(instance.binaries), 0) # before creation + self.assertEqual(len(instance.binaries), 0) # before creation instance.particles.add_particles(stars) instance.binaries.add_particles(binaries[:-1]) instance.commit_particles() instance.evolve_model(1.0 | units.Myr) - self.assertEqual(len(instance.binaries), 2) # before remove + self.assertEqual(len(instance.binaries), 2) # before remove self.assertAlmostEqual(instance.binaries.age, 1.0 | units.Myr) - + instance.binaries.remove_particle(binaries[0]) self.assertEqual(len(instance.binaries), 1) instance.evolve_model(2.0 | units.Myr) self.assertAlmostEqual(instance.binaries[0].age, 2.0 | units.Myr) - + instance.binaries.add_particles(binaries[::2]) - self.assertEqual(len(instance.binaries), 3) # it's back... + self.assertEqual(len(instance.binaries), 3) # it's back... self.assertAlmostEqual(instance.binaries[0].age, 2.0 | units.Myr) self.assertAlmostEqual(instance.binaries[1].age, 0.0 | units.Myr) - self.assertAlmostEqual(instance.binaries[2].age, 0.0 | units.Myr) # ... and rejuvenated. - - instance.evolve_model(3.0 | units.Myr) # The young stars keep their age offset from the old star + self.assertAlmostEqual(instance.binaries[2].age, 0.0 | units.Myr) # ... and rejuvenated. + + instance.evolve_model(3.0 | units.Myr) # The young stars keep their age offset from the old star self.assertAlmostEqual(instance.binaries.age, [3.0, 1.0, 1.0] | units.Myr) instance.evolve_model(4.0 | units.Myr) self.assertAlmostEqual(instance.binaries.age, [4.0, 2.0, 2.0] | units.Myr) instance.stop() - + def test9(self): print("Testing MOBSE states") instance = MOBSE() - - stars = Particles(2) - stars.mass = [1.0, 0.2] | units.MSun - - binaries = Particles(1) - orbital_period = 200.0 | units.day - semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass , stars[1].mass) + + stars = Particles(2) + stars.mass = [1.0, 0.2] | units.MSun + + binaries = Particles(1) + orbital_period = 200.0 | units.day + semi_major_axis = instance.orbital_period_to_semi_major_axis(orbital_period, stars[0].mass, stars[1].mass) binaries.semi_major_axis = semi_major_axis binaries.eccentricity = 0.0 binaries[0].child1 = stars[0] binaries[0].child2 = stars[1] - + print("First do everything manually:", end=' ') self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') instance.initialize_code() @@ -707,7 +707,7 @@ def test9(self): instance.stop() print("ok") - print("initialize_code(), commit_parameters(), " \ + print("initialize_code(), commit_parameters(), " "and cleanup_code() should be called automatically:", end=' ') instance = MOBSE() self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') @@ -719,4 +719,3 @@ def test9(self): instance.stop() self.assertEqual(instance.get_name_of_current_state(), 'STOPPED') print("ok") - diff --git a/src/amuse/test/suite/codes_tests/test_mocassin.py b/src/amuse/test/suite/codes_tests/test_mocassin.py index c3e1da820e..478d768aed 100644 --- a/src/amuse/test/suite/codes_tests/test_mocassin.py +++ b/src/amuse/test/suite/codes_tests/test_mocassin.py @@ -5,42 +5,42 @@ from amuse.community.mocassin.interface import MocassinInterface, Mocassin, mocassin_rydberg_unit import numpy + class TestMocassinInterface(TestWithMPI): - + def test0(self): - instance=self.new_instance_of_an_optional_code(MocassinInterface) + instance = self.new_instance_of_an_optional_code(MocassinInterface) instance.initialize_code() instance.stop() - + def test1(self): - instance=self.new_instance_of_an_optional_code(MocassinInterface) + instance = self.new_instance_of_an_optional_code(MocassinInterface) instance.initialize_code() - #instance.redirect_outputs_to("moc-out.txt", "moc-err.txt") - - instance.setup_mesh(11,11,11, 100,100,100) + # instance.redirect_outputs_to("moc-out.txt", "moc-err.txt") + + instance.setup_mesh(11, 11, 11, 100, 100, 100) instance.setup_abundancies() print(instance.get_default_input_directory()) instance.set_input_directory(instance.get_default_input_directory()) instance.set_constant_hydrogen_density(900.0) instance.commit_parameters() - indices_x = range(1,12,1) - x,y,z,error = instance.get_position_of_index(indices_x,[1]*len(indices_x), [1]*len(indices_x)) - + indices_x = range(1, 12, 1) + x, y, z, error = instance.get_position_of_index(indices_x, [1]*len(indices_x), [1]*len(indices_x)) + self.assertEqual(error, 0) for index, expected_x in enumerate(range(-100, 120, 20)): self.assertAlmostRelativeEqual(x[index], expected_x, 6) self.assertAlmostRelativeEqual(y[index], -100) self.assertAlmostRelativeEqual(z[index], -100) - + instance.stop() - + def test2(self): - instance=self.new_instance_of_an_optional_code(MocassinInterface) #, debugger = "ddd") + instance = self.new_instance_of_an_optional_code(MocassinInterface) # , debugger = "ddd") instance.initialize_code() instance.set_symmetricXYZ(True) - - - instance.setup_mesh(13,13,13,0.95E+19,0.95E+19,0.95E+19) + + instance.setup_mesh(13, 13, 13, 0.95E+19, 0.95E+19, 0.95E+19) instance.setup_abundancies() instance.set_input_directory(instance.get_default_input_directory()) instance.set_constant_hydrogen_density(100.0) @@ -58,43 +58,41 @@ def test2(self): instance.define_stars(0.0, 0.0, 0.0, 20000, 6003.6396) instance.commit_particles() instance.commit_grid() - + x, error = instance.get_number_of_elements_used() self.assertEqual(0, error) self.assertEqual(x, 7) - indices_x = range(1,12,1) - is_active,error = instance.get_grid_active(indices_x,[1]*len(indices_x), [1]*len(indices_x), 1) + indices_x = range(1, 12, 1) + is_active, error = instance.get_grid_active(indices_x, [1]*len(indices_x), [1]*len(indices_x), 1) self.assertEqual(0, error) - is_active=numpy.array(is_active,dtype=bool) - self.assertEqual([True,True,True,True,True,True,True,True,True,True,True] , is_active) - - - indices_x = range(5,12,1) - temperatures,error = instance.get_grid_electron_temperature(indices_x,[1]*len(indices_x), [1]*len(indices_x), 1) + is_active = numpy.array(is_active, dtype=bool) + self.assertEqual([True, True, True, True, True, True, True, True, True, True, True], is_active) + + indices_x = range(5, 12, 1) + temperatures, error = instance.get_grid_electron_temperature(indices_x, [1]*len(indices_x), [1]*len(indices_x), 1) self.assertEqual(0, error) self.assertEqual([6000.0] * len(indices_x), temperatures) - indices_x = range(1,5,1) - temperatures,error = instance.get_grid_electron_temperature(indices_x,[1]*len(indices_x), [1]*len(indices_x), 1) + indices_x = range(1, 5, 1) + temperatures, error = instance.get_grid_electron_temperature(indices_x, [1]*len(indices_x), [1]*len(indices_x), 1) self.assertEqual(0, error) self.assertEqual([6000.0] * len(indices_x), temperatures) - + ni, nj, nk, error = instance.get_max_indices(1) self.assertEqual(0, error) - + self.assertEqual(ni, 13) self.assertEqual(nj, 13) self.assertEqual(nj, 13) instance.stop() - - + def xtest3(self): - instance=self.new_instance_of_an_optional_code(MocassinInterface) #, debugger = "ddd") - #instance.redirect_outputs_to("moc3-out.txt", "moc3-err.txt") + instance = self.new_instance_of_an_optional_code(MocassinInterface) # , debugger = "ddd") + # instance.redirect_outputs_to("moc3-out.txt", "moc3-err.txt") instance.initialize_code() instance.set_symmetricXYZ(True) - instance.setup_mesh(13,13,13,0.95E+19,0.95E+19,0.95E+19) + instance.setup_mesh(13, 13, 13, 0.95E+19, 0.95E+19, 0.95E+19) instance.setup_abundancies() - #instance.set_abundancies_filename('abunHII20.in') + # instance.set_abundancies_filename('abunHII20.in') instance.set_input_directory(instance.get_default_input_directory()) instance.set_constant_hydrogen_density(100.0) instance.set_initial_nebular_temperature(6000.0) @@ -107,31 +105,28 @@ def xtest3(self): instance.set_convergence_limit(0.09) instance.set_number_of_ionisation_stages(6) instance.setup_auto_convergence(0.8, 2.0, 1000000000) - #instance.set_emit_rate_of_photons(1.006e13) + # instance.set_emit_rate_of_photons(1.006e13) instance.commit_parameters() instance.define_stars(0.0, 0.0, 0.0, 20000.0, 6003.6396) instance.commit_particles() instance.commit_grid() - + x, error = instance.get_number_of_elements_used() self.assertEqual(0, error) self.assertEqual(x, 7) - + instance.iterate() - - - indices_x = range(1,12,1) - temperatures,error = instance.get_grid_electron_temperature(indices_x,[1]*len(indices_x), [1]*len(indices_x), 1) + + indices_x = range(1, 12, 1) + temperatures, error = instance.get_grid_electron_temperature(indices_x, [1]*len(indices_x), [1]*len(indices_x), 1) self.assertEqual(0, error) print(temperatures) instance.stop() - - def test4(self): - instance=self.new_instance_of_an_optional_code(MocassinInterface) + instance = self.new_instance_of_an_optional_code(MocassinInterface) instance.initialize_code() - instance.setup_mesh(3,3,3,0.95E+19,0.95E+19,0.95E+19) + instance.setup_mesh(3, 3, 3, 0.95E+19, 0.95E+19, 0.95E+19) instance.setup_abundancies() instance.set_input_directory(instance.get_default_input_directory()) instance.set_initial_nebular_temperature(6000.0) @@ -141,149 +136,147 @@ def test4(self): instance.set_total_number_of_points_in_frequency_mesh(600) instance.set_high_limit_of_the_frequency_mesh(15) instance.set_low_limit_of_the_frequency_mesh(1.001e-5) - + instance.set_convergence_limit(0.09) instance.set_number_of_ionisation_stages(6) instance.setup_auto_convergence(0.2, 2.0, 1000000000) instance.commit_parameters() - error=instance.define_stars(0.0, 0.0, 0.0, 20000, 6003.6396) + error = instance.define_stars(0.0, 0.0, 0.0, 20000, 6003.6396) self.assertEqual(error, 0) - - instance.set_grid_hydrogen_density(1,1,1, 100) - - value,error = instance.get_grid_hydrogen_density(1,1,1) - + + instance.set_grid_hydrogen_density(1, 1, 1, 100) + + value, error = instance.get_grid_hydrogen_density(1, 1, 1) + self.assertEqual(error, 0) self.assertEqual(value, 100) - - is_active,error = instance.get_grid_active(1,1,1) + + is_active, error = instance.get_grid_active(1, 1, 1) self.assertEqual(error, 0) self.assertFalse(is_active) - - is_active,error = instance.get_grid_active(1,2,1) - + + is_active, error = instance.get_grid_active(1, 2, 1) + self.assertEqual(error, 0) self.assertFalse(is_active) - - value,error = instance.get_grid_hydrogen_density(1,2,1,1) - + + value, error = instance.get_grid_hydrogen_density(1, 2, 1, 1) + self.assertEqual(error, 0) self.assertEqual(value, 0) - + instance.commit_particles() instance.commit_grid() - - is_active,error = instance.get_grid_active(1,1,1) - + + is_active, error = instance.get_grid_active(1, 1, 1) + self.assertEqual(error, 0) self.assertTrue(is_active) - - value,error = instance.get_grid_hydrogen_density(1,1,1) + + value, error = instance.get_grid_hydrogen_density(1, 1, 1) self.assertEqual(error, 0) self.assertEqual(value, 100) - - value,error = instance.get_grid_ion_density(1,1,1,1,1) + + value, error = instance.get_grid_ion_density(1, 1, 1, 1, 1) self.assertEqual(error, 0) self.assertAlmostRelativeEquals(value, 1e-5, 6) - - is_active,error = instance.get_grid_active(1,2,1) - + + is_active, error = instance.get_grid_active(1, 2, 1) + self.assertEqual(error, 0) self.assertFalse(is_active) - - value,error = instance.get_grid_hydrogen_density(1,2,1) + + value, error = instance.get_grid_hydrogen_density(1, 2, 1) self.assertEqual(error, 0) self.assertEqual(value, 0) - - + instance.stop() + class TestMocassin(TestWithMPI): - + def test1(self): - instance=self.new_instance_of_an_optional_code(Mocassin) + instance = self.new_instance_of_an_optional_code(Mocassin) instance.initialize_code() - + self.assertEqual(0.0 | units.cm**-3, instance.parameters.constant_hydrogen_density) print(instance.parameters.abundancies_filename) instance.parameters.constant_hydrogen_density = 100.0 | units.cm**-3 self.assertEqual(100.0 | units.cm**-3, instance.parameters.constant_hydrogen_density) - + self.assertEqual(10000 | units.K, instance.parameters.initial_nebular_temperature) - + self.assertEqual("", instance.parameters.abundancies_filename) instance.stop() - - + def test2(self): - instance=self.new_instance_of_an_optional_code(Mocassin) #, redirection = "none") + instance = self.new_instance_of_an_optional_code(Mocassin) # , redirection = "none") instance.initialize_code() instance.set_input_directory(instance.get_default_input_directory()) - - + instance.set_symmetricXYZ(True) - + instance.parameters.nx = 11 instance.parameters.ny = 12 instance.parameters.nz = 13 - + instance.parameters.length_x = 1 | units.km instance.parameters.length_y = 1 | units.km instance.parameters.length_z = 1 | units.km - + instance.commit_parameters() self.assertEqual(instance.grid.shape[0], 11) self.assertEqual(instance.grid.shape[1], 12) self.assertEqual(instance.grid.shape[2], 13) instance.stop() - + def test3(self): - instance=self.new_instance_of_an_optional_code(Mocassin) #, debugger = "xterm") + instance = self.new_instance_of_an_optional_code(Mocassin) # , debugger = "xterm") instance.initialize_code() instance.set_random_seed(1) instance.set_input_directory(instance.get_default_input_directory()) instance.set_mocassin_output_directory(instance.output_directory + os.sep) - + instance.set_initial_nebular_temperature(200.0 | units.K) - + instance.parameters.nx = 7 instance.parameters.ny = 7 instance.parameters.nz = 7 - + print((0.95E+19 | units.cm).value_in(units.parsec)) instance.parameters.length_x = 0.95E+19 | units.cm instance.parameters.length_y = 0.95E+19 | units.cm instance.parameters.length_z = 0.95E+19 | units.cm - + instance.set_high_limit_of_the_frequency_mesh(15 | mocassin_rydberg_unit) - instance.set_low_limit_of_the_frequency_mesh(1.001e-5| mocassin_rydberg_unit) + instance.set_low_limit_of_the_frequency_mesh(1.001e-5 | mocassin_rydberg_unit) instance.set_maximum_number_of_monte_carlo_iterations(1) instance.set_total_number_of_photons(100) - #~ instance.set_constant_hydrogen_density(100 | units.cm**-3) - + # ~ instance.set_constant_hydrogen_density(100 | units.cm**-3) + instance.commit_parameters() instance.grid.hydrogen_density = 100 | units.cm**-3 instance.commit_grid() - + p = datamodel.Particle() p.x = 0 | units.cm p.y = 0 | units.cm p.z = 0 | units.cm p.temperature = 20000 | units.K - p.luminosity = 1. | units.LSun - + p.luminosity = 1. | units.LSun + instance.particles.add_particle(p) - + instance.commit_particles() - + self.assertAlmostRelativeEquals(1e-5, instance.ion_density_grid.density[3][1][2][0][0], 7) - self.assertAlmostRelativeEquals(1e-5 , instance.ion_density_grid.density[3][1][3][0][0], 7) - + self.assertAlmostRelativeEquals(1e-5, instance.ion_density_grid.density[3][1][3][0][0], 7) + instance.step() print(instance.grid.electron_density.mean()) - + self.assertAlmostRelativeEquals(0.0, instance.get_percentage_converged()) self.assertGreater(instance.grid.electron_density.mean(), 65. | units.cm**-3) self.assertLess(instance.grid.electron_density.mean(), 95. | units.cm**-3) diff --git a/src/amuse/test/suite/codes_tests/test_mosse.py b/src/amuse/test/suite/codes_tests/test_mosse.py index 6c63a3dfc4..75e2e9db1c 100644 --- a/src/amuse/test/suite/codes_tests/test_mosse.py +++ b/src/amuse/test/suite/codes_tests/test_mosse.py @@ -15,14 +15,14 @@ class TestMPIInterface(TestWithMPI): - + class state(object): def __init__(self): self.stellar_type = 0.0 self.zams_mass = 0.0 self.mass = 0.0 self.radius = 0.0 - self.luminosity = 0.0 + self.luminosity = 0.0 self.core_mass = 0.0 self.core_radius = 0.0 self.envelope_mass = 0.0 @@ -31,117 +31,113 @@ def __init__(self): self.epoch = 0.0 self.t_ms = 0.0 self.sse_age = 0.0 - + def initialize_module_with_default_parameters(self, mosse): metallicity = 0.02 - + neta = 0.5 - bwind = 0.0 - hewind = 1.0 - sigma1 = 265.0 - sigma2 = 7.0 - - ifflag = 0 - wdflag = 1 - bhflag = 1 - nsflag = 3 - piflag = 1 - mxns = 3.0 + bwind = 0.0 + hewind = 1.0 + sigma1 = 265.0 + sigma2 = 7.0 + + ifflag = 0 + wdflag = 1 + bhflag = 1 + nsflag = 3 + piflag = 1 + mxns = 3.0 idum = 29769 pts1 = 0.05 pts2 = 0.01 pts3 = 0.02 - - + status = mosse.initialize(metallicity, neta, bwind, hewind, sigma1, sigma2, ifflag, wdflag, bhflag, nsflag, piflag, mxns, idum, pts1, pts2, pts3) - + def test1(self): mosse = MOSSEInterface() - + metallicity = 0.02 - + neta = 0.5 - bwind = 0.0 - hewind = 1.0 - sigma1 = 265.0 - sigma2 = 7.0 - + bwind = 0.0 + hewind = 1.0 + sigma1 = 265.0 + sigma2 = 7.0 + ifflag = 0 - wdflag = 1 - bhflag = 1 - nsflag = 3 - piflag = 1 - mxns = 3.0 + wdflag = 1 + bhflag = 1 + nsflag = 3 + piflag = 1 + mxns = 3.0 idum = 29769 - + pts1 = 0.05 pts2 = 0.01 pts3 = 0.02 - - + status = mosse.initialize(metallicity, neta, bwind, hewind, sigma1, sigma2, ifflag, wdflag, bhflag, nsflag, piflag, mxns, idum, pts1, pts2, pts3) - - self.assertEqual(status,0) - + + self.assertEqual(status, 0) + mosse.stop() - + def test2(self): mosse = MOSSEInterface() - + metallicity = 0.02 - + neta = 0.5 - bwind = 0.0 - hewind = 1.0 - sigma1 = 265.0 - sigma2 = 7.0 - + bwind = 0.0 + hewind = 1.0 + sigma1 = 265.0 + sigma2 = 7.0 + ifflag = 0 - wdflag = 1 - bhflag = 1 - nsflag = 3 - piflag = 1 - mxns = 3.0 + wdflag = 1 + bhflag = 1 + nsflag = 3 + piflag = 1 + mxns = 3.0 idum = 29769 pts1 = 0.05 pts2 = 0.01 pts3 = 0.02 - status = mosse.initialize(metallicity, neta, bwind, hewind, sigma1, sigma2, ifflag, wdflag, bhflag, nsflag, piflag, mxns, idum, pts1, pts2, pts3) - self.assertEqual(status,0) + self.assertEqual(status, 0) new_state = self.state() new_state.mass = 1.0 new_state.zams_mass = 1.0 new_state.stellar_type = 1.0 new_state.age = 1e-06 result = mosse.evolve_star( - new_state.stellar_type, - new_state.zams_mass, new_state.mass, new_state.radius, + new_state.stellar_type, + new_state.zams_mass, new_state.mass, new_state.radius, new_state.luminosity, new_state.core_mass, new_state.core_radius, new_state.envelope_mass, new_state.envelope_radius, new_state.spin, new_state.epoch, new_state.t_ms, new_state.sse_age, new_state.age ) updated_state = self.state() - (updated_state.stellar_type,updated_state.zams_mass, updated_state.mass, updated_state.radius, + (updated_state.stellar_type, updated_state.zams_mass, updated_state.mass, updated_state.radius, updated_state.luminosity, updated_state.core_mass, updated_state.core_radius, updated_state.envelope_mass, updated_state.envelope_radius, updated_state.spin, updated_state.epoch, updated_state.t_ms, updated_state.sse_age, updated_state.age) = result attributes = ('stellar_type', 'zams_mass', 'mass', 'radius', 'luminosity', 'core_mass', 'core_radius', 'envelope_mass', 'envelope_radius', 'spin', 'epoch', 't_ms', 'sse_age', 'age') - - + expected = { 'zams_mass': '0x1.0000000000000p+0', 'mass': '0x1.0000000000000p+0', @@ -156,139 +152,138 @@ def test2(self): 't_ms': '0x1.57d90abe54643p+13', 'sse_age': '0x1.0c6f7a0b5ed8dp-20', 'age': '0x1.0c6f7a0b5ed8dp-20', - }; - + } for x in expected: - self.assertAlmostRelativeEqual(float.fromhex(expected[x]),getattr(updated_state, x)) - + self.assertAlmostRelativeEqual(float.fromhex(expected[x]), getattr(updated_state, x)) + self.assertEqual(updated_state.age, 1e-06) dt = mosse.get_time_step(updated_state.stellar_type, - updated_state.zams_mass, - updated_state.age, - updated_state.mass, - updated_state.t_ms, + updated_state.zams_mass, + updated_state.age, + updated_state.mass, + updated_state.t_ms, updated_state.epoch) self.assertAlmostEqual(dt, 550.1565, 2) mosse.stop() - + def test3(self): mosse = MOSSEInterface() - self.initialize_module_with_default_parameters(mosse) - types = [1,1,1] - masses = [10,5,4] + self.initialize_module_with_default_parameters(mosse) + types = [1, 1, 1] + masses = [10, 5, 4] radii = [5.0, 2.0, 1.0] - luminosity = core_mass = core_radius = envelope_mass =\ - envelope_radius = spin = epoch = t_ms = [0.0,0.0,0.0] + luminosity = core_mass = core_radius = envelope_mass =\ + envelope_radius = spin = epoch = t_ms = [0.0, 0.0, 0.0] sse_age = age = [1e-6, 1e-06, 1e-6] result = mosse.evolve_star( - types, - masses, - masses, - radii, - luminosity, - core_mass, + types, + masses, + masses, + radii, + luminosity, + core_mass, core_radius, envelope_mass, - envelope_radius, + envelope_radius, spin, - epoch, - t_ms, - sse_age, + epoch, + t_ms, + sse_age, age ) self.assertEqual(result['mass'][0], 10) self.assertEqual(result['mass'][1], 5) self.assertAlmostEqual(result['mass'][2], 4.0, 2) mosse.stop() - + def test4(self): mosse = MOSSEInterface() - self.initialize_module_with_default_parameters(mosse) - types = [1 for x in range(1,4000)] - masses = [1.0 + ((x / 4000.0) * 10.0) for x in range(1,4000)] - radii = [1.0 for x in range(1,4000)] - luminosity = core_mass = core_radius = envelope_mass =\ - envelope_radius = spin = epoch =\ - t_ms = [0.0 for x in range(1,4000)] - - sse_age = age = [1e-06 for x in range(1,4000)] + self.initialize_module_with_default_parameters(mosse) + types = [1 for x in range(1, 4000)] + masses = [1.0 + ((x / 4000.0) * 10.0) for x in range(1, 4000)] + radii = [1.0 for x in range(1, 4000)] + luminosity = core_mass = core_radius = envelope_mass =\ + envelope_radius = spin = epoch =\ + t_ms = [0.0 for x in range(1, 4000)] + + sse_age = age = [1e-06 for x in range(1, 4000)] result = mosse.evolve_star( - types, - masses, - masses, - radii, - luminosity, - core_mass, + types, + masses, + masses, + radii, + luminosity, + core_mass, core_radius, envelope_mass, - envelope_radius, + envelope_radius, spin, - epoch, - t_ms, - sse_age, + epoch, + t_ms, + sse_age, age ) self.assertEqual(len(result['mass']), 3999) mosse.stop() - + class TestSSE(TestWithMPI): - + def test1(self): mosse = MOSSE() - mosse.commit_parameters() + mosse.commit_parameters() stars = Particles(1) star = stars[0] star.mass = 5 | units.MSun star.radius = 0.0 | units.RSun - + mosse.particles.add_particles(stars) from_sse_to_model = mosse.particles.new_channel_to(stars) from_sse_to_model.copy() - + previous_type = star.stellar_type results = [] t0 = 0 | units.Myr current_time = t0 - + while current_time < (125 | units.Myr): mosse.update_time_steps() - + current_time = current_time + mosse.particles[0].time_step - + mosse.evolve_model(current_time) from_sse_to_model.copy() - + if not star.stellar_type == previous_type: results.append((star.age, star.mass, star.stellar_type)) previous_type = star.stellar_type - + self.assertEqual(len(results), 6) - - times = ( - 104.19 | units.Myr, - 104.62 | units.Myr, - 104.87 | units.Myr, + + times = ( + 104.19 | units.Myr, + 104.62 | units.Myr, + 104.87 | units.Myr, 120.39 | units.Myr, 121.17 | units.Myr, 121.88 | units.Myr ) for result, expected in zip(results, times): self.assertAlmostEqual(result[0].value_in(units.Myr), expected.value_in(units.Myr), 1) - - masses = ( - 4.991 | units.MSun, - 4.991 | units.MSun, - 4.989 | units.MSun, + + masses = ( + 4.991 | units.MSun, + 4.991 | units.MSun, + 4.989 | units.MSun, 4.923 | units.MSun, 4.886 | units.MSun, 1.003 | units.MSun ) for result, expected in zip(results, masses): self.assertAlmostEqual(result[1].value_in(units.MSun), expected.value_in(units.MSun), 3) - + types = ( "Hertzsprung Gap", "First Giant Branch", @@ -297,83 +292,80 @@ def test1(self): "Second Asymptotic Giant Branch", "Carbon/Oxygen White Dwarf", ) - + for result, expected in zip(results, types): self.assertEqual(str(result[2]), expected) - + mosse.stop() - + def test2(self): mosse = MOSSE() - mosse.commit_parameters() + mosse.commit_parameters() stars = Particles(1) - + star = stars[0] star.mass = 5 | units.MSun star.radius = 0.0 | units.RSun - + mosse.particles.add_particles(stars) mosse.evolve_model(120.1 | units.Myr) - + self.assertAlmostEqual(mosse.particles[0].mass.value_in(units.MSun), 4.925, 3) self.assertAlmostEqual(mosse.particles[0].temperature.value_in(units.K), 4271., 0) - + mosse.stop() - - + def test3(self): mosse = MOSSE() - mosse.commit_parameters() + mosse.commit_parameters() stars = Particles(1) - + star = stars[0] star.mass = 5 | units.MSun star.radius = 0.0 | units.RSun - + stars.synchronize_to(mosse.particles) - + channel = mosse.particles.new_channel_to(stars) - channel.copy_attributes(mosse.particles.get_attribute_names_defined_in_store()) - + channel.copy_attributes(mosse.particles.get_attribute_names_defined_in_store()) + previous_type = mosse.particles.stellar_type results = [] - + mosse.evolve_model(121.9 | units.Myr) - - channel.copy_attributes(mosse.particles.get_attribute_names_defined_in_store()) - + + channel.copy_attributes(mosse.particles.get_attribute_names_defined_in_store()) + self.assertAlmostEqual(star.mass.value_in(units.MSun), 1.002, 3) - + mosse.stop() - - + def test5(self): mosse = MOSSE() - mosse.commit_parameters() + mosse.commit_parameters() stars = Particles(1) - + star = stars[0] star.mass = 35 | units.MSun star.radius = 0.0 | units.RSun - + stars.synchronize_to(mosse.particles) - + channel = mosse.particles.new_channel_to(stars) - channel.copy_attributes(mosse.particles.get_attribute_names_defined_in_store()) - + channel.copy_attributes(mosse.particles.get_attribute_names_defined_in_store()) + previous_type = star.stellar_type results = [] - + dt = 1 | units.Myr t = 0 | units.Myr while t < 30 | units.Myr: t += dt mosse.evolve_model(t) - + self.assertTrue(mosse.particles[0].mass.value_in(units.MSun) < 6.0) - - mosse.stop() + mosse.stop() def test6(self): print("Test whether a set of stars evolves synchronously...") @@ -385,16 +377,16 @@ def test6(self): # Initialize stellar evolution code instance = MOSSE() - instance.commit_parameters() + instance.commit_parameters() instance.particles.add_particles(stars) instance.commit_particles() - + from_code_to_model = instance.particles.new_channel_to(stars) from_code_to_model.copy() - - instance.evolve_model(end_time = 125 | units.Myr) + + instance.evolve_model(end_time=125 | units.Myr) from_code_to_model.copy() - + end_types = ( "deeply or fully convective low mass MS star", "Main Sequence star", @@ -408,7 +400,7 @@ def test6(self): self.assertTrue(stars[i].mass <= masses[i]) self.assertEqual(str(stars[i].stellar_type), end_types[i]) instance.stop() - + def test7(self): print("Test: evolve particles one at a time.") print("Used to be problematic, since initial_mass of idle particle is set to zero.") @@ -428,7 +420,7 @@ def test7(self): self.assertEqual(stars[0].luminosity, stars[1].luminosity) self.assertEqual(stars[0].age, stars[1].age) print("Solved: SSE_muse_interface.f sets initial_mass to mass when necessary.") - + def test8(self): instance = MOSSE() self.assertEqual(instance.parameters.reimers_mass_loss_coefficient, 0.5) @@ -438,7 +430,7 @@ def test8(self): instance.commit_parameters() self.assertEqual(instance.parameters.reimers_mass_loss_coefficient, myvalue) instance.stop() - + instance = MOSSE() self.assertEqual(instance.parameters.reimers_mass_loss_coefficient, 0.5) myvalue = 0.7 @@ -447,7 +439,7 @@ def test8(self): instance.commit_parameters() self.assertEqual(instance.parameters.reimers_mass_loss_coefficient, 0.5) instance.stop() - + def test9(self): print("Test: large number of particles") stellar_evolution = MOSSE(max_message_length=500) @@ -460,7 +452,6 @@ def test9(self): stellar_evolution.particles.add_particles(stars) self.assertEqual(len(stellar_evolution.particles), number_of_particles) stellar_evolution.stop() - def test10(self): stellar_evolution = MOSSE() @@ -469,17 +460,17 @@ def test10(self): stars.mass = 1.0 | units.MSun stellar_evolution.particles.add_particles(stars) self.assertEqual(stellar_evolution.particles._factory_for_new_collection(), Particles) - + filename = os.path.join(get_path_to_results(), "test.h5") if os.path.exists(filename): os.remove(filename) - + io.write_set_to_file(stellar_evolution.particles, filename, 'hdf5') stored_stars = io.read_set_from_file(filename, 'hdf5') self.assertEqual(len(stars), len(stored_stars)) - + self.assertAlmostRelativeEquals(stars.mass, stored_stars.mass) - + def test11(self): print("Test evolve_model optional arguments: end_time and keep_synchronous") stars = Particles(3) @@ -487,68 +478,68 @@ def test11(self): instance = MOSSE() instance.commit_parameters() instance.particles.add_particles(stars) - + self.assertEqual(instance.particles.age, [0.0, 0.0, 0.0] | units.yr) self.assertAlmostEqual(instance.particles.time_step, [550.1565, 58.2081, 18.877] | units.Myr, 2) self.assertAlmostEqual(instance.particles.radius, [0.8882494502, 1.610210385, 1.979134445] | units.RSun) - + print("evolve_model without arguments: use shared timestep = min(particles.time_step)") instance.evolve_model() self.assertAlmostEqual(instance.particles.age, [18.877, 18.877, 18.877] | units.Myr, 2) self.assertAlmostEqual(instance.particles.time_step, [550.157, 58.208, 18.877] | units.Myr, 2) self.assertAlmostEqual(instance.model_time, 18.877 | units.Myr, 2) - + print("evolve_model with end_time: take timesteps, until end_time is reached exactly") instance.evolve_model(100 | units.Myr) self.assertAlmostEqual(instance.particles.age, [100.0, 100.0, 100.0] | units.Myr, 2) self.assertAlmostEqual(instance.particles.time_step, [550.157, 58.208, 18.877] | units.Myr, 2) self.assertAlmostEqual(instance.model_time, 100.0 | units.Myr, 2) - + print("evolve_model with keep_synchronous: use non-shared timestep, particle ages will typically diverge") - instance.evolve_model(keep_synchronous = False) + instance.evolve_model(keep_synchronous=False) self.assertAlmostEqual(instance.particles.age, (100 | units.Myr) + ([550.157, 58.208, 18.877] | units.Myr), 2) self.assertAlmostEqual(instance.particles.time_step, [550.157, 58.208, 18.877] | units.Myr, 2) - self.assertAlmostEqual(instance.model_time, 100.0 | units.Myr, 2) # Unchanged! + self.assertAlmostEqual(instance.model_time, 100.0 | units.Myr, 2) # Unchanged! instance.stop() - + def test12(self): print("Testing adding and removing particles from stellar evolution code...") - + particles = Particles(3) particles.mass = 1.0 | units.MSun - + instance = MOSSE() instance.initialize_code() instance.commit_parameters() - self.assertEqual(len(instance.particles), 0) # before creation + self.assertEqual(len(instance.particles), 0) # before creation instance.particles.add_particles(particles[:-1]) instance.commit_particles() instance.evolve_model(1.0 | units.Myr) - self.assertEqual(len(instance.particles), 2) # before remove + self.assertEqual(len(instance.particles), 2) # before remove self.assertAlmostEqual(instance.particles.age, 1.0 | units.Myr) - + instance.particles.remove_particle(particles[0]) self.assertEqual(len(instance.particles), 1) instance.evolve_model(2.0 | units.Myr) self.assertAlmostEqual(instance.particles[0].age, 2.0 | units.Myr) - + instance.particles.add_particles(particles[::2]) - self.assertEqual(len(instance.particles), 3) # it's back... + self.assertEqual(len(instance.particles), 3) # it's back... self.assertAlmostEqual(instance.particles[0].age, 2.0 | units.Myr) self.assertAlmostEqual(instance.particles[1].age, 0.0 | units.Myr) - self.assertAlmostEqual(instance.particles[2].age, 0.0 | units.Myr) # ... and rejuvenated. - - instance.evolve_model(3.0 | units.Myr) # The young stars keep their age offset from the old star + self.assertAlmostEqual(instance.particles[2].age, 0.0 | units.Myr) # ... and rejuvenated. + + instance.evolve_model(3.0 | units.Myr) # The young stars keep their age offset from the old star self.assertAlmostEqual(instance.particles.age, [3.0, 1.0, 1.0] | units.Myr) instance.evolve_model(4.0 | units.Myr) self.assertAlmostEqual(instance.particles.age, [4.0, 2.0, 2.0] | units.Myr) instance.stop() - + def test13(self): print("Testing SSE states") stars = Particles(1) stars.mass = 1.0 | units.MSun - + print("First do everything manually:", end=' ') instance = MOSSE() self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') @@ -561,7 +552,7 @@ def test13(self): instance.stop() print("ok") - print("initialize_code(), commit_parameters(), " \ + print("initialize_code(), commit_parameters(), " "and cleanup_code() should be called automatically:", end=' ') instance = MOSSE() self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') @@ -580,7 +571,7 @@ def test14a(self): instance = MOSSE() se_stars = instance.particles.add_particles(stars) self.assertAlmostEqual(se_stars.age, [0.0, 0.0] | units.yr) - + for i in range(3): se_stars[0].evolve_one_step() self.assertAlmostEqual(se_stars.age, [1650.46953688, 0.0] | units.Myr, 3) @@ -595,7 +586,7 @@ def test14a(self): self.assertAlmostRelativeEqual(se_stars[0].radius, se_stars[1].radius, 3) self.assertAlmostRelativeEqual(se_stars[0].temperature, se_stars[1].temperature, 3) instance.stop() - + def test14b(self): print("Testing basic operations: evolve_one_step and evolve_for (on subset)") stars = Particles(2) @@ -603,7 +594,7 @@ def test14b(self): instance = MOSSE() se_stars = instance.particles.add_particles(stars) self.assertAlmostEqual(se_stars.age, [0.0, 0.0] | units.yr) - + for i in range(3): se_stars[:1].evolve_one_step() self.assertAlmostEqual(se_stars.age, [1650.46953688, 0.0] | units.Myr, 3) @@ -618,68 +609,70 @@ def test14b(self): self.assertAlmostRelativeEqual(se_stars[0].radius, se_stars[1].radius, 3) self.assertAlmostRelativeEqual(se_stars[0].temperature, se_stars[1].temperature, 3) instance.stop() - + def test15(self): print("test evolution of 1000 star sampled over flattish IMF") - - number_of_stars=1000 - + + number_of_stars = 1000 + class notsorandom(object): - def random(self,N): + def random(self, N): return numpy.array(range(N))/(N-1.) - def random_sample(self,N): + + def random_sample(self, N): return numpy.array(range(N))/(N-1.) masses = new_salpeter_mass_distribution( - number_of_stars, - mass_min = 0.1 | units.MSun, - mass_max = 100.0 | units.MSun, - alpha = -1.01,random=notsorandom() + number_of_stars, + mass_min=0.1 | units.MSun, + mass_max=100.0 | units.MSun, + alpha=-1.01, random=notsorandom() ) - - stars=Particles(mass=masses) - instance=MOSSE() + stars = Particles(mass=masses) + + instance = MOSSE() instance.particles.add_particles(stars) - - i=0 + + i = 0 for p in instance.particles: - print(i,p.mass) - p.evolve_for(0.1 | units.Myr) - i+=1 + print(i, p.mass) + p.evolve_for(0.1 | units.Myr) + i += 1 instance.stop() def test16(self): print("test evolution of 1000 star sampled over flattish IMF") - - number_of_stars=1000 - + + number_of_stars = 1000 + class notsorandom(object): - def random(self,N): + def random(self, N): return numpy.array(range(N))/(N-1.) - def random_sample(self,N): + + def random_sample(self, N): return numpy.array(range(N))/(N-1.) masses = new_salpeter_mass_distribution( - number_of_stars, - mass_min = 0.1 | units.MSun, - mass_max = 100.0 | units.MSun, - alpha = -1.01,random=notsorandom() + number_of_stars, + mass_min=0.1 | units.MSun, + mass_max=100.0 | units.MSun, + alpha=-1.01, random=notsorandom() ) - - stars=Particles(mass=masses) - instance=MOSSE() + stars = Particles(mass=masses) + + instance = MOSSE() instance.particles.add_particles(stars) - - i=0 + + i = 0 for p in instance.particles: - print(i,p.mass, end=' ') - p.evolve_for(13.2 | units.Gyr) - print(p.mass) - i+=1 + print(i, p.mass, end=' ') + p.evolve_for(13.2 | units.Gyr) + print(p.mass) + i += 1 instance.stop() - + def test17(self): print("evolve_one_step and evolve_for after particle removal and addition") particles = Particles(10) @@ -691,15 +684,15 @@ def test17(self): for i in range(10): instance.particles[i].evolve_for(time_steps[i]) self.assertAlmostEqual(instance.particles.age, time_steps) - + instance.particles.remove_particles(particles[[1, 4, 8]]) revived = instance.particles.add_particle(particles[4]) revived.evolve_for(numpy.pi | units.Myr) for star in instance.particles: star.evolve_for(star.age) - self.assertAlmostEqual(instance.particles.age[:-1], 2*time_steps[[0, 2,3, 5,6,7, 9]]) + self.assertAlmostEqual(instance.particles.age[:-1], 2*time_steps[[0, 2, 3, 5, 6, 7, 9]]) self.assertAlmostEqual(instance.particles.age[-1], 2*numpy.pi | units.Myr) - + instance.particles.remove_particles(particles[[2, 5, 6]]) instance.particles.add_particles(particles[[8, 1]]) self.assertEqual(len(instance.particles), 7) @@ -708,28 +701,28 @@ def test17(self): star.evolve_one_step() self.assertAlmostEqual(instance.particles.age, expected_ages) instance.stop() - + def test18(self): print("MOSSE validation") mosse_src_path = os.path.join(os.path.dirname(sys.modules[MOSSE.__module__].__file__), 'src') if not os.path.exists(os.path.join(mosse_src_path, "evolve.in")): self.skip("Not in a source release") instance = MOSSE() - instance.particles.add_particle(Particle(mass = 1.416 | units.MSun)) + instance.particles.add_particle(Particle(mass=1.416 | units.MSun)) instance.particles[0].evolve_for(7000.0 | units.Myr) evolved_star = instance.particles.copy()[0] evolved_star.temperature = instance.particles[0].temperature instance.stop() - + testpath = get_path_to_results() shutil.copy(os.path.join(mosse_src_path, "evolve.in"), os.path.join(testpath, "evolve.in")) - + call([os.path.join(mosse_src_path, "mosse")], cwd=testpath) - + with open(os.path.join(testpath, "evolve.dat"), "r") as sse_output: lines = sse_output.readlines() sse_final_result = lines[-2].split() - + self.assertAlmostEqual(evolved_star.age, float(sse_final_result[0]) | units.Myr, 3) self.assertAlmostEqual(evolved_star.stellar_type, float(sse_final_result[1]) | units.stellar_type, 3) self.assertAlmostEqual(evolved_star.initial_mass, float(sse_final_result[2]) | units.MSun, 3) @@ -741,11 +734,11 @@ def test18(self): self.assertAlmostEqual(evolved_star.convective_envelope_mass, float(sse_final_result[8]) | units.MSun, 3) self.assertAlmostEqual(evolved_star.epoch, float(sse_final_result[9]) | units.Myr, 3) self.assertAlmostEqual(evolved_star.spin, float(sse_final_result[10]) | units.yr**-1, 3) - + def test19(self): print("MOSSE core_mass and CO_core_mass (high mass star)") instance = MOSSE() - star = instance.particles.add_particle(Particle(mass = 30 | units.MSun)) + star = instance.particles.add_particle(Particle(mass=30 | units.MSun)) instance.evolve_model(5.8 | units.Myr) print(star.mass, star.core_mass, star.CO_core_mass, star.stellar_type) self.assertEqual(str(star.stellar_type), "Main Sequence star") @@ -761,7 +754,7 @@ def test19(self): instance.evolve_model(6.5 | units.Myr) print(star.mass, star.core_mass, star.CO_core_mass, star.stellar_type) self.assertEqual(str(star.stellar_type), "Core Helium Burning") - self.assertIsOfOrder(star.mass, 10 | units.MSun) + self.assertIsOfOrder(star.mass, 10 | units.MSun) self.assertIsOfOrder(star.core_mass, 10 | units.MSun) self.assertEqual(star.CO_core_mass, 0 | units.MSun) instance.evolve_model(6.65 | units.Myr) @@ -783,11 +776,11 @@ def test19(self): self.assertEqual(star.core_mass, star.mass) self.assertEqual(star.CO_core_mass, star.mass) instance.stop() - + def test20(self): print("MOSSE core_mass and CO_core_mass (low mass stars)") instance = MOSSE() - stars = instance.particles.add_particles(Particles(mass = [0.6, 1.0] | units.MSun)) + stars = instance.particles.add_particles(Particles(mass=[0.6, 1.0] | units.MSun)) instance.evolve_model(100 | units.Gyr) self.assertEqual(str(stars[0].stellar_type), "Helium White Dwarf") self.assertAlmostEqual(stars[0].mass, 0.405 | units.MSun, 2) @@ -798,23 +791,22 @@ def test20(self): self.assertEqual(stars[1].core_mass, stars[1].mass) self.assertEqual(stars[1].CO_core_mass, stars[1].mass) instance.stop() - def test21(self): instance = MOSSE() - stars = instance.particles.add_particles(Particles(mass = 30 | units.MSun)) + stars = instance.particles.add_particles(Particles(mass=30 | units.MSun)) mass_loss_wind = stars[0].mass_loss_wind self.assertAlmostRelativeEquals(mass_loss_wind, 2.209e-07 | units.MSun / units.yr, 3) instance.evolve_model(1 | units.Myr) - dm = (1 | units.Myr)* mass_loss_wind - self.assertAlmostRelativeEquals(stars[0].mass, (30 | units.MSun) - dm , 3) + dm = (1 | units.Myr) * mass_loss_wind + self.assertAlmostRelativeEquals(stars[0].mass, (30 | units.MSun) - dm, 3) self.assertAlmostRelativeEquals(stars[0].mass_loss_wind, 2.7056e-07 | units.MSun / units.yr, 3) - + instance.stop() - + def test22(self): instance = MOSSE() - stars = instance.particles.add_particles(Particles(mass = [1.0, 10.0] | units.MSun)) + stars = instance.particles.add_particles(Particles(mass=[1.0, 10.0] | units.MSun)) gyration_radius = stars.gyration_radius self.assertTrue(numpy.all(0.0 < gyration_radius)) self.assertTrue(numpy.all(gyration_radius < 1.0)) @@ -827,10 +819,9 @@ def test22(self): def test23(self): instance = MOSSE() - p=Particles(mass = [1.0, 10.0] | units.MSun, temperature=[10,10] | units.K) + p = Particles(mass=[1.0, 10.0] | units.MSun, temperature=[10, 10] | units.K) stars = instance.particles.add_particles(p) - channel=stars.new_channel_to(p) - channel.copy_attributes(["mass","temperature"]) + channel = stars.new_channel_to(p) + channel.copy_attributes(["mass", "temperature"]) self.assertEqual(stars.temperature, p.temperature) - instance.stop() - + instance.stop() diff --git a/src/amuse/test/suite/codes_tests/test_mpiamrvac.py b/src/amuse/test/suite/codes_tests/test_mpiamrvac.py index 6bf50da049..02d99dd890 100644 --- a/src/amuse/test/suite/codes_tests/test_mpiamrvac.py +++ b/src/amuse/test/suite/codes_tests/test_mpiamrvac.py @@ -9,40 +9,41 @@ import os import numpy + + class TestMpiAmrVacInterface(TestWithMPI): - + def test1(self): instance = self.new_instance_of_an_optional_code(MpiAmrVacInterface) instance.initialize_code() instance.stop() - + def test2(self): instance = self.new_instance_of_an_optional_code(MpiAmrVacInterface) - filename, error = instance.get_parameters_filename() + filename, error = instance.get_parameters_filename() self.assertEqual(error, 0) self.assertEqual(filename, "amrvac.par") - error = instance.set_parameters_filename("dontexists.file") + error = instance.set_parameters_filename("dontexists.file") self.assertEqual(error, -1) - - filename, error = instance.get_parameters_filename() + + filename, error = instance.get_parameters_filename() self.assertEqual(error, 0) self.assertEqual(filename, "amrvac.par") - + name_of_parametersfile = 'amrvac.tst.par' with open(name_of_parametersfile, 'w') as f: f.write('test param') - error = instance.set_parameters_filename(name_of_parametersfile) + error = instance.set_parameters_filename(name_of_parametersfile) self.assertEqual(error, 0) - - filename, error = instance.get_parameters_filename() + + filename, error = instance.get_parameters_filename() self.assertEqual(error, 0) self.assertEqual(filename, name_of_parametersfile) - + os.remove(name_of_parametersfile) - + instance.initialize_code() instance.stop() - def test3(self): instance = self.new_instance_of_an_optional_code(MpiAmrVacInterface) @@ -50,86 +51,83 @@ def test3(self): error = instance.initialize_code() self.assertEqual(error, 0) instance.stop() - + def test4(self): instance = self.new_instance_of_an_optional_code(MpiAmrVacInterface) instance.set_parameters_filename(instance.default_parameters_filename) error = instance.initialize_code() self.assertEqual(error, 0) - instance.setup_mesh(20,20,20, 20.0, 20.0, 20.0) + instance.setup_mesh(20, 20, 20, 20.0, 20.0, 20.0) error = instance.commit_parameters() self.assertEqual(error, 0) number_of_grids, error = instance.get_number_of_grids() self.assertEqual(error, 0) self.assertEqual(number_of_grids, 8) - + lx, ly, lz, error = instance.get_mesh_size(1) self.assertEqual(lx, 10) self.assertEqual(ly, 10) self.assertEqual(lz, 10) - x,y,z, error = instance.get_position_of_index(0,0,0,1) + x, y, z, error = instance.get_position_of_index(0, 0, 0, 1) self.assertEqual(error, 0) self.assertEqual(x % 0.5, 0) self.assertEqual(y % 0.5, 0) self.assertEqual(z % 0.5, 0) instance.stop() - #self.assertTrue(False) - - + # self.assertTrue(False) + def test5(self): instance = self.new_instance_of_an_optional_code(MpiAmrVacInterface) instance.set_parameters_filename(instance.default_parameters_filename) error = instance.initialize_code() self.assertEqual(error, 0) - instance.setup_mesh(20,20,20, 20.0, 20.0, 20.0) + instance.setup_mesh(20, 20, 20, 20.0, 20.0, 20.0) error = instance.commit_parameters() self.assertEqual(error, 0) - + number_of_grids, error = instance.get_number_of_grids() self.assertEqual(error, 0) self.assertEqual(number_of_grids, 8) - - rho, error = instance.get_grid_density(1,1,1, 1) + + rho, error = instance.get_grid_density(1, 1, 1, 1) self.assertEqual(error, 0) self.assertEqual(rho, 0) - error = instance.set_grid_density(1,1,1, 0.1, 1) + error = instance.set_grid_density(1, 1, 1, 0.1, 1) self.assertEqual(error, 0) - rho, error = instance.get_grid_density(1,1,1, 1) + rho, error = instance.get_grid_density(1, 1, 1, 1) self.assertEqual(error, 0) self.assertEqual(rho, 0.1) - rho, error = instance.get_grid_density(1,1,1, 2) + rho, error = instance.get_grid_density(1, 1, 1, 2) self.assertEqual(error, 0) self.assertEqual(rho, 0.0) - + instance.stop() - - - + def test6(self): instance = self.new_instance_of_an_optional_code(MpiAmrVacInterface) instance.set_parameters_filename(instance.default_parameters_filename) error = instance.initialize_code() self.assertEqual(error, 0) - instance.setup_mesh(20,20,20, 20.0, 20.0, 20.0) + instance.setup_mesh(20, 20, 20, 20.0, 20.0, 20.0) error = instance.commit_parameters() self.assertEqual(error, 0) - + number_of_grids, error = instance.get_number_of_grids() self.assertEqual(error, 0) self.assertEqual(number_of_grids, 8) - - rho, error = instance.get_grid_energy_density(1,1,1, 1) + + rho, error = instance.get_grid_energy_density(1, 1, 1, 1) self.assertEqual(error, 0) self.assertEqual(rho, 0) - error = instance.set_grid_energy_density(1,1,1, 0.1, 1) + error = instance.set_grid_energy_density(1, 1, 1, 0.1, 1) self.assertEqual(error, 0) - rho, error = instance.get_grid_energy_density(1,1,1, 1) + rho, error = instance.get_grid_energy_density(1, 1, 1, 1) self.assertEqual(error, 0) self.assertEqual(rho, 0.1) - rho, error = instance.get_grid_density(1,1,1, 1) + rho, error = instance.get_grid_density(1, 1, 1, 1) self.assertEqual(error, 0) self.assertEqual(rho, 0.0) - rho, error = instance.get_grid_energy_density(1,1,1, 2) + rho, error = instance.get_grid_energy_density(1, 1, 1, 2) self.assertEqual(error, 0) self.assertEqual(rho, 0.0) instance.stop() @@ -139,145 +137,138 @@ def test7(self): instance.set_parameters_filename(instance.default_parameters_filename) error = instance.initialize_code() self.assertEqual(error, 0) - instance.setup_mesh(20,20,20, 20.0, 20.0, 20.0) + instance.setup_mesh(20, 20, 20, 20.0, 20.0, 20.0) error = instance.commit_parameters() self.assertEqual(error, 0) - + number_of_grids, error = instance.get_number_of_grids() self.assertEqual(error, 0) self.assertEqual(number_of_grids, 8) - - rhovx, rhovy, rhovz, error = instance.get_grid_momentum_density(1,1,1, 1) + + rhovx, rhovy, rhovz, error = instance.get_grid_momentum_density(1, 1, 1, 1) self.assertEqual(error, 0) self.assertEqual(rhovx, 0.0) self.assertEqual(rhovy, 0.0) self.assertEqual(rhovz, 0.0) - error = instance.set_grid_momentum_density(1,1,1, 0.1, 0.2, 0.3, 1) + error = instance.set_grid_momentum_density(1, 1, 1, 0.1, 0.2, 0.3, 1) self.assertEqual(error, 0) - rhovx, rhovy, rhovz, error = instance.get_grid_momentum_density(1,1,1, 1) + rhovx, rhovy, rhovz, error = instance.get_grid_momentum_density(1, 1, 1, 1) self.assertEqual(error, 0) self.assertEqual(rhovx, 0.1) self.assertEqual(rhovy, 0.2) self.assertEqual(rhovz, 0.3) - rhovx, rhovy, rhovz, error = instance.get_grid_momentum_density(1,1,1, 2) + rhovx, rhovy, rhovz, error = instance.get_grid_momentum_density(1, 1, 1, 2) self.assertEqual(error, 0) self.assertEqual(rhovx, 0.0) self.assertEqual(rhovy, 0.0) self.assertEqual(rhovz, 0.0) - rho, error = instance.get_grid_energy_density(1,1,1, 1) + rho, error = instance.get_grid_energy_density(1, 1, 1, 1) self.assertEqual(error, 0) self.assertEqual(rho, 0.0) - + instance.stop() - + def test8(self): instance = self.new_instance_of_an_optional_code(MpiAmrVacInterface) instance.set_parameters_filename(instance.default_parameters_filename) error = instance.initialize_code() self.assertEqual(error, 0) - instance.setup_mesh(20,20,20, 20.0, 20.0, 20.0) + instance.setup_mesh(20, 20, 20, 20.0, 20.0, 20.0) error = instance.set_boundary("periodic", "periodic", "periodic", "periodic", "periodic", "periodic") - + self.assertEqual(error, 0) error = instance.commit_parameters() self.assertEqual(error, 0) - + number_of_grids, error = instance.get_number_of_grids() self.assertEqual(error, 0) self.assertEqual(number_of_grids, 8) error = instance.initialize_grid() self.assertEqual(error, 0) - + instance.stop() - - - - def test9(self): + + def test9(self): instance = self.new_instance_of_an_optional_code(MpiAmrVacInterface) instance.set_parameters_filename(instance.default_parameters_filename) error = instance.initialize_code() self.assertEqual(error, 0) - instance.setup_mesh(20,20,20, 20.0, 20.0, 20.0) + instance.setup_mesh(20, 20, 20, 20.0, 20.0, 20.0) instance.commit_parameters() n1, n2, n3, error = instance.get_acceleration_grid_size() self.assertEqual(error, 0) self.assertEqual(n1, 50) self.assertEqual(n2, 50) self.assertEqual(n3, 50) - - a1, a2, a3, error = instance.get_acceleration_grid_acceleration(1,1,1) + + a1, a2, a3, error = instance.get_acceleration_grid_acceleration(1, 1, 1) self.assertEqual(error, 0) self.assertEqual(a1, 0.0) self.assertEqual(a2, 0) self.assertEqual(a3, 0) - - error = instance.set_acceleration_grid_acceleration(1,1,1, 10.0, 20.0, 30.0) + + error = instance.set_acceleration_grid_acceleration(1, 1, 1, 10.0, 20.0, 30.0) self.assertEqual(error, 0) - - a1, a2, a3, error = instance.get_acceleration_grid_acceleration(1,1,1) + + a1, a2, a3, error = instance.get_acceleration_grid_acceleration(1, 1, 1) self.assertEqual(error, 0) self.assertEqual(a1, 10.0) self.assertEqual(a2, 20.0) self.assertEqual(a3, 30.0) - - x,y,z, error = instance.get_acceleration_grid_position_of_index(1,1,1) + + x, y, z, error = instance.get_acceleration_grid_position_of_index(1, 1, 1) self.assertEqual(error, 0) - + self.assertEqual(x, -1) self.assertEqual(y, -1) self.assertEqual(z, -1) instance.stop() - - class TestMpiAmrVac(TestWithMPI): - + def test1(self): instance = self.new_instance_of_an_optional_code(MpiAmrVac) instance.set_parameters_filename(instance.default_parameters_filename) - instance.setup_mesh(20,20,20, 20.0 | generic_unit_system.length, 20.0 | generic_unit_system.length, 20.0 | generic_unit_system.length) + instance.setup_mesh(20, 20, 20, 20.0 | generic_unit_system.length, 20.0 | generic_unit_system.length, 20.0 | generic_unit_system.length) error = instance.set_boundary("periodic", "periodic", "periodic", "periodic", "periodic", "periodic") - - rhovx, rhovy, rhovz = instance.get_grid_momentum_density(1,1,1, 1) + + rhovx, rhovy, rhovz = instance.get_grid_momentum_density(1, 1, 1, 1) self.assertEqual(rhovx, 0.0 | generic_unit_system.momentum_density) self.assertEqual(rhovy, 0.0 | generic_unit_system.momentum_density) self.assertEqual(rhovz, 0.0 | generic_unit_system.momentum_density) instance.stop() - + def test2(self): - + instance = self.new_instance_of_an_optional_code(MpiAmrVac) instance.set_parameters_filename(instance.default_parameters_filename) instance.parameters.mesh_length = (20.0, 20.0, 20.0) | generic_unit_system.length - instance.parameters.mesh_size = (20, 20, 20) + instance.parameters.mesh_size = (20, 20, 20) instance.set_boundary("periodic", "periodic", "periodic", "periodic", "periodic", "periodic") - + grids = list(instance.itergrids()) - + self.assertEqual(len(grids), 8) - + for grid in grids: position = grids[0].position for i in range(3): - max_x = position[...,i].amax() - min_x = position[...,i].amin() - + max_x = position[..., i].amax() + min_x = position[..., i].amin() + self.assertTrue(min_x >= 0.5 | generic_unit_system.length) self.assertTrue(min_x <= 11.5 | generic_unit_system.length) self.assertTrue(max_x >= 9.5 | generic_unit_system.length) self.assertTrue(max_x <= 19.5 | generic_unit_system.length) - - - - + self.assertEqual(grids[0][0][0][0].rho, 0.0 | generic_unit_system.density) - + grids[0].rho = 0.2 | generic_unit_system.density - + rho1 = grids[1].rho rho0 = grids[0].rho for i in range(10): @@ -285,44 +276,43 @@ def test2(self): for k in range(10): self.assertEqual(rho1[0][0][0], 0.0 | generic_unit_system.density) self.assertEqual(rho0[0][0][0], 0.2 | generic_unit_system.density) - + instance.stop() - - + def test3(self): - - for number_of_workers in range(2,6): - instance = self.new_instance_of_an_optional_code(MpiAmrVac, number_of_workers = number_of_workers) + + for number_of_workers in range(2, 6): + instance = self.new_instance_of_an_optional_code(MpiAmrVac, number_of_workers=number_of_workers) instance.set_parameters_filename(instance.default_parameters_filename) instance.parameters.mesh_length = (20.0, 20.0, 20.0) | generic_unit_system.length - instance.parameters.mesh_size = (20, 20, 20) - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") - instance.parameters.z_boundary_conditions = ("periodic","periodic") + instance.parameters.mesh_size = (20, 20, 20) + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") + instance.parameters.z_boundary_conditions = ("periodic", "periodic") grids = list(instance.itergrids()) - + self.assertEqual(len(grids), 8) - + for index, grid in enumerate(grids): position = grid.position - #print instance.get_level_of_grid(index + 1) + # print instance.get_level_of_grid(index + 1) level = instance.get_level_of_grid(index + 1) self.assertEqual(level, 1) for i in range(3): - max_x = position[...,i].amax() - min_x = position[...,i].amin() - + max_x = position[..., i].amax() + min_x = position[..., i].amin() + self.assertTrue(min_x >= 0.5 | generic_unit_system.length) self.assertTrue(min_x <= 10.5 | generic_unit_system.length) self.assertTrue(max_x >= 9.5 | generic_unit_system.length) self.assertTrue(max_x <= 19.5 | generic_unit_system.length) - self.assertEqual(max_x - min_x , 9.0 | generic_unit_system.length) - + self.assertEqual(max_x - min_x, 9.0 | generic_unit_system.length) + self.assertEqual(grids[0][0][0][0].rho, 0.0 | generic_unit_system.density) - + grids[0].rho = 0.2 | generic_unit_system.density - + rho1 = grids[4].rho rho0 = grids[0].rho for i in range(10): @@ -330,34 +320,33 @@ def test3(self): for k in range(10): self.assertEqual(rho1[0][0][0], 0.0 | generic_unit_system.density) self.assertEqual(rho0[0][0][0], 0.2 | generic_unit_system.density) - + instance.stop() - + def test4(self): - - instance = self.new_instance_of_an_optional_code(MpiAmrVac, number_of_workers = 1) + + instance = self.new_instance_of_an_optional_code(MpiAmrVac, number_of_workers=1) instance.set_parameters_filename(instance.default_parameters_filename) - instance.parameters.mesh_length = (10.0,10.0, 10.0) | generic_unit_system.length + instance.parameters.mesh_length = (10.0, 10.0, 10.0) | generic_unit_system.length instance.parameters.mesh_size = (10, 10, 10) instance.parameters.maximum_number_of_grid_levels = 5 - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") - instance.parameters.z_boundary_conditions = ("periodic","periodic") - + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") + instance.parameters.z_boundary_conditions = ("periodic", "periodic") + grids = list(instance.itergrids()) self.assertEqual(len(grids), 1) - + levels = [instance.get_level_of_grid(i+1) for i in range(len(grids))] self.assertEqual(levels, [1] * 1) - + gamma = 5.0 / 3.0 - energy = generic_unit_system.mass / (generic_unit_system.time**2 * generic_unit_system.length) + energy = generic_unit_system.mass / (generic_unit_system.time**2 * generic_unit_system.length) grids_in_memory = [] for grid in grids: - grid.rho = 1.0 | generic_unit_system.density - grid.energy = (0.1795 | energy)/ (gamma - 1) - - + grid.rho = 1.0 | generic_unit_system.density + grid.energy = (0.1795 | energy) / (gamma - 1) + has_advanced = instance.refine_grid() grids = list(instance.itergrids()) self.assertFalse(has_advanced) @@ -369,17 +358,16 @@ def fill_grids(grids): firsthalf = grid.x > 5.0 | generic_unit_system.length secondhalf = numpy.logical_not(firsthalf) if(numpy.any(firsthalf)): - grid[firsthalf].rho = 1.0 | generic_unit_system.density - - instance = self.new_instance_of_an_optional_code(MpiAmrVac, number_of_workers = 1) + grid[firsthalf].rho = 1.0 | generic_unit_system.density + + instance = self.new_instance_of_an_optional_code(MpiAmrVac, number_of_workers=1) instance.set_parameters_filename(instance.default_parameters_filename) - instance.parameters.mesh_length = (10.0,10.0, 10.0) | generic_unit_system.length + instance.parameters.mesh_length = (10.0, 10.0, 10.0) | generic_unit_system.length instance.parameters.mesh_size = (10, 10, 10) instance.parameters.maximum_number_of_grid_levels = 4 - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") - instance.parameters.z_boundary_conditions = ("periodic","periodic") - + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") + instance.parameters.z_boundary_conditions = ("periodic", "periodic") n = 1 for i in range(3): @@ -387,580 +375,556 @@ def fill_grids(grids): grids = list(instance.itergrids()) levels = [instance.get_level_of_grid(grid+1) for grid in range(len(grids))] self.assertEqual(len(grids), expected_length) - + self.assertEqual(levels, [i+1] * expected_length) - + n *= 2 - + fill_grids(grids) has_advanced = instance.refine_grid() self.assertTrue(has_advanced) - + has_advanced = instance.refine_grid() self.assertFalse(has_advanced) - - + instance.stop() - - + def test6(self): - instance = self.new_instance_of_an_optional_code(MpiAmrVac, number_of_workers = 1) + instance = self.new_instance_of_an_optional_code(MpiAmrVac, number_of_workers=1) instance.set_parameters_filename(instance.default_parameters_filename) - instance.parameters.mesh_length = (10.0,10.0, 10.0) | generic_unit_system.length + instance.parameters.mesh_length = (10.0, 10.0, 10.0) | generic_unit_system.length instance.parameters.mesh_size = (10, 10, 10) - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") - instance.parameters.z_boundary_conditions = ("periodic","periodic") - + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") + instance.parameters.z_boundary_conditions = ("periodic", "periodic") + self.assertEqual(instance.parameters.maximum_number_of_grid_levels, 3) instance.parameters.maximum_number_of_grid_levels = 2 self.assertEqual(instance.parameters.maximum_number_of_grid_levels, 2) - - self.assertEqual(instance.parameters.entropy_type , 'nul') + + self.assertEqual(instance.parameters.entropy_type, 'nul') instance.parameters.entropy_type = 'powell' - self.assertEqual(instance.parameters.entropy_type , 'powell') - - self.assertEqual(instance.parameters.time_integration_procedure , 'twostep') + self.assertEqual(instance.parameters.entropy_type, 'powell') + + self.assertEqual(instance.parameters.time_integration_procedure, 'twostep') instance.parameters.time_integration_procedure = 'onestep' - self.assertEqual(instance.parameters.time_integration_procedure , 'onestep') - - self.assertEqual(instance.parameters.spatial_discretization_method , 'tvdmu') + self.assertEqual(instance.parameters.time_integration_procedure, 'onestep') + + self.assertEqual(instance.parameters.spatial_discretization_method, 'tvdmu') instance.parameters.spatial_discretization_method = 'tvdlf' - self.assertEqual(instance.parameters.spatial_discretization_method , 'tvdlf') - - - - self.assertEqual(instance.parameters.predictor_step_discretization_method , 'tvdmu') + self.assertEqual(instance.parameters.spatial_discretization_method, 'tvdlf') + + self.assertEqual(instance.parameters.predictor_step_discretization_method, 'tvdmu') instance.parameters.predictor_step_discretization_method = 'hancock' - self.assertEqual(instance.parameters.predictor_step_discretization_method , 'hancock') - + self.assertEqual(instance.parameters.predictor_step_discretization_method, 'hancock') + instance.commit_parameters() - - self.assertEqual(instance.parameters.entropy_type , 'powell') + + self.assertEqual(instance.parameters.entropy_type, 'powell') self.assertEqual(instance.parameters.maximum_number_of_grid_levels, 2) - self.assertEqual(instance.parameters.time_integration_procedure , 'onestep') - self.assertEqual(instance.parameters.spatial_discretization_method , 'tvdlf') - self.assertEqual(instance.parameters.predictor_step_discretization_method , 'hancock') - + self.assertEqual(instance.parameters.time_integration_procedure, 'onestep') + self.assertEqual(instance.parameters.spatial_discretization_method, 'tvdlf') + self.assertEqual(instance.parameters.predictor_step_discretization_method, 'hancock') + def test7(self): - instance=self.new_instance_of_an_optional_code(MpiAmrVac) + instance = self.new_instance_of_an_optional_code(MpiAmrVac) instance.set_parameters_filename(instance.default_parameters_filename) - instance.parameters.mesh_length = (10.0,10.0, 10.0) | generic_unit_system.length - instance.parameters.mesh_size = (10,10,10) + instance.parameters.mesh_length = (10.0, 10.0, 10.0) | generic_unit_system.length + instance.parameters.mesh_size = (10, 10, 10) instance.parameters.maximum_number_of_grid_levels = 1 - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") - instance.parameters.z_boundary_conditions = ("periodic","periodic") - - - grid = datamodel.Grid(10,10,10) + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") + instance.parameters.z_boundary_conditions = ("periodic", "periodic") + + grid = datamodel.Grid(10, 10, 10) grid.rho = 0.1 | generic_unit_system.density grid.rhovx = 0.0 | generic_unit_system.momentum_density - grid.rhovy = 0.0 | generic_unit_system.momentum_density - grid.rhovz = 0.0 | generic_unit_system.momentum_density - grid.energy = 1.0 | generic_unit_system.energy_density - + grid.rhovy = 0.0 | generic_unit_system.momentum_density + grid.rhovz = 0.0 | generic_unit_system.momentum_density + grid.energy = 1.0 | generic_unit_system.energy_density + grids = list(instance.itergrids()) self.assertEqual(len(grids), 1) igrid = grids[0] channel = grid.new_channel_to(igrid) channel.copy() - - + instance.evolve_model(0.1 | generic_unit_system.time) - + grids = list(instance.itergrids()) self.assertEqual(len(grids), 1) igrid = grids[0] self.assertAlmostRelativeEquals(igrid.rho, grid.rho) - + instance.evolve_model(0.3 | generic_unit_system.time) grids = list(instance.itergrids()) self.assertEqual(len(grids), 1) igrid = grids[0] self.assertAlmostRelativeEquals(igrid.rho, grid.rho) - + instance.stop() - + def test8(self): - instance=self.new_instance_of_an_optional_code(MpiAmrVac) + instance = self.new_instance_of_an_optional_code(MpiAmrVac) instance.set_parameters_filename(instance.default_parameters_filename) - instance.parameters.mesh_size = (10,10,10) + instance.parameters.mesh_size = (10, 10, 10) instance.parameters.maximum_number_of_grid_levels = 1 instance.parameters.length_x = 1.0 | generic_unit_system.length instance.parameters.length_y = 1.0 | generic_unit_system.length instance.parameters.length_z = 1.0 | generic_unit_system.length - instance.parameters.x_boundary_conditions = "periodic","periodic" - instance.parameters.y_boundary_conditions = "periodic","periodic" - instance.parameters.z_boundary_conditions = "periodic","periodic" - + instance.parameters.x_boundary_conditions = "periodic", "periodic" + instance.parameters.y_boundary_conditions = "periodic", "periodic" + instance.parameters.z_boundary_conditions = "periodic", "periodic" + name = instance.get_typeghostfill() self.assertEqual(name, 'linear') instance.commit_parameters() - + name = instance.get_typeghostfill() self.assertEqual(name, 'linear') - grid = datamodel.Grid(10,10,10) + grid = datamodel.Grid(10, 10, 10) grid.rho = 0.1 | generic_unit_system.density grid.rhovx = 0.0 | generic_unit_system.momentum_density - grid.rhovy = 0.0 | generic_unit_system.momentum_density - grid.rhovz = 0.0 | generic_unit_system.momentum_density - grid.energy = 1.0 | generic_unit_system.energy_density - + grid.rhovy = 0.0 | generic_unit_system.momentum_density + grid.rhovz = 0.0 | generic_unit_system.momentum_density + grid.energy = 1.0 | generic_unit_system.energy_density + grids = list(instance.itergrids()) self.assertEqual(len(grids), 1) igrid = grids[0] channel = grid.new_channel_to(igrid) channel.copy() - + name = instance.get_typeghostfill() self.assertEqual(name, 'linear') - - self.assertEqual((50,50,50), instance.acceleration_grid.shape) - - acc_grid = datamodel.Grid(50,50,50) + + self.assertEqual((50, 50, 50), instance.acceleration_grid.shape) + + acc_grid = datamodel.Grid(50, 50, 50) acceleration = 1 | generic_unit_system.acceleration acc_grid.ax = acceleration acc_grid.ay = acceleration acc_grid.az = acceleration - #self.assertEquals(acc_grid.acceleration[0][0][0], ( 1,1,1) | generic_unit_system.acceleration) + # self.assertEquals(acc_grid.acceleration[0][0][0], ( 1,1,1) | generic_unit_system.acceleration) channel = acc_grid.new_channel_to(instance.acceleration_grid) channel.copy() - + name = instance.get_typeghostfill() self.assertEqual(name, 'linear') - + result = instance.initialize_grid() - + name = instance.get_typeghostfill() self.assertEqual(name, 'linear') - + instance.evolve_model(0.1 | generic_unit_system.time) - + grids = list(instance.itergrids()) self.assertEqual(len(grids), 1) igrid = grids[0] - self.assertAlmostRelativeEquals(igrid.rho, grid.rho); - #self.assertAlmostRelativeEquals(igrid.rhovx, 0.1 * 1.0 * 0.1 | generic_unit_system.momentum_density); - #self.assertAlmostRelativeEquals(igrid.rhovy, 0.1 * 1.0 * 0.1 | generic_unit_system.momentum_density); - #self.assertAlmostRelativeEquals(igrid.rhovz, 0.1 * 1.0 * 0.1 | generic_unit_system.momentum_density); + self.assertAlmostRelativeEquals(igrid.rho, grid.rho) + # self.assertAlmostRelativeEquals(igrid.rhovx, 0.1 * 1.0 * 0.1 | generic_unit_system.momentum_density); + # self.assertAlmostRelativeEquals(igrid.rhovy, 0.1 * 1.0 * 0.1 | generic_unit_system.momentum_density); + # self.assertAlmostRelativeEquals(igrid.rhovz, 0.1 * 1.0 * 0.1 | generic_unit_system.momentum_density); instance.evolve_model(0.3 | generic_unit_system.time) grids = list(instance.itergrids()) self.assertEqual(len(grids), 1) igrid = grids[0] - self.assertAlmostRelativeEquals(igrid.rho, grid.rho); - #self.assertAlmostRelativeEquals(igrid.rhovx, grid.rho * instance.model_time * acceleration,2); - #self.assertAlmostRelativeEquals(igrid.rhovy, grid.rho * instance.model_time * acceleration,2); - #self.assertAlmostRelativeEquals(igrid.rhovz, grid.rho * instance.model_time * acceleration,2); + self.assertAlmostRelativeEquals(igrid.rho, grid.rho) + # self.assertAlmostRelativeEquals(igrid.rhovx, grid.rho * instance.model_time * acceleration,2); + # self.assertAlmostRelativeEquals(igrid.rhovy, grid.rho * instance.model_time * acceleration,2); + # self.assertAlmostRelativeEquals(igrid.rhovz, grid.rho * instance.model_time * acceleration,2); instance.stop() - - + def test9(self): - instance=self.new_instance_of_an_optional_code(MpiAmrVac, mode="2d") + instance = self.new_instance_of_an_optional_code(MpiAmrVac, mode="2d") instance.set_parameters_filename(instance.default_parameters_filename) - instance.parameters.mesh_length = (10.0,10.0, 1) | generic_unit_system.length - instance.parameters.mesh_size = (10,10,1) + instance.parameters.mesh_length = (10.0, 10.0, 1) | generic_unit_system.length + instance.parameters.mesh_size = (10, 10, 1) instance.parameters.maximum_number_of_grid_levels = 1 - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") - instance.parameters.z_boundary_conditions = ("periodic","periodic") - - - grid = datamodel.Grid(10,10,1) + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") + instance.parameters.z_boundary_conditions = ("periodic", "periodic") + + grid = datamodel.Grid(10, 10, 1) grid.rho = 0.1 | generic_unit_system.density grid.rhovx = 0.0 | generic_unit_system.momentum_density - grid.rhovy = 0.0 | generic_unit_system.momentum_density - grid.rhovz = 0.0 | generic_unit_system.momentum_density - grid.energy = 1.0 | generic_unit_system.energy_density - + grid.rhovy = 0.0 | generic_unit_system.momentum_density + grid.rhovz = 0.0 | generic_unit_system.momentum_density + grid.energy = 1.0 | generic_unit_system.energy_density + grids = list(instance.itergrids()) self.assertEqual(len(grids), 1) igrid = grids[0] channel = grid.new_channel_to(igrid) channel.copy() - - + instance.evolve_model(0.1 | generic_unit_system.time) - + grids = list(instance.itergrids()) self.assertEqual(len(grids), 1) igrid = grids[0] self.assertAlmostRelativeEquals(igrid.rho, grid.rho) - + instance.evolve_model(0.3 | generic_unit_system.time) grids = list(instance.itergrids()) self.assertEqual(len(grids), 1) igrid = grids[0] self.assertAlmostRelativeEquals(igrid.rho, grid.rho) - + instance.stop() - - - def test10(self): - instance=self.new_instance_of_an_optional_code(MpiAmrVac) - instance.parameters.mesh_size = (10,10,10) + + def test10(self): + instance = self.new_instance_of_an_optional_code(MpiAmrVac) + instance.parameters.mesh_size = (10, 10, 10) instance.parameters.mesh_length = [1.0, 1.0, 1.0] | generic_unit_system.length instance.parameters.maximum_number_of_grid_levels = 1 instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.z_boundary_conditions = ("periodic", "periodic") instance.parameters.stopping_conditions_number_of_steps = 1 - + gamma = 5.0 / 3.0 - - grid = datamodel.new_regular_grid((10,10,10), [1.0, 1.0, 1.0] | generic_unit_system.length ) - + + grid = datamodel.new_regular_grid((10, 10, 10), [1.0, 1.0, 1.0] | generic_unit_system.length) + density = generic_unit_system.density - momentum = generic_unit_system.speed * generic_unit_system.density - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - - + momentum = generic_unit_system.speed * generic_unit_system.density + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + grid.rho = 0.01 | density grid.rhovx = 0.1 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum grid[0:5].rho = 0.015 | density - + p = 1.0 | (generic_unit_system.mass / (generic_unit_system.length * generic_unit_system.time**2)) - - grid.energy = p / (gamma - 1) - grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho - + + grid.energy = p / (gamma - 1) + grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho + grids = list(instance.itergrids()) self.assertEqual(len(grids), 1) igrid = grids[0] channel = grid.new_channel_to(igrid) channel.copy() - + instance.stopping_conditions.number_of_steps_detection.enable() instance.evolve_model(1.0 | generic_unit_system.time) - + self.assertTrue(instance.stopping_conditions.number_of_steps_detection.is_set()) - rho = next(instance.itergrids()).rho[...,0,0] + rho = next(instance.itergrids()).rho[..., 0, 0] self.assertAlmostRelativeEquals(rho[7], 0.01 | density) self.assertTrue(rho[0] < 0.015 | density) - self.assertTrue( instance.model_time < 1.0 | generic_unit_system.time) - - + self.assertTrue(instance.model_time < 1.0 | generic_unit_system.time) + instance.stopping_conditions.number_of_steps_detection.disable() instance.evolve_model(0.1 | generic_unit_system.time) - rho = next(instance.itergrids()).rho[...,0,0] - self.assertAlmostRelativeEquals( instance.model_time, 0.1 | generic_unit_system.time) + rho = next(instance.itergrids()).rho[..., 0, 0] + self.assertAlmostRelativeEquals(instance.model_time, 0.1 | generic_unit_system.time) self.assertAlmostRelativeEquals(rho[7], 0.012812 | density, 3) self.assertTrue(rho[0] < 0.015 | density) - + instance.stop() - def test11(self): - instance=self.new_instance_of_an_optional_code(MpiAmrVac) - instance.parameters.mesh_size = (10,10,10) + def test11(self): + instance = self.new_instance_of_an_optional_code(MpiAmrVac) + instance.parameters.mesh_size = (10, 10, 10) instance.parameters.mesh_length = [1.0, 1.0, 1.0] | generic_unit_system.length instance.parameters.maximum_number_of_grid_levels = 1 instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.z_boundary_conditions = ("periodic", "periodic") instance.parameters.stopping_conditions_timeout = 0.1 | units.s - + gamma = 5.0 / 3.0 - - grid = datamodel.new_regular_grid((10,10,10), [1.0, 1.0, 1.0] | generic_unit_system.length ) - + + grid = datamodel.new_regular_grid((10, 10, 10), [1.0, 1.0, 1.0] | generic_unit_system.length) + density = generic_unit_system.density - momentum = generic_unit_system.speed * generic_unit_system.density - energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) - - + momentum = generic_unit_system.speed * generic_unit_system.density + energy = generic_unit_system.mass / ((generic_unit_system.time**2) * generic_unit_system.length) + grid.rho = 0.01 | density grid.rhovx = 0.1 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum grid[0:5].rho = 0.015 | density - + p = 1.0 | (generic_unit_system.mass / (generic_unit_system.length * generic_unit_system.time**2)) - - grid.energy = p / (gamma - 1) - grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho - + + grid.energy = p / (gamma - 1) + grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho + grids = list(instance.itergrids()) self.assertEqual(len(grids), 1) igrid = grids[0] channel = grid.new_channel_to(igrid) channel.copy() - + instance.stopping_conditions.timeout_detection.enable() instance.evolve_model(1.0 | generic_unit_system.time) - + self.assertTrue(instance.stopping_conditions.timeout_detection.is_set()) - rho = next(instance.itergrids()).rho[...,0,0] + rho = next(instance.itergrids()).rho[..., 0, 0] self.assertAlmostRelativeEquals(rho.mean(), 0.0125 | density) - self.assertTrue( instance.model_time < 1.0 | generic_unit_system.time) - - + self.assertTrue(instance.model_time < 1.0 | generic_unit_system.time) + instance.stopping_conditions.timeout_detection.disable() - tnext = instance.model_time.round(2) + (0.2 | generic_unit_system.time) + tnext = instance.model_time.round(2) + (0.2 | generic_unit_system.time) instance.evolve_model(tnext) - rho = next(instance.itergrids()).rho[...,0,0] - self.assertAlmostRelativeEquals( instance.model_time.round(2) ,tnext) + rho = next(instance.itergrids()).rho[..., 0, 0] + self.assertAlmostRelativeEquals(instance.model_time.round(2), tnext) self.assertAlmostRelativeEquals(rho.mean(), 0.0125 | density) self.assertTrue(rho[0] < 0.015 | density) - + instance.stop() - - + def test12(self): - instance=self.new_instance_of_an_optional_code(MpiAmrVac, mode="1d") + instance = self.new_instance_of_an_optional_code(MpiAmrVac, mode="1d") instance.set_parameters_filename(instance.default_parameters_filename) instance.parameters.mesh_length = (10.0, 1, 1) | generic_unit_system.length instance.parameters.mesh_size = (10, 1, 1) instance.parameters.maximum_number_of_grid_levels = 1 - instance.parameters.x_boundary_conditions = ("periodic","periodic") - - - grid = datamodel.Grid(10,1,1) + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + + grid = datamodel.Grid(10, 1, 1) grid.rho = 0.1 | generic_unit_system.density grid.rhovx = 0.0 | generic_unit_system.momentum_density - grid.rhovy = 0.0 | generic_unit_system.momentum_density - grid.rhovz = 0.0 | generic_unit_system.momentum_density - grid.energy = 1.0 | generic_unit_system.energy_density - + grid.rhovy = 0.0 | generic_unit_system.momentum_density + grid.rhovz = 0.0 | generic_unit_system.momentum_density + grid.energy = 1.0 | generic_unit_system.energy_density + grids = list(instance.itergrids()) self.assertEqual(len(grids), 1) igrid = grids[0] channel = grid.new_channel_to(igrid) channel.copy() - - + instance.evolve_model(0.1 | generic_unit_system.time) - + grids = list(instance.itergrids()) self.assertEqual(len(grids), 1) igrid = grids[0] self.assertAlmostRelativeEquals(igrid.rho, grid.rho) - + instance.evolve_model(0.3 | generic_unit_system.time) grids = list(instance.itergrids()) self.assertEqual(len(grids), 1) igrid = grids[0] self.assertAlmostRelativeEquals(igrid.rho, grid.rho) - + instance.stop() - def test13(self): - instance=self.new_instance_of_an_optional_code(MpiAmrVac, mode="2d-acc") + instance = self.new_instance_of_an_optional_code(MpiAmrVac, mode="2d-acc") instance.set_parameters_filename(instance.default_parameters_filename) instance.parameters.mesh_length = (10.0, 10.0, 1) | generic_unit_system.length instance.parameters.mesh_size = (20, 20, 1) instance.parameters.maximum_number_of_grid_levels = 2 - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") - - must_refine = True - middle = 5.0 | generic_unit_system.length + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") + + must_refine = True + middle = 5.0 | generic_unit_system.length while must_refine: must_refine = instance.refine_grid() - + for x in instance.itergrids(): inmem = x.copy() - inmem[inmem.x < middle].rho= 0.3 | generic_unit_system.density + inmem[inmem.x < middle].rho = 0.3 | generic_unit_system.density inmem[inmem.x >= middle].rho = 0.1 | generic_unit_system.density inmem.rhovx = 0.0 | generic_unit_system.momentum_density - inmem.rhovy = 0.0 | generic_unit_system.momentum_density - inmem.rhovz = 0.0 | generic_unit_system.momentum_density + inmem.rhovy = 0.0 | generic_unit_system.momentum_density + inmem.rhovz = 0.0 | generic_unit_system.momentum_density inmem.ax = 0.2 | generic_unit_system.acceleration - inmem.ay = 0.0 | generic_unit_system.acceleration - inmem.az = 0.0 | generic_unit_system.acceleration - - inmem.energy = 1.0 | generic_unit_system.energy_density + inmem.ay = 0.0 | generic_unit_system.acceleration + inmem.az = 0.0 | generic_unit_system.acceleration + + inmem.energy = 1.0 | generic_unit_system.energy_density from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() self.assertAlmostRelativeEquals(x.ax, 0.2 | generic_unit_system.acceleration) self.assertAlmostRelativeEquals(x.ay, 0.0 | generic_unit_system.acceleration) self.assertAlmostRelativeEquals(x.az, 0.0 | generic_unit_system.acceleration) - + self.assertEqual(len(list(instance.itergrids())), 4) for igrid in instance.itergrids(): self.assertAlmostRelativeEquals(igrid.ax, 0.2 | generic_unit_system.acceleration) self.assertAlmostRelativeEquals(igrid.ay, 0.0 | generic_unit_system.acceleration) self.assertAlmostRelativeEquals(igrid.az, 0.0 | generic_unit_system.acceleration) - + instance.evolve_model(0.1 | generic_unit_system.time) - + self.assertEqual(len(list(instance.itergrids())), 16) for igrid in instance.itergrids(): self.assertAlmostRelativeEquals(igrid.ax, 0.2 | generic_unit_system.acceleration) self.assertAlmostRelativeEquals(igrid.ay, 0.0 | generic_unit_system.acceleration) self.assertAlmostRelativeEquals(igrid.az, 0.0 | generic_unit_system.acceleration) - - + instance.stop() - - + def test14(self): - for ax, ay in ((0.2,0.0), (0.0, 0.2), (0.2,0.2)) | generic_unit_system.acceleration: - instance=self.new_instance_of_an_optional_code(MpiAmrVac, mode="2d-acc") + for ax, ay in ((0.2, 0.0), (0.0, 0.2), (0.2, 0.2)) | generic_unit_system.acceleration: + instance = self.new_instance_of_an_optional_code(MpiAmrVac, mode="2d-acc") instance.set_parameters_filename(instance.default_parameters_filename) instance.parameters.mesh_length = (10.0, 10.0, 1) | generic_unit_system.length instance.parameters.mesh_size = (10, 10, 1) instance.parameters.maximum_number_of_grid_levels = 1 - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") rho = 0.1 | generic_unit_system.density - middle = 5.0 | generic_unit_system.length + middle = 5.0 | generic_unit_system.length for x in instance.itergrids(): inmem = x.copy() inmem.rho = 0.1 | generic_unit_system.density inmem.rhovx = 0.0 | generic_unit_system.momentum_density - inmem.rhovy = 0.0 | generic_unit_system.momentum_density + inmem.rhovy = 0.0 | generic_unit_system.momentum_density inmem.ax = ax inmem.ay = ay - - inmem.energy = 1.0 | generic_unit_system.energy_density + + inmem.energy = 1.0 | generic_unit_system.energy_density from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() - + self.assertEqual(len(list(instance.itergrids())), 1) - + dt = 0.1 | generic_unit_system.time instance.evolve_model(dt) - + self.assertEqual(len(list(instance.itergrids())), 1) igrid = list(instance.itergrids())[0] - - self.assertAlmostRelativeEquals(igrid.rho , 0.1 | generic_unit_system.density) - self.assertAlmostRelativeEquals(igrid.rhovx , ax * dt* rho) - self.assertAlmostRelativeEquals(igrid.rhovy , ay * dt* rho) + + self.assertAlmostRelativeEquals(igrid.rho, 0.1 | generic_unit_system.density) + self.assertAlmostRelativeEquals(igrid.rhovx, ax * dt * rho) + self.assertAlmostRelativeEquals(igrid.rhovy, ay * dt * rho) instance.stop() - - - + def test15(self): - for ax, ay in ((0.2,0.0), (0.0, 0.2), (0.2,0.2)) | generic_unit_system.acceleration: #(0.0,0.0), - instance=self.new_instance_of_an_optional_code(MpiAmrVac, mode="2d-acc") + for ax, ay in ((0.2, 0.0), (0.0, 0.2), (0.2, 0.2)) | generic_unit_system.acceleration: # (0.0,0.0), + instance = self.new_instance_of_an_optional_code(MpiAmrVac, mode="2d-acc") instance.set_parameters_filename(instance.default_parameters_filename) instance.parameters.mesh_length = (10.0, 10.0, 1) | generic_unit_system.length instance.parameters.mesh_size = (20, 20, 1) instance.parameters.maximum_number_of_grid_levels = 1 instance.parameters.time_accurate = False - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") rho = 0.1 | generic_unit_system.density - middle = 5.0 | generic_unit_system.length + middle = 5.0 | generic_unit_system.length for x in instance.itergrids(): inmem = x.copy() inmem.rho = 0.1 | generic_unit_system.density inmem.rhovx = 0.0 | generic_unit_system.momentum_density - inmem.rhovy = 0.0 | generic_unit_system.momentum_density + inmem.rhovy = 0.0 | generic_unit_system.momentum_density inmem.ax = ax inmem.ay = ay - - inmem.energy = 1.0 | generic_unit_system.energy_density + + inmem.energy = 1.0 | generic_unit_system.energy_density from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() - + self.assertEqual(len(list(instance.itergrids())), 4) - + dt = 0.1 | generic_unit_system.time instance.evolve_model(dt) dt = instance.model_time - #~ for igrid in instance.itergrids(): - #~ print(ax * dt* rho, ax, instance.model_time) + # ~ for igrid in instance.itergrids(): + # ~ print(ax * dt* rho, ax, instance.model_time) self.assertEqual(len(list(instance.itergrids())), 4) - + for igrid in instance.itergrids(): - #print igrid.rho[2] - self.assertAlmostRelativeEquals(igrid.rho , rho) - self.assertAlmostRelativeEquals(igrid.rhovx, ax * dt* rho) - self.assertAlmostRelativeEquals(igrid.rhovy, ay * dt* rho) + # print igrid.rho[2] + self.assertAlmostRelativeEquals(igrid.rho, rho) + self.assertAlmostRelativeEquals(igrid.rhovx, ax * dt * rho) + self.assertAlmostRelativeEquals(igrid.rhovy, ay * dt * rho) instance.stop() - - + def test16(self): - - instance=self.new_instance_of_an_optional_code(MpiAmrVac, mode="1d") - instance.parameters.x_boundary_conditions = ("periodic","periodic") + + instance = self.new_instance_of_an_optional_code(MpiAmrVac, mode="1d") + instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.mesh_length = (20.0, 1, 1) | generic_unit_system.length instance.parameters.mesh_size = (20, 1, 1) instance.parameters.maximum_number_of_grid_levels = 1 - + for x in instance.itergrids(): inmem = x.copy() - inmem.rho = inmem.x/(1| generic_unit_system.length) | generic_unit_system.density + inmem.rho = inmem.x/(1 | generic_unit_system.length) | generic_unit_system.density inmem.rhovx = 0.0 | generic_unit_system.momentum_density - inmem.energy = 1.0 | generic_unit_system.energy_density + inmem.energy = 1.0 | generic_unit_system.energy_density from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() - rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5| generic_unit_system.length,0.0| generic_unit_system.length,0.0| generic_unit_system.length) - - self.assertEqual(rho , 0.5 | generic_unit_system.density) - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5 | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length) + + self.assertEqual(rho, 0.5 | generic_unit_system.density) + for value in numpy.arange(0.5, 19.6, 0.1): - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( value | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length ) - - self.assertAlmostRelativeEquals(rho , value | generic_unit_system.density) - + + self.assertAlmostRelativeEquals(rho, value | generic_unit_system.density) + for value in numpy.arange(0.0, 0.6, 0.1): rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( value | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length ) - self.assertAlmostRelativeEquals(rho , ((0.5 + value) * 0.5 + (0.5-value) * 19.5) | generic_unit_system.density) - - + self.assertAlmostRelativeEquals(rho, ((0.5 + value) * 0.5 + (0.5-value) * 19.5) | generic_unit_system.density) + for value in numpy.arange(0.0, 0.5, 0.1): rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( - value + 19.5| generic_unit_system.length, + value + 19.5 | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length ) - self.assertAlmostRelativeEquals(rho , (19.5 - (value * 19)) | generic_unit_system.density, 9) - + self.assertAlmostRelativeEquals(rho, (19.5 - (value * 19)) | generic_unit_system.density, 9) + # out of range rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( - 20.0| generic_unit_system.length, + 20.0 | generic_unit_system.length, 0.0 | generic_unit_system.length, 0.0 | generic_unit_system.length ) - self.assertAlmostRelativeEquals(rho , 0.0 | generic_unit_system.density, 9) - + self.assertAlmostRelativeEquals(rho, 0.0 | generic_unit_system.density, 9) + def test17(self): - - instance=self.new_instance_of_an_optional_code(MpiAmrVac, mode="2d", number_of_workers=2) - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") + + instance = self.new_instance_of_an_optional_code(MpiAmrVac, mode="2d", number_of_workers=2) + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.mesh_length = (20.0, 20.0, 1) | generic_unit_system.length instance.parameters.mesh_length = (20.0, 20.0, 1) | generic_unit_system.length instance.parameters.mesh_size = (20, 20, 1) instance.parameters.maximum_number_of_grid_levels = 1 - + for x in instance.itergrids(): inmem = x.copy() - inmem.rho = (inmem.x + ((inmem.y - (0.5| generic_unit_system.length))* 20.0))/(1| generic_unit_system.length) | generic_unit_system.density + inmem.rho = (inmem.x + ((inmem.y - (0.5 | generic_unit_system.length)) * 20.0))/(1 | generic_unit_system.length) | generic_unit_system.density inmem.rhovx = 0.0 | generic_unit_system.momentum_density - inmem.energy = 1.0 | generic_unit_system.energy_density + inmem.energy = 1.0 | generic_unit_system.energy_density from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() - rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5| generic_unit_system.length,0.5| generic_unit_system.length,0.0| generic_unit_system.length) - - self.assertEqual(rho , 0.5 | generic_unit_system.density) - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5 | generic_unit_system.length, 0.5 | generic_unit_system.length, 0.0 | generic_unit_system.length) + + self.assertEqual(rho, 0.5 | generic_unit_system.density) + for value in numpy.arange(0.5, 19.6, 0.1): - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( value | generic_unit_system.length, 0.5 | generic_unit_system.length, 0.0 | generic_unit_system.length ) - - self.assertAlmostRelativeEquals(rho , value | generic_unit_system.density) - + + self.assertAlmostRelativeEquals(rho, value | generic_unit_system.density) + for x in numpy.arange(8.5, 11.5, 0.25): for y in numpy.arange(0.5, 19.6, 0.25): rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( @@ -968,49 +932,48 @@ def test17(self): y | generic_unit_system.length, 0.0 | generic_unit_system.length ) - - self.assertAlmostRelativeEquals(rho , x + (20 * (y-0.5)) | generic_unit_system.density) - - + + self.assertAlmostRelativeEquals(rho, x + (20 * (y-0.5)) | generic_unit_system.density) + def test18(self): - - instance=self.new_instance_of_an_optional_code(MpiAmrVac, number_of_workers=3) - instance.parameters.x_boundary_conditions = ("periodic","periodic") - instance.parameters.y_boundary_conditions = ("periodic","periodic") - instance.parameters.z_boundary_conditions = ("periodic","periodic") + + instance = self.new_instance_of_an_optional_code(MpiAmrVac, number_of_workers=3) + instance.parameters.x_boundary_conditions = ("periodic", "periodic") + instance.parameters.y_boundary_conditions = ("periodic", "periodic") + instance.parameters.z_boundary_conditions = ("periodic", "periodic") instance.parameters.mesh_length = (20.0, 20.0, 20.0) | generic_unit_system.length instance.parameters.mesh_length = (20.0, 20.0, 20.0) | generic_unit_system.length instance.parameters.mesh_size = (20, 20, 20) instance.parameters.maximum_number_of_grid_levels = 1 - + for x in instance.itergrids(): inmem = x.copy() inmem.rho = ( ( - inmem.x + - ((inmem.y - (0.5| generic_unit_system.length))* 20.0) + - ((inmem.z - (0.5| generic_unit_system.length))* 400.0) + inmem.x + + ((inmem.y - (0.5 | generic_unit_system.length)) * 20.0) + + ((inmem.z - (0.5 | generic_unit_system.length)) * 400.0) ) - /(1| generic_unit_system.length) | generic_unit_system.density + / (1 | generic_unit_system.length) | generic_unit_system.density ) inmem.rhovx = 0.0 | generic_unit_system.momentum_density - inmem.energy = 1.0 | generic_unit_system.energy_density + inmem.energy = 1.0 | generic_unit_system.energy_density from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() - rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5| generic_unit_system.length,0.5| generic_unit_system.length,0.5| generic_unit_system.length) - - self.assertEqual(rho , 0.5 | generic_unit_system.density) - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point(0.5 | generic_unit_system.length, 0.5 | generic_unit_system.length, 0.5 | generic_unit_system.length) + + self.assertEqual(rho, 0.5 | generic_unit_system.density) + for value in numpy.arange(0.5, 19.6, 0.1): - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( value | generic_unit_system.length, 0.5 | generic_unit_system.length, 0.5 | generic_unit_system.length ) - - self.assertAlmostRelativeEquals(rho , value | generic_unit_system.density) - + + self.assertAlmostRelativeEquals(rho, value | generic_unit_system.density) + sample = sample = datamodel.new_regular_grid( (4, 4, 76), (2, 2, 19) | generic_unit_system.length @@ -1021,17 +984,12 @@ def test18(self): x = sample.x.flatten() y = sample.y.flatten() z = sample.z.flatten() - + rho, rhovx, rhovy, rhovx, rhoenergy = instance.get_hydro_state_at_point( x, y, z ) half = 0.5 | generic_unit_system.length - - self.assertAlmostRelativeEquals(rho , (x + (20 * (y-half)) + (400 * (z-half)))/(1| generic_unit_system.length) | generic_unit_system.density ) - - - - + self.assertAlmostRelativeEquals(rho, (x + (20 * (y-half)) + (400 * (z-half)))/(1 | generic_unit_system.length) | generic_unit_system.density) diff --git a/src/amuse/test/suite/codes_tests/test_multiples.py b/src/amuse/test/suite/codes_tests/test_multiples.py index 4f05e5b9eb..c3a68c078d 100644 --- a/src/amuse/test/suite/codes_tests/test_multiples.py +++ b/src/amuse/test/suite/codes_tests/test_multiples.py @@ -20,17 +20,17 @@ class TestSimpleMultiples(TestWithMPI): previous = None - + def new_smalln(self): if not self.previous is None: self.previous.stop() - + result = SmallN() result.parameters.timestep_parameter = 0.1 result.parameters.cm_index = 2001 self.previous = result return result - + def new_kepler_si(self): unit_converter = nbody_system.nbody_to_si( 1.0 | units.MSun, @@ -39,14 +39,14 @@ def new_kepler_si(self): kepler = Kepler(unit_converter) kepler.initialize_code() return kepler - + def new_kepler(self): kepler = Kepler() kepler.initialize_code() return kepler - + def new_smalln_si(self): - + if not self.previous is None: self.previous.stop() converter = nbody_system.nbody_to_si(units.MSun, units.parsec) @@ -54,36 +54,35 @@ def new_smalln_si(self): result.parameters.timestep_parameter = 0.1 result.parameters.cm_index = 2001 return result - + def new_binary(self, mass1, mass2, semi_major_axis, - eccentricity = 0, keyoffset = -1): + eccentricity=0, keyoffset=-1): total_mass = mass1 + mass2 mass_fraction_particle_1 = mass1 / (total_mass) - + if keyoffset >= 0: binary = datamodel.Particles(keys=range(keyoffset, keyoffset+2)) else: binary = datamodel.Particles(2) - + binary[0].mass = mass1 binary[1].mass = mass2 - + mu = nbody_system.G * total_mass - - velocity_perihelion = numpy.sqrt( mu / semi_major_axis * ((1.0 + eccentricity)/(1.0 - eccentricity))) + + velocity_perihelion = numpy.sqrt(mu / semi_major_axis * ((1.0 + eccentricity)/(1.0 - eccentricity))) radius_perihelion = semi_major_axis * (1.0 - eccentricity) - - binary[0].position = ((1.0 - mass_fraction_particle_1) * radius_perihelion * [1.0,0.0,0.0]) - binary[1].position = -(mass_fraction_particle_1 * radius_perihelion * [1.0,0.0,0.0]) - - binary[0].velocity = ((1.0 - mass_fraction_particle_1) * velocity_perihelion * [0.0,1.0,0.0]) - binary[1].velocity = -(mass_fraction_particle_1 * velocity_perihelion * [0.0,1.0,0.0]) + + binary[0].position = ((1.0 - mass_fraction_particle_1) * radius_perihelion * [1.0, 0.0, 0.0]) + binary[1].position = -(mass_fraction_particle_1 * radius_perihelion * [1.0, 0.0, 0.0]) + + binary[0].velocity = ((1.0 - mass_fraction_particle_1) * velocity_perihelion * [0.0, 1.0, 0.0]) + binary[1].velocity = -(mass_fraction_particle_1 * velocity_perihelion * [0.0, 1.0, 0.0]) return binary - - + def create_binaries(self, center_of_mass_particles, mass1, mass2, semi_major_axis, - eccentricity = 0): + eccentricity=0): singles_in_binaries = datamodel.Particles() for binary in center_of_mass_particles: particles_in_binary = self.new_binary( @@ -91,317 +90,307 @@ def create_binaries(self, center_of_mass_particles, mass1, mass2, semi_major_axi mass2, semi_major_axis ) - + particles_in_binary.radius = semi_major_axis - + binary.child1 = particles_in_binary[0] binary.child2 = particles_in_binary[1] binary.mass = mass1 + mass2 - + particles_in_binary.position += binary.position particles_in_binary.velocity += binary.velocity singles_in_binaries.add_particles(particles_in_binary) return center_of_mass_particles, singles_in_binaries - - + def test0(self): code = Hermite() stars = datamodel.Particles(2) stars.mass = 1 | nbody_system.mass stars.position = [ - [0.0, 0,0], + [0.0, 0, 0], [1.2, 0, 0] - ]|nbody_system.length + ] | nbody_system.length stars.velocity = [ - [0.0,0,0], - [0,0.1, 0] - ]|nbody_system.speed + [0.0, 0, 0], + [0, 0.1, 0] + ] | nbody_system.speed stars.radius = 0.5 | nbody_system.length - + encounter_code = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = self.new_smalln(), - interaction_over_code = None + kepler_code=self.new_kepler(), + resolve_collision_code=self.new_smalln(), + interaction_over_code=None ) encounter_code.parameters.hard_binary_factor = 1 encounter_code.small_scale_factor = 1 multiples_code = encounters.Multiples( - gravity_code = code, - handle_encounter_code = encounter_code + gravity_code=code, + handle_encounter_code=encounter_code ) multiples_code.particles.add_particles(stars) multiples_code.commit_particles() - multiples_code.evolve_model(0.6|nbody_system.time) + multiples_code.evolve_model(0.6 | nbody_system.time) self.assertEqual(len(multiples_code.multiples), 1) self.assertEqual(len(multiples_code.binaries), 1) - - + def test1(self): code = Hermite() - stars = datamodel.Particles(keys = (1,2,3, 4)) + stars = datamodel.Particles(keys=(1, 2, 3, 4)) stars.mass = 1 | nbody_system.mass stars.position = [ - [0.0,0,0], + [0.0, 0, 0], [0.5, 0, 0], [2.0, 0, 0], [-10.0, 0, 0], - ]|nbody_system.length + ] | nbody_system.length stars.velocity = [ - [0.0,0,0], - [0,0.1, 0], - [0,-0.1, 0], - [0,0.2, 0], - ]|nbody_system.speed + [0.0, 0, 0], + [0, 0.1, 0], + [0, -0.1, 0], + [0, 0.2, 0], + ] | nbody_system.speed stars.radius = 0.5 | nbody_system.length - + encounter_code = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = self.new_smalln(), - interaction_over_code = None + kepler_code=self.new_kepler(), + resolve_collision_code=self.new_smalln(), + interaction_over_code=None ) multiples_code = encounters.Multiples( - gravity_code = code, - handle_encounter_code = encounter_code + gravity_code=code, + handle_encounter_code=encounter_code ) multiples_code.particles.add_particles(stars) multiples_code.commit_particles() - - multiples_code.evolve_model(0.6|nbody_system.time) + + multiples_code.evolve_model(0.6 | nbody_system.time) self.assertEqual(len(multiples_code.multiples), 1) self.assertEqual(len(multiples_code.binaries), 1) - + self.assertAlmostRelativeEquals(multiples_code.particles[:-1].radius, 0.5 | nbody_system.length) - self.assertAlmostRelativeEquals(multiples_code.particles[-1].radius, 0.4446| nbody_system.length, 3) - multiples_code.evolve_model(2|nbody_system.time) + self.assertAlmostRelativeEquals(multiples_code.particles[-1].radius, 0.4446 | nbody_system.length, 3) + multiples_code.evolve_model(2 | nbody_system.time) self.assertEqual(len(multiples_code.multiples), 1) self.assertEqual(len(multiples_code.binaries), 1) - multiples_code.evolve_model(3|nbody_system.time) + multiples_code.evolve_model(3 | nbody_system.time) self.assertEqual(len(multiples_code.multiples), 1) self.assertEqual(len(multiples_code.particles), 2) self.assertEqual(len(multiples_code.binaries), 1) - def test2(self): code = Hermite() - stars = datamodel.Particles(keys = (1,2,3, 4)) + stars = datamodel.Particles(keys=(1, 2, 3, 4)) stars.mass = 1 | nbody_system.mass stars.position = [ - [0.0,0,0], + [0.0, 0, 0], [0.5, 0, 0], [3, 0, 0], [-10, 0, 0], - ]|nbody_system.length + ] | nbody_system.length stars.velocity = [ - [0.0,0,0], - [0,0.1, 0], - [0.0,-0.5, 0], - [0,0.2, 0], - ]|nbody_system.speed + [0.0, 0, 0], + [0, 0.1, 0], + [0.0, -0.5, 0], + [0, 0.2, 0], + ] | nbody_system.speed stars.radius = 0.5 | nbody_system.length - + encounter_code = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = self.new_smalln(), - interaction_over_code = None + kepler_code=self.new_kepler(), + resolve_collision_code=self.new_smalln(), + interaction_over_code=None ) multiples_code = encounters.Multiples( - gravity_code = code, - handle_encounter_code = encounter_code + gravity_code=code, + handle_encounter_code=encounter_code ) multiples_code.particles.add_particles(stars) multiples_code.commit_particles() - - multiples_code.evolve_model(3|nbody_system.time) + + multiples_code.evolve_model(3 | nbody_system.time) self.assertEqual(len(multiples_code.multiples), 1) print(multiples_code.multiples[0].components) self.assertEqual(len(multiples_code.multiples[0].components), 2) self.assertEqual(len(multiples_code.particles), 3) self.assertEqual(len(multiples_code.binaries), 1) self.assertEqual(len(multiples_code.singles), 2) - - + def test3(self): code = Hermite() particles_in_binary = self.new_binary( 0.1 | nbody_system.mass, 0.1 | nbody_system.mass, 0.01 | nbody_system.length, - keyoffset = 1 + keyoffset=1 ) particles_in_binary.radius = 0.001 | nbody_system.length - binary = datamodel.Particle(key = 3) + binary = datamodel.Particle(key=3) binary.child1 = particles_in_binary[0] binary.child2 = particles_in_binary[1] binary.radius = 0.5 | nbody_system.length binary.mass = 0.2 | nbody_system.mass encounter_code = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = self.new_smalln(), - interaction_over_code = None + kepler_code=self.new_kepler(), + resolve_collision_code=self.new_smalln(), + interaction_over_code=None ) multiples_code = encounters.Multiples( - gravity_code = code, - handle_encounter_code = encounter_code + gravity_code=code, + handle_encounter_code=encounter_code ) multiples_code.singles_in_binaries.add_particles(particles_in_binary) multiples_code.binaries.add_particle(binary) - + self.assertEqual(len(multiples_code.singles_in_binaries), 2) self.assertEqual(id(multiples_code.binaries[0].child1.particles_set), id(multiples_code.singles_in_binaries)) - + multiples_code.commit_particles() - + self.assertEqual(len(multiples_code.multiples), 1) self.assertEqual(len(multiples_code.components_of_multiples), 2) - - - + def test4(self): code = Hermite() - stars = datamodel.Particles(keys = (1,2,3, 4)) + stars = datamodel.Particles(keys=(1, 2, 3, 4)) stars.mass = 1 | nbody_system.mass stars.position = [ - [0.0,0,0], + [0.0, 0, 0], [0.5, 0, 0], [2, 0, 0], [-10, 0, 0], - ]|nbody_system.length + ] | nbody_system.length stars.velocity = [ - [0,0,0], - [0,0.2, 0], - [0,-0.2, 0], - [0,0.3, 0], - ]|nbody_system.speed + [0, 0, 0], + [0, 0.2, 0], + [0, -0.2, 0], + [0, 0.3, 0], + ] | nbody_system.speed stars.radius = 0.5 | nbody_system.length - + encounter_code = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = self.new_smalln(), - interaction_over_code = None + kepler_code=self.new_kepler(), + resolve_collision_code=self.new_smalln(), + interaction_over_code=None ) multiples_code = encounters.Multiples( - gravity_code = code, - handle_encounter_code = encounter_code + gravity_code=code, + handle_encounter_code=encounter_code ) multiples_code.particles.add_particles(stars) multiples_code.commit_particles() stopping_condition = multiples_code.stopping_conditions.multiples_change_detection stopping_condition.enable() - - multiples_code.evolve_model(3|nbody_system.time) + + multiples_code.evolve_model(3 | nbody_system.time) self.assertTrue(stopping_condition.is_set()) - self.assertAlmostRelativeEquals(multiples_code.model_time , 0.0075 | nbody_system.time, 4) + self.assertAlmostRelativeEquals(multiples_code.model_time, 0.0075 | nbody_system.time, 4) self.assertEqual(len(stopping_condition.particles(0)), 1) self.assertEqual(len(stopping_condition.particles(1)), 0) - + self.assertEqual(len(multiples_code.multiples), 1) self.assertEqual(len(multiples_code.multiples[0].components), 2) - self.assertEqual(len(multiples_code.particles), 3) # 1 multiples with 2 singles, plus 2 singles free + self.assertEqual(len(multiples_code.particles), 3) # 1 multiples with 2 singles, plus 2 singles free self.assertEqual(len(multiples_code.binaries), 1) self.assertEqual(len(multiples_code.singles), 2) - - multiples_code.evolve_model(3|nbody_system.time) + + multiples_code.evolve_model(3 | nbody_system.time) self.assertTrue(stopping_condition.is_set()) - self.assertAlmostRelativeEquals(multiples_code.model_time , 1.2195 | nbody_system.time, 4) - self.assertEqual(len(stopping_condition.particles(0)), 1) # 1 new multiple - self.assertEqual(len(stopping_condition.particles(1)), 1) # 1 dissolved multiple - + self.assertAlmostRelativeEquals(multiples_code.model_time, 1.2195 | nbody_system.time, 4) + self.assertEqual(len(stopping_condition.particles(0)), 1) # 1 new multiple + self.assertEqual(len(stopping_condition.particles(1)), 1) # 1 dissolved multiple + self.assertEqual(len(multiples_code.multiples[0].components), 3) - self.assertEqual(len(multiples_code.particles), 2) # 1 multiple, plus 1 single free + self.assertEqual(len(multiples_code.particles), 2) # 1 multiple, plus 1 single free self.assertEqual(len(multiples_code.binaries), 1) self.assertEqual(len(multiples_code.singles), 1) - + def test5(self): converter = nbody_system.nbody_to_si(units.MSun, units.parsec) - + code = Hermite(converter) - stars = datamodel.Particles(keys=(1,2)) + stars = datamodel.Particles(keys=(1, 2)) stars.mass = converter.to_si(1 | nbody_system.mass) stars.position = converter.to_si([ - [0,0,0], + [0, 0, 0], [1.2, 0, 0] - ]|nbody_system.length) + ] | nbody_system.length) stars.velocity = converter.to_si([ - [0,0,0], - [0,0.1, 0] - ]|nbody_system.speed) + [0, 0, 0], + [0, 0.1, 0] + ] | nbody_system.speed) stars.radius = converter.to_si(0.5 | nbody_system.length) - - + encounter_code = encounters.HandleEncounter( - kepler_code = self.new_kepler_si(), - resolve_collision_code = self.new_smalln_si(), - interaction_over_code = None, - G = constants.G + kepler_code=self.new_kepler_si(), + resolve_collision_code=self.new_smalln_si(), + interaction_over_code=None, + G=constants.G ) encounter_code.parameters.hard_binary_factor = 1 multiples_code = encounters.Multiples( - gravity_code = code, - handle_encounter_code = encounter_code, - G = constants.G + gravity_code=code, + handle_encounter_code=encounter_code, + G=constants.G ) - end_time = converter.to_si(1.0|nbody_system.time) + end_time = converter.to_si(1.0 | nbody_system.time) multiples_code.particles.add_particles(stars) multiples_code.commit_particles() multiples_code.evolve_model(end_time) - - self.assertEqual(len(multiples_code.particles),1) # 1 multiples with 2 singles + + self.assertEqual(len(multiples_code.particles), 1) # 1 multiples with 2 singles self.assertEqual(len(multiples_code.multiples), 1) self.assertEqual(len(multiples_code.multiples[0].components), 2) self.assertEqual(len(multiples_code.binaries), 1) self.assertEqual(len(multiples_code.singles), 0) - - - + def test6(self): converter = nbody_system.nbody_to_si(units.MSun, units.parsec) - + code = Hermite(converter) - stars = datamodel.Particles(keys=(1,2,3,4)) + stars = datamodel.Particles(keys=(1, 2, 3, 4)) stars.mass = converter.to_si(1 | nbody_system.mass) stars.position = converter.to_si([ - [0,0,0], + [0, 0, 0], [1.2, 0, 0], [100, 0, 0], [100, 1.2, 0] - ]|nbody_system.length) + ] | nbody_system.length) stars.velocity = converter.to_si([ - [0,0,0], - [0,0.1, 0], - [0,0,0], - [0,0,0.1], - ]|nbody_system.speed) + [0, 0, 0], + [0, 0.1, 0], + [0, 0, 0], + [0, 0, 0.1], + ] | nbody_system.speed) stars.radius = converter.to_si(0.5 | nbody_system.length) - - + encounter_code = encounters.HandleEncounter( - kepler_code = self.new_kepler_si(), - resolve_collision_code = self.new_smalln_si(), - interaction_over_code = None, - G = constants.G + kepler_code=self.new_kepler_si(), + resolve_collision_code=self.new_smalln_si(), + interaction_over_code=None, + G=constants.G ) encounter_code.small_scale_factor = 1.0 multiples_code = encounters.Multiples( - gravity_code = code, - handle_encounter_code = encounter_code, - G = constants.G + gravity_code=code, + handle_encounter_code=encounter_code, + G=constants.G ) multiples_code.must_handle_one_encounter_per_stopping_condition = False multiples_code.particles.add_particles(stars) multiples_code.commit_particles() - + stopping_condition = multiples_code.stopping_conditions.multiples_change_detection stopping_condition.enable() - - end_time = converter.to_si(3.0|nbody_system.time) + + end_time = converter.to_si(3.0 | nbody_system.time) print(end_time.as_quantity_in(units.Myr)) multiples_code.evolve_model(end_time) self.assertTrue(stopping_condition.is_set()) print(multiples_code.model_time.as_quantity_in(units.Myr)) - self.assertAlmostRelativeEquals(multiples_code.model_time , 7.99844 | units.Myr, 4) + self.assertAlmostRelativeEquals(multiples_code.model_time, 7.99844 | units.Myr, 4) self.assertEqual(len(stopping_condition.particles(0)), 2) self.assertEqual(len(stopping_condition.particles(1)), 0) - + self.assertEqual(len(multiples_code.particles), 2) # 1 multiples with 2 singles self.assertEqual(len(multiples_code.multiples), 2) self.assertEqual(len(multiples_code.binaries), 2) @@ -410,318 +399,300 @@ def test6(self): self.assertEqual(len(multiples_code.singles), 0) self.assertEqual(len(multiples_code.all_singles), 4) - def test7(self): converter = nbody_system.nbody_to_si(units.MSun, units.parsec) - + code = Hermite(converter) - stars = datamodel.Particles(keys=(1,2)) + stars = datamodel.Particles(keys=(1, 2)) stars.mass = converter.to_si(1 | nbody_system.mass) stars.position = converter.to_si([ - [0,0,0], + [0, 0, 0], [1.1, 0, 0], - ]|nbody_system.length) + ] | nbody_system.length) stars.velocity = converter.to_si([ - [0,0,0], - [-0.5,1.5, 0], - ]|nbody_system.speed) + [0, 0, 0], + [-0.5, 1.5, 0], + ] | nbody_system.speed) stars.radius = converter.to_si(0.55 | nbody_system.length) - - + encounter_code = encounters.HandleEncounter( - kepler_code = self.new_kepler_si(), - resolve_collision_code = self.new_smalln_si(), - interaction_over_code = None, - G = constants.G + kepler_code=self.new_kepler_si(), + resolve_collision_code=self.new_smalln_si(), + interaction_over_code=None, + G=constants.G ) encounter_code.small_scale_factor = 1.0 encounter_code.parameters.hard_binary_factor = 1 multiples_code = encounters.Multiples( - gravity_code = code, - handle_encounter_code = encounter_code, - G = constants.G + gravity_code=code, + handle_encounter_code=encounter_code, + G=constants.G ) multiples_code.must_handle_one_encounter_per_stopping_condition = False multiples_code.singles.add_particles(stars) multiples_code.commit_particles() - + stopping_condition = multiples_code.stopping_conditions.encounter_detection stopping_condition.enable() - - end_time = converter.to_si(3.0|nbody_system.time) + + end_time = converter.to_si(3.0 | nbody_system.time) print(end_time.as_quantity_in(units.Myr)) multiples_code.evolve_model(end_time) self.assertTrue(stopping_condition.is_set()) print(multiples_code.model_time.as_quantity_in(units.Myr)) - #self.assertAlmostRelativeEquals(multiples_code.model_time , 5.96955 | units.Myr, 4) + # self.assertAlmostRelativeEquals(multiples_code.model_time , 5.96955 | units.Myr, 4) self.assertEqual(len(stopping_condition.particles(0)), 1) model = stopping_condition.particles(0)[0] - + self.assertEqual(len(model.particles_before_encounter), 2) self.assertEqual(len(model.particles_after_encounter), 2) - - + before = model.particles_before_encounter after = model.particles_after_encounter - + self.assertAlmostRelativeEquals(before.center_of_mass(), after.center_of_mass(), 7) self.assertAlmostRelativeEquals(before.center_of_mass_velocity(), after.center_of_mass_velocity(), 7) - + total_energy_before = before.kinetic_energy() + before.potential_energy(G=constants.G) total_energy_after = after.kinetic_energy() + after.potential_energy(G=constants.G) - + self.assertAlmostRelativeEquals(total_energy_before, total_energy_after, 7) - - + def test8(self): code = Hermite() particles_in_binary = self.new_binary( 0.1 | nbody_system.mass, 0.1 | nbody_system.mass, 0.01 | nbody_system.length, - keyoffset = 1 + keyoffset=1 ) particles_in_binary.radius = 0.001 | nbody_system.length - binary = datamodel.Particle(key = 3) + binary = datamodel.Particle(key=3) binary.child1 = particles_in_binary[0] binary.child2 = particles_in_binary[1] binary.radius = 0.5 | nbody_system.length binary.mass = 0.2 | nbody_system.mass - binary.position = [0.0,0.0,0.0] | nbody_system.length - binary.velocity = [0.0,0.0,0.0] | nbody_system.speed + binary.position = [0.0, 0.0, 0.0] | nbody_system.length + binary.velocity = [0.0, 0.0, 0.0] | nbody_system.speed encounter_code = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = self.new_smalln(), - interaction_over_code = None + kepler_code=self.new_kepler(), + resolve_collision_code=self.new_smalln(), + interaction_over_code=None ) encounter_code.parameters.hard_binary_factor = 1 encounter_code.small_scale_factor = 1 multiples_code = encounters.Multiples( - gravity_code = code, - handle_encounter_code = encounter_code + gravity_code=code, + handle_encounter_code=encounter_code ) multiples_code.singles_in_binaries.add_particles(particles_in_binary) multiples_code.binaries.add_particle(binary) multiples_code.must_handle_one_encounter_per_stopping_condition = False - - field_particle = datamodel.Particle(key = 4) - field_particle.mass = 0.5 | nbody_system.mass + + field_particle = datamodel.Particle(key=4) + field_particle.mass = 0.5 | nbody_system.mass field_particle.radius = 0.1 | nbody_system.length - field_particle.position = [0.0,0.2,0.0]| nbody_system.length - field_particle.velocity = [0.0,0.0,0.0] | nbody_system.speed - + field_particle.position = [0.0, 0.2, 0.0] | nbody_system.length + field_particle.velocity = [0.0, 0.0, 0.0] | nbody_system.speed + multiples_code.singles.add_particle(field_particle) - + self.assertEqual(len(multiples_code.singles_in_binaries), 2) self.assertEqual(id(multiples_code.binaries[0].child1.particles_set), id(multiples_code.singles_in_binaries)) - + multiples_code.commit_particles() - multiples_code.multiples.radius = 0.5 | nbody_system.length + multiples_code.multiples.radius = 0.5 | nbody_system.length initial_energy = multiples_code.get_total_energy() - + self.assertEqual(len(multiples_code.multiples), 1) self.assertEqual(len(multiples_code.components_of_multiples), 2) self.assertEqual(len(multiples_code.particles), 2) - + stopping_condition = multiples_code.stopping_conditions.encounter_detection stopping_condition.enable() - + singles = datamodel.Particles() singles.add_particles(particles_in_binary) singles.add_particle(field_particle) - - + singles_energy = singles.kinetic_energy() + singles.potential_energy(G=nbody_system.G) self.assertAlmostRelativeEquals(initial_energy, singles_energy, 3) - - - multiples_code.evolve_model(2 |nbody_system.time) - + + multiples_code.evolve_model(2 | nbody_system.time) + final_energy = multiples_code.get_total_energy() self.assertTrue(stopping_condition.is_set()) self.assertAlmostRelativeEquals(initial_energy, final_energy, 7) - - + def test9(self): code = Hermite() - + particles_in_binary = self.new_binary( 0.1 | nbody_system.mass, 0.1 | nbody_system.mass, 0.01 | nbody_system.length, - keyoffset = 1 + keyoffset=1 ) particles_in_binary.radius = 0.001 | nbody_system.length - - binary = datamodel.Particle(key = 3) + + binary = datamodel.Particle(key=3) binary.child1 = particles_in_binary[0] binary.child2 = particles_in_binary[1] binary.radius = 0.5 | nbody_system.length binary.mass = 0.2 | nbody_system.mass encounter_code = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = self.new_smalln(), + kepler_code=self.new_kepler(), + resolve_collision_code=self.new_smalln(), ) - - - others = datamodel.Particles(key = [4,5,6]) + + others = datamodel.Particles(key=[4, 5, 6]) for i in range(3): others[i].position = [i, 0, 0] | nbody_system.length others[i].velocity = [0, 0, i] | nbody_system.speed others[i].mass = 1 | nbody_system.mass others[i].radius = 0 | nbody_system.length - + multiples_code = encounters.Multiples( - gravity_code = code, - handle_encounter_code = encounter_code + gravity_code=code, + handle_encounter_code=encounter_code ) multiples_code.singles_in_binaries.add_particles(particles_in_binary) multiples_code.binaries.add_particle(binary) - + multiples_code.singles.add_particles(others) - - + multiples_code.commit_particles() - + self.assertEqual(len(multiples_code.multiples), 1) self.assertEqual(len(multiples_code.components_of_multiples), 2) self.assertEqual(len(multiples_code.singles), 3) self.assertEqual(len(multiples_code.particles), 4) self.assertEqual(len(code.particles), 4) - - self.assertAlmostRelativeEquals(multiples_code.particles[-1].mass,0.2 | nbody_system.mass) - self.assertAlmostRelativeEquals(code.particles[-1].mass,0.2 | nbody_system.mass) - self.assertAlmostRelativeEquals(code.particles[-1].position, [0,0,0] | nbody_system.length, 6) - self.assertAlmostRelativeEquals(code.particles[-1].velocity, [0,0, 0] | nbody_system.speed, 6) - - + + self.assertAlmostRelativeEquals(multiples_code.particles[-1].mass, 0.2 | nbody_system.mass) + self.assertAlmostRelativeEquals(code.particles[-1].mass, 0.2 | nbody_system.mass) + self.assertAlmostRelativeEquals(code.particles[-1].position, [0, 0, 0] | nbody_system.length, 6) + self.assertAlmostRelativeEquals(code.particles[-1].velocity, [0, 0, 0] | nbody_system.speed, 6) + multiples_code.update_model() self.assertAlmostRelativeEquals(multiples_code.particles[-1].mass, 0.2 | nbody_system.mass) self.assertAlmostRelativeEquals(code.particles[-1].mass, 0.2 | nbody_system.mass) - self.assertAlmostRelativeEquals(code.particles[-1].position, [0,0,0] | nbody_system.length, 6) - self.assertAlmostRelativeEquals(code.particles[-1].velocity, [0,0, 0] | nbody_system.speed, 6) - + self.assertAlmostRelativeEquals(code.particles[-1].position, [0, 0, 0] | nbody_system.length, 6) + self.assertAlmostRelativeEquals(code.particles[-1].velocity, [0, 0, 0] | nbody_system.speed, 6) + multiples_code.singles_in_binaries[0].mass = 0.2 | nbody_system.mass - + multiples_code.update_model() - + print(code.particles.mass) self.assertAlmostRelativeEquals(multiples_code.particles[-1].mass, 0.3 | nbody_system.mass) self.assertAlmostRelativeEquals(code.particles[-1].mass, 0.3 | nbody_system.mass) print(code.particles[-1].position) print(code.particles[-1].velocity) - self.assertAlmostRelativeEquals(code.particles[-1].position, [0.00166666666667,0,0] | nbody_system.length, 6) + self.assertAlmostRelativeEquals(code.particles[-1].position, [0.00166666666667, 0, 0] | nbody_system.length, 6) self.assertAlmostRelativeEquals(code.particles[-1].velocity, [0, 0.7453559925, 0] | nbody_system.speed, 6) - - - - + def test10(self): code = Hermite() - + particles_in_binary = self.new_binary( 0.1 | nbody_system.mass, 0.1 | nbody_system.mass, 0.01 | nbody_system.length, - keyoffset = 1 + keyoffset=1 ) particles_in_binary.radius = 0.001 | nbody_system.length - + encounter_code = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = self.new_smalln(), + kepler_code=self.new_kepler(), + resolve_collision_code=self.new_smalln(), ) - + encounter_code.parameters.hard_binary_factor = 1 encounter_code.small_scale_factor = 1 - - others = datamodel.Particles(key = [4,5,6]) + + others = datamodel.Particles(key=[4, 5, 6]) for i in range(3): others[i].position = [i, 0, 0] | nbody_system.length others[i].velocity = [0, 0, i] | nbody_system.speed others[i].mass = 1 | nbody_system.mass - others[i].radius = 0.05 | nbody_system.length - + others[i].radius = 0.05 | nbody_system.length + multiples_code = encounters.Multiples( - gravity_code = code, - handle_encounter_code = encounter_code + gravity_code=code, + handle_encounter_code=encounter_code ) multiples_code.must_handle_one_encounter_per_stopping_condition = False multiples_code.singles.add_particles(particles_in_binary) multiples_code.singles.add_particles(others) - - + multiples_code.commit_particles() multiples_code.evolve_model(1 | nbody_system.time) - + self.assertEqual(len(multiples_code.multiples), 1) self.assertEqual(len(multiples_code.components_of_multiples), 2) self.assertEqual(len(multiples_code.singles), 3) self.assertEqual(len(multiples_code.particles), 4) self.assertEqual(len(code.particles), 4) - + self.assertEqual(id(multiples_code.singles_in_binaries), id(multiples_code.binaries[0].child1.particles_set)) self.assertEqual(id(multiples_code.components_of_multiples), id(multiples_code.multiples[0].components[0].particles_set)) - #multiples_code.singles_in_binaries[0].mass = 0.2 | nbody_system.mass + # multiples_code.singles_in_binaries[0].mass = 0.2 | nbody_system.mass print(multiples_code.particles.mass) self.assertAlmostRelativeEquals(multiples_code.particles[-1].mass, 1.1 | nbody_system.mass) self.assertAlmostRelativeEquals(multiples_code.particles.mass.sum(), 0.1 + 0.1 + 3.0 | nbody_system.mass) multiples_code.update_model() - + self.assertAlmostRelativeEquals(multiples_code.particles[-1].mass, 1.1 | nbody_system.mass) - + index = -1 - if not code.particles[index].mass > 1.0| nbody_system.mass: + if not code.particles[index].mass > 1.0 | nbody_system.mass: index = -2 self.assertAlmostRelativeEquals(code.particles[index].mass, 1.1 | nbody_system.mass) - + multiples_code.singles_in_binaries[0].mass += 0.2 | nbody_system.mass - + multiples_code.update_model() - + self.assertAlmostRelativeEquals(multiples_code.particles[-1].mass, 1.3 | nbody_system.mass) self.assertAlmostRelativeEquals(code.particles[index].mass, 1.3 | nbody_system.mass) - - - + def test11(self): code = Hermite() - + particles_in_binary = self.new_binary( 1.0 | nbody_system.mass, 1.0 | nbody_system.mass, 0.001 | nbody_system.length, - keyoffset = 1 + keyoffset=1 ) particles_in_binary.radius = 0.01 | nbody_system.length - + encounter_code = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = self.new_smalln(), + kepler_code=self.new_kepler(), + resolve_collision_code=self.new_smalln(), ) - - - others = datamodel.Particles(keys = [4,5,6]) + + others = datamodel.Particles(keys=[4, 5, 6]) for i in range(3): others[i].position = [i, 0, 0] | nbody_system.length others[i].velocity = [0, 0, 0] | nbody_system.speed others[i].mass = 0.2 | nbody_system.mass - others[i].radius = 0.05 | nbody_system.length - + others[i].radius = 0.05 | nbody_system.length + multiples_code = encounters.Multiples( - gravity_code = code, - handle_encounter_code = encounter_code + gravity_code=code, + handle_encounter_code=encounter_code ) multiples_code.singles.add_particles(particles_in_binary) multiples_code.singles.add_particles(others) - - + stopping_condition = multiples_code.stopping_conditions.binaries_change_detection stopping_condition.enable() - - multiples_code.commit_particles() + + multiples_code.commit_particles() multiples_code.evolve_model(1 | nbody_system.time) - self.assertEqual(len(multiples_code.multiples), 1) + self.assertEqual(len(multiples_code.multiples), 1) self.assertEqual(len(multiples_code.binaries), 1) self.assertEqual(len(multiples_code.components_of_multiples), 2) self.assertEqual(len(multiples_code.singles), 3) @@ -731,7 +702,7 @@ def test11(self): multiples_code.particles[-1].velocity = [0, 0, 0] | nbody_system.speed multiples_code.update_model() print(multiples_code.particles.key) - + self.assertEqual(len(stopping_condition.particles(0)), 1) self.assertEqual(len(stopping_condition.particles(1)), 0) self.assertEqual(len(stopping_condition.particles(2)), 0) @@ -745,83 +716,75 @@ def test11(self): self.assertEqual(len(stopping_condition.particles(2)), 1) self.assertAlmostRelativeEquals(multiples_code.multiples[0].mass, 2.0 | nbody_system.mass) self.assertAlmostRelativeEquals(multiples_code.particles.mass.sum(), 2.6 | nbody_system.mass) - - + def test12(self): code = Hermite() - + particles_in_binary = self.new_binary( 1.0 | nbody_system.mass, 1.0 | nbody_system.mass, 0.001 | nbody_system.length, - keyoffset = 10 + keyoffset=10 ) particles_in_binary.radius = 0.01 | nbody_system.length - + encounter_code = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = self.new_smalln(), + kepler_code=self.new_kepler(), + resolve_collision_code=self.new_smalln(), ) binary = datamodel.Particle(key=20) binary.child1 = particles_in_binary[0] binary.child2 = particles_in_binary[1] - binary.position = [1,0,1] | nbody_system.length - particles_in_binary.position += [1,0,1] | nbody_system.length - - others = datamodel.Particles(keys = [4,5,6]) + binary.position = [1, 0, 1] | nbody_system.length + particles_in_binary.position += [1, 0, 1] | nbody_system.length + + others = datamodel.Particles(keys=[4, 5, 6]) for i in range(3): others[i].position = [i*10, 0, 0] | nbody_system.length others[i].velocity = [0, 0, 0] | nbody_system.speed others[i].mass = 0.2 | nbody_system.mass - others[i].radius = 0.05 | nbody_system.length - - + others[i].radius = 0.05 | nbody_system.length + multiples_code = encounters.Multiples( - gravity_code = code, - handle_encounter_code = encounter_code + gravity_code=code, + handle_encounter_code=encounter_code ) multiples_code.particles.add_particles(others) multiples_code.singles_in_binaries.add_particles(particles_in_binary) multiples_code.binaries.add_particle(binary) - multiples_code.commit_particles() + multiples_code.commit_particles() print(multiples_code.particles) self.assertEqual(len(multiples_code.particles), 4) - self.assertAlmostRelativeEquals(multiples_code.particles[-1].position, [1,0,1] | nbody_system.length) - - - - + self.assertAlmostRelativeEquals(multiples_code.particles[-1].position, [1, 0, 1] | nbody_system.length) + def test13(self): code = Hermite() - - + encounter_code = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = self.new_smalln(), + kepler_code=self.new_kepler(), + resolve_collision_code=self.new_smalln(), ) center_of_mass_particles = datamodel.Particles(5) - center_of_mass_particles.position = (numpy.asarray(range(5))).reshape(5,1) * ([1.0, 0.0, 0.0] | nbody_system.length) + center_of_mass_particles.position = (numpy.asarray(range(5))).reshape(5, 1) * ([1.0, 0.0, 0.0] | nbody_system.length) center_of_mass_particles.velocity = [0.0, 0.0, 0.0] | nbody_system.speed - center_of_mass_particles.radius = 0.05 | nbody_system.length + center_of_mass_particles.radius = 0.05 | nbody_system.length binaries, singles_in_binaries = self.create_binaries( - center_of_mass_particles, + center_of_mass_particles, 1 | nbody_system.mass, 0.01 | nbody_system.mass, 0.0001 | nbody_system.length ) - + multiples_code = encounters.Multiples( - gravity_code = code, - handle_encounter_code = encounter_code + gravity_code=code, + handle_encounter_code=encounter_code ) multiples_code.singles_in_binaries.add_particles(singles_in_binaries) multiples_code.binaries.add_particles(binaries) - multiples_code.commit_particles() - - - - #stopping_condition = multiples_code.stopping_conditions.encounter_detection - #stopping_condition.enable() + multiples_code.commit_particles() + + # stopping_condition = multiples_code.stopping_conditions.encounter_detection + # stopping_condition.enable() stopping_condition = multiples_code.stopping_conditions.binaries_change_detection stopping_condition.enable() for x in multiples_code.binaries: @@ -841,38 +804,35 @@ def test13(self): print(x.key, x.mass) self.assertEqual(len(multiples_code.singles_in_binaries) + len(multiples_code.singles), 2*len(center_of_mass_particles)) self.assertEqual(len(multiples_code.binaries) - len(stopping_condition.particles(0)) + len(stopping_condition.particles(1)), len(center_of_mass_particles)) - + def test14(self): code = Hermite() - - + encounter_code = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = self.new_smalln(), + kepler_code=self.new_kepler(), + resolve_collision_code=self.new_smalln(), ) center_of_mass_particles = datamodel.Particles(5) - center_of_mass_particles.position = (numpy.asarray(range(5))).reshape(5,1) * ([1.0, 0.0, 0.0] | nbody_system.length) + center_of_mass_particles.position = (numpy.asarray(range(5))).reshape(5, 1) * ([1.0, 0.0, 0.0] | nbody_system.length) center_of_mass_particles.velocity = [0.0, 0.0, 0.0] | nbody_system.speed - center_of_mass_particles.radius = 0.05 | nbody_system.length + center_of_mass_particles.radius = 0.05 | nbody_system.length binaries, singles_in_binaries = self.create_binaries( - center_of_mass_particles, + center_of_mass_particles, 1 | nbody_system.mass, 0.1 | nbody_system.mass, 0.00000001 | nbody_system.length ) - + multiples_code = encounters.Multiples( - gravity_code = code, - handle_encounter_code = encounter_code + gravity_code=code, + handle_encounter_code=encounter_code ) multiples_code.singles_in_binaries.add_particles(singles_in_binaries) multiples_code.binaries.add_particles(binaries) - multiples_code.commit_particles() - - - - #stopping_condition = multiples_code.stopping_conditions.encounter_detection - #stopping_condition.enable() + multiples_code.commit_particles() + + # stopping_condition = multiples_code.stopping_conditions.encounter_detection + # stopping_condition.enable() stopping_condition = multiples_code.stopping_conditions.binaries_change_detection stopping_condition.enable() for x in multiples_code.binaries: @@ -892,37 +852,34 @@ def test14(self): print(x.key, x.mass) self.assertEqual(len(multiples_code.singles_in_binaries) + len(multiples_code.singles), 2*len(center_of_mass_particles)) self.assertEqual(len(multiples_code.binaries) - len(stopping_condition.particles(0)) + len(stopping_condition.particles(1)), len(center_of_mass_particles)) - + def test15(self): code = Hermite() - - + encounter_code = encounters.HandleEncounter( - kepler_code = self.new_kepler(), - resolve_collision_code = self.new_smalln(), + kepler_code=self.new_kepler(), + resolve_collision_code=self.new_smalln(), ) n = 10 center_of_mass_particles = plummer.new_plummer_model(n, random=numpy.random.mtrand.RandomState(1)) - center_of_mass_particles.radius = 0.5 | nbody_system.length + center_of_mass_particles.radius = 0.5 | nbody_system.length center_of_mass_particles.velocity *= 0 binaries, singles_in_binaries = self.create_binaries( - center_of_mass_particles, + center_of_mass_particles, 0.999 * ((1.0 | nbody_system.mass) / n), 0.001 * ((1.0 | nbody_system.mass) / n), 0.00001 | nbody_system.length ) multiples_code = encounters.Multiples( - gravity_code = code, - handle_encounter_code = encounter_code + gravity_code=code, + handle_encounter_code=encounter_code ) multiples_code.singles_in_binaries.add_particles(singles_in_binaries) multiples_code.binaries.add_particles(binaries) - multiples_code.commit_particles() - - - - #stopping_condition = multiples_code.stopping_conditions.encounter_detection - #stopping_condition.enable() + multiples_code.commit_particles() + + # stopping_condition = multiples_code.stopping_conditions.encounter_detection + # stopping_condition.enable() stopping_condition = multiples_code.stopping_conditions.binaries_change_detection stopping_condition.enable() for x in multiples_code.binaries: @@ -941,28 +898,26 @@ def test15(self): for x in multiples_code.singles: print(x.key, x.mass) self.assertEqual(len(multiples_code.binaries) - len(stopping_condition.particles(0)) + len(stopping_condition.particles(1)), len(center_of_mass_particles)) - - + def test16(self): code = Hermite() - - + n = 10 - singles = datamodel.Particles(keys = range(1,n+1)) + singles = datamodel.Particles(keys=range(1, n+1)) singles.mass = 1 | nbody_system.mass for x in range(n): singles[x].position = [x*x, 0, 0] | nbody_system.length - singles.velocity = [0,0,0] | nbody_system.speed - - singles.radius = 0.5 | nbody_system.length - + singles.velocity = [0, 0, 0] | nbody_system.speed + + singles.radius = 0.5 | nbody_system.length + multiples_code = encounters.Multiples( - gravity_code = code, - handle_encounter_code = encounters.StickyHandleEncounter() + gravity_code=code, + handle_encounter_code=encounters.StickyHandleEncounter() ) multiples_code.singles.add_particles(singles) - multiples_code.commit_particles() - + multiples_code.commit_particles() + multiples_code.evolve_model(1 | nbody_system.time) print(len(multiples_code.multiples)) self.assertEqual(len(multiples_code.multiples), 1) @@ -975,18 +930,18 @@ def test16(self): with tempfile.NamedTemporaryFile() as temp: io.write_set_to_file( ( - multiples_code.singles, - multiples_code.singles_in_binaries, - multiples_code.binaries, - multiples_code.components_of_multiples, + multiples_code.singles, + multiples_code.singles_in_binaries, + multiples_code.binaries, + multiples_code.components_of_multiples, multiples_code.multiples ), temp.name, - # "multiples.hdf5", + # "multiples.hdf5", "hdf5", overwrite_file=True, - version = "2.0", - names = ( + version="2.0", + names=( "singles", "singles_in_binaries", "binaries", @@ -994,12 +949,12 @@ def test16(self): "multiples" ) ) - - multiples_code_loaded = encounters.Multiples( - gravity_code = Hermite(), - handle_encounter_code = encounters.StickyHandleEncounter() + + multiples_code_loaded = encounters.Multiples( + gravity_code=Hermite(), + handle_encounter_code=encounters.StickyHandleEncounter() ) - + ( singles, singles_in_binaries, @@ -1008,10 +963,10 @@ def test16(self): multiples ) = io.read_set_from_file( temp.name, - # "multiples.hdf5", + # "multiples.hdf5", "hdf5", - version = "2.0", - names = ( + version="2.0", + names=( "singles", "singles_in_binaries", "binaries", @@ -1023,33 +978,32 @@ def test16(self): self.assertEqual(len(singles), 8) self.assertEqual(len(binaries), 1) self.assertEqual(len(singles_in_binaries), 2) - #self.assertEquals(id(components_of_multiples), id(multiples[0].components[0].particles_set)) - + # self.assertEquals(id(components_of_multiples), id(multiples[0].components[0].particles_set)) + multiples_code_loaded.singles.add_particles(singles) multiples_code_loaded.singles_in_binaries.add_particles(singles_in_binaries) multiples_code_loaded.binaries.add_particles(binaries) multiples_code_loaded.components_of_multiples.add_particles(components_of_multiples) multiples_code_loaded.multiples.add_particles(multiples) - - multiples_code_loaded.commit_particles() - + + multiples_code_loaded.commit_particles() + self.assertEqual(len(multiples_code_loaded.multiples), 1) self.assertEqual(len(multiples_code_loaded.particles), 9) self.assertEqual(len(multiples_code_loaded.singles), 8) self.assertEqual(len(multiples_code_loaded.binaries), 1) self.assertEqual(len(multiples_code_loaded.singles_in_binaries), 2) - #self.assertEquals(id(multiples_code_loaded.components_of_multiples), id(multiples_code_loaded.multiples[0].components[0].particles_set)) - + # self.assertEquals(id(multiples_code_loaded.components_of_multiples), id(multiples_code_loaded.multiples[0].components[0].particles_set)) + multiples_code.evolve_model(4 | nbody_system.time) - + # need to use 3 here as the model_time is reset when doing a restart and we dit not set it after creating Hermite multiples_code_loaded.evolve_model(3.0 | nbody_system.time) - print(len(multiples_code.multiples), multiples_code.particles) print(multiples_code.particles.position - multiples_code_loaded.particles.position) - self.assertAlmostRelativeEquals(multiples_code.particles.position - multiples_code_loaded.particles.position, [0,0,0] | nbody_system.length) - + self.assertAlmostRelativeEquals(multiples_code.particles.position - multiples_code_loaded.particles.position, [0, 0, 0] | nbody_system.length) + for code in [multiples_code, multiples_code_loaded]: self.assertEqual(len(code.multiples), 1) self.assertEqual(len(code.particles), 8) diff --git a/src/amuse/test/suite/codes_tests/test_nbody6xx.py b/src/amuse/test/suite/codes_tests/test_nbody6xx.py index 2897f8b28c..a5fe6fcfc4 100644 --- a/src/amuse/test/suite/codes_tests/test_nbody6xx.py +++ b/src/amuse/test/suite/codes_tests/test_nbody6xx.py @@ -6,72 +6,70 @@ import math + class Nbody6xxInterfaceTests(TestWithMPI): - + def test1(self): instance = Nbody6xxInterface() instance.initialize_code() - res1 = instance.new_particle(mass = 11.0, radius = 2.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) - res2 = instance.new_particle(mass = 21.0, radius = 5.0, x = 10.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) - + res1 = instance.new_particle(mass=11.0, radius=2.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) + res2 = instance.new_particle(mass=21.0, radius=5.0, x=10.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) + self.assertEqual(1, res1['index_of_the_particle']) self.assertEqual(2, res2['index_of_the_particle']) - + retrieved_state1 = instance.get_state(1) retrieved_state2 = instance.get_state(2) - + self.assertEqual(11.0, retrieved_state1['mass']) self.assertEqual(21.0, retrieved_state2['mass']) self.assertEqual(0.0, retrieved_state1['x']) self.assertEqual(10.0, retrieved_state2['x']) - #self.assertEquals(2.0, retrieved_state1['radius']) - #self.assertEquals(5.0, retrieved_state2['radius']) - + # self.assertEquals(2.0, retrieved_state1['radius']) + # self.assertEquals(5.0, retrieved_state2['radius']) + instance.cleanup_code() instance.stop() - def test2(self): instance = Nbody6xxInterface() instance.initialize_code() - - instance.new_particle([10,20],[0,0],[0,0], [0,0], [0,0], [0,0], [0,0],[1,1]) + + instance.new_particle([10, 20], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 1]) retrieved_state = instance.get_state(1) - + self.assertEqual(10.0, retrieved_state['mass']) - #self.assertEquals(1, retrieved_state['radius']) - - retrieved_state = instance.get_state([1,2]) - + # self.assertEquals(1, retrieved_state['radius']) + + retrieved_state = instance.get_state([1, 2]) + self.assertEqual(20.0, retrieved_state['mass'][1]) self.assertEqual(instance.get_number_of_particles()['number_of_particles'], 2) - instance.cleanup_code() + instance.cleanup_code() instance.stop() - - + def xtest3(self): - instance = Nbody6xxInterface(redirection="none")#,debugger="ddd") + instance = Nbody6xxInterface(redirection="none") # ,debugger="ddd") self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - + # Set up an equal-mass binary on a circular orbit: self.assertEqual([1, 0], list(instance.new_particle(0.5, 0.5, 0, 0, 0, 0.5, 0, 0.01).values())) - self.assertEqual([2, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0,-0.5, 0, 0.01).values())) - self.assertEqual([3, 0], list(instance.new_particle(100.5, -0.5, 0, 0, 0,-0.5, 0, 0.01).values())) + self.assertEqual([2, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0, -0.5, 0, 0.01).values())) + self.assertEqual([3, 0], list(instance.new_particle(100.5, -0.5, 0, 0, 0, -0.5, 0, 0.01).values())) self.assertEqual(0, instance.commit_particles()) - + self.assertEqual(0, instance.evolve_model(math.pi)) for result, expected in zip(instance.get_position(1).values(), [-0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 3) for result, expected in zip(instance.get_position(2).values(), [0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 3) - + self.assertEqual(0, instance.evolve_model(2 * math.pi)) for result, expected in zip(instance.get_position(1).values(), [0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 3) for result, expected in zip(instance.get_position(2).values(), [-0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 3) - + self.assertEqual(0, instance.cleanup_code()) instance.stop() - diff --git a/src/amuse/test/suite/codes_tests/test_octgrav.py b/src/amuse/test/suite/codes_tests/test_octgrav.py index 918196b229..2cc9a4e56d 100644 --- a/src/amuse/test/suite/codes_tests/test_octgrav.py +++ b/src/amuse/test/suite/codes_tests/test_octgrav.py @@ -10,10 +10,12 @@ from amuse import datamodel from amuse.rfi import channel from amuse.ic.plummer import * + + class TestMPIInterface(TestWithMPI): def test1(self): - + instance = self.new_instance_of_an_optional_code(OctgravInterface) instance.new_particle(11.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0) retrieved_state = instance.get_state(1) @@ -24,33 +26,33 @@ def test1(self): instance.stop() def test2(self): - + instance = self.new_instance_of_an_optional_code(OctgravInterface) instance.initialize_code() instance.new_particle( - [1,10,100], - [3,12,102], - [4,13,103], - [5,14,104], - [6,15,105], - [7,16,106], - [8,17,107], - [2,11,101]) - + [1, 10, 100], + [3, 12, 102], + [4, 13, 103], + [5, 14, 104], + [6, 15, 105], + [7, 16, 106], + [8, 17, 107], + [2, 11, 101]) + particle1_state = instance.get_state(1) self.assertEqual(1, particle1_state['mass']) - + particle2_state = instance.get_state(2) self.assertEqual(10, particle2_state['mass']) - + instance.delete_particle(1) - + size_result = instance.get_number_of_particles() self.assertEqual(2, size_result['number_of_particles']) - + new_particle1_state = instance.get_state(1) self.assertEqual(10, new_particle1_state['mass']) - + new_particle_result = instance.new_particle( 1000, 1002, @@ -60,14 +62,14 @@ def test2(self): 1006, 1007, 1001) - self.assertEqual(4, new_particle_result['index_of_the_particle'],4) - + self.assertEqual(4, new_particle_result['index_of_the_particle'], 4) + new_particle4_state = instance.get_state(4) self.assertEqual(1000, new_particle4_state['mass']) - + instance.cleanup_code() instance.stop() - + def test3(self): instance = self.new_instance_of_an_optional_code(OctgravInterface) instance.initialize_code() @@ -75,57 +77,57 @@ def test3(self): instance.commit_parameters() ids = [] for i in range(32): - id,errorcode = instance.new_particle(mass = 10.0, radius = 1.0, x = i, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) + id, errorcode = instance.new_particle(mass=10.0, radius=1.0, x=i, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) ids.append(id) self.assertEqual(errorcode, 0) instance.commit_particles() potential, errorcode = instance.get_potential(ids[0]) self.assertEqual(errorcode, 0) - excpected_potential = numpy.sum([ -10.0 / numpy.sqrt((x+1.0)**2 + 0.1**2) for x in range(31)]) - self.assertAlmostRelativeEquals(potential,excpected_potential , 5) + excpected_potential = numpy.sum([-10.0 / numpy.sqrt((x+1.0)**2 + 0.1**2) for x in range(31)]) + self.assertAlmostRelativeEquals(potential, excpected_potential, 5) total_potential, errorcode = instance.get_potential_energy() potentials, errorcode = instance.get_potential(ids) - + self.assertAlmostRelativeEquals(total_potential, numpy.sum(potentials * 10.0) / 2.0) - + class TestAmuseInterface(TestWithMPI): def new_system_of_sun_and_earth(self): stars = datamodel.Stars(2) sun = stars[0] sun.mass = units.MSun(1.0) - sun.position = units.m(numpy.array((0.0,0.0,0.0))) - sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) + sun.position = units.m(numpy.array((0.0, 0.0, 0.0))) + sun.velocity = units.ms(numpy.array((0.0, 0.0, 0.0))) sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) - earth.radius = units.km(6371) - earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) - earth.velocity = units.ms(numpy.array((0.0,29800,0.0))) - + earth.radius = units.km(6371) + earth.position = units.km(numpy.array((149.5e6, 0.0, 0.0))) + earth.velocity = units.ms(numpy.array((0.0, 29800, 0.0))) + return stars def test0(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, units.AU) instance = self.new_instance_of_an_optional_code(Octgrav, convert_nbody) instance.initialize_code() - self.assertAlmostRelativeEqual(0.01, instance.parameters.epsilon_squared.value_in(units.AU**2), 2)#default + self.assertAlmostRelativeEqual(0.01, instance.parameters.epsilon_squared.value_in(units.AU**2), 2) # default instance.parameters.epsilon_squared = 0.05 | units.AU**2 self.assertAlmostRelativeEqual(0.05, instance.parameters.epsilon_squared.value_in(units.AU**2), 6) - - self.assertAlmostEqual(0.8, instance.parameters.opening_angle, 6)#default + + self.assertAlmostEqual(0.8, instance.parameters.opening_angle, 6) # default instance.parameters.opening_angle = 0.5 self.assertAlmostEqual(0.5, instance.parameters.opening_angle, 6) - instance.parameters.timestep = 1.0 |units.s - self.assertEqual(1.0|units.s, instance.parameters.timestep) + instance.parameters.timestep = 1.0 | units.s + self.assertEqual(1.0 | units.s, instance.parameters.timestep) instance.stop() def test1(self): plummer_size = 500 convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) - stars = new_plummer_model(plummer_size, convert_nbody) - stars.radius = range(1, plummer_size+1)|units.km + stars = new_plummer_model(plummer_size, convert_nbody) + stars.radius = range(1, plummer_size+1) | units.km instance = self.new_instance_of_an_optional_code(Octgrav, convert_nbody) instance.particles.add_particles(stars) @@ -140,40 +142,40 @@ def test1(self): def test2(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) - + instance = self.new_instance_of_an_optional_code(Octgrav, convert_nbody) instance.initialize_code() instance.parameters.epsilon_squared = 0.0 | units.AU**2 instance.parameters.stopping_conditions_number_of_steps = 1 - self.assertEqual(instance.parameters.stopping_conditions_number_of_steps,1) - + self.assertEqual(instance.parameters.stopping_conditions_number_of_steps, 1) + stars = self.new_system_of_sun_and_earth() earth = stars[1] - + instance.particles.add_particles(stars) instance.stopping_conditions.number_of_steps_detection.enable() instance.evolve_model(365.0 | units.day) self.assertTrue(instance.stopping_conditions.number_of_steps_detection.is_set()) instance.cleanup_code() instance.stop() - + def test3(self): particles = datamodel.Particles(2) - particles.x = [0.0,10.0] | nbody_system.length + particles.x = [0.0, 10.0] | nbody_system.length particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.radius = 0.005 | nbody_system.length - particles.vx = 0 | nbody_system.speed - particles.vy = 0 | nbody_system.speed - particles.vz = 0 | nbody_system.speed + particles.vx = 0 | nbody_system.speed + particles.vy = 0 | nbody_system.speed + particles.vz = 0 | nbody_system.speed particles.mass = 1.0 | nbody_system.mass - + instance = self.new_instance_of_an_optional_code(Octgrav) instance.initialize_code() instance.parameters.stopping_conditions_number_of_steps = 20 self.assertEqual(instance.parameters.stopping_conditions_number_of_steps, 20) instance.parameters.epsilon_squared = (0.01 | nbody_system.length)**2 - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.stopping_conditions.number_of_steps_detection.enable() instance.evolve_model(10 | nbody_system.time) self.assertTrue(instance.stopping_conditions.number_of_steps_detection.is_set()) @@ -183,28 +185,27 @@ def test3(self): def test4(self): plummer_size = 500 stars = new_plummer_model(plummer_size) - stars.radius=0|nbody_system.length + stars.radius = 0 | nbody_system.length instance = self.new_instance_of_an_optional_code(Octgrav) instance.particles.add_particles(stars) instance.synchronize_model() - ax,ay,az=instance.get_gravity_at_point(0. | nbody_system.length, - 0. | nbody_system.length, + ax, ay, az = instance.get_gravity_at_point(0. | nbody_system.length, + 0. | nbody_system.length, 100. | nbody_system.length, 0. | nbody_system.length) - self.assertAlmostEqual(ax.number,0., 3) - self.assertAlmostRelativeEqual(ay.number,-1./100**2, 3) - self.assertAlmostEqual(az.number,0., 3) - + self.assertAlmostEqual(ax.number, 0., 3) + self.assertAlmostRelativeEqual(ay.number, -1./100**2, 3) + self.assertAlmostEqual(az.number, 0., 3) - pot=instance.get_potential_at_point([0.,0.]|nbody_system.length, - [0.,100] | nbody_system.length, - [100.,0.] | nbody_system.length, - [0.,0.] | nbody_system.length) + pot = instance.get_potential_at_point([0., 0.] | nbody_system.length, + [0., 100] | nbody_system.length, + [100., 0.] | nbody_system.length, + [0., 0.] | nbody_system.length) - self.assertAlmostRelativeEqual(pot.number,[-1/100.,-1/100.], 3) + self.assertAlmostRelativeEqual(pot.number, [-1/100., -1/100.], 3) instance.stop() diff --git a/src/amuse/test/suite/codes_tests/test_parallel.py b/src/amuse/test/suite/codes_tests/test_parallel.py index 6fd4f6c005..6429a36ac2 100644 --- a/src/amuse/test/suite/codes_tests/test_parallel.py +++ b/src/amuse/test/suite/codes_tests/test_parallel.py @@ -17,22 +17,23 @@ except ImportError: HAS_MATPLOTLIB = False + class TestAmuseInterface(TestWithMPI): def new_system_sun_and_earth(self): result = Particles(2) sun = result[0] sun.mass = units.MSun(1.0) - sun.position = units.m(numpy.array((0.0,0.0,0.0))) - sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) + sun.position = units.m(numpy.array((0.0, 0.0, 0.0))) + sun.velocity = units.ms(numpy.array((0.0, 0.0, 0.0))) sun.radius = units.RSun(1.0) earth = result[1] earth.mass = units.kg(5.9736e24) - earth.radius = units.km(6371) - earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) - earth.velocity = units.ms(numpy.array((0.0,29800,0.0))) + earth.radius = units.km(6371) + earth.position = units.km(numpy.array((149.5e6, 0.0, 0.0))) + earth.velocity = units.ms(numpy.array((0.0, 29800, 0.0))) return result - + def evolve_model_unit_day(self, instance, particles, day): delta_days = 5 for x in range(1, day + delta_days, delta_days): @@ -53,63 +54,59 @@ def test2(self): bhtree = BHTree(convert_nbody) bhtree.initialize_code() bhtree.eps2_for_gravity = 0.001 - + bhtree_particles = self.new_system_sun_and_earth() bhtree.particles.add_particles(bhtree_particles) - + if bhtree.legacy_interface.channel_type == 'mpi': from mpi4py import MPI if not MPI.Query_thread() == MPI.THREAD_MULTIPLE: bhtree.stop() self.skip("can only test parallel with multiple thread support in mpi implementation") - - + hermite = Hermite(convert_nbody) hermite.dt_dia = 5000 hermite.commit_parameters() - + hermite_particles = self.new_system_sun_and_earth() hermite.particles.add_particles(hermite_particles) - - thread1 = threading.Thread(target = self.evolve_model_unit_day, args = (bhtree, bhtree_particles, 10)) - thread2 = threading.Thread(target = self.evolve_model_unit_day, args = (hermite, hermite_particles, 10)) - + + thread1 = threading.Thread(target=self.evolve_model_unit_day, args=(bhtree, bhtree_particles, 10)) + thread2 = threading.Thread(target=self.evolve_model_unit_day, args=(hermite, hermite_particles, 10)) + thread1.start() thread2.start() - + thread1.join() thread2.join() - - - + if HAS_MATPLOTLIB: figure = pyplot.figure() - plot = figure.add_subplot(1,1,1) - + plot = figure.add_subplot(1, 1, 1) + earth = bhtree_particles[1] x_points = earth.get_timeline_of_attribute("x") y_points = earth.get_timeline_of_attribute("y") x_points_in_AU = [t_x[1].value_in(units.AU) for t_x in x_points] y_points_in_AU = [t_x1[1].value_in(units.AU) for t_x1 in y_points] - - plot.scatter(x_points_in_AU,y_points_in_AU, color = "b", marker = 'o') - + + plot.scatter(x_points_in_AU, y_points_in_AU, color="b", marker='o') + earth = hermite_particles[1] x_points = earth.get_timeline_of_attribute("x") y_points = earth.get_timeline_of_attribute("y") x_points_in_AU = [t_x2[1].value_in(units.AU) for t_x2 in x_points] y_points_in_AU = [t_x3[1].value_in(units.AU) for t_x3 in y_points] - - plot.scatter(x_points_in_AU,y_points_in_AU, color = "g", marker = 'o') - + + plot.scatter(x_points_in_AU, y_points_in_AU, color="g", marker='o') + plot.set_xlim(-1.5, 1.5) plot.set_ylim(-1.5, 1.5) - + test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "parallel-earth-sun.svg") figure.savefig(output_file) - + bhtree.stop() hermite.stop() bhtree.stop() - diff --git a/src/amuse/test/suite/codes_tests/test_parameter_doc.py b/src/amuse/test/suite/codes_tests/test_parameter_doc.py index 2b32b12a64..9c0e015172 100644 --- a/src/amuse/test/suite/codes_tests/test_parameter_doc.py +++ b/src/amuse/test/suite/codes_tests/test_parameter_doc.py @@ -8,6 +8,8 @@ from amuse.units import nbody_system from amuse.units import units from amuse import datamodel + + class TestParameterDoc(amusetest.TestCase): def test_bhtree(self): @@ -20,7 +22,7 @@ def test_bhtree(self): bhtree.parameters.timestep = 1.0 | units.s bhtree.parameters.opening_angle = 0.1 - docstring = bhtree.parameters.__doc__ + docstring = bhtree.parameters.__doc__ self.assertTrue("smoothing parameter for gravity calculations (default value:125000.0 m**2)" in docstring) @@ -38,13 +40,12 @@ def test_hermite(self): hermite.parameters.epsilon_squared = 10 | units.km**2 - docstring = hermite.parameters.__doc__ + docstring = hermite.parameters.__doc__ self.assertTrue("smoothing parameter for gravity calculations (default value:0.0 m**2)" in docstring) parameter_str_method_output = str(hermite.parameters) self.assertTrue("epsilon_squared: 10000000.0 m**2" in parameter_str_method_output) - def test_phigrape(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.kg, 1.0 | units.km) @@ -52,7 +53,7 @@ def test_phigrape(self): phigrape = PhiGRAPE(convert_nbody) phigrape.parameters.epsilon_squared = 10 | units.km**2 - docstring = phigrape.parameters.__doc__ + docstring = phigrape.parameters.__doc__ print(docstring) self.assertTrue("smoothing parameter for gravity calculations (default value:0.0 m**2)" in docstring) self.assertTrue("timestep parameter (default value:0.02" in docstring) diff --git a/src/amuse/test/suite/codes_tests/test_particle_attributes.py b/src/amuse/test/suite/codes_tests/test_particle_attributes.py index 6ce77f39bf..620d91b9cb 100644 --- a/src/amuse/test/suite/codes_tests/test_particle_attributes.py +++ b/src/amuse/test/suite/codes_tests/test_particle_attributes.py @@ -13,114 +13,115 @@ from amuse.datamodel import Particle, Particles, ParticlesWithUnitsConverted from amuse.datamodel import particle_attributes + class TestParticlesAttributes(amusetest.TestCase): - + def test3(self): print("Test new_particle_from_cluster_core - nbody units") numpy.random.seed(123) plummer = new_plummer_sphere(10000) result = plummer.new_particle_from_cluster_core(density_weighting_power=1, reuse_hop=True) self.assertTrue(isinstance(result, Particle)) - + # Casertano & Hut (1985, ApJ, 298, 80): density weighted core radius = 0.6791 * r_plummer plummer_radius = 3 * constants.pi / 16.0 | nbody_system.length self.assertAlmostRelativeEqual(result.radius, 0.6791 * plummer_radius, 2) self.assertAlmostEqual(result.position, [0.0, 0.0, 0.0] | nbody_system.length, 1) self.assertAlmostEqual(result.velocity, [0.0, 0.0, 0.0] | nbody_system.speed, 1) self.assertAlmostEqual(result.density, 3.55015420914 | nbody_system.density) - + plummer.vx += 42 | nbody_system.speed - plummer.vy += (1 - plummer.y / abs(plummer.y).amax()) * (13|nbody_system.speed) + plummer.vy += (1 - plummer.y / abs(plummer.y).amax()) * (13 | nbody_system.speed) plummer.position *= 0.1 plummer.position += [1.0, 2.0, 3.0] | nbody_system.length result = plummer.new_particle_from_cluster_core(density_weighting_power=1, reuse_hop=False) self.assertTrue(isinstance(result, Particle)) - + self.assertAlmostRelativeEqual(result.radius, 0.06791 * plummer_radius, 2) self.assertAlmostEqual(result.position, [1.0, 2.0, 3.0] | nbody_system.length, 1) self.assertAlmostEqual(result.velocity, [42.0, 13.0, 0.0] | nbody_system.speed, 1) self.assertAlmostRelativeEqual(result.density, 3.55015420914e3 | nbody_system.density, 4) - + def test4(self): print("Test new_particle_from_cluster_core - SI units") numpy.random.seed(123) - converter = nbody_system.nbody_to_si(1000.0|units.MSun, 1.0 | units.parsec) + converter = nbody_system.nbody_to_si(1000.0 | units.MSun, 1.0 | units.parsec) plummer = new_plummer_sphere(10000, convert_nbody=converter) result = plummer.new_particle_from_cluster_core(unit_converter=converter, density_weighting_power=1, reuse_hop=True) self.assertTrue(isinstance(result, Particle)) - + # Casertano & Hut (1985, ApJ, 298, 80): density weighted core radius = 0.6791 * r_plummer plummer_radius = 3 * constants.pi / 16.0 | units.parsec self.assertAlmostRelativeEqual(result.radius, 0.6791 * plummer_radius, 2) self.assertAlmostEqual(result.position, [0.0, 0.0, 0.0] | units.parsec, 1) self.assertAlmostEqual(result.velocity, [0.0, 0.0, 0.0] | units.km / units.s, 1) self.assertAlmostEqual(result.density, 3.55015420914e3 | units.MSun * units.parsec**-3) - + plummer.vx += 42 | units.km / units.s - plummer.vy += (1 - plummer.y / abs(plummer.y).amax()) * (13|units.km / units.s) + plummer.vy += (1 - plummer.y / abs(plummer.y).amax()) * (13 | units.km / units.s) plummer.position *= 0.1 plummer.position += [1.0, 2.0, 3.0] | units.parsec result = plummer.new_particle_from_cluster_core(unit_converter=converter, density_weighting_power=1, reuse_hop=False) self.assertTrue(isinstance(result, Particle)) - + self.assertAlmostRelativeEqual(result.radius, 0.06791 * plummer_radius, 2) self.assertAlmostEqual(result.position, [1.0, 2.0, 3.0] | units.parsec, 1) self.assertAlmostEqual(result.velocity, [42.0, 13.0, 0.0] | units.km / units.s, 1) self.assertAlmostRelativeEqual(result.density, 3.55015420914e6 | units.MSun * units.parsec**-3, 4) - + def test5(self): print("Test new_particle_from_cluster_core - reuse_hop or not") - converter = nbody_system.nbody_to_si(1.0|units.MSun, 1.0 | units.parsec) + converter = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.parsec) plummer = new_plummer_sphere(100, convert_nbody=converter) result = plummer.new_particle_from_cluster_core(unit_converter=converter, reuse_hop=True) - + # Hop wasn't stopped, will use same Hop instance: result = plummer.new_particle_from_cluster_core(unit_converter=converter, reuse_hop=True) - + nbody_plummer = new_plummer_sphere(100) # Hop wasn't stopped, unit_converters don't match: - self.assertRaises(AttributeError, nbody_plummer.new_particle_from_cluster_core, + self.assertRaises(AttributeError, nbody_plummer.new_particle_from_cluster_core, expected_message="Cannot combine units from different systems: m and length") - + result = plummer.new_particle_from_cluster_core(unit_converter=converter, reuse_hop=False) - + # Hop was stopped, new instance will be made with supplied unit_converter (None in this case): result = nbody_plummer.new_particle_from_cluster_core(reuse_hop=True) - - self.assertRaises(ConvertArgumentsException, plummer.new_particle_from_cluster_core, unit_converter=converter,#, + + self.assertRaises(ConvertArgumentsException, plummer.new_particle_from_cluster_core, unit_converter=converter, # , expected_message="error while converting parameter 'mass', error: Cannot express kg in mass, the units do not have the same bases") - + result = nbody_plummer.new_particle_from_cluster_core(reuse_hop=False) result = plummer.new_particle_from_cluster_core(unit_converter=converter, reuse_hop=False) - + def test6(self): print("Test all particle attributes using Hop - each different function creates its own instance of Hop") numpy.random.seed(123) nbody_plummer = new_plummer_sphere(100) nbody_plummer.mass = new_salpeter_mass_distribution_nbody(100) - + # Each different function creates its own instance of Hop result = nbody_plummer.new_particle_from_cluster_core(reuse_hop=True) result = nbody_plummer.bound_subset(G=nbody_system.G, reuse_hop=True) result = nbody_plummer.mass_segregation_Gini_coefficient(reuse_hop=True) result = nbody_plummer.LagrangianRadii(reuse_hop=True) result = nbody_plummer.densitycentre_coreradius_coredens(reuse_hop=True) - - converter = nbody_system.nbody_to_si(1.0|units.MSun, 1.0 | units.parsec) + + converter = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.parsec) si_plummer = ParticlesWithUnitsConverted(nbody_plummer, converter.as_converter_from_si_to_nbody()) functions_using_hop = [ - si_plummer.new_particle_from_cluster_core, - si_plummer.bound_subset, - si_plummer.mass_segregation_Gini_coefficient, - si_plummer.LagrangianRadii, + si_plummer.new_particle_from_cluster_core, + si_plummer.bound_subset, + si_plummer.mass_segregation_Gini_coefficient, + si_plummer.LagrangianRadii, si_plummer.densitycentre_coreradius_coredens ] - + # Each fails since the Hop instance it tries to reuse has a different unit_converter for function_using_hop in functions_using_hop: self.assertRaises(Exception, function_using_hop, unit_converter=converter) # expected_message="error while converting parameter 'mass', error: Cannot express kg in mass, the units do not have the same bases (note: check whether Hop needs a converter here)") - + # Close all Hop instances: nbody_results = [] nbody_results.append(nbody_plummer.new_particle_from_cluster_core(reuse_hop=False)) @@ -128,20 +129,18 @@ def test6(self): nbody_results.append(nbody_plummer.mass_segregation_Gini_coefficient(reuse_hop=False)) nbody_results.append(nbody_plummer.LagrangianRadii(reuse_hop=False)) nbody_results.append(nbody_plummer.densitycentre_coreradius_coredens(reuse_hop=False)) - + # Now it works, because the Hop instances were closed, and new ones will be instantiated si_results = [] for function_using_hop in functions_using_hop: si_results.append(function_using_hop(unit_converter=converter)) - + convert = converter.as_converter_from_si_to_nbody() - self.assertAlmostRelativeEqual(si_results[0].position, + self.assertAlmostRelativeEqual(si_results[0].position, ParticlesWithUnitsConverted(nbody_results[0].as_set(), convert)[0].position) - self.assertAlmostRelativeEqual(si_results[1].position, + self.assertAlmostRelativeEqual(si_results[1].position, ParticlesWithUnitsConverted(nbody_results[1], convert).position) self.assertAlmostRelativeEqual(si_results[2], nbody_results[2], places=10) self.assertAlmostRelativeEqual(si_results[3][0], convert.from_target_to_source(nbody_results[3][0]), places=10) for in_si, in_nbody in zip(si_results[4], nbody_results[4]): self.assertAlmostRelativeEqual(in_si, convert.from_target_to_source(in_nbody), places=10) - - diff --git a/src/amuse/test/suite/codes_tests/test_ph4.py b/src/amuse/test/suite/codes_tests/test_ph4.py index ca1caef4b0..40a5c17f5f 100644 --- a/src/amuse/test/suite/codes_tests/test_ph4.py +++ b/src/amuse/test/suite/codes_tests/test_ph4.py @@ -36,48 +36,46 @@ def test7(self): instance.initialize_code() instance.set_eps2(0.1**2) instance.commit_parameters() - id1,errorcode = instance.new_particle(mass = 10.0, radius = 1.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) - id2,errorcode = instance.new_particle(mass = 10.0, radius = 1.0, x = 2.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) - + id1, errorcode = instance.new_particle(mass=10.0, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) + id2, errorcode = instance.new_particle(mass=10.0, radius=1.0, x=2.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) + instance.commit_particles() potential, errorcode = instance.get_potential(id1) self.assertEqual(errorcode, 0) self.assertAlmostRelativeEquals(potential, -10.0 / numpy.sqrt(2.0**2 + 0.1**2), 8) total_potential, errorcode = instance.get_potential_energy() potentials, errorcode = instance.get_potential([id1, id2]) - + instance.cleanup_code() instance.stop() - + self.assertAlmostRelativeEquals(total_potential, numpy.sum(potentials * [10.0, 10.0]) / 2.0) - - + def test8(self): instance = ph4Interface() instance.initialize_code() instance.set_eps2(0) instance.commit_parameters() - id1,errorcode = instance.new_particle(mass = 10.0, radius = 1.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) - id2,errorcode = instance.new_particle(mass = 1.0, radius = 1.0, x = 2.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) - + id1, errorcode = instance.new_particle(mass=10.0, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) + id2, errorcode = instance.new_particle(mass=1.0, radius=1.0, x=2.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) + instance.commit_particles() potential, errorcode = instance.get_potential(id1) self.assertEqual(errorcode, 0) self.assertAlmostRelativeEquals(potential, -1.0 / numpy.sqrt(2.0**2), 8) - + potential, errorcode = instance.get_potential(id2) self.assertEqual(errorcode, 0) self.assertAlmostRelativeEquals(potential, -10.0 / numpy.sqrt(2.0**2), 8) - + total_potential, errorcode = instance.get_potential_energy() potentials, errorcode = instance.get_potential([id1, id2]) - + instance.cleanup_code() instance.stop() - + self.assertAlmostRelativeEquals(total_potential, numpy.sum(potentials * [10.0, 1.0]) / 2.0) - - + def test9(self): instance = ph4Interface() instance.initialize_code() @@ -85,13 +83,13 @@ def test9(self): index, error = instance.new_particle(11.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 10) self.assertEqual(error, 0) self.assertEqual(index, 10) - #index, error = instance.new_particle(12.0, 3.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 10) - #print index, error + # index, error = instance.new_particle(12.0, 3.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 10) + # print index, error # self.assertEquals(error, -1) - #self.assertEquals(index, 10) + # self.assertEquals(index, 10) error = instance.commit_particles() self.assertEqual(error, 0) - + retrieved_state = instance.get_state(index) self.assertEqual(retrieved_state['__result'], 0) self.assertEqual(11.0, retrieved_state['mass']) @@ -100,257 +98,252 @@ def test9(self): instance.cleanup_code() instance.stop() + class TestPH4(TestWithMPI): def new_system_of_sun_and_earth(self): stars = datamodel.Stars(2) sun = stars[0] sun.mass = units.MSun(1.0) - sun.position = units.m(numpy.array((0.0,0.0,0.0))) - sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) + sun.position = units.m(numpy.array((0.0, 0.0, 0.0))) + sun.velocity = units.ms(numpy.array((0.0, 0.0, 0.0))) sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) - earth.radius = units.km(6371) - earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) - earth.velocity = units.ms(numpy.array((0.0,29800,0.0))) - + earth.radius = units.km(6371) + earth.position = units.km(numpy.array((149.5e6, 0.0, 0.0))) + earth.velocity = units.ms(numpy.array((0.0, 29800, 0.0))) + return stars - - + def test0(self): instance = ph4() instance.stop() - + def test1(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) - instance = ph4(convert_nbody)#, redirection="none")#, debugger="xterm") + instance = ph4(convert_nbody) # , redirection="none")#, debugger="xterm") instance.initialize_code() - + instance.parameters.epsilon_squared = 0.0 | units.AU**2 instance.parameters.timestep_parameter = 0.01 - + stars = self.new_system_of_sun_and_earth() earth = stars[1] - + instance.particles.add_particles(stars) instance.commit_particles() - + instance.evolve_model(365 | units.day) - + instance.particles.copy_values_of_all_attributes_to(stars) - + position_at_start = earth.position.value_in(units.AU)[0] position_after_full_rotation = earth.position.value_in(units.AU)[0] self.assertAlmostEqual(position_at_start, position_after_full_rotation, 6) - + instance.evolve_model(365.0 + (365.0 / 2) | units.day) - + instance.particles.copy_values_of_all_attributes_to(stars) position_after_half_a_rotation = earth.position.value_in(units.AU)[0] self.assertAlmostEqual(-position_at_start, position_after_half_a_rotation, 3) - - instance.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) - + + instance.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) + instance.particles.copy_values_of_all_attributes_to(stars) position_after_half_a_rotation = earth.position.value_in(units.AU)[1] self.assertAlmostEqual(-position_at_start, position_after_half_a_rotation, 3) - + instance.cleanup_code() - + instance.stop() def test2(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) instance = ph4(convert_nbody) - + instance.initialize_code() instance.parameters.epsilon_squared = 0.0 | units.AU**2 instance.parameters.timestep_parameter = 0.01 instance.dt_dia = 5000 - + stars = self.new_system_of_sun_and_earth() earth = stars[1] instance.particles.add_particles(stars) instance.commit_particles() - - for x in range(1,365,30): + + for x in range(1, 365, 30): instance.evolve_model(x | units.day) instance.particles.copy_values_of_all_attributes_to(stars) stars.savepoint() - + if HAS_MATPLOTLIB: figure = pyplot.figure() - plot = figure.add_subplot(1,1,1) - + plot = figure.add_subplot(1, 1, 1) + x_points = earth.get_timeline_of_attribute("x") y_points = earth.get_timeline_of_attribute("y") - + x_points_in_AU = [t_x[1].value_in(units.AU) for t_x in x_points] y_points_in_AU = [t_x1[1].value_in(units.AU) for t_x1 in y_points] - - plot.scatter(x_points_in_AU,y_points_in_AU, color = "b", marker = 'o') - + + plot.scatter(x_points_in_AU, y_points_in_AU, color="b", marker='o') + plot.set_xlim(-1.5, 1.5) plot.set_ylim(-1.5, 1.5) - + test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "ph4-earth-sun2.svg") figure.savefig(output_file) - + instance.cleanup_code() instance.stop() - - + def test3(self): convert_nbody = nbody_system.nbody_to_si(5.0 | units.kg, 10.0 | units.m) instance = ph4(convert_nbody) instance.initialize_code() - + particles = datamodel.Particles(2) self.assertEqual(len(instance.particles), 0) - + particles.mass = [15.0, 30.0] | units.kg - particles.radius = [10.0, 20.0] | units.m + particles.radius = [10.0, 20.0] | units.m particles.position = [[10.0, 20.0, 30.0], [20.0, 40.0, 60.0]] | units.m particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.m / units.s - instance.particles.add_particles(particles) self.assertEqual(len(instance.particles), 2) instance.commit_particles() - - instance.particles.mass = [17.0, 33.0] | units.kg - - self.assertEqual(instance.get_mass(1), 17.0| units.kg) - self.assertEqual(instance.get_mass(2), 33.0| units.kg) - + + instance.particles.mass = [17.0, 33.0] | units.kg + + self.assertEqual(instance.get_mass(1), 17.0 | units.kg) + self.assertEqual(instance.get_mass(2), 33.0 | units.kg) + instance.cleanup_code() instance.stop() - + def test4(self): instance = ph4() instance.initialize_code() - + particles = datamodel.Particles(6) - particles.mass = nbody_system.mass.new_quantity(range(1,7)) - particles.radius = 0.00001 | nbody_system.length - particles.position = [[-1.0,0.0,0.0],[1.0,0.0,0.0],[0.0,-1.0,0.0],[0.0,1.0,0.0],[0.0,0.0,-1.0],[0.0,0.0,1.0]] | nbody_system.length - particles.velocity = [[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0]] | nbody_system.speed + particles.mass = nbody_system.mass.new_quantity(range(1, 7)) + particles.radius = 0.00001 | nbody_system.length + particles.position = [[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0], [0.0, 0.0, 1.0]] | nbody_system.length + particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed instance.particles.add_particles(particles) - + instance.commit_particles() copyof = instance.particles.copy() - + instance.cleanup_code() instance.stop() - - self.assertEqual(2 | nbody_system.mass, copyof[1].mass) - - + + self.assertEqual(2 | nbody_system.mass, copyof[1].mass) + def test5(self): instance = ph4() instance.initialize_code() instance.parameters.manage_encounters = 2 instance.parameters.epsilon_squared = 0.0 | nbody_system.length ** 2 particles = datamodel.Particles(6) - particles.mass = [0.01, 0.1, 0.1, 0.1, 0.1, 0.1] | nbody_system.mass - particles.radius = 0.1 | nbody_system.length + particles.mass = [0.01, 0.1, 0.1, 0.1, 0.1, 0.1] | nbody_system.mass + particles.radius = 0.1 | nbody_system.length particles.position = [ - [-1.0,0.0,0.0], #first two close together - [-1.2,0.0,0.0], - [0.0,4.0,0.0], #rest far away - [0.0,5.0,0.0], - [0.0,6.0,0.0], - [0.0,7.0,0.0] + [-1.0, 0.0, 0.0], # first two close together + [-1.2, 0.0, 0.0], + [0.0, 4.0, 0.0], # rest far away + [0.0, 5.0, 0.0], + [0.0, 6.0, 0.0], + [0.0, 7.0, 0.0] ] | nbody_system.length - particles.velocity = [[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0]] | nbody_system.speed - + particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed + instance.particles.add_particles(particles) - + instance.commit_particles() - instance.evolve_model(0.1 | nbody_system.time) - + instance.evolve_model(0.1 | nbody_system.time) + instance.update_particle_set() - + self.assertEqual(len(instance.particles), 5) - self.assertEqual(instance.particles.index_in_code, [3,4,5,6,10]) - self.assertEqual(instance.particles.mass, [0.1,0.1,0.1,0.1,0.11] | nbody_system.mass) - + self.assertEqual(instance.particles.index_in_code, [3, 4, 5, 6, 10]) + self.assertEqual(instance.particles.mass, [0.1, 0.1, 0.1, 0.1, 0.11] | nbody_system.mass) + self.assertEqual(len(particles), 6) instance.particles.synchronize_to(particles) self.assertEqual(len(particles), 5) - self.assertEqual(particles.mass, [0.1,0.1,0.1,0.1,0.11] | nbody_system.mass) - + self.assertEqual(particles.mass, [0.1, 0.1, 0.1, 0.1, 0.11] | nbody_system.mass) + binary_energy1, error = instance.legacy_interface.get_binary_energy() self.assertEqual(error, 0) self.assertTrue(binary_energy1 < 0) - + binary_energy2 = instance.get_binary_energy() - + instance.cleanup_code() instance.stop() - + self.assertEqual(binary_energy2.value_in(nbody_system.energy), binary_energy1) - + def test6(self): instance = ph4() instance.initialize_code() instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2 - particles = datamodel.Particles(2) particles.mass = [1.0, 1.0] | nbody_system.mass - particles.radius = [0.0001, 0.0001] | nbody_system.length - particles.position = [[0.0,0.0,0.0], [2.0,0.0,0.0]] | nbody_system.length + particles.radius = [0.0001, 0.0001] | nbody_system.length + particles.position = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]] | nbody_system.length particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed instance.particles.add_particles(particles) - + instance.commit_particles() - + zero = 0.0 | nbody_system.length - fx, fy, fz = instance.get_gravity_at_point(zero, 1.0| nbody_system.length, zero, zero) + fx, fy, fz = instance.get_gravity_at_point(zero, 1.0 | nbody_system.length, zero, zero) self.assertAlmostEqual(fx, 0.0 | nbody_system.acceleration, 3) self.assertAlmostEqual(fy, 0.0 | nbody_system.acceleration, 3) self.assertAlmostEqual(fz, 0.0 | nbody_system.acceleration, 3) for x in (0.25, 0.5, 0.75): - x0 = x| nbody_system.length + x0 = x | nbody_system.length x1 = (2.0 - x) | nbody_system.length potential0 = instance.get_potential_at_point(zero, x0, zero, zero) potential1 = instance.get_potential_at_point(zero, x1, zero, zero) fx0, fy0, fz0 = instance.get_gravity_at_point(zero, x0, zero, zero) fx1, fy1, fz1 = instance.get_gravity_at_point(zero, x1, zero, zero) - + self.assertAlmostEqual(fy0, 0.0 | nbody_system.acceleration, 3) self.assertAlmostEqual(fz0, 0.0 | nbody_system.acceleration, 3) self.assertAlmostEqual(fy1, 0.0 | nbody_system.acceleration, 3) self.assertAlmostEqual(fz1, 0.0 | nbody_system.acceleration, 3) - + self.assertAlmostEqual(fx0, -1.0 * fx1, 5) fx = (-1.0 / (x0**2) + 1.0 / (x1**2)) * (1.0 | nbody_system.length ** 3 / nbody_system.time ** 2) self.assertAlmostEqual(fx, fx0, 2) self.assertAlmostEqual(potential0, potential1, 5) - + instance.stop() - + def xtest7(self): instance = ph4() instance.initialize_code() instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2 - instance.set_eta(0.01,0.02) + instance.set_eta(0.01, 0.02) - particles = datamodel.Particles(2) particles.mass = [1.0, 1.0] | nbody_system.mass - particles.radius = [0.0001, 0.0001] | nbody_system.length - particles.position = [[0.0,0.0,0.0], [2.0,0.0,0.0]] | nbody_system.length + particles.radius = [0.0001, 0.0001] | nbody_system.length + particles.position = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]] | nbody_system.length particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed instance.particles.add_particles(particles) - - instance.initialize_particles(0.0 ) - + + instance.initialize_particles(0.0) + zero = [0.0, 0.0, 0.0] | nbody_system.length fx, fy, fz = instance.get_gravity_at_point(zero, [0.5, 1.0, 1.5] | nbody_system.length, zero, zero) self.assertAlmostRelativeEqual(fx[0], -3.55555555556 | nbody_system.acceleration, 5) @@ -362,26 +355,26 @@ def xtest7(self): self.assertAlmostRelativeEqual(fx[2], 3.55555555556 | nbody_system.acceleration, 5) self.assertAlmostRelativeEqual(fy[2], 0.0 | nbody_system.acceleration, 3) self.assertAlmostRelativeEqual(fz[2], 0.0 | nbody_system.acceleration, 3) - + n = 512 x = nbody_system.length.new_quantity(numpy.linspace(0.1, 1.9, n)) zero = nbody_system.length.new_quantity(numpy.zeros(n)) fx, fy, fz = instance.get_gravity_at_point(zero, x, zero, zero) for i in range(n/2): self.assertAlmostRelativeEqual(fx[i], - fx[n - 1 - i], 5) - + instance.stop() - + def xtest8(self): particles = datamodel.Particles(6) - particles.mass = nbody_system.mass.new_quantity(range(1,7)) - particles.radius = 0.00001 | nbody_system.length - particles.position = [[-1.0,0.0,0.0],[1.0,0.0,0.0],[0.0,-1.0,0.0],[0.0,1.0,0.0],[0.0,0.0,-1.0],[0.0,0.0,1.0]] | nbody_system.length - particles.velocity = [[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0]] | nbody_system.speed - + particles.mass = nbody_system.mass.new_quantity(range(1, 7)) + particles.radius = 0.00001 | nbody_system.length + particles.position = [[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0], [0.0, 0.0, 1.0]] | nbody_system.length + particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed + for current_mode in ['gpu']: try: - instance = ph4(mode = current_mode) + instance = ph4(mode=current_mode) except: print("Running PhiGRAPE with mode=", current_mode, " was unsuccessful.") else: @@ -393,70 +386,67 @@ def xtest8(self): instance.cleanup_code() instance.stop() print("ok") - - def test10(self): instance = ph4() instance.initialize_code() - + instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2 instance.parameters.timestep_parameter = 0.01 - + stars = new_plummer_model(100) - + instance.particles.add_particles(stars) channel = stars.new_channel_to(instance.particles) - + instance.evolve_model(0.001 | nbody_system.time) - + e0 = instance.kinetic_energy + instance.potential_energy - + stars.mass *= 0.9 channel.copy() - + instance.synchronize_model() - + e1 = instance.kinetic_energy + instance.potential_energy - + instance.cleanup_code() instance.stop() - + delta_e = e1 - e0 - + self.assertTrue(e1 != e0) def test10b(self): instance = ph4(number_of_workers=4) instance.initialize_code() - + instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2 instance.parameters.timestep_parameter = 0.01 - + stars = new_plummer_model(100) - + instance.particles.add_particles(stars) channel = stars.new_channel_to(instance.particles) - + instance.evolve_model(0.001 | nbody_system.time) - + e0 = instance.kinetic_energy + instance.potential_energy - + stars.mass *= 0.9 channel.copy() - + instance.synchronize_model() - + e1 = instance.kinetic_energy + instance.potential_energy - + instance.cleanup_code() instance.stop() - + delta_e = e1 - e0 - + self.assertTrue(e1 != e0) - def test11(self): print("Testing PH4 collision_detection") particles = datamodel.Particles(7) @@ -466,7 +456,7 @@ def test11(self): particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.velocity = [[2, 0, 0], [-2, 0, 0]]*3 + [[-4, 0, 0]] | nbody_system.speed - + instance = ph4() instance.initialize_code() instance.parameters.set_defaults() @@ -474,30 +464,30 @@ def test11(self): instance.particles.add_particles(particles) collisions = instance.stopping_conditions.collision_detection collisions.enable() - - for i in range(3): # PH4 can handle only one collision (=closest) at a time + + for i in range(3): # PH4 can handle only one collision (=closest) at a time instance.evolve_model(1.0 | nbody_system.time) - + self.assertTrue(collisions.is_set()) self.assertTrue(instance.model_time < 0.5 | nbody_system.time) self.assertEqual(len(collisions.particles(0)), 1) self.assertEqual(len(collisions.particles(1)), 1) self.assertEqual(len(instance.particles - collisions.particles(0) - collisions.particles(1)), 5 - i) - self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < + self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < (collisions.particles(0).radius + collisions.particles(1).radius), True) - + sticky_merged = datamodel.Particles(len(collisions.particles(0))) sticky_merged.mass = collisions.particles(0).mass + collisions.particles(1).mass sticky_merged.radius = collisions.particles(0).radius for p1, p2, merged in zip(collisions.particles(0), collisions.particles(1), sticky_merged): merged.position = (p1 + p2).center_of_mass() merged.velocity = (p1 + p2).center_of_mass_velocity() - + print(instance.model_time) print(instance.particles) instance.particles.remove_particles(collisions.particles(0) + collisions.particles(1)) instance.particles.add_particles(sticky_merged) - + instance.evolve_model(1.0 | nbody_system.time) print() print(instance.model_time) @@ -507,7 +497,7 @@ def test11(self): self.assertEqual(len(collisions.particles(0)), 1) self.assertEqual(len(collisions.particles(1)), 1) self.assertEqual(len(instance.particles - collisions.particles(0) - collisions.particles(1)), 2) - self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < + self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < (collisions.particles(0).radius + collisions.particles(1).radius), [True]) instance.stop() @@ -515,82 +505,82 @@ def test11(self): def xtest11(self): particles = datamodel.Particles(2) particles.x = [ - 0.0,1.0, - #5,7, - #10,12, - #15,17, - #20,22 + 0.0, 1.0, + # 5,7, + # 10,12, + # 15,17, + # 20,22 ] | nbody_system.length particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.radius = 0.75 | nbody_system.length - particles.vx = 0.1 | nbody_system.speed - particles.vy = 0 | nbody_system.speed - particles.vz = 0 | nbody_system.speed + particles.vx = 0.1 | nbody_system.speed + particles.vy = 0 | nbody_system.speed + particles.vz = 0 | nbody_system.speed particles.mass = 0 | nbody_system.mass - + instance = ph4() instance.initialize_code() instance.parameters.epsilon_squared = (0.01 | nbody_system.length)**2 - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.stopping_conditions.collision_detection.enable() instance.evolve_model(0.5 | nbody_system.time) self.assertTrue(instance.stopping_conditions.collision_detection.is_set()) - self.assertEqual(len(instance.stopping_conditions.collision_detection.particles(0)), 2 ) - p0 = instance.stopping_conditions.collision_detection.particles(0)[0] - p1 = instance.stopping_conditions.collision_detection.particles(1)[0] + self.assertEqual(len(instance.stopping_conditions.collision_detection.particles(0)), 2) + p0 = instance.stopping_conditions.collision_detection.particles(0)[0] + p1 = instance.stopping_conditions.collision_detection.particles(1)[0] self.assertNotEqual(p0, p1) - self.assertTrue(p1.x - p0.x < 1.5| nbody_system.length) + self.assertTrue(p1.x - p0.x < 1.5 | nbody_system.length) instance.stop() def xtest12(self): particles = datamodel.Particles(2) particles.x = [ - 0.0,1.0, - #5,7, - #10,12, - #15,17, - #20,22 + 0.0, 1.0, + # 5,7, + # 10,12, + # 15,17, + # 20,22 ] | nbody_system.length particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.radius = 0.75 | nbody_system.length - particles.vx = 0 | nbody_system.speed - particles.vy = 0 | nbody_system.speed - particles.vz = 0 | nbody_system.speed + particles.vx = 0 | nbody_system.speed + particles.vy = 0 | nbody_system.speed + particles.vz = 0 | nbody_system.speed particles.mass = 1.0 | nbody_system.mass - + instance = ph4() instance.initialize_code() instance.parameters.epsilon_squared = (0.01 | nbody_system.length)**2 - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.stopping_conditions.pair_detection.enable() instance.evolve_model(1.5 | nbody_system.time) self.assertTrue(instance.stopping_conditions.pair_detection.is_set()) - self.assertEqual(len(instance.stopping_conditions.pair_detection.particles(0)), 2 ) - p0 = instance.stopping_conditions.pair_detection.particles(0)[0] - p1 = instance.stopping_conditions.pair_detection.particles(1)[0] + self.assertEqual(len(instance.stopping_conditions.pair_detection.particles(0)), 2) + p0 = instance.stopping_conditions.pair_detection.particles(0)[0] + p1 = instance.stopping_conditions.pair_detection.particles(1)[0] self.assertNotEqual(p0, p1) - self.assertTrue(p1.x - p0.x < 1.5| nbody_system.length) + self.assertTrue(p1.x - p0.x < 1.5 | nbody_system.length) instance.stop() def xtest13(self): particles = datamodel.Particles(2) - particles.x = [0.0,10.0] | nbody_system.length + particles.x = [0.0, 10.0] | nbody_system.length particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.radius = 0.005 | nbody_system.length - particles.vx = 0 | nbody_system.speed - particles.vy = 0 | nbody_system.speed - particles.vz = 0 | nbody_system.speed + particles.vx = 0 | nbody_system.speed + particles.vy = 0 | nbody_system.speed + particles.vz = 0 | nbody_system.speed particles.mass = 1.0 | nbody_system.mass - + instance = ph4() instance.initialize_code() instance.parameters.stopping_conditions_number_of_steps = 2 self.assertEqual(instance.parameters.stopping_conditions_number_of_steps, 2) instance.parameters.epsilon_squared = (0.01 | nbody_system.length)**2 - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.stopping_conditions.number_of_steps_detection.enable() instance.evolve_model(10 | nbody_system.time) self.assertTrue(instance.stopping_conditions.number_of_steps_detection.is_set()) @@ -600,13 +590,13 @@ def xtest13(self): def xtest14(self): particles = datamodel.Particles(2) - particles.x = [0.0,10.0] | nbody_system.length + particles.x = [0.0, 10.0] | nbody_system.length particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.radius = 0.005 | nbody_system.length - particles.vx = 0 | nbody_system.speed - particles.vy = 0 | nbody_system.speed - particles.vz = 0 | nbody_system.speed + particles.vx = 0 | nbody_system.speed + particles.vy = 0 | nbody_system.speed + particles.vz = 0 | nbody_system.speed particles.mass = 1.0 | nbody_system.mass very_short_time_to_evolve = 1 | units.s @@ -617,45 +607,43 @@ def xtest14(self): instance.parameters.stopping_conditions_timeout = very_short_time_to_evolve self.assertEqual(instance.parameters.stopping_conditions_timeout, very_short_time_to_evolve) instance.parameters.epsilon_squared = (0.01 | nbody_system.length)**2 - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.stopping_conditions.timeout_detection.enable() start = time.time() instance.evolve_model(very_long_time_to_evolve) end = time.time() self.assertTrue(instance.stopping_conditions.timeout_detection.is_set()) - self.assertTrue((end-start) 0: instance.particles.remove_particles(instance.particles) instance.particles.add_particles(particles) instance.evolve_model(instance.model_time.as_quantity_in(units.yr) + (0.25 | units.yr)) - tan_final_direction.append(instance.particles[1].velocity[1]/ + tan_final_direction.append(instance.particles[1].velocity[1] / instance.particles[1].velocity[0]) print(tan_final_direction) # Small values of epsilon_squared should result in normal earth-sun dynamics: rotation of 90 degrees @@ -328,29 +327,29 @@ def test6a(self): self.assertAlmostEqual(tan_final_direction[-1], tan_initial_direction, 2) # Outcome is most sensitive to epsilon_squared when epsilon_squared = d(earth, sun)^2 delta = [abs(tan_final_direction[i+1]-tan_final_direction[i]) for i in range(len(tan_final_direction)-1)] - self.assertEqual(delta[len(tan_final_direction)/2 -1], max(delta)) - + self.assertEqual(delta[len(tan_final_direction)/2 - 1], max(delta)) + def test6b(self): print("Testing effect of Pikachu parameter epsilon_squared (using reset)") converter = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) particles = self.new_sun_earth_system() particles.rotate(0.0, 0.0, math.pi/4) particles.move_to_center() - + tan_initial_direction = particles[1].vy/particles[1].vx self.assertAlmostEqual(tan_initial_direction, math.tan(-math.pi/4)) - tan_final_direction = [] - + tan_final_direction = [] + instance = self.new_instance_of_an_optional_code(Pikachu, converter, **default_options) instance.initialize_code() instance.parameters.timestep = 0.005 | units.yr - for log_eps2 in range(-5,6,2): + for log_eps2 in range(-5, 6, 2): instance.parameters.epsilon_squared = 10.0**log_eps2 | units.AU ** 2 instance.commit_parameters() instance.particles.add_particles(particles) instance.commit_particles() instance.evolve_model(0.25 | units.yr) - tan_final_direction.append(instance.particles[1].velocity[1]/ + tan_final_direction.append(instance.particles[1].velocity[1] / instance.particles[1].velocity[0]) instance.reset() instance.cleanup_code() @@ -362,23 +361,23 @@ def test6b(self): self.assertAlmostEqual(tan_final_direction[-1], tan_initial_direction, 2) # Outcome is most sensitive to epsilon_squared when epsilon_squared = d(earth, sun)^2 delta = [abs(tan_final_direction[i+1]-tan_final_direction[i]) for i in range(len(tan_final_direction)-1)] - self.assertEqual(delta[len(tan_final_direction)/2 -1], max(delta)) - + self.assertEqual(delta[len(tan_final_direction)/2 - 1], max(delta)) + def test7(self): print("Testing Pikachu states") stars = new_plummer_model(100) black_hole = Particle() black_hole.mass = 1.0 | nbody_system.mass - black_hole.radius = 0.0 | nbody_system.length + black_hole.radius = 0.0 | nbody_system.length black_hole.position = [0.0, 0.0, 0.0] | nbody_system.length black_hole.velocity = [0.0, 0.0, 0.0] | nbody_system.speed - + print("First do everything manually:") instance = self.new_instance_of_an_optional_code(Pikachu, **default_options) self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') instance.initialize_code() self.assertEqual(instance.get_name_of_current_state(), 'INITIALIZED') -#~ instance.parameters.rcut_out_star_star = 1.0 | nbody_system.length +# ~ instance.parameters.rcut_out_star_star = 1.0 | nbody_system.length instance.parameters.timestep = 0.001 | nbody_system.time instance.commit_parameters() self.assertEqual(instance.get_name_of_current_state(), 'EDIT') @@ -397,9 +396,9 @@ def test7(self): instance.cleanup_code() self.assertEqual(instance.get_name_of_current_state(), 'END') instance.stop() - - print("initialize_code(), commit_parameters(), (re)commit_particles(), " \ - "synchronize_model(), and cleanup_code() should be called " \ + + print("initialize_code(), commit_parameters(), (re)commit_particles(), " + "synchronize_model(), and cleanup_code() should be called " "automatically before editing parameters, new_particle(), get_xx(), and stop():") instance = self.new_instance_of_an_optional_code(Pikachu, **default_options) self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') @@ -420,4 +419,3 @@ def test7(self): self.assertEqual(instance.get_name_of_current_state(), 'RUN') instance.stop() self.assertEqual(instance.get_name_of_current_state(), 'STOPPED') - diff --git a/src/amuse/test/suite/codes_tests/test_rebound.py b/src/amuse/test/suite/codes_tests/test_rebound.py index 0b9b24c0d1..da5933259d 100644 --- a/src/amuse/test/suite/codes_tests/test_rebound.py +++ b/src/amuse/test/suite/codes_tests/test_rebound.py @@ -12,81 +12,78 @@ class ReboundInterfaceTests(TestWithMPI): - + def test1(self): instance = self.new_instance_of_an_optional_code(ReboundInterface) instance.initialize_code() - - res1,error = instance.new_particle(mass = 11.0, radius = 2.0, x = 1.0, y = 2.0, z = 3.0, vx = 4.0, vy = 5.0, vz = 6.0) - res2,error = instance.new_particle(mass = 21.0, radius = 5.0, x = 10.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) - + + res1, error = instance.new_particle(mass=11.0, radius=2.0, x=1.0, y=2.0, z=3.0, vx=4.0, vy=5.0, vz=6.0) + res2, error = instance.new_particle(mass=21.0, radius=5.0, x=10.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) + self.assertEqual(error, 0) self.assertEqual(res1, 0) self.assertEqual(res2, 1) - + m1, error = instance.get_mass(res1) self.assertEqual(error, 0) self.assertEqual(m1, 11) - + m2, error = instance.get_mass(res2) self.assertEqual(error, 0) self.assertEqual(m2, 21) - - - x,y,z, error = instance.get_position(res1) + + x, y, z, error = instance.get_position(res1) self.assertEqual(error, 0) self.assertEqual(x, 1) self.assertEqual(y, 2) self.assertEqual(z, 3) - - - vx,vy,vz, error = instance.get_velocity(res1) + + vx, vy, vz, error = instance.get_velocity(res1) self.assertEqual(error, 0) self.assertEqual(vx, 4) self.assertEqual(vy, 5) self.assertEqual(vz, 6) instance.cleanup_code() instance.stop() - + def test2(self): instance = self.new_instance_of_an_optional_code(ReboundInterface) instance.initialize_code() - - instance.new_particle([10,20],[0,0],[0,0], [0,0], [0,0], [0,0], [0,0],[1,1]) + + instance.new_particle([10, 20], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 1]) retrieved_state = instance.get_state(0) - + self.assertEqual(10.0, retrieved_state['mass']) - - retrieved_state = instance.get_state([0,1]) + + retrieved_state = instance.get_state([0, 1]) self.assertEqual(10.0, retrieved_state['mass'][0]) self.assertEqual(20.0, retrieved_state['mass'][1]) - instance.cleanup_code() + instance.cleanup_code() instance.stop() - + def test3(self): - + instance = self.new_instance_of_an_optional_code(ReboundInterface) instance.initialize_code() - - indices, error = instance.new_particle([10,20, 30],[1,2,3],[0,0,0], [0,0,0], [0,0,0], [0,0,0], [0,0,0],[1,0,1]) + + indices, error = instance.new_particle([10, 20, 30], [1, 2, 3], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 0, 1]) n, error = instance.get_number_of_particles() - self.assertEqual(n,3) + self.assertEqual(n, 3) error = instance.delete_particle(indices[1]) n, error = instance.get_number_of_particles() - self.assertEqual(n,2) + self.assertEqual(n, 2) instance.commit_particles() - - retrieved_state = instance.get_state([0,2]) + + retrieved_state = instance.get_state([0, 2]) self.assertEqual(10.0, retrieved_state['mass'][0]) self.assertEqual(30.0, retrieved_state['mass'][1]) mass, error = instance.get_mass(1) self.assertEqual(error, -1) - instance.cleanup_code() + instance.cleanup_code() instance.stop() - def test4(self): - + instance = self.new_instance_of_an_optional_code(ReboundInterface) instance.initialize_code() error = 0 @@ -100,48 +97,45 @@ def test4(self): self.assertEqual("whfast", integrator) instance.cleanup_code() instance.stop() - + def test5(self): instance = self.new_instance_of_an_optional_code(ReboundInterface) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - + # Set up an equal-mass binary on a circular orbit: self.assertEqual([0, 0], list(instance.new_particle(0.5, 0.5, 0, 0, 0, 0.5, 0, 0.01).values())) - self.assertEqual([1, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0,-0.5, 0, 0.01).values())) + self.assertEqual([1, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0, -0.5, 0, 0.01).values())) self.assertEqual(0, instance.commit_particles()) - + self.assertEqual(0, instance.evolve_model(math.pi)) for result, expected in zip(list(instance.get_position(0).values()), [-0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 3) for result, expected in zip(list(instance.get_position(1).values()), [0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 3) - + self.assertEqual(0, instance.evolve_model(2 * math.pi)) for result, expected in zip(list(instance.get_position(0).values()), [0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 3) for result, expected in zip(list(instance.get_position(1).values()), [-0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 3) - + self.assertEqual(0, instance.cleanup_code()) instance.stop() - def test6(self): instance = self.new_instance_of_an_optional_code(ReboundInterface) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - - - index,err=instance.new_particle(0.5, 0.5, 0, 0, 0, 0.5, 0, 0.01, 1) + + index, err = instance.new_particle(0.5, 0.5, 0, 0, 0, 0.5, 0, 0.01, 1) self.assertEqual(-10, err) - + instance.cleanup_code() instance.stop() - def test7(self): - + instance = self.new_instance_of_an_optional_code(ReboundInterface) instance.initialize_code() @@ -153,9 +147,8 @@ def test7(self): instance.cleanup_code() instance.stop() - def test8(self): - + instance = self.new_instance_of_an_optional_code(ReboundInterface) instance.initialize_code() @@ -173,106 +166,102 @@ def test8(self): instance.cleanup_code() instance.stop() - + class TestRebound(TestWithMPI): def new_system_of_sun_and_earth(self): stars = datamodel.Stars(2) sun = stars[0] sun.mass = units.MSun(1.0) - sun.position = units.m(numpy.array((0.0,0.0,0.0))) - sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) + sun.position = units.m(numpy.array((0.0, 0.0, 0.0))) + sun.velocity = units.ms(numpy.array((0.0, 0.0, 0.0))) sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) - earth.radius = units.km(6371) - earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) - earth.velocity = units.ms(numpy.array((0.0,29800,0.0))) - + earth.radius = units.km(6371) + earth.position = units.km(numpy.array((149.5e6, 0.0, 0.0))) + earth.velocity = units.ms(numpy.array((0.0, 29800, 0.0))) + return stars - - + def test1(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) - + interface = self.new_instance_of_an_optional_code(Rebound, convert_nbody) interface.initialize_code() interface.parameters.epsilon_squared = 0.0 | units.AU**2 interface.dt_dia = 5000 - + stars = self.new_system_of_sun_and_earth() earth = stars[1] - + interface.particles.add_particles(stars) - + interface.evolve_model(365.0 | units.day) interface.particles.copy_values_of_all_attributes_to(stars) - + position_at_start = earth.position.value_in(units.AU)[0] position_after_full_rotation = earth.position.value_in(units.AU)[0] self.assertAlmostRelativeEqual(position_at_start, position_after_full_rotation, 6) - + interface.evolve_model(365.0 + (365.0 / 2) | units.day) - + self.assertAlmostRelativeEqual(interface.model_time, 365.0 + (365.0 / 2) | units.day, 3) interface.particles.copy_values_of_all_attributes_to(stars) position_after_half_a_rotation = earth.position.value_in(units.AU)[0] self.assertAlmostRelativeEqual(-position_at_start, position_after_half_a_rotation, 3) - - interface.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) - self.assertAlmostRelativeEqual(interface.model_time, 365.0 + (365.0 / 2) + (365.0 / 4) | units.day, 3) - + + interface.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) + self.assertAlmostRelativeEqual(interface.model_time, 365.0 + (365.0 / 2) + (365.0 / 4) | units.day, 3) + interface.particles.copy_values_of_all_attributes_to(stars) position_after_half_a_rotation = earth.position.value_in(units.AU)[1] self.assertAlmostRelativeEqual(-position_at_start, position_after_half_a_rotation, 3) - + interface.cleanup_code() - + interface.stop() - def test2(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) - + instance = self.new_instance_of_an_optional_code(Rebound, convert_nbody) instance.initialize_code() instance.parameters.epsilon_squared = 0.0 | units.AU**2 instance.dt_dia = 5000 - + stars = self.new_system_of_sun_and_earth() earth = stars[1] instance.particles.add_particles(stars) - + for x in range(1, 500, 10): instance.evolve_model(x | units.day) instance.particles.copy_values_of_all_attributes_to(stars) stars.savepoint() - + if HAS_MATPLOTLIB: figure = pyplot.figure() - plot = figure.add_subplot(1,1,1) - + plot = figure.add_subplot(1, 1, 1) + x_points = earth.get_timeline_of_attribute("x") y_points = earth.get_timeline_of_attribute("y") - + x_points_in_AU = [t_x[1].value_in(units.AU) for t_x in x_points] y_points_in_AU = [t_x1[1].value_in(units.AU) for t_x1 in y_points] - - plot.scatter(x_points_in_AU,y_points_in_AU, color = "b", marker = 'o') - + + plot.scatter(x_points_in_AU, y_points_in_AU, color="b", marker='o') + plot.set_xlim(-1.5, 1.5) plot.set_ylim(-1.5, 1.5) - - + test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "rebound-earth-sun2.svg") figure.savefig(output_file) - - + instance.cleanup_code() instance.stop() - + def test3(self): particles = datamodel.Particles(7) particles.mass = 0.001 | nbody_system.mass @@ -281,7 +270,7 @@ def test3(self): particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.velocity = [[2, 0, 0], [-2, 0, 0]]*3 + [[-4, 0, 0]] | nbody_system.speed - + instance = self.new_instance_of_an_optional_code(Rebound) instance.initialize_code() instance.parameters.set_defaults() @@ -289,24 +278,24 @@ def test3(self): collisions = instance.stopping_conditions.collision_detection collisions.enable() instance.evolve_model(1.0 | nbody_system.time) - + print(instance.particles) self.assertTrue(collisions.is_set()) self.assertTrue(instance.model_time < 0.5 | nbody_system.time) self.assertEqual(len(collisions.particles(0)), 3) self.assertEqual(len(collisions.particles(1)), 3) self.assertEqual(len(particles - collisions.particles(0) - collisions.particles(1)), 1) - self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) <= + self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) <= (collisions.particles(0).radius + collisions.particles(1).radius), [True, True, True]) - + sticky_merged = datamodel.Particles(len(collisions.particles(0))) sticky_merged.mass = collisions.particles(0).mass + collisions.particles(1).mass sticky_merged.radius = collisions.particles(0).radius for p1, p2, merged in zip(collisions.particles(0), collisions.particles(1), sticky_merged): merged.position = (p1 + p2).center_of_mass() merged.velocity = (p1 + p2).center_of_mass_velocity() - + print(instance.model_time) print(instance.particles) instance.particles.remove_particles(collisions.particles(0) + collisions.particles(1)) @@ -321,7 +310,7 @@ def test3(self): self.assertEqual(len(collisions.particles(0)), 1) self.assertEqual(len(collisions.particles(1)), 1) self.assertEqual(len(instance.particles - collisions.particles(0) - collisions.particles(1)), 2) - self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) <= + self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) <= (collisions.particles(0).radius + collisions.particles(1).radius), [True]) instance.stop() @@ -332,26 +321,25 @@ def test4(self): instance.initialize_code() instance.parameters.epsilon_squared = 0.0 | units.AU**2 instance.dt_dia = 5000 - + stars = self.new_system_of_sun_and_earth() earth = stars[1] instance.particles.add_particles(stars) self.assertAlmostRelativeEquals(instance.kinetic_energy, stars.kinetic_energy()) self.assertAlmostRelativeEquals(instance.potential_energy, stars.potential_energy(), 10) - + instance.stop() - def test5(self): instance = self.new_instance_of_an_optional_code(Rebound) instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2 - + particles = datamodel.Particles(2) - particles.position = ([0,0,0], [1,0,0] )| nbody_system.length - particles.velocity = ([-1,0,0], [2,0,0] )| nbody_system.speed - particles.radius = 0| nbody_system.length - particles.mass = 0.1| nbody_system.mass - + particles.position = ([0, 0, 0], [1, 0, 0]) | nbody_system.length + particles.velocity = ([-1, 0, 0], [2, 0, 0]) | nbody_system.speed + particles.radius = 0 | nbody_system.length + particles.mass = 0.1 | nbody_system.mass + instance.particles.add_particles(particles) instance.stopping_conditions.out_of_box_detection.enable() instance.parameters.stopping_conditions_out_of_box_size = 2 | nbody_system.length @@ -361,24 +349,22 @@ def test5(self): self.assertEqual(len(instance.stopping_conditions.out_of_box_detection.particles(0)), 1) self.assertEqual(instance.stopping_conditions.out_of_box_detection.particles(0)[0].key, particles[1].key) instance.stop() - def test6(self): instance = self.new_instance_of_an_optional_code(Rebound) instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2 - + particles = datamodel.Particles(2) - particles.position = ([0,0,0], [1,0,0] )| nbody_system.length - particles.velocity = ([-1,0,0], [2,0,0] )| nbody_system.speed - particles.radius = 0| nbody_system.length - particles.mass = 0.1| nbody_system.mass - + particles.position = ([0, 0, 0], [1, 0, 0]) | nbody_system.length + particles.velocity = ([-1, 0, 0], [2, 0, 0]) | nbody_system.speed + particles.radius = 0 | nbody_system.length + particles.mass = 0.1 | nbody_system.mass + instance.particles.add_particles(particles) self.assertAlmostRelativeEquals(instance.kinetic_energy, particles.kinetic_energy()) - self.assertAlmostRelativeEquals(instance.potential_energy, particles.potential_energy(G = nbody_system.G)) + self.assertAlmostRelativeEquals(instance.potential_energy, particles.potential_energy(G=nbody_system.G)) instance.stop() - def test7(self): instance = self.new_instance_of_an_optional_code(Rebound) instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2 @@ -386,30 +372,28 @@ def test7(self): subset1 = instance.new_subset() print(subset1) self.assertEqual(subset1, 1) - + particles = datamodel.Particles(2) - particles.position = ([0,0,0], [1,0,0] )| nbody_system.length - particles.velocity = ([-1,0,0], [2,0,0] )| nbody_system.speed - particles.radius = 0| nbody_system.length - particles.mass = 0.1| nbody_system.mass - + particles.position = ([0, 0, 0], [1, 0, 0]) | nbody_system.length + particles.velocity = ([-1, 0, 0], [2, 0, 0]) | nbody_system.speed + particles.radius = 0 | nbody_system.length + particles.mass = 0.1 | nbody_system.mass + particles2 = datamodel.Particles(2) - particles2.position = ([0,0,0], [1,0,0] )| nbody_system.length - particles2.velocity = ([-1,0,0], [2,0,0] )| nbody_system.speed - particles2.radius = 0| nbody_system.length + particles2.position = ([0, 0, 0], [1, 0, 0]) | nbody_system.length + particles2.velocity = ([-1, 0, 0], [2, 0, 0]) | nbody_system.speed + particles2.radius = 0 | nbody_system.length particles2.mass = 2 | nbody_system.mass particles2.subset = subset1 - + instance.particles.add_particles(particles) instance.particles.add_particles(particles2) print(instance.particles) self.assertAlmostRelativeEquals(instance.kinetic_energy, particles.kinetic_energy()) - self.assertAlmostRelativeEquals(instance.potential_energy, particles.potential_energy(G = nbody_system.G)) + self.assertAlmostRelativeEquals(instance.potential_energy, particles.potential_energy(G=nbody_system.G)) self.assertAlmostRelativeEquals(instance.get_kinetic_energy(subset1), particles2.kinetic_energy()) - self.assertAlmostRelativeEquals(instance.get_potential_energy(subset1), particles2.potential_energy(G = nbody_system.G)) - #instance.stop() - - + self.assertAlmostRelativeEquals(instance.get_potential_energy(subset1), particles2.potential_energy(G=nbody_system.G)) + # instance.stop() def test8(self): instance = self.new_instance_of_an_optional_code(Rebound) @@ -418,30 +402,30 @@ def test8(self): subset1 = instance.new_subset() print(subset1) self.assertEqual(subset1, 1) - + particles = datamodel.Particles(2) - particles.position = ([0,0,0], [1,0,0] )| nbody_system.length - particles.velocity = ([0,0,0], [0,0.5,0] )| nbody_system.speed - particles.radius = 0| nbody_system.length - particles.mass = 0.1| nbody_system.mass - + particles.position = ([0, 0, 0], [1, 0, 0]) | nbody_system.length + particles.velocity = ([0, 0, 0], [0, 0.5, 0]) | nbody_system.speed + particles.radius = 0 | nbody_system.length + particles.mass = 0.1 | nbody_system.mass + particles2 = datamodel.Particles(2) - particles2.position = ([0,0,0], [2,0,0] )| nbody_system.length - particles2.velocity = ([0,0,0], [0,1,0] )| nbody_system.speed - particles2.radius = 0| nbody_system.length + particles2.position = ([0, 0, 0], [2, 0, 0]) | nbody_system.length + particles2.velocity = ([0, 0, 0], [0, 1, 0]) | nbody_system.speed + particles2.radius = 0 | nbody_system.length particles2.mass = 1 | nbody_system.mass particles2.subset = subset1 - + instance.particles.add_particles(particles) instance.particles.add_particles(particles2) instance.evolve_model(0.1 | nbody_system.time) self.assertAlmostRelativeEquals(instance.kinetic_energy, particles.kinetic_energy(), 2) - self.assertAlmostRelativeEquals(instance.potential_energy, particles.potential_energy(G = nbody_system.G), 2) + self.assertAlmostRelativeEquals(instance.potential_energy, particles.potential_energy(G=nbody_system.G), 2) self.assertAlmostRelativeEquals(instance.get_kinetic_energy(subset1), particles2.kinetic_energy(), 2) - self.assertAlmostRelativeEquals(instance.get_potential_energy(subset1), particles2.potential_energy(G = nbody_system.G), 2) + self.assertAlmostRelativeEquals(instance.get_potential_energy(subset1), particles2.potential_energy(G=nbody_system.G), 2) particles_evolved = instance.particles.copy() instance.stop() - + instance1 = self.new_instance_of_an_optional_code(Rebound) instance1.parameters.epsilon_squared = 0.0 | nbody_system.length**2 particles1c = particles.copy() @@ -454,7 +438,7 @@ def test8(self): self.assertAlmostRelativeEquals(instance1.particles.position, particles1evolved.position, 10) self.assertAlmostRelativeEquals(instance1.particles.velocity, particles1evolved.velocity, 10) instance1.stop() - + instance2 = self.new_instance_of_an_optional_code(Rebound) instance2.parameters.epsilon_squared = 0.0 | nbody_system.length**2 particles2c = particles2.copy() @@ -467,25 +451,25 @@ def test8(self): print(instance2.particles) self.assertAlmostRelativeEquals(instance2.particles.position, particles2evolved.position, 10) self.assertAlmostRelativeEquals(instance2.particles.velocity, particles2evolved.velocity, 10) - instance2.stop() - + instance2.stop() + def test9(self): instance = self.new_instance_of_an_optional_code(Rebound) - #instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2 - + # instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2 + particles = datamodel.Particles(10) - particles.x = numpy.arange(0,10,1) | nbody_system.length + particles.x = numpy.arange(0, 10, 1) | nbody_system.length particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length - particles.velocity = [0,1,0] | nbody_system.speed - particles[5].velocity = [0,0,0] | nbody_system.speed - particles.radius = 0| nbody_system.length + particles.velocity = [0, 1, 0] | nbody_system.speed + particles[5].velocity = [0, 0, 0] | nbody_system.speed + particles.radius = 0 | nbody_system.length particles[5].mass = 1 | nbody_system.mass - + instance.particles.add_particles(particles) self.assertEqual(instance.particles[5].mass, 1 | nbody_system.mass) self.assertEqual(instance.particles[6].mass, 0 | nbody_system.mass) - + instance.evolve_model(1 | nbody_system.time) self.assertEqual(instance.particles[5].mass, 1 | nbody_system.mass) self.assertEqual(instance.particles[6].mass, 0 | nbody_system.mass) @@ -500,20 +484,18 @@ def test9(self): def test10(self): instance = self.new_instance_of_an_optional_code(Rebound) - #instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2 - + # instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2 + particles = datamodel.Particles(1) particles.x = 0 | nbody_system.length particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length - particles.velocity = [0,2,0] | nbody_system.speed - particles.radius = 1| nbody_system.length + particles.velocity = [0, 2, 0] | nbody_system.speed + particles.radius = 1 | nbody_system.length particles.mass = 1 | nbody_system.mass - + instance.particles.add_particles(particles) instance.evolve_model(4 | nbody_system.time) - self.assertAlmostRelativeEquals(instance.particles[0].velocity, [0, 2,0] | nbody_system.speed) + self.assertAlmostRelativeEquals(instance.particles[0].velocity, [0, 2, 0] | nbody_system.speed) self.assertAlmostRelativeEquals(instance.particles[0].position, [0, 2 * 4, 0] | nbody_system.length, 8) instance.stop() - - diff --git a/src/amuse/test/suite/codes_tests/test_sakura.py b/src/amuse/test/suite/codes_tests/test_sakura.py index 76ea1bb0b6..754b0b415d 100644 --- a/src/amuse/test/suite/codes_tests/test_sakura.py +++ b/src/amuse/test/suite/codes_tests/test_sakura.py @@ -36,10 +36,10 @@ def test02(self): self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - id, error = instance.new_particle(mass = 11.0, radius = 2.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) + id, error = instance.new_particle(mass=11.0, radius=2.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) self.assertEqual(0, error) self.assertEqual(0, id) - id, error = instance.new_particle(mass = 21.0, radius = 5.0, x = 10.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) + id, error = instance.new_particle(mass=21.0, radius=5.0, x=10.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) self.assertEqual(0, error) self.assertEqual(1, id) self.assertEqual(0, instance.commit_particles()) @@ -50,7 +50,7 @@ def test02(self): self.assertEqual(0, retrieved_state2['__result']) self.assertEqual(11.0, retrieved_state1['mass']) self.assertEqual(21.0, retrieved_state2['mass']) - self.assertEqual( 0.0, retrieved_state1['x']) + self.assertEqual(0.0, retrieved_state1['x']) self.assertEqual(10.0, retrieved_state2['x']) self.assertEqual(0, instance.cleanup_code()) @@ -65,34 +65,34 @@ def test03(self): self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) self.assertEqual([0, 0], list(instance.new_particle(0.01, 1, 0, 0, 0, 1, 0, 0.1).values())) - self.assertEqual([1, 0], list(instance.new_particle(0.02, -1, 0, 0, 0,-1, 0, 0.1).values())) + self.assertEqual([1, 0], list(instance.new_particle(0.02, -1, 0, 0, 0, -1, 0, 0.1).values())) #### self.assertEquals(-1, instance.get_mass(1)['__result']) # Have to commit first self.assertEqual(0, instance.commit_particles()) # getters mass, result = instance.get_mass(0) self.assertAlmostEqual(0.01, mass) - self.assertEqual(0,result) + self.assertEqual(0, result) radius, result = instance.get_radius(1) self.assertAlmostEqual(0.1, radius) - self.assertEqual(0,result) - self.assertEqual(-1, instance.get_mass(2)['__result']) # Particle not found - self.assertEqual([ 1, 0, 0, 0], list(instance.get_position(0).values())) + self.assertEqual(0, result) + self.assertEqual(-1, instance.get_mass(2)['__result']) # Particle not found + self.assertEqual([1, 0, 0, 0], list(instance.get_position(0).values())) self.assertEqual([-1, 0, 0, 0], list(instance.get_position(1).values())) - self.assertEqual([ 0, 1, 0, 0], list(instance.get_velocity(0).values())) - self.assertEqual([ 0,-1, 0, 0], list(instance.get_velocity(1).values())) + self.assertEqual([0, 1, 0, 0], list(instance.get_velocity(0).values())) + self.assertEqual([0, -1, 0, 0], list(instance.get_velocity(1).values())) # setters - self.assertEqual(0, instance.set_state(0, 0.01, 1,2,3, 4,5,6, 0.1)) - self.assertEqual([0.01, 1.0,2.0,3.0, 4.0,5.0,6.0, 0.1, 0], list(instance.get_state(0).values())) + self.assertEqual(0, instance.set_state(0, 0.01, 1, 2, 3, 4, 5, 6, 0.1)) + self.assertEqual([0.01, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.1, 0], list(instance.get_state(0).values())) self.assertEqual(0, instance.set_mass(0, 0.02)) - self.assertEqual([0.02, 1.0,2.0,3.0, 4.0,5.0,6.0, 0.1, 0], list(instance.get_state(0).values())) + self.assertEqual([0.02, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.1, 0], list(instance.get_state(0).values())) self.assertEqual(0, instance.set_radius(0, 0.2)) - self.assertEqual([0.02, 1.0,2.0,3.0, 4.0,5.0,6.0, 0.2, 0], list(instance.get_state(0).values())) - self.assertEqual(0, instance.set_position(0, 10,20,30)) - self.assertEqual([0.02, 10.0,20.0,30.0, 4.0,5.0,6.0, 0.2, 0], list(instance.get_state(0).values())) - self.assertEqual(0, instance.set_velocity(0, 40,50,60)) - self.assertEqual([0.02, 10.0,20.0,30.0, 40.0,50.0,60.0, 0.2, 0], list(instance.get_state(0).values())) + self.assertEqual([0.02, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.2, 0], list(instance.get_state(0).values())) + self.assertEqual(0, instance.set_position(0, 10, 20, 30)) + self.assertEqual([0.02, 10.0, 20.0, 30.0, 4.0, 5.0, 6.0, 0.2, 0], list(instance.get_state(0).values())) + self.assertEqual(0, instance.set_velocity(0, 40, 50, 60)) + self.assertEqual([0.02, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 0.2, 0], list(instance.get_state(0).values())) self.assertEqual(0, instance.cleanup_code()) instance.stop() @@ -117,20 +117,20 @@ def test04(self): self.assertEqual(0, instance.set_t(1.0)) self.assertEqual([1.0, 0], list(instance.get_t().values())) - #self.assertEquals(["sakura", 0], instance.get_integrator_method().values()) - #self.assertEquals(0, instance.set_integrator_method("bogus")) - #self.assertEquals(["bogus", 0], instance.get_integrator_method().values()) - #self.assertEquals(-1, instance.commit_parameters()) - #self.assertEquals(0, instance.set_integrator_method("asakura")) - #self.assertEquals(["asakura", 0], instance.get_integrator_method().values()) + # self.assertEquals(["sakura", 0], instance.get_integrator_method().values()) + # self.assertEquals(0, instance.set_integrator_method("bogus")) + # self.assertEquals(["bogus", 0], instance.get_integrator_method().values()) + # self.assertEquals(-1, instance.commit_parameters()) + # self.assertEquals(0, instance.set_integrator_method("asakura")) + # self.assertEquals(["asakura", 0], instance.get_integrator_method().values()) self.assertEqual(0, instance.commit_parameters()) - #self.assertEquals(0, instance.set_pn_order(7)) - #self.assertEquals([7, 0], instance.get_pn_order().values()) - #self.assertEquals(-1, instance.commit_parameters()) - #self.assertEquals(0, instance.set_clight(1024)) - #self.assertEquals([1024, 0], instance.get_clight().values()) + # self.assertEquals(0, instance.set_pn_order(7)) + # self.assertEquals([7, 0], instance.get_pn_order().values()) + # self.assertEquals(-1, instance.commit_parameters()) + # self.assertEquals(0, instance.set_clight(1024)) + # self.assertEquals([1024, 0], instance.get_clight().values()) self.assertEqual(0, instance.commit_parameters()) self.assertEqual(0, instance.cleanup_code()) @@ -146,19 +146,20 @@ def test05(self): self.assertEqual(0, instance.commit_parameters()) self.assertEqual([0, 0], list(instance.new_particle(0.5, 0.5, 0, 0, 0, 0.5, 0, 0.001).values())) - self.assertEqual([1, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0,-0.5, 0, 0.001).values())) + self.assertEqual([1, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0, -0.5, 0, 0.001).values())) self.assertEqual(0, instance.commit_particles()) P = 2 * math.pi - self.assertEqual(0, instance.evolve_model(P / 2)) # half an orbit + self.assertEqual(0, instance.evolve_model(P / 2)) # half an orbit for result, expected in zip(instance.get_position(0).values(), [-0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 2) - self.assertEqual(0, instance.evolve_model(P)) # full orbit + self.assertEqual(0, instance.evolve_model(P)) # full orbit for result, expected in zip(instance.get_position(0).values(), [0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 2) self.assertEqual(0, instance.cleanup_code()) instance.stop() + class TestSakura(TestWithMPI): default_converter = nbody_system.nbody_to_si(1.0e4 | units.MSun, 1.0 | units.AU) @@ -369,8 +370,8 @@ def xtest07(self): tan_initial_direction = particles[1].vy/particles[1].vx self.assertAlmostEqual(tan_initial_direction, math.tan(math.pi/4)) - tan_final_direction = [] - for log_eps2 in range(-9,10,2): + tan_final_direction = [] + for log_eps2 in range(-9, 10, 2): instance = self.new_instance_of_an_optional_code( Sakura, converter, **default_options) instance.initialize_code() @@ -380,7 +381,7 @@ def xtest07(self): instance.particles.add_particles(particles) instance.commit_particles() instance.evolve_model(0.25 | units.yr) - tan_final_direction.append(instance.particles[1].velocity[1]/ + tan_final_direction.append(instance.particles[1].velocity[1] / instance.particles[1].velocity[0]) instance.cleanup_code() instance.stop() @@ -390,7 +391,7 @@ def xtest07(self): self.assertAlmostEqual(tan_final_direction[-1], tan_initial_direction, 2) # Outcome is most sensitive to epsilon_squared when epsilon_squared = d(earth, sun)^2 delta = [abs(tan_final_direction[i+1]-tan_final_direction[i]) for i in range(len(tan_final_direction)-1)] - self.assertEqual(delta[len(tan_final_direction)/2 -1], max(delta)) + self.assertEqual(delta[len(tan_final_direction)/2 - 1], max(delta)) def xtest08(self): if MODULES_MISSING: @@ -404,8 +405,8 @@ def xtest08(self): particles = Particles(2) particles.mass = 1.0 | nbody_system.mass - particles.radius = 0.0 | nbody_system.length - particles.position = [[0.0,0.0,0.0], [2.0,0.0,0.0]] | nbody_system.length + particles.radius = 0.0 | nbody_system.length + particles.position = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]] | nbody_system.length particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed instance.particles.add_particles(particles) @@ -565,8 +566,3 @@ def test11(self): instance.cleanup_code() instance.stop() - - - - - diff --git a/src/amuse/test/suite/codes_tests/test_seba.py b/src/amuse/test/suite/codes_tests/test_seba.py index 87f5c2f2cc..ca9712e821 100644 --- a/src/amuse/test/suite/codes_tests/test_seba.py +++ b/src/amuse/test/suite/codes_tests/test_seba.py @@ -9,6 +9,7 @@ from amuse.datamodel import Particle from amuse.datamodel import Particles + class TestSeBaInterface(TestWithMPI): def test1(self): @@ -16,7 +17,7 @@ def test1(self): endtime, mass, radius, luminosity, temperature, time_step, stellar_type, error = instance.evolve_star(1, 4600, 0.02) self.assertEqual(error, 0) - self.assertTrue( endtime <= 4600.0) + self.assertTrue(endtime <= 4600.0) self.assertAlmostRelativeEqual(endtime, 4600.0, 4) self.assertAlmostRelativeEqual(mass, 1.0, 6) self.assertAlmostRelativeEqual(radius, 0.9856, 4) @@ -28,11 +29,11 @@ def test1(self): instance.stop() def test2(self): - instance = SeBaInterface() #self.new_instance_of_an_optional_code(SeBaInterface) + instance = SeBaInterface() # self.new_instance_of_an_optional_code(SeBaInterface) error = instance.initialize_code() self.assertEqual(error, 0) - index,error = instance.new_particle(1.) + index, error = instance.new_particle(1.) self.assertEqual(error, 0) self.assertEqual(index, 1) mass, error = instance.get_mass(index) @@ -49,11 +50,11 @@ def test2(self): instance.stop() def test3(self): - instance = SeBaInterface() #self.new_instance_of_an_optional_code(SeBaInterface) + instance = SeBaInterface() # self.new_instance_of_an_optional_code(SeBaInterface) error = instance.initialize_code() self.assertEqual(error, 0) - index,error = instance.new_particle(1.) + index, error = instance.new_particle(1.) self.assertEqual(error, 0) self.assertEqual(index, 1) error = instance.evolve_model(4600) @@ -79,11 +80,11 @@ def test3(self): instance.stop() def test4(self): - instance = SeBaInterface() #self.new_instance_of_an_optional_code(SeBaInterface) + instance = SeBaInterface() # self.new_instance_of_an_optional_code(SeBaInterface) error = instance.initialize_code() self.assertEqual(error, 0) - index,error = instance.new_particle(1.) + index, error = instance.new_particle(1.) self.assertEqual(error, 0) self.assertEqual(index, 1) for t in range(46): @@ -110,23 +111,22 @@ def test4(self): instance.stop() def test5(self): - instance = SeBaInterface() #self.new_instance_of_an_optional_code(SeBaInterface) + instance = SeBaInterface() # self.new_instance_of_an_optional_code(SeBaInterface) error = instance.initialize_code() self.assertEqual(error, 0) - index,error = instance.new_particle([1., 2., 3.]) + index, error = instance.new_particle([1., 2., 3.]) self.assertEqual(error, 0) - self.assertEqual(index, [1,2,3]) + self.assertEqual(index, [1, 2, 3]) mass, error = instance.get_mass(2) self.assertEqual(error, 0) - self.assertAlmostRelativeEqual(mass, 2 , 6) + self.assertAlmostRelativeEqual(mass, 2, 6) mass, error = instance.get_mass(3) self.assertEqual(error, 0) self.assertAlmostRelativeEqual(mass, 3, 6) - error = instance.evolve_model(4600) self.assertEqual(error, 0) @@ -137,17 +137,16 @@ def test5(self): self.assertAlmostRelativeEqual(mass[1], 0.62973, 4) self.assertAlmostRelativeEqual(mass[2], 0.75012, 4) - instance.stop() def test6(self): - instance = SeBaInterface() #self.new_instance_of_an_optional_code(SeBaInterface) + instance = SeBaInterface() # self.new_instance_of_an_optional_code(SeBaInterface) error = instance.initialize_code() self.assertEqual(error, 0) - index,error = instance.new_particle([1., 2., 3.]) + index, error = instance.new_particle([1., 2., 3.]) self.assertEqual(error, 0) - self.assertEqual(index, [1,2,3]) + self.assertEqual(index, [1, 2, 3]) for t in range(46): error = instance.evolve_model((t+1) * 100) @@ -161,17 +160,17 @@ def test6(self): instance.stop() def test7(self): - instance = SeBaInterface() #self.new_instance_of_an_optional_code(SeBaInterface) + instance = SeBaInterface() # self.new_instance_of_an_optional_code(SeBaInterface) error = instance.initialize_code() self.assertEqual(error, 0) - index,error = instance.new_particle([1., 2., 3.]) + index, error = instance.new_particle([1., 2., 3.]) self.assertEqual(error, 0) - self.assertEqual(index, [1,2,3]) + self.assertEqual(index, [1, 2, 3]) mass, error = instance.get_mass(2) self.assertEqual(error, 0) - self.assertAlmostRelativeEqual(mass, 2 , 6) + self.assertAlmostRelativeEqual(mass, 2, 6) mass, error = instance.get_mass(3) self.assertEqual(error, 0) @@ -197,18 +196,18 @@ def test7(self): instance.stop() def test8(self): - instance = SeBaInterface() #self.new_instance_of_an_optional_code(SeBaInterface) + instance = SeBaInterface() # self.new_instance_of_an_optional_code(SeBaInterface) error = instance.initialize_code() self.assertEqual(error, 0) - index,error = instance.new_particle([3.0,1.0,2.0]) + index, error = instance.new_particle([3.0, 1.0, 2.0]) self.assertEqual(error, 0) - self.assertEqual(index, [1,2,3]) + self.assertEqual(index, [1, 2, 3]) error = instance.delete_star(1) self.assertEqual(error, 0) - error = instance.evolve_model(4600); + error = instance.evolve_model(4600) mass, error = instance.get_mass(2) self.assertEqual(error, 0) @@ -217,15 +216,13 @@ def test8(self): error = instance.delete_star(3) self.assertEqual(error, 0) - - index,error = instance.new_particle([5.0]) + index, error = instance.new_particle([5.0]) self.assertEqual(error, 0) mass, error = instance.get_mass(index) self.assertEqual(error, 0) self.assertAlmostRelativeEqual(mass, 5.0, 6) - error = instance.evolve_model(5000); - + error = instance.evolve_model(5000) mass, error = instance.get_mass(index) self.assertEqual(error, 0) @@ -240,10 +237,10 @@ def test8(self): mass, error = instance.get_mass(index+1) self.assertEqual(error, -1) - index,error = instance.new_particle([5.0]) + index, error = instance.new_particle([5.0]) self.assertEqual(error, 0) - error = instance.evolve_model(10000); + error = instance.evolve_model(10000) mass, error = instance.get_mass(index) self.assertEqual(error, 0) @@ -252,23 +249,22 @@ def test8(self): instance.stop() def test9(self): - instance = SeBaInterface() #self.new_instance_of_an_optional_code(SeBaInterface) + instance = SeBaInterface() # self.new_instance_of_an_optional_code(SeBaInterface) error = instance.initialize_code() self.assertEqual(error, 0) instance.set_metallicity(0.001) - index,error = instance.new_particle([3.0,0.3]) + index, error = instance.new_particle([3.0, 0.3]) self.assertEqual(error, 0) - self.assertEqual(index, [1,2]) + self.assertEqual(index, [1, 2]) mu = (3.3 | units.MSun) * constants.G orbital_period = 200.0 | units.day semi_major_axis = (((orbital_period / 2.0 * numpy.pi)**2)*mu)**(1.0/3.0) print(semi_major_axis.value_in(units.RSun)) - eccentricity = 0.5 - index,error = instance.new_binary( + index, error = instance.new_binary( semi_major_axis.value_in(units.RSun), eccentricity, index[0], @@ -293,7 +289,6 @@ def test9(self): self.assertEqual(error, 0) self.assertAlmostRelativeEqual(mass, 0.29999, 4) - error = instance.evolve_model(400) self.assertEqual(error, 0) mass, error = instance.get_mass(1) @@ -309,15 +304,16 @@ def test9(self): self.assertEqual(error, -1) # check if singles are still in the mode and evolve - value, error = instance.get_age([1,2]) + value, error = instance.get_age([1, 2]) self.assertEqual(error, 0) self.assertAlmostRelativeEqual(value, 400, 4) error = instance.evolve_model(500) self.assertEqual(error, 0) - value, error = instance.get_age([1,2]) + value, error = instance.get_age([1, 2]) self.assertEqual(error, 0) self.assertAlmostRelativeEqual(value, 500, 4) + class TestSeBa(TestWithMPI): def test_evolve_star(self): @@ -326,7 +322,7 @@ def test_evolve_star(self): endtime, mass, radius, luminosity, temperature, time_step, stellar_type = instance.evolve_star(1 | units.MSun, 4600 | units.Myr, 0.02) - self.assertTrue( endtime <= 4600 | units.Myr) + self.assertTrue(endtime <= 4600 | units.Myr) self.assertAlmostRelativeEqual(mass, 1.0 | units.MSun, 4) self.assertAlmostRelativeEqual(radius, 0.9856 | units.RSun, 4) self.assertAlmostRelativeEqual(luminosity, 0.9585 | units.LSun, 4) @@ -334,7 +330,6 @@ def test_evolve_star(self): self.assertAlmostRelativeEqual(time_step, 1089.3 | units.Myr, 4) self.assertEqual(stellar_type, 1 | units.stellar_type) - def test_add_particle(self): instance = self.new_instance_of_an_optional_code(SeBa) @@ -352,18 +347,17 @@ def test_evolution_of_close_binary_system(self): # print("Testing evolution of a close binary system...") instance = self.new_instance_of_an_optional_code(SeBa) instance.commit_parameters() - stars = Particles(2) + stars = Particles(2) stars[0].mass = 3.0 | units.MSun stars[1].mass = 0.3 | units.MSun - mu = (3.3 | units.MSun) * constants.G orbital_period = 200.0 | units.day semi_major_axis = (((orbital_period / (2.0 * numpy.pi))**2)*mu)**(1.0/3.0) instance.particles.add_particles(stars) - binaries = Particles(1) + binaries = Particles(1) binary = binaries[0] binary.semi_major_axis = semi_major_axis @@ -386,7 +380,7 @@ def test_evolution_of_close_binary_system(self): while current_time < (480 | units.Myr): instance.update_time_steps() # The next line appears a bit weird, but saves time for this simple test. - deltat = max(1.0*instance.binaries[0].time_step, 0.1| units.Myr) + deltat = max(1.0*instance.binaries[0].time_step, 0.1 | units.Myr) current_time = current_time + deltat instance.evolve_model(current_time) from_seba_to_model.copy() @@ -408,7 +402,6 @@ def test_evolution_of_close_binary_system(self): "Carbon/Oxygen White Dwarf", ) - for result, expected in zip(results, types): self.assertEqual(str(result[2]), expected) @@ -436,12 +429,11 @@ def test_evolution_of_close_binary_system(self): instance.stop() - def test_set_parameter_metallicity(self): instance = self.new_instance_of_an_optional_code(SeBa) - self.assertAlmostRelativeEquals(instance.parameters.metallicity , 0.02) + self.assertAlmostRelativeEquals(instance.parameters.metallicity, 0.02) instance.parameters.metallicity = 0.04 - self.assertAlmostRelativeEquals(instance.parameters.metallicity , 0.04) + self.assertAlmostRelativeEquals(instance.parameters.metallicity, 0.04) def test_set_parameter_logging(self): instance = self.new_instance_of_an_optional_code(SeBa) @@ -452,18 +444,17 @@ def test_set_parameter_logging(self): def test_add_binary_particles(self): instance = self.new_instance_of_an_optional_code(SeBa) instance.commit_parameters() - stars = Particles(2) + stars = Particles(2) stars[0].mass = 3.0 | units.MSun stars[1].mass = 0.3 | units.MSun - mu = (3.3 | units.MSun) * constants.G orbital_period = 200.0 | units.day semi_major_axis = (((orbital_period / (2.0 * numpy.pi))**2)*mu)**(1.0/3.0) instance.particles.add_particles(stars) - binaries = Particles(1) + binaries = Particles(1) binary = binaries[0] binary.semi_major_axis = semi_major_axis @@ -476,7 +467,6 @@ def test_add_binary_particles(self): self.assertAlmostRelativeEquals(instance.binaries[0].child1.mass, 3.0 | units.MSun, 4) self.assertAlmostRelativeEquals(instance.binaries[0].child2.mass, 0.3 | units.MSun, 4) - def xtest7(self): instance = self.new_instance_of_an_optional_code(SeBa) instance.parameters.metallicity = 0.03 @@ -486,7 +476,7 @@ def xtest7(self): p = instance.particles.add_particle(p) instance.evolve_model(614 | units.Myr) print(p.stellar_type) - self.assertEqual(str(p.stellar_type),'Black Hole') + self.assertEqual(str(p.stellar_type), 'Black Hole') self.assertAlmostRelativeEqual(p.mass, 0.9906 | units.MSun, 4) def test_set_semi_major_axis_eccentricity(self): @@ -524,9 +514,9 @@ def test_add_stars_at_different_times(self): stars[1].mass = 9 | units.MSun instance.particles.add_particles(stars) - instance.evolve_model(30|units.Myr) + instance.evolve_model(30 | units.Myr) - self.assertAlmostRelativeEquals(instance.particles.age, [30,30] |units.Myr) + self.assertAlmostRelativeEquals(instance.particles.age, [30, 30] | units.Myr) self.assertAlmostRelativeEquals(instance.model_time, 30 | units.Myr) self.assertAlmostRelativeEquals(instance.particles[0].mass, 1.2507 | units.MSun, 4) self.assertAlmostRelativeEquals(instance.particles[1].mass, 8.9351 | units.MSun, 4) @@ -539,7 +529,7 @@ def test_add_stars_at_different_times(self): print(instance.particles.age) print(instance.particles.mass) self.assertAlmostRelativeEquals(instance.model_time, 60 | units.Myr) - self.assertAlmostRelativeEquals(instance.particles.age, [60,60,30,30] | units.Myr) + self.assertAlmostRelativeEquals(instance.particles.age, [60, 60, 30, 30] | units.Myr) self.assertAlmostRelativeEquals(instance.particles[2].mass, 1.2507 | units.MSun, 4) self.assertAlmostRelativeEquals(instance.particles[3].mass, 8.9351 | units.MSun, 4) @@ -553,7 +543,7 @@ def test_supernova_stopping_condition(self): p.metallicity = 0.02 p = instance.particles.add_particle(p) - instance.set_supernova_kick_velocity(0.0|units.kms) + instance.set_supernova_kick_velocity(0.0 | units.kms) instance.evolve_model(30 | units.Myr) self.assertEqual(instance.stopping_conditions.supernova_detection.is_set(), True) self.assertEqual(instance.stopping_conditions.supernova_detection.particles(0)[0].key, p.key) @@ -561,22 +551,21 @@ def test_supernova_stopping_condition(self): self.assertAlmostRelativeEqual(p.age, 27.2715 | units.Myr, 4) self.assertAlmostRelativeEqual(p.mass, 1.2507 | units.MSun, 4) - self.assertAlmostRelativeEqual(p.natal_kick_velocity, [-54.070,12.818,42.583] | units.kms, 4) - + self.assertAlmostRelativeEqual(p.natal_kick_velocity, [-54.070, 12.818, 42.583] | units.kms, 4) def test_supernova_stopping_condition_in_a_binary(self): """ Test supernova stopping condition in a binary """ instance = self.new_instance_of_an_optional_code(SeBa) instance.stopping_conditions.supernova_detection.enable() - stars = Particles(2) + stars = Particles(2) stars[0].mass = 10.0 | units.MSun stars[1].mass = 5.0 | units.MSun instance.particles.add_particles(stars) - binaries = Particles(1) + binaries = Particles(1) binary = binaries[0] - binary.semi_major_axis = 1.e6|units.RSun + binary.semi_major_axis = 1.e6 | units.RSun binary.eccentricity = 0.1 binary.child1 = stars[0] binary.child2 = stars[1] @@ -605,13 +594,12 @@ def test_supernova_stopping_condition_with_multiple_stars(self): instance = self.new_instance_of_an_optional_code(SeBa) instance.stopping_conditions.supernova_detection.enable() - stars = Particles(3) + stars = Particles(3) stars[0].mass = 10.0 | units.MSun stars[1].mass = 5.0 | units.MSun stars[2].mass = 0.5 | units.MSun instance.particles.add_particles(stars) - instance.evolve_model(30 | units.Myr) self.assertEqual(instance.stopping_conditions.supernova_detection.is_set(), True) self.assertEqual(instance.stopping_conditions.supernova_detection.particles(0)[0].key, instance.particles[0].key) @@ -629,13 +617,12 @@ def test_supernova_stopping_condition_with_multiple_stars_multiple_supernovae(se instance = self.new_instance_of_an_optional_code(SeBa) instance.stopping_conditions.supernova_detection.enable() - stars = Particles(3) + stars = Particles(3) stars[0].mass = 10.0 | units.MSun stars[1].mass = 11.0 | units.MSun stars[2].mass = 0.5 | units.MSun instance.particles.add_particles(stars) - instance.evolve_model(30 | units.Myr) self.assertEqual(instance.stopping_conditions.supernova_detection.is_set(), True) self.assertEqual(instance.stopping_conditions.supernova_detection.particles(0)[0].key, instance.particles[1].key) @@ -665,13 +652,12 @@ def test_supernova_stopping_condition_with_multiple_stars_of_equal_mass(self): instance = self.new_instance_of_an_optional_code(SeBa) instance.stopping_conditions.supernova_detection.enable() - stars = Particles(3) + stars = Particles(3) stars[0].mass = 10.0 | units.MSun stars[1].mass = 10.0 | units.MSun stars[2].mass = 0.5 | units.MSun instance.particles.add_particles(stars) - instance.evolve_model(30 | units.Myr) self.assertEqual(instance.stopping_conditions.supernova_detection.is_set(), True) self.assertEqual(len(instance.stopping_conditions.supernova_detection.particles(0)), 2) @@ -697,4 +683,3 @@ def test_supernova_stopping_condition_with_multiple_stars_of_equal_mass(self): self.assertAlmostRelativeEqual(instance.particles[0].mass, 1.2507 | units.MSun, 4) self.assertAlmostRelativeEqual(instance.particles[1].mass, 1.2507 | units.MSun, 4) self.assertAlmostRelativeEqual(instance.particles[2].mass, 0.5 | units.MSun, 4) - diff --git a/src/amuse/test/suite/codes_tests/test_secularmultiple.py b/src/amuse/test/suite/codes_tests/test_secularmultiple.py index eda68d3210..0c4d5b0281 100644 --- a/src/amuse/test/suite/codes_tests/test_secularmultiple.py +++ b/src/amuse/test/suite/codes_tests/test_secularmultiple.py @@ -6,28 +6,31 @@ from amuse.community.secularmultiple.interface import SecularMultipleInterface, SecularMultiple -from amuse.units import units,quantities,constants +from amuse.units import units, quantities, constants from amuse.datamodel import Particles HAS_MATPLOTLIB = False # disable plotting in the test script + def parse_arguments(): from amuse.units.optparse import OptionParser parser = OptionParser() parser.add_option("--test", - dest="test",type="int",default=1, + dest="test", type="int", default=1, help="") options, args = parser.parse_args() return options.__dict__ + class TestSecularMultipleInterface(TestWithMPI): def test0(self): instance = SecularMultipleInterface() instance.stop() -def create_binary(m1,m2,a,e,i,g,h): + +def create_binary(m1, m2, a, e, i, g, h): particles = Particles(3) for index in range(2): @@ -51,16 +54,17 @@ def create_binary(m1,m2,a,e,i,g,h): return particles -def create_triple(m1,m2,m3,a_in,a_out,e_in,e_out,i_in,i_out,g_in,g_out,h_in,h_out): + +def create_triple(m1, m2, m3, a_in, a_out, e_in, e_out, i_in, i_out, g_in, g_out, h_in, h_out): N_bodies = 3 N_binaries = 2 - m_list = [m1,m2,m3] - a_list = [a_in,a_out] - e_list = [e_in,e_out] - i_list = [i_in,i_out] - g_list = [g_in,g_out] - h_list = [h_in,h_out] + m_list = [m1, m2, m3] + a_list = [a_in, a_out] + e_list = [e_in, e_out] + i_list = [i_in, i_out] + g_list = [g_in, g_out] + h_list = [h_in, h_out] particles = Particles(N_bodies + N_binaries) @@ -79,25 +83,26 @@ def create_triple(m1,m2,m3,a_in,a_out,e_in,e_out,i_in,i_out,g_in,g_out,h_in,h_ou particles[index+N_bodies].argument_of_pericenter = g_list[index] particles[index+N_bodies].longitude_of_ascending_node = h_list[index] - if index==0: + if index == 0: particles[index+N_bodies].child1 = particles[0] particles[index+N_bodies].child2 = particles[1] - elif index==1: + elif index == 1: particles[index+N_bodies].child1 = particles[2] particles[index+N_bodies].child2 = particles[3] return particles -def create_quadruple_triple_single(m1,m2,m3,m4,a_A,a_B,a_C,e_A,e_B,e_C,i_A,i_B,i_C,g_A,g_B,g_C,h_A,h_B,h_C): + +def create_quadruple_triple_single(m1, m2, m3, m4, a_A, a_B, a_C, e_A, e_B, e_C, i_A, i_B, i_C, g_A, g_B, g_C, h_A, h_B, h_C): N_bodies = 4 N_binaries = 3 - m_list = [m1,m2,m3,m4] - a_list = [a_A,a_B,a_C] - e_list = [e_A,e_B,e_C] - i_list = [i_A,i_B,i_C] - g_list = [g_A,g_B,g_C] - h_list = [h_A,h_B,h_C] + m_list = [m1, m2, m3, m4] + a_list = [a_A, a_B, a_C] + e_list = [e_A, e_B, e_C] + i_list = [i_A, i_B, i_C] + g_list = [g_A, g_B, g_C] + h_list = [h_A, h_B, h_C] particles = Particles(N_bodies + N_binaries) @@ -117,20 +122,20 @@ def create_quadruple_triple_single(m1,m2,m3,m4,a_A,a_B,a_C,e_A,e_B,e_C,i_A,i_B,i particle.argument_of_pericenter = g_list[index] particle.longitude_of_ascending_node = h_list[index] - if index==0: + if index == 0: particle.child1 = particles[1] particle.child2 = particles[0] - elif index==1: + elif index == 1: particle.child1 = particles[2] particle.child2 = particles[4] - elif index==2: + elif index == 2: particle.child1 = particles[5] particle.child2 = particles[3] return particles -def create_nested_multiple(N,masses,semimajor_axes,eccentricities,inclinations,arguments_of_pericentre,longitudes_of_ascending_node): +def create_nested_multiple(N, masses, semimajor_axes, eccentricities, inclinations, arguments_of_pericentre, longitudes_of_ascending_node): """ N is number of bodies masses should be N-sized array @@ -159,8 +164,7 @@ def create_nested_multiple(N,masses,semimajor_axes,eccentricities,inclinations,a particle.argument_of_pericenter = arguments_of_pericentre[index] particle.longitude_of_ascending_node = longitudes_of_ascending_node[index] - - if index==0: + if index == 0: particle.child1 = particles[0] particle.child2 = particles[1] else: @@ -171,17 +175,17 @@ def create_nested_multiple(N,masses,semimajor_axes,eccentricities,inclinations,a return particles + class TestSecularMultiple(TestWithMPI): def test0(self): instance = SecularMultiple() print(instance.parameters) - def test1(self): """ test reference system of Naoz et al. (2009) """ - particles = create_nested_multiple(3,[1.0|units.MSun, 1.0|units.MJupiter, 40.0|units.MJupiter], [6.0|units.AU,100.0|units.AU], [0.001,0.6], [0.0001,65.0*numpy.pi/180.0],[45.0*numpy.pi/180.0,0.0001],[0.01,0.01]) + particles = create_nested_multiple(3, [1.0 | units.MSun, 1.0 | units.MJupiter, 40.0 | units.MJupiter], [6.0 | units.AU, 100.0 | units.AU], [0.001, 0.6], [0.0001, 65.0*numpy.pi/180.0], [45.0*numpy.pi/180.0, 0.0001], [0.01, 0.01]) binaries = particles[particles.is_binary] binaries.include_pairwise_1PN_terms = False @@ -192,7 +196,6 @@ def test1(self): channel_to_code = particles.new_channel_to(code.particles) channel_from_code = code.particles.new_channel_to(particles) - channel_to_code.copy() self.assertEqual(0.6, code.particles[particles.is_binary][1].eccentricity) @@ -207,11 +210,11 @@ def test1(self): AP_print_array = quantities.AdaptingVectorQuantity() N = 0 - while (t= 7: @@ -515,11 +511,12 @@ def read_input_file(input_file): flux.append(float(l[5])) xion.append(float(l[6])) u.append(float(l[7])) - - return x, y, z, nh, flux, xion,u + + return x, y, z, nh, flux, xion, u + def particles_from_input_file(input_file): - x, y, z, n_H, flux, X_ion,u = read_input_file(input_file) + x, y, z, n_H, flux, X_ion, u = read_input_file(input_file) particles = Particles(len(x)) particles.x = x | units.parsec particles.y = y | units.parsec @@ -530,9 +527,10 @@ def particles_from_input_file(input_file): particles.u = u | (units.cm**2/units.s**2) return particles + def splitset_from_input_file(input_file): - x, y, z, n_H, flux, X_ion,u = read_input_file(input_file) - + x, y, z, n_H, flux, X_ion, u = read_input_file(input_file) + particles = Particles(len(x)) particles.x = x | units.parsec particles.y = y | units.parsec @@ -540,13 +538,12 @@ def splitset_from_input_file(input_file): particles.rho = n_H | units.amu / units.cm**3 particles.xion = X_ion | units.none particles.u = u | (units.cm**2/units.s**2) - - a=numpy.where(numpy.array(flux) > 0.)[0] - src_particles=Particles(len(a)) + + a = numpy.where(numpy.array(flux) > 0.)[0] + src_particles = Particles(len(a)) src_particles.x = numpy.array(x)[a] | units.parsec src_particles.y = numpy.array(y)[a] | units.parsec src_particles.z = numpy.array(z)[a] | units.parsec - src_particles.luminosity = numpy.array(flux)[a] | 1.e48*units.s**-1 - - return particles,src_particles + src_particles.luminosity = numpy.array(flux)[a] | 1.e48*units.s**-1 + return particles, src_particles diff --git a/src/amuse/test/suite/codes_tests/test_smalln.py b/src/amuse/test/suite/codes_tests/test_smalln.py index d4c7593019..5c33a5bf61 100644 --- a/src/amuse/test/suite/codes_tests/test_smalln.py +++ b/src/amuse/test/suite/codes_tests/test_smalln.py @@ -24,27 +24,27 @@ class TestSmallNInterface(TestWithMPI): def test0(self): instance = SmallNInterface() instance.stop() - + def test1(self): instance = SmallNInterface() instance.initialize_code() - - res1 = instance.new_particle(mass = 11.0, radius = 2.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) - res2 = instance.new_particle(mass = 21.0, radius = 5.0, x = 10.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) - + + res1 = instance.new_particle(mass=11.0, radius=2.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) + res2 = instance.new_particle(mass=21.0, radius=5.0, x=10.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) + self.assertEqual(1, res1['index_of_the_particle']) self.assertEqual(2, res2['index_of_the_particle']) - + retrieved_state1 = instance.get_state(1) retrieved_state2 = instance.get_state(2) - + self.assertEqual(11.0, retrieved_state1['mass']) self.assertEqual(21.0, retrieved_state2['mass']) self.assertEqual(0.0, retrieved_state1['x']) self.assertEqual(10.0, retrieved_state2['x']) self.assertEqual(2.0, retrieved_state1['radius']) self.assertEqual(5.0, retrieved_state2['radius']) - + instance.cleanup_code() instance.stop() @@ -53,84 +53,82 @@ def test2(self): instance.initialize_code() self.skip("index of the next particle not implemented correctly yet") for i in [0, 1, 2]: - temp_particle = instance.new_particle(mass = i, radius = 1.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) + temp_particle = instance.new_particle(mass=i, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) self.assertEqual(i+1, temp_particle['index_of_the_particle']) - + instance.delete_particle(2) - + self.assertEqual(2, instance.get_number_of_particles()['number_of_particles']) - + self.assertEqual(1, instance.get_index_of_first_particle()['index_of_the_particle']) - + self.assertEqual(2, instance.get_index_of_next_particle(1)['index_of_the_next_particle']) self.assertEqual(0, instance.get_index_of_next_particle(1)['__result']) self.assertEqual(-1, instance.get_index_of_next_particle(3)['__result']) self.assertEqual(1, instance.get_index_of_next_particle(2)['__result']) instance.cleanup_code() instance.stop() - def test5(self): smalln = SmallNInterface() smalln.initialize_code() - - smalln.new_particle([10,20],[0,0],[0,0], [0,0], [0,0], [0,0], [0,0],[1,1]) + + smalln.new_particle([10, 20], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 1]) retrieved_state = smalln.get_state(1) - + self.assertEqual(10.0, retrieved_state['mass']) self.assertEqual(1, retrieved_state['radius']) - - retrieved_state = smalln.get_state([1,2]) + + retrieved_state = smalln.get_state([1, 2]) self.assertEqual(20.0, retrieved_state['mass'][1]) self.assertEqual(smalln.get_number_of_particles()['number_of_particles'], 2) - smalln.cleanup_code() + smalln.cleanup_code() smalln.stop() def test6(self): smalln = SmallNInterface() smalln.initialize_code() - - smalln.new_particle([10,10],[-1,1],[0,0], [0,0], [0,0], [0,0], [0,0], [1,1]) + + smalln.new_particle([10, 10], [-1, 1], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [1, 1]) retrieved_state = smalln.get_state(1) - + self.assertFalse(hasattr(smalln, 'get_potential_at_point')) - #retr = smalln.get_potential_at_point(0.01, 0, 0, 0) - #self.assertEqual(retr['__result'], -1) + # retr = smalln.get_potential_at_point(0.01, 0, 0, 0) + # self.assertEqual(retr['__result'], -1) smalln.cleanup_code() smalln.stop() - + def xtest7(self): instance = SmallNInterface() instance.initialize_code() instance.set_eps2(0.1 * 0.1) instance.commit_parameters() - id1,errorcode = instance.new_particle(mass = 10.0, radius = 1.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) - id2,errorcode = instance.new_particle(mass = 10.0, radius = 1.0, x = 2.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) - + id1, errorcode = instance.new_particle(mass=10.0, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) + id2, errorcode = instance.new_particle(mass=10.0, radius=1.0, x=2.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) + instance.commit_particles() potential, errorcode = instance.get_potential(id1) self.assertEqual(errorcode, 0) self.assertAlmostRelativeEquals(potential, -10.0 / numpy.sqrt(2.0**2 + 0.1**2), 8) - + potential, errorcode = instance.get_potential(id2) self.assertEqual(errorcode, 0) self.assertAlmostRelativeEquals(potential, -10.0 / numpy.sqrt(2.0**2 + 0.1**2), 8) - + total_potential, errorcode = instance.get_potential_energy() potentials, errorcode = instance.get_potential([id1, id2]) instance.cleanup_code() instance.stop() - + self.assertAlmostRelativeEquals(total_potential, numpy.sum(potentials * [10.0, 10.0]) / 2.0) - def xtest8(self): instance = SmallNInterface() instance.initialize_code() instance.commit_parameters() - id1,errorcode = instance.new_particle(mass = 10.0, radius = 1.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) - id2,errorcode = instance.new_particle(mass = 1.0, radius = 1.0, x = 2.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) - + id1, errorcode = instance.new_particle(mass=10.0, radius=1.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) + id2, errorcode = instance.new_particle(mass=1.0, radius=1.0, x=2.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) + instance.commit_particles() potential, errorcode = instance.get_potential(id1) self.assertEqual(errorcode, 0) @@ -139,41 +137,39 @@ def xtest8(self): potentials, errorcode = instance.get_potential([id1, id2]) instance.cleanup_code() instance.stop() - + self.assertAlmostRelativeEquals(total_potential, numpy.sum(potentials * [10.0, 1.0]) / 2.0) - - + def test9(self): print("Test SmallNInterface evolve_model") instance = SmallNInterface() self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.set_eta(0.001)) self.assertEqual(0, instance.commit_parameters()) - + # Set up an equal-mass binary on a circular orbit: self.assertEqual([1, 0], list(instance.new_particle(0.5, 0.5, 0, 0, 0, 0.5, 0, 0.01).values())) - self.assertEqual([2, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0,-0.5, 0, 0.01).values())) + self.assertEqual([2, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0, -0.5, 0, 0.01).values())) self.assertEqual(0, instance.commit_particles()) - + self.assertEqual(0, instance.evolve_model(math.pi)) for result, expected in zip(instance.get_position(1).values(), [-0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 3) for result, expected in zip(instance.get_position(2).values(), [0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 3) - + self.assertEqual(0, instance.evolve_model(2 * math.pi)) - #print instance.get_time() - #print instance.get_position(1), instance.get_velocity(1) - #print instance.get_position(2) - #for result, expected in zip(instance.get_position(1).values(), [0.5, 0.0, 0.0, 0]): + # print instance.get_time() + # print instance.get_position(1), instance.get_velocity(1) + # print instance.get_position(2) + # for result, expected in zip(instance.get_position(1).values(), [0.5, 0.0, 0.0, 0]): # self.assertAlmostEquals(result, expected, 3) - #for result, expected in zip(instance.get_position(2).values(), [-0.5, 0.0, 0.0, 0]): + # for result, expected in zip(instance.get_position(2).values(), [-0.5, 0.0, 0.0, 0]): # self.assertAlmostEquals(result, expected, 3) - + self.assertEqual(0, instance.cleanup_code()) instance.cleanup_code() instance.stop() - class TestSmallN(TestWithMPI): @@ -181,93 +177,88 @@ def new_system_of_sun_and_earth(self): stars = datamodel.Stars(2) sun = stars[0] sun.mass = units.MSun(1.0) - sun.position = units.m(numpy.array((0.0,0.0,0.0))) - sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) + sun.position = units.m(numpy.array((0.0, 0.0, 0.0))) + sun.velocity = units.ms(numpy.array((0.0, 0.0, 0.0))) sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) - earth.radius = units.km(6371) - earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) - earth.velocity = units.ms(numpy.array((0.0,29800,0.0))) - + earth.radius = units.km(6371) + earth.position = units.km(numpy.array((149.5e6, 0.0, 0.0))) + earth.velocity = units.ms(numpy.array((0.0, 29800, 0.0))) + return stars - - + def test1(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) - + smalln = SmallN(convert_nbody) smalln.initialize_code() smalln.dt_dia = 5000 - + stars = self.new_system_of_sun_and_earth() earth = stars[1] - + smalln.particles.add_particles(stars) - + smalln.evolve_model(365.0 | units.day) smalln.particles.copy_values_of_all_attributes_to(stars) - + position_at_start = earth.position.value_in(units.AU)[0] position_after_full_rotation = earth.position.value_in(units.AU)[0] self.assertAlmostEqual(position_at_start, position_after_full_rotation, 6) - + smalln.evolve_model(365.0 + (365.0 / 2) | units.day) - + smalln.particles.copy_values_of_all_attributes_to(stars) position_after_half_a_rotation = earth.position.value_in(units.AU)[0] self.assertAlmostEqual(-position_at_start, position_after_half_a_rotation, 2) - - smalln.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) - + + smalln.evolve_model(365.0 + (365.0 / 2) + (365.0 / 4) | units.day) + smalln.particles.copy_values_of_all_attributes_to(stars) position_after_half_a_rotation = earth.position.value_in(units.AU)[1] self.assertAlmostEqual(-position_at_start, position_after_half_a_rotation, 3) - + smalln.cleanup_code() - + smalln.stop() - def test2(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) - + instance = SmallN(convert_nbody) instance.initialize_code() instance.dt_dia = 5000 - + stars = self.new_system_of_sun_and_earth() earth = stars[1] instance.particles.add_particles(stars) - - for x in range(1,2000,10): + + for x in range(1, 2000, 10): instance.evolve_model(x | units.day) instance.particles.copy_values_of_all_attributes_to(stars) stars.savepoint() - + if HAS_MATPLOTLIB: figure = pyplot.figure() - plot = figure.add_subplot(1,1,1) - + plot = figure.add_subplot(1, 1, 1) + x_points = earth.get_timeline_of_attribute("x") y_points = earth.get_timeline_of_attribute("y") - + x_points_in_AU = [t_x[1].value_in(units.AU) for t_x in x_points] y_points_in_AU = [t_x1[1].value_in(units.AU) for t_x1 in y_points] - - plot.scatter(x_points_in_AU,y_points_in_AU, color = "b", marker = 'o') - + + plot.scatter(x_points_in_AU, y_points_in_AU, color="b", marker='o') + plot.set_xlim(-1.5, 1.5) plot.set_ylim(-1.5, 1.5) - - + test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "smalln-earth-sun2.svg") figure.savefig(output_file) - - - + instance.cleanup_code() instance.stop() @@ -277,53 +268,51 @@ def test3(self): instance = SmallN(convert_nbody) instance.initialize_code() instance.dt_dia = 5000 - + stars = datamodel.Stars(2) star1 = stars[0] star2 = stars[1] star1.mass = units.MSun(1.0) - star1.position = units.AU(numpy.array((-1.0,0.0,0.0))) - star1.velocity = units.AUd(numpy.array((0.0,0.0,0.0))) + star1.position = units.AU(numpy.array((-1.0, 0.0, 0.0))) + star1.velocity = units.AUd(numpy.array((0.0, 0.0, 0.0))) star1.radius = units.RSun(1.0) star2.mass = units.MSun(1.0) - star2.position = units.AU(numpy.array((1.0,0.0,0.0))) - star2.velocity = units.AUd(numpy.array((0.0,0.0,0.0))) + star2.position = units.AU(numpy.array((1.0, 0.0, 0.0))) + star2.velocity = units.AUd(numpy.array((0.0, 0.0, 0.0))) star2.radius = units.RSun(100.0) - + instance.particles.add_particles(stars) - - for x in range(1,2000,10): + + for x in range(1, 2000, 10): instance.evolve_model(x | units.day) instance.particles.copy_values_of_all_attributes_to(stars) stars.savepoint() - + instance.stop() - + def test4(self): convert_nbody = nbody_system.nbody_to_si(5.0 | units.kg, 10.0 | units.m) instance = SmallN(convert_nbody) instance.initialize_code() - + particles = datamodel.Particles(2) self.assertEqual(len(instance.particles), 0) - + particles.mass = [15.0, 30.0] | units.kg - particles.radius = [10.0, 20.0] | units.m + particles.radius = [10.0, 20.0] | units.m particles.position = [[10.0, 20.0, 30.0], [20.0, 40.0, 60.0]] | units.m particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.m / units.s - instance.particles.add_particles(particles) self.assertEqual(len(instance.particles), 2) - - instance.particles.mass = [17.0, 33.0] | units.kg - - - self.assertEqual(instance.get_mass(1), 17.0| units.kg) - self.assertEqual(instance.get_mass(2), 33.0| units.kg) + + instance.particles.mass = [17.0, 33.0] | units.kg + + self.assertEqual(instance.get_mass(1), 17.0 | units.kg) + self.assertEqual(instance.get_mass(2), 33.0 | units.kg) instance.stop() def test5(self): @@ -331,51 +320,48 @@ def test5(self): instance = SmallN(convert_nbody) instance.initialize_code() - + particles = datamodel.Particles(2) self.assertEqual(len(instance.particles), 0) - + particles.mass = [15.0, 30.0] | units.kg - particles.radius = [10.0, 20.0] | units.m + particles.radius = [10.0, 20.0] | units.m particles.position = [[10.0, 20.0, 30.0], [20.0, 40.0, 60.0]] | units.m particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.m / units.s - instance.particles.add_particles(particles) self.assertEqual(len(instance.particles), 2) - instance.set_state(1, 16|units.kg, - 20.0|units.m, 40.0|units.m, 60.0|units.m, - 1.0|units.ms, 1.0|units.ms, 1.0|units.ms , - 20.0|units.m) - - curr_state = instance.get_state(1) - for expected, actual in zip([16|units.kg, - 20.0|units.m, 40.0|units.m, 60.0|units.m, - 1.0|units.ms, 1.0|units.ms, 1.0|units.ms , - 20.0|units.m], curr_state): + instance.set_state(1, 16 | units.kg, + 20.0 | units.m, 40.0 | units.m, 60.0 | units.m, + 1.0 | units.ms, 1.0 | units.ms, 1.0 | units.ms, + 20.0 | units.m) + + curr_state = instance.get_state(1) + for expected, actual in zip([16 | units.kg, + 20.0 | units.m, 40.0 | units.m, 60.0 | units.m, + 1.0 | units.ms, 1.0 | units.ms, 1.0 | units.ms, + 20.0 | units.m], curr_state): self.assertAlmostRelativeEquals(expected, actual) instance.stop() - - self.assertEqual(curr_state[0], 16|units.kg, 8) - + + self.assertEqual(curr_state[0], 16 | units.kg, 8) + def test6(self): print("Test6: Testing SmallN parameters") convert_nbody = nbody_system.nbody_to_si(1.0 | units.yr, 1.0 | units.AU) instance = SmallN(convert_nbody) instance.initialize_code() - - + value = instance.get_eta() self.assertEqual(0.14, value) self.assertAlmostEqual(0.14, instance.parameters.timestep_parameter) for x in [0.001, 0.01, 0.1]: instance.parameters.timestep_parameter = x self.assertAlmostEqual(x, instance.parameters.timestep_parameter) - - + value = instance.get_time() - self.assertEqual(0| units.yr, value) - + self.assertEqual(0 | units.yr, value) + value = instance.get_gamma() self.assertEqual(1e-6, value) self.assertAlmostEqual(1e-6, instance.parameters.unperturbed_threshold) @@ -383,37 +369,36 @@ def test6(self): instance.parameters.unperturbed_threshold = x self.assertAlmostEqual(x, instance.parameters.unperturbed_threshold) instance.stop() - def test15(self): particles = datamodel.Particles(2) - particles.x = [0.0,10.0] | nbody_system.length + particles.x = [0.0, 10.0] | nbody_system.length particles.y = 0.0 | nbody_system.length particles.z = 0.0 | nbody_system.length - particles.vx = 0.0 | nbody_system.speed - particles.vy = 0.0 | nbody_system.speed - particles.vz = 0.0 | nbody_system.speed + particles.vx = 0.0 | nbody_system.speed + particles.vy = 0.0 | nbody_system.speed + particles.vz = 0.0 | nbody_system.speed particles.mass = 1.0 | nbody_system.mass instance = SmallN() - instance.particles.add_particles(particles) + instance.particles.add_particles(particles) instance.commit_particles() self.assertEqual(instance.particles[0].radius, 0.0 | nbody_system.length) p = datamodel.Particle( - x = 1.0 | nbody_system.length, - y = 2.0 | nbody_system.length, - z = 3.0 | nbody_system.length, - vx = 1.0 | nbody_system.speed, - vy = 2.0 | nbody_system.speed, - vz = 3.0 | nbody_system.speed, - mass = 1.0 | nbody_system.mass, - radius = 4.0 | nbody_system.length, + x=1.0 | nbody_system.length, + y=2.0 | nbody_system.length, + z=3.0 | nbody_system.length, + vx=1.0 | nbody_system.speed, + vy=2.0 | nbody_system.speed, + vz=3.0 | nbody_system.speed, + mass=1.0 | nbody_system.mass, + radius=4.0 | nbody_system.length, ) - instance.particles.add_particle(p) + instance.particles.add_particle(p) self.assertEqual(instance.particles[0].radius, 0.0 | nbody_system.length) self.assertEqual(instance.particles[1].radius, 0.0 | nbody_system.length) self.assertEqual(instance.particles[2].radius, 4.0 | nbody_system.length) - + instance.stop() def assertEarthAndMoonWasDetectedAsBinary(self, set, stars): @@ -426,64 +411,59 @@ def assertEarthAndMoonWasDetectedAsBinary(self, set, stars): earth_and_moon = root.child1 else: earth_and_moon = root.child2 - + self.assertAlmostRelativeEquals(earth_and_moon.mass, stars[1].mass + stars[2].mass) - - + def test16(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) - + smalln = SmallN(convert_nbody) smalln.initialize_code() smalln.dt_dia = 5000 - + stars = self.new_system_of_sun_and_earth() - + moon = datamodel.Particle() moon.mass = units.kg(7.3477e22) - moon.radius = units.km(1737.10) - moon.position = units.km(numpy.array((149.5e6 + 384.399 ,0.0,0.0))) - moon.velocity = units.ms(numpy.array((0.0,29800 + 1022,0.0))) - + moon.radius = units.km(1737.10) + moon.position = units.km(numpy.array((149.5e6 + 384.399, 0.0, 0.0))) + moon.velocity = units.ms(numpy.array((0.0, 29800 + 1022, 0.0))) + stars.add_particle(moon) - + earth = stars[1] - + smalln.particles.add_particles(stars) - + smalln.evolve_model(365.0 | units.day) smalln.update_particle_tree() smalln.update_particle_set() - self.assertEqual(len(smalln.particles), 5) - + self.assertEarthAndMoonWasDetectedAsBinary(smalln.particles, stars) - - + inmemory = smalln.particles.copy() self.assertEarthAndMoonWasDetectedAsBinary(inmemory, stars) - + test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "newsmalln-test16.hdf5") if os.path.exists(output_file): os.remove(output_file) - + io.write_set_to_file(smalln.particles, output_file, "hdf5") fromfile = io.read_set_from_file(output_file, "hdf5") self.assertEarthAndMoonWasDetectedAsBinary(fromfile, stars) smalln.stop() - - def test17(self): - - particles = datamodel.Particles(keys=[1,2,3,4,5,6,7]) + + particles = datamodel.Particles(keys=[1, 2, 3, 4, 5, 6, 7]) particles.mass = 0.001 | nbody_system.mass particles.radius = 0.1 | nbody_system.length particles.x = [ - -100.5, -99.5, - -0.5, 0.5, + -100.5, -99.5, + -0.5, 0.5, 99.5, 100.5, 120.0 ] | nbody_system.length @@ -495,101 +475,97 @@ def test17(self): [2, 0, 0], [-2, 0, 0], [-4, 0, 0] ] | nbody_system.speed - + instance = SmallN() instance.particles.add_particles(particles) - + collisions = instance.stopping_conditions.collision_detection collisions.enable() - + instance.evolve_model(1.0 | nbody_system.time) - + self.assertTrue(collisions.is_set()) self.assertTrue(instance.model_time < 0.5 | nbody_system.time) - + self.assertEqual(len(collisions.particles(0)), 3) self.assertEqual(len(collisions.particles(1)), 3) self.assertEqual(len(particles - collisions.particles(0) - collisions.particles(1)), 1) - self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) <= + self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) <= (collisions.particles(0).radius + collisions.particles(1).radius), [True, True, True]) instance.stop() - - + def test18(self): - - particles = datamodel.Particles(keys=[1,2]) + + particles = datamodel.Particles(keys=[1, 2]) particles.mass = 1 | nbody_system.mass particles.radius = 0.1 | nbody_system.length particles.x = [1, -1] | nbody_system.length particles.y = [1, -1] | nbody_system.length particles.z = 0 | nbody_system.length particles.velocity = [[-1, 0, 0], [1, 0, 0]] | nbody_system.speed - + instance = SmallN() instance.particles.add_particles(particles) - + stopping_condition = instance.stopping_conditions.interaction_over_detection stopping_condition.enable() - - + instance.evolve_model(10.0 | nbody_system.time) self.assertTrue(stopping_condition.is_set()) self.assertTrue(instance.model_time < 11.0 | nbody_system.time) - instance.stop() - + instance.stop() def test19(self): - - particles = datamodel.Particles(keys=[1,2, 3]) + + particles = datamodel.Particles(keys=[1, 2, 3]) particles.mass = 1 | nbody_system.mass particles.radius = 0.1 | nbody_system.length particles.x = [1, -1, 0] | nbody_system.length particles.y = [1, -1, 0] | nbody_system.length - particles.z = [0, 0, 1]| nbody_system.length - particles.velocity = [[-1, 0, 0], [1, 0, 0],[0,0,-10]] | nbody_system.speed - + particles.z = [0, 0, 1] | nbody_system.length + particles.velocity = [[-1, 0, 0], [1, 0, 0], [0, 0, -10]] | nbody_system.speed + instance = SmallN() instance.particles.add_particles(particles) - + stopping_condition = instance.stopping_conditions.interaction_over_detection stopping_condition.enable() - - + instance.evolve_model(10.0 | nbody_system.time) self.assertTrue(stopping_condition.is_set()) - + self.assertTrue(instance.model_time < 10.0 | nbody_system.time) - instance.stop() - + instance.stop() + def test20(self): p = datamodel.Particles(3) - p[0].mass = 6.667e-01 | nbody_system.mass + p[0].mass = 6.667e-01 | nbody_system.mass p[0].radius = 4.000e-03 | nbody_system.length - p[0].x = -1.309e+01 | nbody_system.length - p[0].y = 1.940e+01 | nbody_system.length - p[0].z = -1.163e+01 | nbody_system.length - p[0].vx = 2.366e-01 | nbody_system.speed + p[0].x = -1.309e+01 | nbody_system.length + p[0].y = 1.940e+01 | nbody_system.length + p[0].z = -1.163e+01 | nbody_system.length + p[0].vx = 2.366e-01 | nbody_system.speed p[0].vy = -3.813e-01 | nbody_system.speed - p[0].vz = 2.486e-01 | nbody_system.speed - - p[1].mass = 3.333e-01 | nbody_system.mass - p[1].radius = 1.000e-03 | nbody_system.length - p[1].x = -1.506e+01 | nbody_system.length - p[1].y = 1.937e+01 | nbody_system.length - p[1].z = -1.163e+01 | nbody_system.length - p[1].vx = 3.483e-01 | nbody_system.speed + p[0].vz = 2.486e-01 | nbody_system.speed + + p[1].mass = 3.333e-01 | nbody_system.mass + p[1].radius = 1.000e-03 | nbody_system.length + p[1].x = -1.506e+01 | nbody_system.length + p[1].y = 1.937e+01 | nbody_system.length + p[1].z = -1.163e+01 | nbody_system.length + p[1].vx = 3.483e-01 | nbody_system.speed p[1].vy = -4.513e-01 | nbody_system.speed - p[1].vz = 2.486e-01 | nbody_system.speed + p[1].vz = 2.486e-01 | nbody_system.speed - p[2].mass = 5.000e-01 | nbody_system.mass - p[2].radius = 2.000e-03 | nbody_system.length - p[2].x = 2.749e+01 | nbody_system.length - p[2].y = -3.877e+01 | nbody_system.length - p[2].z = 2.325e+01 | nbody_system.length + p[2].mass = 5.000e-01 | nbody_system.mass + p[2].radius = 2.000e-03 | nbody_system.length + p[2].x = 2.749e+01 | nbody_system.length + p[2].y = -3.877e+01 | nbody_system.length + p[2].z = 2.325e+01 | nbody_system.length p[2].vx = -5.476e-01 | nbody_system.speed - p[2].vy = 8.092e-01 | nbody_system.speed + p[2].vy = 8.092e-01 | nbody_system.speed p[2].vz = -4.972e-01 | nbody_system.speed instance = SmallN() @@ -604,14 +580,12 @@ def test20(self): instance.particles.add_particles(particles) instance.commit_particles() - sc = instance.stopping_conditions.collision_detection sc.enable() - isCollision = False instance.evolve_model(t_end) isCollision = sc.is_set() - + instance.stop() self.assertTrue(isCollision, "no collision detected") diff --git a/src/amuse/test/suite/codes_tests/test_sphray.py b/src/amuse/test/suite/codes_tests/test_sphray.py index aa1a70a445..2cd3f2dbcd 100644 --- a/src/amuse/test/suite/codes_tests/test_sphray.py +++ b/src/amuse/test/suite/codes_tests/test_sphray.py @@ -2,28 +2,29 @@ import numpy from amuse.test.amusetest import TestWithMPI -from amuse.community.sphray.interface import SPHRayInterface,SPHRay +from amuse.community.sphray.interface import SPHRayInterface, SPHRay from amuse.units import units -from amuse.datamodel import Particles,create_particle_set +from amuse.datamodel import Particles, create_particle_set from amuse.datamodel import Particle from amuse.io import read_set_from_file -#default_options = dict(redirection="none") -default_options={} +# default_options = dict(redirection="none") +default_options = {} + class TestSPHRayInterface(TestWithMPI): - + def setUp(self): super(TestWithMPI, self).setUp() - + def test1(self): print("Test 1: initialization") - + instance = SPHRayInterface(**default_options) self.assertEqual(0, instance.initialize_code()) - self.assertEqual(0, instance.set_sphray_data_directory(instance.data_directory)) - self.assertEqual(0, instance.set_sphray_output_directory(instance.output_directory)) + self.assertEqual(0, instance.set_sphray_data_directory(instance.data_directory)) + self.assertEqual(0, instance.set_sphray_output_directory(instance.output_directory)) self.assertEqual(0, instance.commit_parameters()) self.assertEqual(0, instance.cleanup_code()) instance.stop() @@ -32,26 +33,26 @@ def test2(self): print("Test 2: add, commit_particles") instance = SPHRayInterface(**default_options) self.assertEqual(0, instance.set_sphray_data_directory(instance.data_directory)) - self.assertEqual(0, instance.set_sphray_output_directory(instance.output_directory)) + self.assertEqual(0, instance.set_sphray_output_directory(instance.output_directory)) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - + input_file = os.path.join(os.path.dirname(__file__), "test_sphray_data_4K") mass, hsml, x, y, z, rho, xe, u = self.read_gas_file(input_file) number_of_gas_particles = len(x) indices, errors = instance.new_gas_particle(mass, hsml, x, y, z, rho, xe, u) self.assertEqual(errors, [0]*number_of_gas_particles) - self.assertEqual(indices, list(range(1,number_of_gas_particles+1))) - + self.assertEqual(indices, list(range(1, number_of_gas_particles+1))) + input_file = os.path.join(os.path.dirname(__file__), "test_sphray_data_sources_001.1") L, xs, ys, zs, spctype = self.read_src_file(input_file) number_of_src_particles = len(xs) s_indices, errors = instance.new_src_particle(L, xs, ys, zs, spctype) self.assertEqual(errors, [0]*number_of_src_particles) - self.assertEqual(s_indices, list(range(number_of_gas_particles+1,number_of_src_particles+number_of_gas_particles+1))) - + self.assertEqual(s_indices, list(range(number_of_gas_particles+1, number_of_src_particles+number_of_gas_particles+1))) + self.assertEqual(0, instance.commit_particles()) - mass2, hsml2, x2, y2, z2, rho2, xe2, u2 , error = instance.get_state_gas(indices) + mass2, hsml2, x2, y2, z2, rho2, xe2, u2, error = instance.get_state_gas(indices) self.assertAlmostEqual((mass-mass2), numpy.zeros_like(x), 7) self.assertAlmostEqual((hsml-hsml2), numpy.zeros_like(x), 7) self.assertAlmostEqual((x-x2)/13200., numpy.zeros_like(x), 7) @@ -61,7 +62,7 @@ def test2(self): # self.assertAlmostEqual((xe-xe2), numpy.zeros_like(x), 7) self.assertAlmostEqual((u-u2), numpy.zeros_like(x), 7) - L2, xs2, ys2, zs2, spctype2 , error = instance.get_state_src(s_indices) + L2, xs2, ys2, zs2, spctype2, error = instance.get_state_src(s_indices) self.assertAlmostEqual((L-L2), numpy.zeros_like(xs), 7) self.assertAlmostEqual((xs-xs2)/13200., numpy.zeros_like(xs), 7) self.assertAlmostEqual((ys-ys2)/13200., numpy.zeros_like(xs), 7) @@ -75,26 +76,26 @@ def test3(self): print("Test 3: add, commit_particles, setters, remove") instance = SPHRayInterface(**default_options) self.assertEqual(0, instance.set_sphray_data_directory(instance.data_directory)) - self.assertEqual(0, instance.set_sphray_output_directory(instance.output_directory)) + self.assertEqual(0, instance.set_sphray_output_directory(instance.output_directory)) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - + input_file = os.path.join(os.path.dirname(__file__), "test_sphray_data_4K") mass, hsml, x, y, z, rho, xe, u = self.read_gas_file(input_file) number_of_gas_particles = len(x) indices, errors = instance.new_gas_particle(mass, hsml, x, y, z, rho, xe, u) self.assertEqual(errors, [0]*number_of_gas_particles) - self.assertEqual(indices, list(range(1,number_of_gas_particles+1))) - + self.assertEqual(indices, list(range(1, number_of_gas_particles+1))) + input_file = os.path.join(os.path.dirname(__file__), "test_sphray_data_sources_001.1") L, xs, ys, zs, spctype = self.read_src_file(input_file) number_of_src_particles = len(xs) s_indices, errors = instance.new_src_particle(L, xs, ys, zs, spctype) self.assertEqual(errors, [0]*number_of_src_particles) - self.assertEqual(s_indices, list(range(number_of_gas_particles+1,number_of_src_particles+number_of_gas_particles+1))) - + self.assertEqual(s_indices, list(range(number_of_gas_particles+1, number_of_src_particles+number_of_gas_particles+1))) + self.assertEqual(0, instance.commit_particles()) - mass2, hsml2, x2, y2, z2, rho2, xe2, u2 , error = instance.get_state_gas(indices) + mass2, hsml2, x2, y2, z2, rho2, xe2, u2, error = instance.get_state_gas(indices) self.assertAlmostEqual((mass-mass2), numpy.zeros_like(x), 7) self.assertAlmostEqual((hsml-hsml2), numpy.zeros_like(x), 7) self.assertAlmostEqual((x-x2)/13200., numpy.zeros_like(x), 7) @@ -104,19 +105,19 @@ def test3(self): # self.assertAlmostEqual((xe-xe2), numpy.zeros_like(x), 7) self.assertAlmostEqual((u-u2), numpy.zeros_like(x), 7) - L2, xs2, ys2, zs2, spctype2 , error = instance.get_state_src(s_indices) + L2, xs2, ys2, zs2, spctype2, error = instance.get_state_src(s_indices) self.assertAlmostEqual((L-L2), numpy.zeros_like(xs), 7) self.assertAlmostEqual((xs-xs2)/13200., numpy.zeros_like(xs), 7) self.assertAlmostEqual((ys-ys2)/13200., numpy.zeros_like(xs), 7) self.assertAlmostEqual((zs-zs2)/13200., numpy.zeros_like(xs), 7) self.assertAlmostEqual((spctype-spctype2), numpy.zeros_like(xs), 7) - error=instance.set_state_gas(100,1.,2.,3.,4.,5.,6.,7.,8.) + error = instance.set_state_gas(100, 1., 2., 3., 4., 5., 6., 7., 8.) self.assertEqual(0, error) - error=instance.set_state_gas(10000,1.,2.,3.,4.,5.,6.,7.,8.) + error = instance.set_state_gas(10000, 1., 2., 3., 4., 5., 6., 7., 8.) self.assertEqual(-1, error) - - m,h,x,y,z,rho,xe,u,error=instance.get_state_gas(100) + + m, h, x, y, z, rho, xe, u, error = instance.get_state_gas(100) self.assertEqual(0, error) self.assertAlmostEqual(m, 1., 7) self.assertAlmostEqual(h, 2., 7) @@ -127,18 +128,17 @@ def test3(self): # self.assertAlmostEqual(xe, 7., 7) self.assertAlmostEqual(u, 8., 7) - error=instance.remove_gas_particle(100) + error = instance.remove_gas_particle(100) self.assertEqual(0, error) - error=instance.remove_gas_particle(100) + error = instance.remove_gas_particle(100) self.assertEqual(-4, error) - - error=instance.set_state_src(4097,1.,2.,3.,4.,5.) + error = instance.set_state_src(4097, 1., 2., 3., 4., 5.) self.assertEqual(0, error) - error=instance.set_state_src(10000,1.,2.,3.,4.,5.) + error = instance.set_state_src(10000, 1., 2., 3., 4., 5.) self.assertEqual(-1, error) - - L,x,y,z,s,error=instance.get_state_src(4097) + + L, x, y, z, s, error = instance.get_state_src(4097) self.assertEqual(0, error) self.assertAlmostEqual(L, 1., 7) self.assertAlmostEqual(x, 2., 7) @@ -146,17 +146,16 @@ def test3(self): self.assertAlmostEqual(z, 4., 7) self.assertAlmostEqual(s, 5., 7) - error=instance.remove_src_particle(4097) + error = instance.remove_src_particle(4097) self.assertEqual(0, error) - error=instance.remove_src_particle(4097) + error = instance.remove_src_particle(4097) self.assertEqual(-4, error) instance.recommit_particles() - error=instance.remove_gas_particle(100) - self.assertEqual(-1, error) - error=instance.remove_gas_particle(4097) + error = instance.remove_gas_particle(100) + self.assertEqual(-1, error) + error = instance.remove_gas_particle(4097) self.assertEqual(-1, error) - self.assertEqual(0, instance.cleanup_code()) instance.stop() @@ -165,74 +164,74 @@ def test4(self): print("Test 2: set, get time") instance = SPHRayInterface(**default_options) self.assertEqual(0, instance.set_sphray_data_directory(instance.data_directory)) - self.assertEqual(0, instance.set_sphray_output_directory(instance.output_directory)) + self.assertEqual(0, instance.set_sphray_output_directory(instance.output_directory)) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - + input_file = os.path.join(os.path.dirname(__file__), "test_sphray_data_4K") mass, hsml, x, y, z, rho, xe, u = self.read_gas_file(input_file) number_of_gas_particles = len(x) indices, errors = instance.new_gas_particle(mass, hsml, x, y, z, rho, xe, u) self.assertEqual(errors, [0]*number_of_gas_particles) - self.assertEqual(indices, list(range(1,number_of_gas_particles+1))) - + self.assertEqual(indices, list(range(1, number_of_gas_particles+1))) + input_file = os.path.join(os.path.dirname(__file__), "test_sphray_data_sources_001.1") L, xs, ys, zs, spctype = self.read_src_file(input_file) number_of_src_particles = len(xs) s_indices, errors = instance.new_src_particle(L, xs, ys, zs, spctype) self.assertEqual(errors, [0]*number_of_src_particles) - self.assertEqual(s_indices, list(range(number_of_gas_particles+1,number_of_src_particles+number_of_gas_particles+1))) - + self.assertEqual(s_indices, list(range(number_of_gas_particles+1, number_of_src_particles+number_of_gas_particles+1))) + self.assertEqual(0, instance.commit_particles()) - - time,err= instance.get_time() - self.assertEqual(0,err) - self.assertEqual(0.,time) - err= instance.set_time(123.) - self.assertEqual(-1,err) # because we don't know whether it is safe yet - time,err= instance.get_time() + + time, err = instance.get_time() + self.assertEqual(0, err) + self.assertEqual(0., time) + err = instance.set_time(123.) + self.assertEqual(-1, err) # because we don't know whether it is safe yet + time, err = instance.get_time() instance.stop() - self.assertEqual(0,err) - self.assertEqual(123.,time) + self.assertEqual(0, err) + self.assertEqual(123., time) def test5(self): - instance=SPHRayInterface() + instance = SPHRayInterface() instance.initialize_code() - - for x,l in [('isothermal',0), ('H_caseA',1),('He_caseA',1)]: - result,err=getattr(instance, 'get_'+x)() - self.assertEqual( (x,result),(x,l)) - err=getattr(instance, 'set_'+x)(1) - result,err=getattr(instance, 'get_'+x)() - self.assertEqual( (x,result),(x,1)) - err=getattr(instance, 'set_'+x)(0) - result,err=getattr(instance, 'get_'+x)() - self.assertEqual((x,result),(x,0)) - - for x,l in [('iontempsolver',2),('boundary',0)]: - result,err=getattr(instance, 'get_'+x)() - self.assertEqual( (x,result),(x,l)) - err=getattr(instance, 'set_'+x)(1) - result,err=getattr(instance, 'get_'+x)() - self.assertEqual( (x,result),(x,1)) - err=getattr(instance, 'set_'+x)(0) - result,err=getattr(instance, 'get_'+x)() - self.assertEqual((x,result),(x,0)) - - for x,l in [('raynumber',1000000.),('boxsize',13.2),("defaultspectype",-1.)]: - result,err=getattr(instance, 'get_'+x)() - self.assertAlmostEqual( result,l ,6) - err=getattr(instance, 'set_'+x)(1.) - result,err=getattr(instance, 'get_'+x)() - self.assertAlmostEqual( result,1. ,6) - err=getattr(instance, 'set_'+x)(0) - result,err=getattr(instance, 'get_'+x)() - self.assertAlmostEqual( result,0. ,6) - - result,err=instance.get_globalHefraction() + + for x, l in [('isothermal', 0), ('H_caseA', 1), ('He_caseA', 1)]: + result, err = getattr(instance, 'get_'+x)() + self.assertEqual((x, result), (x, l)) + err = getattr(instance, 'set_'+x)(1) + result, err = getattr(instance, 'get_'+x)() + self.assertEqual((x, result), (x, 1)) + err = getattr(instance, 'set_'+x)(0) + result, err = getattr(instance, 'get_'+x)() + self.assertEqual((x, result), (x, 0)) + + for x, l in [('iontempsolver', 2), ('boundary', 0)]: + result, err = getattr(instance, 'get_'+x)() + self.assertEqual((x, result), (x, l)) + err = getattr(instance, 'set_'+x)(1) + result, err = getattr(instance, 'get_'+x)() + self.assertEqual((x, result), (x, 1)) + err = getattr(instance, 'set_'+x)(0) + result, err = getattr(instance, 'get_'+x)() + self.assertEqual((x, result), (x, 0)) + + for x, l in [('raynumber', 1000000.), ('boxsize', 13.2), ("defaultspectype", -1.)]: + result, err = getattr(instance, 'get_'+x)() + self.assertAlmostEqual(result, l, 6) + err = getattr(instance, 'set_'+x)(1.) + result, err = getattr(instance, 'get_'+x)() + self.assertAlmostEqual(result, 1., 6) + err = getattr(instance, 'set_'+x)(0) + result, err = getattr(instance, 'get_'+x)() + self.assertAlmostEqual(result, 0., 6) + + result, err = instance.get_globalHefraction() self.assertEqual(err, 0) - self.assertEqual(result,0.) - err=instance.set_globalHefraction(0.1) + self.assertEqual(result, 0.) + err = instance.set_globalHefraction(0.1) instance.stop() self.assertEqual(err, -2) @@ -240,27 +239,27 @@ def test6(self): print("Test 3: add, commit_particles, setters, remove with velocity") instance = SPHRayInterface(**default_options) self.assertEqual(0, instance.set_sphray_data_directory(instance.data_directory)) - self.assertEqual(0, instance.set_sphray_output_directory(instance.output_directory)) + self.assertEqual(0, instance.set_sphray_output_directory(instance.output_directory)) self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - + input_file = os.path.join(os.path.dirname(__file__), "test_sphray_data_4K") - mass, hsml, x, y, z, rho, xe, u,vx,vy,vz = self.read_gas_file_vel(input_file) + mass, hsml, x, y, z, rho, xe, u, vx, vy, vz = self.read_gas_file_vel(input_file) number_of_gas_particles = len(x) - indices, errors = instance.new_gas_particle(mass, hsml, x, y, z, rho, xe, u,vx,vy,vz) + indices, errors = instance.new_gas_particle(mass, hsml, x, y, z, rho, xe, u, vx, vy, vz) self.assertEqual(errors, [0]*number_of_gas_particles) - self.assertEqual(indices, list(range(1,number_of_gas_particles+1))) - + self.assertEqual(indices, list(range(1, number_of_gas_particles+1))) + input_file = os.path.join(os.path.dirname(__file__), "test_sphray_data_sources_001.1") L, xs, ys, zs, spctype = self.read_src_file(input_file) number_of_src_particles = len(xs) s_indices, errors = instance.new_src_particle(L, xs, ys, zs, spctype) self.assertEqual(errors, [0]*number_of_src_particles) - self.assertEqual(s_indices, list(range(number_of_gas_particles+1,number_of_src_particles+number_of_gas_particles+1))) - + self.assertEqual(s_indices, list(range(number_of_gas_particles+1, number_of_src_particles+number_of_gas_particles+1))) + self.assertEqual(0, instance.commit_particles()) - mass2, hsml2, x2, y2, z2, rho2, xe2, u2 , error = instance.get_state_gas(indices) - vx2,vy2,vz2,error=instance.get_vel_gas(indices) + mass2, hsml2, x2, y2, z2, rho2, xe2, u2, error = instance.get_state_gas(indices) + vx2, vy2, vz2, error = instance.get_vel_gas(indices) self.assertAlmostEqual((mass-mass2), numpy.zeros_like(x), 7) self.assertAlmostEqual((hsml-hsml2), numpy.zeros_like(x), 7) self.assertAlmostEqual((x-x2)/13200., numpy.zeros_like(x), 7) @@ -273,22 +272,22 @@ def test6(self): # self.assertAlmostEqual((xe-xe2), numpy.zeros_like(x), 7) self.assertAlmostEqual((u-u2), numpy.zeros_like(x), 7) - L2, xs2, ys2, zs2, spctype2 , error = instance.get_state_src(s_indices) + L2, xs2, ys2, zs2, spctype2, error = instance.get_state_src(s_indices) self.assertAlmostEqual((L-L2), numpy.zeros_like(xs), 7) self.assertAlmostEqual((xs-xs2)/13200., numpy.zeros_like(xs), 7) self.assertAlmostEqual((ys-ys2)/13200., numpy.zeros_like(xs), 7) self.assertAlmostEqual((zs-zs2)/13200., numpy.zeros_like(xs), 7) self.assertAlmostEqual((spctype-spctype2), numpy.zeros_like(xs), 7) - error=instance.set_state_gas(100,1.,2.,3.,4.,5.,6.,7.,8.) + error = instance.set_state_gas(100, 1., 2., 3., 4., 5., 6., 7., 8.) self.assertEqual(0, error) - error=instance.set_vel_gas(100,9.,10.,11.) + error = instance.set_vel_gas(100, 9., 10., 11.) self.assertEqual(0, error) - error=instance.set_state_gas(10000,1.,2.,3.,4.,5.,6.,7.,8.) + error = instance.set_state_gas(10000, 1., 2., 3., 4., 5., 6., 7., 8.) self.assertEqual(-1, error) - - m,h,x,y,z,rho,xe,u,error=instance.get_state_gas(100) - vx,vy,vz,error=instance.get_vel_gas(100) + + m, h, x, y, z, rho, xe, u, error = instance.get_state_gas(100) + vx, vy, vz, error = instance.get_vel_gas(100) self.assertEqual(0, error) self.assertAlmostEqual(m, 1., 7) self.assertAlmostEqual(h, 2., 7) @@ -302,18 +301,17 @@ def test6(self): self.assertAlmostEqual(vy, 10., 7) self.assertAlmostEqual(vz, 11., 7) - error=instance.remove_gas_particle(100) + error = instance.remove_gas_particle(100) self.assertEqual(0, error) - error=instance.remove_gas_particle(100) + error = instance.remove_gas_particle(100) self.assertEqual(-4, error) - - error=instance.set_state_src(4097,1.,2.,3.,4.,5.) + error = instance.set_state_src(4097, 1., 2., 3., 4., 5.) self.assertEqual(0, error) - error=instance.set_state_src(10000,1.,2.,3.,4.,5.) + error = instance.set_state_src(10000, 1., 2., 3., 4., 5.) self.assertEqual(-1, error) - - L,x,y,z,s,error=instance.get_state_src(4097) + + L, x, y, z, s, error = instance.get_state_src(4097) self.assertEqual(0, error) self.assertAlmostEqual(L, 1., 7) self.assertAlmostEqual(x, 2., 7) @@ -321,252 +319,247 @@ def test6(self): self.assertAlmostEqual(z, 4., 7) self.assertAlmostEqual(s, 5., 7) - error=instance.remove_src_particle(4097) + error = instance.remove_src_particle(4097) self.assertEqual(0, error) - error=instance.remove_src_particle(4097) + error = instance.remove_src_particle(4097) self.assertEqual(-4, error) instance.recommit_particles() - error=instance.remove_gas_particle(100) - self.assertEqual(-1, error) - error=instance.remove_gas_particle(4097) + error = instance.remove_gas_particle(100) + self.assertEqual(-1, error) + error = instance.remove_gas_particle(4097) self.assertEqual(-1, error) - self.assertEqual(0, instance.cleanup_code()) instance.stop() - - def read_gas_file(self,filename): - p=read_set_from_file(filename,'amuse') - mass=p.mass.number - hsml=p.smoothing_length.number - x=p.x.number - y=p.y.number - z=p.z.number - rho=p.rho.number - u=p.internal_energy.number - xe=numpy.zeros_like(x) + def read_gas_file(self, filename): + p = read_set_from_file(filename, 'amuse') + mass = p.mass.number + hsml = p.smoothing_length.number + x = p.x.number + y = p.y.number + z = p.z.number + rho = p.rho.number + u = p.internal_energy.number + xe = numpy.zeros_like(x) return mass, hsml, x, y, z, rho, xe, u - def read_gas_file_vel(self,filename): - p=read_set_from_file(filename,'amuse') - mass=p.mass.number - hsml=p.smoothing_length.number - x=p.x.number - y=p.y.number - z=p.z.number - vx=numpy.random.random(len(mass)) - vy=numpy.random.random(len(mass)) - vz=numpy.random.random(len(mass)) - rho=p.rho.number - u=p.internal_energy.number - xe=numpy.zeros_like(x) - return mass, hsml, x, y, z, rho, xe, u,vx,vy,vz - - def read_src_file(self,filename): - f=open(filename) - lines=f.readlines() + def read_gas_file_vel(self, filename): + p = read_set_from_file(filename, 'amuse') + mass = p.mass.number + hsml = p.smoothing_length.number + x = p.x.number + y = p.y.number + z = p.z.number + vx = numpy.random.random(len(mass)) + vy = numpy.random.random(len(mass)) + vz = numpy.random.random(len(mass)) + rho = p.rho.number + u = p.internal_energy.number + xe = numpy.zeros_like(x) + return mass, hsml, x, y, z, rho, xe, u, vx, vy, vz + + def read_src_file(self, filename): + f = open(filename) + lines = f.readlines() f.close() - L=[] - x=[] - y=[] - z=[] - spctype=[] + L = [] + x = [] + y = [] + z = [] + spctype = [] for line in lines: - l=line.split() - if len(l) == 9: - L.append(float(l[6])) - x.append(float(l[0])) - y.append(float(l[1])) - z.append(float(l[2])) - spctype.append(float(l[7])) + l = line.split() + if len(l) == 9: + L.append(float(l[6])) + x.append(float(l[0])) + y.append(float(l[1])) + z.append(float(l[2])) + spctype.append(float(l[7])) return numpy.array(L), numpy.array(x), numpy.array(y), numpy.array(z), numpy.array(spctype) + class TestSPHRay(TestWithMPI): - + def setUp(self): super(TestWithMPI, self).setUp() - + def test0(self): print("test1: basic startup and flow") - instance=SPHRay() + instance = SPHRay() self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') instance.initialize_code() self.assertEqual(instance.get_name_of_current_state(), 'INITIALIZED') instance.parameters.box_size = 100 | units.parsec - self.assertAlmostRelativeEquals(instance.parameters.box_size, 100 | units.parsec,7) + self.assertAlmostRelativeEquals(instance.parameters.box_size, 100 | units.parsec, 7) instance.commit_parameters() self.assertEqual(instance.get_name_of_current_state(), 'EDIT') instance.commit_particles() self.assertEqual(instance.get_name_of_current_state(), 'RUN') - self.assertAlmostRelativeEquals(instance.parameters.box_size, 100 | units.parsec,7) + self.assertAlmostRelativeEquals(instance.parameters.box_size, 100 | units.parsec, 7) instance.cleanup_code() instance.stop() def test1(self): print("test1: adding particles") - instance=SPHRay() + instance = SPHRay() + + gasparts = self.read_gas_file(os.path.join(os.path.dirname(__file__), "test_sphray_data_4K")) + srcparts = self.read_src_file(os.path.join(os.path.dirname(__file__), "test_sphray_data_sources_001.1")) - gasparts=self.read_gas_file(os.path.join(os.path.dirname(__file__), "test_sphray_data_4K")) - srcparts=self.read_src_file(os.path.join(os.path.dirname(__file__), "test_sphray_data_sources_001.1")) - - self.assertEqual(len(instance.gas_particles),0) - self.assertEqual(len(instance.src_particles),0) + self.assertEqual(len(instance.gas_particles), 0) + self.assertEqual(len(instance.src_particles), 0) instance.gas_particles.add_particles(gasparts) instance.src_particles.add_particles(srcparts) - self.assertEqual(len(instance.gas_particles),len(gasparts)) - self.assertEqual(len(instance.src_particles),len(srcparts)) + self.assertEqual(len(instance.gas_particles), len(gasparts)) + self.assertEqual(len(instance.src_particles), len(srcparts)) self.assertEqual(instance.get_name_of_current_state(), 'EDIT') - gaspart2=instance.gas_particles.copy() + gaspart2 = instance.gas_particles.copy() - self.assertAlmostRelativeEquals(gasparts.position,gaspart2.position,6) - self.assertAlmostRelativeEquals(gasparts.rho,gaspart2.rho,6) - self.assertAlmostRelativeEquals(gasparts.u,gaspart2.u,6) + self.assertAlmostRelativeEquals(gasparts.position, gaspart2.position, 6) + self.assertAlmostRelativeEquals(gasparts.rho, gaspart2.rho, 6) + self.assertAlmostRelativeEquals(gasparts.u, gaspart2.u, 6) instance.cleanup_code() instance.stop() def test2(self): print("test2: test parameters") - instance=SPHRay() + instance = SPHRay() self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') - for par,val in [("isothermal_flag", False), - ("hydrogen_case_A_flag", True),("helium_case_A_flag", True)]: - val1=getattr(instance.parameters,par) - self.assertEqual(val,val1) + for par, val in [("isothermal_flag", False), + ("hydrogen_case_A_flag", True), ("helium_case_A_flag", True)]: + val1 = getattr(instance.parameters, par) + self.assertEqual(val, val1) setattr(instance.parameters, par, False) - val1=getattr(instance.parameters,par) - self.assertEqual(val1,False) + val1 = getattr(instance.parameters, par) + self.assertEqual(val1, False) setattr(instance.parameters, par, True) - val1=getattr(instance.parameters,par) - self.assertEqual(val1,True) + val1 = getattr(instance.parameters, par) + self.assertEqual(val1, True) setattr(instance.parameters, par, False) - val1=getattr(instance.parameters,par) - self.assertEqual(val1,False) + val1 = getattr(instance.parameters, par) + self.assertEqual(val1, False) - for par,val in [ - ("ionization_temperature_solver", 2),("boundary_condition", 0)]: - val1=getattr(instance.parameters,par) - self.assertEqual(val,val1) + for par, val in [ + ("ionization_temperature_solver", 2), ("boundary_condition", 0)]: + val1 = getattr(instance.parameters, par) + self.assertEqual(val, val1) setattr(instance.parameters, par, 123) - val1=getattr(instance.parameters,par) - self.assertEqual(val1,123) + val1 = getattr(instance.parameters, par) + self.assertEqual(val1, 123) - for par,val in [ + for par, val in [ ("spectra_file", "./spectra/thermal1e5.cdf")]: - val1=getattr(instance.parameters,par) - self.assertEqual(val,val1) + val1 = getattr(instance.parameters, par) + self.assertEqual(val, val1) setattr(instance.parameters, par, "somefile") - val1=getattr(instance.parameters,par) - self.assertEqual(val1,"somefile") - - for par,val,tval in [ ("number_of_rays", 1022.69032205 | (units.Myr**-1) , 10000| units.Myr**-1), - ("box_size",13.2 | units.kpc, 10. | units.kpc), - ("default_spectral_type", -1.,1.)]: - val1=getattr(instance.parameters,par) - self.assertAlmostRelativeEqual(val,val1,6) + val1 = getattr(instance.parameters, par) + self.assertEqual(val1, "somefile") + + for par, val, tval in [("number_of_rays", 1022.69032205 | (units.Myr**-1), 10000 | units.Myr**-1), + ("box_size", 13.2 | units.kpc, 10. | units.kpc), + ("default_spectral_type", -1., 1.)]: + val1 = getattr(instance.parameters, par) + self.assertAlmostRelativeEqual(val, val1, 6) setattr(instance.parameters, par, tval) - val1=getattr(instance.parameters,par) - self.assertAlmostRelativeEqual(val1,tval,6) + val1 = getattr(instance.parameters, par) + self.assertAlmostRelativeEqual(val1, tval, 6) - self.assertEqual(instance.get_name_of_current_state(), 'INITIALIZED') instance.stop() - - + def test3(self): - instance=SPHRay() + instance = SPHRay() instance.src_particles.add_particle( Particle( - luminosity = 1 | 1e48 * units.s**-1, - x = 2 | units.m, - y = 3 | units.m, - z = 4 | units.m, - SpcType = 12.3 + luminosity=1 | 1e48 * units.s**-1, + x=2 | units.m, + y=3 | units.m, + z=4 | units.m, + SpcType=12.3 ) ) self.assertAlmostRelativeEquals(instance.src_particles.luminosity, 1 | 1e48 * units.s**-1, 6) - self.assertAlmostRelativeEquals(instance.src_particles.x, 2 | units.m,7) - self.assertAlmostRelativeEquals(instance.src_particles.y, 3 | units.m,7) - self.assertAlmostRelativeEquals(instance.src_particles.z, 4 | units.m,7) - self.assertAlmostRelativeEquals(instance.src_particles.SpcType, 12.3,7) + self.assertAlmostRelativeEquals(instance.src_particles.x, 2 | units.m, 7) + self.assertAlmostRelativeEquals(instance.src_particles.y, 3 | units.m, 7) + self.assertAlmostRelativeEquals(instance.src_particles.z, 4 | units.m, 7) + self.assertAlmostRelativeEquals(instance.src_particles.SpcType, 12.3, 7) instance.stop() - + def test4(self): - instance=SPHRay() + instance = SPHRay() instance.gas_particles.add_particle( Particle( - mass = 1 | (10**10*units.MSun), - x = 2 | units.kpc, - y = 3 | units.kpc, - z = 4 | units.kpc, - h_smooth = 0.1 | (units.kpc), - rho = 0.5 | ((10**10*units.MSun) /(units.kpc)**3), - xion = 0.01, - u = 0.2 | (10**5 * units.cm/units.s)**2 + mass=1 | (10**10*units.MSun), + x=2 | units.kpc, + y=3 | units.kpc, + z=4 | units.kpc, + h_smooth=0.1 | (units.kpc), + rho=0.5 | ((10**10*units.MSun) / (units.kpc)**3), + xion=0.01, + u=0.2 | (10**5 * units.cm/units.s)**2 ) ) instance.src_particles.add_particle( Particle( - luminosity = 1 | 1e48 * units.s**-1, - x = 2 | units.m, - y = 3 | units.m, - z = 4 | units.m, - SpcType = 12.3 + luminosity=1 | 1e48 * units.s**-1, + x=2 | units.m, + y=3 | units.m, + z=4 | units.m, + SpcType=12.3 ) ) instance.commit_particles() self.assertAlmostRelativeEquals(instance.src_particles.luminosity, 1 | 1e48 * units.s**-1, 6) - self.assertAlmostRelativeEquals(instance.src_particles.x, 2 | units.m,7) - self.assertAlmostRelativeEquals(instance.src_particles.y, 3 | units.m,7) - self.assertAlmostRelativeEquals(instance.src_particles.z, 4 | units.m,7) - self.assertAlmostRelativeEquals(instance.src_particles.SpcType, 12.3,7) - + self.assertAlmostRelativeEquals(instance.src_particles.x, 2 | units.m, 7) + self.assertAlmostRelativeEquals(instance.src_particles.y, 3 | units.m, 7) + self.assertAlmostRelativeEquals(instance.src_particles.z, 4 | units.m, 7) + self.assertAlmostRelativeEquals(instance.src_particles.SpcType, 12.3, 7) + print(instance.src_particles) instance.stop() - - def read_gas_file(self,filename): - p=read_set_from_file(filename,'amuse') - mass=p.mass.number - hsml=p.smoothing_length.number - x=p.x.number - y=p.y.number - z=p.z.number - rho=p.rho.number - u=p.internal_energy.number - xe=numpy.zeros_like(x) - return create_particle_set(mass=mass | (10**10*units.MSun), h_smooth=hsml | (units.kpc), - x=x | (units.kpc), y=y| (units.kpc), z=z| (units.kpc), rho=rho | ((10**10*units.MSun) /(units.kpc)**3), - xion=xe, u=u| (10**5 * units.cm/units.s)**2) - - def read_src_file(self,filename): - f=open(filename) - lines=f.readlines() + + def read_gas_file(self, filename): + p = read_set_from_file(filename, 'amuse') + mass = p.mass.number + hsml = p.smoothing_length.number + x = p.x.number + y = p.y.number + z = p.z.number + rho = p.rho.number + u = p.internal_energy.number + xe = numpy.zeros_like(x) + return create_particle_set(mass=mass | (10**10*units.MSun), h_smooth=hsml | (units.kpc), + x=x | (units.kpc), y=y | (units.kpc), z=z | (units.kpc), rho=rho | ((10**10*units.MSun) / (units.kpc)**3), + xion=xe, u=u | (10**5 * units.cm/units.s)**2) + + def read_src_file(self, filename): + f = open(filename) + lines = f.readlines() f.close() - L=[] - x=[] - y=[] - z=[] - spctype=[] + L = [] + x = [] + y = [] + z = [] + spctype = [] for line in lines: - l=line.split() - if len(l) == 9: - L.append(float(l[6])) - x.append(float(l[0])) - y.append(float(l[1])) - z.append(float(l[2])) - spctype.append(float(l[7])) - return create_particle_set( luminosity=numpy.array(L) | (10**48 * units.s**-1), - x=numpy.array(x) | (units.kpc), y=numpy.array(y)| (units.kpc), - z=numpy.array(z)| (units.kpc), SpcType=numpy.array(spctype)) - - + l = line.split() + if len(l) == 9: + L.append(float(l[6])) + x.append(float(l[0])) + y.append(float(l[1])) + z.append(float(l[2])) + spctype.append(float(l[7])) + return create_particle_set(luminosity=numpy.array(L) | (10**48 * units.s**-1), + x=numpy.array(x) | (units.kpc), y=numpy.array(y) | (units.kpc), + z=numpy.array(z) | (units.kpc), SpcType=numpy.array(spctype)) diff --git a/src/amuse/test/suite/codes_tests/test_sse.py b/src/amuse/test/suite/codes_tests/test_sse.py index 69a5ca5df1..1d41fe9254 100644 --- a/src/amuse/test/suite/codes_tests/test_sse.py +++ b/src/amuse/test/suite/codes_tests/test_sse.py @@ -15,14 +15,14 @@ class TestMPIInterface(TestWithMPI): - + class state(object): def __init__(self): self.stellar_type = 0.0 self.zams_mass = 0.0 self.mass = 0.0 self.radius = 0.0 - self.luminosity = 0.0 + self.luminosity = 0.0 self.core_mass = 0.0 self.core_radius = 0.0 self.envelope_mass = 0.0 @@ -31,108 +31,104 @@ def __init__(self): self.epoch = 0.0 self.t_ms = 0.0 self.sse_age = 0.0 - + def initialize_module_with_default_parameters(self, sse): metallicity = 0.02 - + neta = 0.5 - bwind = 0.0 - hewind = 0.5 - sigma = 190.0 - + bwind = 0.0 + hewind = 0.5 + sigma = 190.0 + ifflag = 0 - wdflag = 1 - bhflag = 0 - nsflag = 1 - mxns = 3.0 - + wdflag = 1 + bhflag = 0 + nsflag = 1 + mxns = 3.0 + pts1 = 0.05 pts2 = 0.01 pts3 = 0.02 - - + status = sse.initialize(metallicity, neta, bwind, hewind, sigma, ifflag, wdflag, bhflag, nsflag, mxns, pts1, pts2, pts3) - + def test1(self): sse = SSEInterface() - + metallicity = 0.02 - + neta = 0.5 - bwind = 0.0 - hewind = 0.5 - sigma = 190.0 - + bwind = 0.0 + hewind = 0.5 + sigma = 190.0 + ifflag = 0 - wdflag = 1 - bhflag = 0 - nsflag = 1 - mxns = 3.0 - + wdflag = 1 + bhflag = 0 + nsflag = 1 + mxns = 3.0 + pts1 = 0.05 pts2 = 0.01 pts3 = 0.02 - - + status = sse.initialize(metallicity, neta, bwind, hewind, sigma, ifflag, wdflag, bhflag, nsflag, mxns, pts1, pts2, pts3) - - self.assertEqual(status,0) - + + self.assertEqual(status, 0) + sse.stop() - + def test2(self): sse = SSEInterface() - + metallicity = 0.02 - + neta = 0.5 - bwind = 0.0 - hewind = 0.5 - sigma = 190.0 - + bwind = 0.0 + hewind = 0.5 + sigma = 190.0 + ifflag = 0 - wdflag = 1 - bhflag = 0 - nsflag = 1 - mxns = 3.0 - + wdflag = 1 + bhflag = 0 + nsflag = 1 + mxns = 3.0 + pts1 = 0.05 pts2 = 0.01 pts3 = 0.02 - - + status = sse.initialize(metallicity, neta, bwind, hewind, sigma, ifflag, wdflag, bhflag, nsflag, mxns, pts1, pts2, pts3) - self.assertEqual(status,0) + self.assertEqual(status, 0) new_state = self.state() new_state.mass = 1.0 new_state.zams_mass = 1.0 new_state.stellar_type = 1.0 new_state.age = 1e-06 result = sse.evolve_star( - new_state.stellar_type, - new_state.zams_mass, new_state.mass, new_state.radius, + new_state.stellar_type, + new_state.zams_mass, new_state.mass, new_state.radius, new_state.luminosity, new_state.core_mass, new_state.core_radius, new_state.envelope_mass, new_state.envelope_radius, new_state.spin, new_state.epoch, new_state.t_ms, new_state.sse_age, new_state.age ) updated_state = self.state() - (updated_state.stellar_type,updated_state.zams_mass, updated_state.mass, updated_state.radius, + (updated_state.stellar_type, updated_state.zams_mass, updated_state.mass, updated_state.radius, updated_state.luminosity, updated_state.core_mass, updated_state.core_radius, updated_state.envelope_mass, updated_state.envelope_radius, updated_state.spin, updated_state.epoch, updated_state.t_ms, updated_state.sse_age, updated_state.age) = result attributes = ('stellar_type', 'zams_mass', 'mass', 'radius', 'luminosity', 'core_mass', 'core_radius', 'envelope_mass', 'envelope_radius', 'spin', 'epoch', 't_ms', 'sse_age', 'age') - - + expected = { 'zams_mass': '0x1.0000000000000p+0', 'mass': '0x1.0000000000000p+0', @@ -147,139 +143,138 @@ def test2(self): 't_ms': '0x1.57d90abe54643p+13', 'sse_age': '0x1.0c6f7a0b5ed8dp-20', 'age': '0x1.0c6f7a0b5ed8dp-20', - }; - + } for x in expected: - self.assertAlmostRelativeEqual(float.fromhex(expected[x]),getattr(updated_state, x)) - + self.assertAlmostRelativeEqual(float.fromhex(expected[x]), getattr(updated_state, x)) + self.assertEqual(updated_state.age, 1e-06) dt = sse.get_time_step(updated_state.stellar_type, - updated_state.zams_mass, - updated_state.age, - updated_state.mass, - updated_state.t_ms, + updated_state.zams_mass, + updated_state.age, + updated_state.mass, + updated_state.t_ms, updated_state.epoch) self.assertAlmostEqual(dt, 550.1565, 2) sse.stop() - + def test3(self): sse = SSEInterface() - self.initialize_module_with_default_parameters(sse) - types = [1,1,1] - masses = [10,5,4] + self.initialize_module_with_default_parameters(sse) + types = [1, 1, 1] + masses = [10, 5, 4] radii = [5.0, 2.0, 1.0] - luminosity = core_mass = core_radius = envelope_mass =\ - envelope_radius = spin = epoch = t_ms = [0.0,0.0,0.0] + luminosity = core_mass = core_radius = envelope_mass =\ + envelope_radius = spin = epoch = t_ms = [0.0, 0.0, 0.0] sse_age = age = [1e-6, 1e-06, 1e-6] result = sse.evolve_star( - types, - masses, - masses, - radii, - luminosity, - core_mass, + types, + masses, + masses, + radii, + luminosity, + core_mass, core_radius, envelope_mass, - envelope_radius, + envelope_radius, spin, - epoch, - t_ms, - sse_age, + epoch, + t_ms, + sse_age, age ) self.assertEqual(result['mass'][0], 10) self.assertEqual(result['mass'][1], 5) self.assertAlmostEqual(result['mass'][2], 4.0, 2) sse.stop() - + def test4(self): sse = SSEInterface() - self.initialize_module_with_default_parameters(sse) - types = [1 for x in range(1,4000)] - masses = [1.0 + ((x / 4000.0) * 10.0) for x in range(1,4000)] - radii = [1.0 for x in range(1,4000)] - luminosity = core_mass = core_radius = envelope_mass =\ - envelope_radius = spin = epoch =\ - t_ms = [0.0 for x in range(1,4000)] - - sse_age = age = [1e-06 for x in range(1,4000)] + self.initialize_module_with_default_parameters(sse) + types = [1 for x in range(1, 4000)] + masses = [1.0 + ((x / 4000.0) * 10.0) for x in range(1, 4000)] + radii = [1.0 for x in range(1, 4000)] + luminosity = core_mass = core_radius = envelope_mass =\ + envelope_radius = spin = epoch =\ + t_ms = [0.0 for x in range(1, 4000)] + + sse_age = age = [1e-06 for x in range(1, 4000)] result = sse.evolve_star( - types, - masses, - masses, - radii, - luminosity, - core_mass, + types, + masses, + masses, + radii, + luminosity, + core_mass, core_radius, envelope_mass, - envelope_radius, + envelope_radius, spin, - epoch, - t_ms, - sse_age, + epoch, + t_ms, + sse_age, age ) self.assertEqual(len(result['mass']), 3999) sse.stop() - + class TestSSE(TestWithMPI): - + def test1(self): sse = SSE() - sse.commit_parameters() + sse.commit_parameters() stars = Particles(1) star = stars[0] star.mass = 5 | units.MSun star.radius = 0.0 | units.RSun - + sse.particles.add_particles(stars) from_sse_to_model = sse.particles.new_channel_to(stars) from_sse_to_model.copy() - + previous_type = star.stellar_type results = [] t0 = 0 | units.Myr current_time = t0 - + while current_time < (125 | units.Myr): sse.update_time_steps() - + current_time = current_time + sse.particles[0].time_step - + sse.evolve_model(current_time) from_sse_to_model.copy() - + if not star.stellar_type == previous_type: results.append((star.age, star.mass, star.stellar_type)) previous_type = star.stellar_type - + self.assertEqual(len(results), 6) - - times = ( - 104.0 | units.Myr, - 104.4 | units.Myr, - 104.7 | units.Myr, + + times = ( + 104.0 | units.Myr, + 104.4 | units.Myr, + 104.7 | units.Myr, 120.1 | units.Myr, 120.9 | units.Myr, 121.5 | units.Myr ) for result, expected in zip(results, times): self.assertAlmostEqual(result[0].value_in(units.Myr), expected.value_in(units.Myr), 1) - - masses = ( - 5.000 | units.MSun, - 5.000 | units.MSun, - 4.998 | units.MSun, + + masses = ( + 5.000 | units.MSun, + 5.000 | units.MSun, + 4.998 | units.MSun, 4.932 | units.MSun, 4.895 | units.MSun, 0.997 | units.MSun ) for result, expected in zip(results, masses): self.assertAlmostEqual(result[1].value_in(units.MSun), expected.value_in(units.MSun), 3) - + types = ( "Hertzsprung Gap", "First Giant Branch", @@ -288,83 +283,80 @@ def test1(self): "Second Asymptotic Giant Branch", "Carbon/Oxygen White Dwarf", ) - + for result, expected in zip(results, types): self.assertEqual(str(result[2]), expected) - + sse.stop() - + def test2(self): sse = SSE() - sse.commit_parameters() + sse.commit_parameters() stars = Particles(1) - + star = stars[0] star.mass = 5 | units.MSun star.radius = 0.0 | units.RSun - + sse.particles.add_particles(stars) sse.evolve_model(120.1 | units.Myr) - + self.assertAlmostEqual(sse.particles[0].mass.value_in(units.MSun), 4.932, 3) self.assertAlmostEqual(sse.particles[0].temperature.value_in(units.K), 4221., 0) - + sse.stop() - - + def test3(self): sse = SSE() - sse.commit_parameters() + sse.commit_parameters() stars = Particles(1) - + star = stars[0] star.mass = 5 | units.MSun star.radius = 0.0 | units.RSun - + stars.synchronize_to(sse.particles) - + channel = sse.particles.new_channel_to(stars) - channel.copy_attributes(sse.particles.get_attribute_names_defined_in_store()) - + channel.copy_attributes(sse.particles.get_attribute_names_defined_in_store()) + previous_type = sse.particles.stellar_type results = [] - + sse.evolve_model(121.5 | units.Myr) - - channel.copy_attributes(sse.particles.get_attribute_names_defined_in_store()) - + + channel.copy_attributes(sse.particles.get_attribute_names_defined_in_store()) + self.assertAlmostEqual(star.mass.value_in(units.MSun), 0.997, 3) - + sse.stop() - - + def test5(self): sse = SSE() - sse.commit_parameters() + sse.commit_parameters() stars = Particles(1) - + star = stars[0] star.mass = 35 | units.MSun star.radius = 0.0 | units.RSun - + stars.synchronize_to(sse.particles) - + channel = sse.particles.new_channel_to(stars) - channel.copy_attributes(sse.particles.get_attribute_names_defined_in_store()) - + channel.copy_attributes(sse.particles.get_attribute_names_defined_in_store()) + previous_type = star.stellar_type results = [] - + dt = 1 | units.Myr t = 0 | units.Myr while t < 30 | units.Myr: t += dt sse.evolve_model(t) - + self.assertTrue(sse.particles[0].mass.value_in(units.MSun) < 10.6) - - sse.stop() + sse.stop() def test6(self): print("Test whether a set of stars evolves synchronously...") @@ -376,16 +368,16 @@ def test6(self): # Initialize stellar evolution code instance = SSE() - instance.commit_parameters() + instance.commit_parameters() instance.particles.add_particles(stars) instance.commit_particles() - + from_code_to_model = instance.particles.new_channel_to(stars) from_code_to_model.copy() - - instance.evolve_model(end_time = 125 | units.Myr) + + instance.evolve_model(end_time=125 | units.Myr) from_code_to_model.copy() - + end_types = ( "deeply or fully convective low mass MS star", "Main Sequence star", @@ -399,7 +391,7 @@ def test6(self): self.assertTrue(stars[i].mass <= masses[i]) self.assertEqual(str(stars[i].stellar_type), end_types[i]) instance.stop() - + def test7(self): print("Test: evolve particles one at a time.") print("Used to be problematic, since initial_mass of idle particle is set to zero.") @@ -418,7 +410,7 @@ def test7(self): self.assertEqual(stars[0].luminosity, stars[1].luminosity) self.assertEqual(stars[0].age, stars[1].age) print("Solved: SSE_muse_interface.f sets initial_mass to mass when necessary.") - + def test8(self): instance = SSE() self.assertEqual(instance.parameters.reimers_mass_loss_coefficient, 0.5) @@ -428,7 +420,7 @@ def test8(self): instance.commit_parameters() self.assertEqual(instance.parameters.reimers_mass_loss_coefficient, myvalue) instance.stop() - + instance = SSE() self.assertEqual(instance.parameters.reimers_mass_loss_coefficient, 0.5) myvalue = 0.7 @@ -437,7 +429,7 @@ def test8(self): instance.commit_parameters() self.assertEqual(instance.parameters.reimers_mass_loss_coefficient, 0.5) instance.stop() - + def test9(self): print("Test: large number of particles") stellar_evolution = SSE(max_message_length=500) @@ -450,7 +442,6 @@ def test9(self): stellar_evolution.particles.add_particles(stars) self.assertEqual(len(stellar_evolution.particles), number_of_particles) stellar_evolution.stop() - def test10(self): stellar_evolution = SSE() @@ -459,17 +450,17 @@ def test10(self): stars.mass = 1.0 | units.MSun stellar_evolution.particles.add_particles(stars) self.assertEqual(stellar_evolution.particles._factory_for_new_collection(), Particles) - + filename = os.path.join(get_path_to_results(), "test.h5") if os.path.exists(filename): os.remove(filename) - + io.write_set_to_file(stellar_evolution.particles, filename, 'hdf5') stored_stars = io.read_set_from_file(filename, 'hdf5') self.assertEqual(len(stars), len(stored_stars)) - + self.assertAlmostRelativeEquals(stars.mass, stored_stars.mass) - + def test11(self): print("Test evolve_model optional arguments: end_time and keep_synchronous") stars = Particles(3) @@ -477,68 +468,68 @@ def test11(self): instance = SSE() instance.commit_parameters() instance.particles.add_particles(stars) - + self.assertEqual(instance.particles.age, [0.0, 0.0, 0.0] | units.yr) self.assertAlmostEqual(instance.particles.time_step, [550.1565, 58.2081, 18.8768] | units.Myr, 3) self.assertAlmostEqual(instance.particles.radius, [0.8882494502, 1.610210385, 1.979134445] | units.RSun) - + print("evolve_model without arguments: use shared timestep = min(particles.time_step)") instance.evolve_model() self.assertAlmostEqual(instance.particles.age, [18.8768, 18.8768, 18.8768] | units.Myr, 3) self.assertAlmostEqual(instance.particles.time_step, [550.1565, 58.2081, 18.8768] | units.Myr, 3) self.assertAlmostEqual(instance.model_time, 18.8768 | units.Myr, 3) - + print("evolve_model with end_time: take timesteps, until end_time is reached exactly") instance.evolve_model(100 | units.Myr) self.assertAlmostEqual(instance.particles.age, [100.0, 100.0, 100.0] | units.Myr, 3) self.assertAlmostEqual(instance.particles.time_step, [550.1565, 58.2081, 18.8768] | units.Myr, 3) self.assertAlmostEqual(instance.model_time, 100.0 | units.Myr, 3) - + print("evolve_model with keep_synchronous: use non-shared timestep, particle ages will typically diverge") - instance.evolve_model(keep_synchronous = False) + instance.evolve_model(keep_synchronous=False) self.assertAlmostEqual(instance.particles.age, (100 | units.Myr) + ([550.1565, 58.2081, 18.8768] | units.Myr), 3) self.assertAlmostEqual(instance.particles.time_step, [550.1565, 58.2081, 18.8768] | units.Myr, 3) - self.assertAlmostEqual(instance.model_time, 100.0 | units.Myr, 3) # Unchanged! + self.assertAlmostEqual(instance.model_time, 100.0 | units.Myr, 3) # Unchanged! instance.stop() - + def test12(self): print("Testing adding and removing particles from stellar evolution code...") - + particles = Particles(3) particles.mass = 1.0 | units.MSun - + instance = SSE() instance.initialize_code() instance.commit_parameters() - self.assertEqual(len(instance.particles), 0) # before creation + self.assertEqual(len(instance.particles), 0) # before creation instance.particles.add_particles(particles[:-1]) instance.commit_particles() instance.evolve_model(1.0 | units.Myr) - self.assertEqual(len(instance.particles), 2) # before remove + self.assertEqual(len(instance.particles), 2) # before remove self.assertAlmostEqual(instance.particles.age, 1.0 | units.Myr) - + instance.particles.remove_particle(particles[0]) self.assertEqual(len(instance.particles), 1) instance.evolve_model(2.0 | units.Myr) self.assertAlmostEqual(instance.particles[0].age, 2.0 | units.Myr) - + instance.particles.add_particles(particles[::2]) - self.assertEqual(len(instance.particles), 3) # it's back... + self.assertEqual(len(instance.particles), 3) # it's back... self.assertAlmostEqual(instance.particles[0].age, 2.0 | units.Myr) self.assertAlmostEqual(instance.particles[1].age, 0.0 | units.Myr) - self.assertAlmostEqual(instance.particles[2].age, 0.0 | units.Myr) # ... and rejuvenated. - - instance.evolve_model(3.0 | units.Myr) # The young stars keep their age offset from the old star + self.assertAlmostEqual(instance.particles[2].age, 0.0 | units.Myr) # ... and rejuvenated. + + instance.evolve_model(3.0 | units.Myr) # The young stars keep their age offset from the old star self.assertAlmostEqual(instance.particles.age, [3.0, 1.0, 1.0] | units.Myr) instance.evolve_model(4.0 | units.Myr) self.assertAlmostEqual(instance.particles.age, [4.0, 2.0, 2.0] | units.Myr) instance.stop() - + def test13(self): print("Testing SSE states") stars = Particles(1) stars.mass = 1.0 | units.MSun - + print("First do everything manually:", end=' ') instance = SSE() self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') @@ -551,7 +542,7 @@ def test13(self): instance.stop() print("ok") - print("initialize_code(), commit_parameters(), " \ + print("initialize_code(), commit_parameters(), " "and cleanup_code() should be called automatically:", end=' ') instance = SSE() self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED') @@ -570,7 +561,7 @@ def test14a(self): instance = SSE() se_stars = instance.particles.add_particles(stars) self.assertAlmostEqual(se_stars.age, [0.0, 0.0] | units.yr) - + for i in range(3): se_stars[0].evolve_one_step() self.assertAlmostEqual(se_stars.age, [1650.46953688, 0.0] | units.Myr, 3) @@ -584,7 +575,7 @@ def test14a(self): self.assertAlmostRelativeEqual(se_stars[0].radius, se_stars[1].radius, 3) self.assertAlmostRelativeEqual(se_stars[0].temperature, se_stars[1].temperature, 3) instance.stop() - + def test14b(self): print("Testing basic operations: evolve_one_step and evolve_for (on subset)") stars = Particles(2) @@ -592,7 +583,7 @@ def test14b(self): instance = SSE() se_stars = instance.particles.add_particles(stars) self.assertAlmostEqual(se_stars.age, [0.0, 0.0] | units.yr) - + for i in range(3): se_stars[:1].evolve_one_step() self.assertAlmostEqual(se_stars.age, [1650.46953688, 0.0] | units.Myr, 3) @@ -606,65 +597,67 @@ def test14b(self): self.assertAlmostRelativeEqual(se_stars[0].radius, se_stars[1].radius, 3) self.assertAlmostRelativeEqual(se_stars[0].temperature, se_stars[1].temperature, 3) instance.stop() - + def test15(self): print("test evolution of 1000 star sampled over flattish IMF") - - number_of_stars=1000 - + + number_of_stars = 1000 + class notsorandom(object): - def random(self,N): + def random(self, N): return numpy.array(range(N))/(N-1.) - def random_sample(self,N): + + def random_sample(self, N): return numpy.array(range(N))/(N-1.) masses = new_salpeter_mass_distribution( - number_of_stars, - mass_min = 0.1 | units.MSun, - mass_max = 100.0 | units.MSun, - alpha = -1.01,random=notsorandom() + number_of_stars, + mass_min=0.1 | units.MSun, + mass_max=100.0 | units.MSun, + alpha=-1.01, random=notsorandom() ) - - stars=Particles(mass=masses) - instance=SSE() + stars = Particles(mass=masses) + + instance = SSE() instance.particles.add_particles(stars) - - i=0 + + i = 0 for p in instance.particles: - p.evolve_for(0.1 | units.Myr) - i+=1 + p.evolve_for(0.1 | units.Myr) + i += 1 instance.stop() def test16(self): print("test evolution of 1000 star sampled over flattish IMF") - - number_of_stars=1000 - + + number_of_stars = 1000 + class notsorandom(object): - def random(self,N): + def random(self, N): return numpy.array(range(N))/(N-1.) - def random_sample(self,N): + + def random_sample(self, N): return numpy.array(range(N))/(N-1.) masses = new_salpeter_mass_distribution( - number_of_stars, - mass_min = 0.1 | units.MSun, - mass_max = 100.0 | units.MSun, - alpha = -1.01,random=notsorandom() + number_of_stars, + mass_min=0.1 | units.MSun, + mass_max=100.0 | units.MSun, + alpha=-1.01, random=notsorandom() ) - - stars=Particles(mass=masses) - instance=SSE() + stars = Particles(mass=masses) + + instance = SSE() instance.particles.add_particles(stars) - - i=0 + + i = 0 for p in instance.particles: - p.evolve_for(13.2 | units.Gyr) - i+=1 + p.evolve_for(13.2 | units.Gyr) + i += 1 instance.stop() - + def test17(self): print("evolve_one_step and evolve_for after particle removal and addition") particles = Particles(10) @@ -676,15 +669,15 @@ def test17(self): for i in range(10): instance.particles[i].evolve_for(time_steps[i]) self.assertAlmostEqual(instance.particles.age, time_steps) - + instance.particles.remove_particles(particles[[1, 4, 8]]) revived = instance.particles.add_particle(particles[4]) revived.evolve_for(numpy.pi | units.Myr) for star in instance.particles: star.evolve_for(star.age) - self.assertAlmostEqual(instance.particles.age[:-1], 2*time_steps[[0, 2,3, 5,6,7, 9]]) + self.assertAlmostEqual(instance.particles.age[:-1], 2*time_steps[[0, 2, 3, 5, 6, 7, 9]]) self.assertAlmostEqual(instance.particles.age[-1], 2*numpy.pi | units.Myr) - + instance.particles.remove_particles(particles[[2, 5, 6]]) instance.particles.add_particles(particles[[8, 1]]) self.assertEqual(len(instance.particles), 7) @@ -693,28 +686,29 @@ def test17(self): star.evolve_one_step() self.assertAlmostEqual(instance.particles.age, expected_ages) instance.stop() - + def test18(self): print("SSE validation") sse_src_path = os.path.join(os.path.dirname(sys.modules[SSE.__module__].__file__), 'src') if not os.path.exists(os.path.join(sse_src_path, "evolve.in")): self.skip("Not in a source release") instance = SSE() - instance.particles.add_particle(Particle(mass = 1.416 | units.MSun)) + instance.particles.add_particle(Particle(mass=1.416 | units.MSun)) instance.particles[0].evolve_for(7000.0 | units.Myr) evolved_star = instance.particles.copy()[0] - evolved_star.temperature = instance.particles[0].temperature + # See issue #957 + # evolved_star.temperature = instance.particles[0].temperature instance.stop() - + testpath = get_path_to_results() shutil.copy(os.path.join(sse_src_path, "evolve.in"), os.path.join(testpath, "evolve.in")) - + call([os.path.join(sse_src_path, "sse")], cwd=testpath) - + with open(os.path.join(testpath, "evolve.dat"), "r") as sse_output: lines = sse_output.readlines() sse_final_result = lines[-2].split() - + self.assertAlmostEqual(evolved_star.age, float(sse_final_result[0]) | units.Myr, 3) self.assertAlmostEqual(evolved_star.stellar_type, float(sse_final_result[1]) | units.stellar_type, 3) self.assertAlmostEqual(evolved_star.initial_mass, float(sse_final_result[2]) | units.MSun, 3) @@ -726,11 +720,11 @@ def test18(self): self.assertAlmostEqual(evolved_star.convective_envelope_mass, float(sse_final_result[8]) | units.MSun, 3) self.assertAlmostEqual(evolved_star.epoch, float(sse_final_result[9]) | units.Myr, 3) self.assertAlmostEqual(evolved_star.spin, float(sse_final_result[10]) | units.yr**-1, 3) - + def test19(self): print("SSE core_mass and CO_core_mass (high mass star)") instance = SSE() - star = instance.particles.add_particle(Particle(mass = 30 | units.MSun)) + star = instance.particles.add_particle(Particle(mass=30 | units.MSun)) instance.evolve_model(5.8 | units.Myr) print(star.mass, star.core_mass, star.CO_core_mass, star.stellar_type) self.assertEqual(str(star.stellar_type), "Main Sequence star") @@ -762,11 +756,11 @@ def test19(self): self.assertEqual(star.core_mass, star.mass) self.assertEqual(star.CO_core_mass, star.mass) instance.stop() - + def test20(self): print("SSE core_mass and CO_core_mass (low mass stars)") instance = SSE() - stars = instance.particles.add_particles(Particles(mass = [0.6, 1.0] | units.MSun)) + stars = instance.particles.add_particles(Particles(mass=[0.6, 1.0] | units.MSun)) instance.evolve_model(100 | units.Gyr) self.assertEqual(str(stars[0].stellar_type), "Helium White Dwarf") self.assertAlmostEqual(stars[0].mass, 0.405 | units.MSun, 2) @@ -777,23 +771,22 @@ def test20(self): self.assertEqual(stars[1].core_mass, stars[1].mass) self.assertEqual(stars[1].CO_core_mass, stars[1].mass) instance.stop() - def test21(self): instance = SSE() - stars = instance.particles.add_particles(Particles(mass = 30 | units.MSun)) + stars = instance.particles.add_particles(Particles(mass=30 | units.MSun)) mass_loss_wind = stars[0].mass_loss_wind self.assertAlmostRelativeEquals(mass_loss_wind, 1.703e-07 | units.MSun / units.yr, 3) instance.evolve_model(1 | units.Myr) - dm = (1 | units.Myr)* mass_loss_wind - self.assertAlmostRelativeEquals(stars[0].mass, (30 | units.MSun) - dm , 3) + dm = (1 | units.Myr) * mass_loss_wind + self.assertAlmostRelativeEquals(stars[0].mass, (30 | units.MSun) - dm, 3) self.assertAlmostRelativeEquals(stars[0].mass_loss_wind, 2.053e-07 | units.MSun / units.yr, 3) - + instance.stop() - + def test22(self): instance = SSE() - stars = instance.particles.add_particles(Particles(mass = [1.0, 10.0] | units.MSun)) + stars = instance.particles.add_particles(Particles(mass=[1.0, 10.0] | units.MSun)) gyration_radius = stars.gyration_radius self.assertTrue(numpy.all(0.0 < gyration_radius)) self.assertTrue(numpy.all(gyration_radius < 1.0)) @@ -806,10 +799,9 @@ def test22(self): def test23(self): instance = SSE() - p=Particles(mass = [1.0, 10.0] | units.MSun, temperature=[10,10] | units.K) + p = Particles(mass=[1.0, 10.0] | units.MSun, temperature=[10, 10] | units.K) stars = instance.particles.add_particles(p) - channel=stars.new_channel_to(p) - channel.copy_attributes(["mass","temperature"]) + channel = stars.new_channel_to(p) + channel.copy_attributes(["mass", "temperature"]) self.assertEqual(stars.temperature, p.temperature) instance.stop() - diff --git a/src/amuse/test/suite/codes_tests/test_stellar_evolution.py b/src/amuse/test/suite/codes_tests/test_stellar_evolution.py index 99f74abb36..e3af2594ee 100644 --- a/src/amuse/test/suite/codes_tests/test_stellar_evolution.py +++ b/src/amuse/test/suite/codes_tests/test_stellar_evolution.py @@ -14,103 +14,100 @@ class _TestStellarEvolutionCodes(TestWithMPI): - + def code_factory(self): self.skip("abstract test") - + def test1(self): - instance=self.code_factory() + instance = self.code_factory() def test2(self): - for m in ([0.2,1.,5.,25.]|units.MSun): - instance=self.code_factory()() - p=datamodel.Particle(mass=m) - p2=instance.particles.add_particle(p) - self.assertAlmostEqual(p2.mass,p.mass) - self.assertTrue( hasattr(p2, "radius") ) - self.assertTrue( hasattr(p2, "luminosity") ) - self.assertTrue( hasattr(p2, "age") ) - self.assertTrue( hasattr(p2, "stellar_type") ) + for m in ([0.2, 1., 5., 25.] | units.MSun): + instance = self.code_factory()() + p = datamodel.Particle(mass=m) + p2 = instance.particles.add_particle(p) + self.assertAlmostEqual(p2.mass, p.mass) + self.assertTrue(hasattr(p2, "radius")) + self.assertTrue(hasattr(p2, "luminosity")) + self.assertTrue(hasattr(p2, "age")) + self.assertTrue(hasattr(p2, "stellar_type")) def test3(self): - instance=self.code_factory()() - p=datamodel.Particle(mass=1. | units.MSun) - p2=instance.particles.add_particle(p) - self.assertAlmostEqual(p2.mass,p.mass) - self.assertTrue( hasattr(p2, "radius") ) - self.assertTrue( hasattr(p2, "luminosity") ) - self.assertTrue( hasattr(p2, "age") ) - self.assertTrue( hasattr(p2, "stellar_type") ) - self.assertEqual( str(p2.stellar_type),"Main Sequence star") + instance = self.code_factory()() + p = datamodel.Particle(mass=1. | units.MSun) + p2 = instance.particles.add_particle(p) + self.assertAlmostEqual(p2.mass, p.mass) + self.assertTrue(hasattr(p2, "radius")) + self.assertTrue(hasattr(p2, "luminosity")) + self.assertTrue(hasattr(p2, "age")) + self.assertTrue(hasattr(p2, "stellar_type")) + self.assertEqual(str(p2.stellar_type), "Main Sequence star") def test4(self): - for m in ([0.2,1.,5.]|units.MSun): - instance=self.code_factory()() - p=datamodel.Particle(mass=m) - p2=instance.particles.add_particle(p) - self.assertAlmostEqual(p2.age, 0. | units.Myr) - instance.evolve_model(1.| units.Myr) - self.assertGreaterEqual(p2.age, (1. | units.Myr) ) - self.assertGreaterEqual(instance.model_time, (1. | units.Myr) ) - + for m in ([0.2, 1., 5.] | units.MSun): + instance = self.code_factory()() + p = datamodel.Particle(mass=m) + p2 = instance.particles.add_particle(p) + self.assertAlmostEqual(p2.age, 0. | units.Myr) + instance.evolve_model(1. | units.Myr) + self.assertGreaterEqual(p2.age, (1. | units.Myr)) + self.assertGreaterEqual(instance.model_time, (1. | units.Myr)) def test5(self): - instance=self.code_factory()() - p1=datamodel.Particle(mass=1. | units.MSun) - p2=datamodel.Particle(mass=1. | units.MSun) - p1=instance.particles.add_particle(p1) - instance.evolve_model( 1.|units.Gyr) - p2=instance.particles.add_particle(p2) - instance.evolve_model( 2.|units.Gyr) - self.assertGreaterEqual(p1.age, (1. | units.Gyr) ) - self.assertGreaterEqual(p2.age,(1. | units.Gyr) ) - self.assertLess(p2.age, (2. | units.Gyr) ) + instance = self.code_factory()() + p1 = datamodel.Particle(mass=1. | units.MSun) + p2 = datamodel.Particle(mass=1. | units.MSun) + p1 = instance.particles.add_particle(p1) + instance.evolve_model(1. | units.Gyr) + p2 = instance.particles.add_particle(p2) + instance.evolve_model(2. | units.Gyr) + self.assertGreaterEqual(p1.age, (1. | units.Gyr)) + self.assertGreaterEqual(p2.age, (1. | units.Gyr)) + self.assertLess(p2.age, (2. | units.Gyr)) def test6(self): - instance1=self.code_factory()() - p1=datamodel.Particle(mass=1. | units.MSun) - p2=datamodel.Particle(mass=1. | units.MSun) - p3=datamodel.Particle(mass=1. | units.MSun) - p1=instance1.particles.add_particle(p1) - instance1.evolve_model( 10.|units.Myr) - p2=instance1.particles.add_particle(p2) - instance1.evolve_model( 20.|units.Myr) - - instance2=self.code_factory()() - p3=instance2.particles.add_particle(p3) - instance2.evolve_model(10.|units.Myr) - - self.assertAlmostEqual(p2.mass,p3.mass) - self.assertAlmostEqual(p2.radius,p3.radius) - self.assertAlmostEqual(p2.luminosity,p3.luminosity) + instance1 = self.code_factory()() + p1 = datamodel.Particle(mass=1. | units.MSun) + p2 = datamodel.Particle(mass=1. | units.MSun) + p3 = datamodel.Particle(mass=1. | units.MSun) + p1 = instance1.particles.add_particle(p1) + instance1.evolve_model(10. | units.Myr) + p2 = instance1.particles.add_particle(p2) + instance1.evolve_model(20. | units.Myr) + + instance2 = self.code_factory()() + p3 = instance2.particles.add_particle(p3) + instance2.evolve_model(10. | units.Myr) + + self.assertAlmostEqual(p2.mass, p3.mass) + self.assertAlmostEqual(p2.radius, p3.radius) + self.assertAlmostEqual(p2.luminosity, p3.luminosity) def test7(self): - instance1=self.code_factory()() - instance2=self.code_factory()() - p1=datamodel.Particle(mass=1. | units.MSun) - p1=instance1.particles.add_particle(p1) + instance1 = self.code_factory()() + instance2 = self.code_factory()() + p1 = datamodel.Particle(mass=1. | units.MSun) + p1 = instance1.particles.add_particle(p1) p1.evolve_one_step() - p2=datamodel.Particle(mass=1. | units.MSun) - p2=instance2.particles.add_particle(p2) - instance2.evolve_model( p1.age) - self.assertAlmostEqual(p1.mass,p2.mass) - self.assertAlmostEqual(p1.radius,p2.radius) - self.assertAlmostEqual(p1.luminosity,p2.luminosity) + p2 = datamodel.Particle(mass=1. | units.MSun) + p2 = instance2.particles.add_particle(p2) + instance2.evolve_model(p1.age) + self.assertAlmostEqual(p1.mass, p2.mass) + self.assertAlmostEqual(p1.radius, p2.radius) + self.assertAlmostEqual(p1.luminosity, p2.luminosity) def test8(self): - instance1=self.code_factory()() - instance2=self.code_factory()() - p1=datamodel.Particle(mass=1. | units.MSun) - p1=instance1.particles.add_particle(p1) + instance1 = self.code_factory()() + instance2 = self.code_factory()() + p1 = datamodel.Particle(mass=1. | units.MSun) + p1 = instance1.particles.add_particle(p1) p1.evolve_for(10. | units.Myr) - p2=datamodel.Particle(mass=1. | units.MSun) - p2=instance2.particles.add_particle(p2) - instance2.evolve_model( 10.|units.Myr) - self.assertAlmostEqual(p1.mass,p2.mass) - self.assertAlmostEqual(p1.radius,p2.radius) - self.assertAlmostEqual(p1.luminosity,p2.luminosity) - - + p2 = datamodel.Particle(mass=1. | units.MSun) + p2 = instance2.particles.add_particle(p2) + instance2.evolve_model(10. | units.Myr) + self.assertAlmostEqual(p1.mass, p2.mass) + self.assertAlmostEqual(p1.radius, p2.radius) + self.assertAlmostEqual(p1.luminosity, p2.luminosity) """ @@ -140,14 +137,16 @@ def test7(self): self.assertalmostEqual( p1.mass,p2.mass) """ + class TestSSECode(_TestStellarEvolutionCodes): def code_factory(self): return SSE -#class xTestBSECode(_TestStellarEvolutionCodes): +# class xTestBSECode(_TestStellarEvolutionCodes): # def code_factory(self): # return BSE + class TestMESACode(_TestStellarEvolutionCodes): def code_factory(self): try: @@ -156,12 +155,12 @@ def code_factory(self): self.skip("Tried to instantiate a new object of the optional code with type '{0}', but this code is not available".format(MESA)) return MESA + class TestSeBaCode(_TestStellarEvolutionCodes): def code_factory(self): return SeBa + class TestEVtwinCode(_TestStellarEvolutionCodes): def code_factory(self): return EVtwin - - diff --git a/src/amuse/test/suite/codes_tests/test_tupan.py b/src/amuse/test/suite/codes_tests/test_tupan.py index ed8d98797e..41d40b8d84 100644 --- a/src/amuse/test/suite/codes_tests/test_tupan.py +++ b/src/amuse/test/suite/codes_tests/test_tupan.py @@ -32,10 +32,10 @@ def test02(self): self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) - id, error = instance.new_particle(mass = 11.0, radius = 2.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) + id, error = instance.new_particle(mass=11.0, radius=2.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) self.assertEqual(0, error) self.assertEqual(0, id) - id, error = instance.new_particle(mass = 21.0, radius = 5.0, x = 10.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) + id, error = instance.new_particle(mass=21.0, radius=5.0, x=10.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) self.assertEqual(0, error) self.assertEqual(1, id) self.assertEqual(0, instance.commit_particles()) @@ -46,7 +46,7 @@ def test02(self): self.assertEqual(0, retrieved_state2['__result']) self.assertEqual(11.0, retrieved_state1['mass']) self.assertEqual(21.0, retrieved_state2['mass']) - self.assertEqual( 0.0, retrieved_state1['x']) + self.assertEqual(0.0, retrieved_state1['x']) self.assertEqual(10.0, retrieved_state2['x']) self.assertEqual(0, instance.cleanup_code()) @@ -60,34 +60,34 @@ def test03(self): self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) self.assertEqual([0, 0], list(instance.new_particle(0.01, 1, 0, 0, 0, 1, 0, 0.1).values())) - self.assertEqual([1, 0], list(instance.new_particle(0.02, -1, 0, 0, 0,-1, 0, 0.1).values())) + self.assertEqual([1, 0], list(instance.new_particle(0.02, -1, 0, 0, 0, -1, 0, 0.1).values())) #### self.assertEquals(-1, instance.get_mass(1)['__result']) # Have to commit first self.assertEqual(0, instance.commit_particles()) # getters mass, result = instance.get_mass(0) self.assertAlmostEqual(0.01, mass) - self.assertEqual(0,result) + self.assertEqual(0, result) radius, result = instance.get_radius(1) self.assertAlmostEqual(0.1, radius) - self.assertEqual(0,result) - self.assertEqual(-1, instance.get_mass(2)['__result']) # Particle not found - self.assertEqual([ 1, 0, 0, 0], list(instance.get_position(0).values())) + self.assertEqual(0, result) + self.assertEqual(-1, instance.get_mass(2)['__result']) # Particle not found + self.assertEqual([1, 0, 0, 0], list(instance.get_position(0).values())) self.assertEqual([-1, 0, 0, 0], list(instance.get_position(1).values())) - self.assertEqual([ 0, 1, 0, 0], list(instance.get_velocity(0).values())) - self.assertEqual([ 0,-1, 0, 0], list(instance.get_velocity(1).values())) + self.assertEqual([0, 1, 0, 0], list(instance.get_velocity(0).values())) + self.assertEqual([0, -1, 0, 0], list(instance.get_velocity(1).values())) # setters - self.assertEqual(0, instance.set_state(0, 0.01, 1,2,3, 4,5,6, 0.1)) - self.assertEqual([0.01, 1.0,2.0,3.0, 4.0,5.0,6.0, 0.1, 0], list(instance.get_state(0).values())) + self.assertEqual(0, instance.set_state(0, 0.01, 1, 2, 3, 4, 5, 6, 0.1)) + self.assertEqual([0.01, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.1, 0], list(instance.get_state(0).values())) self.assertEqual(0, instance.set_mass(0, 0.02)) - self.assertEqual([0.02, 1.0,2.0,3.0, 4.0,5.0,6.0, 0.1, 0], list(instance.get_state(0).values())) + self.assertEqual([0.02, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.1, 0], list(instance.get_state(0).values())) self.assertEqual(0, instance.set_radius(0, 0.2)) - self.assertEqual([0.02, 1.0,2.0,3.0, 4.0,5.0,6.0, 0.2, 0], list(instance.get_state(0).values())) - self.assertEqual(0, instance.set_position(0, 10,20,30)) - self.assertEqual([0.02, 10.0,20.0,30.0, 4.0,5.0,6.0, 0.2, 0], list(instance.get_state(0).values())) - self.assertEqual(0, instance.set_velocity(0, 40,50,60)) - self.assertEqual([0.02, 10.0,20.0,30.0, 40.0,50.0,60.0, 0.2, 0], list(instance.get_state(0).values())) + self.assertEqual([0.02, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.2, 0], list(instance.get_state(0).values())) + self.assertEqual(0, instance.set_position(0, 10, 20, 30)) + self.assertEqual([0.02, 10.0, 20.0, 30.0, 4.0, 5.0, 6.0, 0.2, 0], list(instance.get_state(0).values())) + self.assertEqual(0, instance.set_velocity(0, 40, 50, 60)) + self.assertEqual([0.02, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 0.2, 0], list(instance.get_state(0).values())) self.assertEqual(0, instance.cleanup_code()) instance.stop() @@ -135,15 +135,15 @@ def test05(self): self.assertEqual(0, instance.commit_parameters()) self.assertEqual([0, 0], list(instance.new_particle(0.5, 0.5, 0, 0, 0, 0.5, 0, 0.001).values())) - self.assertEqual([1, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0,-0.5, 0, 0.001).values())) + self.assertEqual([1, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0, -0.5, 0, 0.001).values())) self.assertEqual(0, instance.commit_particles()) P = 2 * math.pi - self.assertEqual(0, instance.evolve_model(P / 2)) # half an orbit + self.assertEqual(0, instance.evolve_model(P / 2)) # half an orbit for result, expected in zip(instance.get_position(0).values(), [-0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 2) - self.assertEqual(0, instance.evolve_model(P)) # full orbit + self.assertEqual(0, instance.evolve_model(P)) # full orbit for result, expected in zip(instance.get_position(0).values(), [0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 2) @@ -151,7 +151,6 @@ def test05(self): instance.stop() - class TestTupan(TestWithMPI): default_converter = nbody_system.nbody_to_si(1.0e4 | units.MSun, 1.0 | units.AU) @@ -356,8 +355,8 @@ def test07(self): tan_initial_direction = particles[1].vy/particles[1].vx self.assertAlmostEqual(tan_initial_direction, math.tan(math.pi/4)) - tan_final_direction = [] - for log_eps2 in range(-9,10,2): + tan_final_direction = [] + for log_eps2 in range(-9, 10, 2): instance = self.new_instance_of_an_optional_code(Tupan, converter) instance.initialize_code() instance.parameters.epsilon_squared = 10.0**log_eps2 | units.AU ** 2 @@ -366,7 +365,7 @@ def test07(self): instance.particles.add_particles(particles) instance.commit_particles() instance.evolve_model(0.25 | units.yr) - tan_final_direction.append(instance.particles[1].velocity[1]/ + tan_final_direction.append(instance.particles[1].velocity[1] / instance.particles[1].velocity[0]) instance.cleanup_code() instance.stop() @@ -376,7 +375,7 @@ def test07(self): self.assertAlmostEqual(tan_final_direction[-1], tan_initial_direction, 2) # Outcome is most sensitive to epsilon_squared when epsilon_squared = d(earth, sun)^2 delta = [abs(tan_final_direction[i+1]-tan_final_direction[i]) for i in range(len(tan_final_direction)-1)] - self.assertEqual(delta[len(tan_final_direction)/2 -1], max(delta)) + self.assertEqual(delta[len(tan_final_direction)/2 - 1], max(delta)) def xtest08(self): if MODULES_MISSING: @@ -389,8 +388,8 @@ def xtest08(self): particles = Particles(2) particles.mass = 1.0 | nbody_system.mass - particles.radius = 0.0 | nbody_system.length - particles.position = [[0.0,0.0,0.0], [2.0,0.0,0.0]] | nbody_system.length + particles.radius = 0.0 | nbody_system.length + particles.position = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]] | nbody_system.length particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed instance.particles.add_particles(particles) @@ -544,4 +543,3 @@ def test11(self): instance.cleanup_code() instance.stop() - diff --git a/src/amuse/test/suite/codes_tests/test_twobody.py b/src/amuse/test/suite/codes_tests/test_twobody.py index e9f689034e..301f70b05e 100644 --- a/src/amuse/test/suite/codes_tests/test_twobody.py +++ b/src/amuse/test/suite/codes_tests/test_twobody.py @@ -9,23 +9,25 @@ from amuse.support.exceptions import AmuseException from amuse import datamodel + class TwoBodyCodeTests(TestWithMPI): - + def test_stumpff(self): - self.assertAlmostEqual(interface.stumpff_C(0),interface.stumpff_C(0.0001),5) - self.assertAlmostEqual(interface.stumpff_C(0),interface.stumpff_C(-0.0001),5) - self.assertAlmostEqual(interface.stumpff_S(0),interface.stumpff_S(0.0001),5) - self.assertAlmostEqual(interface.stumpff_S(0),interface.stumpff_S(-0.0001),5) + self.assertAlmostEqual(interface.stumpff_C(0), interface.stumpff_C(0.0001), 5) + self.assertAlmostEqual(interface.stumpff_C(0), interface.stumpff_C(-0.0001), 5) + self.assertAlmostEqual(interface.stumpff_S(0), interface.stumpff_S(0.0001), 5) + self.assertAlmostEqual(interface.stumpff_S(0), interface.stumpff_S(-0.0001), 5) + class TwoBodyInterfaceTests(TestWithMPI): - + def test1(self): - + instance = interface.TwoBodyInterface() - - res1 = instance.new_particle(mass = 11.0, radius = 2.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) - res2 = instance.new_particle(mass = 21.0, radius = 5.0, x = 10.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) - + + res1 = instance.new_particle(mass=11.0, radius=2.0, x=0.0, y=0.0, z=0.0, vx=0.0, vy=0.0, vz=0.0) + res2 = instance.new_particle(mass=21.0, radius=5.0, x=10.0, y=0.0, z=0.0, vx=10.0, vy=0.0, vz=0.0) + self.assertEqual(0, res1['index_of_the_particle']) self.assertEqual(1, res2['index_of_the_particle']) @@ -38,106 +40,104 @@ def test1(self): self.assertEqual(10.0, retrieved_state2['x']) instance.stop() - + def test2(self): - + instance = interface.TwoBodyInterface() - - res1 = instance.new_particle(mass = 10.0, radius = 0.0, x = -1.0, y = 0.0, z = 0.0, vx = 0.0, vy = 10.0, vz = 0.0) - res2 = instance.new_particle(mass = 10.0, radius = 0.0, x = 1.0, y = 0.0, z = 0.0, vx = 0.0, vy = -10.0, vz = 0.0) - - ek=0.5*(10*100+10*100) - ep=-(10*10/2) - - e,err=instance.get_kinetic_energy() - self.assertEqual(ek,e) - - e,err=instance.get_potential_energy() - self.assertEqual(ep,e) + + res1 = instance.new_particle(mass=10.0, radius=0.0, x=-1.0, y=0.0, z=0.0, vx=0.0, vy=10.0, vz=0.0) + res2 = instance.new_particle(mass=10.0, radius=0.0, x=1.0, y=0.0, z=0.0, vx=0.0, vy=-10.0, vz=0.0) + + ek = 0.5*(10*100+10*100) + ep = -(10*10/2) + + e, err = instance.get_kinetic_energy() + self.assertEqual(ek, e) + + e, err = instance.get_potential_energy() + self.assertEqual(ep, e) instance.stop() - class TwoBodyTests(TestWithMPI): - + def test1(self): - convert_nbody = nbody_system.nbody_to_si(5.9742e24 | units.kg, 1e6| units.m) + convert_nbody = nbody_system.nbody_to_si(5.9742e24 | units.kg, 1e6 | units.m) instance = interface.TwoBody(convert_nbody) instance.stop() - + def test2(self): - convert_nbody = nbody_system.nbody_to_si(5.9742e24 | units.kg, 1e6| units.m) + convert_nbody = nbody_system.nbody_to_si(5.9742e24 | units.kg, 1e6 | units.m) instance = interface.TwoBody(convert_nbody) - + p = datamodel.Particle() p.mass = 5.9742e24 | units.kg p.radius = 6.371e6 | units.m - p.position = [0.,7.e6,-1.2124e7] | units.m - p.velocity = [0.,2.6679e3,4.6210e3] | units.m/units.s - + p.position = [0., 7.e6, -1.2124e7] | units.m + p.velocity = [0., 2.6679e3, 4.6210e3] | units.m/units.s + instance.particles.add_particle(p) - + instance.evolve_model(3600.0 | units.s) - + position = instance.particles[0].position velocity = instance.particles[0].velocity - - self.assertAlmostEqual(position.x.value_in(units.m),0.,7) - self.assertAlmostEqual(position.y.value_in(units.m)/(-3.30647600568e6),1.,7) - self.assertAlmostEqual(position.z.value_in(units.m)/7.40831575351e6,1.,7) - self.assertAlmostEqual(velocity.x.value_in(units.m / units.s),0.,7) - self.assertAlmostEqual(velocity.y.value_in(units.m / units.s)/(-8.29821376206e3),1.,7) - self.assertAlmostEqual(velocity.z.value_in(units.m / units.s)/(-0.972888312209e3),1.,7) + + self.assertAlmostEqual(position.x.value_in(units.m), 0., 7) + self.assertAlmostEqual(position.y.value_in(units.m)/(-3.30647600568e6), 1., 7) + self.assertAlmostEqual(position.z.value_in(units.m)/7.40831575351e6, 1., 7) + self.assertAlmostEqual(velocity.x.value_in(units.m / units.s), 0., 7) + self.assertAlmostEqual(velocity.y.value_in(units.m / units.s)/(-8.29821376206e3), 1., 7) + self.assertAlmostEqual(velocity.z.value_in(units.m / units.s)/(-0.972888312209e3), 1., 7) instance.stop() def test3(self): - convert_nbody = nbody_system.nbody_to_si(5.9742e24 | units.kg, 1e6| units.m) + convert_nbody = nbody_system.nbody_to_si(5.9742e24 | units.kg, 1e6 | units.m) instance = interface.TwoBody(convert_nbody) - + p = datamodel.Particle() p.mass = 5.9742e24 | units.kg p.radius = 7.1e6 | units.m - p.position = [0.,7.e6,-1.2124e7] | units.m - p.velocity = [0.,2.6679e3,4.6210e3] | units.m/units.s - + p.position = [0., 7.e6, -1.2124e7] | units.m + p.velocity = [0., 2.6679e3, 4.6210e3] | units.m/units.s + instance.particles.add_particle(p) - + instance.evolve_model(3600.0 | units.s) - + dt = convert_nbody.to_si(instance.model_time) - self.assertAlmostEqual(dt.value_in(units.s)/2583.44780926,1.,7) - + self.assertAlmostEqual(dt.value_in(units.s)/2583.44780926, 1., 7) + position = instance.particles[0].position - self.assertAlmostEqual(((position.x**2+position.y**2+position.z**2)/(7.1e6)**2).value_in(units.m**2),1.,7) + self.assertAlmostEqual(((position.x**2+position.y**2+position.z**2)/(7.1e6)**2).value_in(units.m**2), 1., 7) instance.stop() def test4(self): - convert_nbody = nbody_system.nbody_to_si(5.9742e24 | units.kg, 1e6| units.m) + convert_nbody = nbody_system.nbody_to_si(5.9742e24 | units.kg, 1e6 | units.m) instance = interface.TwoBody(convert_nbody) - + p = datamodel.Particle() p.mass = 5.9742e24 | units.kg p.radius = 7.1e6 | units.m - p.position = [0.,7.e6,-1.2124e7] | units.m - p.velocity = [0.,2.6679e3,4.6210e3] | units.m/units.s - + p.position = [0., 7.e6, -1.2124e7] | units.m + p.velocity = [0., 2.6679e3, 4.6210e3] | units.m/units.s + instance.particles.add_particle(p) - + instance.evolve_model(3600.0 | units.s) - + dt = convert_nbody.to_si(instance.model_time) - - self.assertEqual(instance.particles[0].mass,5.9742e24 | units.kg) - - instance.particles[0].mass=0.8*5.9742e24 | units.kg + self.assertEqual(instance.particles[0].mass, 5.9742e24 | units.kg) + + instance.particles[0].mass = 0.8*5.9742e24 | units.kg instance.evolve_model(4000.0 | units.s) - self.assertEqual(instance.particles.mass[0],0.8*5.9742e24 | units.kg) + self.assertEqual(instance.particles.mass[0], 0.8*5.9742e24 | units.kg) instance.stop() def test5(self): - #from: Fundamentals of Celestial Mechanics, J.M.A. Danby 2nd edition + # from: Fundamentals of Celestial Mechanics, J.M.A. Danby 2nd edition instance = interface.TwoBody() p = datamodel.Particle() @@ -147,14 +147,14 @@ def test5(self): p.velocity = [-0.1, 2.0, -0.2] | nbody_system.speed instance.particles.add_particle(p) - instance.evolve_model(1.0|nbody_system.time) - self.assertAlmostEqual(instance.particles.x, 0.611238439231|nbody_system.length, 7) - self.assertAlmostEqual(instance.particles.y, 1.92873971354574|nbody_system.length, 7) - self.assertAlmostEqual(instance.particles.z, -0.2562478900031234|nbody_system.length, 7) + instance.evolve_model(1.0 | nbody_system.time) + self.assertAlmostEqual(instance.particles.x, 0.611238439231 | nbody_system.length, 7) + self.assertAlmostEqual(instance.particles.y, 1.92873971354574 | nbody_system.length, 7) + self.assertAlmostEqual(instance.particles.z, -0.2562478900031234 | nbody_system.length, 7) instance.stop() def test6(self): - #from: Fundamentals of Celestial Mechanics, J.M.A. Danby 2nd edition + # from: Fundamentals of Celestial Mechanics, J.M.A. Danby 2nd edition instance = interface.TwoBody() p = datamodel.Particles(2) @@ -169,12 +169,12 @@ def test6(self): p.vz = [-0.2, 0.0] | nbody_system.speed instance.particles.add_particles(p) - instance.evolve_model(1.0|nbody_system.time) - self.assertAlmostEqual(instance.particles.x[0] - instance.particles.x[1], 0.611238439231|nbody_system.length, 7) - self.assertAlmostEqual(instance.particles.y[0] - instance.particles.y[1], 1.92873971354574|nbody_system.length, 7) - self.assertAlmostEqual(instance.particles.z[0] - instance.particles.z[1], -0.2562478900031234|nbody_system.length, 7) + instance.evolve_model(1.0 | nbody_system.time) + self.assertAlmostEqual(instance.particles.x[0] - instance.particles.x[1], 0.611238439231 | nbody_system.length, 7) + self.assertAlmostEqual(instance.particles.y[0] - instance.particles.y[1], 1.92873971354574 | nbody_system.length, 7) + self.assertAlmostEqual(instance.particles.z[0] - instance.particles.z[1], -0.2562478900031234 | nbody_system.length, 7) instance.stop() - + def test7(self): print("Test 7: get_gravity_at_point") instance = interface.TwoBody() @@ -191,19 +191,19 @@ def test7(self): self.assertAlmostEqual(ax, 16/9.0 | nbody_system.acceleration) self.assertAlmostEqual(ay, 0 | nbody_system.acceleration) self.assertAlmostEqual(az, 0 | nbody_system.acceleration) - + zero = [0.0]*4 | nbody_system.length ax, ay, az = instance.get_gravity_at_point(zero, [0, 0.5, 1.5, 2.5] | nbody_system.length, zero, zero) self.assertAlmostEqual(ax, [0, 16/9.0, -2.08, -0.26303854] | nbody_system.acceleration) self.assertAlmostEqual(ay, 0 | nbody_system.acceleration) self.assertAlmostEqual(az, 0 | nbody_system.acceleration) - + zero = [0.0] | nbody_system.length ax, ay, az = instance.get_gravity_at_point(zero, 1.0 | nbody_system.length, zero, zero) self.assertTrue(numpy.isnan(ax[0].value_in(nbody_system.acceleration))) self.assertTrue(numpy.isnan(ay[0].value_in(nbody_system.acceleration))) self.assertTrue(numpy.isnan(az[0].value_in(nbody_system.acceleration))) - + zero = [0.0] | nbody_system.length eps = [0.1] | nbody_system.length ax, ay, az = instance.get_gravity_at_point(eps, 1.0 | nbody_system.length, zero, zero) @@ -211,7 +211,7 @@ def test7(self): self.assertAlmostEqual(ay, 0 | nbody_system.acceleration) self.assertAlmostEqual(az, 0 | nbody_system.acceleration) instance.stop() - + def test8(self): print("Test 8: get_potential_at_point") instance = interface.TwoBody() @@ -226,41 +226,40 @@ def test8(self): zero = [0.0] | nbody_system.length phi = instance.get_potential_at_point(zero, 0.5 | nbody_system.length, zero, zero) self.assertAlmostEqual(phi, -4/3.0 | nbody_system.potential) - + zero = [0.0]*4 | nbody_system.length phi = instance.get_potential_at_point(zero, [0, 0.5, 1.5, 2.5] | nbody_system.length, zero, zero) self.assertAlmostEqual(phi, [-1, -4/3.0, -1.2, -0.47619047] | nbody_system.potential) - + zero = [0.0] | nbody_system.length phi = instance.get_potential_at_point(zero, 1.0 | nbody_system.length, zero, zero) self.assertTrue(numpy.isinf(phi[0].value_in(nbody_system.potential))) instance.stop() - + def test9(self): print("Test 9: TwoBody parameters") instance = interface.TwoBody() - + self.assertEqual(instance.parameters.epsilon_squared, zero) - - self.assertRaises(AmuseException, setattr, instance.parameters, "epsilon_squared", zero, - expected_message = "Could not set value for parameter 'epsilon_squared' of a 'TwoBody' object, " + + self.assertRaises(AmuseException, setattr, instance.parameters, "epsilon_squared", zero, + expected_message="Could not set value for parameter 'epsilon_squared' of a 'TwoBody' object, " "parameter is read-only") - + instance.stop() - - + def test10(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.yr, 1.0 | units.AU) instance = interface.TwoBody(convert_nbody) - + value = instance.get_begin_time() - self.assertEqual(0.0| units.yr, value) + self.assertEqual(0.0 | units.yr, value) self.assertAlmostEqual(0.0 | units.yr, instance.parameters.begin_time, in_units=units.yr) for x in [1.0, 10.0, 100.0]: instance.parameters.begin_time = x | units.yr self.assertAlmostEqual(x | units.yr, instance.parameters.begin_time, in_units=units.yr) instance.stop() - + def test11(self): instance = interface.TwoBody() p = datamodel.Particles(2) @@ -276,18 +275,16 @@ def test11(self): p.vz = [-0.2, 0.0] | nbody_system.speed instance.particles.add_particles(p) - instance.evolve_model(0.5|nbody_system.time) + instance.evolve_model(0.5 | nbody_system.time) particles1 = instance.particles.copy() instance.stop() - - + instance = interface.TwoBody() - instance.parameters.begin_time = 0.5 |nbody_system.time + instance.parameters.begin_time = 0.5 | nbody_system.time instance.particles.add_particles(particles1) - instance.evolve_model(1.0|nbody_system.time) - - self.assertAlmostEqual(instance.particles.x[0] - instance.particles.x[1], 0.611238439231|nbody_system.length, 7) - self.assertAlmostEqual(instance.particles.y[0] - instance.particles.y[1], 1.92873971354574|nbody_system.length, 7) - self.assertAlmostEqual(instance.particles.z[0] - instance.particles.z[1], -0.2562478900031234|nbody_system.length, 7) + instance.evolve_model(1.0 | nbody_system.time) + + self.assertAlmostEqual(instance.particles.x[0] - instance.particles.x[1], 0.611238439231 | nbody_system.length, 7) + self.assertAlmostEqual(instance.particles.y[0] - instance.particles.y[1], 1.92873971354574 | nbody_system.length, 7) + self.assertAlmostEqual(instance.particles.z[0] - instance.particles.z[1], -0.2562478900031234 | nbody_system.length, 7) instance.stop() - diff --git a/src/amuse/test/suite/codes_tests/test_vader.py b/src/amuse/test/suite/codes_tests/test_vader.py index c69f2be694..0ecea26c2d 100644 --- a/src/amuse/test/suite/codes_tests/test_vader.py +++ b/src/amuse/test/suite/codes_tests/test_vader.py @@ -8,6 +8,7 @@ default_options = dict() + class TestVaderInterface(TestWithMPI): def test1(self): @@ -20,9 +21,9 @@ def test1(self): index = 25 - self.assertEqual(1.23, + self.assertEqual(1.23, instance.get_rotational_velocity_of_index([index])['vphi'][0]) - self.assertEqual(float(index)+1.5, + self.assertEqual(float(index)+1.5, instance.get_position_of_index([index])['r'][0]) instance.cleanup_code() @@ -36,7 +37,7 @@ def test2(self): instance.initialize_keplerian_grid(n=100, linear=False, rmin=1., rmax=100., m=1.) - G = 6.67384e-8 # From VADER source + G = 6.67384e-8 # From VADER source index = 50 r = instance.get_position_of_index([index])['r'][0] @@ -44,9 +45,9 @@ def test2(self): v_kepler = (G/r)**0.5 # Should be exactly equal, but different roundoff in python/c could ruin this - #self.assertEqual(v_kepler, + # self.assertEqual(v_kepler, # instance.get_rotational_velocity_of_index([index])['vphi'][0]) - self.assertAlmostEqual(v_kepler, + self.assertAlmostEqual(v_kepler, instance.get_rotational_velocity_of_index([index])['vphi'][0]) self.assertAlmostEqual(v_kepler*v_kepler, instance.get_gravitational_potential_of_index([index])['psi_grav'][0]) @@ -67,8 +68,8 @@ def test3(self): index = 75 - self.assertEqual(10., - instance.get_grid_pressure([index])['pressure'][0] / \ + self.assertEqual(10., + instance.get_grid_pressure([index])['pressure'][0] / instance.get_grid_column_density([index])['sigma'][0]) instance.cleanup_code() @@ -92,38 +93,39 @@ def test4(self): instance.cleanup_code() instance.stop() + class TestVader(TestWithMPI): def test1(self): instance = self.new_instance_of_an_optional_code( Vader, **default_options) - instance.initialize_flat_grid(100, False, 1.|units.AU, 100.|units.AU, - 1.|units.kms) + instance.initialize_flat_grid(100, False, 1. | units.AU, 100. | units.AU, + 1. | units.kms) - self.assertEqual(1.|units.kms, instance.grid.rotational_velocity[0]) + self.assertEqual(1. | units.kms, instance.grid.rotational_velocity[0]) - instance.update_flat_grid(2.|units.kms) + instance.update_flat_grid(2. | units.kms) - self.assertEqual(2.|units.kms, instance.grid.rotational_velocity[0]) + self.assertEqual(2. | units.kms, instance.grid.rotational_velocity[0]) instance.stop() def test2(self): instance = self.new_instance_of_an_optional_code( Vader, **default_options) - instance.initialize_keplerian_grid(100, False, 1.|units.AU, 100.|units.AU, - 1.|units.MSun) + instance.initialize_keplerian_grid(100, False, 1. | units.AU, 100. | units.AU, + 1. | units.MSun) - G = 6.67384e-8 | units.cm**3/units.g/units.s**2 # From VADER source + G = 6.67384e-8 | units.cm**3/units.g/units.s**2 # From VADER source index = 25 - v_kepler = (G*(1.|units.MSun)/instance.grid.r[index])**0.5 + v_kepler = (G*(1. | units.MSun)/instance.grid.r[index])**0.5 self.assertEqual(v_kepler, instance.grid.rotational_velocity[index]) - instance.update_keplerian_grid(2.|units.MSun) + instance.update_keplerian_grid(2. | units.MSun) - v_kepler = (G*(2.|units.MSun)/instance.grid.r[index])**0.5 + v_kepler = (G*(2. | units.MSun)/instance.grid.r[index])**0.5 self.assertEqual(v_kepler, instance.grid.rotational_velocity[index]) self.assertEqual((v_kepler*v_kepler).value_in((units.cm/units.s)**2), @@ -135,8 +137,8 @@ def test2(self): def test3(self): instance = self.new_instance_of_an_optional_code( Vader, **default_options) - instance.initialize_keplerian_grid(100, False, 1.|units.AU, 100.|units.AU, - 1.|units.MSun) + instance.initialize_keplerian_grid(100, False, 1. | units.AU, 100. | units.AU, + 1. | units.MSun) instance.parameters.alpha = 1e-3 instance.parameters.gamma = 5./3. @@ -144,18 +146,18 @@ def test3(self): self.assertEqual(0.001, instance.parameters.alpha) self.assertEqual(5./3., instance.parameters.gamma) - self.assertEqual(1., + self.assertEqual(1., instance.parameters.delta.value_in((units.cm/units.s)**2)) col = np.logspace(0, -2, num=100) | units.g/units.cm**2 - pres = col * constants.kB*(100.|units.K)/(constants.u) + pres = col * constants.kB*(100. | units.K)/(constants.u) - instance.grid.column_density = col + instance.grid.column_density = col instance.grid.pressure = pres mass0 = instance.mass - instance.evolve_model( 1.|units.kyr ) + instance.evolve_model(1. | units.kyr) mass1 = instance.mass @@ -167,8 +169,8 @@ def test3(self): def test4(self): instance = self.new_instance_of_an_optional_code( Vader, **default_options) - instance.initialize_keplerian_grid(100, False, 1.|units.AU, 100.|units.AU, - 1.|units.MSun) + instance.initialize_keplerian_grid(100, False, 1. | units.AU, 100. | units.AU, + 1. | units.MSun) instance.parameters.alpha = 1e-3 instance.parameters.inner_pressure_boundary_mass_flux = \ @@ -177,20 +179,20 @@ def test4(self): 1e-12 | units.MSun/units.yr col = np.logspace(0, -2, num=100) | units.g/units.cm**2 - pres = col * constants.kB*(100.|units.K)/(constants.u) + pres = col * constants.kB*(100. | units.K)/(constants.u) - instance.grid.column_density = col + instance.grid.column_density = col instance.grid.pressure = pres mass0 = instance.mass - instance.evolve_model( 1.|units.kyr ) + instance.evolve_model(1. | units.kyr) mass1 = instance.mass self.assertAlmostEqual(mass0.value_in(units.MSun), - (mass1 - \ - instance.inner_boundary_mass_out - \ + (mass1 - + instance.inner_boundary_mass_out - instance.outer_boundary_mass_out ).value_in(units.MSun)) diff --git a/src/amuse/test/suite/compile_tests/test_async.py b/src/amuse/test/suite/compile_tests/test_async.py index 1de7521b16..6a78c965b4 100644 --- a/src/amuse/test/suite/compile_tests/test_async.py +++ b/src/amuse/test/suite/compile_tests/test_async.py @@ -13,13 +13,13 @@ from amuse.rfi import async_request from amuse.rfi.core import * -from . import test_c_implementation +from . import test_c_implementation from amuse.test import compile_tools from amuse.community.distributed.interface import DistributedAmuse, Pilot -codestring=test_c_implementation.codestring+""" +codestring = test_c_implementation.codestring+""" #include float _x[10] = { 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.}; @@ -50,26 +50,27 @@ """ + class ForTestingInterface(test_c_implementation.ForTestingInterface): @legacy_function def do_sleep(): function = LegacyFunctionSpecification() function.addParameter('int_in', dtype='int32', direction=function.IN) function.result_type = 'int32' - return function + return function @legacy_function def return_error(): function = LegacyFunctionSpecification() function.addParameter('out', dtype='int32', direction=function.OUT) function.result_type = 'int32' - return function + return function @legacy_function def echo_2_int(): function = LegacyFunctionSpecification() function.addParameter('int_in1', dtype='int32', direction=function.IN, unit=units.m) - function.addParameter('int_in2', dtype='int32', direction=function.IN, default = 1, unit=units.kg) + function.addParameter('int_in2', dtype='int32', direction=function.IN, default=1, unit=units.kg) function.addParameter('int_out1', dtype='int32', direction=function.OUT, unit=units.m) function.addParameter('int_out2', dtype='int32', direction=function.OUT, unit=units.kg) function.addParameter('len', dtype='int32', direction=function.LENGTH) @@ -84,7 +85,7 @@ def get_x(): function.addParameter('x', dtype='float32', direction=function.OUT, unit=units.m) function.result_type = 'int32' function.can_handle_array = True - return function + return function @legacy_function def set_x(): @@ -93,21 +94,22 @@ def set_x(): function.addParameter('x', dtype='float32', direction=function.IN, unit=units.m) function.result_type = 'int32' function.can_handle_array = True - return function + return function @legacy_function def dummy(): function = LegacyFunctionSpecification() function.result_type = 'int32' - return function + return function + class ForTesting(InCodeComponentImplementation): - + def __init__(self, exefile, **options): InCodeComponentImplementation.__init__(self, ForTestingInterface(exefile, **options), **options) def get_grid_range(self): - return (0,9) + return (0, 9) def define_grids(self, handler): handler.define_grid('grid') @@ -115,6 +117,7 @@ def define_grids(self, handler): handler.add_getter('grid', 'get_x', names=["x"]) handler.add_setter('grid', 'set_x', names=["x"]) + class ForTestingWithState(ForTesting): def define_state(self, handler): handler.set_initial_state("1") @@ -122,6 +125,7 @@ def define_state(self, handler): handler.add_method("2", "get_x") handler.add_method("2", "set_x") + class TestASync(TestWithMPI): @classmethod @@ -134,7 +138,7 @@ def setup_class(cls): print(ex) raise print("done") - + def test1(self): instance = ForTestingInterface(self.exefile) int_out, error = instance.echo_int(10) @@ -147,7 +151,7 @@ def test2(self): request = instance.echo_int.asynchronous(10) self.assertEqual(request, instance.async_request) request.wait() - int_out,error=request.result() + int_out, error = request.result() self.assertEqual(int_out, 10) self.assertEqual(error, 0) instance.stop() @@ -158,7 +162,7 @@ def test3(self): request2 = instance.echo_int.asynchronous(10) self.assertEqual(request2, instance.async_request) request2.wait() - int_out,error=request2.result() + int_out, error = request2.result() self.assertEqual(int_out, 10) self.assertEqual(error, 0) instance.stop() @@ -169,48 +173,48 @@ def test4(self): request2 = instance.echo_int(10, return_request=True) self.assertEqual(request2, instance.async_request) instance.async_request.wait() - int_out=request2.result() + int_out = request2.result() self.assertEqual(int_out, 10) instance.stop() def test5(self): instance = ForTesting(self.exefile) instance.do_sleep(1, return_request=True) - requests=[] + requests = [] for x in range(10): requests.append(instance.echo_int(x, return_request=True)) instance.async_request.wait() - for i,x in enumerate(requests): + for i, x in enumerate(requests): self.assertEqual(x.result(), i) instance.stop() def test6(self): instance = ForTesting(self.exefile) - requests=[] + requests = [] for x in range(10): requests.append(instance.echo_int(x, return_request=True)) instance.async_request.wait() - for i,x in enumerate(requests): + for i, x in enumerate(requests): self.assertEqual(x.result(), i) instance.stop() def test7(self): instance1 = ForTesting(self.exefile) instance2 = ForTesting(self.exefile) - t1=time.time() + t1 = time.time() - requests=[] + requests = [] for x in range(10): - requests.append([instance1.echo_int(x, return_request=True),x]) + requests.append([instance1.echo_int(x, return_request=True), x]) for x in range(10): - requests.append([instance2.echo_int(x, return_request=True),x]) + requests.append([instance2.echo_int(x, return_request=True), x]) instance1.do_sleep(1, return_request=True) instance2.do_sleep(1, return_request=True) - pool=instance1.async_request.join(instance2.async_request) + pool = instance1.async_request.join(instance2.async_request) pool.waitall() - t2=time.time() + t2 = time.time() for x in requests: self.assertEqual(x[0].result(), x[1]) @@ -222,27 +226,27 @@ def test8(self): from threading import Thread instance1 = ForTesting(self.exefile) instance2 = ForTesting(self.exefile) - t1=time.time() + t1 = time.time() - requests=[] + requests = [] for x in range(10): - requests.append([instance1.echo_int(x, return_request=True),x]) + requests.append([instance1.echo_int(x, return_request=True), x]) for x in range(10): - requests.append([instance2.echo_int(x, return_request=True),x]) + requests.append([instance2.echo_int(x, return_request=True), x]) instance1.do_sleep(1, return_request=True) instance2.do_sleep(1, return_request=True) - pool=instance1.async_request.join(instance2.async_request) - - thread=Thread(target=pool.waitall) + pool = instance1.async_request.join(instance2.async_request) + + thread = Thread(target=pool.waitall) thread.start() time.sleep(1) thread.join() - + self.assertTrue(pool) - - t2=time.time() + + t2 = time.time() for x in requests: self.assertEqual(x[0].result(), x[1]) @@ -254,47 +258,47 @@ def test9(self): instance = ForTesting(self.exefile) for x in range(10): instance.echo_int(x, return_request=True) - results=instance.async_request.results + results = instance.async_request.results self.assertEqual(results, list(range(10))) instance.stop() def test10(self): instance = ForTesting(self.exefile) - r1=instance.do_sleep(1, return_request=True) - r2=instance.return_error( return_request=True) - r3=instance.echo_int(1, return_request=True) - r4=instance.echo_int(2, return_request=True) + r1 = instance.do_sleep(1, return_request=True) + r2 = instance.return_error(return_request=True) + r3 = instance.echo_int(1, return_request=True) + r4 = instance.echo_int(2, return_request=True) self.assertRaises(Exception, instance.async_request.waitall, expected_message="Error in dependent call: Error when calling 'return_error' of a 'ForTesting', errorcode is -1") - self.assertTrue( r1.is_result_available() ) - self.assertFalse( r2.is_result_available() ) - self.assertTrue( r2.is_finished ) - self.assertTrue( r3.is_finished ) - self.assertFalse( bool(r3) ) - self.assertTrue( r4.is_finished ) - self.assertTrue( r4.waits_for() is None ) - self.assertFalse( r3.is_result_available() ) - + self.assertTrue(r1.is_result_available()) + self.assertFalse(r2.is_result_available()) + self.assertTrue(r2.is_finished) + self.assertTrue(r3.is_finished) + self.assertFalse(bool(r3)) + self.assertTrue(r4.is_finished) + self.assertTrue(r4.waits_for() is None) + self.assertFalse(r3.is_result_available()) + instance.stop() def test11(self): """ cross dependency """ instance1 = ForTesting(self.exefile) instance2 = ForTesting(self.exefile) - + instance1.do_sleep(1, return_request=True) - request1=instance1.echo_int(10, return_request=True) - + request1 = instance1.echo_int(10, return_request=True) + def fac(): - return instance2.echo_int(20, return_request=True) + return instance2.echo_int(20, return_request=True) - #~ request2=instance2.echo_int(20, async_dependency=request1) - request2=async_request.DependentASyncRequest(request1, fac) + # ~ request2=instance2.echo_int(20, async_dependency=request1) + request2 = async_request.DependentASyncRequest(request1, fac) request2.wait() - - self.assertEqual(request2.result(),20) - + + self.assertEqual(request2.result(), 20) + instance1.stop() instance2.stop() @@ -302,16 +306,16 @@ def test11b(self): """ cross dependency """ instance1 = ForTesting(self.exefile) instance2 = ForTesting(self.exefile) - + instance1.do_sleep(1, return_request=True) - request1=instance1.echo_int(10, return_request=True) - request2=instance2.echo_int(20, async_dependency=request1, return_request=True) + request1 = instance1.echo_int(10, return_request=True) + request2 = instance2.echo_int(20, async_dependency=request1, return_request=True) request2.wait() self.assertTrue(request1.is_result_available()) - - self.assertEqual(request2.result(),20) - + + self.assertEqual(request2.result(), 20) + instance1.stop() instance2.stop() @@ -319,29 +323,29 @@ def test12(self): """ cross dependency with input-output dependency """ instance1 = ForTesting(self.exefile) instance2 = ForTesting(self.exefile) - + instance1.do_sleep(1, return_request=True) - request1=instance1.echo_int(10, return_request=True) - - results=dict() - + request1 = instance1.echo_int(10, return_request=True) + + results = dict() + def safe_result(arg, index): - result=arg() - results[index]=result + result = arg() + results[index] = result return result - - request1.add_result_handler(safe_result,(1,)) - + + request1.add_result_handler(safe_result, (1,)) + def fac(): - return instance2.echo_int(results[1], return_request=True) + return instance2.echo_int(results[1], return_request=True) - #~ request2=instance2.echo_int(??, async_factory=fac) - request2=async_request.DependentASyncRequest(request1, fac) + # ~ request2=instance2.echo_int(??, async_factory=fac) + request2 = async_request.DependentASyncRequest(request1, fac) request2.wait() - - self.assertEqual( request2.result(), 10) - + + self.assertEqual(request2.result(), 10) + instance1.stop() instance2.stop() @@ -349,16 +353,16 @@ def test12b(self): """ cross dependency with input-output dependency """ instance1 = ForTesting(self.exefile) instance2 = ForTesting(self.exefile) - + instance1.do_sleep(1, return_request=True) - request1=instance1.echo_int(10, return_request=True) + request1 = instance1.echo_int(10, return_request=True) + + request2 = instance2.echo_int(request1, return_request=True) - request2=instance2.echo_int(request1, return_request=True) - request2.wait() - self.assertEqual( request2.result(), 10) - + self.assertEqual(request2.result(), 10) + instance1.stop() instance2.stop() @@ -366,19 +370,19 @@ def test12c(self): """ cross dependency with input-output dependency """ instance1 = ForTesting(self.exefile) instance2 = ForTesting(self.exefile) - + instance1.do_sleep(1, return_request=True) - request1=instance1.echo_2_int(1 | units.m , 2 | units.kg, return_request=True) + request1 = instance1.echo_2_int(1 | units.m, 2 | units.kg, return_request=True) + + request2 = instance2.echo_2_int(request1[0], request1[1], return_request=True) - request2=instance2.echo_2_int(request1[0], request1[1], return_request=True) - print("do...wait...") request2.wait() print("done", request2.result()) - self.assertEqual( request2.result()[0], 1 | units.m) - self.assertEqual( request2.result()[1], 2 | units.kg) - + self.assertEqual(request2.result()[0], 1 | units.m) + self.assertEqual(request2.result()[1], 2 | units.kg) + instance1.stop() instance2.stop() @@ -388,40 +392,39 @@ def test12c(self): instance2 = ForTesting(self.exefile) instance3 = ForTesting(self.exefile) instance4 = ForTesting(self.exefile) - + instance1.do_sleep(1, return_request=True) - request1=instance1.echo_2_int(1 | units.m , 2 | units.kg, return_request=True) - request1b=instance1.do_sleep(1, return_request=True) - request2=instance2.echo_2_int(3 | units.m , 4 | units.kg, return_request=True) - request3=instance3.echo_2_int(request2[0] , 5 | units.kg, return_request=True) + request1 = instance1.echo_2_int(1 | units.m, 2 | units.kg, return_request=True) + request1b = instance1.do_sleep(1, return_request=True) + request2 = instance2.echo_2_int(3 | units.m, 4 | units.kg, return_request=True) + request3 = instance3.echo_2_int(request2[0], 5 | units.kg, return_request=True) instance4.do_sleep(1, return_request=True) - request4=instance4.echo_2_int(request2[0], request3[1], return_request=True, async_dependency=request1b) - + request4 = instance4.echo_2_int(request2[0], request3[1], return_request=True, async_dependency=request1b) + request3.wait() - self.assertEqual( request4.result()[0], 3 | units.m) - self.assertEqual( request4.result()[1], 5 | units.kg) - + self.assertEqual(request4.result()[0], 3 | units.m) + self.assertEqual(request4.result()[1], 5 | units.kg) + instance1.stop() instance2.stop() instance3.stop() instance4.stop() - def test13(self): instance = ForTesting(self.exefile) - r=instance.echo_int(1, return_request=True) + r = instance.echo_int(1, return_request=True) time.sleep(0.1) self.assertTrue(r.is_result_available()) r.result() - r=instance.return_error(return_request=True) + r = instance.return_error(return_request=True) time.sleep(0.1) self.assertTrue(r.is_result_available()) self.assertTrue(r.is_result_available()) - self.assertRaises(Exception, r.result, expected_message="Error when calling 'return_error' of a 'ForTesting', errorcode is -1") + self.assertRaises(Exception, r.result, expected_message="Error when calling 'return_error' of a 'ForTesting', errorcode is -1") self.assertFalse(r.is_result_available()) self.assertTrue(r.is_finished) instance.stop() @@ -429,16 +432,16 @@ def test13(self): def test14(self): instance = ForTesting(self.exefile, channel_type="sockets") - r=instance.echo_int(1, return_request=True) + r = instance.echo_int(1, return_request=True) time.sleep(0.1) self.assertTrue(r.is_result_available()) r.result() - r=instance.return_error(return_request=True) + r = instance.return_error(return_request=True) time.sleep(0.1) self.assertTrue(r.is_result_available()) self.assertTrue(r.is_result_available()) - self.assertRaises(Exception, r.result, expected_message="Error when calling 'return_error' of a 'ForTesting', errorcode is -1") + self.assertRaises(Exception, r.result, expected_message="Error when calling 'return_error' of a 'ForTesting', errorcode is -1") self.assertFalse(r.is_result_available()) self.assertTrue(r.is_finished) instance.stop() @@ -447,11 +450,10 @@ def test15(self): instance = ForTesting(self.exefile) instance.do_sleep(1, return_request=True) - instance.return_error( return_request=True) + instance.return_error(return_request=True) instance.echo_int(1, return_request=True) instance.echo_int(1, return_request=True) - #~ self.assertRinstance.echo_int(1) - + # ~ self.assertRinstance.echo_int(1) instance.stop() @@ -459,28 +461,27 @@ def test16(self): instance = ForTesting(self.exefile) instance.do_sleep(1, return_request=True) - result=instance.echo_2_int([11,12,13] | units.m,[3,2,1]| units.kg, return_request=True) - - r1=result[0] - r2=result[1] - - self.assertEqual(r1.result(),[11,12,13] | units.m) - self.assertEqual(r2.result(),[3,2,1] | units.kg) - + result = instance.echo_2_int([11, 12, 13] | units.m, [3, 2, 1] | units.kg, return_request=True) + + r1 = result[0] + r2 = result[1] + + self.assertEqual(r1.result(), [11, 12, 13] | units.m) + self.assertEqual(r2.result(), [3, 2, 1] | units.kg) + instance.stop() def test17(self): instance = ForTestingInterface(self.exefile) instance.do_sleep.asynchronous(1) - request=instance.echo_2_int.asynchronous([11,12,13],[3,2,1]) + request = instance.echo_2_int.asynchronous([11, 12, 13], [3, 2, 1]) - r1=request["int_out1"] - r2=request["int_out2"] - - self.assertEqual(r1.result(),[11,12,13] ) - self.assertEqual(r2.result(),[3,2,1] ) - + r1 = request["int_out1"] + r2 = request["int_out2"] + + self.assertEqual(r1.result(), [11, 12, 13]) + self.assertEqual(r2.result(), [3, 2, 1]) instance.stop() @@ -489,18 +490,18 @@ def test18(self): instance1 = ForTesting(self.exefile) instance2 = ForTesting(self.exefile) instance3 = ForTesting(self.exefile) - - request0=instance1.do_sleep(1, return_request=True) - request1=instance1.echo_int(10, return_request=True) - request2=instance2.echo_int(10, return_request=True) - request=async_request.AsyncRequestsPool(request1,request2) - - request3=instance3.echo_int(11, async_dependency=request, return_request=True) + + request0 = instance1.do_sleep(1, return_request=True) + request1 = instance1.echo_int(10, return_request=True) + request2 = instance2.echo_int(10, return_request=True) + request = async_request.AsyncRequestsPool(request1, request2) + + request3 = instance3.echo_int(11, async_dependency=request, return_request=True) request3.wait() self.assertTrue(request1.is_result_available()) self.assertTrue(request2.is_result_available()) - self.assertEqual( request3.result(), 11) - + self.assertEqual(request3.result(), 11) + instance1.stop() instance2.stop() instance3.stop() @@ -510,18 +511,18 @@ def test18b(self): instance1 = ForTesting(self.exefile) instance2 = ForTesting(self.exefile) instance3 = ForTesting(self.exefile) - - request0=instance1.do_sleep(1, return_request=True) - request1=instance1.echo_int(10, return_request=True) - request2=instance1.echo_int(10, return_request=True) - request=async_request.AsyncRequestsPool(request1,request2) - - request3=instance3.echo_int(11, async_dependency=request, return_request=True) + + request0 = instance1.do_sleep(1, return_request=True) + request1 = instance1.echo_int(10, return_request=True) + request2 = instance1.echo_int(10, return_request=True) + request = async_request.AsyncRequestsPool(request1, request2) + + request3 = instance3.echo_int(11, async_dependency=request, return_request=True) request3.wait() self.assertTrue(request1.is_result_available()) self.assertTrue(request2.is_result_available()) - self.assertEqual( request3.result(), 11) - + self.assertEqual(request3.result(), 11) + instance1.stop() instance2.stop() instance3.stop() @@ -530,23 +531,23 @@ def test19(self): """ test sum request """ instance1 = ForTesting(self.exefile) instance2 = ForTesting(self.exefile) - + instance1.do_sleep(1, return_request=True) - - r1=instance1.echo_int(1, return_request=True) - r2=instance2.echo_int(2, return_request=True) - s=r1+r2 - r1=instance1.echo_int(2, return_request=True) - r2=instance2.echo_int(3, return_request=True) - m=r1*r2 - r1=instance1.echo_int(12, return_request=True) - r2=instance2.echo_int(3, return_request=True) - d=r1/r2 - - self.assertEqual( s.result(), 3) - self.assertEqual( m.result(), 6) - self.assertEqual( d.result(), 4) - + + r1 = instance1.echo_int(1, return_request=True) + r2 = instance2.echo_int(2, return_request=True) + s = r1+r2 + r1 = instance1.echo_int(2, return_request=True) + r2 = instance2.echo_int(3, return_request=True) + m = r1*r2 + r1 = instance1.echo_int(12, return_request=True) + r2 = instance2.echo_int(3, return_request=True) + d = r1/r2 + + self.assertEqual(s.result(), 3) + self.assertEqual(m.result(), 6) + self.assertEqual(d.result(), 4) + instance1.stop() instance2.stop() @@ -554,20 +555,20 @@ def test19b(self): """ test sum request """ instance1 = ForTesting(self.exefile) instance2 = ForTesting(self.exefile) - + instance1.do_sleep(1, return_request=True) - - r1=instance1.echo_int(1, return_request=True) - s=r1+2 - r1=instance1.echo_int(2, return_request=True) - m=r1*3 - r2=instance2.echo_int(3, return_request=True) - d=12/r2 - - self.assertEqual( s.result(), 3) - self.assertEqual( m.result(), 6) - self.assertEqual( d.result(), 4) - + + r1 = instance1.echo_int(1, return_request=True) + s = r1+2 + r1 = instance1.echo_int(2, return_request=True) + m = r1*3 + r2 = instance2.echo_int(3, return_request=True) + d = 12/r2 + + self.assertEqual(s.result(), 3) + self.assertEqual(m.result(), 6) + self.assertEqual(d.result(), 4) + instance1.stop() instance2.stop() @@ -576,19 +577,19 @@ def test20(self): instance1 = ForTesting(self.exefile) instance2 = ForTesting(self.exefile) instance3 = ForTesting(self.exefile) - + instance1.do_sleep(1, return_request=True) - request1=instance1.echo_2_int(1 | units.m , 2 | units.kg, return_request=True) - request2=instance2.echo_2_int(4 | units.m , 6 | units.kg, return_request=True) - request3a=instance3.echo_int(request2[0] / request1[0]-4, return_request=True) - request3b=instance3.echo_int(request2[1] / request1[1]-3, return_request=True) + request1 = instance1.echo_2_int(1 | units.m, 2 | units.kg, return_request=True) + request2 = instance2.echo_2_int(4 | units.m, 6 | units.kg, return_request=True) + request3a = instance3.echo_int(request2[0] / request1[0]-4, return_request=True) + request3b = instance3.echo_int(request2[1] / request1[1]-3, return_request=True) request3a.wait() request3b.wait() - self.assertEqual( request3a.result(), 0 ) - self.assertEqual( request3b.result(), 0 ) - + self.assertEqual(request3a.result(), 0) + self.assertEqual(request3b.result(), 0) + instance1.stop() instance2.stop() instance3.stop() @@ -597,23 +598,23 @@ def test21(self): """ test sum request, sockets """ instance1 = ForTesting(self.exefile, channel_type="sockets") instance2 = ForTesting(self.exefile, channel_type="sockets") - + instance1.do_sleep(1, return_request=True) - - r1=instance1.echo_int(1, return_request=True) - r2=instance2.echo_int(2, return_request=True) - s=r1+r2 - r1=instance1.echo_int(2, return_request=True) - r2=instance2.echo_int(3, return_request=True) - m=r1*r2 - r1=instance1.echo_int(12, return_request=True) - r2=instance2.echo_int(3, return_request=True) - d=r1/r2 - - self.assertEqual( s.result(), 3) - self.assertEqual( m.result(), 6) - self.assertEqual( d.result(), 4) - + + r1 = instance1.echo_int(1, return_request=True) + r2 = instance2.echo_int(2, return_request=True) + s = r1+r2 + r1 = instance1.echo_int(2, return_request=True) + r2 = instance2.echo_int(3, return_request=True) + m = r1*r2 + r1 = instance1.echo_int(12, return_request=True) + r2 = instance2.echo_int(3, return_request=True) + d = r1/r2 + + self.assertEqual(s.result(), 3) + self.assertEqual(m.result(), 6) + self.assertEqual(d.result(), 4) + instance1.stop() instance2.stop() @@ -621,73 +622,72 @@ def test21(self): """ some more tests of request expressions """ instance1 = ForTesting(self.exefile) - a=[10,30,15] | units.m - b=[1,3,5] | units.kg - + a = [10, 30, 15] | units.m + b = [1, 3, 5] | units.kg + instance1.do_sleep(1, return_request=True) - request1=instance1.echo_2_int(a , b, return_request=True) - - request2=(3*request1[1]/(2.*request1[0])+(55. | units.kg/units.m)) - self.assertEqual( request2.result(), (3*b/(2.*a)+(55. | units.kg/units.m)) ) - + request1 = instance1.echo_2_int(a, b, return_request=True) + + request2 = (3*request1[1]/(2.*request1[0])+(55. | units.kg/units.m)) + self.assertEqual(request2.result(), (3*b/(2.*a)+(55. | units.kg/units.m))) + instance1.stop() def test22(self): """ tests of unpack """ instance1 = ForTesting(self.exefile) - a=[10,30,15] | units.m - b=[1,3,5] | units.kg - - #~ instance1.do_sleep(1, return_request=True) - a_,b_=instance1.echo_2_int(a , b, return_request=True) - - self.assertEqual( (3*b_/(2.*a_)+(55. | units.kg/units.m)).result(), (3*b/(2.*a)+(55. | units.kg/units.m)) ) - + a = [10, 30, 15] | units.m + b = [1, 3, 5] | units.kg + + # ~ instance1.do_sleep(1, return_request=True) + a_, b_ = instance1.echo_2_int(a, b, return_request=True) + + self.assertEqual((3*b_/(2.*a_)+(55. | units.kg/units.m)).result(), (3*b/(2.*a)+(55. | units.kg/units.m))) + instance1.stop() def test23(self): """ tests of unpack """ instance1 = ForTestingInterface(self.exefile) - a=[10,30,15] - b=[1,3,5] - - #~ instance1.do_sleep(1, return_request=True) - res=instance1.echo_2_int.asynchronous(a,b) - #~ res=res['int_out1'] - a_,b_, err= res - - - self.assertEqual( a,a_.result() ) - self.assertEqual( b,b_.result() ) - + a = [10, 30, 15] + b = [1, 3, 5] + + # ~ instance1.do_sleep(1, return_request=True) + res = instance1.echo_2_int.asynchronous(a, b) + # ~ res=res['int_out1'] + a_, b_, err = res + + self.assertEqual(a, a_.result()) + self.assertEqual(b, b_.result()) + instance1.stop() def test24(self): """ more test of pool """ instance1 = ForTesting(self.exefile) instance2 = ForTesting(self.exefile) - - r1=instance1.echo_int(1, return_request=True) - r2=instance1.echo_int(2, return_request=True) - r3=instance2.echo_int(3, return_request=True) - r4=instance2.echo_int(4, return_request=True) - - p1=r1.join(r3) - p2=r2.join(r4) - - p3=p1.join(p2) - + + r1 = instance1.echo_int(1, return_request=True) + r2 = instance1.echo_int(2, return_request=True) + r3 = instance2.echo_int(3, return_request=True) + r4 = instance2.echo_int(4, return_request=True) + + p1 = r1.join(r3) + p2 = r2.join(r4) + + p3 = p1.join(p2) + self.assertTrue(p3 is p1) - + p3.waitall() - + self.assertEqual(r1.result(), 1) self.assertEqual(r2.result(), 2) self.assertEqual(r3.result(), 3) self.assertEqual(r4.result(), 4) - + instance1.stop() instance2.stop() @@ -695,143 +695,142 @@ def test25(self): """ more test of pool: calls of same code """ from amuse.rfi.async_request import AsyncRequestsPool instance1 = ForTesting(self.exefile) - - r1=instance1.do_sleep(1, return_request=True) - r2=instance1.echo_int(2, return_request=True) - - p1=AsyncRequestsPool() + + r1 = instance1.do_sleep(1, return_request=True) + r2 = instance1.echo_int(2, return_request=True) + + p1 = AsyncRequestsPool() r1.wait() r2.wait() p1.add_request(r1) p1.add_request(r2) - - #~ p1=r1.join(r2) - + + # ~ p1=r1.join(r2) + p1.waitall() - + self.assertEqual(r2.result(), 2) - + instance1.stop() def test26(self): """ test a lot of calls""" - instances=[] + instances = [] for i in range(20): - instances.append(ForTesting(self.exefile, channel_type="sockets")) - + instances.append(ForTesting(self.exefile, channel_type="sockets")) + import time print("ready") time.sleep(1) - + print("start") - t1=time.time() - pool=[] + t1 = time.time() + pool = [] for i in instances: - print(i, "submit") - pool.append(i.do_sleep(5, return_request=True)) - - for i,p in enumerate(pool): - print("result:", i, p.result()) - t2=time.time() + print(i, "submit") + pool.append(i.do_sleep(5, return_request=True)) + + for i, p in enumerate(pool): + print("result:", i, p.result()) + t2 = time.time() print(t2-t1) for i in instances: - i.stop() - + i.stop() def test30(self): """ test a grid attribute request """ instance1 = ForTesting(self.exefile, redirection="none") - self.assertEqual(instance1.grid.x, numpy.arange(1,11) |units.m) + self.assertEqual(instance1.grid.x, numpy.arange(1, 11) | units.m) instance1.do_sleep(1, return_request=True) - t1=time.time() - request=instance1.grid.request.x - t2=time.time() + t1 = time.time() + request = instance1.grid.request.x + t2 = time.time() self.assertLess(t2-t1, 0.5) - self.assertEqual(request.result(), numpy.arange(1,11) | units.m) - t2=time.time() + self.assertEqual(request.result(), numpy.arange(1, 11) | units.m) + t2 = time.time() self.assertGreater(t2-t1, 1.) - + def test31(self): """ test a grid attribute request, subgrids """ instance1 = ForTesting(self.exefile, redirection="none") - self.assertEqual(instance1.grid.x, numpy.arange(1,11) |units.m) + self.assertEqual(instance1.grid.x, numpy.arange(1, 11) | units.m) instance1.do_sleep(1, return_request=True) - t1=time.time() - request=instance1.grid[:5].request.x - request2=instance1.grid[5:].request.x - t2=time.time() + t1 = time.time() + request = instance1.grid[:5].request.x + request2 = instance1.grid[5:].request.x + t2 = time.time() self.assertLess(t2-t1, 0.5) - self.assertEqual(request.result(), numpy.arange(1,6) | units.m) - self.assertEqual(request2.result(), numpy.arange(6,11) | units.m) - t2=time.time() + self.assertEqual(request.result(), numpy.arange(1, 6) | units.m) + self.assertEqual(request2.result(), numpy.arange(6, 11) | units.m) + t2 = time.time() self.assertGreater(t2-t1, 1.) def test32(self): """ test a grid attribute request setter """ instance1 = ForTesting(self.exefile, redirection="none") - instance1.grid.x=(66.+numpy.arange(1,11)) |units.m - self.assertEqual(instance1.grid.x, (66.+numpy.arange(1,11)) |units.m) + instance1.grid.x = (66.+numpy.arange(1, 11)) | units.m + self.assertEqual(instance1.grid.x, (66.+numpy.arange(1, 11)) | units.m) - t1=time.time() + t1 = time.time() instance1.do_sleep(1, return_request=True) - instance1.grid.request.x=(11.+numpy.arange(1,11)) |units.m - t2=time.time() + instance1.grid.request.x = (11.+numpy.arange(1, 11)) | units.m + t2 = time.time() self.assertLess(t2-t1, 0.5) instance1.async_request.wait() - t2=time.time() + t2 = time.time() self.assertGreater(t2-t1, 1.) - t1=time.time() - self.assertEqual(instance1.grid.x, (11.+numpy.arange(1,11)) | units.m) - t2=time.time() + t1 = time.time() + self.assertEqual(instance1.grid.x, (11.+numpy.arange(1, 11)) | units.m) + t2 = time.time() self.assertLess(t2-t1, 0.5) def test33(self): """ test a grid attribute request, subgrids """ instance1 = ForTesting(self.exefile, redirection="none") - self.assertEqual(instance1.grid.x, numpy.arange(1,11) |units.m) + self.assertEqual(instance1.grid.x, numpy.arange(1, 11) | units.m) - t1=time.time() + t1 = time.time() instance1.do_sleep(1, return_request=True) - instance1.grid[::2].request.x=(11.+numpy.arange(1,11,2)) |units.m - t2=time.time() + instance1.grid[::2].request.x = (11.+numpy.arange(1, 11, 2)) | units.m + t2 = time.time() self.assertLess(t2-t1, 0.5) instance1.async_request.wait() - t2=time.time() + t2 = time.time() self.assertGreater(t2-t1, 1.) - self.assertEqual(instance1.grid.x[::2], (11.+numpy.arange(1,11,2)) | units.m) - self.assertEqual(instance1.grid.x[1::2], (numpy.arange(2,11,2)) | units.m) + self.assertEqual(instance1.grid.x[::2], (11.+numpy.arange(1, 11, 2)) | units.m) + self.assertEqual(instance1.grid.x[1::2], (numpy.arange(2, 11, 2)) | units.m) def test34(self): """ test a grid attribute request, subgrids """ instance1 = ForTesting(self.exefile, redirection="none") - grid=instance1.grid.copy() - request=instance1.grid.request.x - self.assertEqual(request.result(), numpy.arange(1,11) | units.m) + grid = instance1.grid.copy() + request = instance1.grid.request.x + self.assertEqual(request.result(), numpy.arange(1, 11) | units.m) def test35(self): """ test a grid attribute request setter with state""" instance1 = ForTestingWithState(self.exefile, redirection="none") - t1=time.time() + t1 = time.time() instance1.do_sleep(1, return_request=True) self.assertEqual(instance1.get_name_of_current_state(), '1') - instance1.grid.request.x=(11.+numpy.arange(1,11)) |units.m + instance1.grid.request.x = (11.+numpy.arange(1, 11)) | units.m self.assertEqual(instance1.get_name_of_current_state(), '2') - t2=time.time() + t2 = time.time() self.assertGreater(t2-t1, 1.) # first time, state calls dummy (blocking) -> wait - t1=time.time() + t1 = time.time() instance1.do_sleep(1, return_request=True) - instance1.grid.request.x=(12.+numpy.arange(1,11)) |units.m - t2=time.time() + instance1.grid.request.x = (12.+numpy.arange(1, 11)) | units.m + t2 = time.time() self.assertLess(t2-t1, 0.5) # second time should be less - + instance1.async_request.wait() - t2=time.time() + t2 = time.time() self.assertGreater(t2-t1, 1.) - t1=time.time() - self.assertEqual(instance1.grid.x, (12. +numpy.arange(1,11)) | units.m) - t2=time.time() + t1 = time.time() + self.assertEqual(instance1.grid.x, (12. + numpy.arange(1, 11)) | units.m) + t2 = time.time() self.assertLess(t2-t1, 0.5) def test36(self): @@ -841,9 +840,9 @@ def test36(self): # this documents current behaviour: instance1.dummy(return_request=True) self.assertEqual(instance1.get_name_of_current_state(), '1') - instance1.async_request.wait() + instance1.async_request.wait() self.assertEqual(instance1.get_name_of_current_state(), '2') - # ie state changes upon completion of call at wait. This is + # ie state changes upon completion of call at wait. This is # sort of ok, alternatively state could be changed immediately... @@ -853,29 +852,29 @@ class TestASyncDistributed(TestASync): def setup_class(cls): cls.check_not_in_mpiexec() super(TestASyncDistributed, cls).setup_class() - cls.distinstance = cls.new_instance_of_an_optional_code(DistributedAmuse)#, redirection='none') + cls.distinstance = cls.new_instance_of_an_optional_code(DistributedAmuse) # , redirection='none') cls.distinstance.parameters.debug = False - #~ print "Resources:" - #~ print cls.distinstance.resources + # ~ print "Resources:" + # ~ print cls.distinstance.resources pilot = Pilot() - pilot.resource_name='local' - pilot.node_count=1 - pilot.time= 2|units.hour - pilot.slots_per_node=8 - pilot.label='local' + pilot.resource_name = 'local' + pilot.node_count = 1 + pilot.time = 2 | units.hour + pilot.slots_per_node = 8 + pilot.label = 'local' cls.distinstance.pilots.add_pilot(pilot) - #~ print "Pilots:" - #~ print cls.distinstance.pilots + # ~ print "Pilots:" + # ~ print cls.distinstance.pilots - #~ print "Waiting for pilots" + # ~ print "Waiting for pilots" cls.distinstance.wait_for_pilots() cls.distinstance.use_for_all_workers() @classmethod def tearDown(cls): - #~ print "Stopping distributed code" + # ~ print "Stopping distributed code" cls.distinstance.stop() @classmethod @@ -883,7 +882,7 @@ def check_not_in_mpiexec(cls): """ The tests will fork another process, if the test run is itself an mpi process, the tests may fail. - + For the hydra process manager the tests will fail. So skip the tests if we detect hydra """ @@ -892,8 +891,9 @@ def check_not_in_mpiexec(cls): if 'HYDRA_CONTROL_FD' in os.environ or 'PMI_FD' in os.environ: cls.skip('cannot run the socket tests under hydra process manager') -if __name__=="__main__": + +if __name__ == "__main__": TestASync.setup_class() - t=TestASync() - + t = TestASync() + t.test26() diff --git a/src/amuse/test/suite/compile_tests/test_c_distributed_implementation.py b/src/amuse/test/suite/compile_tests/test_c_distributed_implementation.py index c7c397fb55..676e2730eb 100644 --- a/src/amuse/test/suite/compile_tests/test_c_distributed_implementation.py +++ b/src/amuse/test/suite/compile_tests/test_c_distributed_implementation.py @@ -16,37 +16,38 @@ from . import test_c_implementation + class TestCDistributedImplementationInterface(test_c_implementation.TestCImplementationInterface): @classmethod def setup_class(cls): cls.check_not_in_mpiexec() super(TestCDistributedImplementationInterface, cls).setup_class() - #~ print "Setting up distributed code" - #instance = DistributedAmuse(redirection='none') - cls.distinstance = cls.new_instance_of_an_optional_code(DistributedAmuse)#, redirection='none') + # ~ print "Setting up distributed code" + # instance = DistributedAmuse(redirection='none') + cls.distinstance = cls.new_instance_of_an_optional_code(DistributedAmuse) # , redirection='none') cls.distinstance.parameters.debug = False - #~ print "Resources:" - #~ print cls.distinstance.resources + # ~ print "Resources:" + # ~ print cls.distinstance.resources pilot = Pilot() - pilot.resource_name='local' - pilot.node_count=1 - pilot.time= 2|units.hour - pilot.slots_per_node=2 - pilot.label='local' + pilot.resource_name = 'local' + pilot.node_count = 1 + pilot.time = 2 | units.hour + pilot.slots_per_node = 2 + pilot.label = 'local' cls.distinstance.pilots.add_pilot(pilot) - #~ print "Pilots:" - #~ print cls.distinstance.pilots + # ~ print "Pilots:" + # ~ print cls.distinstance.pilots - #~ print "Waiting for pilots" + # ~ print "Waiting for pilots" cls.distinstance.wait_for_pilots() cls.distinstance.use_for_all_workers() @classmethod def tearDown(cls): - #~ print "Stopping distributed code" + # ~ print "Stopping distributed code" cls.distinstance.stop() @classmethod @@ -54,7 +55,7 @@ def check_not_in_mpiexec(cls): """ The tests will fork another process, if the test run is itself an mpi process, the tests may fail. - + For the hydra process manager the tests will fail. So skip the tests if we detect hydra """ @@ -65,4 +66,3 @@ def check_not_in_mpiexec(cls): def test22(self): self.skip("this test uses mpi internals, skip here") - diff --git a/src/amuse/test/suite/compile_tests/test_c_implementation.py b/src/amuse/test/suite/compile_tests/test_c_implementation.py index f07b1cd0f4..aa9f7ea22f 100644 --- a/src/amuse/test/suite/compile_tests/test_c_implementation.py +++ b/src/amuse/test/suite/compile_tests/test_c_implementation.py @@ -145,9 +145,10 @@ } """ + class ForTestingInterface(CodeInterface): include_headers = ['worker_code.h'] - + def __init__(self, exefile, **options): CodeInterface.__init__(self, exefile, **options) @@ -158,8 +159,8 @@ def echo_int(): function.addParameter('int_out', dtype='int32', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def echo_long_long_int(): function = LegacyFunctionSpecification() @@ -167,109 +168,104 @@ def echo_long_long_int(): function.addParameter('out', dtype='int64', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def echo_double(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('double_in', dtype='float64', direction=function.IN) function.addParameter('double_out', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def echo_float(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('float_in', dtype='float32', direction=function.IN) function.addParameter('float_out', dtype='float32', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def echo_string(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('string_in', dtype='string', direction=function.IN) function.addParameter('string_out', dtype='string', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def echo_strings(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('string_inout1', dtype='string', direction=function.INOUT) function.addParameter('string_inout2', dtype='string', direction=function.INOUT) function.result_type = 'int32' function.can_handle_array = True - return function - - + return function + @legacy_function def echo_string_int(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('inint', dtype='int32', direction=function.IN) - function.addParameter('in', dtype='string', direction=function.IN, default = "echo") + function.addParameter('in', dtype='string', direction=function.IN, default="echo") function.addParameter('out', dtype='string', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def echo_string_two(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('in1', dtype='string', direction=function.IN) - function.addParameter('in2', dtype='string', direction=function.IN, default = "echo") + function.addParameter('in2', dtype='string', direction=function.IN, default="echo") function.addParameter('out1', dtype='string', direction=function.OUT) function.addParameter('out2', dtype='string', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - - - + return function + @legacy_function def echo_array(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('int_in', dtype='int32', direction=function.IN) function.addParameter('int_out', dtype='int32', direction=function.OUT) function.addParameter('len', dtype='int32', direction=function.LENGTH) function.result_type = None function.must_handle_array = True return function - + @legacy_function def echo_array_with_result(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('int_in', dtype='int32', direction=function.IN) function.addParameter('int_out', dtype='int32', direction=function.OUT) function.addParameter('len', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True - return function - - #@legacy_function + return function + + # @legacy_function def return_string(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('string_in', dtype='string', direction=function.IN) function.result_type = 'string' function.can_handle_array = True - return function - + return function + @legacy_function def echo_2_int(): function = LegacyFunctionSpecification() function.addParameter('int_in1', dtype='int32', direction=function.IN) - function.addParameter('int_in2', dtype='int32', direction=function.IN, default = 1) + function.addParameter('int_in2', dtype='int32', direction=function.IN, default=1) function.addParameter('int_out1', dtype='int32', direction=function.OUT) function.addParameter('int_out2', dtype='int32', direction=function.OUT) function.addParameter('len', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True - return function - - + return function @legacy_function def echo_3_int(): @@ -277,24 +273,22 @@ def echo_3_int(): function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('j', dtype='int32', direction=function.IN) function.addParameter('k', dtype='int32', direction=function.IN) - function.addParameter('l', dtype='int32', direction=function.IN, default = 0) - function.addParameter('m', dtype='int32', direction=function.IN, default = 1) + function.addParameter('l', dtype='int32', direction=function.IN, default=0) + function.addParameter('m', dtype='int32', direction=function.IN, default=1) function.addParameter('int_out', dtype='int32', direction=function.OUT) function.addParameter('len', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True - return function - + return function + @legacy_function def echo_inout_array_with_result(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('in_out', dtype='int32', direction=function.INOUT) function.addParameter('len', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True - return function - - + return function @legacy_function def echo_logical(): @@ -304,15 +298,15 @@ def echo_logical(): function.result_type = 'int32' function.can_handle_array = True return function - + @legacy_function def print_string(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('string_in', dtype='string', direction=function.IN) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def dummy_3_int(): function = LegacyFunctionSpecification() @@ -320,22 +314,21 @@ def dummy_3_int(): function.addParameter('j', dtype='int32', direction=function.IN) function.addParameter('k', dtype='int32', direction=function.IN) function.result_type = 'int32' - return function - + return function + @legacy_function def print_error_string(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('string_in', dtype='string', direction=function.IN) function.result_type = 'int32' function.can_handle_array = True - return function - - + return function + @legacy_function def sum_doubles(): function = LegacyFunctionSpecification() function.addParameter('double_in1', dtype='float64', direction=function.IN) - function.addParameter('double_in2', dtype='float64', direction=function.IN, default = 1.0) + function.addParameter('double_in2', dtype='float64', direction=function.IN, default=1.0) function.addParameter('double_out', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True @@ -343,15 +336,14 @@ def sum_doubles(): class ForTesting(InCodeComponentImplementation): - + def __init__(self, exefile, **options): InCodeComponentImplementation.__init__(self, ForTestingInterface(exefile, **options), **options) - + def define_methods(self, object): object.add_method( 'echo_int', - (units.m,) - , + (units.m,), ( units.m, object.ERROR_CODE, @@ -371,50 +363,48 @@ def setup_class(cls): print(ex) raise print("done") - + def test1(self): instance = ForTestingInterface(self.exefile) int_out, error = instance.echo_int(10) instance.stop() self.assertEqual(int_out, 10) self.assertEqual(error, 0) - + def test2(self): instance = ForTestingInterface(self.exefile) out, error = instance.echo_double(4.0) instance.stop() self.assertEqual(out, 4.0) self.assertEqual(error, 0) - - + def test3(self): instance = ForTestingInterface(self.exefile) - input = [1,2,3,4] + input = [1, 2, 3, 4] output, errors = instance.echo_int(input) instance.stop() - self.assertEqual(len(errors),4) + self.assertEqual(len(errors), 4) for actual, expected in zip(output, input): self.assertEqual(actual, expected) - + def test4(self): instance = ForTestingInterface(self.exefile) - input = [1.0,2.1,3.3,4.2] + input = [1.0, 2.1, 3.3, 4.2] output, errors = instance.echo_double(input) instance.stop() - self.assertEqual(len(errors),4) + self.assertEqual(len(errors), 4) for actual, expected in zip(output, input): self.assertEqual(actual, expected) - - + def test5(self): instance = ForTestingInterface(self.exefile) out, error = instance.echo_float(4.0) instance.stop() self.assertEqual(out, 4.0) self.assertEqual(error, 0) - + def test6(self): - + instance = ForTestingInterface(self.exefile) out, error = instance.echo_string("abc") instance.stop() @@ -423,9 +413,9 @@ def test6(self): def test7(self): instance = ForTestingInterface(self.exefile) - out, error = instance.echo_string(["abc","def"]) + out, error = instance.echo_string(["abc", "def"]) instance.stop() - + self.assertEqual(error[0], 0) self.assertEqual(error[1], 0) self.assertEqual(out[0], "abc") @@ -435,7 +425,7 @@ def test7b(self): instance = ForTestingInterface(self.exefile) out, error = instance.echo_int(numpy.arange(2000000)) - + self.assertEqual(error, [0]*2000000) self.assertEqual(out, numpy.arange(2000000)) @@ -445,7 +435,7 @@ def test7c(self): instance = ForTestingInterface(self.exefile) out, error = instance.echo_string(["abc"]*10) - + self.assertEqual(error, [0]*10) self.assertEqual(out, ["abc"]*10) @@ -455,7 +445,7 @@ def test7d(self): instance = ForTestingInterface(self.exefile) out, error = instance.echo_string(["abc"]*100000) - + self.assertEqual(error, [0]*100000) self.assertEqual(out, ["abc"]*100000) @@ -463,29 +453,29 @@ def test7d(self): def test8(self): instance = ForTestingInterface(self.exefile) - out1, out2, error = instance.echo_strings("abc","def") + out1, out2, error = instance.echo_strings("abc", "def") instance.stop() - + self.assertEqual(error, 0) self.assertEqual(out1, "def") self.assertEqual(out2, "abc") - + def test9(self): instance = ForTestingInterface(self.exefile) str1_out, str2_out, error = instance.echo_strings(["abc", "def"], ["ghi", "jkl"]) instance.stop() - + self.assertEqual(error[0], 0) self.assertEqual(error[1], 0) self.assertEqual(str1_out[0], "ghi") self.assertEqual(str1_out[1], "jkl") self.assertEqual(str2_out[0], "abc") self.assertEqual(str2_out[1], "def") - + def xtest10(self): """test for ticket #74, 'running out of os file descriptors' - - + + Note: this test takes a very long time, to enable it remove the 'X' infront of the test name, to disable it add an 'X'. @@ -500,49 +490,48 @@ def xtest10(self): print("x:", x) instance.stop() - def test11(self): instance = ForTestingInterface(self.exefile) - (output_ints,) = instance.echo_array([4,5,6]) + (output_ints,) = instance.echo_array([4, 5, 6]) instance.stop() print(output_ints) self.assertEqual(output_ints[0], 4) self.assertEqual(output_ints[1], 5) self.assertEqual(output_ints[2], 6) - + def test12(self): instance = ForTestingInterface(self.exefile) - (output_ints, error) = instance.echo_array_with_result([4,5,6]) + (output_ints, error) = instance.echo_array_with_result([4, 5, 6]) instance.stop() self.assertEqual(output_ints[0], 4) self.assertEqual(output_ints[1], 5) self.assertEqual(output_ints[2], 6) - + self.assertEqual(error[0], -1) self.assertEqual(error[1], -1) self.assertEqual(error[2], -1) - + def test13(self): instance = ForTesting(self.exefile) - self.assertRaises(exceptions.AmuseException, instance.echo_int, [-1, -2]| units.m, - expected_message = "Error when calling 'echo_int' of a '', errorcode is -1") + self.assertRaises(exceptions.AmuseException, instance.echo_int, [-1, -2] | units.m, + expected_message="Error when calling 'echo_int' of a '', errorcode is -1") instance.stop() def test14(self): instance = ForTesting(self.exefile) - self.assertRaises(exceptions.CodeException, lambda : instance.echo_int()) + self.assertRaises(exceptions.CodeException, lambda: instance.echo_int()) old_id = instance.legacy_interface.echo_int.specification.id instance.legacy_interface.echo_int.specification.id = -9 - self.assertRaises(exceptions.CodeException, lambda : instance.echo_int(1 | units.m)) + self.assertRaises(exceptions.CodeException, lambda: instance.echo_int(1 | units.m)) instance.legacy_interface.echo_int.specification.id = old_id instance.echo_int(1 | units.m) instance.stop() def test15(self): instance = ForTesting(self.exefile) - output_ints1, output_ints2 = instance.echo_2_int([1,2],[3,4]) - output_ints3, output_ints4 = instance.echo_2_int([1,2,3]) - output_ints5, output_ints6 = instance.echo_2_int([5],[0]) + output_ints1, output_ints2 = instance.echo_2_int([1, 2], [3, 4]) + output_ints3, output_ints4 = instance.echo_2_int([1, 2, 3]) + output_ints5, output_ints6 = instance.echo_2_int([5], [0]) output_ints7, output_ints8 = instance.echo_2_int([5]) instance.stop() self.assertEqual(output_ints1[1], 2) @@ -558,18 +547,18 @@ def test15(self): def test16(self): instance = ForTesting(self.exefile) - - self.assertRaises(exceptions.AmuseException, lambda : instance.echo_int([])) + + self.assertRaises(exceptions.AmuseException, lambda: instance.echo_int([])) instance.stop() - + def test17(self): instance = ForTestingInterface(self.exefile) - (output_ints, error) = instance.echo_inout_array_with_result([4,5,6]) + (output_ints, error) = instance.echo_inout_array_with_result([4, 5, 6]) instance.stop() self.assertEqual(output_ints[0], 14) self.assertEqual(output_ints[1], 15) self.assertEqual(output_ints[2], 16) - + self.assertEqual(error[0], 11) self.assertEqual(error[1], 11) self.assertEqual(error[2], 11) @@ -580,7 +569,7 @@ def test18(self): instance.stop() self.assertEqual(out, [True, False, True]) self.assertEqual(error, 0) - + def test19(self): instance = ForTestingInterface(self.exefile) print(3935559000370003845) @@ -588,9 +577,9 @@ def test19(self): instance.stop() self.assertEqual(int_out, 3935559000370003845) self.assertEqual(error, 0) - + def xtest20(self): - + # # TURNED OFF support for redirection, # by default output is redirected to /dev/null @@ -600,37 +589,35 @@ def xtest20(self): os.remove("pout.000") if os.path.exists("perr.000"): os.remove("perr.000") - - x = ForTesting(self.exefile, redirect_stderr_file = 'perr', redirect_stdout_file = 'pout', redirection="file") + + x = ForTesting(self.exefile, redirect_stderr_file='perr', redirect_stdout_file='pout', redirection="file") x.print_string("abc") x.print_error_string("exex") x.stop() - + time.sleep(0.2) - + self.assertTrue(os.path.exists("pout.000")) - with open("pout.000","r") as f: + with open("pout.000", "r") as f: content = f.read() self.assertEqual(content.strip(), "abc") - + self.assertTrue(os.path.exists("perr.000")) - with open("perr.000","r") as f: + with open("perr.000", "r") as f: content = f.read() self.assertEqual(content.strip(), "exex") - - x = ForTesting(self.exefile, redirect_stderr_file = 'pout', redirect_stdout_file = 'pout', redirection="file") + + x = ForTesting(self.exefile, redirect_stderr_file='pout', redirect_stdout_file='pout', redirection="file") x.print_string("def") x.print_error_string("exex") x.stop() - + time.sleep(0.2) - + self.assertTrue(os.path.exists("pout.000")) - with open("pout.000","r") as f: + with open("pout.000", "r") as f: content = f.read() self.assertEqual(content.strip(), "abc\ndef\nexex") - - def test21(self): instance = ForTestingInterface(self.exefile) @@ -644,7 +631,7 @@ def test21(self): self.assertEqual(error2, 0) self.assertEqual(error3, 0) self.assertEqual(output2, 1234) - + def test22(self): self.check_for_mpi() instance = ForTestingInterface(self.exefile) @@ -662,12 +649,10 @@ def test22(self): self.assertEqual(error3, 0) self.assertEqual(output2, 500 * 1000) # the following is not necessarily true since polling interval is the maximum wait time - #~ self.assertTrue((t3 - t2) > 0.25) - - + # ~ self.assertTrue((t3 - t2) > 0.25) def test23(self): - + instance = ForTestingInterface(self.exefile) out, error = instance.echo_string_int(1) instance.stop() @@ -675,7 +660,7 @@ def test23(self): self.assertEqual(out, "echo") def test24(self): - + instance = ForTestingInterface(self.exefile) out, error = instance.echo_string_int(1, "abc") instance.stop() @@ -683,36 +668,35 @@ def test24(self): self.assertEqual(out, "abc") def test25(self): - + instance = ForTestingInterface(self.exefile) - out, error = instance.echo_string_int([1,2]) + out, error = instance.echo_string_int([1, 2]) instance.stop() self.assertEqual(error, 0) self.assertEqual(out[0], "echo") self.assertEqual(out[1], "echo") - + def test26(self): - + instance = ForTestingInterface(self.exefile) - out, error = instance.echo_string_int([1,2],["abc","def"]) + out, error = instance.echo_string_int([1, 2], ["abc", "def"]) instance.stop() self.assertEqual(error, 0) self.assertEqual(out[0], "abc") self.assertEqual(out[1], "def") - - + def test27(self): - + instance = ForTestingInterface(self.exefile) - out, error = instance.echo_string_int([1,2], "abc") + out, error = instance.echo_string_int([1, 2], "abc") instance.stop() self.assertEqual(error, 0) self.assertEqual(out[0], "abc") self.assertEqual(out[1], "abc") - + def test28(self): instance = ForTestingInterface(self.exefile) - out1, out2, error = instance.echo_string_two(["one","two"], "three") + out1, out2, error = instance.echo_string_two(["one", "two"], "three") instance.stop() self.assertEqual(error, 0) self.assertEqual(out1[0], "one") @@ -720,7 +704,6 @@ def test28(self): self.assertEqual(out2[0], "three") self.assertEqual(out2[1], "three") - def test29(self): self.check_for_mpi() instance1 = ForTestingInterface(self.exefile) @@ -731,21 +714,19 @@ def test29(self): request2 = instance2.internal__connect_to_port.asynchronous(portname) request1.wait() request2.wait() - port_id1, error1 = request1.result() + port_id1, error1 = request1.result() port_id2, error2 = request2.result() self.assertTrue(port_id1 >= 0) self.assertTrue(port_id2 >= 0) self.assertEqual(error1, 0) self.assertEqual(error2, 0) - def test30(self): from amuse.support.interface import ConvertArgumentsException instance = ForTesting(self.exefile) - self.assertRaises(ConvertArgumentsException,instance.dummy_3_int,2,3,i=1, expected_message= - "got multiple values for argument 'i' of method dummy_3_int") + self.assertRaises(ConvertArgumentsException, instance.dummy_3_int, 2, 3, i=1, expected_message="got multiple values for argument 'i' of method dummy_3_int") instance.stop() - + def test31(self): x = ForTesting(self.exefile, max_message_length=10) N = 100 @@ -758,13 +739,10 @@ def test31(self): doubles = x.echo_double([1.0*i for i in range(N)]) self.assertTrue(list(doubles) == [1.0*i for i in range(N)]) sums = x.sum_doubles([3.0*i for i in range(N)]) - self.assertTrue(list(sums) == [3.0*i +1 for i in range(N)]) + self.assertTrue(list(sums) == [3.0*i + 1 for i in range(N)]) x.stop() - + def test32(self): for i in range(5): - instance = ForTestingInterface(self.exefile) - instance.stop() - - - + instance = ForTestingInterface(self.exefile) + instance.stop() diff --git a/src/amuse/test/suite/compile_tests/test_c_implementation_simplified.py b/src/amuse/test/suite/compile_tests/test_c_implementation_simplified.py index 439615c9c9..ad009bdc3e 100644 --- a/src/amuse/test/suite/compile_tests/test_c_implementation_simplified.py +++ b/src/amuse/test/suite/compile_tests/test_c_implementation_simplified.py @@ -140,98 +140,98 @@ */ """ + class ForTestingInterface(CodeInterface): - + def __init__(self, exefile, **options): CodeInterface.__init__(self, exefile, **options) @remote_function(can_handle_array=True) def echo_int(int_in='int32'): - returns (int_out='int32') - + returns(int_out='int32') + @remote_function(can_handle_array=True) def echo_long_long_int(int_in='int64'): - returns (int_out='int64') - + returns(int_out='int64') + @remote_function(can_handle_array=True) def echo_double(double_in='float64'): - returns (double_out='float64') + returns(double_out='float64') @remote_function(can_handle_array=True) def echo_float(float_in='float32'): - returns (float_out='float32') - + returns(float_out='float32') + @remote_function(can_handle_array=True) def echo_string(string_in='string'): - returns (string_out='string') + returns(string_out='string') @remote_function(can_handle_array=True) - def echo_strings(string_inout1='string',string_inout2='string'): - returns (string_inout1='string',string_inout2='string') - + def echo_strings(string_inout1='string', string_inout2='string'): + returns(string_inout1='string', string_inout2='string') + @remote_function(can_handle_array=True) - def echo_string_int(inint='int32',ins='echo'): - returns (out='string') - + def echo_string_int(inint='int32', ins='echo'): + returns(out='string') + @remote_function(can_handle_array=True) - def echo_string_two(in1='s',in2='echo'): - returns (out1='s',out2='s') - + def echo_string_two(in1='s', in2='echo'): + returns(out1='s', out2='s') + @remote_function(must_handle_array=True) - def echo_array(len,int_in='int32'): - returns (int_out='int32',__result=None) + def echo_array(len, int_in='int32'): + returns(int_out='int32', __result=None) @remote_function(must_handle_array=True) - def echo_array_with_result(len,int_in='int32'): - returns (int_out='int32') - - #~ #@legacy_function - #~ def return_string(): - #~ function = LegacyFunctionSpecification() - #~ function.addParameter('string_in', dtype='string', direction=function.IN) - #~ function.result_type = 'string' - #~ function.can_handle_array = True - #~ return function - + def echo_array_with_result(len, int_in='int32'): + returns(int_out='int32') + + # ~ #@legacy_function + # ~ def return_string(): + # ~ function = LegacyFunctionSpecification() + # ~ function.addParameter('string_in', dtype='string', direction=function.IN) + # ~ function.result_type = 'string' + # ~ function.can_handle_array = True + # ~ return function + @remote_function(must_handle_array=True) - def echo_2_int(N,int_in1='int32',int_in2=numpy.int32(1)): - returns (int_out1='int32',int_out2='int32') - + def echo_2_int(N, int_in1='int32', int_in2=numpy.int32(1)): + returns(int_out1='int32', int_out2='int32') + @remote_function(must_handle_array=True) - def echo_3_int(i='int32',j='int32',k='int32',l=numpy.int32(0),m=numpy.int32(1)): - returns (int_out='int32') - + def echo_3_int(i='int32', j='int32', k='int32', l=numpy.int32(0), m=numpy.int32(1)): + returns(int_out='int32') + @remote_function(must_handle_array=True) def echo_inout_array_with_result(in_out='int32'): - returns (in_out='int32') - + returns(in_out='int32') + @remote_function(can_handle_array=True) def echo_logical(input='bool'): - returns (output='bool') - + returns(output='bool') + @remote_function(can_handle_array=True) def print_string(string_in='string'): pass - + @remote_function - def dummy_3_int(i='i',j='i',k='i'): + def dummy_3_int(i='i', j='i', k='i'): pass - + @remote_function(can_handle_array=True) def print_error_string(string_in='string'): pass - - + + class ForTesting(InCodeComponentImplementation): - + def __init__(self, exefile, **options): InCodeComponentImplementation.__init__(self, ForTestingInterface(exefile, **options), **options) - + def define_methods(self, object): object.add_method( 'echo_int', - (units.m,) - , + (units.m,), ( units.m, object.ERROR_CODE, @@ -239,7 +239,6 @@ def define_methods(self, object): ) - class TestCImplementationInterface(TestWithMPI): @classmethod @@ -247,56 +246,54 @@ def setup_class(cls): print("building...") cls.check_can_compile_modules() try: - cls.exefile = compile_tools.build_worker(codestring, cls.get_path_to_results(), + cls.exefile = compile_tools.build_worker(codestring, cls.get_path_to_results(), ForTestingInterface, write_header=False) except Exception as ex: print(ex) raise print("done") - + def test1(self): instance = ForTestingInterface(self.exefile) int_out, error = instance.echo_int(10) instance.stop() self.assertEqual(int_out, 10) self.assertEqual(error, 0) - + def test2(self): instance = ForTestingInterface(self.exefile) out, error = instance.echo_double(4.0) instance.stop() self.assertEqual(out, 4.0) self.assertEqual(error, 0) - - + def test3(self): instance = ForTestingInterface(self.exefile) - input = [1,2,3,4] + input = [1, 2, 3, 4] output, errors = instance.echo_int(input) instance.stop() - self.assertEqual(len(errors),4) + self.assertEqual(len(errors), 4) for actual, expected in zip(output, input): self.assertEqual(actual, expected) - + def test4(self): instance = ForTestingInterface(self.exefile) - input = [1.0,2.1,3.3,4.2] + input = [1.0, 2.1, 3.3, 4.2] output, errors = instance.echo_double(input) instance.stop() - self.assertEqual(len(errors),4) + self.assertEqual(len(errors), 4) for actual, expected in zip(output, input): self.assertEqual(actual, expected) - - + def test5(self): instance = ForTestingInterface(self.exefile) out, error = instance.echo_float(4.0) instance.stop() self.assertEqual(out, 4.0) self.assertEqual(error, 0) - + def test6(self): - + instance = ForTestingInterface(self.exefile) out, error = instance.echo_string("abc") instance.stop() @@ -305,9 +302,9 @@ def test6(self): def test7(self): instance = ForTestingInterface(self.exefile) - out, error = instance.echo_string(["abc","def"]) + out, error = instance.echo_string(["abc", "def"]) instance.stop() - + self.assertEqual(error[0], 0) self.assertEqual(error[1], 0) self.assertEqual(out[0], "abc") @@ -315,29 +312,29 @@ def test7(self): def test8(self): instance = ForTestingInterface(self.exefile) - out1, out2, error = instance.echo_strings("abc","def") + out1, out2, error = instance.echo_strings("abc", "def") instance.stop() - + self.assertEqual(error, 0) self.assertEqual(out1, "def") self.assertEqual(out2, "abc") - + def test9(self): instance = ForTestingInterface(self.exefile) str1_out, str2_out, error = instance.echo_strings(["abc", "def"], ["ghi", "jkl"]) instance.stop() - + self.assertEqual(error[0], 0) self.assertEqual(error[1], 0) self.assertEqual(str1_out[0], "ghi") self.assertEqual(str1_out[1], "jkl") self.assertEqual(str2_out[0], "abc") self.assertEqual(str2_out[1], "def") - + def xtest10(self): """test for ticket #74, 'running out of os file descriptors' - - + + Note: this test takes a very long time, to enable it remove the 'X' infront of the test name, to disable it add an 'X'. @@ -352,49 +349,48 @@ def xtest10(self): print("x:", x) instance.stop() - def test11(self): instance = ForTestingInterface(self.exefile) - (output_ints,) = instance.echo_array([4,5,6]) + (output_ints,) = instance.echo_array([4, 5, 6]) instance.stop() print(output_ints) self.assertEqual(output_ints[0], 4) self.assertEqual(output_ints[1], 5) self.assertEqual(output_ints[2], 6) - + def test12(self): instance = ForTestingInterface(self.exefile) - (output_ints, error) = instance.echo_array_with_result([4,5,6]) + (output_ints, error) = instance.echo_array_with_result([4, 5, 6]) instance.stop() self.assertEqual(output_ints[0], 4) self.assertEqual(output_ints[1], 5) self.assertEqual(output_ints[2], 6) - + self.assertEqual(error[0], -1) self.assertEqual(error[1], -1) self.assertEqual(error[2], -1) - + def test13(self): instance = ForTesting(self.exefile) - self.assertRaises(exceptions.AmuseException, instance.echo_int, [-1, -2]| units.m, - expected_message = "Error when calling 'echo_int' of a 'ForTesting', errorcode is -1") + self.assertRaises(exceptions.AmuseException, instance.echo_int, [-1, -2] | units.m, + expected_message="Error when calling 'echo_int' of a 'ForTesting', errorcode is -1") instance.stop() def test14(self): instance = ForTesting(self.exefile) - self.assertRaises(exceptions.CodeException, lambda : instance.echo_int()) + self.assertRaises(exceptions.CodeException, lambda: instance.echo_int()) old_id = instance.legacy_interface.echo_int.specification.id instance.legacy_interface.echo_int.specification.id = -9 - self.assertRaises(exceptions.CodeException, lambda : instance.echo_int(1 | units.m)) + self.assertRaises(exceptions.CodeException, lambda: instance.echo_int(1 | units.m)) instance.legacy_interface.echo_int.specification.id = old_id instance.echo_int(1 | units.m) instance.stop() def test15(self): instance = ForTesting(self.exefile) - output_ints1, output_ints2 = instance.echo_2_int([1,2],[3,4]) - output_ints3, output_ints4 = instance.echo_2_int([1,2,3]) - output_ints5, output_ints6 = instance.echo_2_int([5],[0]) + output_ints1, output_ints2 = instance.echo_2_int([1, 2], [3, 4]) + output_ints3, output_ints4 = instance.echo_2_int([1, 2, 3]) + output_ints5, output_ints6 = instance.echo_2_int([5], [0]) output_ints7, output_ints8 = instance.echo_2_int([5]) instance.stop() self.assertEqual(output_ints1[1], 2) @@ -410,18 +406,18 @@ def test15(self): def test16(self): instance = ForTesting(self.exefile) - - self.assertRaises(exceptions.AmuseException, lambda : instance.echo_int([])) + + self.assertRaises(exceptions.AmuseException, lambda: instance.echo_int([])) instance.stop() - + def test17(self): instance = ForTestingInterface(self.exefile) - (output_ints, error) = instance.echo_inout_array_with_result([4,5,6]) + (output_ints, error) = instance.echo_inout_array_with_result([4, 5, 6]) instance.stop() self.assertEqual(output_ints[0], 14) self.assertEqual(output_ints[1], 15) self.assertEqual(output_ints[2], 16) - + self.assertEqual(error[0], 11) self.assertEqual(error[1], 11) self.assertEqual(error[2], 11) @@ -432,7 +428,7 @@ def test18(self): instance.stop() self.assertEqual(out, [True, False, True]) self.assertEqual(error, 0) - + def test19(self): instance = ForTestingInterface(self.exefile) print(3935559000370003845) @@ -440,9 +436,9 @@ def test19(self): instance.stop() self.assertEqual(int_out, 3935559000370003845) self.assertEqual(error, 0) - + def xtest20(self): - + # # TURNED OFF support for redirection, # by default output is redirected to /dev/null @@ -452,37 +448,35 @@ def xtest20(self): os.remove("pout.000") if os.path.exists("perr.000"): os.remove("perr.000") - - x = ForTesting(self.exefile, redirect_stderr_file = 'perr', redirect_stdout_file = 'pout', redirection="file") + + x = ForTesting(self.exefile, redirect_stderr_file='perr', redirect_stdout_file='pout', redirection="file") x.print_string("abc") x.print_error_string("exex") x.stop() - + time.sleep(0.2) - + self.assertTrue(os.path.exists("pout.000")) - with open("pout.000","r") as f: + with open("pout.000", "r") as f: content = f.read() self.assertEqual(content.strip(), "abc") - + self.assertTrue(os.path.exists("perr.000")) - with open("perr.000","r") as f: + with open("perr.000", "r") as f: content = f.read() self.assertEqual(content.strip(), "exex") - - x = ForTesting(self.exefile, redirect_stderr_file = 'pout', redirect_stdout_file = 'pout', redirection="file") + + x = ForTesting(self.exefile, redirect_stderr_file='pout', redirect_stdout_file='pout', redirection="file") x.print_string("def") x.print_error_string("exex") x.stop() - + time.sleep(0.2) - + self.assertTrue(os.path.exists("pout.000")) - with open("pout.000","r") as f: + with open("pout.000", "r") as f: content = f.read() self.assertEqual(content.strip(), "abc\ndef\nexex") - - def test21(self): instance = ForTestingInterface(self.exefile) @@ -496,7 +490,7 @@ def test21(self): self.assertEqual(error2, 0) self.assertEqual(error3, 0) self.assertEqual(output2, 1234) - + def test22(self): self.check_for_mpi() instance = ForTestingInterface(self.exefile) @@ -513,13 +507,11 @@ def test22(self): self.assertEqual(error2, 0) self.assertEqual(error3, 0) self.assertEqual(output2, 500 * 1000) - #~ print t1 - t0, t3 - t2 - #~ self.assertTrue((t3 - t2) > 0.25) - - + # ~ print t1 - t0, t3 - t2 + # ~ self.assertTrue((t3 - t2) > 0.25) def test23(self): - + instance = ForTestingInterface(self.exefile) out, error = instance.echo_string_int(1) instance.stop() @@ -527,7 +519,7 @@ def test23(self): self.assertEqual(out, "echo") def test24(self): - + instance = ForTestingInterface(self.exefile) out, error = instance.echo_string_int(1, "abc") instance.stop() @@ -535,36 +527,35 @@ def test24(self): self.assertEqual(out, "abc") def test25(self): - + instance = ForTestingInterface(self.exefile) - out, error = instance.echo_string_int([1,2]) + out, error = instance.echo_string_int([1, 2]) instance.stop() self.assertEqual(error, 0) self.assertEqual(out[0], "echo") self.assertEqual(out[1], "echo") - + def test26(self): - + instance = ForTestingInterface(self.exefile) - out, error = instance.echo_string_int([1,2],["abc","def"]) + out, error = instance.echo_string_int([1, 2], ["abc", "def"]) instance.stop() self.assertEqual(error, 0) self.assertEqual(out[0], "abc") self.assertEqual(out[1], "def") - - + def test27(self): - + instance = ForTestingInterface(self.exefile) - out, error = instance.echo_string_int([1,2], "abc") + out, error = instance.echo_string_int([1, 2], "abc") instance.stop() self.assertEqual(error, 0) self.assertEqual(out[0], "abc") self.assertEqual(out[1], "abc") - + def test28(self): instance = ForTestingInterface(self.exefile) - out1, out2, error = instance.echo_string_two(["one","two"], "three") + out1, out2, error = instance.echo_string_two(["one", "two"], "three") instance.stop() self.assertEqual(error, 0) self.assertEqual(out1[0], "one") @@ -572,7 +563,6 @@ def test28(self): self.assertEqual(out2[0], "three") self.assertEqual(out2[1], "three") - def test29(self): self.check_for_mpi() instance1 = ForTestingInterface(self.exefile) @@ -583,38 +573,36 @@ def test29(self): request2 = instance2.internal__connect_to_port.asynchronous(portname) request1.wait() request2.wait() - port_id1, error1 = request1.result() + port_id1, error1 = request1.result() port_id2, error2 = request2.result() self.assertTrue(port_id1 >= 0) self.assertTrue(port_id2 >= 0) self.assertEqual(error1, 0) self.assertEqual(error2, 0) - def test30(self): from amuse.support.interface import ConvertArgumentsException instance = ForTesting(self.exefile) - self.assertRaises(ConvertArgumentsException,instance.dummy_3_int,2,3,i=1, expected_message= - "got multiple values for argument 'i' of method dummy_3_int") + self.assertRaises(ConvertArgumentsException, instance.dummy_3_int, 2, 3, i=1, expected_message="got multiple values for argument 'i' of method dummy_3_int") instance.stop() @unittest.skip def test31(self): import time instance = ForTestingInterface(self.exefile) - N=5000 - t1=time.time() + N = 5000 + t1 = time.time() for i in range(N): - res,err= instance.echo_int([i]) - t2=time.time() - print("1 time:",t2-t1,(t2-t1)/N) + res, err = instance.echo_int([i]) + t2 = time.time() + print("1 time:", t2-t1, (t2-t1)/N) instance.stop() instance = ForTesting(self.exefile) - N=5000 - t1=time.time() + N = 5000 + t1 = time.time() for i in range(N): - res= instance.echo_int([i]| units.m) - t2=time.time() - print("2 time:",t2-t1,(t2-t1)/N) + res = instance.echo_int([i] | units.m) + t2 = time.time() + print("2 time:", t2-t1, (t2-t1)/N) instance.stop() diff --git a/src/amuse/test/suite/compile_tests/test_c_sockets_implementation.py b/src/amuse/test/suite/compile_tests/test_c_sockets_implementation.py index 972b1d5f5a..8e4db6c0a4 100644 --- a/src/amuse/test/suite/compile_tests/test_c_sockets_implementation.py +++ b/src/amuse/test/suite/compile_tests/test_c_sockets_implementation.py @@ -15,13 +15,14 @@ from . import test_c_implementation + class TestCSocketsImplementationInterface(test_c_implementation.TestCImplementationInterface): @classmethod def setup_class(cls): cls.check_not_in_mpiexec() - super(TestCSocketsImplementationInterface, cls).setup_class() - #set sockets channel as default channel + super(TestCSocketsImplementationInterface, cls).setup_class() + # set sockets channel as default channel options.GlobalOptions.instance().override_value_for_option("channel_type", "sockets") @classmethod @@ -30,21 +31,20 @@ def teardown_class(cls): def test22(self): self.skip("this test uses mpi internals, skip here") - + def test29(self): self.skip("this test uses mpi internals, skip here") - - @classmethod + + @classmethod def check_not_in_mpiexec(cls): """ The tests will fork another process, if the test run is itself an mpi process, the tests may fail. - + For the hydra process manager the tests will fail. So skip the tests if we detect hydra """ if 'HYDI_CONTROL_FD' in os.environ: - return # for now assume HYDI_CONTROL_FD is newer, and sockets will work! + return # for now assume HYDI_CONTROL_FD is newer, and sockets will work! if 'HYDRA_CONTROL_FD' in os.environ or 'PMI_FD' in os.environ: cls.skip('cannot run the socket tests under mpi process manager') - diff --git a/src/amuse/test/suite/compile_tests/test_fortran_implementation.py b/src/amuse/test/suite/compile_tests/test_fortran_implementation.py index dce731f699..bfab72593b 100644 --- a/src/amuse/test/suite/compile_tests/test_fortran_implementation.py +++ b/src/amuse/test/suite/compile_tests/test_fortran_implementation.py @@ -181,108 +181,102 @@ end function """ + class ForTestingInterface(CodeInterface): - + def __init__(self, exefile, **options): CodeInterface.__init__(self, exefile, **options) - - #use_modules=['code'] - + # use_modules=['code'] @legacy_function def echo_int(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('int_in', dtype='int32', direction=function.IN, unit=units.m) function.addParameter('int_out', dtype='int32', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def echo_double(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('double_in', dtype='float64', direction=function.IN) function.addParameter('double_out', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def echo_float(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('float_in', dtype='float32', direction=function.IN) function.addParameter('float_out', dtype='float32', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def echo_string(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('string_in', dtype='string', direction=function.IN) function.addParameter('string_out', dtype='string', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def echo_strings(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('string_inout1', dtype='string', direction=function.INOUT) function.addParameter('string_inout2', dtype='string', direction=function.INOUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def return_string(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('string_in', dtype='string', direction=function.IN) function.result_type = 'string' function.can_handle_array = True - return function - - + return function + @legacy_function def hello_string(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('string_out', dtype='string', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def echo_string_fixed_len(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('string_in', dtype='string', direction=function.IN) function.addParameter('string_out', dtype='string', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def echo_array_with_result(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('int_in', dtype='int32', direction=function.IN) function.addParameter('int_out', dtype='int32', direction=function.OUT) function.addParameter('len', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function - + @legacy_function def echo_inout_array_with_result(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('in_out', dtype='int32', direction=function.INOUT) function.addParameter('len', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True - return function - - - - + return function @legacy_function def echo_logical(): @@ -303,37 +297,37 @@ def echo_logical2(): function.must_handle_array = True return function - @legacy_function def print_string(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('string_in', dtype='string', direction=function.IN) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def print_error_string(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('string_in', dtype='string', direction=function.IN) function.result_type = 'int32' function.can_handle_array = True - return function + return function @legacy_function def get_element_status(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('index', dtype='i', direction=function.IN) function.addParameter('status', dtype='string', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True return function - + + class ForTesting(InCodeComponentImplementation): - + def __init__(self, exefile, **options): InCodeComponentImplementation.__init__(self, ForTestingInterface(exefile, **options), **options) - + """ def define_methods(self, object): object.add_method( @@ -346,8 +340,10 @@ def define_methods(self, object): ) ) """ + + class TestInterface(TestWithMPI): - + @classmethod def skip_if_fortran_does_not_support_mpi(cls): try: @@ -355,62 +351,60 @@ def skip_if_fortran_does_not_support_mpi(cls): is_configured = hasattr(config, 'compilers') and hasattr(config.compilers, 'fc_iso_c_bindings') except ImportError: is_configured = False - + if is_configured and config.compilers.fc_iso_c_bindings: return else: cls.skip("cannot run test as fortran does not support iso c bindings") - + @classmethod def setup_class(cls): print("building") cls.check_can_compile_modules() - cls.exefile=compile_tools.build_fortran_worker(codestring, cls.get_path_to_results(), ForTestingInterface) + cls.exefile = compile_tools.build_fortran_worker(codestring, cls.get_path_to_results(), ForTestingInterface) print("done") - + def test1(self): instance = ForTestingInterface(self.exefile) int_out, error = instance.echo_int(10) del instance self.assertEqual(int_out, 10) self.assertEqual(error, 0) - + def test2(self): instance = ForTestingInterface(self.exefile) out, error = instance.echo_double(4.0) del instance self.assertEqual(out, 4.0) self.assertEqual(error, 0) - - + def test3(self): instance = ForTestingInterface(self.exefile) - input = [1,2,3,4] + input = [1, 2, 3, 4] output, errors = instance.echo_int(input) del instance - self.assertEqual(len(errors),4) + self.assertEqual(len(errors), 4) for actual, expected in zip(output, input): self.assertEqual(actual, expected) - + def test4(self): instance = ForTestingInterface(self.exefile) - input = [1.0,2.1,3.3,4.2] + input = [1.0, 2.1, 3.3, 4.2] output, errors = instance.echo_double(input) del instance - self.assertEqual(len(errors),4) + self.assertEqual(len(errors), 4) for actual, expected in zip(output, input): self.assertEqual(actual, expected) - - + def test5(self): instance = ForTestingInterface(self.exefile) out, error = instance.echo_float(4.0) del instance self.assertEqual(out, 4.0) self.assertEqual(error, 0) - + def test6(self): - + instance = ForTestingInterface(self.exefile) out, error = instance.echo_string("abc") del instance @@ -419,9 +413,9 @@ def test6(self): def test7(self): instance = ForTestingInterface(self.exefile) - out, error = instance.echo_string(["abc","def"]) + out, error = instance.echo_string(["abc", "def"]) del instance - + self.assertEqual(error[0], 0) self.assertEqual(error[1], 0) self.assertEqual(out[0], "abc") @@ -429,83 +423,81 @@ def test7(self): def test8(self): instance = ForTestingInterface(self.exefile) - out1, out2, error = instance.echo_strings("abc","def") + out1, out2, error = instance.echo_strings("abc", "def") del instance - + self.assertEqual(error, 0) self.assertEqual(out1, "Abc") self.assertEqual(out2, "Bef") - + def test9(self): instance = ForTestingInterface(self.exefile) str1_out, str2_out, error = instance.echo_strings(["abc", "def"], ["ghi", "jkl"]) del instance - + self.assertEqual(error[0], 0) self.assertEqual(error[1], 0) self.assertEqual(str1_out[0], "Abc") self.assertEqual(str1_out[1], "Aef") self.assertEqual(str2_out[0], "Bhi") self.assertEqual(str2_out[1], "Bkl") - + def test10(self): instance = ForTestingInterface(self.exefile) out = instance.return_string("abc") del instance - + self.assertEqual(out, "abc") - + def test11(self): instance = ForTestingInterface(self.exefile) out, error = instance.hello_string() del instance - + self.assertEqual(out, "hello") - + def test12(self): - + instance = ForTestingInterface(self.exefile) out, error = instance.echo_string_fixed_len("abc") del instance self.assertEqual(error, 0) self.assertEqual(out, "abc") - - + def test13(self): instance = ForTestingInterface(self.exefile, debugger="none") - (output_ints, error) = instance.echo_array_with_result([4,5,6]) + (output_ints, error) = instance.echo_array_with_result([4, 5, 6]) instance.stop() print(output_ints, error) self.assertEqual(output_ints[0], 4) self.assertEqual(output_ints[1], 5) self.assertEqual(output_ints[2], 6) - + self.assertEqual(error[0], -1) self.assertEqual(error[1], -1) self.assertEqual(error[2], -1) - - + def test14(self): - + for x in range(4): instance = ForTestingInterface(self.exefile) int_out, error = instance.echo_int(10) instance.stop() self.assertEqual(int_out, 10) self.assertEqual(error, 0) - + def test15(self): instance = ForTestingInterface(self.exefile) - (output_ints, error) = instance.echo_inout_array_with_result([4,5,6]) + (output_ints, error) = instance.echo_inout_array_with_result([4, 5, 6]) instance.stop() self.assertEqual(output_ints[0], 14) self.assertEqual(output_ints[1], 15) self.assertEqual(output_ints[2], 16) - + self.assertEqual(error[0], 11) self.assertEqual(error[1], 11) self.assertEqual(error[2], 11) - + def test16(self): instance = ForTestingInterface(self.exefile) (output1, error1) = instance.echo_logical(True) @@ -518,12 +510,12 @@ def test16(self): def test16b(self): instance = ForTesting(self.exefile) - output = instance.echo_logical([True, True,False, True, False]*256) + output = instance.echo_logical([True, True, False, True, False]*256) self.assertEqual(output, [True, True, False, True, False]*256) def test16c(self): instance = ForTesting(self.exefile, redirection="none") - output = instance.echo_logical2([True, True,False, True, False]*1024) + output = instance.echo_logical2([True, True, False, True, False]*1024) self.assertEqual(output, [True, True, False, True, False]*1024) def xtest20(self): @@ -536,43 +528,40 @@ def xtest20(self): os.remove("pout.000") if os.path.exists("perr.000"): os.remove("perr.000") - - x = ForTestingInterface(self.exefile, redirect_stderr_file = 'perr', redirect_stdout_file = 'pout', redirection="file") + + x = ForTestingInterface(self.exefile, redirect_stderr_file='perr', redirect_stdout_file='pout', redirection="file") x.print_string("abc") x.print_error_string("exex") x.stop() - + time.sleep(0.2) - + self.assertTrue(os.path.exists("pout.000")) - with open("pout.000","r") as f: + with open("pout.000", "r") as f: content = f.read() self.assertEqual(content.strip(), "abc") - + self.assertTrue(os.path.exists("perr.000")) - with open("perr.000","r") as f: + with open("perr.000", "r") as f: content = f.read() self.assertEqual(content.strip(), "exex") - - x = ForTestingInterface(self.exefile, redirect_stderr_file = 'perr', redirect_stdout_file = 'pout', redirection="file") + + x = ForTestingInterface(self.exefile, redirect_stderr_file='perr', redirect_stdout_file='pout', redirection="file") x.print_string("def") x.print_error_string("exex") x.stop() - + time.sleep(0.2) - + self.assertTrue(os.path.exists("pout.000")) - with open("pout.000","r") as f: + with open("pout.000", "r") as f: content = f.read() - self.assertEqual(content.strip(), "abc\n def") - + self.assertEqual(content.strip(), "abc\n def") + self.assertTrue(os.path.exists("perr.000")) - with open("perr.000","r") as f: + with open("perr.000", "r") as f: content = f.read() self.assertEqual(content.strip(), "exex\n exex") - - - def test17(self): self.check_for_mpi() @@ -586,16 +575,11 @@ def test17(self): self.assertEqual(error2, 0) self.assertEqual(error3, 0) self.assertEqual(output2, 1234) - - - - - def test18(self): self.check_for_mpi() self.skip_if_fortran_does_not_support_mpi() - + instance = ForTestingInterface(self.exefile) t0 = time.time() (output1, error1) = instance.internal__get_message_polling_interval() @@ -612,9 +596,8 @@ def test18(self): self.assertEqual(error2, 0) self.assertEqual(error3, 0) self.assertEqual(output2, 500 * 1000) - #~ print t1 - t0, t3 - t2 - #~ self.assertTrue((t3 - t2) > 0.25) - + # ~ print t1 - t0, t3 - t2 + # ~ self.assertTrue((t3 - t2) > 0.25) def test19(self): self.check_for_mpi() @@ -626,62 +609,61 @@ def test19(self): request2 = instance2.internal__connect_to_port.asynchronous(portname) request1.wait() request2.wait() - port_id1, error1 = request1.result() + port_id1, error1 = request1.result() port_id2, error2 = request2.result() self.assertTrue(port_id1 >= 0) self.assertTrue(port_id2 >= 0) self.assertEqual(error1, 0) self.assertEqual(error2, 0) - @unittest.skip def test31(self): import time instance = ForTestingInterface(self.exefile) - N=5000 - t1=time.time() + N = 5000 + t1 = time.time() for i in range(N): - res,err= instance.echo_int([i]) - t2=time.time() - print("1 time:",t2-t1,(t2-t1)/N) + res, err = instance.echo_int([i]) + t2 = time.time() + print("1 time:", t2-t1, (t2-t1)/N) instance.stop() instance = ForTesting(self.exefile) - N=5000 - t1=time.time() + N = 5000 + t1 = time.time() for i in range(N): - res= instance.echo_int([i]| units.m) - t2=time.time() - print("2 time:",t2-t1,(t2-t1)/N) + res = instance.echo_int([i] | units.m) + t2 = time.time() + print("2 time:", t2-t1, (t2-t1)/N) instance.stop() def test32(self): instance = ForTestingInterface(self.exefile) out, error = instance.get_element_status(numpy.arange(10)) del instance - + self.assertEqual(out, ["dry"]*10) def test33(self): instance = ForTestingInterface(self.exefile) out, error = instance.get_element_status(numpy.arange(100)) del instance - + self.assertEqual(out, ["dry"]*100) def test34(self): instance = ForTestingInterface(self.exefile) out, error = instance.echo_string(["abc"]*14) del instance - + self.assertEqual(out, ["abc"]*14) self.assertEqual(error, [0]*14) def test35(self): instance = ForTestingInterface(self.exefile) - out, error = instance.echo_string(["abc","def"]*100000) + out, error = instance.echo_string(["abc", "def"]*100000) del instance - + self.assertEqual(error[0], 0) self.assertEqual(error[1], 0) self.assertEqual(out[-2], "abc") @@ -689,9 +671,9 @@ def test35(self): def test36(self): instance = ForTestingInterface(self.exefile) - N=255 + N = 255 out, error = instance.echo_string("a"*N) del instance - + self.assertEqual(error, 0) self.assertEqual(out, "a"*N) diff --git a/src/amuse/test/suite/compile_tests/test_fortran_sockets_implementation.py b/src/amuse/test/suite/compile_tests/test_fortran_sockets_implementation.py index 7ad12bd217..56e7276deb 100644 --- a/src/amuse/test/suite/compile_tests/test_fortran_sockets_implementation.py +++ b/src/amuse/test/suite/compile_tests/test_fortran_sockets_implementation.py @@ -16,7 +16,7 @@ class ForTesting(InCodeComponentImplementation): - + def __init__(self, exefile, **options): InCodeComponentImplementation.__init__(self, ForTestingInterface(exefile, **options), **options) @@ -29,71 +29,68 @@ def setup_class(cls): cls.check_can_compile_modules() cls.check_fortran_version() cls.check_not_in_mpiexec() - cls.exefile=compile_tools.build_fortran_worker(codestring, cls.get_path_to_results(), ForTestingInterface) + cls.exefile = compile_tools.build_fortran_worker(codestring, cls.get_path_to_results(), ForTestingInterface) print("done") - + @classmethod def check_fortran_version(self): pass - + @classmethod def check_not_in_mpiexec(cls): """ The tests will fork another process, if the test run is itself an mpi process, the tests may fail. - + For the hydra process manager the tests will fail. So skip the tests if we detect hydra """ if 'HYDI_CONTROL_FD' in os.environ: - return # can run in modern mpiexec.hydra + return # can run in modern mpiexec.hydra if 'HYDRA_CONTROL_FD' in os.environ or 'PMI_FD' in os.environ: cls.skip('cannot run the socket tests under hydra process manager') - - + def test1(self): instance = ForTestingInterface(self.exefile, channel_type="sockets") int_out, error = instance.echo_int(10) del instance self.assertEqual(int_out, 10) self.assertEqual(error, 0) - + def test2(self): instance = ForTestingInterface(self.exefile, channel_type="sockets") out, error = instance.echo_double(4.0) del instance self.assertEqual(out, 4.0) self.assertEqual(error, 0) - - + def test3(self): instance = ForTestingInterface(self.exefile, channel_type="sockets") - input = [1,2,3,4] + input = [1, 2, 3, 4] output, errors = instance.echo_int(input) del instance - self.assertEqual(len(errors),4) + self.assertEqual(len(errors), 4) for actual, expected in zip(output, input): self.assertEqual(actual, expected) - + def test4(self): instance = ForTestingInterface(self.exefile, channel_type="sockets") - input = [1.0,2.1,3.3,4.2] + input = [1.0, 2.1, 3.3, 4.2] output, errors = instance.echo_double(input) del instance - self.assertEqual(len(errors),4) + self.assertEqual(len(errors), 4) for actual, expected in zip(output, input): self.assertEqual(actual, expected) - - + def test5(self): instance = ForTestingInterface(self.exefile, channel_type="sockets") out, error = instance.echo_float(4.0) del instance self.assertEqual(out, 4.0) self.assertEqual(error, 0) - + def test6(self): - + instance = ForTestingInterface(self.exefile, channel_type="sockets") out, error = instance.echo_string("abc") del instance @@ -102,9 +99,9 @@ def test6(self): def test7(self): instance = ForTestingInterface(self.exefile, channel_type="sockets") - out, error = instance.echo_string(["abc","def"]) + out, error = instance.echo_string(["abc", "def"]) del instance - + self.assertEqual(error[0], 0) self.assertEqual(error[1], 0) self.assertEqual(out[0], "abc") @@ -112,86 +109,84 @@ def test7(self): def test8(self): instance = ForTestingInterface(self.exefile, channel_type="sockets") - out1, out2, error = instance.echo_strings("abc","def") + out1, out2, error = instance.echo_strings("abc", "def") del instance - + self.assertEqual(error, 0) self.assertEqual(out1, "Abc") self.assertEqual(out2, "Bef") - + def test9(self): instance = ForTestingInterface(self.exefile, channel_type="sockets") str1_out, str2_out, error = instance.echo_strings(["abc", "def"], ["ghi", "jkl"]) del instance - + self.assertEqual(error[0], 0) self.assertEqual(error[1], 0) self.assertEqual(str1_out[0], "Abc") self.assertEqual(str1_out[1], "Aef") self.assertEqual(str2_out[0], "Bhi") self.assertEqual(str2_out[1], "Bkl") - + def test10(self): instance = ForTestingInterface(self.exefile, channel_type="sockets") out = instance.return_string("qwerty") out = instance.return_string("abcdefghi") - + instance.stop() del instance - + self.assertEqual(out, "abcdefghi") - + def test11(self): instance = ForTestingInterface(self.exefile, channel_type="sockets") out, error = instance.hello_string() del instance - + self.assertEqual(out, "hello") - + def test12(self): - + instance = ForTestingInterface(self.exefile, channel_type="sockets") out, error = instance.echo_string_fixed_len("abc") del instance self.assertEqual(error, 0) self.assertEqual(out, "abc") - - + def test13(self): instance = ForTestingInterface(self.exefile, debugger="none", channel_type="sockets") - (output_ints, error) = instance.echo_array_with_result([4,5,6]) + (output_ints, error) = instance.echo_array_with_result([4, 5, 6]) instance.stop() print(output_ints, error) self.assertEqual(output_ints[0], 4) self.assertEqual(output_ints[1], 5) self.assertEqual(output_ints[2], 6) - + self.assertEqual(error[0], -1) self.assertEqual(error[1], -1) self.assertEqual(error[2], -1) - - + def test14(self): - + for x in range(4): instance = ForTestingInterface(self.exefile, channel_type="sockets") int_out, error = instance.echo_int(10) instance.stop() self.assertEqual(int_out, 10) self.assertEqual(error, 0) - + def test15(self): instance = ForTestingInterface(self.exefile, channel_type="sockets") - (output_ints, error) = instance.echo_inout_array_with_result([4,5,6]) + (output_ints, error) = instance.echo_inout_array_with_result([4, 5, 6]) instance.stop() self.assertEqual(output_ints[0], 14) self.assertEqual(output_ints[1], 15) self.assertEqual(output_ints[2], 16) - + self.assertEqual(error[0], 11) self.assertEqual(error[1], 11) self.assertEqual(error[2], 11) - + def test16(self): instance = ForTestingInterface(self.exefile, channel_type="sockets") (output1, error1) = instance.echo_logical(True) @@ -204,14 +199,14 @@ def test16(self): def test16b(self): instance = ForTesting(self.exefile, channel_type="sockets") - output = instance.echo_logical([True, True,False, True, False]) + output = instance.echo_logical([True, True, False, True, False]) self.assertEqual(output, [True, True, False, True, False]) def test16c(self): instance = ForTesting(self.exefile, redirection="none") - output = instance.echo_logical2([True, True,False, True, False]*1024) + output = instance.echo_logical2([True, True, False, True, False]*1024) self.assertEqual(output, [True, True, False, True, False]*1024) - + def xtest20(self): # # TURNED OFF support for redirection, @@ -222,56 +217,56 @@ def xtest20(self): os.remove("pout.000") if os.path.exists("perr.000"): os.remove("perr.000") - - x = ForTestingInterface(self.exefile, redirect_stderr_file = 'perr', redirect_stdout_file = 'pout', redirection="file", channel_type="sockets") + + x = ForTestingInterface(self.exefile, redirect_stderr_file='perr', redirect_stdout_file='pout', redirection="file", channel_type="sockets") x.print_string("abc") x.print_error_string("exex") x.stop() - + time.sleep(0.2) - + self.assertTrue(os.path.exists("pout.000")) - with open("pout.000","r") as f: + with open("pout.000", "r") as f: content = f.read() self.assertEqual(content.strip(), "abc") - + self.assertTrue(os.path.exists("perr.000")) - with open("perr.000","r") as f: + with open("perr.000", "r") as f: content = f.read() self.assertEqual(content.strip(), "exex") - - x = ForTestingInterface(self.exefile, redirect_stderr_file = 'perr', redirect_stdout_file = 'pout', redirection="file", channel_type="sockets") + + x = ForTestingInterface(self.exefile, redirect_stderr_file='perr', redirect_stdout_file='pout', redirection="file", channel_type="sockets") x.print_string("def") x.print_error_string("exex") x.stop() - + time.sleep(0.2) - + self.assertTrue(os.path.exists("pout.000")) - with open("pout.000","r") as f: + with open("pout.000", "r") as f: content = f.read() - self.assertEqual(content.strip(), "abc\n def") - + self.assertEqual(content.strip(), "abc\n def") + self.assertTrue(os.path.exists("perr.000")) - with open("perr.000","r") as f: + with open("perr.000", "r") as f: content = f.read() self.assertEqual(content.strip(), "exex\n exex") - + def test35(self): instance = ForTestingInterface(self.exefile, channel_type="sockets") - out, error = instance.echo_string(["abc","def"]*100000) + out, error = instance.echo_string(["abc", "def"]*100000) del instance - + self.assertEqual(error[0], 0) self.assertEqual(error[1], 0) self.assertEqual(out[-2], "abc") self.assertEqual(out[-1], "def") - + def test36(self): instance = ForTestingInterface(self.exefile, channel_type="sockets") - N=255 + N = 255 out, error = instance.echo_string("a"*N) del instance - + self.assertEqual(error, 0) self.assertEqual(out, "a"*N) diff --git a/src/amuse/test/suite/compile_tests/test_grid_implementation.py b/src/amuse/test/suite/compile_tests/test_grid_implementation.py index da5daebc9e..49f474f73b 100644 --- a/src/amuse/test/suite/compile_tests/test_grid_implementation.py +++ b/src/amuse/test/suite/compile_tests/test_grid_implementation.py @@ -35,32 +35,33 @@ """ + class ForTestingInterface(CodeInterface): include_headers = ['worker_code.h'] - + def __init__(self, exefile, **options): CodeInterface.__init__(self, exefile, **options) @remote_function def set0(a=0. | units.m): - returns () + returns() @remote_function def get0(): - returns (a=0. | units.m) + returns(a=0. | units.m) @remote_function def get_grid0_range(): - returns () + returns() class ForTesting(InCodeComponentImplementation): - + def __init__(self, exefile, **options): InCodeComponentImplementation.__init__(self, ForTestingInterface(exefile, **options), **options) - - def define_grids(self,object): - object.define_grid('grid0', grid_class=datamodel.RectilinearGrid,state_guard="before_new_set_instance") + + def define_grids(self, object): + object.define_grid('grid0', grid_class=datamodel.RectilinearGrid, state_guard="before_new_set_instance") object.set_grid_range('grid0', 'get_grid0_range') object.add_getter('grid0', 'get0', names=['a']) object.add_setter('grid0', 'set0', names=['a']) @@ -69,31 +70,30 @@ def define_grids(self,object): class TestCImplementationInterface(TestWithMPI): def build_worker(self): - + path = os.path.abspath(self.get_path_to_results()) - codefile = os.path.join(path,"code.o") - headerfile = os.path.join(path,"worker_code.h") - interfacefile = os.path.join(path,"interface.o") - self.exefile = os.path.join(path,"c_worker") - + codefile = os.path.join(path, "code.o") + headerfile = os.path.join(path, "worker_code.h") + interfacefile = os.path.join(path, "interface.o") + self.exefile = os.path.join(path, "c_worker") + compile_tools.c_compile(codefile, codestring) - + uc = create_c.GenerateACHeaderStringFromASpecificationClass() uc.specification_class = ForTestingInterface uc.needs_mpi = False - header = uc.result + header = uc.result with open(headerfile, "w") as f: f.write(header) - + uc = create_c.GenerateACSourcecodeStringFromASpecificationClass() uc.specification_class = ForTestingInterface uc.needs_mpi = False - code = uc.result + code = uc.result - compile_tools.cxx_compile(interfacefile, code,extra_args=['-I', path]) - compile_tools.c_build(self.exefile, [interfacefile, codefile] ) - + compile_tools.cxx_compile(interfacefile, code, extra_args=['-I', path]) + compile_tools.c_build(self.exefile, [interfacefile, codefile]) def setUp(self): super(TestCImplementationInterface, self).setUp() @@ -105,7 +105,7 @@ def setUp(self): print(ex) raise print("done") - + def test1(self): instance = ForTestingInterface(self.exefile) error = instance.set0(1) @@ -113,19 +113,19 @@ def test1(self): instance.stop() self.assertEqual(a_out, 1) self.assertEqual(error, 0) - + def test2(self): instance = ForTesting(self.exefile) print(instance.grid0) - instance.grid0.a=12. | units.m - self.assertEqual(instance.grid0.a,12.| units.m) + instance.grid0.a = 12. | units.m + self.assertEqual(instance.grid0.a, 12. | units.m) instance.stop() def test3(self): instance1 = ForTesting(self.exefile) instance2 = ForTesting(self.exefile) - instance1.grid0.a=12. | units.m + instance1.grid0.a = 12. | units.m instance1.grid0.new_channel_to(instance2.grid0).copy_all_attributes() - self.assertEqual(instance2.grid0.a,12.| units.m) + self.assertEqual(instance2.grid0.a, 12. | units.m) instance1.stop() instance2.stop() diff --git a/src/amuse/test/suite/compile_tests/test_java_implementation.py b/src/amuse/test/suite/compile_tests/test_java_implementation.py index 7a4b65f864..ef2585f832 100644 --- a/src/amuse/test/suite/compile_tests/test_java_implementation.py +++ b/src/amuse/test/suite/compile_tests/test_java_implementation.py @@ -178,16 +178,17 @@ } """ + class ForTestingInterface(CodeInterface): classpath = ['worker.jar'] cwd = '' - + def __init__(self, exefile, **options): CodeInterface.__init__(self, exefile, **options) - #override default channel_type. We don't support the mpi channel... - @option(choices=['mpi','remote','distributed', 'sockets'], sections=("channel",)) + # override default channel_type. We don't support the mpi channel... + @option(choices=['mpi', 'remote', 'distributed', 'sockets'], sections=("channel",)) def channel_type(self): return 'sockets' @@ -197,8 +198,8 @@ def echo_int(): function.addParameter('int_in', dtype='int32', direction=function.IN) function.addParameter('int_out', dtype='int32', direction=function.OUT) function.result_type = 'int32' - return function - + return function + @legacy_function def echo_int_array(): function = LegacyFunctionSpecification() @@ -206,7 +207,7 @@ def echo_int_array(): function.addParameter('int_out', dtype='int32', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function + return function @legacy_function def echo_long_long_int(): @@ -215,96 +216,92 @@ def echo_long_long_int(): function.addParameter('out', dtype='int64', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def echo_double(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('double_in', dtype='float64', direction=function.IN) function.addParameter('double_out', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def echo_float(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('float_in', dtype='float32', direction=function.IN) function.addParameter('float_out', dtype='float32', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def echo_string(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('string_in', dtype='string', direction=function.IN) function.addParameter('string_out', dtype='string', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def echo_strings(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('string_inout1', dtype='string', direction=function.INOUT) function.addParameter('string_inout2', dtype='string', direction=function.INOUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def echo_array(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('int_in', dtype='int32', direction=function.IN) function.addParameter('int_out', dtype='int32', direction=function.OUT) function.addParameter('len', dtype='int32', direction=function.LENGTH) function.result_type = None function.must_handle_array = True return function - + @legacy_function def echo_array_with_result(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('int_in', dtype='int32', direction=function.IN) function.addParameter('int_out', dtype='int32', direction=function.OUT) function.addParameter('len', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True - return function - - #@legacy_function + return function + + # @legacy_function def return_string(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('string_in', dtype='string', direction=function.IN) function.result_type = 'string' function.can_handle_array = True - return function - + return function + @legacy_function def echo_2_int(): function = LegacyFunctionSpecification() function.addParameter('int_in1', dtype='int32', direction=function.IN) - function.addParameter('int_in2', dtype='int32', direction=function.IN, default = 1) + function.addParameter('int_in2', dtype='int32', direction=function.IN, default=1) function.addParameter('int_out1', dtype='int32', direction=function.OUT) function.addParameter('int_out2', dtype='int32', direction=function.OUT) function.addParameter('len', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True - return function - - + return function @legacy_function def echo_inout_array_with_result(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('in_out', dtype='int32', direction=function.INOUT) function.addParameter('len', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True - return function - - + return function @legacy_function def echo_logical(): @@ -314,34 +311,33 @@ def echo_logical(): function.result_type = 'int32' function.can_handle_array = True return function - + @legacy_function def print_string(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('string_in', dtype='string', direction=function.IN) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def print_error_string(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('string_in', dtype='string', direction=function.IN) function.result_type = 'int32' function.can_handle_array = True - return function - - + return function + + class ForTesting(InCodeComponentImplementation): - + def __init__(self, exefile, **options): InCodeComponentImplementation.__init__(self, ForTestingInterface(exefile, **options), **options) - + def define_methods(self, object): object.add_method( 'echo_int', - (units.m,) - , + (units.m,), ( units.m, object.ERROR_CODE, @@ -349,92 +345,89 @@ def define_methods(self, object): ) - class TestInterface(TestWithMPI): - + @classmethod def check_not_in_mpiexec(cls): """ The tests will fork another process, if the test run is itself an mpi process, the tests may fail. - + For the hydra process manager the tests will fail. So skip the tests if we detect hydra """ if 'HYDI_CONTROL_FD' in os.environ: - return # can run in modern mpiexec.hydra + return # can run in modern mpiexec.hydra if 'HYDRA_CONTROL_FD' in os.environ or 'PMI_FD' in os.environ: cls.skip('cannot run the socket tests under mpi process manager') - + @classmethod def check_has_java(cls): """ The tests will fork another process, if the test run is itself an mpi process, the tests may fail. - + For the hydra process manager the tests will fail. So skip the tests if we detect hydra """ - + if not config.java.is_enabled: cls.skip("java not enabled") javac = config.java.javac if not os.path.exists(javac): - cls.skip("java compiler not available") - + cls.skip("java compiler not available") + @classmethod def setup_class(cls): cls.check_not_in_mpiexec() cls.check_has_java() cls.check_can_compile_modules() try: - cls.exefile=compile_tools.build_java_worker(codestring, cls.get_path_to_results(),ForTestingInterface) + cls.exefile = compile_tools.build_java_worker(codestring, cls.get_path_to_results(), ForTestingInterface) except Exception as ex: print(ex) raise - + def test1(self): instance = ForTestingInterface(self.exefile) int_out, error = instance.echo_int(10) instance.stop() self.assertEqual(int_out, 10) self.assertEqual(error, 0) - + def test2(self): instance = ForTestingInterface(self.exefile) out, error = instance.echo_double(4.0) instance.stop() self.assertEqual(out, 4.0) self.assertEqual(error, 0) - - + def test3(self): instance = ForTestingInterface(self.exefile) - input = [1,2,3,4] + input = [1, 2, 3, 4] output, errors = instance.echo_int_array(input) instance.stop() - self.assertEqual(len(errors),4) + self.assertEqual(len(errors), 4) for actual, expected in zip(output, input): self.assertEqual(actual, expected) - + def test4(self): instance = ForTestingInterface(self.exefile) - input = [1.0,2.1,3.3,4.2] + input = [1.0, 2.1, 3.3, 4.2] output, errors = instance.echo_double(input) instance.stop() - self.assertEqual(len(errors),4) + self.assertEqual(len(errors), 4) for actual, expected in zip(output, input): self.assertEqual(actual, expected) - - + def test5(self): instance = ForTestingInterface(self.exefile) out, error = instance.echo_float(4.0) instance.stop() self.assertEqual(out, 4.0) self.assertEqual(error, 0) - + def test6(self): instance = ForTestingInterface(self.exefile) out, error = instance.echo_string("abc") @@ -444,9 +437,9 @@ def test6(self): def test7(self): instance = ForTestingInterface(self.exefile) - out, error = instance.echo_string(["abc","def"]) + out, error = instance.echo_string(["abc", "def"]) instance.stop() - + self.assertEqual(error[0], 0) self.assertEqual(error[1], 0) self.assertEqual(out[0], "abc") @@ -454,29 +447,29 @@ def test7(self): def test8(self): instance = ForTestingInterface(self.exefile) - out1, out2, error = instance.echo_strings("abc","def") + out1, out2, error = instance.echo_strings("abc", "def") instance.stop() - + self.assertEqual(error, 0) self.assertEqual(out1, "def") self.assertEqual(out2, "abc") - + def test9(self): instance = ForTestingInterface(self.exefile) str1_out, str2_out, error = instance.echo_strings(["abc", "def"], ["ghi", "jkl"]) instance.stop() - + self.assertEqual(error[0], 0) self.assertEqual(error[1], 0) self.assertEqual(str1_out[0], "ghi") self.assertEqual(str1_out[1], "jkl") self.assertEqual(str2_out[0], "abc") self.assertEqual(str2_out[1], "def") - + def xtest10(self): """test for ticket #74, 'running out of os file descriptors' - - + + Note: this test takes a very long time, to enable it remove the 'X' infront of the test name, to disable it add an 'X'. @@ -489,45 +482,44 @@ def xtest10(self): out, error = instance.echo_float(4.0) instance.stop() - def test11(self): instance = ForTestingInterface(self.exefile) - (output_ints,) = instance.echo_array([4,5,6]) + (output_ints,) = instance.echo_array([4, 5, 6]) instance.stop() self.assertEqual(output_ints[0], 4) self.assertEqual(output_ints[1], 5) self.assertEqual(output_ints[2], 6) - + def test12(self): instance = ForTestingInterface(self.exefile) - (output_ints, error) = instance.echo_array_with_result([4,5,6]) + (output_ints, error) = instance.echo_array_with_result([4, 5, 6]) instance.stop() self.assertEqual(output_ints[0], 4) self.assertEqual(output_ints[1], 5) self.assertEqual(output_ints[2], 6) - + self.assertEqual(error[0], -1) self.assertEqual(error[1], -1) self.assertEqual(error[2], -1) - + def test13(self): instance = ForTesting(self.exefile) - self.assertRaises(exceptions.AmuseException, instance.echo_int, [-1, -2]| units.m, - expected_message = "Error when calling 'echo_int' of a 'ForTesting', errorcode is -1") + self.assertRaises(exceptions.AmuseException, instance.echo_int, [-1, -2] | units.m, + expected_message="Error when calling 'echo_int' of a 'ForTesting', errorcode is -1") instance.stop() def test14(self): instance = ForTesting(self.exefile) - self.assertRaises(exceptions.CodeException, lambda : instance.echo_int()) + self.assertRaises(exceptions.CodeException, lambda: instance.echo_int()) instance.legacy_interface.echo_int.specification.id = -9 - self.assertRaises(exceptions.CodeException, lambda : instance.echo_int(1 | units.m)) + self.assertRaises(exceptions.CodeException, lambda: instance.echo_int(1 | units.m)) instance.stop() def test15(self): instance = ForTesting(self.exefile) - output_ints1, output_ints2 = instance.echo_2_int([1,2],[3,4]) - output_ints3, output_ints4 = instance.echo_2_int([1,2,3]) - output_ints5, output_ints6 = instance.echo_2_int([5],[0]) + output_ints1, output_ints2 = instance.echo_2_int([1, 2], [3, 4]) + output_ints3, output_ints4 = instance.echo_2_int([1, 2, 3]) + output_ints5, output_ints6 = instance.echo_2_int([5], [0]) output_ints7, output_ints8 = instance.echo_2_int([5]) instance.stop() self.assertEqual(output_ints1[1], 2) @@ -543,18 +535,18 @@ def test15(self): def test16(self): instance = ForTesting(self.exefile) - - #self.assertRaises(exceptions.AmuseException, lambda : instance.echo_int([])) + + # self.assertRaises(exceptions.AmuseException, lambda : instance.echo_int([])) instance.stop() - + def test17(self): instance = ForTestingInterface(self.exefile) - (output_ints, error) = instance.echo_inout_array_with_result([4,5,6]) + (output_ints, error) = instance.echo_inout_array_with_result([4, 5, 6]) instance.stop() self.assertEqual(output_ints[0], 14) self.assertEqual(output_ints[1], 15) self.assertEqual(output_ints[2], 16) - + self.assertEqual(error[0], 11) self.assertEqual(error[1], 11) self.assertEqual(error[2], 11) @@ -565,63 +557,62 @@ def test18(self): instance.stop() self.assertEqual(out, [True, False, True]) self.assertEqual(error, 0) - + def test19(self): instance = ForTestingInterface(self.exefile) int_out, error = instance.echo_long_long_int(3935559000370003845) instance.stop() self.assertEqual(int_out, 3935559000370003845) self.assertEqual(error, 0) - - + def test20(self): path = os.path.abspath(self.get_path_to_results()) - output = os.path.join(path,"output.txt") - error = os.path.join(path,"error.txt") - + output = os.path.join(path, "output.txt") + error = os.path.join(path, "error.txt") + if os.path.exists(output): os.remove(output) if os.path.exists(error): os.remove(error) - instance = ForTesting(self.exefile, redirect_stderr_file = error, redirect_stdout_file = output, redirection="file") + instance = ForTesting(self.exefile, redirect_stderr_file=error, redirect_stdout_file=output, redirection="file") instance.print_string("test_string_123") instance.print_error_string("error_string_123") instance.stop() - + time.sleep(0.2) - + self.assertTrue(os.path.exists(output)) - with open(output,"r") as f: + with open(output, "r") as f: content = f.read() self.assertTrue("test_string_123" in content.strip()) - + self.assertTrue(os.path.exists(error)) - with open(error,"r") as f: + with open(error, "r") as f: content = f.read() # some times java generates "Picked up _JAVA_OPTIONS" message, so only test: self.assertTrue(content.strip().endswith("error_string_123")) def test21(self): path = os.path.abspath(self.get_path_to_results()) - output = os.path.join(path,"output.txt") - error = os.path.join(path,"error.txt") + output = os.path.join(path, "output.txt") + error = os.path.join(path, "error.txt") if os.path.exists(output): os.remove(output) if os.path.exists(error): os.remove(error) - instance = ForTesting(self.exefile, redirect_stderr_file = output, redirect_stdout_file = output, redirection="file") + instance = ForTesting(self.exefile, redirect_stderr_file=output, redirect_stdout_file=output, redirection="file") instance.print_string("abcdef") instance.print_error_string("&Hfecd") instance.stop() - + time.sleep(0.2) - + self.assertTrue(os.path.exists(output)) - with open(output,"r") as f: + with open(output, "r") as f: content = f.read() # some times java generates "Picked up _JAVA_OPTIONS" message, so only test: self.assertTrue("abcdef" in content) diff --git a/src/amuse/test/suite/compile_tests/test_python_implementation.py b/src/amuse/test/suite/compile_tests/test_python_implementation.py index acb70b888c..fdd0e82be6 100644 --- a/src/amuse/test/suite/compile_tests/test_python_implementation.py +++ b/src/amuse/test/suite/compile_tests/test_python_implementation.py @@ -24,6 +24,7 @@ from amuse.support import exceptions + class ForTestingInterface(PythonCodeInterface): def __init__(self, **options): @@ -278,7 +279,7 @@ class ForTestingImplementation(object): def __init__(self): self.masses = [0.0] * 100 self._particle_data = numpy.reshape(numpy.arange(300.0), (-1, 3)) - self.maxindex = 0 + self.maxindex = 0 def new_particle(self, mass, other, index_of_the_particle): try: @@ -957,7 +958,7 @@ def test27(self): instance2 = self.ForTestingInterface(redirection="none") encoded_interface = pickle.dumps(instance1, 0) decoded_interface = pickle.loads(encoded_interface) - #pickle.loads(pickle.dumps(instance1,0)) + # pickle.loads(pickle.dumps(instance1,0)) portname, error = instance2.internal__open_port() request1 = instance2.internal__accept_on_port.asynchronous(portname) request2 = instance1.internal__connect_to_port.asynchronous(portname) @@ -982,6 +983,7 @@ def test27(self): def test28(self): x = self.ForTestingInterface() + def next_request(index): if index < 3: return x.sleep.asynchronous(0.1) @@ -1003,6 +1005,7 @@ def test29(self): x = self.ForTestingInterface() y = self.ForTestingInterface() sequenced_requests_indices = [] + def next_request(index): if index < 4: sequenced_requests_indices.append(index) @@ -1046,9 +1049,9 @@ def handle_result(request, index): def test30(self): instance = self.ForTesting() input = [1.0, 2.0, 3.0] - output = instance.sum_doubles(input, 5) + output = instance.sum_doubles(input, 5) self.assertAlmostRelativeEquals(output, [6.0, 7.0, 8.0]) - output = instance.sum_doubles(5, input) + output = instance.sum_doubles(5, input) self.assertAlmostRelativeEquals(output, [6.0, 7.0, 8.0]) def test31(self): @@ -1080,7 +1083,7 @@ def test33(self): def test34(self): x = self.ForTestingInterface() - #self.assertException(x.echo_quantities_error, [20, 30, 40] | units.m) + # self.assertException(x.echo_quantities_error, [20, 30, 40] | units.m) quantity_out, error = x.echo_quantities([20, 30, 40] | units.m) self.assertEqual(error, 0) self.assertEqual(quantity_out, [200, 300, 400] | (units.m/units.s)) @@ -1118,4 +1121,3 @@ def test40(self): out = x.echo_bool([True, False, True]) self.assertEqual(out, [True, False, True]) x.stop() - diff --git a/src/amuse/test/suite/compile_tests/test_python_implementation_mpi.py b/src/amuse/test/suite/compile_tests/test_python_implementation_mpi.py index 1d82278373..b1a9c31a2d 100644 --- a/src/amuse/test/suite/compile_tests/test_python_implementation_mpi.py +++ b/src/amuse/test/suite/compile_tests/test_python_implementation_mpi.py @@ -3,110 +3,114 @@ from amuse.test.amusetest import TestWithMPI from amuse import datamodel -from amuse.rfi.core import PythonCodeInterface, legacy_function,LegacyFunctionSpecification +from amuse.rfi.core import PythonCodeInterface, legacy_function, LegacyFunctionSpecification from amuse.support import exceptions import numpy from mpi4py import MPI + class ForTestingInterface(PythonCodeInterface): - + def __init__(self, **options): - PythonCodeInterface.__init__(self, implementation_factory = ForTestingImplementation, **options) - + PythonCodeInterface.__init__(self, implementation_factory=ForTestingImplementation, **options) + @legacy_function def get_range(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('imin', dtype='int32', direction=function.OUT) function.addParameter('imax', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function - + @legacy_function def get_x(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('index', dtype='int32', direction=function.IN) function.addParameter('x', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function + return function @legacy_function def get_dens(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('index', dtype='int32', direction=function.IN) function.addParameter('dens', dtype='float64', direction=function.OUT) function.addParameter('N', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True - return function + return function + class ForTestingImplementation(object): - + def __init__(self): - self.comm=MPI.COMM_WORLD - self.myrank=self.comm.Get_rank() - self.N=self.comm.Get_size() - self.Ngrid=3*4*5 - n=self.Ngrid//self.N + self.comm = MPI.COMM_WORLD + self.myrank = self.comm.Get_rank() + self.N = self.comm.Get_size() + self.Ngrid = 3*4*5 + n = self.Ngrid//self.N x = (numpy.arange(n)+self.myrank*n)/(1.*self.Ngrid) - self.local_imin=self.myrank*n - self.local_imax=(self.myrank+1)*n-1 + self.local_imin = self.myrank*n + self.local_imax = (self.myrank+1)*n-1 self.dens = x**2 - - def get_range(self,imin,imax): - imin.value=0 - imax.value=self.Ngrid-1 + + def get_range(self, imin, imax): + imin.value = 0 + imax.value = self.Ngrid-1 return 0 - - def get_x(self,index,x): - x.value=index/(1.*self.Ngrid) + + def get_x(self, index, x): + x.value = index/(1.*self.Ngrid) return 0 - def get_dens(self,index,dens,N): - a=(index>=self.local_imin)*(index<=self.local_imax) - _dens=numpy.zeros(N) - _dens[a]=self.dens[index[a]-self.local_imin] - dens.value=numpy.zeros(N) - _dens=self.comm.Reduce(_dens, dens.value, MPI.SUM,root=0) + def get_dens(self, index, dens, N): + a = (index >= self.local_imin)*(index <= self.local_imax) + _dens = numpy.zeros(N) + _dens[a] = self.dens[index[a]-self.local_imin] + dens.value = numpy.zeros(N) + _dens = self.comm.Reduce(_dens, dens.value, MPI.SUM, root=0) return 0 + class ForTesting(InCodeComponentImplementation): - + def __init__(self, **options): InCodeComponentImplementation.__init__(self, ForTestingInterface(**options), **options) - def define_grids(self, object): - object.define_grid('grid',axes_names = ['x'],grid_class=datamodel.CartesianGrid) + def define_grids(self, object): + object.define_grid('grid', axes_names=['x'], grid_class=datamodel.CartesianGrid) object.set_grid_range('grid', 'get_range') object.add_getter('grid', 'get_dens', names=('dens',)) object.add_getter('grid', 'get_x', names=('x',)) - + + class TestInterface(TestWithMPI): - + def ForTesting(self, **options): - options["worker_dir"]=self.get_path_to_results() - return ForTesting( **options) + options["worker_dir"] = self.get_path_to_results() + return ForTesting(**options) + def ForTestingInterface(self, **options): - options["worker_dir"]=self.get_path_to_results() + options["worker_dir"] = self.get_path_to_results() return ForTestingInterface(**options) def test1(self): - interface=self.ForTesting(redirection="none",number_of_workers=1) - x=interface.grid.x - dens=interface.grid.dens - self.assertEqual(x,numpy.arange(60)/60.) - self.assertEqual(dens,x**2) + interface = self.ForTesting(redirection="none", number_of_workers=1) + x = interface.grid.x + dens = interface.grid.dens + self.assertEqual(x, numpy.arange(60)/60.) + self.assertEqual(dens, x**2) interface.stop() - + def test2(self): - for n in [3,5,6]: - interface=self.ForTesting(redirection="none",number_of_workers=n) - x=interface.grid.x - dens=interface.grid.dens - self.assertEqual(x,numpy.arange(60)/60.) - self.assertEqual(dens,x**2) + for n in [3, 5, 6]: + interface = self.ForTesting(redirection="none", number_of_workers=n) + x = interface.grid.x + dens = interface.grid.dens + self.assertEqual(x, numpy.arange(60)/60.) + self.assertEqual(dens, x**2) interface.stop() - diff --git a/src/amuse/test/suite/compile_tests/test_python_sockets_implementation.py b/src/amuse/test/suite/compile_tests/test_python_sockets_implementation.py index b7d43d4e9f..5e7079a245 100644 --- a/src/amuse/test/suite/compile_tests/test_python_sockets_implementation.py +++ b/src/amuse/test/suite/compile_tests/test_python_sockets_implementation.py @@ -15,80 +15,79 @@ from . import test_python_implementation from . import test_python_implementation_mpi - + + class TestInterfaceSockets(test_python_implementation.TestInterface): def setUp(self): self.check_not_in_mpiexec() super(test_python_implementation.TestInterface, self).setUp() - + def check_not_in_mpiexec(self): """ The tests will fork another process, if the test run is itself an mpi process, the tests may fail. - + For the hydra process manager the tests will fail. So skip the tests if we detect hydra """ if 'HYDRA_CONTROL_FD' in os.environ or 'PMI_FD' in os.environ: self.skip('cannot run the socket tests under hydra process manager') - + def ForTesting(self, **options): - options["worker_dir"]=self.get_path_to_results() - options["channel_type"]="sockets" - return test_python_implementation.ForTesting( **options) + options["worker_dir"] = self.get_path_to_results() + options["channel_type"] = "sockets" + return test_python_implementation.ForTesting(**options) + def ForTestingInterface(self, **options): - options["worker_dir"]=self.get_path_to_results() - options["channel_type"]="sockets" + options["worker_dir"] = self.get_path_to_results() + options["channel_type"] = "sockets" return test_python_implementation.ForTestingInterface(**options) - - def test2(self): implementation = test_python_implementation.ForTestingImplementation() x = python_code.PythonImplementation(implementation, test_python_implementation.ForTestingInterface) - + input_message = python_code.SocketMessage(0, 10, 1) input_message.ints = [1] - + output_message = python_code.SocketMessage(0, 10, 1) - + x.handle_message(input_message, output_message) - + self.assertEqual(len(output_message.ints), 1) self.assertEqual(len(output_message.doubles), 1) self.assertEqual(output_message.ints[0], 0) self.assertEqual(output_message.doubles[0], 0.0) - + def test3(self): implementation = test_python_implementation.ForTestingImplementation() x = python_code.PythonImplementation(implementation, test_python_implementation.ForTestingInterface) - + input_message = python_code.SocketMessage(0, 11, 1) input_message.ints = [1] input_message.doubles = [12.0] - + output_message = python_code.SocketMessage(0, 10, 1) - + x.handle_message(input_message, output_message) - + self.assertEqual(len(output_message.ints), 1) self.assertEqual(len(output_message.doubles), 0) self.assertEqual(output_message.ints[0], 0) self.assertEqual(implementation.masses[1], 12.0) - - + def test4(self): implementation = test_python_implementation.ForTestingImplementation() x = python_code.PythonImplementation(implementation, test_python_implementation.ForTestingInterface) - + input_message = python_code.SocketMessage(0, 11, 4) - input_message.ints = [1,2,3,4] - input_message.doubles = [12.0,13.0,14.0,15.0] - + input_message.ints = [1, 2, 3, 4] + input_message.doubles = [12.0, 13.0, 14.0, 15.0] + output_message = python_code.SocketMessage(0, 10, 4) - + x.handle_message(input_message, output_message) - + self.assertEqual(len(output_message.ints), 4) self.assertEqual(len(output_message.doubles), 0) self.assertEqual(output_message.ints[0], 0) @@ -97,48 +96,48 @@ def test4(self): self.assertEqual(implementation.masses[2], 13.0) self.assertEqual(implementation.masses[3], 14.0) self.assertEqual(implementation.masses[4], 15.0) - - + def test8(self): implementation = test_python_implementation.ForTestingImplementation() x = python_code.PythonImplementation(implementation, test_python_implementation.ForTestingInterface) - + input_message = python_code.SocketMessage(0, 12, 1) input_message.ints = [20] - + output_message = python_code.SocketMessage(0, 10, 1) - + x.handle_message(input_message, output_message) - + self.assertEqual(len(output_message.ints), 2) self.assertEqual(output_message.ints[0], 0) self.assertEqual(output_message.ints[1], 20) - + def test27(self): - pass # skip because only supported for mpi channel + pass # skip because only supported for mpi channel + class TestInterfaceSocketsMPI(test_python_implementation_mpi.TestInterface): def setUp(self): self.check_not_in_mpiexec() super(test_python_implementation_mpi.TestInterface, self).setUp() - + def check_not_in_mpiexec(self): """ The tests will fork another process, if the test run is itself an mpi process, the tests may fail. - + For the hydra process manager the tests will fail. So skip the tests if we detect hydra """ if 'HYDRA_CONTROL_FD' in os.environ or 'PMI_FD' in os.environ: self.skip('cannot run the socket tests under hydra process manager') - + def ForTesting(self, **options): - options["worker_dir"]=self.get_path_to_results() - options["channel_type"]="sockets" - return test_python_implementation_mpi.ForTesting( **options) + options["worker_dir"] = self.get_path_to_results() + options["channel_type"] = "sockets" + return test_python_implementation_mpi.ForTesting(**options) + def ForTestingInterface(self, **options): - options["worker_dir"]=self.get_path_to_results() - options["channel_type"]="sockets" + options["worker_dir"] = self.get_path_to_results() + options["channel_type"] = "sockets" return test_python_implementation_mpi.ForTestingInterface(**options) - diff --git a/src/amuse/test/suite/compile_tests/test_stopping_conditions.py b/src/amuse/test/suite/compile_tests/test_stopping_conditions.py index a4347d9934..fda3ea9ae7 100644 --- a/src/amuse/test/suite/compile_tests/test_stopping_conditions.py +++ b/src/amuse/test/suite/compile_tests/test_stopping_conditions.py @@ -2,7 +2,7 @@ from amuse.test import compile_tools from amuse.test.amusetest import get_amuse_root_dir -#cello +# cello from amuse.community.interface import stopping_conditions from amuse.support.interface import InCodeComponentImplementation @@ -118,90 +118,91 @@ END MODULE """ + class ForTestingInterface(CodeInterface, stopping_conditions.StoppingConditionInterface): def __init__(self, exefile, **options): CodeInterface.__init__(self, exefile, **options) include_headers = ['stopcond.h'] + @legacy_function def initialize_code(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.result_type = 'int32' function.can_handle_array = False - return function + return function @legacy_function def reset_stopping_conditions(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.result_type = 'int32' function.can_handle_array = False - return function - + return function + @legacy_function def next_index_for_stopping_condition(): function = LegacyFunctionSpecification() function.result_type = 'int32' function.result_unit = NO_UNIT function.can_handle_array = False - return function - + return function + @legacy_function def set_stopping_condition_info(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('index', dtype='int32', direction=function.IN) function.addParameter('index_of_the_condition', dtype='int32', direction=function.IN) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def set_stopping_condition_particle_index(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('index', dtype='int32', direction=function.IN) function.addParameter('index_of_the_condition', dtype='int32', direction=function.IN) function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.result_type = 'int32' function.can_handle_array = True - return function - - + return function + @legacy_function def mpi_setup_stopping_conditions(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.result_type = 'int32' function.can_handle_array = False - return function - + return function + @legacy_function def mpi_collect_stopping_conditions(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.result_type = 'int32' function.can_handle_array = False - return function - + return function + @legacy_function def mpi_distribute_stopping_conditions(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.result_type = 'int32' function.can_handle_array = False - return function - - + return function + class ForTestingInterfaceFortranModule(ForTestingInterface): use_modules = ['StoppingConditions', 'AmuseInterface'] - + @legacy_function def fire_condition(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('condition_to_set', dtype='int32', direction=function.IN) function.addParameter('particle_index_1', dtype='int32', direction=function.IN) function.addParameter('particle_index_2', dtype='int32', direction=function.IN) - function.addParameter('rank', dtype='int32', direction=function.IN, default = -1) + function.addParameter('rank', dtype='int32', direction=function.IN, default=-1) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + + class ForTesting(InCodeComponentImplementation): def __init__(self, exefile, **options): if 'community_interface' in options: @@ -211,22 +212,22 @@ def __init__(self, exefile, **options): self.stopping_conditions = stopping_conditions.StoppingConditions(self) InCodeComponentImplementation.__init__(self, interface(exefile, **options), **options) self.my_particles = datamodel.Particles() - + def define_methods(self, object): self.stopping_conditions.define_methods(object) - + def new_particle(self, mass): particles = datamodel.Particles(len(mass)) particles.mass = mass self.my_particles.add_particles(particles) return list(range(len(self.my_particles)-len(mass), len(self.my_particles))) - + def get_mass(self, indices): return self.my_particles.mass[indices] - + def delete_particle(self, particle): self.my_particles.remove_particle(particle) - + def define_particle_sets(self, object): object.define_set('particles', 'index_of_the_particle') object.set_new('particles', 'new_particle') @@ -234,48 +235,48 @@ def define_particle_sets(self, object): object.add_getter('particles', 'get_mass', names=("mass",)) self.stopping_conditions.define_particle_set(object) - - + class _AbstractTestInterface(TestWithMPI): @classmethod def get_libname(cls): return "stopcond" - + @classmethod def setup_class(cls): cls.check_can_compile_modules() - cls.exefile=compile_tools.build_worker(codestring, - cls.get_path_to_results(), - cls.get_interface_class(), write_header=False, + cls.exefile = compile_tools.build_worker(codestring, + cls.get_path_to_results(), + cls.get_interface_class(), write_header=False, extra_args=["-L"+get_amuse_root_dir()+"/lib/stopcond", "-l" + cls.get_libname()] ) - + @classmethod def get_interface_class(cls): return ForTestingInterface - + + class TestInterface(_AbstractTestInterface): - + def test1(self): - #~ print self.exefile + # ~ print self.exefile instance = ForTestingInterface(self.exefile) instance.reset_stopping_conditions() next = instance.next_index_for_stopping_condition() next = instance.next_index_for_stopping_condition() instance.stop() self.assertEqual(next, 1) - + def test2(self): - instance = ForTesting(self.exefile) #, debugger = "xterm") + instance = ForTesting(self.exefile) # , debugger = "xterm") instance.initialize_code() self.assertTrue(instance.stopping_conditions.pair_detection.is_supported()) self.assertTrue(instance.stopping_conditions.collision_detection.is_supported()) self.assertFalse(instance.stopping_conditions.escaper_detection.is_supported()) instance.stop() - + def test3(self): - instance = ForTesting(self.exefile) #, debugger = "xterm") + instance = ForTesting(self.exefile) # , debugger = "xterm") instance.initialize_code() self.assertFalse(instance.stopping_conditions.pair_detection.is_enabled()) instance.stopping_conditions.pair_detection.enable() @@ -283,25 +284,25 @@ def test3(self): instance.stopping_conditions.pair_detection.disable() self.assertFalse(instance.stopping_conditions.pair_detection.is_enabled()) instance.stop() - + def test4(self): instance = ForTesting(self.exefile) instance.reset_stopping_conditions() next = instance.next_index_for_stopping_condition() self.assertFalse(instance.stopping_conditions.pair_detection.is_set()) - #~ print next,instance.stopping_conditions.pair_detection.type - instance.set_stopping_condition_info(next,instance.stopping_conditions.pair_detection.type) - + # ~ print next,instance.stopping_conditions.pair_detection.type + instance.set_stopping_condition_info(next, instance.stopping_conditions.pair_detection.type) + self.assertTrue(instance.stopping_conditions.pair_detection.is_set()) instance.stop() - + def test5(self): instance = ForTesting(self.exefile) instance.reset_stopping_conditions() next = instance.next_index_for_stopping_condition() self.assertFalse(instance.stopping_conditions.pair_detection.is_set()) - instance.set_stopping_condition_info(next,instance.stopping_conditions.pair_detection.type) + instance.set_stopping_condition_info(next, instance.stopping_conditions.pair_detection.type) instance.set_stopping_condition_particle_index(next, 0, 11) instance.set_stopping_condition_particle_index(next, 1, 12) self.assertTrue(instance.stopping_conditions.pair_detection.is_set()) @@ -313,21 +314,21 @@ def test6(self): instance = ForTesting(self.exefile) instance.reset_stopping_conditions() next = instance.next_index_for_stopping_condition() - instance.set_stopping_condition_info(next,instance.stopping_conditions.out_of_box_detection.type) + instance.set_stopping_condition_info(next, instance.stopping_conditions.out_of_box_detection.type) self.assertTrue(instance.stopping_conditions.out_of_box_detection.is_set()) instance.stop() - + def test7(self): instance = ForTesting(self.exefile) particles = datamodel.Particles(20) particles.mass = range(1, 21) | units.kg instance.particles.add_particles(particles) instance.reset_stopping_conditions() - + pairs = [(11, 12), (0, 4), (3, 18), (7, 2)] next = instance.next_index_for_stopping_condition() self.assertFalse(instance.stopping_conditions.pair_detection.is_set()) - instance.set_stopping_condition_info(next,instance.stopping_conditions.pair_detection.type) + instance.set_stopping_condition_info(next, instance.stopping_conditions.pair_detection.type) instance.set_stopping_condition_particle_index(next, 0, pairs[0][0]) instance.set_stopping_condition_particle_index(next, 1, pairs[0][1]) self.assertEqual(11, instance.get_stopping_condition_particle_index(next, 0)) @@ -335,10 +336,10 @@ def test7(self): self.assertTrue(instance.stopping_conditions.pair_detection.is_set()) self.assertEqual(len(instance.stopping_conditions.pair_detection.particles(0)), 1) self.assertEqual(len(instance.stopping_conditions.pair_detection.particles(1)), 1) - + for index1, index2 in pairs[1:]: next = instance.next_index_for_stopping_condition() - instance.set_stopping_condition_info(next,instance.stopping_conditions.pair_detection.type) + instance.set_stopping_condition_info(next, instance.stopping_conditions.pair_detection.type) instance.set_stopping_condition_particle_index(next, 0, index1) instance.set_stopping_condition_particle_index(next, 1, index2) self.assertEqual(index1, instance.get_stopping_condition_particle_index(next, 0)) @@ -346,48 +347,47 @@ def test7(self): self.assertEqual(len(instance.stopping_conditions.pair_detection.particles(0)), 4) self.assertEqual(len(instance.stopping_conditions.pair_detection.particles(1)), 4) self.assertEqual(len(instance.stopping_conditions.pair_detection.particles(2)), 0) - - self.assertEqual(instance.stopping_conditions.pair_detection.particles(0).mass, + + self.assertEqual(instance.stopping_conditions.pair_detection.particles(0).mass, [first + 1 for first, second in pairs] | units.kg) - self.assertEqual(instance.stopping_conditions.pair_detection.particles(1).mass, + self.assertEqual(instance.stopping_conditions.pair_detection.particles(1).mass, [second + 1 for first, second in pairs] | units.kg) instance.stop() - + def test8(self): instance = ForTesting(self.exefile) instance.initialize_code() self.assertFalse(instance.stopping_conditions.escaper_detection.is_supported()) - self.assertRaises(AmuseException, instance.stopping_conditions.escaper_detection.enable, expected_message= - "Can't enable stopping condition 'escaper_detection', since 'ForTesting' does not support this condition.") + self.assertRaises(AmuseException, instance.stopping_conditions.escaper_detection.enable, expected_message="Can't enable stopping condition 'escaper_detection', since 'ForTesting' does not support this condition.") instance.stop() - - + def test9(self): instance = ForTestingInterface(self.exefile) instance.reset_stopping_conditions() nmax = 2048 for i in range(nmax): next = instance.next_index_for_stopping_condition() - #~ print i, next + # ~ print i, next self.assertEqual(next, i) instance.stop() - + + class TestInterfaceMP(_AbstractTestInterface): - @classmethod + @classmethod def get_interface_class(self): return ForTestingInterfaceFortranModule - + def get_number_of_workers(self): return 3 - + @classmethod def get_libname(self): return "stopcondmpi" - + def test1(self): number_of_workers = 4 - instance = ForTestingInterface(self.exefile, number_of_workers = number_of_workers) + instance = ForTestingInterface(self.exefile, number_of_workers=number_of_workers) instance.reset_stopping_conditions() instance.mpi_setup_stopping_conditions() instance.enable_stopping_condition(1) @@ -402,104 +402,102 @@ def test1(self): i, error = instance.get_number_of_stopping_conditions_set() self.assertEqual(error, 0) self.assertEqual(i, number_of_workers * nmax) - + instance.stop() - - + def test2(self): instance = ForTesting( - self.exefile, - community_interface = ForTestingInterfaceFortranModule, - number_of_workers = self.get_number_of_workers() + self.exefile, + community_interface=ForTestingInterfaceFortranModule, + number_of_workers=self.get_number_of_workers() ) instance.initialize_code() instance.reset_stopping_conditions() instance.mpi_setup_stopping_conditions() - + pair_detection = instance.stopping_conditions.pair_detection - + particles = datamodel.Particles(20) particles.mass = range(1, 21) | units.kg instance.particles.add_particles(particles) - + instance.stopping_conditions.pair_detection.enable() - + instance.mpi_distribute_stopping_conditions() - - #~ print pair_detection.type + + # ~ print pair_detection.type instance.fire_condition( pair_detection.type, 1, 2, -1 ) instance.mpi_collect_stopping_conditions() self.assertTrue(pair_detection.is_set()) - self.assertEqual(len(pair_detection.particles(0)),self.get_number_of_workers()) - self.assertEqual(len(pair_detection.particles(1)),self.get_number_of_workers()) - self.assertEqual(pair_detection.particles(0).key,particles[1].key) - self.assertEqual(pair_detection.particles(1).key,particles[2].key) - self.assertEqual(pair_detection.particles(0).mass,[2,2,2] | units.kg) - self.assertEqual(pair_detection.particles(1).mass,[3,3,3] | units.kg) + self.assertEqual(len(pair_detection.particles(0)), self.get_number_of_workers()) + self.assertEqual(len(pair_detection.particles(1)), self.get_number_of_workers()) + self.assertEqual(pair_detection.particles(0).key, particles[1].key) + self.assertEqual(pair_detection.particles(1).key, particles[2].key) + self.assertEqual(pair_detection.particles(0).mass, [2, 2, 2] | units.kg) + self.assertEqual(pair_detection.particles(1).mass, [3, 3, 3] | units.kg) instance.stop() - - + def test5(self): instance = ForTesting( - self.exefile, - community_interface = ForTestingInterfaceFortranModule, - number_of_workers = self.get_number_of_workers() + self.exefile, + community_interface=ForTestingInterfaceFortranModule, + number_of_workers=self.get_number_of_workers() ) instance.initialize_code() instance.reset_stopping_conditions() instance.mpi_setup_stopping_conditions() - + pair_detection = instance.stopping_conditions.pair_detection - + particles = datamodel.Particles(20) particles.mass = range(1, 21) | units.kg instance.particles.add_particles(particles) - + instance.stopping_conditions.pair_detection.enable() - + instance.mpi_distribute_stopping_conditions() for rank in range(self.get_number_of_workers()): - #~ print pair_detection.type + # ~ print pair_detection.type instance.fire_condition( pair_detection.type, 1, 2, rank ) instance.mpi_collect_stopping_conditions() self.assertTrue(pair_detection.is_set()) - self.assertEqual(len(pair_detection.particles(0)),1) - self.assertEqual(len(pair_detection.particles(1)),1) - self.assertEqual(pair_detection.particles(0).key,particles[1].key) - self.assertEqual(pair_detection.particles(1).key,particles[2].key) - self.assertEqual(pair_detection.particles(0).mass,[2] | units.kg) - self.assertEqual(pair_detection.particles(1).mass,[3] | units.kg) + self.assertEqual(len(pair_detection.particles(0)), 1) + self.assertEqual(len(pair_detection.particles(1)), 1) + self.assertEqual(pair_detection.particles(0).key, particles[1].key) + self.assertEqual(pair_detection.particles(1).key, particles[2].key) + self.assertEqual(pair_detection.particles(0).mass, [2] | units.kg) + self.assertEqual(pair_detection.particles(1).mass, [3] | units.kg) instance.reset_stopping_conditions() instance.stopping_conditions.pair_detection.enable() - + instance.stop() def test3(self): instance = ForTesting( - self.exefile, - community_interface = ForTestingInterfaceFortranModule, - number_of_workers = self.get_number_of_workers() + self.exefile, + community_interface=ForTestingInterfaceFortranModule, + number_of_workers=self.get_number_of_workers() ) instance.initialize_code() instance.reset_stopping_conditions() instance.mpi_setup_stopping_conditions() - + pair_detection = instance.stopping_conditions.pair_detection - + particles = datamodel.Particles(20) particles.mass = range(1, 21) | units.kg instance.particles.add_particles(particles) - + instance.stopping_conditions.pair_detection.enable() - + instance.mpi_distribute_stopping_conditions() - + instance.fire_condition( pair_detection.type, 1, 2, 0 @@ -514,90 +512,87 @@ def test3(self): ) instance.mpi_collect_stopping_conditions() self.assertTrue(pair_detection.is_set()) - self.assertEqual(len(pair_detection.particles(0)),3) - self.assertEqual(len(pair_detection.particles(1)),3) - self.assertEqual(pair_detection.particles(0).key[0],particles[1].key) - self.assertEqual(pair_detection.particles(1).key[0],particles[2].key) - self.assertEqual(pair_detection.particles(0).key[1],particles[3].key) - self.assertEqual(pair_detection.particles(1).key[1],particles[4].key) - self.assertEqual(pair_detection.particles(0).key[2],particles[5].key) - self.assertEqual(pair_detection.particles(1).key[2],particles[6].key) + self.assertEqual(len(pair_detection.particles(0)), 3) + self.assertEqual(len(pair_detection.particles(1)), 3) + self.assertEqual(pair_detection.particles(0).key[0], particles[1].key) + self.assertEqual(pair_detection.particles(1).key[0], particles[2].key) + self.assertEqual(pair_detection.particles(0).key[1], particles[3].key) + self.assertEqual(pair_detection.particles(1).key[1], particles[4].key) + self.assertEqual(pair_detection.particles(0).key[2], particles[5].key) + self.assertEqual(pair_detection.particles(1).key[2], particles[6].key) instance.reset_stopping_conditions() instance.stopping_conditions.pair_detection.enable() - + instance.stop() - - def test4(self): instance = ForTesting( - self.exefile, - community_interface = ForTestingInterfaceFortranModule, - number_of_workers = self.get_number_of_workers() + self.exefile, + community_interface=ForTestingInterfaceFortranModule, + number_of_workers=self.get_number_of_workers() ) instance.initialize_code() instance.reset_stopping_conditions() instance.mpi_setup_stopping_conditions() - + pair_detection = instance.stopping_conditions.pair_detection - + particles = datamodel.Particles(20) particles.mass = range(1, 21) | units.kg instance.particles.add_particles(particles) - + instance.stopping_conditions.pair_detection.enable() - + instance.mpi_collect_stopping_conditions() - + instance.fire_condition( pair_detection.type, -1, -1, -1 ) instance.mpi_distribute_stopping_conditions() self.assertTrue(pair_detection.is_set()) - self.assertEqual(len(pair_detection.particles(0)),0) - + self.assertEqual(len(pair_detection.particles(0)), 0) + instance.stop() - class _AbstractTestInterfaceFortran: - + @classmethod def get_libname(cls): return 'stopcond' - + @classmethod def get_mpidir(cls): return '' - + @classmethod def get_codestring(cls): return codestringF - @classmethod + @classmethod def get_interface_class(cls): return ForTestingInterface - + def get_number_of_workers(self): return 1 - + @classmethod def setup_class(cls): cls.check_can_compile_modules() - cls.exefile=compile_tools.build_fortran_worker(cls.get_codestring(), - cls.get_path_to_results(), cls.get_interface_class(), needs_mpi= True, - extra_fflags = ["-I","{0}/lib/stopcond".format( get_amuse_root_dir())], - extra_ldflags = ["-L{0}/lib/stopcond".format(get_amuse_root_dir()), "-l"+cls.get_libname()] ) + cls.exefile = compile_tools.build_fortran_worker(cls.get_codestring(), + cls.get_path_to_results(), cls.get_interface_class(), needs_mpi=True, + extra_fflags=["-I", "{0}/lib/stopcond".format(get_amuse_root_dir())], + extra_ldflags=["-L{0}/lib/stopcond".format(get_amuse_root_dir()), "-l"+cls.get_libname()]) class _TestInterfaceFortranSingleProcess(TestWithMPI, _AbstractTestInterfaceFortran): - + def get_number_of_workers(self): return 1 - + def test1(self): - instance = ForTestingInterface(self.exefile, number_of_workers = self.get_number_of_workers()) + instance = ForTestingInterface(self.exefile, number_of_workers=self.get_number_of_workers()) instance.reset_stopping_conditions() next = instance.next_index_for_stopping_condition() next = instance.next_index_for_stopping_condition() @@ -605,7 +600,7 @@ def test1(self): self.assertEqual(next, 1) def test2(self): - instance = ForTesting(self.exefile, number_of_workers = self.get_number_of_workers()) #, debugger = "xterm") + instance = ForTesting(self.exefile, number_of_workers=self.get_number_of_workers()) # , debugger = "xterm") instance.initialize_code() self.assertTrue(instance.stopping_conditions.pair_detection.is_supported()) self.assertTrue(instance.stopping_conditions.collision_detection.is_supported()) @@ -613,7 +608,7 @@ def test2(self): instance.stop() def test3(self): - instance = ForTesting(self.exefile, number_of_workers = self.get_number_of_workers()) #, debugger = "xterm") + instance = ForTesting(self.exefile, number_of_workers=self.get_number_of_workers()) # , debugger = "xterm") instance.initialize_code() self.assertFalse(instance.stopping_conditions.pair_detection.is_enabled()) instance.stopping_conditions.pair_detection.enable() @@ -622,44 +617,43 @@ def test3(self): self.assertFalse(instance.stopping_conditions.pair_detection.is_enabled()) instance.stop() - def test4(self): - instance = ForTesting(self.exefile, number_of_workers = self.get_number_of_workers()) + instance = ForTesting(self.exefile, number_of_workers=self.get_number_of_workers()) instance.reset_stopping_conditions() next = instance.next_index_for_stopping_condition() self.assertFalse(instance.stopping_conditions.pair_detection.is_set()) - - instance.set_stopping_condition_info(next,instance.stopping_conditions.pair_detection.type) - + + instance.set_stopping_condition_info(next, instance.stopping_conditions.pair_detection.type) + self.assertTrue(instance.stopping_conditions.pair_detection.is_set()) instance.stop() - + def test5(self): - instance = ForTesting(self.exefile, number_of_workers = self.get_number_of_workers()) + instance = ForTesting(self.exefile, number_of_workers=self.get_number_of_workers()) instance.reset_stopping_conditions() next = instance.next_index_for_stopping_condition() self.assertFalse(instance.stopping_conditions.pair_detection.is_set()) - - instance.set_stopping_condition_info(next,instance.stopping_conditions.pair_detection.type) + + instance.set_stopping_condition_info(next, instance.stopping_conditions.pair_detection.type) instance.set_stopping_condition_particle_index(next, 0, 11) instance.set_stopping_condition_particle_index(next, 1, 12) self.assertTrue(instance.stopping_conditions.pair_detection.is_set()) self.assertEqual(11, instance.get_stopping_condition_particle_index(next, 0)) self.assertEqual(12, instance.get_stopping_condition_particle_index(next, 1)) instance.stop() - + def test6(self): - instance = ForTesting(self.exefile, number_of_workers = self.get_number_of_workers()) + instance = ForTesting(self.exefile, number_of_workers=self.get_number_of_workers()) particles = datamodel.Particles(20) particles.mass = range(1, 21) | units.kg instance.particles.add_particles(particles) instance.reset_stopping_conditions() - + pairs = [(11, 12), (0, 4), (3, 18), (7, 2)] next = instance.next_index_for_stopping_condition() self.assertFalse(instance.stopping_conditions.pair_detection.is_set()) - instance.set_stopping_condition_info(next,instance.stopping_conditions.pair_detection.type) + instance.set_stopping_condition_info(next, instance.stopping_conditions.pair_detection.type) instance.set_stopping_condition_particle_index(next, 0, pairs[0][0]) instance.set_stopping_condition_particle_index(next, 1, pairs[0][1]) self.assertEqual(11, instance.get_stopping_condition_particle_index(next, 0)) @@ -667,10 +661,10 @@ def test6(self): self.assertTrue(instance.stopping_conditions.pair_detection.is_set()) self.assertEqual(len(instance.stopping_conditions.pair_detection.particles(0)), 1) self.assertEqual(len(instance.stopping_conditions.pair_detection.particles(1)), 1) - + for index1, index2 in pairs[1:]: next = instance.next_index_for_stopping_condition() - instance.set_stopping_condition_info(next,instance.stopping_conditions.pair_detection.type) + instance.set_stopping_condition_info(next, instance.stopping_conditions.pair_detection.type) instance.set_stopping_condition_particle_index(next, 0, index1) instance.set_stopping_condition_particle_index(next, 1, index2) self.assertEqual(index1, instance.get_stopping_condition_particle_index(next, 0)) @@ -678,178 +672,176 @@ def test6(self): self.assertEqual(len(instance.stopping_conditions.pair_detection.particles(0)), 4) self.assertEqual(len(instance.stopping_conditions.pair_detection.particles(1)), 4) self.assertEqual(len(instance.stopping_conditions.pair_detection.particles(2)), 0) - - self.assertEqual(instance.stopping_conditions.pair_detection.particles(0).mass, + + self.assertEqual(instance.stopping_conditions.pair_detection.particles(0).mass, [first + 1 for first, second in pairs] | units.kg) - self.assertEqual(instance.stopping_conditions.pair_detection.particles(1).mass, + self.assertEqual(instance.stopping_conditions.pair_detection.particles(1).mass, [second + 1 for first, second in pairs] | units.kg) instance.stop() - + def test8(self): - instance = ForTesting(self.exefile, number_of_workers = self.get_number_of_workers()) + instance = ForTesting(self.exefile, number_of_workers=self.get_number_of_workers()) instance.initialize_code() self.assertFalse(instance.stopping_conditions.escaper_detection.is_supported()) - self.assertRaises(AmuseException, instance.stopping_conditions.escaper_detection.enable, expected_message= - "Can't enable stopping condition 'escaper_detection', since 'ForTesting' does not support this condition.") + self.assertRaises(AmuseException, instance.stopping_conditions.escaper_detection.enable, expected_message="Can't enable stopping condition 'escaper_detection', since 'ForTesting' does not support this condition.") instance.stop() - + def test9(self): - instance = ForTestingInterface(self.exefile, number_of_workers = self.get_number_of_workers()) + instance = ForTestingInterface(self.exefile, number_of_workers=self.get_number_of_workers()) instance.initialize_code() instance.reset_stopping_conditions() nmax = 2048 for i in range(nmax): next = instance.next_index_for_stopping_condition() - #~ print i, next + # ~ print i, next self.assertEqual(next, i) instance.stop() - - + class TestInterfaceFortran(_TestInterfaceFortranSingleProcess): - + @classmethod def get_libname(cls): return 'stopcond' - + @classmethod def get_codestring(cls): return codestringF - @classmethod + @classmethod def get_interface_class(cls): return ForTestingInterface - + + class TestInterfaceFortranModule(_TestInterfaceFortranSingleProcess): - + @classmethod def get_libname(cls): return 'stopcond' - @classmethod + @classmethod def get_codestring(cls): return codestringFModule - @classmethod + @classmethod def get_interface_class(cls): return ForTestingInterfaceFortranModule - + + class TestInterfaceFortranModuleMultiprocess(TestWithMPI, _AbstractTestInterfaceFortran): - + @classmethod def get_libname(cls): return 'stopcondmpi' - @classmethod + @classmethod def get_codestring(cls): return codestringFModule - + @classmethod def get_interface_class(cls): return ForTestingInterfaceFortranModule - + def get_number_of_workers(self): return 3 - + @classmethod def get_mpidir(self): return '' - + def test1(self): instance = ForTesting( - self.exefile, - community_interface = ForTestingInterfaceFortranModule, - number_of_workers = self.get_number_of_workers() + self.exefile, + community_interface=ForTestingInterfaceFortranModule, + number_of_workers=self.get_number_of_workers() ) instance.initialize_code() instance.reset_stopping_conditions() instance.mpi_setup_stopping_conditions() - + pair_detection = instance.stopping_conditions.pair_detection - + particles = datamodel.Particles(20) particles.mass = range(1, 21) | units.kg instance.particles.add_particles(particles) - + instance.stopping_conditions.pair_detection.enable() - + instance.mpi_distribute_stopping_conditions() - - #~ print pair_detection.type + + # ~ print pair_detection.type instance.fire_condition( pair_detection.type, 1, 2, -1 ) instance.mpi_collect_stopping_conditions() self.assertTrue(pair_detection.is_set()) - self.assertEqual(len(pair_detection.particles(0)),self.get_number_of_workers()) - self.assertEqual(len(pair_detection.particles(1)),self.get_number_of_workers()) - self.assertEqual(pair_detection.particles(0).key,particles[1].key) - self.assertEqual(pair_detection.particles(1).key,particles[2].key) - self.assertEqual(pair_detection.particles(0).mass,[2,2,2] | units.kg) - self.assertEqual(pair_detection.particles(1).mass,[3,3,3] | units.kg) + self.assertEqual(len(pair_detection.particles(0)), self.get_number_of_workers()) + self.assertEqual(len(pair_detection.particles(1)), self.get_number_of_workers()) + self.assertEqual(pair_detection.particles(0).key, particles[1].key) + self.assertEqual(pair_detection.particles(1).key, particles[2].key) + self.assertEqual(pair_detection.particles(0).mass, [2, 2, 2] | units.kg) + self.assertEqual(pair_detection.particles(1).mass, [3, 3, 3] | units.kg) instance.stop() - - - + def test2(self): instance = ForTesting( - self.exefile, - community_interface = ForTestingInterfaceFortranModule, - number_of_workers = self.get_number_of_workers() + self.exefile, + community_interface=ForTestingInterfaceFortranModule, + number_of_workers=self.get_number_of_workers() ) instance.initialize_code() instance.reset_stopping_conditions() instance.mpi_setup_stopping_conditions() - + pair_detection = instance.stopping_conditions.pair_detection - + particles = datamodel.Particles(20) particles.mass = range(1, 21) | units.kg instance.particles.add_particles(particles) - + instance.stopping_conditions.pair_detection.enable() - + instance.mpi_distribute_stopping_conditions() for rank in range(self.get_number_of_workers()): - #~ print pair_detection.type + # ~ print pair_detection.type instance.fire_condition( pair_detection.type, 1, 2, rank ) instance.mpi_collect_stopping_conditions() self.assertTrue(pair_detection.is_set()) - self.assertEqual(len(pair_detection.particles(0)),1) - self.assertEqual(len(pair_detection.particles(1)),1) - self.assertEqual(pair_detection.particles(0).key,particles[1].key) - self.assertEqual(pair_detection.particles(1).key,particles[2].key) - self.assertEqual(pair_detection.particles(0).mass,[2] | units.kg) - self.assertEqual(pair_detection.particles(1).mass,[3] | units.kg) + self.assertEqual(len(pair_detection.particles(0)), 1) + self.assertEqual(len(pair_detection.particles(1)), 1) + self.assertEqual(pair_detection.particles(0).key, particles[1].key) + self.assertEqual(pair_detection.particles(1).key, particles[2].key) + self.assertEqual(pair_detection.particles(0).mass, [2] | units.kg) + self.assertEqual(pair_detection.particles(1).mass, [3] | units.kg) instance.reset_stopping_conditions() instance.stopping_conditions.pair_detection.enable() - + instance.stop() def test3(self): instance = ForTesting( - self.exefile, - community_interface = ForTestingInterfaceFortranModule, - number_of_workers = self.get_number_of_workers() + self.exefile, + community_interface=ForTestingInterfaceFortranModule, + number_of_workers=self.get_number_of_workers() ) instance.initialize_code() instance.reset_stopping_conditions() instance.mpi_setup_stopping_conditions() - + pair_detection = instance.stopping_conditions.pair_detection - + particles = datamodel.Particles(20) particles.mass = range(1, 21) | units.kg instance.particles.add_particles(particles) - + instance.stopping_conditions.pair_detection.enable() - + instance.mpi_distribute_stopping_conditions() - + instance.fire_condition( pair_detection.type, 1, 2, 0 @@ -864,57 +856,54 @@ def test3(self): ) instance.mpi_collect_stopping_conditions() self.assertTrue(pair_detection.is_set()) - self.assertEqual(len(pair_detection.particles(0)),3) - self.assertEqual(len(pair_detection.particles(1)),3) - self.assertEqual(pair_detection.particles(0).key[0],particles[1].key) - self.assertEqual(pair_detection.particles(1).key[0],particles[2].key) - self.assertEqual(pair_detection.particles(0).key[1],particles[3].key) - self.assertEqual(pair_detection.particles(1).key[1],particles[4].key) - self.assertEqual(pair_detection.particles(0).key[2],particles[5].key) - self.assertEqual(pair_detection.particles(1).key[2],particles[6].key) + self.assertEqual(len(pair_detection.particles(0)), 3) + self.assertEqual(len(pair_detection.particles(1)), 3) + self.assertEqual(pair_detection.particles(0).key[0], particles[1].key) + self.assertEqual(pair_detection.particles(1).key[0], particles[2].key) + self.assertEqual(pair_detection.particles(0).key[1], particles[3].key) + self.assertEqual(pair_detection.particles(1).key[1], particles[4].key) + self.assertEqual(pair_detection.particles(0).key[2], particles[5].key) + self.assertEqual(pair_detection.particles(1).key[2], particles[6].key) instance.reset_stopping_conditions() instance.stopping_conditions.pair_detection.enable() - + instance.stop() - - def test4(self): instance = ForTesting( - self.exefile, - community_interface = ForTestingInterfaceFortranModule, - number_of_workers = self.get_number_of_workers() + self.exefile, + community_interface=ForTestingInterfaceFortranModule, + number_of_workers=self.get_number_of_workers() ) instance.initialize_code() instance.reset_stopping_conditions() instance.mpi_setup_stopping_conditions() - + pair_detection = instance.stopping_conditions.pair_detection - + particles = datamodel.Particles(20) particles.mass = range(1, 21) | units.kg instance.particles.add_particles(particles) - + instance.stopping_conditions.pair_detection.enable() - + instance.mpi_collect_stopping_conditions() - + instance.fire_condition( pair_detection.type, -1, -1, -1 ) instance.mpi_distribute_stopping_conditions() self.assertTrue(pair_detection.is_set()) - self.assertEqual(len(pair_detection.particles(0)),0) - + self.assertEqual(len(pair_detection.particles(0)), 0) + instance.stop() - - + def test5(self): number_of_workers = 4 - instance = ForTestingInterface(self.exefile, - community_interface = ForTestingInterfaceFortranModule, - number_of_workers = number_of_workers) + instance = ForTestingInterface(self.exefile, + community_interface=ForTestingInterfaceFortranModule, + number_of_workers=number_of_workers) instance.reset_stopping_conditions() instance.mpi_setup_stopping_conditions() instance.enable_stopping_condition(1) @@ -929,6 +918,5 @@ def test5(self): i, error = instance.get_number_of_stopping_conditions_set() self.assertEqual(error, 0) self.assertEqual(i, number_of_workers * nmax) - + instance.stop() - diff --git a/src/amuse/test/suite/core_tests/test_amuse_import.py b/src/amuse/test/suite/core_tests/test_amuse_import.py index faa3152c38..3e692d29db 100644 --- a/src/amuse/test/suite/core_tests/test_amuse_import.py +++ b/src/amuse/test/suite/core_tests/test_amuse_import.py @@ -4,8 +4,10 @@ print(sys.path) + def test(): - amuse.config.compilers.fc_iso_c_bindings + amuse.config.compilers.fc_iso_c_bindings + -if __name__=="__main__": - test() +if __name__ == "__main__": + test() diff --git a/src/amuse/test/suite/core_tests/test_amusetest.py b/src/amuse/test/suite/core_tests/test_amusetest.py index e05f5921f0..77b1b309d2 100644 --- a/src/amuse/test/suite/core_tests/test_amusetest.py +++ b/src/amuse/test/suite/core_tests/test_amusetest.py @@ -3,88 +3,81 @@ from amuse.units import units import sys + class TestAmusetestTestCase(TestCase): - + def test1(self): self.assertEqual(1 | units.m, 1 | units.m) self.assertEqual(1 | units.m, 1.0 | units.m) - self.assertEqual([1,2,3] | units.m, [1,2,3] | units.m) - self.assertEqual([1,1,1] | units.m, 1 | units.m) - self.assertEqual(1 | units.m, [1,1,1] | units.m) + self.assertEqual([1, 2, 3] | units.m, [1, 2, 3] | units.m) + self.assertEqual([1, 1, 1] | units.m, 1 | units.m) + self.assertEqual(1 | units.m, [1, 1, 1] | units.m) self.assertRaises(self.failureException, self.assertEqual, 1 | units.m, 0 | units.m) - self.assertRaises(self.failureException, self.assertEqual, - 1 | units.m, 0 | units.m, expected_message = "1 m != 0 m") - + self.assertRaises(self.failureException, self.assertEqual, + 1 | units.m, 0 | units.m, expected_message="1 m != 0 m") + def test2(self): self.assertAlmostEqual(1 | units.m, 1 | units.m) self.assertAlmostEqual(1 | units.m, 1.000000049 | units.m) - self.assertAlmostEqual([1,2,3] | units.m, [1,2,3] | units.m) - self.assertAlmostEqual([1,1,1] | units.m, 1.000000049 | units.m) - self.assertAlmostEqual(1 | units.m, [1,1,1.000000049] | units.m) - self.assertAlmostEqual(1 | units.m, 1.00049 | units.m, places = 3) - self.assertRaises(self.failureException, self.assertAlmostEqual, 1.0 | units.m, - 1.000000051 | units.m, expected_message = "1.0 m != 1.000000051 m within 7 places") - self.assertRaises(self.failureException, self.assertAlmostEqual, - [1.1, 1.0, 0.9] | units.m, 1.0 | units.m, - expected_message = "@0, 1.1 m != 1.0 m within 7 places\n@2, 0.9 m != 1.0 m within 7 places") - + self.assertAlmostEqual([1, 2, 3] | units.m, [1, 2, 3] | units.m) + self.assertAlmostEqual([1, 1, 1] | units.m, 1.000000049 | units.m) + self.assertAlmostEqual(1 | units.m, [1, 1, 1.000000049] | units.m) + self.assertAlmostEqual(1 | units.m, 1.00049 | units.m, places=3) + self.assertRaises(self.failureException, self.assertAlmostEqual, 1.0 | units.m, + 1.000000051 | units.m, expected_message="1.0 m != 1.000000051 m within 7 places") + self.assertRaises(self.failureException, self.assertAlmostEqual, + [1.1, 1.0, 0.9] | units.m, 1.0 | units.m, + expected_message="@0, 1.1 m != 1.0 m within 7 places\n@2, 0.9 m != 1.0 m within 7 places") + def test3(self): self.assertAlmostRelativeEqual(1 | units.m, 1 | units.m) self.assertAlmostRelativeEqual(1 | units.m, 1.0 + 4.9e-16 | units.m) - self.assertAlmostRelativeEqual([1,2,3] | units.m, [1,2,3] | units.m) - self.assertAlmostRelativeEqual([1,1,1] | units.m, 1 | units.m) - self.assertAlmostRelativeEqual(1 | units.m, [1,1,1] | units.m) - self.assertAlmostRelativeEqual(100.0 | units.m, 100.1 | units.m, places = 3) - self.assertRaises(self.failureException, self.assertAlmostRelativeEqual, - 1.0 | units.m, [0.0, 1.0001, 1.0011] | units.m, places = 3, expected_message = - "@0, quantity<1.0 m> != quantity<0.0 m> within 3 places\n" + self.assertAlmostRelativeEqual([1, 2, 3] | units.m, [1, 2, 3] | units.m) + self.assertAlmostRelativeEqual([1, 1, 1] | units.m, 1 | units.m) + self.assertAlmostRelativeEqual(1 | units.m, [1, 1, 1] | units.m) + self.assertAlmostRelativeEqual(100.0 | units.m, 100.1 | units.m, places=3) + self.assertRaises(self.failureException, self.assertAlmostRelativeEqual, + 1.0 | units.m, [0.0, 1.0001, 1.0011] | units.m, places=3, expected_message="@0, quantity<1.0 m> != quantity<0.0 m> within 3 places\n" "@2, quantity<1.0 m> != quantity<1.0011 m> within 3 places") - + def test4(self): self.assertIsOfOrder(1 | units.m, 1 | units.m) self.assertIsOfOrder(1 | units.m, 3.0 | units.m) - self.assertIsOfOrder([1,2,3] | units.m, [3,2,1] | units.m) - self.assertIsOfOrder([1,1,1] | units.m, 1 | units.m) - self.assertIsOfOrder(1 | units.m, [0.4,1,3] | units.m) - self.assertRaises(self.failureException, self.assertIsOfOrder, - 1.0 | units.m, [0.3, 1.0, 4.0] | units.m, expected_message = - "@0, 1.0 m is not of order 0.3 m\n@2, 1.0 m is not of order 4.0 m") - - - + self.assertIsOfOrder([1, 2, 3] | units.m, [3, 2, 1] | units.m) + self.assertIsOfOrder([1, 1, 1] | units.m, 1 | units.m) + self.assertIsOfOrder(1 | units.m, [0.4, 1, 3] | units.m) + self.assertRaises(self.failureException, self.assertIsOfOrder, + 1.0 | units.m, [0.3, 1.0, 4.0] | units.m, expected_message="@0, 1.0 m is not of order 0.3 m\n@2, 1.0 m is not of order 4.0 m") + def test5(self): self.assertRaises(AmuseException, (1 | units.m).as_quantity_in, units.kg) self.assertRaises(AmuseException, (1 | units.m).as_quantity_in, 1 | units.cm) - self.assertRaises(AmuseException, (1 | units.m).as_quantity_in, 1 | units.cm, - expected_message = "Cannot expres a unit in a quantity") + self.assertRaises(AmuseException, (1 | units.m).as_quantity_in, 1 | units.cm, + expected_message="Cannot expres a unit in a quantity") # check that a failureException is raised, when we erroneously assert an exception: - + if sys.hexversion > 0x03000000: - error_message = "AmuseException not raised by as_quantity_in" + error_message = "AmuseException not raised by as_quantity_in" else: - error_message = "AmuseException not raised" - self.assertRaises(self.failureException, self.assertRaises, AmuseException, - (1 | units.m).as_quantity_in, units.cm, expected_message = error_message) + error_message = "AmuseException not raised" + self.assertRaises(self.failureException, self.assertRaises, AmuseException, + (1 | units.m).as_quantity_in, units.cm, expected_message=error_message) # the ultimate test... lol - + if sys.hexversion > 0x03000000: - error_message = "AssertionError not raised by assertRaises" + error_message = "AssertionError not raised by assertRaises" else: - error_message = "AssertionError not raised" - - self.assertRaises(self.failureException, self.assertRaises, self.failureException, - self.assertRaises, AmuseException, (1 | units.m).as_quantity_in, - 1 | units.cm, expected_message = error_message) - self.assertRaises(AmuseException, lambda: 1 + (1|units.m)) - self.assertRaises(ZeroDivisionError, lambda: 1|units.m/0) + error_message = "AssertionError not raised" + self.assertRaises(self.failureException, self.assertRaises, self.failureException, + self.assertRaises, AmuseException, (1 | units.m).as_quantity_in, + 1 | units.cm, expected_message=error_message) + self.assertRaises(AmuseException, lambda: 1 + (1 | units.m)) + self.assertRaises(ZeroDivisionError, lambda: 1 | units.m/0) def test6(self): - self.assertRaises(TypeError, self.assertAlmostRelativeEqual, - 1.0 | units.m, 1.0, places = 3, expected_message = - "Cannot compare quantity: 1.0 m with non-quantity: 1.0.") - - self.assertRaises(TypeError, self.assertAlmostRelativeEqual, - 1.0, 1.0 | units.m, places = 3, expected_message = - "Cannot compare non-quantity: 1.0 with quantity: 1.0 m.") - + self.assertRaises(TypeError, self.assertAlmostRelativeEqual, + 1.0 | units.m, 1.0, places=3, expected_message="Cannot compare quantity: 1.0 m with non-quantity: 1.0.") + + self.assertRaises(TypeError, self.assertAlmostRelativeEqual, + 1.0, 1.0 | units.m, places=3, expected_message="Cannot compare non-quantity: 1.0 with quantity: 1.0 m.") diff --git a/src/amuse/test/suite/core_tests/test_attribute_error.py b/src/amuse/test/suite/core_tests/test_attribute_error.py index 03b567797d..5040370753 100644 --- a/src/amuse/test/suite/core_tests/test_attribute_error.py +++ b/src/amuse/test/suite/core_tests/test_attribute_error.py @@ -9,8 +9,9 @@ from amuse.datamodel import * from amuse.datamodel import incode_storage + class TestAttributeError(amusetest.TestCase): - + def new_code_particles(self): class Code(object): def __init__(self): @@ -19,46 +20,46 @@ def __init__(self): self.get_mass_called = False self.set_mass_called = False self.number_of_particles = 0 - + def get_number_of_particles(self): - return self.number_of_particles - - def get_mass(self,index): + return self.number_of_particles + + def get_mass(self, index): self.get_mass_called = True data_to_return = [self.data[i] for i in index] return units.kg(data_to_return) - - def set_mass(self,index,mass): + + def set_mass(self, index, mass): self.set_mass_called = True pass - + def new_particle(self, mass): mass = mass.value_in(units.kg) self.data = mass self.number_of_particles = len(self.data) return [i for i in range(len(mass))] - + code = Code() storage = incode_storage.InCodeAttributeStorage( code, - incode_storage.NewParticleMethod(code.new_particle,("mass",)), + incode_storage.NewParticleMethod(code.new_particle, ("mass",)), None, code.get_number_of_particles, [], [ - incode_storage.ParticleGetAttributesMethod(code.get_mass,("mass",)), + incode_storage.ParticleGetAttributesMethod(code.get_mass, ("mass",)), ], - name_of_the_index = "index" + name_of_the_index="index" ) - - return Particles(storage = storage) - + + return Particles(storage=storage) + def test1(self): print("Test1: Should get error when accessing non-existent attributes (InMemoryAttributeStorage).") particles = Particles(4) - particle = Particle() - subset = particles[:2] - superset = ParticlesSuperset([particles, particle.as_set()]) + particle = Particle() + subset = particles[:2] + superset = ParticlesSuperset([particles, particle.as_set()]) instances = [particles, particle, subset, superset] classes = [Particles, Particle, ParticlesSubset, ParticlesSuperset] @@ -66,15 +67,14 @@ def test1(self): for i, x in enumerate(instances): self.assertTrue(isinstance(x, classes[i])) self.assertEqual(len(x.as_set()), lengths[i]) - self.assertRaises(AttributeError, lambda: x.bogus, expected_message = - "You tried to access attribute 'bogus' but this attribute is not defined for this set.") - + self.assertRaises(AttributeError, lambda: x.bogus, expected_message="You tried to access attribute 'bogus' but this attribute is not defined for this set.") + def test2(self): print("Test2: Should get error when accessing non-existent attributes (in Legacy code storage).") particles = Particles(4) - particle = Particle() - subset = particles[:2] - superset = ParticlesSuperset([particles, particle.as_set()]) + particle = Particle() + subset = particles[:2] + superset = ParticlesSuperset([particles, particle.as_set()]) superset.mass = 1.0 | units.MSun superset.radius = 1.0 | units.RSun for i, x in enumerate(superset): @@ -84,19 +84,18 @@ def test2(self): for i, x in enumerate(instances): code_particles = self.new_code_particles() code_particles.add_particles(x) - self.assertRaises(AttributeError, lambda: code_particles.bogus, expected_message = - "You tried to access attribute 'bogus' but this attribute is not defined for this set.") - + self.assertRaises(AttributeError, lambda: code_particles.bogus, expected_message="You tried to access attribute 'bogus' but this attribute is not defined for this set.") + def test3(self): print("Test3: Should get error when accessing non-existent attributes (HDF5 storage).") particles = Particles(4) - particle = Particle() - subset = particles[:2] - superset = ParticlesSuperset([particles, particle.as_set()]) + particle = Particle() + subset = particles[:2] + superset = ParticlesSuperset([particles, particle.as_set()]) superset.mass = 1.0 | units.MSun test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "attr_test.hdf5") - + instances = [particles, particle, subset] classes = [Particles, Particle, ParticlesSubset] lengths = [4, 1, 2] @@ -106,24 +105,24 @@ def test3(self): if os.path.exists(output_file): os.remove(output_file) HDFstorage = store.StoreHDF(output_file) - if isinstance(x, Particle): x = x.as_set() + if isinstance(x, Particle): + x = x.as_set() x.model_time = 2.0 | units.s HDFstorage.store(x) loaded_particles = HDFstorage.load() - self.assertRaises(AttributeError, lambda: loaded_particles.bogus, expected_message = - "You tried to access attribute 'bogus' but this attribute is not defined for this set.") + self.assertRaises(AttributeError, lambda: loaded_particles.bogus, expected_message="You tried to access attribute 'bogus' but this attribute is not defined for this set.") HDFstorage.close() del HDFstorage - + def bogus_func(self, x): x.mass = 1.0 - + def xtest4(self): print("Test4: Should get error when setting attributes with non-quantities (InMemoryAttributeStorage).") particles = Particles(4) - particle = Particle() - subset = particles[:2] - superset = ParticlesSuperset([particles, particle.as_set()]) + particle = Particle() + subset = particles[:2] + superset = ParticlesSuperset([particles, particle.as_set()]) instances = [particles, particle, subset, superset] classes = [Particles, Particle, ParticlesSubset, ParticlesSuperset] @@ -131,15 +130,14 @@ def xtest4(self): for i, x in enumerate(instances): self.assertTrue(isinstance(x, classes[i])) self.assertEqual(len(x.as_set()), lengths[i]) - self.assertRaises(AttributeError, self.bogus_func, x, expected_message = - "Can only assign quantities or other particles to an attribute.") - + self.assertRaises(AttributeError, self.bogus_func, x, expected_message="Can only assign quantities or other particles to an attribute.") + def xtest5(self): - print("Test5: Should get error when setting attributes with non-quantities (in code storage).") + print("Test5: Should get error when setting attributes with non-quantities (in code storage).") particles = Particles(4) - particle = Particle() - subset = particles[:2] - superset = ParticlesSuperset([particles, particle.as_set()]) + particle = Particle() + subset = particles[:2] + superset = ParticlesSuperset([particles, particle.as_set()]) superset.mass = 1.0 | units.MSun for i, x in enumerate(superset): x.mass = 2.0 | units.kg @@ -149,15 +147,15 @@ def xtest5(self): for i, x in enumerate(instances): code_particles = self.new_code_particles() code_particles.add_particles(x) - #self.assertRaises(AttributeError, self.bogus_func, code_particles, expected_message = + # self.assertRaises(AttributeError, self.bogus_func, code_particles, expected_message = # "Can only assign quantities or other particles to an attribute.") - + def xtest6(self): print("Test6: Should get error when setting attributes with non-quantities (HDF5 storage).") particles = Particles(4) - particle = Particle() - subset = particles[:2] - superset = ParticlesSuperset([particles, particle.as_set()]) + particle = Particle() + subset = particles[:2] + superset = ParticlesSuperset([particles, particle.as_set()]) superset.mass = 1.0 | units.MSun test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "attr_test.hdf5") @@ -170,19 +168,18 @@ def xtest6(self): if os.path.exists(output_file): os.remove(output_file) HDFstorage = store.StoreHDF(output_file) - if isinstance(x, Particle): x = x.as_set() + if isinstance(x, Particle): + x = x.as_set() x.model_time = 2.0 | units.s HDFstorage.store(x) loaded_particles = HDFstorage.load() - self.assertRaises(AttributeError, self.bogus_func, loaded_particles, expected_message = - "Can only assign quantities or other particles to an attribute.") + self.assertRaises(AttributeError, self.bogus_func, loaded_particles, expected_message="Can only assign quantities or other particles to an attribute.") HDFstorage.close() del HDFstorage - + def test7(self): print("Test7: testing whether nonexistent particle attribute access raises correct error") - p=Particles(2) - q=p[0] + p = Particles(2) + q = p[0] p.remove_particle(p[0]) - self.assertRaises(exceptions.KeysNotInStorageException, lambda : q.position) - + self.assertRaises(exceptions.KeysNotInStorageException, lambda: q.position) diff --git a/src/amuse/test/suite/core_tests/test_attribute_storage.py b/src/amuse/test/suite/core_tests/test_attribute_storage.py index 722e015e55..0fe3009870 100644 --- a/src/amuse/test/suite/core_tests/test_attribute_storage.py +++ b/src/amuse/test/suite/core_tests/test_attribute_storage.py @@ -11,14 +11,14 @@ class _AbstractTestInMemoryAttributeStorage: - def new_inmemory_storage(self, is_with_units = True): + def new_inmemory_storage(self, is_with_units=True): raise NotImplementedError() def test1(self): keys = 4, 5, 6 - attributes = "a", "b" + attributes = "a", "b" values = [ - units.m.new_quantity([1.0, 2.0, 3.0]), + units.m.new_quantity([1.0, 2.0, 3.0]), units.g.new_quantity([4.0, 5.0, 6.0]) ] @@ -30,12 +30,11 @@ def test1(self): self.assertEqual(2.0 | units.m, instance.get_value_in_store(indices[1], "a")) self.assertEqual(2.0 | units.m, instance.get_value_of(indices[1], "a")) - def test2(self): - keys = 4, 5, 6 + keys = 4, 5, 6 attributes = "a", "b" values = [ - units.m.new_quantity(numpy.array([1.0, 2.0, 3.0])), + units.m.new_quantity(numpy.array([1.0, 2.0, 3.0])), units.g.new_quantity(numpy.array([4.0, 5.0, 6.0])) ] @@ -43,8 +42,8 @@ def test2(self): indices_stored = instance.add_particles_to_store(keys, attributes, values) indices = instance.get_indices_of([ - keys[2], - keys[1], + keys[2], + keys[1], keys[0] ]) @@ -52,10 +51,10 @@ def test2(self): self.assertEqual(index, wanted) def ntest2b(self): - keys = 4, 5, 6 + keys = 4, 5, 6 attributes = "a", "b" values = [ - units.m.new_quantity(numpy.array([1.0, 2.0, 3.0])), + units.m.new_quantity(numpy.array([1.0, 2.0, 3.0])), units.g.new_quantity(numpy.array([4.0, 5.0, 6.0])) ] @@ -75,12 +74,11 @@ def ntest2b(self): self.assertEqual(all_values[1][0], 0.003 | units.km) self.assertEqual(all_values[1][1], 0.001 | units.km) - def test3(self): - keys = 4, 5, 6 + keys = 4, 5, 6 attributes = "a", "b" values = [ - units.m.new_quantity(numpy.array([1.0, 2.0, 3.0])), + units.m.new_quantity(numpy.array([1.0, 2.0, 3.0])), units.g.new_quantity(numpy.array([4.0, 5.0, 6.0])) ] @@ -96,7 +94,7 @@ def test3(self): indices, ["b", "a"], [ - units.kg.new_quantity(numpy.array([9.0, 11.0])), + units.kg.new_quantity(numpy.array([9.0, 11.0])), units.km.new_quantity(numpy.array([1.0, 2.0])) ] ) @@ -106,12 +104,11 @@ def test3(self): self.assertEqual(values[1][0], 9.0 | units.kg) self.assertEqual(values[1][2], 11.0 | units.kg) - def test4(self): keys = 10, 5, 6, 7 attributes = "a", "b" values = [ - units.m.new_quantity(numpy.array([1.0, 2.0, 3.0, 4.0])), + units.m.new_quantity(numpy.array([1.0, 2.0, 3.0, 4.0])), units.g.new_quantity(numpy.array([4.0, 5.0, 6.0, 7.0])) ] @@ -140,12 +137,11 @@ def test4(self): self.assertEqual(all_values[1][0], 5.0 | units.g) self.assertEqual(all_values[1][1], 7.0 | units.g) - def test5(self): keys = 10, 5, 6, 7 attributes = "a", "b" values = [ - units.m.new_quantity(numpy.array([1.0, 2.0, 3.0, 4.0])), + units.m.new_quantity(numpy.array([1.0, 2.0, 3.0, 4.0])), units.g.new_quantity(numpy.array([4.0, 5.0, 6.0, 7.0])) ] @@ -180,7 +176,7 @@ def test6(self): keys = 10, 5, 6, 7 attributes = "a", "b" values = [ - numpy.array([1.0, 2.0, 3.0, 4.0]), + numpy.array([1.0, 2.0, 3.0, 4.0]), numpy.array([4.0, 5.0, 6.0, 7.0]) ] @@ -232,7 +228,7 @@ def test7(self): keys = 10, 5, 6, 7 attributes = "a", "b" values = [ - units.m.new_quantity(numpy.array([1.0, 2.0, 3.0, 4.0])), + units.m.new_quantity(numpy.array([1.0, 2.0, 3.0, 4.0])), units.g.new_quantity(numpy.array([4.0, 5.0, 6.0, 7.0])) ] instance = self.new_inmemory_storage() @@ -247,7 +243,7 @@ def test8(self): keys = 10, 5, 6, 7 attributes = "a", "b" values = [ - units.m.new_quantity(numpy.array([1.0, 2.0, 3.0, 4.0])), + units.m.new_quantity(numpy.array([1.0, 2.0, 3.0, 4.0])), units.g.new_quantity(numpy.array([4.0, 5.0, 6.0, 7.0])) ] @@ -255,48 +251,47 @@ def test8(self): indices = instance.add_particles_to_store(keys, attributes, values) self.assertEqual(instance.get_all_indices_in_store(), indices) - self.assertEqual(instance.get_indices_of(keys), indices) + self.assertEqual(instance.get_indices_of(keys), indices) def test9(self): keys = 10, 5, 6, 7 attributes = "a", "b" values = [ - units.m.new_quantity(numpy.array([1.0, 2.0, 3.0, 4.0])), + units.m.new_quantity(numpy.array([1.0, 2.0, 3.0, 4.0])), units.g.new_quantity(numpy.array([4.0, 5.0, 6.0, 7.0])) - ] + ] instance = self.new_inmemory_storage() indices = instance.add_particles_to_store(keys, attributes, values) - self.assertRaises(Exception, instance.get_indices_of, [1], expected_message = "Key not found in storage: 1") - self.assertRaises(Exception, instance.get_indices_of, [8], expected_message = "Key not found in storage: 8") - self.assertRaises(Exception, instance.get_indices_of, [11], expected_message = "Key not found in storage: 11") - self.assertRaises(Exception, instance.get_indices_of, [30], expected_message = "Key not found in storage: 30") - self.assertRaises(Exception, instance.get_indices_of, [0], expected_message = "Key not found in storage: 0") + self.assertRaises(Exception, instance.get_indices_of, [1], expected_message="Key not found in storage: 1") + self.assertRaises(Exception, instance.get_indices_of, [8], expected_message="Key not found in storage: 8") + self.assertRaises(Exception, instance.get_indices_of, [11], expected_message="Key not found in storage: 11") + self.assertRaises(Exception, instance.get_indices_of, [30], expected_message="Key not found in storage: 30") + self.assertRaises(Exception, instance.get_indices_of, [0], expected_message="Key not found in storage: 0") def test10(self): keys = 10, 5, 6, 7 attributes = "a", "b" values = [ - units.m.new_quantity(numpy.array([1.0, 2.0, 3.0, 4.0])), + units.m.new_quantity(numpy.array([1.0, 2.0, 3.0, 4.0])), units.g.new_quantity(numpy.array([4.0, 5.0, 6.0, 7.0])) - ] + ] instance = self.new_inmemory_storage() indices = instance.add_particles_to_store(keys, attributes, values) - self.assertRaises(Exception, instance.get_indices_of, [1, 8, 11, 0], expected_message = "Keys not found in storage: [ 1 8 11 0]") - self.assertRaises(Exception, instance.get_indices_of, [5, 1, 6, 8, 7, 11, 10, 0], expected_message = "Keys not found in storage: [ 1 8 11 0]") - self.assertRaises(Exception, instance.get_indices_of, [5, 1, 6], expected_message = "Key not found in storage: 1") - self.assertRaises(Exception, instance.get_indices_of, [1, 5, 6], expected_message = "Key not found in storage: 1") - self.assertRaises(Exception, instance.get_indices_of, [5, 6, 1], expected_message = "Key not found in storage: 1") - + self.assertRaises(Exception, instance.get_indices_of, [1, 8, 11, 0], expected_message="Keys not found in storage: [ 1 8 11 0]") + self.assertRaises(Exception, instance.get_indices_of, [5, 1, 6, 8, 7, 11, 10, 0], expected_message="Keys not found in storage: [ 1 8 11 0]") + self.assertRaises(Exception, instance.get_indices_of, [5, 1, 6], expected_message="Key not found in storage: 1") + self.assertRaises(Exception, instance.get_indices_of, [1, 5, 6], expected_message="Key not found in storage: 1") + self.assertRaises(Exception, instance.get_indices_of, [5, 6, 1], expected_message="Key not found in storage: 1") def test11(self): keys = 10, 5 attributes = "a", "b" values = [ - units.m.new_quantity(numpy.array([1.0, 2.0])), + units.m.new_quantity(numpy.array([1.0, 2.0])), units.g.new_quantity(numpy.array([4.0, 5.0])) ] @@ -321,16 +316,19 @@ def test11(self): instance.remove_particles_from_store([indices]) self.assertEqual(instance.get_all_keys_in_store(), [5, 6]) + class TestSortedKeysInMemoryAttributeStorage(amusetest.TestCase, _AbstractTestInMemoryAttributeStorage): - def new_inmemory_storage(self, is_with_units = True): + def new_inmemory_storage(self, is_with_units=True): return InMemoryAttributeStorageUseSortedKeys() + class TestDictionaryKeysInMemoryAttributeStorage(amusetest.TestCase, _AbstractTestInMemoryAttributeStorage): - def new_inmemory_storage(self, is_with_units = True): + def new_inmemory_storage(self, is_with_units=True): return InMemoryAttributeStorageUseDictionaryForKeySet() + class _Code(object): def __init__(self, is_with_units): self.data = {} @@ -373,9 +371,10 @@ def delete_particle(self, index): for i in index: del self.data[i] + class TestInCodeAttributeStorage(amusetest.TestCase, _AbstractTestInMemoryAttributeStorage): - def new_inmemory_storage(self, is_with_units = True): + def new_inmemory_storage(self, is_with_units=True): code = _Code(is_with_units) return InCodeAttributeStorage( code, @@ -384,9 +383,5 @@ def new_inmemory_storage(self, is_with_units = True): code.get_number_of_particles, [ParticleSetAttributesMethod(code.set_ab, ("a", "b")), ], [ParticleGetAttributesMethod(code.get_ab, ("a", "b")), ], - name_of_the_index = "index" + name_of_the_index="index" ) - - - - diff --git a/src/amuse/test/suite/core_tests/test_binaryio.py b/src/amuse/test/suite/core_tests/test_binaryio.py index 4ec263d0b8..a82e3c575e 100644 --- a/src/amuse/test/suite/core_tests/test_binaryio.py +++ b/src/amuse/test/suite/core_tests/test_binaryio.py @@ -10,8 +10,9 @@ from amuse.units import nbody_system from amuse.datamodel import Particles + class GadgetFileFormatProcessorTests(amusetest.TestCase): - header_parts = ( + header_parts = ( b'\x00\x01\x00\x00 N\x00\x00 \xa1\x07\x00 N\x00', b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', b'\x00\x00\x00\x00\x00\x00\xf6`Q\xc6#\xcc\x9c>\x8d', @@ -44,27 +45,27 @@ def test1(self): self.assertEqual(x.header_struct.Npart[3], 0) self.assertEqual(x.header_struct.Npart[4], 0) self.assertEqual(x.header_struct.Npart[5], 0) - + self.assertEqual(x.header_struct.Massarr[0], 0.0) self.assertAlmostRelativeEqual(x.header_struct.Massarr[1], 4.2911501e-07, 8) print(x.header_struct.Massarr[2]) self.assertAlmostRelativeEqual(x.header_struct.Massarr[2], 2.5000000e-07, 8) - + self.assertEqual(x.header_struct.FlagSfr, 0) self.assertEqual(x.header_struct.FlagFeedback, 0) self.assertEqual(x.header_struct.FlagAge, 0) self.assertEqual(x.header_struct.HubbleParam, 0) - + def test2(self): directory_name = os.path.dirname(__file__) filename = os.path.join(directory_name, 'gadget_snapshot') x = gadget.GadgetFileFormatProcessor() - file = open(filename,'rb') + file = open(filename, 'rb') result = x.load_file(file) file.close() self.assertEqual(len(result[0]), 1000) self.assertEqual(len(result[1]), 10000) - + def test3(self): directory_name = os.path.dirname(__file__) filename = os.path.join(directory_name, 'gadget_snapshot') @@ -72,7 +73,7 @@ def test3(self): result = io.read_set_from_file(filename, format='gadget') self.assertEqual(len(result[0]), 1000) self.assertEqual(len(result[1]), 10000) - + def test4(self): directory_name = os.path.dirname(__file__) filename = os.path.join(directory_name, 'gassphere_littleendian.dat') @@ -80,28 +81,28 @@ def test4(self): result = io.read_set_from_file(filename, format='gadget') self.assertEqual(len(result[0]), 1472) self.assertEqual(len(result[1]), 0) - + def test5(self): options = io.get_options_for_format('gadget') found_has_acceleration = False for name, description, defaultval in options: if name == 'has_acceleration': - found_has_acceleration = True - + found_has_acceleration = True + self.assertTrue(found_has_acceleration) - + def test6(self): directory_name = os.path.dirname(__file__) filename = os.path.join(directory_name, 'gassphere_littleendian.dat') x = gadget.GadgetFileFormatProcessor() - gas, halo, disk, bulge, stars, bndry = io.read_set_from_file(filename, format='gadget') + gas, halo, disk, bulge, stars, bndry = io.read_set_from_file(filename, format='gadget') self.assertEqual(len(gas), 1472) self.assertEqual(len(halo), 0) - self.assertEqual(gas[0].key,1) - self.assertEqual(gas[1].key,2) - self.assertEqual(gas[2].key,3) - self.assertEqual(gas[1471].key,1472) - + self.assertEqual(gas[0].key, 1) + self.assertEqual(gas[1].key, 2) + self.assertEqual(gas[2].key, 3) + self.assertEqual(gas[1471].key, 1472) + def test7(self): """test returned ids from gadget file for ticket #245. @@ -111,21 +112,21 @@ def test7(self): directory_name = os.path.dirname(__file__) filename = os.path.join(directory_name, 'ticket245.dat') gas, halo, disk, bulge, stars, bndry = io.read_set_from_file(filename, format='gadget') - + self.assertEqual(len(gas), 0) - self.assertEqual(len(halo),1324) + self.assertEqual(len(halo), 1324) self.assertEqual(len(disk), 0) self.assertEqual(len(bulge), 0) self.assertEqual(len(stars), 0) self.assertEqual(len(bndry), 0) - self.assertEqual(halo[0].key,544418538) - self.assertEqual(halo[1].key,544511335) - self.assertEqual(halo[2].key,544511457) - self.assertAlmostRelativeEquals(halo[0].velocity[0], -24.785614 | nbody_system.speed, 7) + self.assertEqual(halo[0].key, 544418538) + self.assertEqual(halo[1].key, 544511335) + self.assertEqual(halo[2].key, 544511457) + self.assertAlmostRelativeEquals(halo[0].velocity[0], -24.785614 | nbody_system.speed, 7) print(halo[1].velocity) - self.assertAlmostRelativeEquals(halo[1].velocity[0], -25.346375 | nbody_system.speed, 7) - self.assertAlmostRelativeEquals(halo[2].velocity[0], -25.394440 | nbody_system.speed, 7) - + self.assertAlmostRelativeEquals(halo[1].velocity[0], -25.346375 | nbody_system.speed, 7) + self.assertAlmostRelativeEquals(halo[2].velocity[0], -25.394440 | nbody_system.speed, 7) + def test8(self): """test returned ids from gadget file for ticket #245. @@ -134,32 +135,32 @@ def test8(self): """ directory_name = os.path.dirname(__file__) filename = os.path.join(directory_name, 'ticket245.dat') - gas, halo, disk, bulge, stars, bndry = io.read_set_from_file(filename, format='gadget', ids_are_keys = False) - + gas, halo, disk, bulge, stars, bndry = io.read_set_from_file(filename, format='gadget', ids_are_keys=False) + self.assertEqual(len(gas), 0) - self.assertEqual(len(halo),1324) + self.assertEqual(len(halo), 1324) self.assertEqual(len(disk), 0) self.assertEqual(len(bulge), 0) self.assertEqual(len(stars), 0) self.assertEqual(len(bndry), 0) - self.assertEqual(halo[0].id,544418538) - self.assertEqual(halo[1].id,544511335) - self.assertEqual(halo[2].id,544511457) - self.assertAlmostRelativeEquals(halo[0].velocity[0], -24.785614 | nbody_system.speed, 7) - self.assertAlmostRelativeEquals(halo[1].velocity[0], -25.346375 | nbody_system.speed, 7) - self.assertAlmostRelativeEquals(halo[2].velocity[0], -25.394440 | nbody_system.speed, 7) - - + self.assertEqual(halo[0].id, 544418538) + self.assertEqual(halo[1].id, 544511335) + self.assertEqual(halo[2].id, 544511457) + self.assertAlmostRelativeEquals(halo[0].velocity[0], -24.785614 | nbody_system.speed, 7) + self.assertAlmostRelativeEquals(halo[1].velocity[0], -25.346375 | nbody_system.speed, 7) + self.assertAlmostRelativeEquals(halo[2].velocity[0], -25.394440 | nbody_system.speed, 7) + def test9(self): class FakeList(object): def __init__(self, _len): self._len = _len + def __len__(self): return self._len - + set = (FakeList(20000), FakeList(500000), FakeList(20000), (), (), ()) - x = gadget.GadgetFileFormatProcessor(set = set) - x.equal_mass_array=(0.0,4.291150104743886e-07, 2.5e-07,0.0,0.0,0.0) |nbody_system.mass + x = gadget.GadgetFileFormatProcessor(set=set) + x.equal_mass_array = (0.0, 4.291150104743886e-07, 2.5e-07, 0.0, 0.0, 0.0) | nbody_system.mass file = BytesIO() x.store_header(file) print(x.header_struct) @@ -169,30 +170,30 @@ def __len__(self): self.assertEqual(x.header_struct.Npart[3], 0) self.assertEqual(x.header_struct.Npart[4], 0) self.assertEqual(x.header_struct.Npart[5], 0) - + print(repr(file.getvalue())) print(repr(b''.join(self.header_parts))) self.assertEqual(repr(file.getvalue()[0:30]), repr(b''.join(self.header_parts)[0:30])) - + def test10(self): p = Particles(2) p[0].position = [1.0, 2.0, 3.0] | nbody_system.length p[1].position = [4.0, 5.0, 6.0] | nbody_system.length p[0].velocity = [7.0, 8.0, 10.0] | nbody_system.length / nbody_system.time p[1].velocity = [11.0, 12.0, 13.0] | nbody_system.length / nbody_system.time - p.u = [3,4] | nbody_system.potential - p.rho = [5,6] | nbody_system.density - p.mass = [5,6] | nbody_system.mass - x = gadget.GadgetFileFormatProcessor(set = p) + p.u = [3, 4] | nbody_system.potential + p.rho = [5, 6] | nbody_system.density + p.mass = [5, 6] | nbody_system.mass + x = gadget.GadgetFileFormatProcessor(set=p) file = BytesIO() x.store_body(file) input = BytesIO(file.getvalue()) positions = x.read_fortran_block_float_vectors(input) - self.assertEqual(positions[0] , [1.0, 2.0, 3.0]) - self.assertEqual(positions[1] , [4.0, 5.0, 6.0]) + self.assertEqual(positions[0], [1.0, 2.0, 3.0]) + self.assertEqual(positions[1], [4.0, 5.0, 6.0]) velocities = x.read_fortran_block_float_vectors(input) - self.assertEqual(velocities[0] , [7.0, 8.0, 10.0]) - self.assertEqual(velocities[1] , [11.0, 12.0, 13.0]) + self.assertEqual(velocities[0], [7.0, 8.0, 10.0]) + self.assertEqual(velocities[1], [11.0, 12.0, 13.0]) ids = x.read_fortran_block_ulongs(input) self.assertEqual(ids[0], p[0].key) self.assertEqual(ids[1], p[1].key) @@ -202,84 +203,84 @@ def test10(self): u = x.read_fortran_block_floats(input) self.assertEqual(u[0], 3) self.assertEqual(u[1], 4) - + def test11(self): directory_name = os.path.dirname(__file__) filename = os.path.join(directory_name, 'gassphere_littleendian.dat') gas, halo, disk, bulge, stars, bndry = io.read_set_from_file(filename, format='gadget') self.assertEqual(len(gas), 1472) self.assertEqual(len(halo), 0) - self.assertEqual(gas[0].key,1) - self.assertEqual(gas[1].key,2) - self.assertEqual(gas[2].key,3) - self.assertEqual(gas[1471].key,1472) - self.assertAlmostRelativeEquals(gas[0:5].x,[-0.0713372901082, 0.0713372901082, -0.21178227663, -0.0698266476393, 0.0698266476393] | nbody_system.length, 7) - self.assertAlmostRelativeEquals(gas[0:5].u, [0.0500000007451, 0.0500000007451, 0.0500000007451, 0.0500000007451, 0.0500000007451] | (nbody_system.length / nbody_system.time)**2, 7 ) - + self.assertEqual(gas[0].key, 1) + self.assertEqual(gas[1].key, 2) + self.assertEqual(gas[2].key, 3) + self.assertEqual(gas[1471].key, 1472) + self.assertAlmostRelativeEquals(gas[0:5].x, [-0.0713372901082, 0.0713372901082, -0.21178227663, -0.0698266476393, 0.0698266476393] | nbody_system.length, 7) + self.assertAlmostRelativeEquals(gas[0:5].u, [0.0500000007451, 0.0500000007451, 0.0500000007451, 0.0500000007451, 0.0500000007451] | (nbody_system.length / nbody_system.time)**2, 7) + outputfilename = 'gadgettest.output' try: - io.write_set_to_file((gas, halo, disk, bulge, stars, bndry), outputfilename, format='gadget', ids_are_long = False) - + io.write_set_to_file((gas, halo, disk, bulge, stars, bndry), outputfilename, format='gadget', ids_are_long=False) + gas, halo, disk, bulge, stars, bndry = io.read_set_from_file(outputfilename, format='gadget') self.assertEqual(len(gas), 1472) self.assertEqual(len(halo), 0) - self.assertEqual(gas[0].key,1) - self.assertEqual(gas[1].key,2) - self.assertEqual(gas[2].key,3) - self.assertEqual(gas[1471].key,1472) + self.assertEqual(gas[0].key, 1) + self.assertEqual(gas[1].key, 2) + self.assertEqual(gas[2].key, 3) + self.assertEqual(gas[1471].key, 1472) finally: if os.path.exists(outputfilename): os.remove(outputfilename) - + def test12(self): print("Test return_header for Gadget read_set_from_file") directory_name = os.path.dirname(__file__) filename = os.path.join(directory_name, 'gassphere_littleendian.dat') - data = io.read_set_from_file(filename, format='gadget', return_header=False) # (default) + data = io.read_set_from_file(filename, format='gadget', return_header=False) # (default) self.assertTrue(isinstance(data, tuple)) self.assertEqual(data.__doc__, "GadgetData(gas, halo, disk, bulge, stars, bndry)") - + data = io.read_set_from_file(filename, format='gadget', return_header=True) self.assertTrue(isinstance(data, tuple)) self.assertEqual(data.__doc__, "GadgetData(gas, halo, disk, bulge, stars, bndry, " "Npart, Massarr, Time, Redshift, FlagSfr, FlagFeedback, Nall, FlagCooling, " "NumFiles, BoxSize, Omega0, OmegaLambda, HubbleParam, FlagAge, FlagMetals, " "NallHW, flag_entr_ics)") - + self.assertEqual(len(data.gas), 1472) self.assertEqual(len(data.halo), 0) - self.assertEqual(data.gas[0].key,1) - self.assertEqual(data.gas[1].key,2) - self.assertEqual(data.gas[2].key,3) - self.assertEqual(data.gas[1471].key,1472) - self.assertAlmostRelativeEquals(data.gas[0:5].x,[-0.0713372901082, 0.0713372901082, -0.21178227663, -0.0698266476393, 0.0698266476393] | nbody_system.length, 7) - self.assertAlmostRelativeEquals(data.gas[0:5].u, [0.0500000007451, 0.0500000007451, 0.0500000007451, 0.0500000007451, 0.0500000007451] | (nbody_system.length / nbody_system.time)**2, 7 ) - + self.assertEqual(data.gas[0].key, 1) + self.assertEqual(data.gas[1].key, 2) + self.assertEqual(data.gas[2].key, 3) + self.assertEqual(data.gas[1471].key, 1472) + self.assertAlmostRelativeEquals(data.gas[0:5].x, [-0.0713372901082, 0.0713372901082, -0.21178227663, -0.0698266476393, 0.0698266476393] | nbody_system.length, 7) + self.assertAlmostRelativeEquals(data.gas[0:5].u, [0.0500000007451, 0.0500000007451, 0.0500000007451, 0.0500000007451, 0.0500000007451] | (nbody_system.length / nbody_system.time)**2, 7) + self.assertEqual(data.Npart, (1472, 0, 0, 0, 0, 0)) self.assertEqual(data.Time, 0.0) self.assertEqual(data.Redshift, 0.0) - + def test13(self): print("Test convert_gadget_w_to_velocity and return_header for Gadget read_set_from_file") directory_name = os.path.dirname(__file__) filename = os.path.join(directory_name, 'tiny_lcdm_data_littleendian.dat') - data = io.read_set_from_file(filename, format='gadget', return_header=False, convert_gadget_w_to_velocity=False) # (default) + data = io.read_set_from_file(filename, format='gadget', return_header=False, convert_gadget_w_to_velocity=False) # (default) self.assertTrue(isinstance(data, tuple)) self.assertEqual(data.__doc__, "GadgetData(gas, halo, disk, bulge, stars, bndry)") self.assertEqual(len(data.gas), 32) self.assertEqual(len(data.halo), 32) self.assertEqual(data.gas[0].key, 1) self.assertEqual(data.halo[0].key, 32**3 + 1) - self.assertAlmostRelativeEquals(data.gas[:3].position, [[395.23443604, 395.75210571, 1244.31152344], + self.assertAlmostRelativeEquals(data.gas[:3].position, [[395.23443604, 395.75210571, 1244.31152344], [310.17266846, 440.21728516, 2817.06396484], [191.95669556, 465.57223511, 4430.20068359]] | nbody_system.length, 7) - + data_converted = io.read_set_from_file(filename, format='gadget', return_header=True, convert_gadget_w_to_velocity=True) self.assertTrue(isinstance(data_converted, tuple)) self.assertEqual(data_converted.__doc__, "GadgetData(gas, halo, disk, bulge, stars, bndry, " "Npart, Massarr, Time, Redshift, FlagSfr, FlagFeedback, Nall, FlagCooling, " "NumFiles, BoxSize, Omega0, OmegaLambda, HubbleParam, FlagAge, FlagMetals, " "NallHW, flag_entr_ics)") - + self.assertEqual(len(data_converted.gas), 32) self.assertEqual(len(data_converted.halo), 32) self.assertEqual(data_converted.gas[0].key, 1) @@ -289,12 +290,10 @@ def test13(self): self.assertEqual(data_converted.Redshift, 10.0) self.assertEqual(data.gas.position, data_converted.gas.position) self.assertAlmostRelativeEquals(data.gas.velocity, math.sqrt(data_converted.Time) * data_converted.gas.velocity, 7) - - + class NemoBinaryFileFormatProcessorTests(amusetest.TestCase): - - + def test1(self): directory_name = os.path.dirname(__file__) filename = os.path.join(directory_name, 'plummer128.nemo') @@ -306,18 +305,17 @@ def test1(self): self.assertEqual(len(dim), 1) self.assertEqual(dim[0], 28) file.close() - + def test2(self): directory_name = os.path.dirname(__file__) filename = os.path.join(directory_name, 'plummer128.nemo') file = open(filename, 'rb') nemofile = nemobin.NemoBinaryFile(file) item = nemofile.read_item() - + self.assertEqual(item.data, "init_xrandom: seed used 123") file.close() - - + def test3(self): directory_name = os.path.dirname(__file__) filename = os.path.join(directory_name, 'plummer128.nemo') @@ -331,14 +329,12 @@ def test3(self): self.assertEqual(tags[1], 'History') self.assertEqual(tags[2], 'SnapShot') self.assertEqual(data['History'][0].data, 'mkplummer out=plummer128.nemo nbody=128 seed=123 VERSION=2.8b') - + self.assertEqual(len(data['SnapShot'][0].data), 2) tags = list(data['SnapShot'][0].data.keys()) self.assertEqual(tags[0], 'Parameters') self.assertEqual(tags[1], 'Particles') - - - + def test4(self): directory_name = os.path.dirname(__file__) filename = os.path.join(directory_name, 'plummer128.nemo') @@ -350,7 +346,7 @@ def test4(self): self.assertEqual(len(set), 128) self.assertEqual(set.get_timestamp(), 0.0 | nbody_system.time) self.assertAlmostRelativeEquals(set.kinetic_energy(), 0.230214395174 | nbody_system.energy, 8) - self.assertAlmostRelativeEquals(set.potential_energy(G=nbody_system.G), -0.473503040144 | nbody_system.energy, 8) + self.assertAlmostRelativeEquals(set.potential_energy(G=nbody_system.G), -0.473503040144 | nbody_system.energy, 8) def test5(self): directory_name = os.path.dirname(__file__) @@ -359,13 +355,13 @@ def test5(self): nemofile = nemobin.NemoBinaryFile(file) data = nemofile.read() file.close() - - outputfile = BytesIO() + + outputfile = BytesIO() nemooutputfile = nemobin.NemoBinaryFile(outputfile) nemooutputfile.write(data) string = outputfile.getvalue() outputfile.close() - inputfile = BytesIO(string) + inputfile = BytesIO(string) nemoinputfile = nemobin.NemoBinaryFile(inputfile) tagcharacter, tagstring, dim, mustswap = nemoinputfile.get_item_header() self.assertEqual(tagcharacter, 'c') @@ -373,15 +369,13 @@ def test5(self): self.assertEqual(len(dim), 1) self.assertEqual(dim[0], 28) inputfile.close() - - - def test6(self): + + def test6(self): inputfile = BytesIO() nemoinputfile = nemobin.NemoBinaryFile(inputfile) data = nemoinputfile.read() self.assertEqual(len(data), 0) - - + def test7(self): directory_name = os.path.dirname(__file__) filename = os.path.join(directory_name, 'plummer128.nemo') @@ -389,21 +383,20 @@ def test7(self): nemofile = nemobin.NemoBinaryFile(file) data = nemofile.read() file.close() - - outputfile = BytesIO() + + outputfile = BytesIO() nemooutputfile = nemobin.NemoBinaryFile(outputfile) nemooutputfile.write(data) string = outputfile.getvalue() outputfile.close() - + file = open(filename, 'rb') original = file.read() file.close() - + self.assertEqual(len(original), len(string)) self.assertEqual(original, string) - - + def test8(self): directory_name = os.path.dirname(__file__) filename = os.path.join(directory_name, 'plummer128.nemo') @@ -412,23 +405,23 @@ def test8(self): set = x.load_file(file) file.close() - - outputfile = BytesIO() + + outputfile = BytesIO() y = nemobin.NemoBinaryFileFormatProcessor() y.set = set y.store_file(outputfile) string = outputfile.getvalue() outputfile.close() - + inputfile = BytesIO(string) x = nemobin.NemoBinaryFileFormatProcessor() set = x.load_file(inputfile) inputfile.close() self.assertEqual(len(set), 128) self.assertAlmostRelativeEquals(set.kinetic_energy(), 0.230214395174 | nbody_system.energy, 8) - self.assertAlmostRelativeEquals(set.potential_energy(G=nbody_system.G), -0.473503040144 | nbody_system.energy, 8) - + self.assertAlmostRelativeEquals(set.potential_energy(G=nbody_system.G), -0.473503040144 | nbody_system.energy, 8) + def test9(self): filename = os.path.join(os.path.dirname(__file__), 'plummer128.nemo') particles = io.read_set_from_file(filename, format="nemobin") @@ -437,4 +430,3 @@ def test9(self): self.assertAlmostEqual(particles.center_of_mass(), 0.0 | nbody_system.length) self.assertAlmostEqual(particles.center_of_mass_velocity(), 0.0 | nbody_system.speed) self.assertAlmostEqual(particles.kinetic_energy(), 0.230214395174 | nbody_system.energy) - diff --git a/src/amuse/test/suite/core_tests/test_bridge.py b/src/amuse/test/suite/core_tests/test_bridge.py index cc2ede5382..354a27c41d 100644 --- a/src/amuse/test/suite/core_tests/test_bridge.py +++ b/src/amuse/test/suite/core_tests/test_bridge.py @@ -10,17 +10,18 @@ from amuse.test import amusetest from amuse.couple import bridge + class TestCalculateFieldForParticles(amusetest.TestCase): - + def test1(self): particles = Particles(2) particles.mass = [1.0, 1.0] | nbody_system.mass - particles.radius = [0.0001, 0.0001] | nbody_system.length - particles.position = [[0.0,0.0,0.0], [2.0,0.0,0.0]] | nbody_system.length + particles.radius = [0.0001, 0.0001] | nbody_system.length + particles.position = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]] | nbody_system.length particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed - - instance = bridge.CalculateFieldForParticles(particles = particles, gravity_constant = nbody_system.G) - + + instance = bridge.CalculateFieldForParticles(particles=particles, gravity_constant=nbody_system.G) + zero = 0.0 | nbody_system.length print(instance.get_gravity_at_point([zero], [1.0] | nbody_system.length, [zero], [zero])) fx, fy, fz = instance.get_gravity_at_point([zero], [1.0] | nbody_system.length, [zero], [zero]) @@ -35,113 +36,112 @@ def test1(self): potential1 = instance.get_potential_at_point([zero], [x1], [zero], [zero]) fx0, fy0, fz0 = instance.get_gravity_at_point([zero], [x0], [zero], [zero]) fx1, fy1, fz1 = instance.get_gravity_at_point([zero], [x1], [zero], [zero]) - + self.assertAlmostEqual(fy0[0], 0.0 | nbody_system.acceleration, 6) self.assertAlmostEqual(fz0[0], 0.0 | nbody_system.acceleration, 6) self.assertAlmostEqual(fy1[0], 0.0 | nbody_system.acceleration, 6) self.assertAlmostEqual(fz1[0], 0.0 | nbody_system.acceleration, 6) - + self.assertAlmostEqual(fx0, -1.0 * fx1, 5) fx = (-1.0 / (x0**2) + 1.0 / (x1**2)) * (1.0 | nbody_system.length ** 3 / nbody_system.time ** 2) self.assertAlmostEqual(fx, fx0[0], 5) self.assertAlmostEqual(potential0, potential1, 6) - + def test2(self): print("CalculateFieldForParticles, nbody units, no gravity_constant exceptions") stars = new_plummer_model(100) - self.assertRaises(AmuseException, bridge.CalculateFieldForParticles, stars, - expected_message = "For generic units the gravity_constant must be specified") - self.assertRaises(AmuseException, bridge.CalculateFieldForParticles, Particles(), - expected_message = "Particle data not yet available, so the gravity_constant must be specified") - instance = bridge.CalculateFieldForParticles(particles = stars, gravity_constant = nbody_system.G) - + self.assertRaises(AmuseException, bridge.CalculateFieldForParticles, stars, + expected_message="For generic units the gravity_constant must be specified") + self.assertRaises(AmuseException, bridge.CalculateFieldForParticles, Particles(), + expected_message="Particle data not yet available, so the gravity_constant must be specified") + instance = bridge.CalculateFieldForParticles(particles=stars, gravity_constant=nbody_system.G) + def test3(self): print("CalculateFieldForParticles get_potential_at_point, no softening") epsilon = 0 | units.m - + convert = nbody_system.nbody_to_si(1.e5 | units.MSun, 1.0 | units.parsec) numpy.random.seed(12345) stars = new_plummer_model(100, convert_nbody=convert) - + cluster = ExampleGravityCodeInterface() - cluster.parameters.epsilon_squared = epsilon**2 + cluster.parameters.epsilon_squared = epsilon**2 cluster.particles.add_particles(stars) - - instance = bridge.CalculateFieldForParticles(particles = stars) + + instance = bridge.CalculateFieldForParticles(particles=stars) instance.smoothing_length_squared = epsilon**2 - + zeros = numpy.zeros(9) | units.parsec pos_range = numpy.linspace(-1.0, 1.0, 9) | units.parsec self.assertAlmostRelativeEqual( - instance.get_potential_at_point(zeros, pos_range, zeros, zeros), + instance.get_potential_at_point(zeros, pos_range, zeros, zeros), cluster.get_potential_at_point(zeros, pos_range, zeros, zeros)) for a_calculate_field, a_code in zip( - instance.get_gravity_at_point(zeros, pos_range, zeros, zeros), + instance.get_gravity_at_point(zeros, pos_range, zeros, zeros), cluster.get_gravity_at_point(zeros, pos_range, zeros, zeros)): self.assertAlmostRelativeEqual(a_calculate_field, a_code, 12) - + def test4(self): print("CalculateFieldForParticles get_potential_at_point, with softening") epsilon = 0.5 | units.parsec - + convert = nbody_system.nbody_to_si(1.e5 | units.MSun, 1.0 | units.parsec) numpy.random.seed(12345) stars = new_plummer_model(100, convert_nbody=convert) - + cluster = ExampleGravityCodeInterface() - cluster.parameters.epsilon_squared = epsilon**2 + cluster.parameters.epsilon_squared = epsilon**2 cluster.particles.add_particles(stars) - - instance = bridge.CalculateFieldForParticles(particles = stars) + + instance = bridge.CalculateFieldForParticles(particles=stars) instance.smoothing_length_squared = epsilon**2 - + zeros = numpy.zeros(9) | units.parsec pos_range = numpy.linspace(-1.0, 1.0, 9) | units.parsec self.assertAlmostRelativeEqual( - instance.get_potential_at_point(zeros, pos_range, zeros, zeros), + instance.get_potential_at_point(zeros, pos_range, zeros, zeros), cluster.get_potential_at_point(zeros, pos_range, zeros, zeros)) for a_calculate_field, a_code in zip( - instance.get_gravity_at_point(zeros, pos_range, zeros, zeros), + instance.get_gravity_at_point(zeros, pos_range, zeros, zeros), cluster.get_gravity_at_point(zeros, pos_range, zeros, zeros)): self.assertAlmostRelativeEqual(a_calculate_field, a_code, 12) - + def test5(self): print("CalculateFieldForParticles get_potential_at_point, with individual softening") epsilon = 0.5 | units.parsec - + convert = nbody_system.nbody_to_si(1.e5 | units.MSun, 1.0 | units.parsec) numpy.random.seed(12345) stars = new_plummer_model(100, convert_nbody=convert) stars.radius = epsilon * numpy.random.uniform(low=0.4, high=3.0, size=len(stars)) - + cluster = ExampleGravityCodeInterface(softening_mode="individual") cluster.particles.add_particles(stars) - + instance = bridge.CalculateFieldForParticles(particles=stars, softening_mode="individual") - + zeros = numpy.zeros(9) | units.parsec pos_range = numpy.linspace(-1.0, 1.0, 9) | units.parsec self.assertAlmostRelativeEqual( - instance.get_potential_at_point(zeros, pos_range, zeros, zeros), + instance.get_potential_at_point(zeros, pos_range, zeros, zeros), cluster.get_potential_at_point(zeros, pos_range, zeros, zeros)) for a_calculate_field, a_code in zip( - instance.get_gravity_at_point(zeros, pos_range, zeros, zeros), + instance.get_gravity_at_point(zeros, pos_range, zeros, zeros), cluster.get_gravity_at_point(zeros, pos_range, zeros, zeros)): self.assertAlmostRelativeEqual(a_calculate_field, a_code, 12) def test6(self): - p=Particles(3) - q=Particles(5) - instance1 = bridge.CalculateFieldForParticles(gravity_constant = "dummy") - instance1.particles.add_particles(p) - instance2 = bridge.CalculateFieldForParticles(gravity_constant = "dummy") - instance2.particles.add_particles(q) - self.assertEqual(len(instance2.particles),5) - - + p = Particles(3) + q = Particles(5) + instance1 = bridge.CalculateFieldForParticles(gravity_constant="dummy") + instance1.particles.add_particles(p) + instance2 = bridge.CalculateFieldForParticles(gravity_constant="dummy") + instance2.particles.add_particles(q) + self.assertEqual(len(instance2.particles), 5) + class ExampleGravityCodeInterface(object): - + def __init__(self, softening_mode="shared"): self.particles = Particles() if softening_mode == "individual": @@ -157,50 +157,52 @@ def __init__(self, softening_mode="shared"): "set_epsilon_squared", "epsilon_squared", "gravitational softening length squared", - default_value = 0.0 | nbody_system.length**2, - must_set_before_get = False + default_value=0.0 | nbody_system.length**2, + must_set_before_get=False ) self.parameters = parameters.new_parameters_instance_with_docs([epsilon_squared_parameter], self) self.epsilon_squared = 0.0 | nbody_system.length**2 - + def _softening_lengths_squared_individual(self): return self.particles.radius**2 + def _softening_lengths_squared_shared(self): return self.epsilon_squared.as_vector_with_length(len(self.particles)) - + def _softening_lengths_individual(self): return self.particles.radius + def _softening_lengths_shared(self): return self.epsilon_squared.sqrt().as_vector_with_length(len(self.particles)) - + def initialize_code(self): self.model_time = 0 | units.Myr - - def get_potential_at_point(self, eps, x ,y, z): + + def get_potential_at_point(self, eps, x, y, z): if isinstance(x, VectorQuantity): - return -constants.G * (self.particles.mass.reshape((-1,1)) / - (self._softening_lengths_squared().reshape((-1,1)) + eps.reshape((1,-1))**2 + (self.particles.x.reshape((-1,1)) - - x.reshape((1,-1)))**2 + (self.particles.y.reshape((-1,1)) - y.reshape((1,-1)))**2 + - (self.particles.z.reshape((-1,1)) - z.reshape((1,-1)))**2).sqrt()).sum(axis=0) - return -constants.G * (self.particles.mass / (self._softening_lengths_squared() + eps**2 + (self.particles.x - x)**2 + + return -constants.G * (self.particles.mass.reshape((-1, 1)) / + (self._softening_lengths_squared().reshape((-1, 1)) + eps.reshape((1, -1))**2 + (self.particles.x.reshape((-1, 1)) - + x.reshape((1, -1)))**2 + (self.particles.y.reshape((-1, 1)) - y.reshape((1, -1)))**2 + + (self.particles.z.reshape((-1, 1)) - z.reshape((1, -1)))**2).sqrt()).sum(axis=0) + return -constants.G * (self.particles.mass / (self._softening_lengths_squared() + eps**2 + (self.particles.x - x)**2 + (self.particles.y - y)**2 + (self.particles.z - z)**2).sqrt()).sum() - - def get_gravity_at_point(self, eps, x ,y, z): + + def get_gravity_at_point(self, eps, x, y, z): if isinstance(x, VectorQuantity): - delta_x = x.reshape((1,-1)) - self.particles.x.reshape((-1,1)) - delta_y = y.reshape((1,-1)) - self.particles.y.reshape((-1,1)) - delta_z = z.reshape((1,-1)) - self.particles.z.reshape((-1,1)) - factor = -constants.G * (self.particles.mass.reshape((-1,1)) / - (self._softening_lengths_squared().reshape((-1,1)) + eps.reshape((1,-1))**2 + + delta_x = x.reshape((1, -1)) - self.particles.x.reshape((-1, 1)) + delta_y = y.reshape((1, -1)) - self.particles.y.reshape((-1, 1)) + delta_z = z.reshape((1, -1)) - self.particles.z.reshape((-1, 1)) + factor = -constants.G * (self.particles.mass.reshape((-1, 1)) / + (self._softening_lengths_squared().reshape((-1, 1)) + eps.reshape((1, -1))**2 + delta_x**2 + delta_y**2 + delta_z**2)**1.5) return (factor*delta_x).sum(axis=0), (factor*delta_y).sum(axis=0), (factor*delta_z).sum(axis=0) delta_x = self.particles.x - x delta_y = self.particles.y - y delta_z = self.particles.z - z - factor = -constants.G * (self.particles.mass / + factor = -constants.G * (self.particles.mass / (self._softening_lengths_squared() + eps**2 + delta_x**2 + delta_y**2 + delta_z**2)**1.5) return (factor*delta_x).sum(), (factor*delta_y).sum(), (factor*delta_z).sum() - + @property def potential_energy(self): if self.softening_mode == "individual": @@ -216,38 +218,38 @@ def potential_energy(self): sum_of_energies -= (self.particles.mass[i] * self.particles.mass[i+1:] / dr).sum() return constants.G * sum_of_energies return self.particles.potential_energy(smoothing_length_squared=2*self.epsilon_squared) - + def before_set_parameter(self): pass - + def before_get_parameter(self): pass - + @property def kinetic_energy(self): return self.particles.kinetic_energy() - + def get_epsilon_squared(self): return self.epsilon_squared - + def set_epsilon_squared(self, epsilon_squared): self.epsilon_squared = epsilon_squared - + def commit_particles(self): self.set_accelerations() self.set_next_timestep() - + def set_accelerations(self): - accelerations = self.get_gravity_at_point(self._softening_lengths(), + accelerations = self.get_gravity_at_point(self._softening_lengths(), self.particles.x, self.particles.y, self.particles.z) self.particles.ax = accelerations[0] self.particles.ay = accelerations[1] self.particles.az = accelerations[2] - + def set_next_timestep(self): - self.next_timestep = min([0.01 * (self.particles.velocity / + self.next_timestep = min([0.01 * (self.particles.velocity / self.particles.acceleration).lengths_squared().amin().sqrt(), 1 | units.yr]) - + def evolve_model(self, t_end): while self.model_time < t_end: dt = self.next_timestep @@ -258,130 +260,130 @@ def evolve_model(self, t_end): self.model_time += dt self.set_next_timestep() + def system_from_particles(base_class, kwargs, particles, eps=None): interface = base_class(**kwargs) interface.initialize_code() if eps is not None: - interface.parameters.epsilon_squared = eps**2 + interface.parameters.epsilon_squared = eps**2 interface.particles.add_particles(particles) interface.commit_particles() return interface + class TestBridge(amusetest.TestCase): - + def test1(self): print("Bridge potential energy with code's epsilon_squared as softening length") convert = nbody_system.nbody_to_si(1.e5 | units.MSun, 1.0 | units.parsec) epsilon = 1.0e-2 | units.parsec - test_class=ExampleGravityCodeInterface - + test_class = ExampleGravityCodeInterface + numpy.random.seed(12345) stars = new_plummer_model(100, convert_nbody=convert) - - cluster=test_class() - cluster.parameters.epsilon_squared = epsilon**2 + + cluster = test_class() + cluster.parameters.epsilon_squared = epsilon**2 cluster.particles.add_particles(stars) - - first_half = stars.select_array(lambda x: (x > 0 | units.m), ['x'] ) + + first_half = stars.select_array(lambda x: (x > 0 | units.m), ['x']) second_half = stars - first_half cluster1 = system_from_particles(test_class, dict(), first_half, epsilon) cluster2 = system_from_particles(test_class, dict(), second_half, epsilon) - bridgesys=bridge.Bridge() - bridgesys.add_system(cluster1, (cluster2,) ) - bridgesys.add_system(cluster2, (cluster1,) ) - + bridgesys = bridge.Bridge() + bridgesys.add_system(cluster1, (cluster2,)) + bridgesys.add_system(cluster2, (cluster1,)) + self.assertAlmostRelativeEqual(cluster.potential_energy, bridgesys.potential_energy) self.assertAlmostRelativeEqual(cluster.kinetic_energy, bridgesys.kinetic_energy) - + def test2(self): print("Bridge potential energy with radius as softening length") convert = nbody_system.nbody_to_si(1.e5 | units.MSun, 1.0 | units.parsec) epsilon = 0.1 | units.parsec - test_class=ExampleGravityCodeInterface - + test_class = ExampleGravityCodeInterface + numpy.random.seed(12345) stars = new_plummer_model(100, convert_nbody=convert) stars.radius = epsilon - - cluster=test_class() - cluster.parameters.epsilon_squared = epsilon**2 + + cluster = test_class() + cluster.parameters.epsilon_squared = epsilon**2 cluster.particles.add_particles(stars) - - first_half = stars.select_array(lambda x: (x > 0 | units.m), ['x'] ) + + first_half = stars.select_array(lambda x: (x > 0 | units.m), ['x']) second_half = stars - first_half cluster1 = system_from_particles(test_class, dict(softening_mode="individual"), first_half) cluster2 = system_from_particles(test_class, dict(), second_half, epsilon) - bridgesys=bridge.Bridge() + bridgesys = bridge.Bridge() bridgesys.add_system(cluster1, (cluster2,), radius_is_eps=True) bridgesys.add_system(cluster2, (cluster1,), radius_is_eps=True) - + self.assertAlmostRelativeEqual(cluster.potential_energy, bridgesys.potential_energy) self.assertAlmostRelativeEqual(cluster.kinetic_energy, bridgesys.kinetic_energy) - + def test3(self): print("Bridge potential energy with radius as softening length") convert = nbody_system.nbody_to_si(1.e5 | units.MSun, 1.0 | units.parsec) epsilon = 0.1 | units.parsec - test_class=ExampleGravityCodeInterface - + test_class = ExampleGravityCodeInterface + numpy.random.seed(12345) stars = new_plummer_model(100, convert_nbody=convert) stars.radius = epsilon - - cluster=test_class() - cluster.parameters.epsilon_squared = epsilon**2 + + cluster = test_class() + cluster.parameters.epsilon_squared = epsilon**2 cluster.particles.add_particles(stars) - - first_half = stars.select_array(lambda x: (x > 0 | units.m), ['x'] ) + + first_half = stars.select_array(lambda x: (x > 0 | units.m), ['x']) second_half = stars - first_half cluster1 = system_from_particles(test_class, dict(), first_half, epsilon) cluster2 = system_from_particles(test_class, dict(), second_half, epsilon) - bridgesys=bridge.Bridge() + bridgesys = bridge.Bridge() bridgesys.add_system(cluster1, (cluster2,), radius_is_eps=True) bridgesys.add_system(cluster2, (cluster1,)) - + self.assertAlmostRelativeEqual(cluster.potential_energy, bridgesys.potential_energy) self.assertAlmostRelativeEqual(cluster.kinetic_energy, bridgesys.kinetic_energy) - + def test4(self): print("Bridge evolve_model") convert = nbody_system.nbody_to_si(1.e5 | units.MSun, 1.0 | units.parsec) epsilon = 1.0e-2 | units.parsec - test_class=ExampleGravityCodeInterface - + test_class = ExampleGravityCodeInterface + numpy.random.seed(12345) stars = new_plummer_model(100, convert_nbody=convert) - - cluster=test_class() + + cluster = test_class() cluster.initialize_code() - cluster.parameters.epsilon_squared = epsilon**2 + cluster.parameters.epsilon_squared = epsilon**2 cluster.particles.add_particles(stars) cluster.commit_particles() - - first_half = stars.select_array(lambda x: (x > 0 | units.m), ['x'] ) + + first_half = stars.select_array(lambda x: (x > 0 | units.m), ['x']) second_half = stars - first_half cluster1 = system_from_particles(test_class, dict(), first_half, epsilon) cluster2 = system_from_particles(test_class, dict(), second_half, epsilon) - bridgesys=bridge.Bridge() - bridgesys.add_system(cluster1, (cluster2,) ) - bridgesys.add_system(cluster2, (cluster1,) ) - + bridgesys = bridge.Bridge() + bridgesys.add_system(cluster1, (cluster2,)) + bridgesys.add_system(cluster2, (cluster1,)) + self.assertAlmostRelativeEqual( cluster1.particles.get_intersecting_subset_in(cluster.particles).position, cluster1.particles.position) - -#~ old = cluster1.particles.position + +# ~ old = cluster1.particles.position for i in range(2): one_timestep = cluster.next_timestep cluster.evolve_model(cluster.model_time + one_timestep) bridgesys.evolve_model(bridgesys.model_time + one_timestep, timestep=one_timestep) - -#~ print ((old - cluster1.particles.position)/old).lengths() + +# ~ print ((old - cluster1.particles.position)/old).lengths() self.assertAlmostRelativeEqual( cluster1.particles.get_intersecting_subset_in(cluster.particles).position, cluster1.particles.position) - + self.assertAlmostRelativeEqual(cluster.potential_energy, bridgesys.potential_energy) self.assertAlmostRelativeEqual(cluster.kinetic_energy, bridgesys.kinetic_energy) - - diff --git a/src/amuse/test/suite/core_tests/test_console.py b/src/amuse/test/suite/core_tests/test_console.py index 70c9c30cf0..dd90755637 100644 --- a/src/amuse/test/suite/core_tests/test_console.py +++ b/src/amuse/test/suite/core_tests/test_console.py @@ -10,11 +10,12 @@ import sys + class TestPrintingStrategy(amusetest.TestCase): def tearDown(self): set_printing_strategy("default") - + def test1(self): print("Testing get/set of printing strategy") self.assertEqual(get_current_printing_strategy(), console.DefaultPrintingStrategy) @@ -34,21 +35,21 @@ def test1(self): self.assertEqual(get_current_printing_strategy(), console.NoUnitsPrintingStrategy) set_printing_strategy(console.DefaultPrintingStrategy) self.assertEqual(get_current_printing_strategy(), console.DefaultPrintingStrategy) - + def test2(self): print("Testing no units printing strategy with SI quantities") - mass = 1.0 | units.kg - acc = 9.8 | units.m / units.s**2 + mass = 1.0 | units.kg + acc = 9.8 | units.m / units.s**2 position = [1, 2.0, 3] | units.m mass_in_g = mass.as_quantity_in(units.g) - pi = 3.14 | units.none - + pi = 3.14 | units.none + self.assertEqual(str(mass), "1.0 kg") self.assertEqual(str(acc), "9.8 m / (s**2)") self.assertEqual(str(position), "[1.0, 2.0, 3.0] m") self.assertEqual(str(mass_in_g), "1000.0 g") self.assertEqual(str(pi), "3.14 none") - + set_printing_strategy("no_unit") self.assertEqual(get_current_printing_strategy(), console.NoUnitsPrintingStrategy) self.assertEqual(str(mass), "1.0") @@ -57,59 +58,58 @@ def test2(self): self.assertEqual(str(mass_in_g), "1000.0") self.assertEqual(str(pi), "3.14") set_printing_strategy("default") - + def test3(self): print("Testing no units printing strategy with N-body quantities") - mass = 1.0 | nbody_system.mass - acc = 9.8 | nbody_system.acceleration + mass = 1.0 | nbody_system.mass + acc = 9.8 | nbody_system.acceleration position = [1, 2, 3] | nbody_system.length - + self.assertEqual(str(mass), "1.0 mass") self.assertEqual(str(acc), "9.8 length / (time**2)") self.assertEqual(str(position), "[1, 2, 3] length") - + set_printing_strategy("no_unit") self.assertEqual(str(mass), "1.0") self.assertEqual(str(acc), "9.8") self.assertEqual(str(position), "[1, 2, 3]") set_printing_strategy("default") - + def test4(self): print("Testing formal printing strategy") - mass = 1.0 | units.kg - acc = 9.8 | units.m / units.s**2 + mass = 1.0 | units.kg + acc = 9.8 | units.m / units.s**2 position = [1, 2.0, 3] | nbody_system.length mass_in_g = mass.as_quantity_in(units.g) * 1.0 - pi = 3.14 | units.none - + pi = 3.14 | units.none + set_printing_strategy("formal") self.assertEqual(str(mass), "") self.assertEqual(str(acc), "") self.assertEqual(str(position), "") - self.assertEqual(str(mass_in_g), "")#") + self.assertEqual(str(mass_in_g), "") # ") self.assertEqual(str(pi), "") set_printing_strategy("default") - + def test5(self): print("Testing nbody printing strategy") - mass = 1.0 | nbody_system.mass - acc = 9.8 | nbody_system.length / units.s**2 + mass = 1.0 | nbody_system.mass + acc = 9.8 | nbody_system.length / units.s**2 position = [1, 2, 3] | units.m - pi = 3.14 | units.none + pi = 3.14 | units.none converter = nbody_system.nbody_to_si(1.0 | units.kg, 1.0 | units.m) - + set_printing_strategy("nbody") self.assertEqual(str(mass), "1.0") - self.assertRaises(AmuseException, str, acc, expected_message = - "Unable to convert length / (s**2) to N-body units. No nbody_converter given") + self.assertRaises(AmuseException, str, acc, expected_message="Unable to convert length / (s**2) to N-body units. No nbody_converter given") self.assertEqual(str(converter.to_nbody(acc * constants.G.number)), "9.8") if sys.hexversion > 0x03000000: self.assertEqual(str(converter.to_nbody(position)), "[1.0, 2.0, 3.0]") else: self.assertEqual(str(converter.to_nbody(position)), "[1, 2, 3]") self.assertEqual(str(pi), "3.14") - - set_printing_strategy("nbody", nbody_converter = converter) + + set_printing_strategy("nbody", nbody_converter=converter) self.assertEqual(str(mass), "1.0") self.assertEqual(str(acc * constants.G.number), "9.8") if sys.hexversion > 0x03000000: @@ -117,73 +117,70 @@ def test5(self): else: self.assertEqual(str(position), "[1, 2, 3]") set_printing_strategy("default") - + def test6(self): print("Testing astro printing strategy without units printed") - mass = 2.0 | 0.5 * units.MSun - acc = (0.0098 | nbody_system.length) * (1 | units.Myr**-2).as_quantity_in(units.s**-2) + mass = 2.0 | 0.5 * units.MSun + acc = (0.0098 | nbody_system.length) * (1 | units.Myr**-2).as_quantity_in(units.s**-2) position = [0.1, 0.2, 0.3] | nbody_system.length - energy = 1e8 | units.erg + energy = 1e8 | units.erg temperature = 5000 | units.K - pi = 3.14 | units.none + pi = 3.14 | units.none converter = nbody_system.nbody_to_si(1.0 | units.kg, 1.0 | units.kpc) - - set_printing_strategy("astro", print_units = False) + + set_printing_strategy("astro", print_units=False) self.assertEqual(str(mass), "1.0") - self.assertRaises(AmuseException, str, acc, expected_message = - "Unable to convert length * s**-2 to SI units. No nbody_converter given") + self.assertRaises(AmuseException, str, acc, expected_message="Unable to convert length * s**-2 to SI units. No nbody_converter given") self.assertEqual(str(converter.to_si(acc)), "9.8") self.assertEqual(str(converter.to_si(position)), "[100.0, 200.0, 300.0]") self.assertEqual(str(energy), "10.0") self.assertEqual(str(constants.G)[:8], "0.00449945056135"[:8]) self.assertEqual(str(temperature), "5000") self.assertEqual(str(pi), "3.14") - - set_printing_strategy("astro", nbody_converter = converter, print_units = False) + + set_printing_strategy("astro", nbody_converter=converter, print_units=False) self.assertEqual(str(acc), "9.8") set_printing_strategy("default") - + def test7(self): print("Testing astro printing strategy with units printed") - mass = 2.0 | 0.5 * units.MSun - acc = (0.0097 | nbody_system.length) * (1 | units.Myr**-2).as_quantity_in(units.s**-2) + mass = 2.0 | 0.5 * units.MSun + acc = (0.0097 | nbody_system.length) * (1 | units.Myr**-2).as_quantity_in(units.s**-2) position = [0.1, 0.2, 0.3] | nbody_system.length - energy = 1e8 | units.erg + energy = 1e8 | units.erg temperature = 5000 | units.K - pi = 3.14 | units.none + pi = 3.14 | units.none converter = nbody_system.nbody_to_si(1.0 | units.kg, 1.0 | units.kpc) - + set_printing_strategy("astro") self.assertEqual(str(mass), "1.0 MSun") self.assertEqual(str(acc), "0.0097 length * Myr**-2") self.assertEqual(str(converter.to_si(acc)), "9.7 parsec * Myr**-2") self.assertEqual(str(converter.to_si(position)), "[100.0, 200.0, 300.0] parsec") self.assertEqual(str(energy), "10.0 J") - - + self.assertEqual(str(constants.G)[:8], "0.004499450561351174 parsec**3 * MSun**-1 * Myr**-2"[:8]) self.assertEqual(str(constants.G)[-30:], "parsec**3 * MSun**-1 * Myr**-2") self.assertEqual(str(temperature), "5000 K") self.assertEqual(str(pi), "3.14 none") - - set_printing_strategy("astro", nbody_converter = converter) + + set_printing_strategy("astro", nbody_converter=converter) self.assertEqual(str(acc), "9.7 parsec * Myr**-2") - set_printing_strategy("astro", ignore_converter_exceptions = False) - self.assertRaises(AmuseException, str, acc, expected_message = - "Unable to convert length * s**-2 to SI units. No nbody_converter given") + set_printing_strategy("astro", ignore_converter_exceptions=False) + self.assertRaises(AmuseException, str, acc, expected_message="Unable to convert length * s**-2 to SI units. No nbody_converter given") set_printing_strategy("default") - + def test8(self): print("Testing SI printing strategy") - mass = 2.0 | 0.5 * units.MSun - acc = 0.0098 | nbody_system.length / units.Myr**2 + mass = 2.0 | 0.5 * units.MSun + acc = 0.0098 | nbody_system.length / units.Myr**2 position = [0.1, 0.2, 0.3] | nbody_system.length - energy = 1e8 | units.erg + energy = 1e8 | units.erg temperature = 5000 | units.milli(units.K) - pi = 3.14 | units.none + pi = 3.14 | units.none converter = nbody_system.nbody_to_si(1.0 | units.kg, 1.0 | units.kpc) - - set_printing_strategy("SI", nbody_converter = converter) + + set_printing_strategy("SI", nbody_converter=converter) self.assertEqual(str(mass), "1.98892e+30 kg") self.assertEqual(str(acc), "3.03659755643e-10 m * s**-2") self.assertEqual(str(position), "[3.08567758128e+18, 6.17135516256e+18, 9.25703274384e+18] m") @@ -191,8 +188,8 @@ def test8(self): self.assertEqual(str(constants.G), "6.67428e-11 m**3 * kg**-1 * s**-2") self.assertEqual(str(temperature), "5.0 K") self.assertEqual(str(pi), "3.14 none") - - set_printing_strategy("SI", nbody_converter = converter, print_units = False) + + set_printing_strategy("SI", nbody_converter=converter, print_units=False) self.assertEqual(str(mass), "1.98892e+30") self.assertEqual(str(acc), "3.03659755643e-10") self.assertEqual(str(position), "[3.08567758128e+18, 6.17135516256e+18, 9.25703274384e+18]") @@ -201,20 +198,19 @@ def test8(self): self.assertEqual(str(temperature), "5.0") self.assertEqual(str(pi), "3.14") set_printing_strategy("default") - + def test9(self): print("Testing custom printing strategy") - mass = 2.0 | 0.5 * units.MSun - acc = (0.0098 | nbody_system.length) * (1 | units.Myr**-2).as_quantity_in(units.s**-2) + mass = 2.0 | 0.5 * units.MSun + acc = (0.0098 | nbody_system.length) * (1 | units.Myr**-2).as_quantity_in(units.s**-2) position = [0.1, 0.2, 0.3] | nbody_system.length - power = 10 | units.W + power = 10 | units.W temperature = 5000 | units.K - pi = 3.14 | units.none + pi = 3.14 | units.none converter = nbody_system.nbody_to_si(1.0 | units.kg, 1.0 | units.kpc) - - set_printing_strategy("custom", nbody_converter = converter, preferred_units = - [units.amu, units.AU, units.minute, units.milli(units.K), units.erg], precision = 3, - prefix = "(> ", separator = " <|> ", suffix = " <)") + + set_printing_strategy("custom", nbody_converter=converter, preferred_units=[units.amu, units.AU, units.minute, units.milli(units.K), units.erg], precision=3, + prefix="(> ", separator=" <|> ", suffix=" <)") self.assertEqual(str(mass), "(> 1.20e+57 <|> amu <)") self.assertEqual(str(acc), "(> 7.31e-18 <|> AU * min**-2 <)") self.assertEqual(str(position), "(> [2.06e+07, 4.13e+07, 6.19e+07] <|> AU <)") @@ -224,26 +220,25 @@ def test9(self): self.assertEqual(str(temperature), "(> 5.00e+06 <|> mK <)") self.assertEqual(str(pi), "(> 3.14 <|> none <)") set_printing_strategy("default") - + def test10(self): print("Testing custom printing strategy with precision keyword") - mass = 2.0 | 0.5 * units.MSun - acc = 0.23456 | 0.54321 * units.m * units.s**-2 + mass = 2.0 | 0.5 * units.MSun + acc = 0.23456 | 0.54321 * units.m * units.s**-2 velocity = [-0.12345]*3 | units.km / units.s position = [0.1234567890123456789, 0.2, 3.0] | units.AU positions = [position.number]*2 | position.unit multi_dimensional = [positions.number]*2 | positions.unit - pi = 3.1415926535 | units.none - - set_printing_strategy("custom", precision = 3) + pi = 3.1415926535 | units.none + + set_printing_strategy("custom", precision=3) self.assertEqual(str(mass), "2.00 0.5 * MSun") self.assertEqual(str(acc), "0.235 0.54321 * m * s**-2") self.assertEqual(str(velocity), "[-0.123, -0.123, -0.123] km / s") tmp = "[0.123, 0.200, 3.00]" self.assertEqual(str(position), tmp + " AU") self.assertEqual(str(positions), "["+tmp+", "+tmp+"] AU") - self.assertEqual(str(multi_dimensional), "[["+tmp+", "+tmp+ + self.assertEqual(str(multi_dimensional), "[["+tmp+", "+tmp + "], ["+tmp+", "+tmp+"]] AU") self.assertEqual(str(pi), "3.14 none") set_printing_strategy("default") - diff --git a/src/amuse/test/suite/core_tests/test_constants.py b/src/amuse/test/suite/core_tests/test_constants.py index 6420abd7d5..858175f6b2 100644 --- a/src/amuse/test/suite/core_tests/test_constants.py +++ b/src/amuse/test/suite/core_tests/test_constants.py @@ -4,7 +4,7 @@ class TestConstants(amusetest.TestCase): - + def test1(self): self.assertAlmostEqual(h.value_in(units.J*units.s), 6.6e-34, 35) self.assertAlmostEqual(c.value_in(units.m/units.s), 299792458.0, 7) @@ -23,12 +23,10 @@ def test3(self): self.assertAlmostRelativeEquals( Planck_time**2, hbar * G / c**5, 5) - + def test4(self): self.assertAlmostRelativeEquals(Rydberg_constant_times_hc_in_J, 1 | units.Ry, 7) - self.assertAlmostRelativeEquals(2 * h * Rydberg_constant, + self.assertAlmostRelativeEquals(2 * h * Rydberg_constant, fine_hyphen_structure_constant**2 * electron_mass * c, 7) - self.assertAlmostRelativeEquals(fine_hyphen_structure_constant, + self.assertAlmostRelativeEquals(fine_hyphen_structure_constant, elementary_charge**2 / (2 * h * c * electric_constant), 7) - - diff --git a/src/amuse/test/suite/core_tests/test_generate_fortran.py b/src/amuse/test/suite/core_tests/test_generate_fortran.py index e6e4b236f2..4d959d312c 100644 --- a/src/amuse/test/suite/core_tests/test_generate_fortran.py +++ b/src/amuse/test/suite/core_tests/test_generate_fortran.py @@ -6,92 +6,90 @@ from amuse.rfi.tools import create_fortran from amuse.rfi.core import * + + class ForTestingInterface(CodeInterface): - + def __init__(self, exefile, **options): CodeInterface.__init__(self, exefile, **options) @legacy_function def echo_int(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('int_in', dtype='int32', direction=function.IN) function.addParameter('int_out', dtype='int32', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - + return function + @legacy_function def echo_double(): - function = LegacyFunctionSpecification() + function = LegacyFunctionSpecification() function.addParameter('double_in', dtype='float64', direction=function.IN) function.addParameter('double_out', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True - return function - - + return function + + class TestGenerateAFortranStubStringFromASpecificationClass(amusetest.TestCase): - + def assertContainsString(self, string, substring): index = string.find(substring) if index < 0: self.fail("{0} not found in {1}".format(substring, string)) - + def assertNotContainsString(self, string, substring): index = string.find(substring) if index >= 0: self.fail("{0} found in {1}".format(substring, string)) - + def test1(self): x = create_fortran.GenerateAFortranStubStringFromASpecificationClass() x.specification_class = ForTestingInterface x.start() - outputstring = x.result + outputstring = x.result print(x.result) self.assertContainsString(outputstring, "function echo_int(int_in, int_out)") self.assertContainsString(outputstring, "integer :: echo_int") - + def test2(self): x = create_fortran.GenerateAFortranStubStringFromASpecificationClass() x.specification_class = ForTestingInterface x.start() - outputstring = x.result + outputstring = x.result self.assertNotContainsString(outputstring, "internal__") - - + + class TestGenerateAFortranSourcecodeStringFromASpecificationClass(amusetest.TestCase): - + def assertContainsString(self, string, substring): index = string.find(substring) if index < 0: self.fail("{0} not found in {1}".format(substring, string)) - + def assertNotContainsString(self, string, substring): index = string.find(substring) if index >= 0: self.fail("{0} found in {1}".format(substring, string)) - + def test1(self): x = create_fortran.GenerateAFortranSourcecodeStringFromASpecificationClass() x.specification_class = ForTestingInterface x.start() - outputstring = x.result + outputstring = x.result self.assertContainsString(outputstring, "integer :: echo_int") self.assertContainsString(outputstring, "integer :: echo_double") self.assertContainsString(outputstring, "echo_int(") self.assertContainsString(outputstring, "echo_double(") - + def test2(self): x = create_fortran.GenerateAFortranSourcecodeStringFromASpecificationClass() x.specification_class = ForTestingInterface x.underscore_functions_from_specification_classes = [ForTestingInterface] x.start() - outputstring = x.result + outputstring = x.result self.assertContainsString(outputstring, "integer :: echo_int_") self.assertContainsString(outputstring, "integer :: echo_double_") self.assertContainsString(outputstring, "echo_int_(") self.assertContainsString(outputstring, "echo_double_(") - - - - diff --git a/src/amuse/test/suite/core_tests/test_generic_units.py b/src/amuse/test/suite/core_tests/test_generic_units.py index 509f943289..dbaabf6dd9 100644 --- a/src/amuse/test/suite/core_tests/test_generic_units.py +++ b/src/amuse/test/suite/core_tests/test_generic_units.py @@ -2,6 +2,8 @@ from amuse.units import constants from amuse.units.generic_unit_converter import * + + class TestGenericUnits(amusetest.TestCase): def test1(self): L = 1 | length @@ -10,86 +12,82 @@ def test1(self): self.assertTrue(L/T == V) def test2(self): - #natural units + # natural units convert_generic = ConvertBetweenGenericAndSiUnits(constants.c, constants.hbar, constants.G, constants.kB) M = 1 | mass T = 1 | time L = 1 | length H = 1 | temperature - + M_in_si = convert_generic.to_si(M) T_in_si = convert_generic.to_si(T) L_in_si = convert_generic.to_si(L) H_in_si = convert_generic.to_si(H) - - self.assertAlmostRelativeEqual(M_in_si, 2.1764411e-8|units.kg, 3) - self.assertAlmostRelativeEqual(T_in_si, 5.39124e-44|units.s, 3) - self.assertAlmostRelativeEqual(L_in_si, 1.616252e-35|units.m, 3) - self.assertAlmostRelativeEqual(H_in_si, 1.416785e32|units.K, 3) + + self.assertAlmostRelativeEqual(M_in_si, 2.1764411e-8 | units.kg, 3) + self.assertAlmostRelativeEqual(T_in_si, 5.39124e-44 | units.s, 3) + self.assertAlmostRelativeEqual(L_in_si, 1.616252e-35 | units.m, 3) + self.assertAlmostRelativeEqual(H_in_si, 1.416785e32 | units.K, 3) def test3(self): - #Gadget units - UnitLength_in_cm = 3.085678e21 | units.cm# 1.0 kpc + # Gadget units + UnitLength_in_cm = 3.085678e21 | units.cm # 1.0 kpc UnitMass_in_g = 1.989e43 | units.g # 1.0e10 solar masses - UnitVelocity_in_cm_per_s = 1e5 | units.cm / units.s# 1 km/sec - + UnitVelocity_in_cm_per_s = 1e5 | units.cm / units.s # 1 km/sec + convert_generic = ConvertBetweenGenericAndSiUnits(UnitLength_in_cm, UnitMass_in_g, UnitVelocity_in_cm_per_s) M = 1 | mass T = 1 | time L = 1 | length - + M_in_si = convert_generic.to_si(M) T_in_si = convert_generic.to_si(T) L_in_si = convert_generic.to_si(L) - - self.assertAlmostRelativeEqual(M_in_si, 1.989e40 | units.kg, 3) + + self.assertAlmostRelativeEqual(M_in_si, 1.989e40 | units.kg, 3) self.assertAlmostRelativeEqual(T_in_si, 3.085678e16 | units.s, 3) self.assertAlmostRelativeEqual(L_in_si, 3.085678e19 | units.m, 3) - + def test4(self): print("Generic units and vector quantities") - UnitLength_in_cm = 3.085678e21 | units.cm# 1.0 kpc + UnitLength_in_cm = 3.085678e21 | units.cm # 1.0 kpc UnitMass_in_g = 1.989e43 | units.g # 1.0e10 solar masses - UnitVelocity_in_cm_per_s = 1e5 | units.cm / units.s# 1 km/sec - + UnitVelocity_in_cm_per_s = 1e5 | units.cm / units.s # 1 km/sec + convert_generic = ConvertBetweenGenericAndSiUnits(UnitLength_in_cm, UnitMass_in_g, UnitVelocity_in_cm_per_s) M = [1, 2] | mass T = [1, 2] | time L = [1, 2] | length - + M_in_si = convert_generic.to_si(M) T_in_si = convert_generic.to_si(T) L_in_si = convert_generic.to_si(L) - - self.assertAlmostEqual(M_in_si, [1.989e40, 2*1.989e40 ] | units.kg, 3, in_units=1.0e10*units.MSun) + + self.assertAlmostEqual(M_in_si, [1.989e40, 2*1.989e40] | units.kg, 3, in_units=1.0e10*units.MSun) self.assertAlmostEqual(T_in_si, [3.085678e16, 2*3.085678e16] | units.s, 3, in_units=units.s*units.kpc/units.km) self.assertAlmostEqual(L_in_si, [3.085678e19, 2*3.085678e19] | units.m, 3, in_units=3.085678e19*units.m) - def test5(self): - - self.assertRaises(UnitsNotOrtogonalException, ConvertBetweenGenericAndSiUnits, 1 | units.km, 2 | units.s, - 3 | units.km / units.s, expected_message = "The number of orthoganal units is incorrect, expected 3 " + + self.assertRaises(UnitsNotOrtogonalException, ConvertBetweenGenericAndSiUnits, 1 | units.km, 2 | units.s, + 3 | units.km / units.s, expected_message="The number of orthoganal units is incorrect, expected 3 " "but found 2. To convert between S.I. units and another system of units a set of quantities with " "orthogonal units is needed. These can be quantities with a single unit (such as length or time) " "or quantities with a derived units (such as velocity or force)") - - + def test6(self): self.assertRaises(NotAQuantityException, ConvertBetweenGenericAndSiUnits, 1) - self.assertRaises(NotAScalarException, ConvertBetweenGenericAndSiUnits, 1 | units.km, [1,2] | units.s, ) - + self.assertRaises(NotAScalarException, ConvertBetweenGenericAndSiUnits, 1 | units.km, [1, 2] | units.s, ) + def test7(self): converter = ConvertBetweenGenericAndSiUnits(1.0 | units.MSun, 1.0 | units.AU, 1.0 | units.yr) G_in_generic = converter.to_generic(constants.G) self.assertEqual(str(G_in_generic.unit), 'length**3 * mass**-1 * time**-2') self.assertAlmostEqual(G_in_generic.number, 39.4852492465) - + time_unit = ((1.0 | units.AU)**3 / (constants.G * (1.0 | units.MSun))).sqrt().as_quantity_in(units.yr) self.assertAlmostEqual(time_unit, 0.159141174195 | units.yr) converter = ConvertBetweenGenericAndSiUnits(1.0 | units.MSun, 1.0 | units.AU, time_unit) G_in_generic = converter.to_generic(constants.G) self.assertEqual(str(G_in_generic.unit), 'length**3 * mass**-1 * time**-2') self.assertAlmostEqual(G_in_generic.number, 1.0) - - diff --git a/src/amuse/test/suite/core_tests/test_grid_attributes.py b/src/amuse/test/suite/core_tests/test_grid_attributes.py index e66dbbd213..496846e90b 100644 --- a/src/amuse/test/suite/core_tests/test_grid_attributes.py +++ b/src/amuse/test/suite/core_tests/test_grid_attributes.py @@ -4,79 +4,78 @@ import numpy + class TestGridAttributes(amusetest.TestCase): - + def test1(self): - grid=new_cartesian_grid((10,20),1.) - self.assertEqual(grid.cellsize(),[1.,1.]) - self.assertEqual(grid.get_minimum_index(), (0,0)) - self.assertEqual(grid.get_maximum_index(), (9,19)) - self.assertEqual(grid.get_minimum_position(), [0.,0.]) - self.assertEqual(grid.get_maximum_position(), [10.,20.]) + grid = new_cartesian_grid((10, 20), 1.) + self.assertEqual(grid.cellsize(), [1., 1.]) + self.assertEqual(grid.get_minimum_index(), (0, 0)) + self.assertEqual(grid.get_maximum_index(), (9, 19)) + self.assertEqual(grid.get_minimum_position(), [0., 0.]) + self.assertEqual(grid.get_maximum_position(), [10., 20.]) self.assertEqual(grid.get_volume(), 10*20.) - self.assertEqual(grid.contains(numpy.asarray([[1,1],[-10,-10]])), [True,False]) - points=grid.points() - x=points[:,:,0] - y=points[:,:,1] - self.assertEqual([x,y],numpy.indices((11,21))) + self.assertEqual(grid.contains(numpy.asarray([[1, 1], [-10, -10]])), [True, False]) + points = grid.points() + x = points[:, :, 0] + y = points[:, :, 1] + self.assertEqual([x, y], numpy.indices((11, 21))) - grid2=new_cartesian_grid((10,20),1., offset=(5,5)) + grid2 = new_cartesian_grid((10, 20), 1., offset=(5, 5)) self.assertTrue(grid.overlaps(grid2)) - grid3=new_cartesian_grid((10,20),1., offset=(15,25)) + grid3 = new_cartesian_grid((10, 20), 1., offset=(15, 25)) self.assertFalse(grid.overlaps(grid3)) - overlap=grid.get_overlap_with(grid2) - self.assertEqual(overlap.shape,(5,15)) - + overlap = grid.get_overlap_with(grid2) + self.assertEqual(overlap.shape, (5, 15)) + def test2(self): - grid=new_regular_grid((10,20),(10,10)) - self.assertEqual(grid.cellsize(),[1.,0.5]) - self.assertEqual(grid.get_minimum_index(), (0,0)) - self.assertEqual(grid.get_maximum_index(), (9,19)) - self.assertEqual(grid.get_minimum_position(), [0.,0.]) - self.assertEqual(grid.get_maximum_position(), [10.,10.]) + grid = new_regular_grid((10, 20), (10, 10)) + self.assertEqual(grid.cellsize(), [1., 0.5]) + self.assertEqual(grid.get_minimum_index(), (0, 0)) + self.assertEqual(grid.get_maximum_index(), (9, 19)) + self.assertEqual(grid.get_minimum_position(), [0., 0.]) + self.assertEqual(grid.get_maximum_position(), [10., 10.]) self.assertEqual(grid.get_volume(), 10*10.) - self.assertEqual(grid.contains(numpy.asarray([[1,1],[-10,-10]])), [True,False]) - points=grid.points() - x=points[:,:,0] - y=points[:,:,1] - xp,yp=numpy.indices((11,21)) - self.assertEqual(x,xp) - self.assertEqual(y,yp*0.5) + self.assertEqual(grid.contains(numpy.asarray([[1, 1], [-10, -10]])), [True, False]) + points = grid.points() + x = points[:, :, 0] + y = points[:, :, 1] + xp, yp = numpy.indices((11, 21)) + self.assertEqual(x, xp) + self.assertEqual(y, yp*0.5) - grid2=new_cartesian_grid((10,20),1., offset=(5,5)) + grid2 = new_cartesian_grid((10, 20), 1., offset=(5, 5)) self.assertTrue(grid.overlaps(grid2)) - grid3=new_cartesian_grid((10,20),1., offset=(15,25)) + grid3 = new_cartesian_grid((10, 20), 1., offset=(15, 25)) self.assertFalse(grid.overlaps(grid3)) - overlap=grid.get_overlap_with(grid2) - self.assertEqual(overlap.shape,(5,10)) - + overlap = grid.get_overlap_with(grid2) + self.assertEqual(overlap.shape, (5, 10)) def test3(self): - x=numpy.arange(11)/10. - y=numpy.arange(21)/20. - grid=new_rectilinear_grid((10,20),(x,y**2)) + x = numpy.arange(11)/10. + y = numpy.arange(21)/20. + grid = new_rectilinear_grid((10, 20), (x, y**2)) self.assertRaises(Exception, grid.cellsize, expected_message="a RectilinearGrid does not have a constant cellsize, use the cellsizes method instead") def xtest4(self): - grid=new_structured_grid((10,20),(10,10)) - self.assertEqual(grid.cellsize(),[1.,0.5]) + grid = new_structured_grid((10, 20), (10, 10)) + self.assertEqual(grid.cellsize(), [1., 0.5]) def xtest5(self): - grid=new_unstructured_grid((10,20),(10,10)) - self.assertEqual(grid.cellsize(),[1.,0.5]) + grid = new_unstructured_grid((10, 20), (10, 10)) + self.assertEqual(grid.cellsize(), [1., 0.5]) def test6(self): - grid=new_regular_grid((10,10),(10,10)) - self.assertEqual(grid.get_index((6.2,3.7)), [6,3]) - self.assertEqual(grid.get_index(x=[6.2],y=[3.7]), [6,3]) - self.assertEqual(grid.get_index(y=[6.2],x=[3.7]), [3,6]) - self.assertEqual(grid.get_index(y=6.2,x=3.7)[0], 3) - self.assertEqual(grid.get_index(y=6.2,x=3.7)[1], 6) - - def test7(self): - grid=new_regular_grid((10,10),[20,10] | units.m,axes_names="ab") - self.assertEqual(grid.get_index([16.2,3.7] | units.m), [8,3]) - self.assertEqual(grid.get_index(a=16.2 | units.m,b=3.7 | units.m), [8,3]) - self.assertEqual(grid.get_index(a=[16.2, 4.5] | units.m,b=[3.7,4.2] | units.m), [[8,3],[2,4]]) + grid = new_regular_grid((10, 10), (10, 10)) + self.assertEqual(grid.get_index((6.2, 3.7)), [6, 3]) + self.assertEqual(grid.get_index(x=[6.2], y=[3.7]), [6, 3]) + self.assertEqual(grid.get_index(y=[6.2], x=[3.7]), [3, 6]) + self.assertEqual(grid.get_index(y=6.2, x=3.7)[0], 3) + self.assertEqual(grid.get_index(y=6.2, x=3.7)[1], 6) + def test7(self): + grid = new_regular_grid((10, 10), [20, 10] | units.m, axes_names="ab") + self.assertEqual(grid.get_index([16.2, 3.7] | units.m), [8, 3]) + self.assertEqual(grid.get_index(a=16.2 | units.m, b=3.7 | units.m), [8, 3]) + self.assertEqual(grid.get_index(a=[16.2, 4.5] | units.m, b=[3.7, 4.2] | units.m), [[8, 3], [2, 4]]) diff --git a/src/amuse/test/suite/core_tests/test_grids.py b/src/amuse/test/suite/core_tests/test_grids.py index 4c1f000de6..36808e163b 100644 --- a/src/amuse/test/suite/core_tests/test_grids.py +++ b/src/amuse/test/suite/core_tests/test_grids.py @@ -14,71 +14,72 @@ from amuse.units import nbody_system from amuse import datamodel + class TestGrids(amusetest.TestCase): - + def test1(self): - grid = datamodel.Grid(5,4,3) + grid = datamodel.Grid(5, 4, 3) grid.mass = 2.0 | units.kg self.assertEqual(grid.mass[0][1][2], 2.0 | units.kg) self.assertEqual(grid[0][1][2].mass, 2.0 | units.kg) self.assertEqual(len(grid.mass), 5) - + def test2(self): - grid = datamodel.Grid(5,4,3) - grid.mass = units.kg.new_quantity(numpy.arange(5*4*3).reshape(5,4,3)) + grid = datamodel.Grid(5, 4, 3) + grid.mass = units.kg.new_quantity(numpy.arange(5*4*3).reshape(5, 4, 3)) self.assertEqual(grid.number_of_dimensions(), 3) subgrid = grid[1] self.assertEqual(subgrid.number_of_dimensions(), 2) - self.assertEqual(subgrid.mass.number.shape, (4,3)) - + self.assertEqual(subgrid.mass.number.shape, (4, 3)) + def test3(self): - grid = datamodel.Grid(5,4,3) - values = numpy.arange(5*4*3).reshape(5,4,3) + grid = datamodel.Grid(5, 4, 3) + values = numpy.arange(5*4*3).reshape(5, 4, 3) grid.mass = units.kg.new_quantity(values) self.assertEqual(grid.number_of_dimensions(), 3) - + subgrid = grid[1][2] self.assertEqual(subgrid.number_of_dimensions(), 1) self.assertEqual(subgrid.mass.number.shape, (3,)) self.assertTrue(numpy.all(values[1][2] == subgrid.mass.value_in(units.kg))) - + def test4(self): - grid = datamodel.Grid(5,4,3) - values = numpy.arange(5*4*3).reshape(5,4,3) + grid = datamodel.Grid(5, 4, 3) + values = numpy.arange(5*4*3).reshape(5, 4, 3) grid.mass = units.kg.new_quantity(values) self.assertEqual(grid.number_of_dimensions(), 3) - + gridpoint = grid[1][2][1] self.assertEqual(gridpoint.mass, 19.0 | units.kg) gridpoint = grid[1][2][2] self.assertEqual(gridpoint.mass, 20.0 | units.kg) - + def test5(self): - grid = datamodel.Grid(5,4,3) - grid.add_calculated_attribute("squared_mass", lambda m : m * m, ["mass",]) - values = numpy.arange(5*4*3).reshape(5,4,3) + grid = datamodel.Grid(5, 4, 3) + grid.add_calculated_attribute("squared_mass", lambda m: m * m, ["mass",]) + values = numpy.arange(5*4*3).reshape(5, 4, 3) grid.mass = units.kg.new_quantity(values) gridpoint = grid[1][2][1] self.assertEqual(gridpoint.mass, 19.0 | units.kg) self.assertEqual(gridpoint.squared_mass, (19.0 | units.kg) ** 2) subgrid = grid[1][2] self.assertTrue(numpy.all(subgrid.squared_mass == ([18.0, 19.0, 20.0] | units.kg) ** 2)) - + def test6(self): - grid = datamodel.Grid(5,4,3) - grid.add_function_attribute("sum_mass", lambda grid, x : grid.mass.sum() + x, lambda grid, gridpoint, x : gridpoint.mass + x) - values = numpy.arange(5*4*3).reshape(5,4,3) + grid = datamodel.Grid(5, 4, 3) + grid.add_function_attribute("sum_mass", lambda grid, x: grid.mass.sum() + x, lambda grid, gridpoint, x: gridpoint.mass + x) + values = numpy.arange(5*4*3).reshape(5, 4, 3) grid.mass = units.kg.new_quantity(values) gridpoint = grid[1][2][1] self.assertEqual(gridpoint.mass, 19.0 | units.kg) - self.assertEqual(gridpoint.sum_mass(2.0 | units.kg), (21.0 | units.kg) ) + self.assertEqual(gridpoint.sum_mass(2.0 | units.kg), (21.0 | units.kg)) subgrid = grid[1][2] self.assertTrue(numpy.all(subgrid.sum_mass(2 | units.kg) == (18.0 + 19.0 + 20.0 + 2.0 | units.kg))) - + def test7(self): - grid = datamodel.Grid(5,4,3) - grid.add_vector_attribute("position", ["x","y","z"]) - x = numpy.arange(5*4*3).reshape(5,4,3) + grid = datamodel.Grid(5, 4, 3) + grid.add_vector_attribute("position", ["x", "y", "z"]) + x = numpy.arange(5*4*3).reshape(5, 4, 3) y = x + 100.0 z = x + 200.0 grid.x = units.m.new_quantity(x) @@ -92,121 +93,114 @@ def test7(self): self.assertEqual(subgrid.position[1][0], 19 | units.m) self.assertEqual(subgrid.position[1][1], 119 | units.m) self.assertEqual(subgrid.position[1][2], 219 | units.m) - - + def test8(self): - grid0 = datamodel.Grid(5,4,3) - x = numpy.arange(5*4*3).reshape(5,4,3) + grid0 = datamodel.Grid(5, 4, 3) + x = numpy.arange(5*4*3).reshape(5, 4, 3) y = x + 100.0 grid0.x = units.m.new_quantity(x) grid0.y = units.m.new_quantity(y) - - grid1 = datamodel.Grid(5,4,3) - x = numpy.arange(5*4*3).reshape(5,4,3) + + grid1 = datamodel.Grid(5, 4, 3) + x = numpy.arange(5*4*3).reshape(5, 4, 3) x = x + 200.0 y = x + 200.0 grid1.x = units.m.new_quantity(x) grid1.y = units.m.new_quantity(y) - + self.assertTrue(numpy.all(grid0[1][2].x != grid1[1][2].x)) - + channel = grid0.new_channel_to(grid1) channel.copy_attributes(["x",]) - + self.assertTrue(numpy.all(grid0[1][2].x == grid1[1][2].x)) self.assertTrue(numpy.all(grid0[1][2].y != grid1[1][2].y)) - - - def test9(self): - grid = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) + grid = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) self.assertEqual(grid[0][0][0].x, 0.1 | units.m) self.assertEqual(grid[0][0][0].y, 0.125 | units.m) self.assertEqual(grid[0][0][0].z, 0.25 | units.m) - self.assertEqual(grid[...,0,0].x, [0.1,0.3,0.5,0.7,0.9] | units.m) - self.assertEqual(grid[0,0,...].z, [0.25, 0.75] | units.m) - + self.assertEqual(grid[..., 0, 0].x, [0.1, 0.3, 0.5, 0.7, 0.9] | units.m) + self.assertEqual(grid[0, 0, ...].z, [0.25, 0.75] | units.m) + cellsize = grid.cellsize() self.assertAlmostRelativeEquals(cellsize[0], 0.2 | units.m) self.assertAlmostRelativeEquals(cellsize[1], 0.25 | units.m) self.assertAlmostRelativeEquals(cellsize[2], 0.5 | units.m) - - def test11(self): - grid = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - iarray,jarray,karray = grid.indices() + grid = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + iarray, jarray, karray = grid.indices() for i in range(5): for j in range(4): for k in range(2): self.assertEqual(iarray[i][j][k], i) self.assertEqual(jarray[i][j][k], j) self.assertEqual(karray[i][j][k], k) - iarray,jarray,karray = grid.indices() + iarray, jarray, karray = grid.indices() i = 0 for j in range(4): for k in range(2): self.assertEqual(iarray[i][j][k], i) self.assertEqual(jarray[i][j][k], j) self.assertEqual(karray[i][j][k], k) - - iarray,jarray,karray = grid[...,0,0].indices() + + iarray, jarray, karray = grid[..., 0, 0].indices() j = 0 k = 0 for i in range(5): self.assertEqual(iarray[i], i) self.assertEqual(jarray[i], j) self.assertEqual(karray[i], k) - iarray,jarray,karray = grid[3,2,...].indices() + iarray, jarray, karray = grid[3, 2, ...].indices() i = 3 j = 2 for k in range(2): self.assertEqual(iarray[k], i) self.assertEqual(jarray[k], j) self.assertEqual(karray[k], k) - iarray,jarray,karray = grid[2,...,1].indices() + iarray, jarray, karray = grid[2, ..., 1].indices() i = 2 k = 1 for j in range(4): self.assertEqual(iarray[j], i) self.assertEqual(jarray[j], j) self.assertEqual(karray[j], k) - - + def test12(self): - grid = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - self.assertEqual(grid[grid.x > 0.4| units.m].x.shape, (24,)) - self.assertEqual(grid[grid.x>0.4| units.m].x, grid.x[grid.x>0.4|units.m]) - iarray,jarray,karray = grid.indices() - self.assertEqual(grid[grid.x>0.4| units.m].indices()[0], iarray[grid.x>0.4| units.m]) - self.assertEqual(grid[grid.x>0.4| units.m].indices()[1], jarray[grid.x>0.4| units.m]) - self.assertEqual(grid[grid.x>0.4| units.m].indices()[2], karray[grid.x>0.4| units.m]) - + grid = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + self.assertEqual(grid[grid.x > 0.4 | units.m].x.shape, (24,)) + self.assertEqual(grid[grid.x > 0.4 | units.m].x, grid.x[grid.x > 0.4 | units.m]) + iarray, jarray, karray = grid.indices() + self.assertEqual(grid[grid.x > 0.4 | units.m].indices()[0], iarray[grid.x > 0.4 | units.m]) + self.assertEqual(grid[grid.x > 0.4 | units.m].indices()[1], jarray[grid.x > 0.4 | units.m]) + self.assertEqual(grid[grid.x > 0.4 | units.m].indices()[2], karray[grid.x > 0.4 | units.m]) + def test13(self): - grid = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - self.assertEqual(grid[0].shape, (4,2)) + grid = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + self.assertEqual(grid[0].shape, (4, 2)) self.assertEqual(grid[0][0].shape, (2,)) - self.assertEqual(grid[...,2,1].shape, (5,)) - + self.assertEqual(grid[..., 2, 1].shape, (5,)) + def test14(self): - grid = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) + grid = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) self.assertEqual(grid[0].x, grid.x[0]) self.assertEqual(grid[0][1].x, grid.x[0][1]) self.assertEqual(grid[1][2][1].x, grid.x[1][2][1]) - self.assertEqual(grid[...,2,1].x, grid.x[...,2,1]) - self.assertEqual(grid[1,...,1].x, grid.x[1,...,1]) - self.assertEqual(grid[1,2,...].x, grid.x[1,2,...]) - self.assertEqual(grid[...,1].x, grid.x[...,1]) - self.assertEqual(grid[2,...].x, grid.x[2,...]) - self.assertEqual(grid[:,3,:].x, grid.x[:,3,:]) - self.assertEqual(grid[:,3,:].y, grid.y[:,3,:]) - self.assertEqual(grid[:,3,:].z, grid.z[:,3,:]) - + self.assertEqual(grid[..., 2, 1].x, grid.x[..., 2, 1]) + self.assertEqual(grid[1, ..., 1].x, grid.x[1, ..., 1]) + self.assertEqual(grid[1, 2, ...].x, grid.x[1, 2, ...]) + self.assertEqual(grid[..., 1].x, grid.x[..., 1]) + self.assertEqual(grid[2, ...].x, grid.x[2, ...]) + self.assertEqual(grid[:, 3, :].x, grid.x[:, 3, :]) + self.assertEqual(grid[:, 3, :].y, grid.y[:, 3, :]) + self.assertEqual(grid[:, 3, :].z, grid.z[:, 3, :]) + def test15(self): - - grid = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - nk = nj = ni =0 + + grid = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + nk = nj = ni = 0 for plane1 in grid: nk += 1 for plane2 in plane1: @@ -216,124 +210,119 @@ def test15(self): self.assertEqual(nk, 5) self.assertEqual(nj, 4 * 5) self.assertEqual(ni, 2 * 4 * 5) - + def test16(self): - grid = datamodel.new_regular_grid((5,4,2,4), [1.0 | units.m, 1.0 | units.m, 1.0 | units.m, 1.0 | units.s], ('x', 'y', 'z', 't') ) - self.assertEqual(grid.shape, (5,4,2,4)) - self.assertEqual(grid.x.shape, (5,4,2,4)) - self.assertAlmostRelativeEquals( grid[1][2][1].x, ([0.3] * 4) | units.m) - self.assertAlmostRelativeEquals( grid[1][2][1].t, [0.125, 0.375, 0.625, 0.875] | units.s) + grid = datamodel.new_regular_grid((5, 4, 2, 4), [1.0 | units.m, 1.0 | units.m, 1.0 | units.m, 1.0 | units.s], ('x', 'y', 'z', 't')) + self.assertEqual(grid.shape, (5, 4, 2, 4)) + self.assertEqual(grid.x.shape, (5, 4, 2, 4)) + self.assertAlmostRelativeEquals(grid[1][2][1].x, ([0.3] * 4) | units.m) + self.assertAlmostRelativeEquals(grid[1][2][1].t, [0.125, 0.375, 0.625, 0.875] | units.s) self.assertEqual(grid[0].x, grid.x[0]) self.assertEqual(grid[0][1].x, grid.x[0][1]) self.assertEqual(grid[1][2][1].x, grid.x[1][2][1]) self.assertEqual(grid[1][2][1][2].x, grid.x[1][2][1][2]) def test17(self): - grid = datamodel.new_regular_grid((4,2), [1.0 | units.m, 1.0 | units.m]) - self.assertEqual(grid.shape, (4,2) ) - self.assertEqual(grid.x.shape, (4,2)) - self.assertAlmostRelativeEquals( grid[1].x, ([0.375] * 2) | units.m) - self.assertAlmostRelativeEquals( grid[1][1].y, 0.75 | units.m) + grid = datamodel.new_regular_grid((4, 2), [1.0 | units.m, 1.0 | units.m]) + self.assertEqual(grid.shape, (4, 2)) + self.assertEqual(grid.x.shape, (4, 2)) + self.assertAlmostRelativeEquals(grid[1].x, ([0.375] * 2) | units.m) + self.assertAlmostRelativeEquals(grid[1][1].y, 0.75 | units.m) self.assertEqual(grid[0].x, grid.x[0]) self.assertEqual(grid[0][1].x, grid.x[0][1]) - + def test18(self): - grid = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - self.assertEqual(grid.shape, (5,4,2) ) - self.assertEqual(grid[1:2,...].x.shape, (1,4,2 )) - self.assertEqual(grid[1:2,...].shape, (1,4,2) ) - self.assertEqual(grid[1:2,...].x, grid.x[1:2,...]) - self.assertEqual(grid[1:3,...].x.shape, (2,4,2) ) - self.assertEqual(grid[1:3,...].shape, (2,4,2) ) - self.assertEqual(grid[1:3,...].x, grid.x[1:3,...]) + grid = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + self.assertEqual(grid.shape, (5, 4, 2)) + self.assertEqual(grid[1:2, ...].x.shape, (1, 4, 2)) + self.assertEqual(grid[1:2, ...].shape, (1, 4, 2)) + self.assertEqual(grid[1:2, ...].x, grid.x[1:2, ...]) + self.assertEqual(grid[1:3, ...].x.shape, (2, 4, 2)) + self.assertEqual(grid[1:3, ...].shape, (2, 4, 2)) + self.assertEqual(grid[1:3, ...].x, grid.x[1:3, ...]) def test19(self): - grid = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - self.assertEqual(grid[1:3,...].x, grid.x[1:3,...]) - self.assertEqual(grid[1:3,2:3,...].x, grid.x[1:3,2:3,...]) - self.assertEqual(grid[1:3,2:3,0:1].x, grid.x[1:3,2:3,0:1]) - self.assertEqual(grid[1:3,...,0:1].x, grid.x[1:3,...,0:1]) - self.assertEqual(grid[...,0:1].x, grid.x[...,0:1]) - self.assertEqual(grid[...,2:3,0:1].x, grid.x[...,2:3,0:1]) - + grid = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + self.assertEqual(grid[1:3, ...].x, grid.x[1:3, ...]) + self.assertEqual(grid[1:3, 2:3, ...].x, grid.x[1:3, 2:3, ...]) + self.assertEqual(grid[1:3, 2:3, 0:1].x, grid.x[1:3, 2:3, 0:1]) + self.assertEqual(grid[1:3, ..., 0:1].x, grid.x[1:3, ..., 0:1]) + self.assertEqual(grid[..., 0:1].x, grid.x[..., 0:1]) + self.assertEqual(grid[..., 2:3, 0:1].x, grid.x[..., 2:3, 0:1]) + def test20(self): - grid = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - self.assertEqual(grid[1:3,:,:].x, grid.x[1:3,:,:]) - self.assertEqual(grid[1:3,2:3,:].x, grid.x[1:3,2:3,:]) - self.assertEqual(grid[1:3,2:3,0:1].x, grid.x[1:3,2:3,0:1]) - self.assertEqual(grid[1:3,:,0:1].x, grid.x[1:3,:,0:1]) - self.assertEqual(grid[:,:,0:1].x, grid.x[:,:,0:1]) - self.assertEqual(grid[:,2:3,0:1].x, grid.x[:,2:3,0:1]) - - + grid = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + self.assertEqual(grid[1:3, :, :].x, grid.x[1:3, :, :]) + self.assertEqual(grid[1:3, 2:3, :].x, grid.x[1:3, 2:3, :]) + self.assertEqual(grid[1:3, 2:3, 0:1].x, grid.x[1:3, 2:3, 0:1]) + self.assertEqual(grid[1:3, :, 0:1].x, grid.x[1:3, :, 0:1]) + self.assertEqual(grid[:, :, 0:1].x, grid.x[:, :, 0:1]) + self.assertEqual(grid[:, 2:3, 0:1].x, grid.x[:, 2:3, 0:1]) + def test21(self): - grid = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - self.assertEqual(grid[1:3,:,:].copy().x, grid.x[1:3,:,:]) - self.assertEqual(grid[1:3,:,:].copy().shape, (2,4,2)) - self.assertEqual(grid[1:3,2:3,:].copy().x, grid.x[1:3,2:3,:]) - self.assertEqual(grid[1:3,2:3,:].copy().shape, (2,1,2)) - self.assertEqual(grid[1:3,2:3,0:1].copy().x, grid.x[1:3,2:3,0:1]) - self.assertEqual(grid[1:3,2:3,0:1].copy().shape, (2,1,1)) - self.assertEqual(grid[1:3,:,0:1].copy().x, grid.x[1:3,:,0:1]) - self.assertEqual(grid[1:3,:,0:1].copy().shape, (2,4,1)) - self.assertEqual(grid[:,:,0:1].copy().x, grid.x[:,:,0:1]) - self.assertEqual(grid[:,:,0:1].copy().shape, (5,4,1)) - self.assertEqual(grid[:,2:3,0:1].copy().x, grid.x[:,2:3,0:1]) - self.assertEqual(grid[:,2:3,0:1].copy().shape, (5,1,1)) - - + grid = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + self.assertEqual(grid[1:3, :, :].copy().x, grid.x[1:3, :, :]) + self.assertEqual(grid[1:3, :, :].copy().shape, (2, 4, 2)) + self.assertEqual(grid[1:3, 2:3, :].copy().x, grid.x[1:3, 2:3, :]) + self.assertEqual(grid[1:3, 2:3, :].copy().shape, (2, 1, 2)) + self.assertEqual(grid[1:3, 2:3, 0:1].copy().x, grid.x[1:3, 2:3, 0:1]) + self.assertEqual(grid[1:3, 2:3, 0:1].copy().shape, (2, 1, 1)) + self.assertEqual(grid[1:3, :, 0:1].copy().x, grid.x[1:3, :, 0:1]) + self.assertEqual(grid[1:3, :, 0:1].copy().shape, (2, 4, 1)) + self.assertEqual(grid[:, :, 0:1].copy().x, grid.x[:, :, 0:1]) + self.assertEqual(grid[:, :, 0:1].copy().shape, (5, 4, 1)) + self.assertEqual(grid[:, 2:3, 0:1].copy().x, grid.x[:, 2:3, 0:1]) + self.assertEqual(grid[:, 2:3, 0:1].copy().shape, (5, 1, 1)) + def test22(self): - grid1 = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - grid2 = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - slice1 = grid1[1:3,:,:].copy() - slice2 = grid2[1:3,:,:] + grid1 = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + grid2 = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + slice1 = grid1[1:3, :, :].copy() + slice2 = grid2[1:3, :, :] slice1.x = -10 | units.m channel = slice1.new_channel_to(slice2) channel.copy() self.assertEqual(grid2.x[1:3], -10 | units.m) - self.assertEqual(grid2.x[4],grid1.x[4]) - - + self.assertEqual(grid2.x[4], grid1.x[4]) + def test23(self): - grid1 = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - grid2 = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - self.assertEqual(grid1[1:3,...].shape,(2,4,2)) - slice1 = grid1[1:3,...].copy() - slice2 = grid2[1:3,...] + grid1 = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + grid2 = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + self.assertEqual(grid1[1:3, ...].shape, (2, 4, 2)) + slice1 = grid1[1:3, ...].copy() + slice2 = grid2[1:3, ...] slice1.x = -10 | units.m channel = slice1.new_channel_to(slice2) channel.copy() self.assertEqual(grid2.x[1:3], -10 | units.m) - self.assertEqual(grid2.x[4],grid1.x[4]) - - + self.assertEqual(grid2.x[4], grid1.x[4]) + def test24(self): particle = datamodel.Particle() particle.mass = 10 | units.kg - - grid = datamodel.Grid(5,4,3) + + grid = datamodel.Grid(5, 4, 3) grid.mass = 2.0 | units.kg grid.nounit = 10 self.assertEqual(grid.nounit[0][1][2], 10) self.assertEqual(grid[0][1][2].nounit, 10) self.assertEqual(len(grid.nounit), 5) - #grid[0][1][0].particle = particle - #self.assertEquals(grid.mass[0][1][2], 2.0 | units.kg) - #self.assertEquals(grid[0][1][0].particle, particle) - #self.assertEquals(grid[0][1][1].particle, None) - + # grid[0][1][0].particle = particle + # self.assertEquals(grid.mass[0][1][2], 2.0 | units.kg) + # self.assertEquals(grid[0][1][0].particle, particle) + # self.assertEquals(grid[0][1][1].particle, None) def test25(self): - grid = datamodel.Grid(5,4,3) + grid = datamodel.Grid(5, 4, 3) grid.mass = 2.0 | units.kg for cell in grid.iter_cells(): self.assertEqual(cell.mass, 2.0 | units.kg) - + def test26(self): - - grid = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - - xv, yv, zv = numpy.mgrid[0:5,0:4,0:2] + + grid = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + + xv, yv, zv = numpy.mgrid[0:5, 0:4, 0:2] xv = xv.flatten() yv = yv.flatten() zv = zv.flatten() @@ -344,328 +333,324 @@ def test26(self): i += 1 def test27(self): - grid = datamodel.new_regular_grid((3,3), [1.0, 1.0] | units.m) - subgrid1=grid[0:1,0:2] - subgrid2=grid[0:1,0:2] - subgrid3=grid[0:2,0:3][0:1,0:2] - subgrid4=grid[0:1,0:3] - - self.assertTrue(subgrid1==subgrid2) - self.assertTrue(subgrid1==subgrid3) - self.assertTrue(subgrid2==subgrid3) - self.assertFalse(subgrid1==subgrid4) - self.assertFalse(subgrid2==subgrid4) - self.assertFalse(subgrid3==subgrid4) + grid = datamodel.new_regular_grid((3, 3), [1.0, 1.0] | units.m) + subgrid1 = grid[0:1, 0:2] + subgrid2 = grid[0:1, 0:2] + subgrid3 = grid[0:2, 0:3][0:1, 0:2] + subgrid4 = grid[0:1, 0:3] + + self.assertTrue(subgrid1 == subgrid2) + self.assertTrue(subgrid1 == subgrid3) + self.assertTrue(subgrid2 == subgrid3) + self.assertFalse(subgrid1 == subgrid4) + self.assertFalse(subgrid2 == subgrid4) + self.assertFalse(subgrid3 == subgrid4) def test28(self): - grid = datamodel.Grid(200,400) - subgrid1=grid[1:-1,1:-1] - subgrid2=subgrid1[3:5,1:399] - self.assertEqual(subgrid2.shape,(2,397)) + grid = datamodel.Grid(200, 400) + subgrid1 = grid[1:-1, 1:-1] + subgrid2 = subgrid1[3:5, 1:399] + self.assertEqual(subgrid2.shape, (2, 397)) def test29(self): grid = datamodel.Grid(200) - subgrid1=grid[1:-1] - subgrid2=subgrid1[3:5] - self.assertEqual(subgrid2.shape,(2,)) + subgrid1 = grid[1:-1] + subgrid2 = subgrid1[3:5] + self.assertEqual(subgrid2.shape, (2,)) def test30(self): grid = datamodel.Grid(200) - subgrid1=grid[1:199] - subgrid2=subgrid1[3:5] - self.assertEqual(subgrid2.shape,(2,)) + subgrid1 = grid[1:199] + subgrid2 = subgrid1[3:5] + self.assertEqual(subgrid2.shape, (2,)) def test31(self): - grid = datamodel.Grid(20,20,20) - a=numpy.zeros((20,20,20)) - self.assertEqual(a[1].shape,grid[1].shape) - self.assertEqual(a[1,2].shape,grid[1,2].shape) - self.assertEqual(a[1:5].shape,grid[1:5].shape) - self.assertEqual(a[2,1:5].shape,grid[2,1:5].shape) - self.assertEqual(a[2,...].shape,grid[2,...].shape) - self.assertEqual(a[...,3,:].shape,grid[...,3,:].shape) - self.assertEqual(a[...,3:5,:].shape,grid[...,3:5,:].shape) - self.assertEqual(a[...,3:5,:].shape,grid[...,3:5,:].shape) - self.assertEqual(a[::,::2].shape,grid[::,::2].shape) + grid = datamodel.Grid(20, 20, 20) + a = numpy.zeros((20, 20, 20)) + self.assertEqual(a[1].shape, grid[1].shape) + self.assertEqual(a[1, 2].shape, grid[1, 2].shape) + self.assertEqual(a[1:5].shape, grid[1:5].shape) + self.assertEqual(a[2, 1:5].shape, grid[2, 1:5].shape) + self.assertEqual(a[2, ...].shape, grid[2, ...].shape) + self.assertEqual(a[..., 3, :].shape, grid[..., 3, :].shape) + self.assertEqual(a[..., 3:5, :].shape, grid[..., 3:5, :].shape) + self.assertEqual(a[..., 3:5, :].shape, grid[..., 3:5, :].shape) + self.assertEqual(a[::, ::2].shape, grid[::, ::2].shape) def test32(self): grid = datamodel.Grid(200) - grid.mass=numpy.arange(200) - - self.assertEqual(grid[1].mass,grid.mass[1]) - self.assertEqual(grid[1:-1].mass,grid.mass[1:-1]) - self.assertEqual(grid[-1:1:-1].mass,grid.mass[-1:1:-1]) - self.assertEqual(grid[-1:1:-1][1:-1].mass,grid.mass[-1:1:-1][1:-1]) - self.assertEqual(grid[-1:1:-1][-1:1].mass,grid.mass[-1:1:-1][-1:1]) - self.assertEqual(grid[-1:1:-1][-1:1:-3].mass,grid.mass[-1:1:-1][-1:1:-3]) - self.assertEqual(grid[300:1:-2][-1:5:-3].mass,grid.mass[300:1:-2][-1:5:-3]) - self.assertEqual(grid[100::-2][::3].mass,grid.mass[100::-2][::3]) - self.assertEqual(grid[100::-2][::-3].mass,grid.mass[100::-2][::-3]) - + grid.mass = numpy.arange(200) + + self.assertEqual(grid[1].mass, grid.mass[1]) + self.assertEqual(grid[1:-1].mass, grid.mass[1:-1]) + self.assertEqual(grid[-1:1:-1].mass, grid.mass[-1:1:-1]) + self.assertEqual(grid[-1:1:-1][1:-1].mass, grid.mass[-1:1:-1][1:-1]) + self.assertEqual(grid[-1:1:-1][-1:1].mass, grid.mass[-1:1:-1][-1:1]) + self.assertEqual(grid[-1:1:-1][-1:1:-3].mass, grid.mass[-1:1:-1][-1:1:-3]) + self.assertEqual(grid[300:1:-2][-1:5:-3].mass, grid.mass[300:1:-2][-1:5:-3]) + self.assertEqual(grid[100::-2][::3].mass, grid.mass[100::-2][::3]) + self.assertEqual(grid[100::-2][::-3].mass, grid.mass[100::-2][::-3]) def test32b(self): grid = datamodel.Grid(200) - grid.mass=numpy.arange(200) - - self.assertEqual(grid[::-1].mass,grid.mass[::-1]) - self.assertEqual(grid[10::-1].mass,grid.mass[10::-1]) - self.assertEqual(grid[:100:2].mass,grid.mass[:100:2]) - self.assertEqual(grid[-1::-1].mass,grid.mass[-1::-1]) - self.assertEqual(grid[-1:-300:-1].mass,grid.mass[-1:-300:-1]) - self.assertEqual(grid[300:-300:-1].mass,grid.mass[300:-300:-1]) - self.assertEqual(grid[300:-300:-7].mass,grid.mass[300:-300:-7]) - - - + grid.mass = numpy.arange(200) + + self.assertEqual(grid[::-1].mass, grid.mass[::-1]) + self.assertEqual(grid[10::-1].mass, grid.mass[10::-1]) + self.assertEqual(grid[:100:2].mass, grid.mass[:100:2]) + self.assertEqual(grid[-1::-1].mass, grid.mass[-1::-1]) + self.assertEqual(grid[-1:-300:-1].mass, grid.mass[-1:-300:-1]) + self.assertEqual(grid[300:-300:-1].mass, grid.mass[300:-300:-1]) + self.assertEqual(grid[300:-300:-7].mass, grid.mass[300:-300:-7]) + def test33(self): grid = datamodel.Grid(20) - grid.mass=numpy.zeros((20,5)) - self.assertEqual(grid[1].mass,numpy.zeros(5)) - grid.mass=numpy.arange(5) - self.assertEqual(grid[-1].mass,numpy.arange(5)) - subgrid=grid[::2] - self.assertEqual(subgrid[-1].mass,numpy.arange(5)) - subgrid[1].mass=5-numpy.arange(5) - self.assertEqual(subgrid[1].mass,5-numpy.arange(5)) - self.assertEqual(grid[2].mass,5-numpy.arange(5)) + grid.mass = numpy.zeros((20, 5)) + self.assertEqual(grid[1].mass, numpy.zeros(5)) + grid.mass = numpy.arange(5) + self.assertEqual(grid[-1].mass, numpy.arange(5)) + subgrid = grid[::2] + self.assertEqual(subgrid[-1].mass, numpy.arange(5)) + subgrid[1].mass = 5-numpy.arange(5) + self.assertEqual(subgrid[1].mass, 5-numpy.arange(5)) + self.assertEqual(grid[2].mass, 5-numpy.arange(5)) def test34(self): grid = datamodel.Grid(20) - grid.mass=numpy.zeros((20,5)) | units.kg - self.assertEqual(grid[1].mass,numpy.zeros(5) | units.kg) - grid.mass=numpy.arange(5) | units.kg - self.assertEqual(grid[-1].mass,numpy.arange(5)| units.kg) - subgrid=grid[::2] - self.assertEqual(subgrid[-1].mass,numpy.arange(5)| units.kg) - subgrid[1].mass=(5-numpy.arange(5))| units.kg - self.assertEqual(subgrid[1].mass,(5-numpy.arange(5))| units.kg) - self.assertEqual(grid[2].mass,(5-numpy.arange(5))| units.kg) + grid.mass = numpy.zeros((20, 5)) | units.kg + self.assertEqual(grid[1].mass, numpy.zeros(5) | units.kg) + grid.mass = numpy.arange(5) | units.kg + self.assertEqual(grid[-1].mass, numpy.arange(5) | units.kg) + subgrid = grid[::2] + self.assertEqual(subgrid[-1].mass, numpy.arange(5) | units.kg) + subgrid[1].mass = (5-numpy.arange(5)) | units.kg + self.assertEqual(subgrid[1].mass, (5-numpy.arange(5)) | units.kg) + self.assertEqual(grid[2].mass, (5-numpy.arange(5)) | units.kg) def test35(self): - grid=datamodel.Grid(10,5) - grid.mass=numpy.zeros((10,5,3)) - self.assertEqual(grid[2,2].mass,numpy.zeros(3)) - grid[::3,::2].mass=numpy.arange(3) - self.assertEqual(grid[3,2].mass,numpy.arange(3)) + grid = datamodel.Grid(10, 5) + grid.mass = numpy.zeros((10, 5, 3)) + self.assertEqual(grid[2, 2].mass, numpy.zeros(3)) + grid[::3, ::2].mass = numpy.arange(3) + self.assertEqual(grid[3, 2].mass, numpy.arange(3)) def test36(self): - grid=datamodel.Grid(10) - grid.mass=numpy.zeros((10,5,3)) - self.assertEqual(grid[2].mass,numpy.zeros((5,3))) - grid[::3].mass=numpy.ones((5,3)) - self.assertEqual(grid[3].mass,numpy.ones((5,3))) + grid = datamodel.Grid(10) + grid.mass = numpy.zeros((10, 5, 3)) + self.assertEqual(grid[2].mass, numpy.zeros((5, 3))) + grid[::3].mass = numpy.ones((5, 3)) + self.assertEqual(grid[3].mass, numpy.ones((5, 3))) def test37(self): grid = datamodel.Grid(20) - grid.mass=numpy.zeros((20,5)) - grid.mass=numpy.arange(5) - self.assertEqual(grid[-1].mass,numpy.arange(5)) - self.assertEqual(grid.mass.shape,(20,5)) - subgrid=grid[::2] - self.assertEqual(subgrid[-1].mass,numpy.arange(5)) - subgrid[1].mass=5-numpy.arange(5) - self.assertEqual(subgrid[1].mass,5-numpy.arange(5)) - self.assertEqual(grid[2].mass,5-numpy.arange(5)) - cp=subgrid.copy() - self.assertEqual(cp[1].mass,5-numpy.arange(5)) - self.assertEqual(cp.mass.shape,(10,5)) - cp=grid.copy() - self.assertEqual(cp.mass.shape,(20,5)) - self.assertEqual(cp[2].mass,5-numpy.arange(5)) - self.assertEqual(cp[-1].mass,numpy.arange(5)) + grid.mass = numpy.zeros((20, 5)) + grid.mass = numpy.arange(5) + self.assertEqual(grid[-1].mass, numpy.arange(5)) + self.assertEqual(grid.mass.shape, (20, 5)) + subgrid = grid[::2] + self.assertEqual(subgrid[-1].mass, numpy.arange(5)) + subgrid[1].mass = 5-numpy.arange(5) + self.assertEqual(subgrid[1].mass, 5-numpy.arange(5)) + self.assertEqual(grid[2].mass, 5-numpy.arange(5)) + cp = subgrid.copy() + self.assertEqual(cp[1].mass, 5-numpy.arange(5)) + self.assertEqual(cp.mass.shape, (10, 5)) + cp = grid.copy() + self.assertEqual(cp.mass.shape, (20, 5)) + self.assertEqual(cp[2].mass, 5-numpy.arange(5)) + self.assertEqual(cp[-1].mass, numpy.arange(5)) def test38(self): - grid=datamodel.new_cartesian_grid((10,),1) - sub=grid[::2] - self.assertEqual(sub[0].x,0.5) - self.assertEqual(sub[(0,)].x,0.5) + grid = datamodel.new_cartesian_grid((10,), 1) + sub = grid[::2] + self.assertEqual(sub[0].x, 0.5) + self.assertEqual(sub[(0,)].x, 0.5) - grid=datamodel.new_cartesian_grid((10,10),1) - sub=grid[::2,::] - self.assertEqual(sub[0,0].x,0.5) - self.assertEqual(sub[(0,1)].y,1.5) + grid = datamodel.new_cartesian_grid((10, 10), 1) + sub = grid[::2, ::] + self.assertEqual(sub[0, 0].x, 0.5) + self.assertEqual(sub[(0, 1)].y, 1.5) def test39(self): - grid=datamodel.new_cartesian_grid((10,10),1) - sub=grid[3:6,5:8] - self.assertEqual(sub[0:-1,0:-1].x,sub.x[0:-1,0:-1]) - self.assertEqual(sub[0:-1,-1].x,sub.x[0:-1,-1]) - self.assertEqual(sub[-1,-1].x,sub.x[-1,-1]) - self.assertEqual(sub[-1,-2].x,sub.x[-1,-2]) + grid = datamodel.new_cartesian_grid((10, 10), 1) + sub = grid[3:6, 5:8] + self.assertEqual(sub[0:-1, 0:-1].x, sub.x[0:-1, 0:-1]) + self.assertEqual(sub[0:-1, -1].x, sub.x[0:-1, -1]) + self.assertEqual(sub[-1, -1].x, sub.x[-1, -1]) + self.assertEqual(sub[-1, -2].x, sub.x[-1, -2]) def test40(self): - grid1 = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - grid2 = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) + grid1 = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + grid2 = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) grid1.m1 = 1 grid1.m2 = 2 channel = grid1.new_channel_to(grid2) - channel.transform(["m3"],lambda x,y: (x,),["m1","m2"]) + channel.transform(["m3"], lambda x, y: (x,), ["m1", "m2"]) self.assertEqual(grid2.m3, 1) - channel.transform(["m3"],lambda x,y: (y,),["m1","m2"]) + channel.transform(["m3"], lambda x, y: (y,), ["m1", "m2"]) self.assertEqual(grid2.m3, 2) - channel.transform(["m3"],lambda x,y: (x+y,),["m1","m2"]) + channel.transform(["m3"], lambda x, y: (x+y,), ["m1", "m2"]) self.assertEqual(grid2.m3, 3) - channel.transform(["m3","m4"],lambda x,y: (x+y,2*x-y),["m1","m2"]) + channel.transform(["m3", "m4"], lambda x, y: (x+y, 2*x-y), ["m1", "m2"]) self.assertEqual(grid2.m3, 3) self.assertEqual(grid2.m4, 0) def test40b(self): grid = datamodel.new_regular_grid((50,), [1.0] | units.m) - for index in [ [0], [0,3,4], [1,2,2],[[2,3]],[[0,1],[2,3]],list(range(50)) ]: - i=numpy.array(index) - self.assertEqual(grid[i].x, grid.x[ i ]) - self.assertEqual(grid[i][1:].x, grid.x[ i ][1:]) - self.assertEqual(grid[i][1::2].x, grid.x[ i ][1::2]) + for index in [[0], [0, 3, 4], [1, 2, 2], [[2, 3]], [[0, 1], [2, 3]], list(range(50))]: + i = numpy.array(index) + self.assertEqual(grid[i].x, grid.x[i]) + self.assertEqual(grid[i][1:].x, grid.x[i][1:]) + self.assertEqual(grid[i][1::2].x, grid.x[i][1::2]) def test41(self): - grid = datamodel.new_regular_grid((10,10), [1.0,2.0] | units.m) - for _i,_j in [ ([0,1],[2,3]) ]: - i=numpy.array(_i) - j=numpy.array(_j) - self.assertEqual(grid[i,j].x, grid.x[ i,j ]) - self.assertEqual(grid[i,j][1:].x, grid.x[ i,j ][1:]) - self.assertEqual(grid[i,j][1::2].x, grid.x[ i,j ][1::2]) + grid = datamodel.new_regular_grid((10, 10), [1.0, 2.0] | units.m) + for _i, _j in [([0, 1], [2, 3])]: + i = numpy.array(_i) + j = numpy.array(_j) + self.assertEqual(grid[i, j].x, grid.x[i, j]) + self.assertEqual(grid[i, j][1:].x, grid.x[i, j][1:]) + self.assertEqual(grid[i, j][1::2].x, grid.x[i, j][1::2]) def test42(self): - grid = datamodel.new_regular_grid((3,4,5,6), [1.0,2.0,3.0,4.0],axes_names="abcd") - for _i,_j in [ ([0],[3]),([0,1],[2,3]) ]: - i=numpy.array(_i) - j=numpy.array(_j) - self.assertEqual(grid[i,j].a, grid.a[ i,j ]) - self.assertEqual(grid[0,1,i,j].a, grid.a[0,1, i,j ]) - self.assertEqual(grid[i,j,0,0].a, grid.a[ i,j,0,0 ]) - self.assertEqual(grid[i,1,2,j].a, grid.a[ i,1,2,j]) + grid = datamodel.new_regular_grid((3, 4, 5, 6), [1.0, 2.0, 3.0, 4.0], axes_names="abcd") + for _i, _j in [([0], [3]), ([0, 1], [2, 3])]: + i = numpy.array(_i) + j = numpy.array(_j) + self.assertEqual(grid[i, j].a, grid.a[i, j]) + self.assertEqual(grid[0, 1, i, j].a, grid.a[0, 1, i, j]) + self.assertEqual(grid[i, j, 0, 0].a, grid.a[i, j, 0, 0]) + self.assertEqual(grid[i, 1, 2, j].a, grid.a[i, 1, 2, j]) def test43(self): - grid = datamodel.new_regular_grid((3,4,5,6), [1.0,2.0,3.0,4.0],axes_names="abcd") - for _i,_j in [ ([0,1],[2,3]) ]: - i=numpy.array(_i) - j=numpy.array(_j) - subgrid=grid[:,0,:,:] - self.assertEqual(subgrid[i,j].a, subgrid.a[ i,j ]) - subgrid=grid[:,0,2,:] - self.assertEqual(subgrid[i,j].a, subgrid.a[ i,j ]) - subgrid=grid[:,0,-2,:] - self.assertEqual(subgrid[i,j].a, subgrid.a[ i,j ]) + grid = datamodel.new_regular_grid((3, 4, 5, 6), [1.0, 2.0, 3.0, 4.0], axes_names="abcd") + for _i, _j in [([0, 1], [2, 3])]: + i = numpy.array(_i) + j = numpy.array(_j) + subgrid = grid[:, 0, :, :] + self.assertEqual(subgrid[i, j].a, subgrid.a[i, j]) + subgrid = grid[:, 0, 2, :] + self.assertEqual(subgrid[i, j].a, subgrid.a[i, j]) + subgrid = grid[:, 0, -2, :] + self.assertEqual(subgrid[i, j].a, subgrid.a[i, j]) def test44(self): - grid = datamodel.new_regular_grid((3,4,5,6), [1.0,2.0,3.0,4.0],axes_names="abcd") - for _i,_j in [ ([-2],[-4]),([0,-1],[-2,3]) ]: - i=numpy.array(_i) - j=numpy.array(_j) - subgrid=grid[:,0,:,:] - self.assertEqual(subgrid[i,j].a, subgrid.a[ i,j ]) - subgrid=grid[:,0,2,:] - self.assertEqual(subgrid[i,j].a, subgrid.a[ i,j ]) - subgrid=grid[:,0,-2,:] - self.assertEqual(subgrid[i,j].a, subgrid.a[ i,j ]) + grid = datamodel.new_regular_grid((3, 4, 5, 6), [1.0, 2.0, 3.0, 4.0], axes_names="abcd") + for _i, _j in [([-2], [-4]), ([0, -1], [-2, 3])]: + i = numpy.array(_i) + j = numpy.array(_j) + subgrid = grid[:, 0, :, :] + self.assertEqual(subgrid[i, j].a, subgrid.a[i, j]) + subgrid = grid[:, 0, 2, :] + self.assertEqual(subgrid[i, j].a, subgrid.a[i, j]) + subgrid = grid[:, 0, -2, :] + self.assertEqual(subgrid[i, j].a, subgrid.a[i, j]) def test45(self): - grid = datamodel.new_regular_grid((3,4,5,6), [1.0,2.0,3.0,4.0],axes_names="abcd") - for _i,_j in [ ([-1],[-4]) ]: - i=numpy.array(_i) - j=numpy.array(_j) - subgrid=grid[::2,0,:,:] - self.assertEqual(subgrid[i,j].a, subgrid.a[ i,j ]) + grid = datamodel.new_regular_grid((3, 4, 5, 6), [1.0, 2.0, 3.0, 4.0], axes_names="abcd") + for _i, _j in [([-1], [-4])]: + i = numpy.array(_i) + j = numpy.array(_j) + subgrid = grid[::2, 0, :, :] + self.assertEqual(subgrid[i, j].a, subgrid.a[i, j]) def test46(self): - grid = datamodel.new_regular_grid((6,), [1.0],axes_names="abcd") - subgrid=grid[::2] - self.assertEqual(subgrid[-2].a, subgrid.a[ -2 ]) + grid = datamodel.new_regular_grid((6,), [1.0], axes_names="abcd") + subgrid = grid[::2] + self.assertEqual(subgrid[-2].a, subgrid.a[-2]) - grid = datamodel.new_regular_grid((7,), [1.0],axes_names="abcd") - subgrid=grid[::2] - self.assertEqual(subgrid[-2].a, subgrid.a[ -2 ]) + grid = datamodel.new_regular_grid((7,), [1.0], axes_names="abcd") + subgrid = grid[::2] + self.assertEqual(subgrid[-2].a, subgrid.a[-2]) - grid = datamodel.new_regular_grid((7,), [1.0],axes_names="abcd") - subgrid=grid[6:0:-2] - self.assertEqual(subgrid[-2].a, subgrid.a[ -2 ]) + grid = datamodel.new_regular_grid((7,), [1.0], axes_names="abcd") + subgrid = grid[6:0:-2] + self.assertEqual(subgrid[-2].a, subgrid.a[-2]) def test47(self): grid = datamodel.Grid() - grid.mass=12. - self.assertEqual(grid[...].mass,12.) - self.assertEqual(grid.mass,12.) + grid.mass = 12. + self.assertEqual(grid[...].mass, 12.) + self.assertEqual(grid.mass, 12.) def test48(self): - p=datamodel.Grid(3) + p = datamodel.Grid(3) + + p.a1 = 1. + p.a2 = 1. | units.rad + p.a3 = 1. | units.deg - p.a1=1. - p.a2=1. | units.rad - p.a3=1. | units.deg - # test all combinations: - - p[0].a1=2. - p[0].a2=2. - p[0].a3=2. - - p[1].a1=2. | units.rad - p[1].a2=2. | units.rad - p[1].a3=2. | units.rad - - p[2].a1=2. | units.deg - p[2].a2=2. | units.deg - p[2].a3=2. | units.deg - - self.assertEqual( p.a1, [2.,2., (2. | units.deg).value_in(units.none)]) - self.assertEqual( p.a2, [2.,2., (2. | units.deg).value_in(units.none)]) - self.assertEqual( p.a3, [(2. | units.rad).in_(units.deg), - (2. | units.rad).in_(units.deg) , 2. | units.deg]) + p[0].a1 = 2. + p[0].a2 = 2. + p[0].a3 = 2. + + p[1].a1 = 2. | units.rad + p[1].a2 = 2. | units.rad + p[1].a3 = 2. | units.rad + + p[2].a1 = 2. | units.deg + p[2].a2 = 2. | units.deg + p[2].a3 = 2. | units.deg + + self.assertEqual(p.a1, [2., 2., (2. | units.deg).value_in(units.none)]) + self.assertEqual(p.a2, [2., 2., (2. | units.deg).value_in(units.none)]) + self.assertEqual(p.a3, [(2. | units.rad).in_(units.deg), + (2. | units.rad).in_(units.deg), 2. | units.deg]) def test50(self): - grid = datamodel.Grid(3,2) + grid = datamodel.Grid(3, 2) for i in range(3): grid.density = (i * 1.0) | units.kg/units.m**3 grid.savepoint((i + 1) * 1.0 | units.s) dens = grid.get_timeline_of_attribute("density") self.assertEqual(len(dens), 3) - self.assertEqual(dens[0][1].shape, (3,2)) - self.assertEqual(dens[1][1].shape, (3,2)) - self.assertEqual(dens[2][1].shape, (3,2)) + self.assertEqual(dens[0][1].shape, (3, 2)) + self.assertEqual(dens[1][1].shape, (3, 2)) + self.assertEqual(dens[2][1].shape, (3, 2)) self.assertEqual(dens[0][0], 1.0 | units.s) self.assertEqual(dens[1][0], 2.0 | units.s) self.assertEqual(dens[2][0], 3.0 | units.s) def test51(self): - grid = datamodel.Grid(3,2) + grid = datamodel.Grid(3, 2) for i in range(3): grid.density = (i * 1.0) | units.kg/units.m**3 grid.savepoint((i + 1) * 1.0 | units.s) - dens = grid[0:1,:].get_timeline_of_attribute("density") + dens = grid[0:1, :].get_timeline_of_attribute("density") self.assertEqual(len(dens), 3) - self.assertEqual(dens[0][1].shape, (1,2)) - self.assertEqual(dens[1][1].shape, (1,2)) - self.assertEqual(dens[2][1].shape, (1,2)) + self.assertEqual(dens[0][1].shape, (1, 2)) + self.assertEqual(dens[1][1].shape, (1, 2)) + self.assertEqual(dens[2][1].shape, (1, 2)) self.assertEqual(dens[0][0], 1.0 | units.s) self.assertEqual(dens[1][0], 2.0 | units.s) self.assertEqual(dens[2][0], 3.0 | units.s) def test51(self): - grid = datamodel.Grid(3,2) + grid = datamodel.Grid(3, 2) for i in range(3): grid.density = (i * 1.0) | units.kg/units.m**3 grid.savepoint((i + 1) * 1.0 | units.s) - time,dens = grid[0:1,:].get_timeline_of_attribute_as_vector("density") - self.assertEqual(dens.shape, (3,1,2)) - self.assertEqual(dens[0].shape, (1,2)) - self.assertEqual(dens[1].shape, (1,2)) - self.assertEqual(dens[2].shape, (1,2)) + time, dens = grid[0:1, :].get_timeline_of_attribute_as_vector("density") + self.assertEqual(dens.shape, (3, 1, 2)) + self.assertEqual(dens[0].shape, (1, 2)) + self.assertEqual(dens[1].shape, (1, 2)) + self.assertEqual(dens[2].shape, (1, 2)) self.assertEqual(time[0], 1.0 | units.s) self.assertEqual(time[1], 2.0 | units.s) self.assertEqual(time[2], 3.0 | units.s) def test52(self): - grid = datamodel.Grid(3,2) + grid = datamodel.Grid(3, 2) for i in range(3): grid.density = (i * 1.0) | units.kg/units.m**3 grid.savepoint((i + 1) * 1.0 | units.s) - time,dens = grid[2,1].get_timeline_of_attribute_as_vector("density") + time, dens = grid[2, 1].get_timeline_of_attribute_as_vector("density") self.assertEqual(dens.shape, (3,)) self.assertEqual(dens[0], 0 | units.kg/units.m**3) self.assertEqual(dens[1], 1 | units.kg/units.m**3) @@ -675,14 +660,14 @@ def test52(self): self.assertEqual(time[2], 3.0 | units.s) def test53(self): - grid = datamodel.Grid(3,2) - subgrid=grid[0:1,:] + grid = datamodel.Grid(3, 2) + subgrid = grid[0:1, :] for i in range(3): grid.density = (i * 1.0) | units.kg/units.m**3 subgrid.savepoint((i + 1) * 1.0 | units.s) - time,dens = subgrid.get_timeline_of_attribute_as_vector("density") - self.assertEqual(dens.shape, (3,1,2)) + time, dens = subgrid.get_timeline_of_attribute_as_vector("density") + self.assertEqual(dens.shape, (3, 1, 2)) self.assertEqual(dens[0], 0 | units.kg/units.m**3) self.assertEqual(dens[1], 1 | units.kg/units.m**3) self.assertEqual(dens[2], 2 | units.kg/units.m**3) @@ -694,15 +679,15 @@ def test54(self): """ illustrates getting subgrid/gridpoint with history from subgrid with history """ - grid = datamodel.Grid(3,2) - subgrid=grid[0:1,:] + grid = datamodel.Grid(3, 2) + subgrid = grid[0:1, :] for i in range(3): grid.density = (i * 1.0) | units.kg/units.m**3 subgrid.savepoint((i + 1) * 1.0 | units.s) # if the gridpoint derives directly from subgrid, its defined on the original # grid (which has no history...) - subsub=subgrid.savepoint((i + 1) * 1.0 | units.s) - time,dens = subsub[0,1].get_timeline_of_attribute_as_vector("density") + subsub = subgrid.savepoint((i + 1) * 1.0 | units.s) + time, dens = subsub[0, 1].get_timeline_of_attribute_as_vector("density") self.assertEqual(dens.shape, (3,)) self.assertEqual(dens[0], 0 | units.kg/units.m**3) self.assertEqual(dens[1], 1 | units.kg/units.m**3) @@ -711,164 +696,158 @@ def test54(self): self.assertEqual(time[1], 2.0 | units.s) self.assertEqual(time[2], 3.0 | units.s) + class TestGridFactories(amusetest.TestCase): def test1(self): - grid1 = datamodel.new_cartesian_grid( (4,5), 1.0 | units.m) - grid2 = datamodel.new_regular_grid( (4,5), [4.0,5.0] | units.m) - grid3 = datamodel.new_rectilinear_grid( (4,5), [numpy.arange(5.) | units.m,numpy.arange(6.) | units.m]) - - self.assertEqual(grid1.position,grid2.position) - self.assertEqual(grid2.position,grid3.position) + grid1 = datamodel.new_cartesian_grid((4, 5), 1.0 | units.m) + grid2 = datamodel.new_regular_grid((4, 5), [4.0, 5.0] | units.m) + grid3 = datamodel.new_rectilinear_grid((4, 5), [numpy.arange(5.) | units.m, numpy.arange(6.) | units.m]) + + self.assertEqual(grid1.position, grid2.position) + self.assertEqual(grid2.position, grid3.position) def test2(self): - grid=datamodel.new_rectilinear_grid((10,),(1.*numpy.arange(11),)) - self.assertEqual(grid._axes_cell_boundaries,1.*numpy.arange(11)) - grid=datamodel.new_regular_grid((10,),[10.]) - self.assertEqual(grid._lengths,[10.]) - grid=datamodel.new_cartesian_grid((10,),1.) - self.assertEqual(grid._cellsize,1.) - grid=datamodel.new_regular_grid((10,20,),[10.,15.]) - self.assertEqual(grid._lengths,[10.,15.]) + grid = datamodel.new_rectilinear_grid((10,), (1.*numpy.arange(11),)) + self.assertEqual(grid._axes_cell_boundaries, 1.*numpy.arange(11)) + grid = datamodel.new_regular_grid((10,), [10.]) + self.assertEqual(grid._lengths, [10.]) + grid = datamodel.new_cartesian_grid((10,), 1.) + self.assertEqual(grid._cellsize, 1.) + grid = datamodel.new_regular_grid((10, 20,), [10., 15.]) + self.assertEqual(grid._lengths, [10., 15.]) def test3(self): - N=10 - x,y=numpy.indices((N+1,N+1)) - grid=datamodel.new_structured_grid((N,N),[x,y]) - self.assertEqual(grid.shape,(N,N)) - x,y=numpy.indices((N,N)) - x=x+0.5 - y=y+0.5 - self.assertEqual(grid.x,x) - self.assertEqual(grid.y,y) - - def test4(self): - N=2 - x,y,z=numpy.indices((N+1,N+1,2*N+1)) - grid=datamodel.new_structured_grid((N,N,2*N),[x,y,z]) - self.assertEqual(grid.shape,(N,N,2*N)) - x,y,z=numpy.indices((N,N,2*N)) - x=x+0.5 - y=y+0.5 - z=z+0.5 - self.assertEqual(grid.x,x) - self.assertEqual(grid.y,y) - self.assertEqual(grid.z,z) + N = 10 + x, y = numpy.indices((N+1, N+1)) + grid = datamodel.new_structured_grid((N, N), [x, y]) + self.assertEqual(grid.shape, (N, N)) + x, y = numpy.indices((N, N)) + x = x+0.5 + y = y+0.5 + self.assertEqual(grid.x, x) + self.assertEqual(grid.y, y) + def test4(self): + N = 2 + x, y, z = numpy.indices((N+1, N+1, 2*N+1)) + grid = datamodel.new_structured_grid((N, N, 2*N), [x, y, z]) + self.assertEqual(grid.shape, (N, N, 2*N)) + x, y, z = numpy.indices((N, N, 2*N)) + x = x+0.5 + y = y+0.5 + z = z+0.5 + self.assertEqual(grid.x, x) + self.assertEqual(grid.y, y) + self.assertEqual(grid.z, z) class TestGridAttributes(amusetest.TestCase): - + def test1(self): - grid = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - self.assertAlmostRelativeEquals(grid.get_minimum_position(), ([0.0, 0.0, 0.0] | units.m) ) + grid = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + self.assertAlmostRelativeEquals(grid.get_minimum_position(), ([0.0, 0.0, 0.0] | units.m)) self.assertAlmostRelativeEquals(grid.get_maximum_position(), [1.0, 1.0, 1.0] | units.m) self.assertAlmostRelativeEquals(grid.get_volume(), 1.0 | units.m ** 3) - self.assertTrue(grid.contains([0.5,0.5,0.5] | units.m)) - + self.assertTrue(grid.contains([0.5, 0.5, 0.5] | units.m)) + def test2(self): - grid = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - self.assertTrue(numpy.all(grid.contains([[0.5,0.5,0.5] , [0.1,0.1,0.1]]| units.m))) - self.assertFalse(numpy.all(grid.contains([[1.1,0.5,0.5] , [0.1,1.1,0.1]]| units.m))) - + grid = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + self.assertTrue(numpy.all(grid.contains([[0.5, 0.5, 0.5], [0.1, 0.1, 0.1]] | units.m))) + self.assertFalse(numpy.all(grid.contains([[1.1, 0.5, 0.5], [0.1, 1.1, 0.1]] | units.m))) + def test3(self): - grid = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) + grid = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) points = grid.points() - self.assertEqual(points.shape, (6,5,3, 3)) - self.assertAlmostRelativeEquals(points[0][0][0], ([0.0,0.0, 0.0] | units.m) ) - self.assertAlmostRelativeEquals(points[1][0][0] , ([0.2,0.0, 0.0] | units.m) ) - self.assertAlmostRelativeEquals(points[1][1][1], [0.2,0.25, 0.5] | units.m ) - self.assertAlmostRelativeEquals(points[0][-1][-1] , ([0.0, 1.0, 1.0] | units.m) ) - self.assertAlmostRelativeEquals(points[-1][0][-1] , ([1.0, 0.0, 1.0] | units.m) ) - self.assertAlmostRelativeEquals(points[-1][-1][0] , ([1.0, 1.0, 0.0] | units.m) ) - self.assertAlmostRelativeEquals(points[-1][-1][-1] , ([1.0,1.0, 1.0] | units.m) ) - - + self.assertEqual(points.shape, (6, 5, 3, 3)) + self.assertAlmostRelativeEquals(points[0][0][0], ([0.0, 0.0, 0.0] | units.m)) + self.assertAlmostRelativeEquals(points[1][0][0], ([0.2, 0.0, 0.0] | units.m)) + self.assertAlmostRelativeEquals(points[1][1][1], [0.2, 0.25, 0.5] | units.m) + self.assertAlmostRelativeEquals(points[0][-1][-1], ([0.0, 1.0, 1.0] | units.m)) + self.assertAlmostRelativeEquals(points[-1][0][-1], ([1.0, 0.0, 1.0] | units.m)) + self.assertAlmostRelativeEquals(points[-1][-1][0], ([1.0, 1.0, 0.0] | units.m)) + self.assertAlmostRelativeEquals(points[-1][-1][-1], ([1.0, 1.0, 1.0] | units.m)) + def test4(self): - grid = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - points = grid.points().reshape([6*5*3,3]) + grid = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + points = grid.points().reshape([6*5*3, 3]) connectivity = grid.connectivity() - - self.assertEqual(connectivity.shape, (5,4,2, 8)) + + self.assertEqual(connectivity.shape, (5, 4, 2, 8)) first_cell = connectivity[0][0][0] - self.assertAlmostRelativeEquals(points[first_cell[0]], [0,0,0 ] | units.m) - self.assertAlmostRelativeEquals(points[first_cell[1]], [0.2,0,0] | units.m) - self.assertAlmostRelativeEquals(points[first_cell[2]] , ([0,0.25,0] | units.m)) - self.assertAlmostRelativeEquals(points[first_cell[3]] , ([0.2,0.25,0] | units.m)) - self.assertAlmostRelativeEquals(points[first_cell[4]] , ([0.0,0.0,0.5] | units.m)) - self.assertAlmostRelativeEquals(points[first_cell[5]] , ([0.2,0.0,0.5] | units.m)) - self.assertAlmostRelativeEquals(points[first_cell[6]] , ([0.0,0.25,0.5] | units.m)) - self.assertAlmostRelativeEquals(points[first_cell[7]] , ([0.2,0.25,0.5] | units.m)) - - self.assertEqual(connectivity[0][0][0], [ 0,15, 3, 18, 1, 16, 4, 19]) - - - + self.assertAlmostRelativeEquals(points[first_cell[0]], [0, 0, 0] | units.m) + self.assertAlmostRelativeEquals(points[first_cell[1]], [0.2, 0, 0] | units.m) + self.assertAlmostRelativeEquals(points[first_cell[2]], ([0, 0.25, 0] | units.m)) + self.assertAlmostRelativeEquals(points[first_cell[3]], ([0.2, 0.25, 0] | units.m)) + self.assertAlmostRelativeEquals(points[first_cell[4]], ([0.0, 0.0, 0.5] | units.m)) + self.assertAlmostRelativeEquals(points[first_cell[5]], ([0.2, 0.0, 0.5] | units.m)) + self.assertAlmostRelativeEquals(points[first_cell[6]], ([0.0, 0.25, 0.5] | units.m)) + self.assertAlmostRelativeEquals(points[first_cell[7]], ([0.2, 0.25, 0.5] | units.m)) + + self.assertEqual(connectivity[0][0][0], [0, 15, 3, 18, 1, 16, 4, 19]) + def test5(self): - grid = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - points = grid.points().reshape([6*5*3,3]) + grid = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + points = grid.points().reshape([6*5*3, 3]) connectivity = grid.connectivity() - - self.assertEqual(connectivity.shape, (5,4,2, 8)) + + self.assertEqual(connectivity.shape, (5, 4, 2, 8)) cell = connectivity[0][0][1] - self.assertAlmostRelativeEquals(points[cell[0]] , ([0.0,0.0,0.5 ] | units.m)) - self.assertAlmostRelativeEquals(points[cell[1]] , ([0.2,0,0.5] | units.m)) - self.assertAlmostRelativeEquals(points[cell[2]] , ([0,0.25,0.5] | units.m)) - self.assertAlmostRelativeEquals(points[cell[3]] , ([0.2,0.25,0.5] | units.m)) - self.assertAlmostRelativeEquals(points[cell[4]] , ([0.0,0.0,1.0] | units.m)) - self.assertAlmostRelativeEquals(points[cell[5]] , ([0.2,0.0,1.0] | units.m)) - self.assertAlmostRelativeEquals(points[cell[6]] , ([0.0,0.25,1.0] | units.m)) - self.assertAlmostRelativeEquals(points[cell[7]] , ([0.2,0.25,1.0] | units.m)) - - self.assertEqual(connectivity[0][0][0], [ 0,15, 3, 18, 1, 16, 4, 19]) - - - + self.assertAlmostRelativeEquals(points[cell[0]], ([0.0, 0.0, 0.5] | units.m)) + self.assertAlmostRelativeEquals(points[cell[1]], ([0.2, 0, 0.5] | units.m)) + self.assertAlmostRelativeEquals(points[cell[2]], ([0, 0.25, 0.5] | units.m)) + self.assertAlmostRelativeEquals(points[cell[3]], ([0.2, 0.25, 0.5] | units.m)) + self.assertAlmostRelativeEquals(points[cell[4]], ([0.0, 0.0, 1.0] | units.m)) + self.assertAlmostRelativeEquals(points[cell[5]], ([0.2, 0.0, 1.0] | units.m)) + self.assertAlmostRelativeEquals(points[cell[6]], ([0.0, 0.25, 1.0] | units.m)) + self.assertAlmostRelativeEquals(points[cell[7]], ([0.2, 0.25, 1.0] | units.m)) + + self.assertEqual(connectivity[0][0][0], [0, 15, 3, 18, 1, 16, 4, 19]) + def test6(self): - grid = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - points = grid.points().reshape([6*5*3,3]) + grid = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + points = grid.points().reshape([6*5*3, 3]) connectivity = grid.connectivity() - - self.assertEqual(connectivity.shape, (5,4,2, 8)) + + self.assertEqual(connectivity.shape, (5, 4, 2, 8)) cell = connectivity[1][1][1] - self.assertAlmostRelativeEquals(points[cell[0]], ([0.2, 0.25, 0.5]|units.m) + ([0.0,0.0,0.0 ] | units.m)) - self.assertAlmostRelativeEquals(points[cell[1]], ([0.2, 0.25, 0.5]|units.m) + ([0.2,0,0.0] | units.m)) - self.assertAlmostRelativeEquals(points[cell[2]], ([0.2, 0.25, 0.5]|units.m) + ([0,0.25,0.0] | units.m)) - self.assertAlmostRelativeEquals(points[cell[3]], ([0.2, 0.25, 0.5]|units.m) + ([0.2,0.25,0.0] | units.m)) - self.assertAlmostRelativeEquals(points[cell[4]], ([0.2, 0.25, 0.5]|units.m) + ([0.0,0.0,0.5] | units.m)) - self.assertAlmostRelativeEquals(points[cell[5]], ([0.2, 0.25, 0.5]|units.m) + ([0.2,0.0,0.5] | units.m)) - self.assertAlmostRelativeEquals(points[cell[6]], ([0.2, 0.25, 0.5]|units.m) + ([0.0,0.25,0.5] | units.m)) - self.assertAlmostRelativeEquals(points[cell[7]], ([0.2, 0.25, 0.5]|units.m) + ([0.2,0.25,0.5] | units.m)) - - self.assertEqual(connectivity[0][0][0], [ 0,15, 3, 18, 1, 16, 4, 19]) - + self.assertAlmostRelativeEquals(points[cell[0]], ([0.2, 0.25, 0.5] | units.m) + ([0.0, 0.0, 0.0] | units.m)) + self.assertAlmostRelativeEquals(points[cell[1]], ([0.2, 0.25, 0.5] | units.m) + ([0.2, 0, 0.0] | units.m)) + self.assertAlmostRelativeEquals(points[cell[2]], ([0.2, 0.25, 0.5] | units.m) + ([0, 0.25, 0.0] | units.m)) + self.assertAlmostRelativeEquals(points[cell[3]], ([0.2, 0.25, 0.5] | units.m) + ([0.2, 0.25, 0.0] | units.m)) + self.assertAlmostRelativeEquals(points[cell[4]], ([0.2, 0.25, 0.5] | units.m) + ([0.0, 0.0, 0.5] | units.m)) + self.assertAlmostRelativeEquals(points[cell[5]], ([0.2, 0.25, 0.5] | units.m) + ([0.2, 0.0, 0.5] | units.m)) + self.assertAlmostRelativeEquals(points[cell[6]], ([0.2, 0.25, 0.5] | units.m) + ([0.0, 0.25, 0.5] | units.m)) + self.assertAlmostRelativeEquals(points[cell[7]], ([0.2, 0.25, 0.5] | units.m) + ([0.2, 0.25, 0.5] | units.m)) + + self.assertEqual(connectivity[0][0][0], [0, 15, 3, 18, 1, 16, 4, 19]) + def test7(self): - grid = datamodel.new_regular_grid((5,5,5), [10.0, 10.0, 10.0] | units.m) - - self.assertAlmostRelativeEquals(grid[1][2][3].position, [3,5,7] |units.m) - - grid[1][2][3].position = [7,5,3] |units.m - self.assertAlmostRelativeEquals(grid[1][2][3].position, [7,5,3] |units.m) - - - grid[1][2][3].position += [1,2,3] |units.m - self.assertAlmostRelativeEquals(grid[1][2][3].position, [8,7,6] |units.m) + grid = datamodel.new_regular_grid((5, 5, 5), [10.0, 10.0, 10.0] | units.m) + + self.assertAlmostRelativeEquals(grid[1][2][3].position, [3, 5, 7] | units.m) + + grid[1][2][3].position = [7, 5, 3] | units.m + self.assertAlmostRelativeEquals(grid[1][2][3].position, [7, 5, 3] | units.m) + + grid[1][2][3].position += [1, 2, 3] | units.m + self.assertAlmostRelativeEquals(grid[1][2][3].position, [8, 7, 6] | units.m) def test8(self): - grid = datamodel.new_regular_grid((5,4), [1.0, 1.0] | units.m) - self.assertAlmostRelativeEquals(grid.get_minimum_position(), ([0.0, 0.0] | units.m) ) + grid = datamodel.new_regular_grid((5, 4), [1.0, 1.0] | units.m) + self.assertAlmostRelativeEquals(grid.get_minimum_position(), ([0.0, 0.0] | units.m)) self.assertAlmostRelativeEquals(grid.get_maximum_position(), [1.0, 1.0] | units.m) self.assertAlmostRelativeEquals(grid.get_volume(), 1.0 | units.m ** 2) - self.assertTrue(grid.contains([0.5,0.5] | units.m)) + self.assertTrue(grid.contains([0.5, 0.5] | units.m)) def test9(self): - grid = datamodel.new_regular_grid((5,4,2), [1.0, 1.0, 1.0] | units.m) - self.assertEqual((0,0,0),grid.get_minimum_index()) - self.assertEqual((4,3,1),grid.get_maximum_index()) + grid = datamodel.new_regular_grid((5, 4, 2), [1.0, 1.0, 1.0] | units.m) + self.assertEqual((0, 0, 0), grid.get_minimum_index()) + self.assertEqual((4, 3, 1), grid.get_maximum_index()) def test10(self): - grid1 = datamodel.new_regular_grid((5,4), [1.0, 1.0] | units.m) - grid2 = datamodel.new_regular_grid((5,4), [.1, .1] | units.m) - grid3 = datamodel.new_regular_grid((5,4), [.1, .1] | units.m,offset=[0.5,0.6] | units.m) + grid1 = datamodel.new_regular_grid((5, 4), [1.0, 1.0] | units.m) + grid2 = datamodel.new_regular_grid((5, 4), [.1, .1] | units.m) + grid3 = datamodel.new_regular_grid((5, 4), [.1, .1] | units.m, offset=[0.5, 0.6] | units.m) self.assertTrue(grid1.overlaps(grid2)) self.assertTrue(grid1.overlaps(grid3)) self.assertFalse(grid2.overlaps(grid3)) @@ -877,194 +856,190 @@ def test10(self): self.assertFalse(grid3.overlaps(grid2)) def test11(self): - grid1 = datamodel.new_regular_grid((4,4), [1.0, 1.0] | units.m) - grid2 = datamodel.new_regular_grid((4,4), [1.0, 1.0] | units.m,offset=[-0.5,-0.5] | units.m) + grid1 = datamodel.new_regular_grid((4, 4), [1.0, 1.0] | units.m) + grid2 = datamodel.new_regular_grid((4, 4), [1.0, 1.0] | units.m, offset=[-0.5, -0.5] | units.m) self.assertTrue(grid1.overlaps(grid2)) - overlap=grid1.get_overlap_with(grid2) - self.assertEqual(overlap.position,grid1[0:3,0:3].position) + overlap = grid1.get_overlap_with(grid2) + self.assertEqual(overlap.position, grid1[0:3, 0:3].position) def test12(self): - grid1 = datamodel.new_regular_grid((4,4), [1.0, 1.0] | units.m) - grid2 = datamodel.new_regular_grid((4,4), [1.0, 1.0] | units.m,offset=[-0.5,-0.5] | units.m) + grid1 = datamodel.new_regular_grid((4, 4), [1.0, 1.0] | units.m) + grid2 = datamodel.new_regular_grid((4, 4), [1.0, 1.0] | units.m, offset=[-0.5, -0.5] | units.m) self.assertTrue(grid1.overlaps(grid2)) - overlap=grid1.get_overlap_with(grid2,eps=grid2.cellsize()[0]*1.e-6) - self.assertEqual(overlap.position,grid1[0:2,0:2].position) + overlap = grid1.get_overlap_with(grid2, eps=grid2.cellsize()[0]*1.e-6) + self.assertEqual(overlap.position, grid1[0:2, 0:2].position) class TestGridSampling(amusetest.TestCase): - + def test1(self): - grid = datamodel.new_regular_grid((5,5,5), [10.0, 10.0, 10.0] | units.m) + grid = datamodel.new_regular_grid((5, 5, 5), [10.0, 10.0, 10.0] | units.m) grid.mass = grid.x.value_in(units.m) | units.kg - sample = grid.samplePoint([3.0,3.0,3.0]| units.m,method="interpolation") - self.assertEqual(sample.index , [1,1,1]) - sample = grid.samplePoint([2.5,2.5,2.5]| units.m,method="interpolation") - self.assertEqual(sample.index , [1,1,1]) - sample = grid.samplePoint([3.5,3.5,3.5]| units.m,method="interpolation") - self.assertEqual(sample.index , [1,1,1]) - - for x in range(0,200): - sample = grid.samplePoint([0.0 + (x/100.0),4.0+(x/100.0),6.0+(x/100.0)]| units.m,method="interpolation") - self.assertEqual(sample.index , [0,2,3]) - - for x in range(200,400): - sample = grid.samplePoint([0.0 + (x/100.0),4.0+(x/100.0),6.0+(x/100.0)]| units.m,method="interpolation") - self.assertEqual(sample.index , [1,3,4]) + sample = grid.samplePoint([3.0, 3.0, 3.0] | units.m, method="interpolation") + self.assertEqual(sample.index, [1, 1, 1]) + sample = grid.samplePoint([2.5, 2.5, 2.5] | units.m, method="interpolation") + self.assertEqual(sample.index, [1, 1, 1]) + sample = grid.samplePoint([3.5, 3.5, 3.5] | units.m, method="interpolation") + self.assertEqual(sample.index, [1, 1, 1]) + + for x in range(0, 200): + sample = grid.samplePoint([0.0 + (x/100.0), 4.0+(x/100.0), 6.0+(x/100.0)] | units.m, method="interpolation") + self.assertEqual(sample.index, [0, 2, 3]) + + for x in range(200, 400): + sample = grid.samplePoint([0.0 + (x/100.0), 4.0+(x/100.0), 6.0+(x/100.0)] | units.m, method="interpolation") + self.assertEqual(sample.index, [1, 3, 4]) def test2(self): - grid = datamodel.new_regular_grid((5,5,5), [10.0, 10.0, 10.0] | units.m) + grid = datamodel.new_regular_grid((5, 5, 5), [10.0, 10.0, 10.0] | units.m) grid.mass = grid.x.value_in(units.m) | units.kg - sample = grid.samplePoint([3.0,3.0,3.0]| units.m,method="interpolation") - self.assertEqual(sample.index_for_000_cell , [1,1,1]) - sample = grid.samplePoint([2.5,2.5,2.5]| units.m,method="interpolation") - self.assertEqual(sample.index_for_000_cell , [0,0,0]) - sample = grid.samplePoint([3.5,3.5,3.5]| units.m,method="interpolation") - self.assertEqual(sample.index_for_000_cell , [1,1,1]) - sample = grid.samplePoint([4.5,4.5,4.5]| units.m,method="interpolation") - self.assertEqual(sample.index_for_000_cell , [1,1,1]) - self.assertEqual(sample.index , [2,2,2]) - - for x in range(0,100): - - sample = grid.samplePoint([0.0 + (x/100.0),4.0+(x/100.0),6.0+(x/100.0)]| units.m,method="interpolation") - self.assertEqual(sample.index_for_000_cell , [-1,1,2]) - for x in range(100,300): - - sample = grid.samplePoint([0.0 + (x/100.0),4.0+(x/100.0),6.0+(x/100.0)]| units.m,method="interpolation") - self.assertEqual(sample.index_for_000_cell , [0,2,3]) - - for x in range(300,400): - sample = grid.samplePoint([0.0 + (x/100.0),4.0+(x/100.0),6.0+(x/100.0)]| units.m,method="interpolation") - self.assertEqual(sample.index_for_000_cell , [1,3,4]) - - + sample = grid.samplePoint([3.0, 3.0, 3.0] | units.m, method="interpolation") + self.assertEqual(sample.index_for_000_cell, [1, 1, 1]) + sample = grid.samplePoint([2.5, 2.5, 2.5] | units.m, method="interpolation") + self.assertEqual(sample.index_for_000_cell, [0, 0, 0]) + sample = grid.samplePoint([3.5, 3.5, 3.5] | units.m, method="interpolation") + self.assertEqual(sample.index_for_000_cell, [1, 1, 1]) + sample = grid.samplePoint([4.5, 4.5, 4.5] | units.m, method="interpolation") + self.assertEqual(sample.index_for_000_cell, [1, 1, 1]) + self.assertEqual(sample.index, [2, 2, 2]) + + for x in range(0, 100): + + sample = grid.samplePoint([0.0 + (x/100.0), 4.0+(x/100.0), 6.0+(x/100.0)] | units.m, method="interpolation") + self.assertEqual(sample.index_for_000_cell, [-1, 1, 2]) + for x in range(100, 300): + + sample = grid.samplePoint([0.0 + (x/100.0), 4.0+(x/100.0), 6.0+(x/100.0)] | units.m, method="interpolation") + self.assertEqual(sample.index_for_000_cell, [0, 2, 3]) + + for x in range(300, 400): + sample = grid.samplePoint([0.0 + (x/100.0), 4.0+(x/100.0), 6.0+(x/100.0)] | units.m, method="interpolation") + self.assertEqual(sample.index_for_000_cell, [1, 3, 4]) + def test3(self): - grid = datamodel.new_regular_grid((5,5,5), [10.0, 10.0, 10.0] | units.m) + grid = datamodel.new_regular_grid((5, 5, 5), [10.0, 10.0, 10.0] | units.m) grid.mass = grid.x.value_in(units.m) | units.kg - sample = grid.samplePoint([3.0,3.0,3.0]| units.m,method="interpolation") - self.assertEqual(sample.index_for_000_cell , [1,1,1]) - self.assertEqual(sample.surrounding_cell_indices , [ - [1,1,1], - [2,1,1], - [1,2,1], - [1,1,2], - [2,1,2], - [1,2,2], - [2,2,1], - [2,2,2], + sample = grid.samplePoint([3.0, 3.0, 3.0] | units.m, method="interpolation") + self.assertEqual(sample.index_for_000_cell, [1, 1, 1]) + self.assertEqual(sample.surrounding_cell_indices, [ + [1, 1, 1], + [2, 1, 1], + [1, 2, 1], + [1, 1, 2], + [2, 1, 2], + [1, 2, 2], + [2, 2, 1], + [2, 2, 2], ]) - + def test4(self): - grid = datamodel.new_regular_grid((5,5,5), [10.0, 10.0, 10.0] | units.m) + grid = datamodel.new_regular_grid((5, 5, 5), [10.0, 10.0, 10.0] | units.m) grid.mass = grid.x.value_in(units.m) | units.kg - sample = grid.samplePoint([3.0,3.0,3.0]| units.m,method="interpolation") - self.assertEqual(sample.surrounding_cells[0].position , [3.0,3.0,3.0] | units.m ) - self.assertEqual(sample.surrounding_cells[1].position , [5.0,3.0,3.0] | units.m ) - self.assertEqual(sample.surrounding_cells[-1].position , [5.0,5.0,5.0] | units.m ) + sample = grid.samplePoint([3.0, 3.0, 3.0] | units.m, method="interpolation") + self.assertEqual(sample.surrounding_cells[0].position, [3.0, 3.0, 3.0] | units.m) + self.assertEqual(sample.surrounding_cells[1].position, [5.0, 3.0, 3.0] | units.m) + self.assertEqual(sample.surrounding_cells[-1].position, [5.0, 5.0, 5.0] | units.m) - def test5(self): - grid = datamodel.new_regular_grid((5,5,5), [10.0, 10.0, 10.0] | units.m) + grid = datamodel.new_regular_grid((5, 5, 5), [10.0, 10.0, 10.0] | units.m) grid.mass = grid.x.value_in(units.m) | units.kg - sample = grid.samplePoint([3.0,3.0,3.0]| units.m,method="interpolation") + sample = grid.samplePoint([3.0, 3.0, 3.0] | units.m, method="interpolation") masses = sample.get_values_of_attribute("mass") - self.assertEqual(masses[0] , 3.0 | units.kg ) - self.assertEqual(masses[1] , 5.0 | units.kg ) - self.assertEqual(masses[2] , 3.0 | units.kg ) - self.assertEqual(masses[3] , 3.0 | units.kg ) - self.assertEqual(masses[4] , 5.0 | units.kg ) - self.assertEqual(masses[5] , 3.0 | units.kg ) - self.assertEqual(masses[6] , 5.0 | units.kg ) - self.assertEqual(masses[7] , 5.0 | units.kg ) + self.assertEqual(masses[0], 3.0 | units.kg) + self.assertEqual(masses[1], 5.0 | units.kg) + self.assertEqual(masses[2], 3.0 | units.kg) + self.assertEqual(masses[3], 3.0 | units.kg) + self.assertEqual(masses[4], 5.0 | units.kg) + self.assertEqual(masses[5], 3.0 | units.kg) + self.assertEqual(masses[6], 5.0 | units.kg) + self.assertEqual(masses[7], 5.0 | units.kg) factors = sample.weighing_factors - self.assertEqual(factors[0] , 1.0 | units.none ) - self.assertEqual(factors[1] , 0.0 | units.none ) - self.assertEqual(factors[2] , 0.0 | units.none ) - self.assertEqual(factors[3] , 0.0 | units.none ) - self.assertEqual(factors[4] , 0.0 | units.none ) - self.assertEqual(factors[5] , 0.0 | units.none ) - self.assertEqual(factors[6] , 0.0 | units.none ) - self.assertEqual(factors[7] , 0.0 | units.none ) - - self.assertAlmostRelativeEquals(sample.mass , 3.0 | units.kg ) - + self.assertEqual(factors[0], 1.0 | units.none) + self.assertEqual(factors[1], 0.0 | units.none) + self.assertEqual(factors[2], 0.0 | units.none) + self.assertEqual(factors[3], 0.0 | units.none) + self.assertEqual(factors[4], 0.0 | units.none) + self.assertEqual(factors[5], 0.0 | units.none) + self.assertEqual(factors[6], 0.0 | units.none) + self.assertEqual(factors[7], 0.0 | units.none) + + self.assertAlmostRelativeEquals(sample.mass, 3.0 | units.kg) + def test6(self): - grid = datamodel.new_regular_grid((5,5,5), [10.0, 10.0, 10.0] | units.m) + grid = datamodel.new_regular_grid((5, 5, 5), [10.0, 10.0, 10.0] | units.m) grid.mass = grid.x.value_in(units.m) | units.kg - for xpos in numpy.arange(3.0,5.0,0.1): - sample = grid.samplePoint([xpos,3.0,3.0]| units.m,method="interpolation") - self.assertAlmostRelativeEquals(sample.mass , (3.0 | units.kg) + ((2.0 * (xpos - 3.0) / 2.0) | units.kg) ) - - sample = grid.samplePoint([xpos,3.0,3.0]| units.m,method="interpolation") - self.assertAlmostRelativeEquals(sample.mass , (3.0 | units.kg) + ((2.0 * (xpos - 3.0) / 2.0) | units.kg) ) - - sample = grid.samplePoint([xpos,5.0,3.0]| units.m,method="interpolation") - self.assertAlmostRelativeEquals(sample.mass , (3.0 | units.kg) + ((2.0 * (xpos - 3.0) / 2.0) | units.kg) ) - - sample = grid.samplePoint([xpos,3.0,5.0]| units.m,method="interpolation") - self.assertAlmostRelativeEquals(sample.mass , (3.0 | units.kg) + ((2.0 * (xpos - 3.0) / 2.0) | units.kg) ) - - - sample = grid.samplePoint([4.0,4.0,4.0]| units.m,method="interpolation") - self.assertAlmostRelativeEquals(sample.mass , (4.0 | units.kg)) + for xpos in numpy.arange(3.0, 5.0, 0.1): + sample = grid.samplePoint([xpos, 3.0, 3.0] | units.m, method="interpolation") + self.assertAlmostRelativeEquals(sample.mass, (3.0 | units.kg) + ((2.0 * (xpos - 3.0) / 2.0) | units.kg)) + + sample = grid.samplePoint([xpos, 3.0, 3.0] | units.m, method="interpolation") + self.assertAlmostRelativeEquals(sample.mass, (3.0 | units.kg) + ((2.0 * (xpos - 3.0) / 2.0) | units.kg)) + + sample = grid.samplePoint([xpos, 5.0, 3.0] | units.m, method="interpolation") + self.assertAlmostRelativeEquals(sample.mass, (3.0 | units.kg) + ((2.0 * (xpos - 3.0) / 2.0) | units.kg)) + + sample = grid.samplePoint([xpos, 3.0, 5.0] | units.m, method="interpolation") + self.assertAlmostRelativeEquals(sample.mass, (3.0 | units.kg) + ((2.0 * (xpos - 3.0) / 2.0) | units.kg)) + + sample = grid.samplePoint([4.0, 4.0, 4.0] | units.m, method="interpolation") + self.assertAlmostRelativeEquals(sample.mass, (4.0 | units.kg)) def test7(self): - grid = datamodel.new_regular_grid((5,5,5), [10.0, 10.0, 10.0] | units.m) + grid = datamodel.new_regular_grid((5, 5, 5), [10.0, 10.0, 10.0] | units.m) grid.mass = grid.x.value_in(units.m) | units.kg - sample = grid.samplePoint([3.0,3.0,3.0]| units.m,method="interpolation") + sample = grid.samplePoint([3.0, 3.0, 3.0] | units.m, method="interpolation") self.assertTrue(sample.isvalid) - sample = grid.samplePoint([11.0,3.0,3.0]| units.m,method="interpolation") + sample = grid.samplePoint([11.0, 3.0, 3.0] | units.m, method="interpolation") self.assertFalse(sample.isvalid) - sample = grid.samplePoint([3.0,-1.0,3.0]| units.m,method="interpolation") + sample = grid.samplePoint([3.0, -1.0, 3.0] | units.m, method="interpolation") self.assertFalse(sample.isvalid) - - + def test8(self): - grid = datamodel.new_regular_grid((5,5,5), [10.0, 10.0, 10.0] | units.m) + grid = datamodel.new_regular_grid((5, 5, 5), [10.0, 10.0, 10.0] | units.m) grid.mass = grid.x.value_in(units.m) | units.kg - sample = grid.samplePoint([3.0,3.0,3.0]| units.m, method="nearest") - self.assertEqual(sample.position, [3.0,3.0,3.0]| units.m) + sample = grid.samplePoint([3.0, 3.0, 3.0] | units.m, method="nearest") + self.assertEqual(sample.position, [3.0, 3.0, 3.0] | units.m) self.assertEqual(sample.mass, 3.0 | units.kg) - sample = grid.samplePoint([3.5,3.0,3.0]| units.m, method="nearest") - self.assertEqual(sample.position, [3.0,3.0,3.0]| units.m) + sample = grid.samplePoint([3.5, 3.0, 3.0] | units.m, method="nearest") + self.assertEqual(sample.position, [3.0, 3.0, 3.0] | units.m) self.assertEqual(sample.mass, 3.0 | units.kg) - + def test9(self): - grid = datamodel.new_regular_grid((5,5,5), [10.0, 10.0, 10.0] | units.m) + grid = datamodel.new_regular_grid((5, 5, 5), [10.0, 10.0, 10.0] | units.m) grid.mass = grid.x.value_in(units.m) | units.kg - sample = grid.samplePoint([3.0,3.0,3.0]| units.m, method="linear") - self.assertEqual(sample.position, [3.0,3.0,3.0]| units.m) + sample = grid.samplePoint([3.0, 3.0, 3.0] | units.m, method="linear") + self.assertEqual(sample.position, [3.0, 3.0, 3.0] | units.m) self.assertEqual(sample.mass, 3.0 | units.kg) - sample = grid.samplePoint([3.5,3.0,3.0]| units.m, method="linear") - self.assertEqual(sample.position, [3.5,3.0,3.0]| units.m) + sample = grid.samplePoint([3.5, 3.0, 3.0] | units.m, method="linear") + self.assertEqual(sample.position, [3.5, 3.0, 3.0] | units.m) self.assertEqual(sample.mass, 3.5 | units.kg) - - + + class TestGridSamplingMultiplePoints(amusetest.TestCase): - + def test1(self): - grid = datamodel.new_regular_grid((5,5,5), [10.0, 10.0, 10.0] | units.m) + grid = datamodel.new_regular_grid((5, 5, 5), [10.0, 10.0, 10.0] | units.m) grid.mass = grid.x.value_in(units.m) | units.kg - samples = grid.samplePoints([[3.0,3.0,3.0], [4.0,3.0,3.0]]| units.m, method="linear") + samples = grid.samplePoints([[3.0, 3.0, 3.0], [4.0, 3.0, 3.0]] | units.m, method="linear") self.assertEqual(len(samples), 2) - self.assertEqual(samples.position[0] , [3.0,3.0,3.0]| units.m) - self.assertEqual(samples.position[0] , samples[0].position) - self.assertEqual(samples.position[1] , samples[1].position) - self.assertEqual(samples.mass , [3.0, 4.0] | units.kg) - + self.assertEqual(samples.position[0], [3.0, 3.0, 3.0] | units.m) + self.assertEqual(samples.position[0], samples[0].position) + self.assertEqual(samples.position[1], samples[1].position) + self.assertEqual(samples.mass, [3.0, 4.0] | units.kg) + def test2(self): - grid = datamodel.new_regular_grid((5,5,5), [10.0, 10.0, 10.0] | units.m) + grid = datamodel.new_regular_grid((5, 5, 5), [10.0, 10.0, 10.0] | units.m) grid.mass = grid.x.value_in(units.m) | units.kg - samples = grid.samplePoints([[3.5,3.0,3.0], [4.5,3.0,3.0]]| units.m, method="linear") + samples = grid.samplePoints([[3.5, 3.0, 3.0], [4.5, 3.0, 3.0]] | units.m, method="linear") self.assertEqual(len(samples), 2) - self.assertEqual(samples.mass , [3.5, 4.5] | units.kg) - + self.assertEqual(samples.mass, [3.5, 4.5] | units.kg) + def test3(self): - grid1 = datamodel.new_regular_grid((5,5,5), [10.0, 10.0, 10.0] | units.m) + grid1 = datamodel.new_regular_grid((5, 5, 5), [10.0, 10.0, 10.0] | units.m) grid1.mass = grid1.x.value_in(units.m) | units.kg - grid2 = datamodel.new_regular_grid((5,5,5), [10.0, 10.0, 10.0] | units.m) - grid2.position += (10.0,0,0) | units.m + grid2 = datamodel.new_regular_grid((5, 5, 5), [10.0, 10.0, 10.0] | units.m) + grid2.position += (10.0, 0, 0) | units.m grid2.mass = grid2.x.value_in(units.m) | units.kg - samples = SamplePointsOnMultipleGrids((grid1, grid2), [[3.0,3.0,3.0], [4.0,3.0,3.0], [13,3,3]]| units.m) + samples = SamplePointsOnMultipleGrids((grid1, grid2), [[3.0, 3.0, 3.0], [4.0, 3.0, 3.0], [13, 3, 3]] | units.m) self.assertEqual(len(samples), 3) - self.assertEqual(samples.mass , [3.0, 4.0, 13.0] | units.kg) + self.assertEqual(samples.mass, [3.0, 4.0, 13.0] | units.kg) diff --git a/src/amuse/test/suite/core_tests/test_incode_particle_sets.py b/src/amuse/test/suite/core_tests/test_incode_particle_sets.py index 55f8ad298a..359ceab5b5 100644 --- a/src/amuse/test/suite/core_tests/test_incode_particle_sets.py +++ b/src/amuse/test/suite/core_tests/test_incode_particle_sets.py @@ -6,220 +6,216 @@ from amuse import datamodel + class ExampleParticlesInterface(interface.InCodeComponentImplementation): """This is an example class to demonstrate how to work with incode particle sets using the object mapping interface. - + The particle set mapping has two functions: - + 1) Convert function calls to attribute access. Setting or getting an attribute is converted to a call to the code. - + particles[0].mass = 10 | units.kg --> code.set_mass(index_of_the_particle = 0, mass = 10) - + 2) Convert ids from the code into particle keys. All particles in AMUSE have an unique key, this key is mapped to the corresponding id of that particle in a code by the particle set. As every particle set mapping is unique for a code, every code has a mapping table (and different codes can have differen ids for the same particle, the key to id mapping will ensure that attribute values are assigned correctly) - + This example class is not connected to a real code, instead it provides all necessary methods to create, delete and update particles. - + For simplicity all attributes are stored in quantities (values with units), no unit conversion is provided. - + In this example code particles have an id (id), position (x,y and z) and a mass attribute (mass). - + See the ExampleParticlesInterfaceTests class for examples / tests of use. """ - + def log(self, message, *arguments): print("IN CODE >>", message.format(*arguments)) - + def __init__(self): super(type(self), self).__init__(None) self.mapping_from_id_to_particle = {} self.highest_id = 0 self.log("initialized the code") - def define_particle_sets(self, builder): """In this method we define the particle set and all attribute. We specify wich methods to call for creating and deleting particles. We specify the methods to access attributes of the particles We specify the methods to create subsets or links - + Redefined from CodeInterface. """ - - + # first we define the name of the set and wich parameter will be used # to specify the id of a particle in the code builder.define_set('particles', 'index_of_the_particle') - + # we define new and delete methods builder.set_new('particles', 'new_particle') builder.set_delete('particles', 'delete_particle') - + # we define the methods to get and set # attributes, note these attributes may overlap # we need to specify the returned attribute names for the # get functions as the framework cannot derive these from # python methods (python methods do not have named return values builder.add_setter('particles', 'set_state') - builder.add_getter('particles', 'get_state', names = ('mass', 'x', 'y', 'z')) + builder.add_getter('particles', 'get_state', names=('mass', 'x', 'y', 'z')) builder.add_setter('particles', 'set_mass') - builder.add_getter('particles', 'get_mass', names = ('mass',)) + builder.add_getter('particles', 'get_mass', names=('mass',)) builder.add_setter('particles', 'set_position') - builder.add_getter('particles', 'get_position', names = ('x', 'y', 'z')) - - builder.add_method('particles', 'get_list', 'element_list' ) - + builder.add_getter('particles', 'get_position', names=('x', 'y', 'z')) + + builder.add_method('particles', 'get_list', 'element_list') + self.log("defined the particle set with name {0!r}", 'particles') def new_particle(self, mass, x, y, z): """Creates new particles. - + Note: the parameternames are directly coupled to the attribute names in the particle set - + Note: the arguments are all arrays """ - + result = [] for mass_element, x_element, y_element, z_element in zip(mass, x, y, z): particle = [self.highest_id, mass_element, x_element, y_element, z_element] self.mapping_from_id_to_particle[self.highest_id] = particle result.append(self.highest_id) - + self.log("created new particle with id {0}, (mass={1}, x={2}, y={3}, z={4})", self.highest_id, mass_element, x_element, y_element, z_element) - + self.highest_id += 1 - + return result def delete_particle(self, index_of_the_particle): """Delete particles in array index_of_the_particle - + Note: the parametername index_of_the_particle was specified in the "define_particle_sets" method """ - + for x in index_of_the_particle: del self.mapping_from_id_to_particle[x] - + self.log("deleted the particle with id {0}", x) def set_state(self, index_of_the_particle, mass, x, y, z): """Sets the mass and the position of a particle. - + Note: the arguments are arrays """ - + for index_element, mass_element, x_element, y_element, z_element in zip(index_of_the_particle, mass, x, y, z): particle = self.mapping_from_id_to_particle[index_element] particle[1] = mass particle[2] = x particle[3] = y particle[4] = z - - + self.log("updated state of particle with id {0}", index_element) def get_state(self, index_of_the_particle): """Returns arrays for the mass, x, y and z values """ - + massresult = quantities.AdaptingVectorQuantity() xresult = quantities.AdaptingVectorQuantity() yresult = quantities.AdaptingVectorQuantity() zresult = quantities.AdaptingVectorQuantity() - + for index_element in index_of_the_particle: particle = self.mapping_from_id_to_particle[index_element] - + massresult.append(particle[1]) xresult.append(particle[2]) yresult.append(particle[3]) zresult.append(particle[4]) - + self.log("retrieved state of particle with id {0}", index_element) - + return massresult, xresult, yresult, zresult def get_mass(self, index_of_the_particle): """Returns an array for the masses of the indices int the index_of_the_particle array """ - + massresult = quantities.AdaptingVectorQuantity() - + for index_element in index_of_the_particle: particle = self.mapping_from_id_to_particle[index_element] massresult.append(particle[1]) - + self.log("retrieved mass of particle with id {0} (mass = {1})", index_element, particle[1]) - + return massresult - def set_mass(self, index_of_the_particle, mass): """Sets the mass and the position of a particle. - + Note: the arguments are arrays """ - + for index_element, mass_element in zip(index_of_the_particle, mass): particle = self.mapping_from_id_to_particle[index_element] - + particle[1] = mass - + self.log("updated mass of particle with id {0} (mass = {1})", index_element, particle[1]) - def get_position(self, index_of_the_particle): """Returns an array of the positions for the indices in index_of_the_particle """ - + xresult = quantities.AdaptingVectorQuantity() yresult = quantities.AdaptingVectorQuantity() zresult = quantities.AdaptingVectorQuantity() - + for index_element in index_of_the_particle: particle = self.mapping_from_id_to_particle[index_element] - + xresult.append(particle[2]) yresult.append(particle[3]) zresult.append(particle[4]) - + self.log("retrieved position of particle with id {0} (x = {1}, y = {2}, z = {3})", index_element, particle[2], particle[3], particle[4]) return xresult, yresult, zresult def set_position(self, index_of_the_particle, x, y, z): """Sets the mass and the position of a particle. - + Note: the arguments are arrays """ - + for index_element, x_element, y_element, z_element in zip(index_of_the_particle, x, y, z): particle = self.mapping_from_id_to_particle[index_element] - + particle[2] = x particle[3] = y particle[4] = z - + self.log("updated position of particle with id {0} (x = {1}, y = {2}, z = {3})", index_element, particle[2], particle[3], particle[4]) - + def get_list_size(self, index_of_the_particle): """Returns the inclusive range of indices in the list of element coupled to a particle. """ - return (0,9) - - def get_list_element(self, index_in_the_list, index_of_the_particle ): + return (0, 9) + + def get_list_element(self, index_in_the_list, index_of_the_particle): """Returns an array of the positions for the indices in index_of_the_particle """ if not hasattr(index_in_the_list, '__iter__'): @@ -228,136 +224,134 @@ def get_list_element(self, index_in_the_list, index_of_the_particle ): index_of_the_particle = [index_of_the_particle,] value1 = quantities.AdaptingVectorQuantity() value2 = quantities.AdaptingVectorQuantity() - + for index_of_one_particle, index_of_one_element in zip(index_of_the_particle, index_in_the_list): - + value1.append(index_of_one_particle | units.none) value2.append(index_of_one_element | units.none) - + return value1, value2 - + def get_list(self, index_of_the_particle): if hasattr(index_of_the_particle, '__iter__'): - return [self._create_new_grid(self.specify_list, index_of_the_particle = x) for x in index_of_the_particle] + return [self._create_new_grid(self.specify_list, index_of_the_particle=x) for x in index_of_the_particle] else: - return self._create_new_grid(self.specify_list, index_of_the_particle = index_of_the_particle) - - def specify_list(self, definition, index_of_the_particle = 0): + return self._create_new_grid(self.specify_list, index_of_the_particle=index_of_the_particle) + + def specify_list(self, definition, index_of_the_particle=0): definition.set_grid_range('get_list_size') definition.add_getter('get_list_element', names=('value1', 'value2')) - definition.define_extra_keywords({'index_of_the_particle':index_of_the_particle}) - + definition.define_extra_keywords({'index_of_the_particle': index_of_the_particle}) + class ExampleParticlesInterfaceTests(amusetest.TestCase): """This class runs tests on the example particles interface class. - + """ + def test1(self): """ In this test we will add and remove a particle from the particle set of the code. - + Adding a particle to the set will result in creating a new particle in the code. - + Removing a particle form the set will result in deleting the corresponding particle in the code. """ - + self.log("adding and removing of a particle") - + instance = ExampleParticlesInterface() self.assertEqual(len(instance.particles), 0) - + # we create a particle in our script # all attributes of this particle are stored in the python space # when creating a particle you can set it's key # or let the system determine a unique key # to set the key in the script do: core.Particle(1000) where 1000 is the key - + theParticle = datamodel.Particle() theParticle.mass = 10 | units.kg theParticle.x = 0.1 | units.m theParticle.y = 0.2 | units.m theParticle.z = 0.5 | units.m - + self.log("Adding particle with key {0}", theParticle.key) instance.particles.add_particle(theParticle) - + print(instance.particles.index_in_code) self.assertEqual(len(instance.particles), 1) - + self.log("Removing particle with key {0}", theParticle.key) instance.particles.remove_particle(theParticle) - + self.assertEqual(len(instance.particles), 0) - def test2(self): """ In this test we will set and get different properties of the particle. - + To limit overhead, the system will use the set_* or get_* calls that are the closests match to the attributes queries. """ self.log("accessing attributes of a particle") instance = ExampleParticlesInterface() self.assertEqual(len(instance.particles), 0) - + theParticle = datamodel.Particle() theParticle.mass = 10 | units.kg theParticle.x = 0.1 | units.m theParticle.y = 0.2 | units.m theParticle.z = 0.5 | units.m - + instance.particles.add_particle(theParticle) - + self.log("Getting the mass of particle with key {0}, get_mass should be called", theParticle.key) self.assertEqual(instance.particles[0].mass, 10 | units.kg) - + self.log("Getting the position of particle with key {0}, get_position should be called", theParticle.key) self.assertEqual(instance.particles[0].position, [0.1, 0.2, 0.5] | units.m) - + self.log("Getting the only the x attribute of particle with key {0}, get_position should be called (y and z are discarded)", theParticle.key) self.assertEqual(instance.particles[0].x, 0.1 | units.m) - - + self.log("Setting the position of particle with key {0}, set_position should be called", theParticle.key) - instance.particles[0].position = [0.2, 0.3, 0.6] | units.m - + instance.particles[0].position = [0.2, 0.3, 0.6] | units.m + self.log("Setting the x of particle with key {0}, should fail as no function can set x and no others", theParticle.key) + def block(): - instance.particles[0].x = 0.1 | units.m + instance.particles[0].x = 0.1 | units.m self.assertRaises(Exception, block) - - - + def test3(self): """ In this test we will get a list from a particle """ - + instance = ExampleParticlesInterface() self.assertEqual(len(instance.particles), 0) - + theParticle = datamodel.Particle() theParticle.mass = 10 | units.kg theParticle.x = 0.1 | units.m theParticle.y = 0.2 | units.m theParticle.z = 0.5 | units.m - + instance.particles.add_particle(theParticle) - + theParticle = datamodel.Particle() theParticle.mass = 11 | units.kg theParticle.x = 0.1 | units.m theParticle.y = 0.2 | units.m theParticle.z = 0.5 | units.m - + instance.particles.add_particle(theParticle) - + self.assertEqual(len(instance.particles[0].element_list()), 10) list = instance.particles[0].element_list() self.assertEqual(list[0].value1, 0 | units.none) @@ -367,57 +361,51 @@ def test3(self): for x in range(len(list)): self.assertEqual(list[x].value1, 0 | units.none) self.assertEqual(list[x].value2, x | units.none) - + list = instance.particles[1].element_list() for x in range(len(list)): self.assertEqual(list[x].value1, 1 | units.none) self.assertEqual(list[x].value2, x | units.none) - - #print instance.particles.element_list() - #print instance.particles.element_list()[0][1].value2 - - - + + # print instance.particles.element_list() + # print instance.particles.element_list()[0][1].value2 + def test4(self): """ In this test we will get a list from a particle """ - + instance = ExampleParticlesInterface() self.assertEqual(len(instance.particles), 0) - + theParticle = datamodel.Particle() theParticle.x = 0.1 | units.m theParticle.y = 0.2 | units.m theParticle.z = 0.5 | units.m - - self.assertRaises(exceptions.AmuseException, instance.particles.add_particle, theParticle) - - + self.assertRaises(exceptions.AmuseException, instance.particles.add_particle, theParticle) + def test5(self): """ In this test we will get subsets from the incode set """ - + instance = ExampleParticlesInterface() self.assertEqual(len(instance.particles), 0) - + particles = datamodel.Particles(10) particles.mass = 0.1 | units.kg particles.x = 0.1 | units.m particles.y = 0.2 | units.m particles.z = 0.5 | units.m - + instance.particles.add_particle(particles) - + self.assertEqual(len(instance.particles), 10) - + subset = instance.particles[0:2] self.assertEqual(len(subset), 2) - self.assertTrue(str(subset).find('key')> 0) - + self.assertTrue(str(subset).find('key') > 0) + def log(self, message, *arguments): print("IN TEST >>", message.format(*arguments)) - - diff --git a/src/amuse/test/suite/core_tests/test_incode_storage.py b/src/amuse/test/suite/core_tests/test_incode_storage.py index c0689084e6..7257af2af5 100644 --- a/src/amuse/test/suite/core_tests/test_incode_storage.py +++ b/src/amuse/test/suite/core_tests/test_incode_storage.py @@ -8,8 +8,9 @@ from amuse.units import constants from amuse.units import nbody_system + class TestParticles(amusetest.TestCase): - + def test1(self): class Code(object): def __init__(self): @@ -17,57 +18,57 @@ def __init__(self): self.data = [] self.get_position_called = False self.set_position_called = False - + def get_number_of_particles(self): - return 0 if not self.data else len(self.data[0]) - - def get_position(self,index): + return 0 if not self.data else len(self.data[0]) + + def get_position(self, index): self.get_position_called = True data_to_return = [(self.data[0][i], self.data[1][i], self.data[2][i]) for i in index] - data_to_return = numpy.asarray(data_to_return).reshape(3,-1) + data_to_return = numpy.asarray(data_to_return).reshape(3, -1) return [units.m(x) for x in data_to_return] - - def set_position(self,index,x,y,z): + + def set_position(self, index, x, y, z): self.set_position_called = True pass - + def new_particle(self, x, y, z): x = x.value_in(units.m) y = y.value_in(units.m) z = z.value_in(units.m) - self.data = [x,y,z] + self.data = [x, y, z] return [i for i in range(len(x))] - + code = Code() storage = InCodeAttributeStorage( code, - NewParticleMethod(code.new_particle,("x","y","z")), + NewParticleMethod(code.new_particle, ("x", "y", "z")), None, code.get_number_of_particles, [], - [ParticleGetAttributesMethod(code.get_position,("x","y","z")),], - name_of_the_index = "index" + [ParticleGetAttributesMethod(code.get_position, ("x", "y", "z")),], + name_of_the_index="index" ) - + self.assertEqual(len(storage), 0) - self.assertEqual(storage.get_defined_attribute_names(), ["x","y","z"]) - + self.assertEqual(storage.get_defined_attribute_names(), ["x", "y", "z"]) + self.assertFalse(code.get_position_called) - storage.get_values_in_store([],["x","y","z"]) + storage.get_values_in_store([], ["x", "y", "z"]) self.assertFalse(code.get_position_called) - + storage.add_particles_to_store( - [1,2,3,4], - ["x","y","z"], + [1, 2, 3, 4], + ["x", "y", "z"], [ - units.m([1,2,3,4]), - units.m([2,3,4,5]), - units.m([3,4,5,6]) + units.m([1, 2, 3, 4]), + units.m([2, 3, 4, 5]), + units.m([3, 4, 5, 6]) ] ) - + self.assertEqual(len(storage), 4) - + def test2(self): class Code(object): def __init__(self): @@ -77,75 +78,74 @@ def __init__(self): self.set_position_called = False self.get_mass_called = False self.set_mass_called = False - + def get_number_of_particles(self): - return 0 if not self.data else len(self.data[0]) - - def get_position(self,index): + return 0 if not self.data else len(self.data[0]) + + def get_position(self, index): self.get_position_called = True data_to_return = [(self.data[0][i], self.data[1][i], self.data[2][i]) for i in index] - data_to_return = numpy.asarray(data_to_return).reshape(3,-1) + data_to_return = numpy.asarray(data_to_return).reshape(3, -1) return [units.m(x) for x in data_to_return] - - def get_mass(self,index): + + def get_mass(self, index): self.get_mass_called = True data_to_return = [self.data[3][i] for i in index] return units.kg(data_to_return) - - def set_position(self,index,x,y,z): + + def set_position(self, index, x, y, z): self.set_position_called = True pass - - def set_mass(self,index,mass): + + def set_mass(self, index, mass): self.set_mass_called = True pass - + def new_particle(self, x, y, z, mass): x = x.value_in(units.m) y = y.value_in(units.m) z = z.value_in(units.m) mass = mass.value_in(units.kg) - self.data = [x,y,z, mass] + self.data = [x, y, z, mass] return [i for i in range(len(x))] - + code = Code() storage = InCodeAttributeStorage( code, - NewParticleMethod(code.new_particle,("x","y","z","mass")), + NewParticleMethod(code.new_particle, ("x", "y", "z", "mass")), None, code.get_number_of_particles, [], [ - ParticleGetAttributesMethod(code.get_position,("x","y","z")), - ParticleGetAttributesMethod(code.get_mass,("mass",)), + ParticleGetAttributesMethod(code.get_position, ("x", "y", "z")), + ParticleGetAttributesMethod(code.get_mass, ("mass",)), ], - name_of_the_index = "index" + name_of_the_index="index" ) - + storage.add_particles_to_store( - [1,2,3,4], - ["x","y","z", "mass"], + [1, 2, 3, 4], + ["x", "y", "z", "mass"], [ - units.m([1,2,3,4]), - units.m([2,3,4,5]), - units.m([3,4,5,6]), - units.kg([13,14,15,16]), + units.m([1, 2, 3, 4]), + units.m([2, 3, 4, 5]), + units.m([3, 4, 5, 6]), + units.kg([13, 14, 15, 16]), ] ) - + self.assertEqual(len(storage), 4) - - self.assertEqual(storage.get_defined_attribute_names(), [ "mass", "x","y","z"]) - + + self.assertEqual(storage.get_defined_attribute_names(), ["mass", "x", "y", "z"]) + self.assertFalse(code.get_position_called) self.assertFalse(code.get_mass_called) - indices = storage.get_indices_of([2,3]) - x,y,mass = storage.get_values_in_store(indices,["x","y","mass"]) + indices = storage.get_indices_of([2, 3]) + x, y, mass = storage.get_values_in_store(indices, ["x", "y", "mass"]) self.assertTrue(code.get_position_called) self.assertTrue(code.get_mass_called) self.assertEqual(x[1], 3 | units.m) self.assertEqual(mass[1], 15 | units.kg) - def test3(self): class Code(object): @@ -154,57 +154,57 @@ def __init__(self): self.data = [] self.get_mass_called = False self.set_mass_called = False - + def get_number_of_particles(self): - return 0 if not self.data else len(self.data[0]) - - def get_mass(self,index): + return 0 if not self.data else len(self.data[0]) + + def get_mass(self, index): self.get_mass_called = True data_to_return = [self.data[0][i] for i in index] return units.kg(data_to_return) - - def set_mass(self,index,mass): + + def set_mass(self, index, mass): self.set_mass_called = True pass - + def new_particle(self, mass): mass = mass.value_in(units.kg) self.data = [mass] return [i for i in range(len(mass))] - + code = Code() storage = InCodeAttributeStorage( code, - NewParticleMethod(code.new_particle,("mass",)), + NewParticleMethod(code.new_particle, ("mass",)), None, code.get_number_of_particles, [], [ - ParticleGetAttributesMethod(code.get_mass,("mass",)), + ParticleGetAttributesMethod(code.get_mass, ("mass",)), ], - name_of_the_index = "index" + name_of_the_index="index" ) - + storage.add_particles_to_store( - [1,2,3,4], + [1, 2, 3, 4], ["mass"], [ - units.kg([1,2,3,4]), + units.kg([1, 2, 3, 4]), ] ) - + self.assertEqual(len(storage), 4) - + self.assertEqual(storage.get_defined_attribute_names(), ["mass",]) - - indices = storage.get_indices_of([2,3]) - index,mass = storage.get_values_in_store(indices,["index_in_code","mass"]) + + indices = storage.get_indices_of([2, 3]) + index, mass = storage.get_values_in_store(indices, ["index_in_code", "mass"]) self.assertTrue(code.get_mass_called) self.assertEqual(index[0], 1) self.assertEqual(mass[0], 2 | units.kg) self.assertEqual(index[1], 2) self.assertEqual(mass[1], 3 | units.kg) - + def test4(self): class Code(object): def __init__(self): @@ -213,153 +213,152 @@ def __init__(self): self.get_mass_called = False self.set_mass_called = False self.number_of_particles = 0 - + def get_number_of_particles(self): - return self.number_of_particles - - def get_mass(self,index): + return self.number_of_particles + + def get_mass(self, index): self.get_mass_called = True data_to_return = [self.data[i] for i in index] return units.kg(data_to_return) - - def set_mass(self,index,mass): + + def set_mass(self, index, mass): self.set_mass_called = True pass - + def new_particle(self, mass): mass = mass.value_in(units.kg) self.data = mass self.number_of_particles = len(self.data) return [i for i in range(len(mass))] - + code = Code() storage = InCodeAttributeStorage( code, - NewParticleMethod(code.new_particle,("mass",)), + NewParticleMethod(code.new_particle, ("mass",)), None, code.get_number_of_particles, [], [ - ParticleGetAttributesMethod(code.get_mass,("mass",)), + ParticleGetAttributesMethod(code.get_mass, ("mass",)), ], - name_of_the_index = "index" + name_of_the_index="index" ) - + storage.add_particles_to_store( - numpy.asarray([1,2,3,4], dtype='uint64'), + numpy.asarray([1, 2, 3, 4], dtype='uint64'), ["mass"], [ - units.kg([1,2,3,4]), + units.kg([1, 2, 3, 4]), ] ) - + self.assertEqual(len(storage), 4) - - storage._remove_indices([1,2,]) + + storage._remove_indices([1, 2,]) code.number_of_particles = 2 - indices = storage.get_indices_of([1,4]) - index,mass = storage.get_values_in_store(indices,["index_in_code","mass"]) - + indices = storage.get_indices_of([1, 4]) + index, mass = storage.get_values_in_store(indices, ["index_in_code", "mass"]) + self.assertEqual(index[0], 0) self.assertEqual(index[1], 3) self.assertEqual(mass[0], 1 | units.kg) self.assertEqual(mass[1], 4 | units.kg) - - + self.assertEqual(len(storage), 2) - - storage._add_indices([4,5]) + + storage._add_indices([4, 5]) code.data = numpy.concatenate((code.data, [5, 6])) - + code.number_of_particles = 4 self.assertEqual(len(storage), 4) - + indices = storage.get_indices_of(storage.particle_keys) - mass, = storage.get_values_in_store(indices,["mass"]) - + mass, = storage.get_values_in_store(indices, ["mass"]) + self.assertEqual(mass[0], 1 | units.kg) self.assertEqual(mass[1], 4 | units.kg) self.assertEqual(mass[2], 5 | units.kg) self.assertEqual(mass[3], 6 | units.kg) - + storage._remove_indices([4,]) code.number_of_particles = 3 self.assertEqual(len(storage), 3) - + indices = storage.get_indices_of(storage.particle_keys) - mass, = storage.get_values_in_store(indices,["mass"]) - + mass, = storage.get_values_in_store(indices, ["mass"]) + self.assertEqual(mass[0], 1 | units.kg) self.assertEqual(mass[1], 4 | units.kg) self.assertEqual(mass[2], 6 | units.kg) - + def test5(self): class Code(object): def __init__(self): self.data = [] self.number_of_particles = 0 - + def get_number_of_particles(self): - return self.number_of_particles - - def get_mass(self,index): + return self.number_of_particles + + def get_mass(self, index): data_to_return = [self.data[i][0] for i in index] return units.kg(data_to_return) - - def get_children(self,index): + + def get_children(self, index): return [(self.data[i][1]) for i in index], [(self.data[i][2]) for i in index] - + def new_particle(self, mass): mass = mass.value_in(units.kg) - self.data = [[x,-1,-1] for x in mass] + self.data = [[x, -1, -1] for x in mass] self.number_of_particles = len(self.data) return [i for i in range(len(mass))] - + code = Code() - + children_getter = ParticleGetAttributesMethod( code.get_children, ('child1', 'child2',) ) - children_getter.index_output_attributes = set(['child1','child2']) - + children_getter.index_output_attributes = set(['child1', 'child2']) + storage = InCodeAttributeStorage( code, - NewParticleMethod(code.new_particle,("mass",)), + NewParticleMethod(code.new_particle, ("mass",)), None, code.get_number_of_particles, [], [ - ParticleGetAttributesMethod(code.get_mass,("mass",)), + ParticleGetAttributesMethod(code.get_mass, ("mass",)), children_getter ], - name_of_the_index = "index" + name_of_the_index="index" ) - + storage.add_particles_to_store( - numpy.asarray([100,200,300,400], dtype='uint64'), + numpy.asarray([100, 200, 300, 400], dtype='uint64'), ["mass"], [ - units.kg([1,2,3,4]), + units.kg([1, 2, 3, 4]), ] ) - + self.assertEqual(len(storage), 4) - - indices = storage.get_indices_of([100,400]) - mass = storage.get_values_in_store(indices,["mass",])[0] + + indices = storage.get_indices_of([100, 400]) + mass = storage.get_values_in_store(indices, ["mass",])[0] self.assertEqual(mass[0], 1.0 | units.kg) self.assertEqual(mass[1], 4.0 | units.kg) - + code.data[0][1] = 1 code.data[0][2] = 2 - + indices = storage.get_indices_of([100]) - child1,child2 = storage.get_values_in_store(indices,['child1', 'child2']) - + child1, child2 = storage.get_values_in_store(indices, ['child1', 'child2']) + self.assertEqual(child1[0].number, 200) self.assertEqual(child2[0].number, 300) - + def test7(self): class Code(object): def __init__(self): @@ -369,327 +368,318 @@ def __init__(self): self.set_position_called = False self.get_mass_called = False self.set_mass_called = False - + def get_number_of_particles(self): - return 0 if not self.data else len(self.data[0]) - - def get_position(self,index): + return 0 if not self.data else len(self.data[0]) + + def get_position(self, index): self.get_position_called = True data_to_return = [(self.data[0][i], self.data[1][i], self.data[2][i]) for i in index] - data_to_return = numpy.asarray(data_to_return).reshape(3,-1) + data_to_return = numpy.asarray(data_to_return).reshape(3, -1) return [units.m(x) for x in data_to_return] - - def get_mass(self,index): + + def get_mass(self, index): self.get_mass_called = True data_to_return = [self.data[3][i] for i in index] return data_to_return - - def set_position(self,index,x,y,z): + + def set_position(self, index, x, y, z): self.set_position_called = True pass - - def set_mass(self,index,mass): + + def set_mass(self, index, mass): self.set_mass_called = True - for i,j in enumerate(index): + for i, j in enumerate(index): self.data[3][j] = mass[i] return [0 for i in range(len(index))] - + def new_particle(self, x, y, z, mass): x = x.value_in(units.m) y = y.value_in(units.m) z = z.value_in(units.m) - mass = mass - self.data = [x,y,z,mass] + mass = mass + self.data = [x, y, z, mass] return [i for i in range(len(x))] - + code = Code() storage = InCodeAttributeStorage( code, - NewParticleMethod(code.new_particle,("x","y","z","mass")), + NewParticleMethod(code.new_particle, ("x", "y", "z", "mass")), None, code.get_number_of_particles, [ - ParticleSetAttributesMethod(code.set_position,("x","y","z")), - ParticleSetAttributesMethod(code.set_mass,("mass",)), + ParticleSetAttributesMethod(code.set_position, ("x", "y", "z")), + ParticleSetAttributesMethod(code.set_mass, ("mass",)), ], [ - ParticleGetAttributesMethod(code.get_position,("x","y","z")), - ParticleGetAttributesMethod(code.get_mass,("mass",)), + ParticleGetAttributesMethod(code.get_position, ("x", "y", "z")), + ParticleGetAttributesMethod(code.get_mass, ("mass",)), ], - name_of_the_index = "index" + name_of_the_index="index" ) - + storage.add_particles_to_store( - [1,2,3,4], - ["x","y","z", "mass"], + [1, 2, 3, 4], + ["x", "y", "z", "mass"], [ - units.m([1,2,3,4]), - units.m([2,3,4,5]), - units.m([3,4,5,6]), - numpy.asarray([13.0,14.0,15,16]), + units.m([1, 2, 3, 4]), + units.m([2, 3, 4, 5]), + units.m([3, 4, 5, 6]), + numpy.asarray([13.0, 14.0, 15, 16]), ] ) - + self.assertEqual(len(storage), 4) - - self.assertEqual(storage.get_defined_attribute_names(), [ "mass", "x","y","z"]) - + + self.assertEqual(storage.get_defined_attribute_names(), ["mass", "x", "y", "z"]) + self.assertFalse(code.get_position_called) self.assertFalse(code.get_mass_called) - indices = storage.get_indices_of([2,3]) - x,y,mass = storage.get_values_in_store(indices,["x","y","mass"]) + indices = storage.get_indices_of([2, 3]) + x, y, mass = storage.get_values_in_store(indices, ["x", "y", "mass"]) self.assertTrue(code.get_position_called) self.assertTrue(code.get_mass_called) self.assertEqual(x[1], 3 | units.m) - self.assertEqual(mass[1], 15 ) - self.assertEqual(mass[0], 14 ) - storage.set_values_in_store(indices,["x","y", "z", "mass"], [[10,11] | units.m , [12,14] | units.m, [12,14] | units.m, [40.0, 50.0]]) - x,y,mass = storage.get_values_in_store(indices,["x","y","mass"]) - self.assertEqual(mass[1], 50 ) - self.assertEqual(mass[0], 40 ) - - - - + self.assertEqual(mass[1], 15) + self.assertEqual(mass[0], 14) + storage.set_values_in_store(indices, ["x", "y", "z", "mass"], [[10, 11] | units.m, [12, 14] | units.m, [12, 14] | units.m, [40.0, 50.0]]) + x, y, mass = storage.get_values_in_store(indices, ["x", "y", "mass"]) + self.assertEqual(mass[1], 50) + self.assertEqual(mass[0], 40) + class TestGrids(amusetest.TestCase): - + def test1(self): class Code(object): def get_range(self): - return (1,10,2,5,3,6) - - def get_ijk(self,i,j,k): + return (1, 10, 2, 5, 3, 6) + + def get_ijk(self, i, j, k): return units.m(i), units.m(j), units.m(k) - + code = Code() - + storage = InCodeGridAttributeStorage( code, code.get_range, [], - [ParticleGetAttributesMethod(code.get_ijk,("i","j","k")),], + [ParticleGetAttributesMethod(code.get_ijk, ("i", "j", "k")),], ) - + self.assertEqual(storage.storage_shape(), (10, 4, 4)) - self.assertEqual(storage.get_defined_attribute_names(), ["i","j","k"]) - - values = storage.get_values_in_store((0,1,1), ("i",)) + self.assertEqual(storage.get_defined_attribute_names(), ["i", "j", "k"]) + + values = storage.get_values_in_store((0, 1, 1), ("i",)) self.assertEqual(len(values), 1) self.assertEqual(values[0], 1 | units.m) - - values = storage.get_values_in_store((0,1,1), ("k","j","i",)) + + values = storage.get_values_in_store((0, 1, 1), ("k", "j", "i",)) self.assertEqual(values[0], 4 | units.m) self.assertEqual(values[1], 3 | units.m) self.assertEqual(values[2], 1 | units.m) - - + def test2(self): class Code(object): def get_range(self): - return (1,10,2,5,3,6) - - def get_ijk(self,i,j,k): + return (1, 10, 2, 5, 3, 6) + + def get_ijk(self, i, j, k): return units.m(i), units.m(j), units.m(k) - + code = Code() - + storage = InCodeGridAttributeStorage( code, code.get_range, [], - [ParticleGetAttributesMethod(code.get_ijk,("i","j","k")),], + [ParticleGetAttributesMethod(code.get_ijk, ("i", "j", "k")),], ) values = storage.get_values_in_store(numpy.s_[0:2], ("i",)) self.assertEqual(len(values), 1) self.assertEqual(len(values[0]), 2) - self.assertEqual(values[0].number.shape, (2,4,4)) + self.assertEqual(values[0].number.shape, (2, 4, 4)) self.assertEqual(values[0][0][0][0], 1 | units.m) self.assertEqual(values[0][1][0][0], 2 | units.m) - + def test3(self): - - shape = (11,5,5) - + + shape = (11, 5, 5) + class Code(object): - + def __init__(self): self.storage = numpy.arange(shape[0]*shape[1]*shape[2]).reshape(shape) - + def get_range(self): - return (0,shape[0]-1,0,shape[1]-1,0,shape[2]-1) - - def get_a(self,i_s,j_s,k_s): - return units.m.new_quantity(numpy.asarray([(self.storage[i][j][k]) for i,j,k in zip(i_s, j_s, k_s)])) - + return (0, shape[0]-1, 0, shape[1]-1, 0, shape[2]-1) + + def get_a(self, i_s, j_s, k_s): + return units.m.new_quantity(numpy.asarray([(self.storage[i][j][k]) for i, j, k in zip(i_s, j_s, k_s)])) + def set_a(self, i_s, j_s, k_s, values): - #~ print i_s, j_s, k_s - #~ print "VALUES:", values + # ~ print i_s, j_s, k_s + # ~ print "VALUES:", values index = 0 - for i,j,k in zip(i_s, j_s, k_s): + for i, j, k in zip(i_s, j_s, k_s): self.storage[i][j][k] = values[index].value_in(units.m) index += 1 - #~ print index - + # ~ print index + code = Code() - + storage = InCodeGridAttributeStorage( code, code.get_range, - [ParticleSetAttributesMethod(code.set_a,("a",)),], - [ParticleGetAttributesMethod(code.get_a,("a",)),], + [ParticleSetAttributesMethod(code.set_a, ("a",)),], + [ParticleGetAttributesMethod(code.get_a, ("a",)),], ) - + values = storage.get_values_in_store(None, ("a",)) self.assertTrue(numpy.all(values[0].value_in(units.m) == code.storage)) - #self.assertTrue(False) - values = storage.get_values_in_store((0,0,0), ("a",)) + # self.assertTrue(False) + values = storage.get_values_in_store((0, 0, 0), ("a",)) self.assertEqual(values[0], 0 | units.m) - storage.set_values_in_store((0,0,0), ("a",), [11.0 | units.m,]) - values = storage.get_values_in_store((0,0,0), ("a",)) + storage.set_values_in_store((0, 0, 0), ("a",), [11.0 | units.m,]) + values = storage.get_values_in_store((0, 0, 0), ("a",)) self.assertEqual(values[0], 11.0 | units.m) - values = storage.get_values_in_store((0,0), ("a",)) - storage.set_values_in_store((0,0), ("a",), [[11.0, 12.0, 13.0, 14.0, 15.0]| units.m,]) + values = storage.get_values_in_store((0, 0), ("a",)) + storage.set_values_in_store((0, 0), ("a",), [[11.0, 12.0, 13.0, 14.0, 15.0] | units.m,]) self.assertTrue(numpy.all(code.storage[0][0] == [11.0, 12.0, 13.0, 14.0, 15.0])) - def test4(self): class Code(object): def get_range(self, d, l): - return (1,10,2,5,3,6) - - def get_ijk(self,i,j,k, d, l): + return (1, 10, 2, 5, 3, 6) + + def get_ijk(self, i, j, k, d, l): return units.m(d), units.m(l), units.m(k) - + code = Code() - + storage = InCodeGridAttributeStorage( code, code.get_range, [], - [ParticleGetAttributesMethod(code.get_ijk,("i","j","k")),], - extra_keyword_arguments_for_getters_and_setters = {'d':1, 'l':2}, + [ParticleGetAttributesMethod(code.get_ijk, ("i", "j", "k")),], + extra_keyword_arguments_for_getters_and_setters={'d': 1, 'l': 2}, ) - + self.assertEqual(storage.storage_shape(), (10, 4, 4)) - self.assertEqual(storage.get_defined_attribute_names(), ["i","j","k"]) - - values = storage.get_values_in_store((0,1,1), ("i",)) + self.assertEqual(storage.get_defined_attribute_names(), ["i", "j", "k"]) + + values = storage.get_values_in_store((0, 1, 1), ("i",)) self.assertEqual(len(values), 1) self.assertEqual(values[0], 1 | units.m) - - values = storage.get_values_in_store((0,1,1), ("k","j","i",)) + + values = storage.get_values_in_store((0, 1, 1), ("k", "j", "i",)) self.assertEqual(values[0], 4 | units.m) self.assertEqual(values[1], 2 | units.m) self.assertEqual(values[2], 1 | units.m) - - - def test5(self): class Code(object): def get_range(self): - return (1,10,2,5,3,6) - - def get_ijk(self,i,j,k): + return (1, 10, 2, 5, 3, 6) + + def get_ijk(self, i, j, k): return units.m(i), units.m(j), units.m(k) - + code = Code() - + storage = InCodeGridAttributeStorage( code, code.get_range, [], - [ParticleGetAttributesMethod(code.get_ijk,("i","j","k")),], + [ParticleGetAttributesMethod(code.get_ijk, ("i", "j", "k")),], ) - + self.assertEqual(storage.storage_shape(), (10, 4, 4)) - self.assertEqual(storage.get_defined_attribute_names(), ["i","j","k"]) - + self.assertEqual(storage.get_defined_attribute_names(), ["i", "j", "k"]) + values = storage.get_values_in_store(None, ("i",)) self.assertEqual(len(values), 1) self.assertEqual(values[0].number.ndim, 3) - - + def test6(self): - - shape = (11,5,5) - + + shape = (11, 5, 5) + class Code(object): - + def __init__(self): self.storage = numpy.arange(shape[0]*shape[1]*shape[2]).reshape(shape) - + def get_range(self): - return (0,shape[0]-1,0,shape[1]-1,0,shape[2]-1) - - def get_a(self,i_s,j_s,k_s): - return numpy.asarray([(self.storage[i][j][k]) for i,j,k in zip(i_s, j_s, k_s)]) - + return (0, shape[0]-1, 0, shape[1]-1, 0, shape[2]-1) + + def get_a(self, i_s, j_s, k_s): + return numpy.asarray([(self.storage[i][j][k]) for i, j, k in zip(i_s, j_s, k_s)]) + def set_a(self, i_s, j_s, k_s, values): - #~ print i_s, j_s, k_s - #~ print "VALUES:", values + # ~ print i_s, j_s, k_s + # ~ print "VALUES:", values index = 0 - for i,j,k in zip(i_s, j_s, k_s): + for i, j, k in zip(i_s, j_s, k_s): self.storage[i][j][k] = values[index] index += 1 - #~ print index - + # ~ print index + code = Code() - + storage = InCodeGridAttributeStorage( code, code.get_range, - [ParticleSetAttributesMethod(code.set_a,("a",)),], - [ParticleGetAttributesMethod(code.get_a,("a",)),], + [ParticleSetAttributesMethod(code.set_a, ("a",)),], + [ParticleGetAttributesMethod(code.get_a, ("a",)),], ) - + values = storage.get_values_in_store(None, ("a",)) self.assertTrue(numpy.all(values[0] == code.storage)) - values = storage.get_values_in_store((0,0,0), ("a",)) + values = storage.get_values_in_store((0, 0, 0), ("a",)) self.assertEqual(values[0], 0) - storage.set_values_in_store((0,0,0), ("a",), [11.0,]) - values = storage.get_values_in_store((0,0,0), ("a",)) + storage.set_values_in_store((0, 0, 0), ("a",), [11.0,]) + values = storage.get_values_in_store((0, 0, 0), ("a",)) self.assertEqual(values[0], 11.0) - values = storage.get_values_in_store((0,0), ("a",))[0] + values = storage.get_values_in_store((0, 0), ("a",))[0] self.assertTrue(numpy.all(values == [11.0, 1.0, 2.0, 3.0, 4.0])) - storage.set_values_in_store((0,0), ("a",), [[11.0, 12.0, 13.0, 14.0, 15.0],]) + storage.set_values_in_store((0, 0), ("a",), [[11.0, 12.0, 13.0, 14.0, 15.0],]) self.assertTrue(numpy.all(code.storage[0][0] == [11.0, 12.0, 13.0, 14.0, 15.0])) - + def test7(self): - - shape = (11,5,5) - + + shape = (11, 5, 5) + class Code(object): - + def __init__(self): self.storage = numpy.arange(shape[0]*shape[1]*shape[2]).reshape(shape) - + def get_range(self): - return (0,shape[0]-1,0,shape[1]-1,0,shape[2]-1) - - def get_a(self,i_s,j_s,k_s): - return numpy.asarray([(self.storage[i][j][k]) for i,j,k in zip(i_s, j_s, k_s)]) - + return (0, shape[0]-1, 0, shape[1]-1, 0, shape[2]-1) + + def get_a(self, i_s, j_s, k_s): + return numpy.asarray([(self.storage[i][j][k]) for i, j, k in zip(i_s, j_s, k_s)]) + def set_a(self, i_s, j_s, k_s, values): index = 0 - for i,j,k in zip(i_s, j_s, k_s): + for i, j, k in zip(i_s, j_s, k_s): self.storage[i][j][k] = values[index] index += 1 - + code = Code() - + storage = InCodeGridAttributeStorage( code, code.get_range, - [ParticleSetAttributesMethod(code.set_a,("a",)),], - [ParticleGetAttributesMethod(code.get_a,("a",)),], + [ParticleSetAttributesMethod(code.set_a, ("a",)),], + [ParticleGetAttributesMethod(code.get_a, ("a",)),], ) - + values = storage.get_values_in_store((), ()) - self.assertTrue(values==[]) - values = storage.get_values_in_store((0,0,1,), ("a",)) - self.assertTrue(values[0]==1) + self.assertTrue(values == []) + values = storage.get_values_in_store((0, 0, 1,), ("a",)) + self.assertTrue(values[0] == 1) def test8(self): class Code(object): @@ -698,30 +688,26 @@ def __init__(self): def get_range(self): return () - + def get_a(self): return self.storage - + def set_a(self, value): - self.storage=value - + self.storage = value - code = Code() - + storage = InCodeGridAttributeStorage( code, code.get_range, - [ParticleSetAttributesMethod(code.set_a,("a",)),], - [ParticleGetAttributesMethod(code.get_a,("a",)),], + [ParticleSetAttributesMethod(code.set_a, ("a",)),], + [ParticleGetAttributesMethod(code.get_a, ("a",)),], ) - + self.assertEqual(storage.storage_shape(), ()) self.assertEqual(storage.get_defined_attribute_names(), ['a']) - + values = storage.get_values_in_store((), ("a",)) self.assertEqual(len(values), 1) - print(values,"<") + print(values, "<") self.assertEqual(values[0], 1 | units.m) - - diff --git a/src/amuse/test/suite/core_tests/test_indexing.py b/src/amuse/test/suite/core_tests/test_indexing.py index 2799353d7c..24ccca28c3 100644 --- a/src/amuse/test/suite/core_tests/test_indexing.py +++ b/src/amuse/test/suite/core_tests/test_indexing.py @@ -5,449 +5,438 @@ from amuse.datamodel.indexing import * from amuse.datamodel import indexing + class TestIndexing(amusetest.TestCase): def test1(self): self.assertEqual(2, number_of_dimensions_after_index(3, 1)) self.assertEqual(3, number_of_dimensions_after_index(3, numpy.s_[0:3])) - self.assertEqual(1, number_of_dimensions_after_index(3, combine_indices(3,2))) - self.assertEqual(0, number_of_dimensions_after_index(3, combine_indices(combine_indices(3,2),1))) - self.assertEqual(3, indexing.number_of_dimensions_after_index(3, numpy.s_[1:2,...,...])) - self.assertEqual(3, indexing.number_of_dimensions_after_index(3, numpy.s_[1:2,:,:])) - + self.assertEqual(1, number_of_dimensions_after_index(3, combine_indices(3, 2))) + self.assertEqual(0, number_of_dimensions_after_index(3, combine_indices(combine_indices(3, 2), 1))) + self.assertEqual(3, indexing.number_of_dimensions_after_index(3, numpy.s_[1:2, ..., ...])) + self.assertEqual(3, indexing.number_of_dimensions_after_index(3, numpy.s_[1:2, :, :])) + def test2(self): - a = numpy.arange(12).reshape(3,4) - self.assertEqual(a[combine_indices(0,1)], a[0][1]) - self.assertEqual(a[combine_indices(1,0)], a[1][0]) - self.assertTrue(numpy.all(a[combine_indices(1,numpy.s_[0:2])] == a[1][0:2])) - indirect = combine_indices(0,1) + a = numpy.arange(12).reshape(3, 4) + self.assertEqual(a[combine_indices(0, 1)], a[0][1]) + self.assertEqual(a[combine_indices(1, 0)], a[1][0]) + self.assertTrue(numpy.all(a[combine_indices(1, numpy.s_[0:2])] == a[1][0:2])) + indirect = combine_indices(0, 1) self.assertEqual(number_of_dimensions(a, indirect), 0) - - + def test3(self): - a = numpy.arange(12).reshape(3,4) - self.assertTrue(a[combine_indices(numpy.s_[0:2],0)].shape, a[0:2][0].shape) - self.assertTrue(numpy.all(a[combine_indices(numpy.s_[0:2],0)] == a[0:2][0])) + a = numpy.arange(12).reshape(3, 4) + self.assertTrue(a[combine_indices(numpy.s_[0:2], 0)].shape, a[0:2][0].shape) + self.assertTrue(numpy.all(a[combine_indices(numpy.s_[0:2], 0)] == a[0:2][0])) def test4(self): - a = numpy.arange(12).reshape(3,4) - direct = a[1][:] - indirect = a[combine_indices(1, indexing.normalize_slices(a[1].shape,numpy.s_[:]))] + a = numpy.arange(12).reshape(3, 4) + direct = a[1][:] + indirect = a[combine_indices(1, indexing.normalize_slices(a[1].shape, numpy.s_[:]))] self.assertEqual(indirect.shape, direct.shape) - self.assertTrue(numpy.all(indirect == direct)) - + self.assertTrue(numpy.all(indirect == direct)) + def test5(self): - a = numpy.arange(12).reshape(3,4) - direct = a[0:2][:] - indirect = a[combine_indices(numpy.s_[0:2],indexing.normalize_slices(a[0:2].shape,numpy.s_[:]))] + a = numpy.arange(12).reshape(3, 4) + direct = a[0:2][:] + indirect = a[combine_indices(numpy.s_[0:2], indexing.normalize_slices(a[0:2].shape, numpy.s_[:]))] self.assertEqual(indirect.shape, direct.shape) - self.assertTrue(numpy.all(indirect == direct)) + self.assertTrue(numpy.all(indirect == direct)) def test6(self): - a = numpy.arange(12).reshape(3,4) - direct = a[1:3][1:] - indirect = a[combine_indices(numpy.s_[1:3],indexing.normalize_slices(a[1:3].shape,numpy.s_[1:]))] + a = numpy.arange(12).reshape(3, 4) + direct = a[1:3][1:] + indirect = a[combine_indices(numpy.s_[1:3], indexing.normalize_slices(a[1:3].shape, numpy.s_[1:]))] self.assertEqual(indirect.shape, direct.shape) - self.assertTrue(numpy.all(indirect == direct)) + self.assertTrue(numpy.all(indirect == direct)) def test7(self): - a = numpy.arange(30).reshape(6,5) - direct = a[1:5:2][1:] - indirect = a[combine_indices(numpy.s_[1:5:2],indexing.normalize_slices(a[1:5:2].shape,numpy.s_[1:]))] + a = numpy.arange(30).reshape(6, 5) + direct = a[1:5:2][1:] + indirect = a[combine_indices(numpy.s_[1:5:2], indexing.normalize_slices(a[1:5:2].shape, numpy.s_[1:]))] self.assertEqual(indirect.shape, direct.shape) - self.assertTrue(numpy.all(indirect == direct)) - + self.assertTrue(numpy.all(indirect == direct)) + def test8(self): a = numpy.arange(30) - direct = a[2:14:3][1:5:2] - indirect = a[combine_indices(numpy.s_[2:14:3],numpy.s_[1:5:2])] + direct = a[2:14:3][1:5:2] + indirect = a[combine_indices(numpy.s_[2:14:3], numpy.s_[1:5:2])] self.assertEqual(indirect.shape, direct.shape) - self.assertTrue(numpy.all(indirect == direct)) - - + self.assertTrue(numpy.all(indirect == direct)) + def test9(self): a = numpy.arange(100) - for s in range(0,40): - for e in range(40,101): - for step in range(1,5): - direct = a[s:e:step][1:5:2] - indirect = a[combine_indices(numpy.s_[s:e:step], - indexing.normalize_slices(a[s:e:step].shape,numpy.s_[1:5:2]))] + for s in range(0, 40): + for e in range(40, 101): + for step in range(1, 5): + direct = a[s:e:step][1:5:2] + indirect = a[combine_indices(numpy.s_[s:e:step], + indexing.normalize_slices(a[s:e:step].shape, numpy.s_[1:5:2]))] self.assertEqual(indirect.shape, direct.shape) - self.assertTrue(numpy.all(indirect == direct)) - + self.assertTrue(numpy.all(indirect == direct)) + def test10(self): - a = numpy.arange(60).reshape(5,6,2) - direct = a[3][2][1] - indirect = a[combine_indices(combine_indices(3,2),1)] + a = numpy.arange(60).reshape(5, 6, 2) + direct = a[3][2][1] + indirect = a[combine_indices(combine_indices(3, 2), 1)] self.assertEqual(indirect, direct) - + def test11(self): - a = numpy.arange(60).reshape(5,6,2) - direct = a[3] - indirect = a[combine_indices(3,Ellipsis)] + a = numpy.arange(60).reshape(5, 6, 2) + direct = a[3] + indirect = a[combine_indices(3, Ellipsis)] self.assertEqual(indirect.shape, direct.shape) - self.assertTrue(numpy.all(indirect == direct)) - + self.assertTrue(numpy.all(indirect == direct)) + def test12(self): - self.assertEqual((1,4,2), indexing.shape_after_index((5,4,2), numpy.s_[1:2,...,...])) - self.assertEqual((1,4,2), indexing.shape_after_index((5,4,2), numpy.s_[1:2,:,:])) - self.assertEqual((2,4,2), indexing.shape_after_index((5,4,2), numpy.s_[1:3,...,...])) - self.assertEqual((2,4,2), indexing.shape_after_index((5,4,2), numpy.s_[1:3,:,:])) - self.assertEqual((2,1,2), indexing.shape_after_index((5,4,2), numpy.s_[1:3,2:3,...])) - self.assertEqual((2,1,2), indexing.shape_after_index((5,4,2), numpy.s_[1:3,2:3,:])) - - + self.assertEqual((1, 4, 2), indexing.shape_after_index((5, 4, 2), numpy.s_[1:2, ..., ...])) + self.assertEqual((1, 4, 2), indexing.shape_after_index((5, 4, 2), numpy.s_[1:2, :, :])) + self.assertEqual((2, 4, 2), indexing.shape_after_index((5, 4, 2), numpy.s_[1:3, ..., ...])) + self.assertEqual((2, 4, 2), indexing.shape_after_index((5, 4, 2), numpy.s_[1:3, :, :])) + self.assertEqual((2, 1, 2), indexing.shape_after_index((5, 4, 2), numpy.s_[1:3, 2:3, ...])) + self.assertEqual((2, 1, 2), indexing.shape_after_index((5, 4, 2), numpy.s_[1:3, 2:3, :])) + def xtest13(self): - combined_indices = combine_indices(numpy.s_[1:3],numpy.s_[:]) + combined_indices = combine_indices(numpy.s_[1:3], numpy.s_[:]) self.assertEqual(combined_indices, numpy.s_[1:3:1]) combined_indices = combine_indices(numpy.s_[:], numpy.s_[1:3]) self.assertEqual(combined_indices, numpy.s_[1:3:1]) combined_indices = combine_indices((numpy.s_[:], numpy.s_[:]), (numpy.s_[1:3], numpy.s_[1:2])) - self.assertEqual(combined_indices,(numpy.s_[1:3:1], numpy.s_[1:2:1])) - + self.assertEqual(combined_indices, (numpy.s_[1:3:1], numpy.s_[1:2:1])) + combined_indices = combine_indices((numpy.s_[0:2], numpy.s_[:]), (numpy.s_[1:3], numpy.s_[1:2])) - self.assertEqual(combined_indices,(numpy.s_[1:2:1], numpy.s_[1:2:1])) - - + self.assertEqual(combined_indices, (numpy.s_[1:2:1], numpy.s_[1:2:1])) + def test14(self): - self.assertEqual((5,4,2), indexing.shape_after_index((5,4,2), numpy.s_[:10,...,...])) - self.assertEqual((5,4,2), indexing.shape_after_index((5,4,2), numpy.s_[...,:10,...])) - self.assertEqual((4,4,2), indexing.shape_after_index((5,4,2), numpy.s_[1:10,...,...])) - self.assertEqual((1,4,2), indexing.shape_after_index((5,4,2), numpy.s_[-1:,...,...])) - self.assertEqual((2,4,2), indexing.shape_after_index((5,4,2), numpy.s_[-2:,...,...])) - self.assertEqual((1,4,2), indexing.shape_after_index((5,4,2), numpy.s_[-2:-1,...,...])) - self.assertEqual((5,4,2), indexing.shape_after_index((5,4,2), numpy.s_[-10:,...,...])) - - - + self.assertEqual((5, 4, 2), indexing.shape_after_index((5, 4, 2), numpy.s_[:10, ..., ...])) + self.assertEqual((5, 4, 2), indexing.shape_after_index((5, 4, 2), numpy.s_[..., :10, ...])) + self.assertEqual((4, 4, 2), indexing.shape_after_index((5, 4, 2), numpy.s_[1:10, ..., ...])) + self.assertEqual((1, 4, 2), indexing.shape_after_index((5, 4, 2), numpy.s_[-1:, ..., ...])) + self.assertEqual((2, 4, 2), indexing.shape_after_index((5, 4, 2), numpy.s_[-2:, ..., ...])) + self.assertEqual((1, 4, 2), indexing.shape_after_index((5, 4, 2), numpy.s_[-2:-1, ..., ...])) + self.assertEqual((5, 4, 2), indexing.shape_after_index((5, 4, 2), numpy.s_[-10:, ..., ...])) + def test15(self): - a = numpy.arange(6).reshape(2,3) - indices = numpy.asarray([[True, False, True],[True,False,True]]) - direct = a[indices][list([1,3])] - combined = combine_indices(indices,[1,3]) + a = numpy.arange(6).reshape(2, 3) + indices = numpy.asarray([[True, False, True], [True, False, True]]) + direct = a[indices][list([1, 3])] + combined = combine_indices(indices, [1, 3]) indirect = a[combined] self.assertEqual(indirect, direct) - - + def test16(self): - self.assertEqual((4,), indexing.shape_after_index((2,3), [[True, False, True],[True,False,True]])) - self.assertEqual((1,3), indexing.shape_after_index((2,3), [True, False])) - + self.assertEqual((4,), indexing.shape_after_index((2, 3), [[True, False, True], [True, False, True]])) + self.assertEqual((1, 3), indexing.shape_after_index((2, 3), [True, False])) + def test17(self): - a = numpy.arange(6).reshape(2,3) - indices = numpy.asarray([True,False]) - direct = a[indices, 1:][0,1:] - combined = combine_indices(indexing.normalize_slices(a.shape,numpy.s_[indices,1:]), - indexing.normalize_slices(a[indices,1:].shape,numpy.s_[0,1:])) + a = numpy.arange(6).reshape(2, 3) + indices = numpy.asarray([True, False]) + direct = a[indices, 1:][0, 1:] + combined = combine_indices(indexing.normalize_slices(a.shape, numpy.s_[indices, 1:]), + indexing.normalize_slices(a[indices, 1:].shape, numpy.s_[0, 1:])) indirect = a[combined] self.assertEqual(indirect, direct) - + def test18(self): - a = numpy.arange(6).reshape(2,3) - indices = numpy.asarray([True,False]) - direct = a[indices, 1:][0] - combined = combine_indices(numpy.s_[indices,1:],0) + a = numpy.arange(6).reshape(2, 3) + indices = numpy.asarray([True, False]) + direct = a[indices, 1:][0] + combined = combine_indices(numpy.s_[indices, 1:], 0) indirect = a[combined] self.assertEqual(indirect, direct) - + def test19(self): - a = numpy.arange(6).reshape(2,3) - indices = numpy.asarray([True,False]) - direct = a[:1, 1:][0] - combined = combine_indices(numpy.s_[:1,1:],0) + a = numpy.arange(6).reshape(2, 3) + indices = numpy.asarray([True, False]) + direct = a[:1, 1:][0] + combined = combine_indices(numpy.s_[:1, 1:], 0) indirect = a[combined] self.assertEqual(indirect, direct) def test20(self): - combined=combine_indices( slice(1, 199, None), slice(3, 5, None) ) - self.assertEqual(combined,slice(4,6,1)) - + combined = combine_indices(slice(1, 199, None), slice(3, 5, None)) + self.assertEqual(combined, slice(4, 6, 1)) + def test21(self): - shape=shape_after_index((200,), slice(4, 6, 1)) - self.assertEqual(shape,(2,)) + shape = shape_after_index((200,), slice(4, 6, 1)) + self.assertEqual(shape, (2,)) def xtest22(self): - tiny=list(range(2)) - small=list(range(10)) - big=list(range(1000)) - + tiny = list(range(2)) + small = list(range(10)) + big = list(range(1000)) + # combining slicings w negative stops not possible! e.g. ((7,-1),(2,3),(9,10,1)) # (without normalize) - slicings=[ ((9,19),(5,9,2),(14,18,2)), - ((7,19,2),(5,9,1),(17,19,2)), - ((1,None),(1,10),(2,11,1)), - ((7,None),(1,10),(8,17,1)), - ((None,12),(3,5),(3,5,1)), - ((None,12),(3,15),(3,12,1)), - ((None,None),(3,5),(3,5,1)), - ((None,None),(3,15),(3,15,1)), - ((None,None),(None,15),(0,15,1)), - ((None,None),(None,None),(0,None,1)), - ((9,None),(None,None),(9,None,1)), - ((9,None),(6,None),(15,None,1)), - ((9,None),(None,40),(9,49,1)), - ((1,None),(None,40),(1,41,1)), - ((9,16),(None,40),(9,16,1)), - ((1,16),(None,40),(1,16,1)), - ((49,16),(None,40),(16,16,1)), - ((41,66),(None,40),(41,66,1)), + slicings = [((9, 19), (5, 9, 2), (14, 18, 2)), + ((7, 19, 2), (5, 9, 1), (17, 19, 2)), + ((1, None), (1, 10), (2, 11, 1)), + ((7, None), (1, 10), (8, 17, 1)), + ((None, 12), (3, 5), (3, 5, 1)), + ((None, 12), (3, 15), (3, 12, 1)), + ((None, None), (3, 5), (3, 5, 1)), + ((None, None), (3, 15), (3, 15, 1)), + ((None, None), (None, 15), (0, 15, 1)), + ((None, None), (None, None), (0, None, 1)), + ((9, None), (None, None), (9, None, 1)), + ((9, None), (6, None), (15, None, 1)), + ((9, None), (None, 40), (9, 49, 1)), + ((1, None), (None, 40), (1, 41, 1)), + ((9, 16), (None, 40), (9, 16, 1)), + ((1, 16), (None, 40), (1, 16, 1)), + ((49, 16), (None, 40), (16, 16, 1)), + ((41, 66), (None, 40), (41, 66, 1)), ] - - for t1,t2,t3 in slicings: - s1=slice(*t1) - s2=slice(*t2) - s3=slice(*t3) - self.assertEqual(combine_slices(s1,s2),t3) - self.assertTrue(tiny[s1][s2]==tiny[s3]) - self.assertTrue(small[s1][s2]==small[s3]) - self.assertTrue(big[s1][s2]==big[s3]) - + + for t1, t2, t3 in slicings: + s1 = slice(*t1) + s2 = slice(*t2) + s3 = slice(*t3) + self.assertEqual(combine_slices(s1, s2), t3) + self.assertTrue(tiny[s1][s2] == tiny[s3]) + self.assertTrue(small[s1][s2] == small[s3]) + self.assertTrue(big[s1][s2] == big[s3]) + def xtest23(self): import random random.seed(123456) - tiny=list(range(2)) - small=list(range(20)) - big=list(range(2000)) - - Ntest=1000 - start0=[random.randint(0,20) for x in range(Ntest)] - stop0=[random.randint(15,50) for x in range(Ntest)] - step0=[random.randint(1,3) for x in range(Ntest)] - start1=[random.randint(0,10) for x in range(Ntest)] - stop1=[random.randint(5,25) for x in range(Ntest)] - step1=[random.randint(1,3) for x in range(Ntest)] - - slicings=[] - for x in zip(start0,stop0,step0,start1,stop1,step1): - slicings.append(((x[0],x[1],x[2]),(x[3],x[4],x[5]))) - - for t1,t2 in slicings: - s1=slice(*t1) - s2=slice(*t2) - t3=combine_slices(s1,s2) - s3=slice(*t3) - self.assertTrue(tiny[s1][s2]==tiny[s3]) - self.assertTrue(small[s1][s2]==small[s3]) - self.assertTrue(big[s1][s2]==big[s3]) + tiny = list(range(2)) + small = list(range(20)) + big = list(range(2000)) + + Ntest = 1000 + start0 = [random.randint(0, 20) for x in range(Ntest)] + stop0 = [random.randint(15, 50) for x in range(Ntest)] + step0 = [random.randint(1, 3) for x in range(Ntest)] + start1 = [random.randint(0, 10) for x in range(Ntest)] + stop1 = [random.randint(5, 25) for x in range(Ntest)] + step1 = [random.randint(1, 3) for x in range(Ntest)] + + slicings = [] + for x in zip(start0, stop0, step0, start1, stop1, step1): + slicings.append(((x[0], x[1], x[2]), (x[3], x[4], x[5]))) + + for t1, t2 in slicings: + s1 = slice(*t1) + s2 = slice(*t2) + t3 = combine_slices(s1, s2) + s3 = slice(*t3) + self.assertTrue(tiny[s1][s2] == tiny[s3]) + self.assertTrue(small[s1][s2] == small[s3]) + self.assertTrue(big[s1][s2] == big[s3]) def test24(self): import random random.seed(123456) - tiny=list(range(2)) - small=list(range(20)) - big=list(range(2000)) - - Ntest=1000 - stop0=[random.randint(0,20) for x in range(Ntest)] - start0=[random.randint(15,50) for x in range(Ntest)] - step0=[random.randint(-3,-1) for x in range(Ntest)] - start1=[random.randint(0,10) for x in range(Ntest)] - stop1=[random.randint(5,25) for x in range(Ntest)] - step1=[random.randint(1,3) for x in range(Ntest)] - - slicings=[] - for x in zip(start0,stop0,step0,start1,stop1,step1): - slicings.append(((x[0],x[1],x[2]),(x[3],x[4],x[5]))) - - for t1,t2 in slicings: - s1=slice(*t1) - s2=slice(*t2) - - t3=combine_slices(normalize_slices(len(tiny),s1),normalize_slices(len(tiny[s1]),s2)) - s3=slice(*t3) - self.assertTrue(tiny[s1][s2]==tiny[s3]) - - t3=combine_slices(normalize_slices(len(small),s1),normalize_slices(len(small[s1]),s2)) - s3=slice(*t3) - self.assertTrue(small[s1][s2]==small[s3]) - t3=combine_slices(normalize_slices(len(big),s1),normalize_slices(len(big[s1]),s2)) - s3=slice(*t3) - self.assertTrue(big[s1][s2]==big[s3]) + tiny = list(range(2)) + small = list(range(20)) + big = list(range(2000)) + + Ntest = 1000 + stop0 = [random.randint(0, 20) for x in range(Ntest)] + start0 = [random.randint(15, 50) for x in range(Ntest)] + step0 = [random.randint(-3, -1) for x in range(Ntest)] + start1 = [random.randint(0, 10) for x in range(Ntest)] + stop1 = [random.randint(5, 25) for x in range(Ntest)] + step1 = [random.randint(1, 3) for x in range(Ntest)] + + slicings = [] + for x in zip(start0, stop0, step0, start1, stop1, step1): + slicings.append(((x[0], x[1], x[2]), (x[3], x[4], x[5]))) + + for t1, t2 in slicings: + s1 = slice(*t1) + s2 = slice(*t2) + + t3 = combine_slices(normalize_slices(len(tiny), s1), normalize_slices(len(tiny[s1]), s2)) + s3 = slice(*t3) + self.assertTrue(tiny[s1][s2] == tiny[s3]) + + t3 = combine_slices(normalize_slices(len(small), s1), normalize_slices(len(small[s1]), s2)) + s3 = slice(*t3) + self.assertTrue(small[s1][s2] == small[s3]) + t3 = combine_slices(normalize_slices(len(big), s1), normalize_slices(len(big[s1]), s2)) + s3 = slice(*t3) + self.assertTrue(big[s1][s2] == big[s3]) def test25(self): import random random.seed(123456) - tiny=list(range(2)) - small=list(range(20)) - big=list(range(2000)) - - Ntest=1000 - stop0=[random.randint(0,20) for x in range(Ntest)] - start0=[random.randint(15,50) for x in range(Ntest)] - step0=[random.randint(-3,-1) for x in range(Ntest)] - stop1=[random.randint(0,10) for x in range(Ntest)] - start1=[random.randint(5,25) for x in range(Ntest)] - step1=[random.randint(-3,-1) for x in range(Ntest)] - - slicings=[] - for x in zip(start0,stop0,step0,start1,stop1,step1): - slicings.append(((x[0],x[1],x[2]),(x[3],x[4],x[5]))) - - for t1,t2 in slicings: - s1=slice(*t1) - s2=slice(*t2) - - t3=combine_slices(normalize_slices(len(tiny),s1),normalize_slices(len(tiny[s1]),s2)) - s3=slice(*t3) - #~ print(s1,s2,s3) - self.assertTrue(tiny[s1][s2]==tiny[s3]) - - t3=combine_slices(normalize_slices(len(small),s1),normalize_slices(len(small[s1]),s2)) - s3=slice(*t3) - self.assertTrue(small[s1][s2]==small[s3]) - t3=combine_slices(normalize_slices(len(big),s1),normalize_slices(len(big[s1]),s2)) - s3=slice(*t3) - self.assertTrue(big[s1][s2]==big[s3]) + tiny = list(range(2)) + small = list(range(20)) + big = list(range(2000)) + + Ntest = 1000 + stop0 = [random.randint(0, 20) for x in range(Ntest)] + start0 = [random.randint(15, 50) for x in range(Ntest)] + step0 = [random.randint(-3, -1) for x in range(Ntest)] + stop1 = [random.randint(0, 10) for x in range(Ntest)] + start1 = [random.randint(5, 25) for x in range(Ntest)] + step1 = [random.randint(-3, -1) for x in range(Ntest)] + + slicings = [] + for x in zip(start0, stop0, step0, start1, stop1, step1): + slicings.append(((x[0], x[1], x[2]), (x[3], x[4], x[5]))) + + for t1, t2 in slicings: + s1 = slice(*t1) + s2 = slice(*t2) + + t3 = combine_slices(normalize_slices(len(tiny), s1), normalize_slices(len(tiny[s1]), s2)) + s3 = slice(*t3) + # ~ print(s1,s2,s3) + self.assertTrue(tiny[s1][s2] == tiny[s3]) + + t3 = combine_slices(normalize_slices(len(small), s1), normalize_slices(len(small[s1]), s2)) + s3 = slice(*t3) + self.assertTrue(small[s1][s2] == small[s3]) + t3 = combine_slices(normalize_slices(len(big), s1), normalize_slices(len(big[s1]), s2)) + s3 = slice(*t3) + self.assertTrue(big[s1][s2] == big[s3]) def test26(self): - oned=numpy.zeros(5) - threed=numpy.zeros((4,5,6)) - for index in [0,[1],[1,2],[[1,2],[2,3]],[[2]],[[0,1]]]: - i=numpy.array(index) - self.assertEqual(len(oned[i].shape), number_of_dimensions_after_index(1, i )) - for index in [0,[1],[1,2],[[1,2],[2,3]],[[2]],[[2,1]]]: - i=numpy.array(index) - self.assertEqual(len(threed[i].shape), number_of_dimensions_after_index(3, i )) + oned = numpy.zeros(5) + threed = numpy.zeros((4, 5, 6)) + for index in [0, [1], [1, 2], [[1, 2], [2, 3]], [[2]], [[0, 1]]]: + i = numpy.array(index) + self.assertEqual(len(oned[i].shape), number_of_dimensions_after_index(1, i)) + for index in [0, [1], [1, 2], [[1, 2], [2, 3]], [[2]], [[2, 1]]]: + i = numpy.array(index) + self.assertEqual(len(threed[i].shape), number_of_dimensions_after_index(3, i)) def test27(self): - oned=numpy.zeros(5) - threed=numpy.zeros((4,5,6)) - for index in [0,[1],[1,2],[[1,2],[2,3]],[[2]],[[0,1]]]: - i=numpy.array(index) - self.assertEqual(oned[i].shape, shape_after_index(oned.shape, i )) - for index in [0,[1],[1,2],[[1,2],[2,3]],[[2]],[[2,1]],[[[[0],[1],[1]]]]]: - i=numpy.array(index) - self.assertEqual(threed[i].shape, shape_after_index(threed.shape, i )) + oned = numpy.zeros(5) + threed = numpy.zeros((4, 5, 6)) + for index in [0, [1], [1, 2], [[1, 2], [2, 3]], [[2]], [[0, 1]]]: + i = numpy.array(index) + self.assertEqual(oned[i].shape, shape_after_index(oned.shape, i)) + for index in [0, [1], [1, 2], [[1, 2], [2, 3]], [[2]], [[2, 1]], [[[[0], [1], [1]]]]]: + i = numpy.array(index) + self.assertEqual(threed[i].shape, shape_after_index(threed.shape, i)) def test28(self): - twod=numpy.zeros((5,6)) - threed=numpy.zeros((4,5,6)) - for _i,_j in [([0],[1]),([0,2],[1,3]),([0,2],[1,3]),([[0,1],[1,2]],[[2,3],[3,4]])]: - i=numpy.array(_i) - j=numpy.array(_j) - self.assertEqual(len(twod[i,j].shape), number_of_dimensions_after_index(2, (i,j) )) - for _i,_j in [([0],[1]),([0,2],[1,3]),([0,2],[1,3]),([[0,1],[1,2]],[[2,3],[3,4]])]: - i=numpy.array(_i) - j=numpy.array(_j) - self.assertEqual(len(threed[i,j].shape), number_of_dimensions_after_index(3, (i,j) )) + twod = numpy.zeros((5, 6)) + threed = numpy.zeros((4, 5, 6)) + for _i, _j in [([0], [1]), ([0, 2], [1, 3]), ([0, 2], [1, 3]), ([[0, 1], [1, 2]], [[2, 3], [3, 4]])]: + i = numpy.array(_i) + j = numpy.array(_j) + self.assertEqual(len(twod[i, j].shape), number_of_dimensions_after_index(2, (i, j))) + for _i, _j in [([0], [1]), ([0, 2], [1, 3]), ([0, 2], [1, 3]), ([[0, 1], [1, 2]], [[2, 3], [3, 4]])]: + i = numpy.array(_i) + j = numpy.array(_j) + self.assertEqual(len(threed[i, j].shape), number_of_dimensions_after_index(3, (i, j))) def test29(self): - twod=numpy.zeros((5,6)) - for _i,_j in [([0],[1]),([0,2],[1,3]),([0,2],[1,3]),([[0,1],[1,2]],[[2,3],[3,4]])]: - i=numpy.array(_i) - j=numpy.array(_j) - self.assertEqual(twod[i,j].shape, shape_after_index(twod.shape, (i,j) )) - - threed=numpy.zeros((4,5,6)) - for _i,_j in [([0],[1]),([0,2],[1,3]),([0,2],[1,3]),([[0,1],[1,2]],[[2,3],[3,4]])]: - i=numpy.array(_i) - j=numpy.array(_j) - self.assertEqual(threed[i,j].shape, shape_after_index(threed.shape, (i,j) )) - - fourd=numpy.zeros((4,5,6,7)) - for _i,_j in [([0],[1]),([0,2],[1,3])]: - i=numpy.array(_i) - j=numpy.array(_j) - self.assertEqual(fourd[i,j].shape, shape_after_index(fourd.shape, (i,j) )) - for _i,_j in [([0,2],[1,3])]: - i=numpy.array(_i) - j=numpy.array(_j) - self.assertEqual(fourd[i,Ellipsis,j].shape, shape_after_index(fourd.shape, (i,Ellipsis,j) )) - for _i,_j in [([0,2],[1,3])]: - i=numpy.array(_i) - j=numpy.array(_j) - self.assertEqual(fourd[i,slice(None),j].shape, shape_after_index(fourd.shape, (i,slice(None),j) )) - - - + twod = numpy.zeros((5, 6)) + for _i, _j in [([0], [1]), ([0, 2], [1, 3]), ([0, 2], [1, 3]), ([[0, 1], [1, 2]], [[2, 3], [3, 4]])]: + i = numpy.array(_i) + j = numpy.array(_j) + self.assertEqual(twod[i, j].shape, shape_after_index(twod.shape, (i, j))) + + threed = numpy.zeros((4, 5, 6)) + for _i, _j in [([0], [1]), ([0, 2], [1, 3]), ([0, 2], [1, 3]), ([[0, 1], [1, 2]], [[2, 3], [3, 4]])]: + i = numpy.array(_i) + j = numpy.array(_j) + self.assertEqual(threed[i, j].shape, shape_after_index(threed.shape, (i, j))) + + fourd = numpy.zeros((4, 5, 6, 7)) + for _i, _j in [([0], [1]), ([0, 2], [1, 3])]: + i = numpy.array(_i) + j = numpy.array(_j) + self.assertEqual(fourd[i, j].shape, shape_after_index(fourd.shape, (i, j))) + for _i, _j in [([0, 2], [1, 3])]: + i = numpy.array(_i) + j = numpy.array(_j) + self.assertEqual(fourd[i, Ellipsis, j].shape, shape_after_index(fourd.shape, (i, Ellipsis, j))) + for _i, _j in [([0, 2], [1, 3])]: + i = numpy.array(_i) + j = numpy.array(_j) + self.assertEqual(fourd[i, slice(None), j].shape, shape_after_index(fourd.shape, (i, slice(None), j))) + + class TestSplitOverDimensions(amusetest.TestCase): - + def test1(self): dimension_values = [ - [3,4,5,6], - ['a','b','c'] + [3, 4, 5, 6], + ['a', 'b', 'c'] ] split_dimension_values = indexing.split_numpy_index_over_dimensions(0, dimension_values) - self.assertEqual(len(split_dimension_values) ,2) + self.assertEqual(len(split_dimension_values), 2) self.assertEqual(split_dimension_values[0], 3) - self.assertEqual(split_dimension_values[1], ['a','b','c']) - + self.assertEqual(split_dimension_values[1], ['a', 'b', 'c']) + def test2(self): dimension_values = [ - [3,4,5,6], - ['a','b','c'] + [3, 4, 5, 6], + ['a', 'b', 'c'] ] - split_dimension_values = indexing.split_numpy_index_over_dimensions((1,2), dimension_values) - self.assertEqual(len(split_dimension_values) ,2) + split_dimension_values = indexing.split_numpy_index_over_dimensions((1, 2), dimension_values) + self.assertEqual(len(split_dimension_values), 2) self.assertEqual(split_dimension_values[0], 4) self.assertEqual(split_dimension_values[1], 'c') - + def test3(self): dimension_values = [ - [3,4,5,6], - ['a','b','c'] + [3, 4, 5, 6], + ['a', 'b', 'c'] ] - split_dimension_values = indexing.split_numpy_index_over_dimensions(slice(0,2), dimension_values) - self.assertEqual(len(split_dimension_values) ,2) - self.assertEqual(split_dimension_values[0], [3,4]) - self.assertEqual(split_dimension_values[1], ['a','b','c']) - + split_dimension_values = indexing.split_numpy_index_over_dimensions(slice(0, 2), dimension_values) + self.assertEqual(len(split_dimension_values), 2) + self.assertEqual(split_dimension_values[0], [3, 4]) + self.assertEqual(split_dimension_values[1], ['a', 'b', 'c']) + def test4(self): dimension_values = [ [0, 1, 2, 3, 4, 5, 6, 7, 8, ] ] - split_dimension_values = indexing.split_numpy_index_over_dimensions(slice(1,7,2), dimension_values) - self.assertEqual(len(split_dimension_values) ,1) + split_dimension_values = indexing.split_numpy_index_over_dimensions(slice(1, 7, 2), dimension_values) + self.assertEqual(len(split_dimension_values), 1) self.assertEqual(split_dimension_values[0], [1, 3, 5]) - - + def test5(self): dimension_values = [ - [0, 1, 2, 3, 4, 5, 6, 7, 8,9 ] + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ] - split_dimension_values = indexing.split_numpy_index_over_dimensions(slice(-2,10), dimension_values) + split_dimension_values = indexing.split_numpy_index_over_dimensions(slice(-2, 10), dimension_values) self.assertEqual(split_dimension_values[0], [8, 9]) - split_dimension_values = indexing.split_numpy_index_over_dimensions(slice(-3,3,-1), dimension_values) + split_dimension_values = indexing.split_numpy_index_over_dimensions(slice(-3, 3, -1), dimension_values) self.assertEqual(split_dimension_values[0], [7, 6, 5, 4]) - - + def test6(self): dimension_values = [ - [0, 1, 2, 3, 4, 5, 6, 7, 8,9 ] + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ] - split_dimension_values = indexing.split_numpy_index_over_dimensions(slice(5,None), dimension_values) + split_dimension_values = indexing.split_numpy_index_over_dimensions(slice(5, None), dimension_values) self.assertEqual(split_dimension_values[0], [5, 6, 7, 8, 9]) - - + def test7(self): dimension_values = [ [0, 1], [0, 1, 2], [0] ] - split_dimension_values = indexing.split_numpy_index_over_dimensions(slice(1,2), dimension_values) + split_dimension_values = indexing.split_numpy_index_over_dimensions(slice(1, 2), dimension_values) self.assertEqual(split_dimension_values[0], [1]) - self.assertEqual(split_dimension_values[1], [0,1,2]) + self.assertEqual(split_dimension_values[1], [0, 1, 2]) self.assertEqual(split_dimension_values[2], [0]) - - + def test8(self): dimension_values = [ [0, 1], [0, 1, 2], [0] ] - split_dimension_values = indexing.split_numpy_index_over_dimensions((Ellipsis,0), dimension_values) - self.assertEqual(split_dimension_values[0], [0,1]) - self.assertEqual(split_dimension_values[1], [0,1,2]) + split_dimension_values = indexing.split_numpy_index_over_dimensions((Ellipsis, 0), dimension_values) + self.assertEqual(split_dimension_values[0], [0, 1]) + self.assertEqual(split_dimension_values[1], [0, 1, 2]) self.assertEqual(split_dimension_values[2], 0) - - split_dimension_values = indexing.split_numpy_index_over_dimensions((slice(None),slice(None),0), dimension_values) - self.assertEqual(split_dimension_values[0], [0,1]) - self.assertEqual(split_dimension_values[1], [0,1,2]) + + split_dimension_values = indexing.split_numpy_index_over_dimensions((slice(None), slice(None), 0), dimension_values) + self.assertEqual(split_dimension_values[0], [0, 1]) + self.assertEqual(split_dimension_values[1], [0, 1, 2]) self.assertEqual(split_dimension_values[2], 0) - - split_dimension_values = indexing.split_numpy_index_over_dimensions((Ellipsis,0, Ellipsis), dimension_values) - self.assertEqual(split_dimension_values[0], [0,1]) + + split_dimension_values = indexing.split_numpy_index_over_dimensions((Ellipsis, 0, Ellipsis), dimension_values) + self.assertEqual(split_dimension_values[0], [0, 1]) self.assertEqual(split_dimension_values[1], 0) self.assertEqual(split_dimension_values[2], [0]) diff --git a/src/amuse/test/suite/core_tests/test_inmemorystorage.py b/src/amuse/test/suite/core_tests/test_inmemorystorage.py index 2ab36f45f4..3eff58a3c6 100644 --- a/src/amuse/test/suite/core_tests/test_inmemorystorage.py +++ b/src/amuse/test/suite/core_tests/test_inmemorystorage.py @@ -5,131 +5,130 @@ from amuse.units import units from amuse.datamodel.memory_storage import InMemoryGridAttributeStorage from amuse.datamodel.memory_storage import InMemoryVectorQuantityAttribute - + + class TestInMemoryGridAttributeStorage(amusetest.TestCase): - + def test1(self): - x = InMemoryGridAttributeStorage(5,4,3) - i = (0,1,2,3,4) - j = (1,3,1,3,1) - k = (0,2,0,2,0) + x = InMemoryGridAttributeStorage(5, 4, 3) + i = (0, 1, 2, 3, 4) + j = (1, 3, 1, 3, 1) + k = (0, 2, 0, 2, 0) x.set_values_in_store( - (i,j,k), - ['a','b'], + (i, j, k), + ['a', 'b'], [2.0 | units.kg, 1.0 | units.m] ) - - b, a = x.get_values_in_store(None, ['b','a']) + + b, a = x.get_values_in_store(None, ['b', 'a']) print(b.shape, a.shape) self.assertEqual(b[0][1][0], 1.0 | units.m) self.assertEqual(b[0][0][0], 0.0 | units.m) self.assertEqual(a[0][1][0], 2.0 | units.kg) self.assertEqual(a[1][3][2], 2.0 | units.kg) self.assertEqual(a[1][2][2], 0.0 | units.kg) - + (b,) = x.get_values_in_store((numpy.s_[0:4], numpy.s_[1:4], numpy.s_[:]), ['a']) - + self.assertEqual(b[0][0][0], 2.0 | units.kg) self.assertEqual(b[0][0][2], 0.0 | units.kg) self.assertEqual(b[1][2][2], 2.0 | units.kg) self.assertEqual(b[2][0][0], 2.0 | units.kg) self.assertEqual(b[3][2][2], 2.0 | units.kg) - + self.assertEqual(b.sum(), 8.0 | units.kg) - + self.assertEqual(sorted(x.get_defined_attribute_names()), ["a", "b"]) - + def test2(self): - x = InMemoryGridAttributeStorage(5,4,3) - i = (0,1,2,3,4) - j = (1,3,1,3,1) - k = (0,2,0,2,0) + x = InMemoryGridAttributeStorage(5, 4, 3) + i = (0, 1, 2, 3, 4) + j = (1, 3, 1, 3, 1) + k = (0, 2, 0, 2, 0) x.set_values_in_store( - (i,j,k), - ['a','b'], - [2.0 , 1.0] + (i, j, k), + ['a', 'b'], + [2.0, 1.0] ) - - b, a = x.get_values_in_store(None, ['b','a']) + + b, a = x.get_values_in_store(None, ['b', 'a']) print(a) - self.assertEqual(b[0][1][0], 1.0 ) - self.assertEqual(b[0][0][0], 0.0 ) - self.assertEqual(a[0][1][0], 2.0 ) - self.assertEqual(a[1][3][2], 2.0 ) - self.assertEqual(a[1][2][2], 0.0 ) - + self.assertEqual(b[0][1][0], 1.0) + self.assertEqual(b[0][0][0], 0.0) + self.assertEqual(a[0][1][0], 2.0) + self.assertEqual(a[1][3][2], 2.0) + self.assertEqual(a[1][2][2], 0.0) + (b,) = x.get_values_in_store((numpy.s_[0:4], numpy.s_[1:4], numpy.s_[:]), ['a']) - - self.assertEqual(b[0][0][0], 2.0 ) - self.assertEqual(b[0][0][2], 0.0 ) - self.assertEqual(b[1][2][2], 2.0 ) - self.assertEqual(b[2][0][0], 2.0 ) - self.assertEqual(b[3][2][2], 2.0 ) - - self.assertEqual(b.sum(), 8.0 ) - + + self.assertEqual(b[0][0][0], 2.0) + self.assertEqual(b[0][0][2], 0.0) + self.assertEqual(b[1][2][2], 2.0) + self.assertEqual(b[2][0][0], 2.0) + self.assertEqual(b[3][2][2], 2.0) + + self.assertEqual(b.sum(), 8.0) + self.assertEqual(sorted(x.get_defined_attribute_names()), ["a", "b"]) - + y = x.copy() - + (b,) = y.get_values_in_store((numpy.s_[0:4], numpy.s_[1:4], numpy.s_[:]), ['a']) - - self.assertEqual(b[0][0][0], 2.0 ) - self.assertEqual(b[0][0][2], 0.0 ) - self.assertEqual(b[1][2][2], 2.0 ) - - + + self.assertEqual(b[0][0][0], 2.0) + self.assertEqual(b[0][0][2], 0.0) + self.assertEqual(b[1][2][2], 2.0) + def test3(self): - x = InMemoryGridAttributeStorage(5,4,3) - i = (0,1,2,3,4) - j = (1,3,1,3,1) - k = (0,2,0,2,0) + x = InMemoryGridAttributeStorage(5, 4, 3) + i = (0, 1, 2, 3, 4) + j = (1, 3, 1, 3, 1) + k = (0, 2, 0, 2, 0) x.set_values_in_store( - (i,j,k), - ['a','b'], + (i, j, k), + ['a', 'b'], [2.0 | units.kg, 1.0 | units.m] ) - - b, a = x.get_values_in_store((0,1,0), ['b','a']) + + b, a = x.get_values_in_store((0, 1, 0), ['b', 'a']) print(b, a) self.assertEqual(b, 1.0 | units.m) self.assertEqual(a, 2.0 | units.kg) - b, a = x.get_values_in_store((0,0,0), ['b','a']) + b, a = x.get_values_in_store((0, 0, 0), ['b', 'a']) print(b, a) self.assertEqual(b, 0.0 | units.m) self.assertEqual(a, 0.0 | units.kg) - - + + class TestInMemoryVectorQuantityAttribute(amusetest.TestCase): - + def test1(self): - quantity = units.m.new_quantity(numpy.array([1.0,2.0,3.0])) + quantity = units.m.new_quantity(numpy.array([1.0, 2.0, 3.0])) attribute = InMemoryVectorQuantityAttribute('test', quantity.shape, quantity.unit) attribute.set_values(None, quantity) - + self.assertEqual(attribute.get_length(), 3) - self.assertEqual(attribute.get_shape(), (3,) ) - self.assertEqual(attribute.get_values([1,2]), [2.0,3.0] | units.m) - + self.assertEqual(attribute.get_shape(), (3,)) + self.assertEqual(attribute.get_values([1, 2]), [2.0, 3.0] | units.m) + attribute.increase_to_length(5) - self.assertEqual(attribute.get_values(None), [1.0,2.0,3.0,0.0,0.0] | units.m) - + self.assertEqual(attribute.get_values(None), [1.0, 2.0, 3.0, 0.0, 0.0] | units.m) + def test2(self): - quantity = units.m.new_quantity(numpy.array([1.0,2.0,3.0])) + quantity = units.m.new_quantity(numpy.array([1.0, 2.0, 3.0])) attribute = InMemoryVectorQuantityAttribute('test', quantity.shape, quantity.unit) attribute.set_values(None, quantity) - attribute.set_values([1,2], [4.0,5.0] | units.m) - + attribute.set_values([1, 2], [4.0, 5.0] | units.m) + attribute.increase_to_length(5) - self.assertEqual(attribute.get_values(None), [1.0,4.0,5.0,0.0,0.0] | units.m) + self.assertEqual(attribute.get_values(None), [1.0, 4.0, 5.0, 0.0, 0.0] | units.m) def test3(self): - quantity = units.m.new_quantity(numpy.array([[1.0,2.0,3.0], [4.0,5.0,6.0]])) + quantity = units.m.new_quantity(numpy.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])) attribute = InMemoryVectorQuantityAttribute('test', quantity.shape, quantity.unit) attribute.set_values(None, quantity) - self.assertEqual( attribute.get_values([1]), [4.0,5.0,6.0] | units.m) - self.assertEqual( attribute.get_shape(), (2,3)) + self.assertEqual(attribute.get_values([1]), [4.0, 5.0, 6.0] | units.m) + self.assertEqual(attribute.get_shape(), (2, 3)) attribute.increase_to_length(4) - self.assertEqual( attribute.get_shape(), (4,3)) - self.assertEqual(attribute.get_values(None), [[1.0,2.0,3.0], [4.0,5.0,6.0], [0.0,0.0,0.0], [0.0,0.0,0.0]] | units.m) - + self.assertEqual(attribute.get_shape(), (4, 3)) + self.assertEqual(attribute.get_values(None), [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.m) diff --git a/src/amuse/test/suite/core_tests/test_interface.py b/src/amuse/test/suite/core_tests/test_interface.py index a67516fa01..31826be665 100644 --- a/src/amuse/test/suite/core_tests/test_interface.py +++ b/src/amuse/test/suite/core_tests/test_interface.py @@ -16,110 +16,108 @@ from amuse.rfi.core import legacy_function from amuse.rfi.core import LegacyFunctionSpecification + class CodeInterfaceWithConvertedUnitsTests(amusetest.TestCase): class TestClass(object): - + def get_mass(self): return 10.0, 0 - + def add_to_length(self, length): return length + 10.0 - + def return_an_errorcode(self, error): return error - + def test1(self): - convert_nbody = nbody_system.nbody_to_si(10.0 | units.kg, 5.0 | units.m ) - + convert_nbody = nbody_system.nbody_to_si(10.0 | units.kg, 5.0 | units.m) + original = self.TestClass() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('PROPERTY') handler.add_property('get_mass', nbody_system.mass) - + handler = instance.get_handler('UNIT') handler.set_nbody_converter(convert_nbody) - + handler = instance.get_handler('METHOD') handler.add_method('add_to_length', (nbody_system.length,), nbody_system.length) - + self.assertAlmostEqual(instance.mass.value_in(units.kg), 100.0, 10) - - + def test2(self): - convert_nbody = nbody_system.nbody_to_si(10.0 | units.kg, 5.0 | units.m ) - + convert_nbody = nbody_system.nbody_to_si(10.0 | units.kg, 5.0 | units.m) + original = self.TestClass() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('PROPERTY') handler.add_property('get_mass', nbody_system.mass) - + handler = instance.get_handler('UNIT') handler.set_nbody_converter(convert_nbody) - + handler = instance.get_handler('METHOD') handler.add_method('add_to_length', (nbody_system.length,), nbody_system.length) - - self.assertAlmostEqual(instance.add_to_length(5|units.m).value_in(units.m), 55.0, 10) - + + self.assertAlmostEqual(instance.add_to_length(5 | units.m).value_in(units.m), 55.0, 10) def test3(self): original = self.TestClass() instance = interface.InCodeComponentImplementation(original) handler = instance.get_handler('METHOD') - handler.add_method('add_to_length', (units.m,), units.m, public_name = 'add_10') - + handler.add_method('add_to_length', (units.m,), units.m, public_name='add_10') + self.assertFalse(instance.add_10.is_async_supported) - - + def test4(self): original = self.TestClass() instance = interface.InCodeComponentImplementation(original) handler = instance.get_handler('METHOD') handler.add_method('return_an_errorcode', (handler.NO_UNIT,), handler.ERROR_CODE) - + self.assertEqual(instance.return_an_errorcode(0), None) - self.assertRaises(Exception, lambda : instance.return_an_errorcode(-1), + self.assertRaises(Exception, lambda: instance.return_an_errorcode(-1), expected_message="Error when calling 'return_an_errorcode' of a '', errorcode is -1" ) - - + + class CodeInterfaceWithUnitsOnLegacyFunctionTests(amusetest.TestCase): - - def test1(self): + + def test1(self): class TestImplementation(object): - + def get_mass(self): return 10.0, 0 - + class TestInterface(object): - + @legacy_function def get_mass(): function = LegacyFunctionSpecification() function.addParameter('input1', dtype='d', direction=function.OUT, unit=units.kg) function.result_type = 'i' return function - + original = TestInterface() instance = interface.InCodeComponentImplementation(original) - + instance.get_handler("LEGACY").legacy_interface = TestImplementation() self.assertAlmostRelativeEquals(instance.get_mass(), 10 | units.kg) - - def test2(self): + + def test2(self): class TestImplementation(object): - + def echo_one(self, input): return input, 0 - + class TestInterface(object): - + @legacy_function def echo_one(): function = LegacyFunctionSpecification() @@ -127,41 +125,41 @@ def echo_one(): function.addParameter('output', dtype='d', direction=function.OUT, unit=units.g) function.result_type = 'i' return function - + original = TestInterface() instance = interface.InCodeComponentImplementation(original) - + instance.get_handler("LEGACY").legacy_interface = TestImplementation() - self.assertAlmostRelativeEquals(instance.echo_one(1|units.kg), 1 | units.g) - - def test3(self): + self.assertAlmostRelativeEquals(instance.echo_one(1 | units.kg), 1 | units.g) + + def test3(self): class TestImplementation(object): - + def return_error(self): - return -1 - + return -1 + class TestInterface(object): - + @legacy_function def return_error(): function = LegacyFunctionSpecification() function.result_type = 'i' return function - + original = TestInterface() instance = interface.InCodeComponentImplementation(original) - + instance.get_handler("LEGACY").legacy_interface = TestImplementation() - self.assertRaises(Exception,instance.return_error, " Error when calling 'echo_one' of a '', errorcode is -1") + self.assertRaises(Exception, instance.return_error, " Error when calling 'echo_one' of a '', errorcode is -1") - def test4(self): + def test4(self): class TestImplementation(object): - + def echo_one(self, input): return input, 0 - + class TestInterface(object): - + @legacy_function def echo_one(): function = LegacyFunctionSpecification() @@ -169,339 +167,321 @@ def echo_one(): function.addParameter('output', dtype='d', direction=function.OUT, unit=units.deg) function.result_type = 'i' return function - + original = TestInterface() instance = interface.InCodeComponentImplementation(original) - + instance.get_handler("LEGACY").legacy_interface = TestImplementation() self.assertAlmostRelativeEquals(instance.echo_one(1. | units.rad), 1. | units.rad) # this was: self.assertAlmostRelativeEquals(instance.echo_one(1.), 1. | units.deg) # but after 85bd5d99 or 945bc46, it needs to be: self.assertAlmostRelativeEquals(instance.echo_one(1.), 1. | units.rad) - # this is indeed proper behaviour!! - + # this is indeed proper behaviour!! + + class CodeInterfaceWithMethodsAndPropertiesTests(amusetest.TestCase): class TestClass(object): - + def add_10_to_length(self, length): return length + 10 def get_one(self): return 1.0, 0.0 - + def get_state(self, id): return (1.0, 2.0, 3.0, 0.0) - + def get_state_error(self, id): return (1.0, 2.0, 3.0, -1.0) - + def test1(self): original = self.TestClass() - + instance = interface.InCodeComponentImplementation(original) handler = instance.get_handler('METHOD') handler.add_method('add_10_to_length', (units.m,), units.m) - + self.assertEqual(20.0, original.add_10_to_length(10.0)) - + self.assertEqual(20.0 | units.m, instance.add_10_to_length(10.0 | units.m)) - self.assertEqual(1010.0 | units.m, instance.add_10_to_length(1.0| units.km)) - - + self.assertEqual(1010.0 | units.m, instance.add_10_to_length(1.0 | units.km)) + def test2(self): original = self.TestClass() - + instance = interface.InCodeComponentImplementation(original) - - + handler = instance.get_handler('METHOD') - handler.add_method('add_10_to_length', (units.m,), units.m, public_name = 'add_10') - + handler.add_method('add_10_to_length', (units.m,), units.m, public_name='add_10') + self.assertEqual(20.0 | units.m, instance.add_10(10.0 | units.m)) - self.assertEqual(1010.0 | units.m, instance.add_10(1.0| units.km)) - + self.assertEqual(1010.0 | units.m, instance.add_10(1.0 | units.km)) + def test3(self): original = self.TestClass() - + instance = interface.InCodeComponentImplementation(original) - - + handler = instance.get_handler('PROPERTY') handler.add_property('get_one', units.m) - + self.assertEqual(1.0 | units.m, instance.one) - + def test4(self): original = self.TestClass() - + instance = interface.InCodeComponentImplementation(original) - - + handler = instance.get_handler('PROPERTY') - handler.add_property('get_one', units.m, public_name = 'get_one') - + handler.add_property('get_one', units.m, public_name='get_one') + self.assertEqual(1.0 | units.m, instance.get_one) - - + def test5(self): original = self.TestClass() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') handler.add_method('get_state', (handler.NO_UNIT,), (units.m, units.m, units.kg, handler.ERROR_CODE)) - + result = instance.get_state(1) self.assertEqual(3, len(result)) self.assertEqual(1.0 | units.m, result[0]) self.assertEqual(3.0 | units.kg, result[2]) - - + def test6(self): original = self.TestClass() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') handler.add_method('get_state_error', (handler.NO_UNIT,), (units.m, units.m, units.kg, handler.ERROR_CODE)) - - self.assertRaises(AmuseException, instance.get_state_error, 1, - expected_message = "Error when calling 'get_state_error' of a '', errorcode is -1.0") - + + self.assertRaises(AmuseException, instance.get_state_error, 1, + expected_message="Error when calling 'get_state_error' of a '', errorcode is -1.0") + class ClassWithState(object): - + def __init__(self): self.state = 0 self.number_of_times_move_to_state_1_called = 0 self.number_of_times_move_to_state_2_called = 0 self.number_of_times_move_to_state_3_called = 0 self.number_of_times_move_to_state_4_called = 0 - + def always_works(self): return True - + def move_to_state_1(self): self.number_of_times_move_to_state_1_called += 1 self.state = 1 - + def move_to_state_2(self): self.number_of_times_move_to_state_2_called += 1 self.state = 2 - + def move_to_state_3(self): self.number_of_times_move_to_state_3_called += 1 self.state = 3 - + def move_to_state_4(self): self.number_of_times_move_to_state_4_called += 1 self.state = 4 - + def returns_1(self): return self.state - + def returns_2(self): return self.state - + def returns_3(self): return self.state - + def returns_4(self): return self.state + + class CodeInterfaceTests(amusetest.TestCase): - + def test1(self): original = ClassWithState() - + instance = interface.InCodeComponentImplementation(original) - + self.assertTrue(instance.always_works()) instance.move_to_state_1() self.assertEqual(1, instance.returns_1()) - + def test2(self): original = ClassWithState() - + instance = interface.InCodeComponentImplementation(original) handler = instance.get_handler('STATE') - + handler.add_transition('ZERO', 'ONE', 'move_to_state_1') handler.add_method('ONE', 'returns_1') handler.set_initial_state('ZERO') - - + self.assertTrue(instance.always_works()) self.assertEqual(instance.get_name_of_current_state(), 'ZERO') instance.move_to_state_1() - + self.assertEqual(instance.get_name_of_current_state(), 'ONE') self.assertEqual(instance.returns_1(), 1) - - + def test3(self): class TestCodeInterface(interface.InCodeComponentImplementation): - + def move_to_state_1(self): self.overridden().move_to_state_1() self.traced = True - + original = ClassWithState() - + instance = TestCodeInterface(original) instance.traced = False - + handler = instance.get_handler('STATE') handler.add_transition('ZERO', 'ONE', 'move_to_state_1') handler.add_method('ONE', 'returns_1') handler.set_initial_state('ZERO') - - - + self.assertEqual(instance.get_name_of_current_state(), 'ZERO') self.assertEqual(instance.returns_1(), 1) self.assertEqual(instance.get_name_of_current_state(), 'ONE') self.assertTrue(instance.traced) - - + def test4(self): original = ClassWithState() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('STATE') - + handler.add_transition('ZERO', 'ONE', 'move_to_state_1') handler.add_method('ONE', 'returns_1') handler.set_initial_state('ZERO') - - + self.assertEqual(instance.get_name_of_current_state(), 'ZERO') - self.assertEqual(instance.returns_1(), 1) + self.assertEqual(instance.returns_1(), 1) self.assertEqual(instance.get_name_of_current_state(), 'ONE') - + def test5(self): original = ClassWithState() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('STATE') handler.add_transition('ZERO', 'ONE', 'move_to_state_1') handler.add_transition('ONE', 'TWO', 'move_to_state_2') handler.add_method('ONE', 'returns_1') handler.add_method('TWO', 'returns_2') handler.set_initial_state('ZERO') - - + self.assertEqual(instance.get_name_of_current_state(), 'ZERO') - self.assertEqual(instance.returns_2(), 2) + self.assertEqual(instance.returns_2(), 2) self.assertEqual(instance.get_name_of_current_state(), 'TWO') - + def test6(self): original = ClassWithState() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('STATE') handler.add_transition('ZERO', 'ONE', 'move_to_state_1') handler.add_transition('ONE', 'TWO', 'move_to_state_2') handler.add_transition('TWO', 'THREE', 'move_to_state_3') handler.add_transition('TWO', 'FOUR', 'move_to_state_4') handler.add_transition('THREE', 'ONE', 'move_to_state_1') - + handler.add_method('ONE', 'returns_1') handler.add_method('TWO', 'returns_2') handler.add_method('THREE', 'returns_3') handler.add_method('FOUR', 'returns_4') handler.set_initial_state('ZERO') - - + self.assertEqual(instance.get_name_of_current_state(), 'ZERO') - self.assertEqual(instance.returns_4(), 4) + self.assertEqual(instance.returns_4(), 4) self.assertEqual(instance.get_name_of_current_state(), 'FOUR') - - + handler.set_initial_state('ZERO') self.assertEqual(instance.get_name_of_current_state(), 'ZERO') - self.assertEqual(instance.returns_3(), 3) + self.assertEqual(instance.returns_3(), 3) self.assertEqual(instance.get_name_of_current_state(), 'THREE') - self.assertEqual(instance.returns_4(), 4) + self.assertEqual(instance.returns_4(), 4) self.assertEqual(instance.get_name_of_current_state(), 'FOUR') - - + def test7(self): original = ClassWithState() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('STATE') handler.add_transition('ZERO', 'ONE', 'move_to_state_1') handler.add_transition('ONE', 'TWO', 'move_to_state_2') handler.add_transition('TWO', 'THREE', 'move_to_state_3') handler.add_transition('TWO', 'FOUR', 'move_to_state_4') handler.add_transition('THREE', 'ONE', 'move_to_state_1') - + handler.add_method('ONE', 'returns_1') handler.add_method('TWO', 'returns_2') handler.add_method('THREE', 'returns_3') handler.add_method('FOUR', 'returns_4') handler.set_initial_state('ZERO') handler.do_automatic_state_transitions(False) - - + self.assertEqual(instance.get_name_of_current_state(), 'ZERO') try: self.assertEqual(instance.returns_4(), 4) self.fail("Automatic state transitions is OFF, this method should fail") except Exception as ex: print(ex) - + self.assertEqual(len(ex.transitions), 3) - + for x in ex.transitions: x.do() - + self.assertEqual(instance.returns_4(), 4) - - + def test8(self): original = ClassWithState() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('STATE') handler.add_transition('ZERO', 'ONE', 'move_to_state_1') handler.add_transition('ONE', 'TWO', 'move_to_state_2') - + handler.add_method('ONE', 'returns_1') handler.add_method('TWO', 'returns_2') handler.add_method('THREE', 'returns_3') handler.set_initial_state('ZERO') - - + self.assertEqual(instance.get_name_of_current_state(), 'ZERO') self.assertEqual(instance.returns_2(), 2) - self.assertRaises(Exception, instance.returns_3, - expected_message = "While calling returns_3 of : No transition from current state state 'TWO' to state 'THREE' possible") - + self.assertRaises(Exception, instance.returns_3, + expected_message="While calling returns_3 of : No transition from current state state 'TWO' to state 'THREE' possible") + def test9(self): original = ClassWithState() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('STATE') handler.add_transition('ZERO', 'ONE', 'move_to_state_1') handler.add_transition('ONE', 'TWO', 'move_to_state_2') handler.add_transition('THREE', 'ONE', 'move_to_state_1') handler.add_transition('TWO', 'THREE', 'move_to_state_1') - - + handler.add_method('ONE', 'returns_1') handler.add_method('TWO', 'returns_2') handler.add_method('THREE', 'returns_3') handler.set_initial_state('ZERO') - - + self.assertEqual(instance.get_name_of_current_state(), 'ZERO') instance.move_to_state_1() self.assertEqual(instance.get_name_of_current_state(), 'ONE') @@ -511,29 +491,25 @@ def test9(self): self.assertEqual(instance.get_name_of_current_state(), 'THREE') instance.move_to_state_1() self.assertEqual(instance.get_name_of_current_state(), 'ONE') - - self.assertEqual(instance.returns_3(), 1) - - + self.assertEqual(instance.returns_3(), 1) def test10(self): original = ClassWithState() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('STATE') handler.add_transition('ZERO', 'ONE', 'move_to_state_1') handler.add_transition('ONE', 'TWO', 'move_to_state_2') handler.add_transition('THREE', 'ONE', 'move_to_state_1') handler.add_transition('TWO', 'THREE', 'move_to_state_1') - - + handler.add_method('ONE', 'returns_1') handler.add_method('TWO', 'returns_2') handler.add_method('THREE', 'returns_3') handler.set_initial_state('ZERO') - + self.assertTrue(instance.state_machine.is_enabled) self.assertEqual(instance.state_machine.get_name_of_current_state(), 'ZERO') instance.move_to_state_1() @@ -542,33 +518,30 @@ def test10(self): self.assertFalse(instance.state_machine.is_enabled) instance.move_to_state_2() self.assertEqual(instance.get_name_of_current_state(), 'ONE') - + def test11(self): original = ClassWithState() - + instance = interface.InCodeComponentImplementation(original) handler = instance.get_handler('STATE') - + handler.add_transition('ZERO', 'ONE', 'move_to_state_1') handler.add_transition('!ZERO', 'TWO', 'move_to_state_2') handler.add_transition('TWO', 'ONE', 'move_to_state_1') handler.add_method('TWO', 'returns_1') handler.set_initial_state('ZERO') - - + self.assertEqual(instance.get_name_of_current_state(), 'ZERO') instance.returns_1() - + self.assertEqual(instance.get_name_of_current_state(), 'TWO') self.assertEqual(instance.number_of_times_move_to_state_1_called, 1) self.assertEqual(instance.number_of_times_move_to_state_2_called, 1) - - - + def test12(self): original = ClassWithState() - - instance = interface.InCodeComponentImplementation(original, log_transitions = True) + + instance = interface.InCodeComponentImplementation(original, log_transitions=True) handler = instance.get_handler('STATE') handler.add_transition('ZERO', 'ONE', 'move_to_state_1') handler.add_transition('ONE', 'THREE', 'move_to_state_3') @@ -577,23 +550,20 @@ def test12(self): handler.add_transition('TWO', 'ONE', 'move_to_state_1') handler.add_method('TWO', 'returns_1') handler.set_initial_state('ZERO') - - + self.assertEqual(instance.get_name_of_current_state(), 'ZERO') instance.returns_1() - + self.assertEqual(instance.get_name_of_current_state(), 'TWO') self.assertEqual(instance.number_of_times_move_to_state_1_called, 1) self.assertEqual(instance.number_of_times_move_to_state_2_called, 1) self.assertEqual(instance.number_of_times_move_to_state_3_called, 1) self.assertEqual(instance.number_of_times_move_to_state_4_called, 1) - - - + def test13(self): original = ClassWithState() - - instance = interface.InCodeComponentImplementation(original, log_transitions = True) + + instance = interface.InCodeComponentImplementation(original, log_transitions=True) handler = instance.get_handler('STATE') handler.add_transition('!ZERO!ONE!TWO', 'FOUR', 'move_to_state_4') handler.add_transition('ONE', 'TWO', 'move_to_state_2') @@ -601,11 +571,10 @@ def test13(self): handler.add_transition('ZERO', 'ONE', 'move_to_state_1') handler.add_method('!ZERO', 'returns_1') handler.set_initial_state('ZERO') - - + self.assertEqual(instance.get_name_of_current_state(), 'ZERO') instance.returns_1() - + self.assertEqual(instance.get_name_of_current_state(), 'ONE') self.assertEqual(instance.number_of_times_move_to_state_1_called, 1) self.assertEqual(instance.number_of_times_move_to_state_2_called, 0) @@ -614,86 +583,82 @@ def test13(self): instance.move_to_state_2() self.assertEqual(instance.get_name_of_current_state(), 'TWO') instance.returns_1() - + self.assertEqual(instance.get_name_of_current_state(), 'TWO') - + def test14(self): original = ClassWithState() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('STATE') handler.add_transition('ZERO', 'ONE', 'move_to_state_1') handler.add_transition('ONE', 'TWO', 'move_to_state_2') - - + handler.add_method('ONE', 'returns_1') handler.add_method('TWO', 'returns_2') handler.set_initial_state('ZERO') handler.remove_transition('ZERO', 'ONE', 'move_to_state_1') handler.remove_transition('ONE', 'TWO', 'move_to_state_2') handler.add_transition('ZERO', 'TWO', 'move_to_state_1') - + self.assertEqual(instance.get_name_of_current_state(), 'ZERO') instance.returns_2() self.assertEqual(instance.get_name_of_current_state(), 'TWO') - + def test15(self): original = ClassWithState() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('STATE') handler.add_transition('ZERO', 'ONE', 'move_to_state_1') handler.add_transition('ONE', 'TWO', 'move_to_state_2') handler.add_transition('TWO', 'THREE', 'move_to_state_3') handler.add_transition('TWO', 'FOUR', 'move_to_state_4') handler.add_transition('THREE', 'ONE', 'move_to_state_1') - + handler.add_method('THREE', 'returns_1') handler.add_method('TWO', 'returns_1') handler.add_method('ONE', 'returns_1') handler.set_initial_state('ZERO') - - + self.assertEqual(instance.get_name_of_current_state(), 'ZERO') - self.assertEqual(instance.returns_1(), 1) + self.assertEqual(instance.returns_1(), 1) self.assertEqual(instance.get_name_of_current_state(), 'ONE') - - + def test9(self): original = ClassWithState() instance = interface.InCodeComponentImplementation(original) - - + handler = instance.get_handler('STATE') handler.add_transition('ZERO', 'ONE', 'move_to_state_1') handler.add_transition('ONE', 'TWO', 'move_to_state_2') handler.add_transition('TWO', 'THREE', 'move_to_state_3') handler.add_transition('TWO', 'FOUR', 'move_to_state_4') handler.add_transition('THREE', 'ONE', 'move_to_state_1') - + handler.add_method('THREE', 'returns_3') handler.add_method('TWO', 'returns_2') handler.add_method('ONE', 'returns_1') handler.set_initial_state('ZERO') - + self.assertEqual(instance.get_name_of_current_state(), 'ZERO') - self.assertEqual(instance.returns_1(), 1) + self.assertEqual(instance.returns_1(), 1) self.assertEqual(instance.get_name_of_current_state(), 'ONE') - + pickled_instance = pickle.dumps(instance) unpickled_instance = pickle.loads(pickled_instance) self.assertEqual(unpickled_instance.get_name_of_current_state(), 'ONE') - self.assertEqual(unpickled_instance.returns_2(), 2) + self.assertEqual(unpickled_instance.returns_2(), 2) self.assertEqual(unpickled_instance.get_name_of_current_state(), 'TWO') self.assertEqual(instance.get_name_of_current_state(), 'ONE') def test10(self): original = ClassWithState() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('STATE') handler.add_transition('ZERO', 'ONE', 'move_to_state_1') # remove to generate exception @@ -701,136 +666,125 @@ def test10(self): handler.add_method('ONE', 'returns_1') handler.add_method('TWO', 'returns_2') handler.set_initial_state('ZERO') - - + self.assertEqual(instance.get_name_of_current_state(), 'ZERO') - self.assertRaises( Exception, instance.returns_2, expected_message= - "While calling returns_2 of : No transition from current state state 'ZERO' to state 'TWO' possible") + self.assertRaises(Exception, instance.returns_2, expected_message="While calling returns_2 of : No transition from current state state 'ZERO' to state 'TWO' possible") + - class CodeInterfaceWithUnitsAndStateTests(amusetest.TestCase): class TestClass(object): - + def __init__(self): self.value = 10.0 - + def add_to_length(self, length): return length + self.value - + def move_to_20(self): self.value = 20 - + def test1(self): original = self.TestClass() - + instance = interface.InCodeComponentImplementation(original) - - + handler = instance.get_handler('METHOD') handler.add_method('add_to_length', (units.m,), units.m) - - + handler = instance.get_handler('STATE') handler.set_initial_state('ZERO') handler.add_transition('ZERO', 'ONE', 'move_to_20') handler.add_method('ONE', 'add_to_length') - + self.assertEqual(40.0 | units.m, instance.add_to_length(20.0 | units.m)) - + def test2(self): original = self.TestClass() - + instance = interface.InCodeComponentImplementation(original) - - + handler = instance.get_handler('METHOD') - handler.add_method('add_to_length', (units.m,), units.m, public_name = 'add') - - + handler.add_method('add_to_length', (units.m,), units.m, public_name='add') + handler = instance.get_handler('STATE') handler.set_initial_state('ZERO') handler.add_transition('ZERO', 'ONE', 'move_to_20') handler.add_method('ONE', 'add_to_length') - + self.assertEqual(40.0 | units.m, instance.add(20.0 | units.m)) - + def test3(self): original = self.TestClass() - + instance = interface.InCodeComponentImplementation(original) - - + handler = instance.get_handler('METHOD') - handler.add_method('add_to_length', (units.m,), units.m, public_name = 'add') - - + handler.add_method('add_to_length', (units.m,), units.m, public_name='add') + handler = instance.get_handler('STATE') handler.set_initial_state('ZERO') handler.add_transition('ZERO', 'ONE', 'move_to_20') handler.add_method('ONE', 'add') - + self.assertEqual(40.0 | units.m, instance.add(20.0 | units.m)) - + class CodeInterfaceWithErrorHandlingTests(amusetest.TestCase): class TestClass(object): errorcode = 0 - + def get_mass(self): return 10.0, self.errorcode - - + def test1(self): - convert_nbody = nbody_system.nbody_to_si(10.0 | units.kg, 5.0 | units.m ) - + convert_nbody = nbody_system.nbody_to_si(10.0 | units.kg, 5.0 | units.m) + original = self.TestClass() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') handler.add_method('get_mass', (), (units.m, handler.ERROR_CODE,)) handler = instance.get_handler('ERRORCODE') handler.add_errorcode(-2, "no such method") handler.add_errorcode(-3, "not available") - + self.assertEqual(instance.get_mass(), 10.0 | units.m) original.errorcode = -2 - self.assertRaises(AmuseException, instance.get_mass, expected_message = - "Error when calling 'get_mass' of a '', errorcode is -2, error is 'no such method'") - + self.assertRaises(AmuseException, instance.get_mass, expected_message="Error when calling 'get_mass' of a '', errorcode is -2, error is 'no such method'") + original.errorcode = -1 - self.assertRaises(AmuseException, instance.get_mass, expected_message = - "Error when calling 'get_mass' of a '', errorcode is -1") - + self.assertRaises(AmuseException, instance.get_mass, expected_message="Error when calling 'get_mass' of a '', errorcode is -1") + class CodeInterfaceWithParticlesTests(amusetest.TestCase): class TestClass(object): def get_mass(self): return 10.0, 0 - + def add_to_length(self, length): return length + 10.0 - + def test1(self): - convert_nbody = nbody_system.nbody_to_si(10.0 | units.kg, 5.0 | units.m ) - + convert_nbody = nbody_system.nbody_to_si(10.0 | units.kg, 5.0 | units.m) + original = self.TestClass() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('PROPERTY') handler.add_property('get_mass', nbody_system.mass) - + handler = instance.get_handler('UNIT') handler.set_nbody_converter(convert_nbody) - - + + class ParticlesWithBindingInterface(object): def __init__(self): self.masses = {} - + def get_mass(self, id): masses = [] errors = [] @@ -841,42 +795,41 @@ def get_mass(self, id): result["mass"] = masses result["__result"] = errors return result - + def set_mass(self, id, mass): - for i,m in zip(id,mass): + for i, m in zip(id, mass): self.masses[i] = m - - return ( [0] * len(id),) - + + return ([0] * len(id),) + def new_particle(self, mass): ids = [] errors = [] - + for x in mass: id = len(self.masses) - self.masses[len(self.masses)] = x + self.masses[len(self.masses)] = x ids.append(id) errors.append(0) - + return (ids, errors) - + def delete_particle(self, id): errors = [] for x in id: self.masses[x].stop() errors.append(0) return errors - + def get_number_of_particles(self): return (len(self.masses), 0) - + def get_colliding_indices(self): - return (1,2,0) - - + return (1, 2, 0) + def get_next(self, id): return ([x+1 for x in id], [0 for x in id]) - + def add_1_to_mass(self, id): if isinstance(id, (int, numpy.int64, numpy.int32)): self.masses[id] += 1.0 @@ -884,7 +837,6 @@ def add_1_to_mass(self, id): for i in id: self.masses[i] += 1.0 return [0 for x in id] - def get_heaviest_particle(self): max = -1 @@ -894,20 +846,20 @@ def get_heaviest_particle(self): id = index max = mass return id - + def get_number_of_lightest_particles(self): return 2 - + def get_lightest_particles(self, offset): - sorted_masses = sorted(list(self.masses.items()), key = lambda x : x[1]) + sorted_masses = sorted(list(self.masses.items()), key=lambda x: x[1]) return [sorted_masses[x][0] for x in offset] - + def get_number_of_particles_with_same_mass(self, id): result = [] for index in id: mass = self.masses[index] count = 0 - + for otherindex, m in self.masses.items(): if otherindex == index: continue @@ -915,7 +867,7 @@ def get_number_of_particles_with_same_mass(self, id): count += 1 result.append(count) return result - + def get_particle_with_same_mass(self, id, offset): result = [] for index, index_in_list in zip(id, offset): @@ -930,290 +882,275 @@ def get_particle_with_same_mass(self, id, offset): result.append(otherindex) break return result + + class TestParticlesWithBinding(amusetest.TestCase): - - - + def test1(self): original = ParticlesWithBindingInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_mass',(handler.NO_UNIT,), (units.kg, handler.ERROR_CODE)) - handler.add_method('set_mass',(handler.NO_UNIT, units.kg,), (handler.ERROR_CODE,)) - handler.add_method('new_particle',(units.kg,), (handler.NO_UNIT, handler.ERROR_CODE)) - handler.add_method('delete_particle',(handler.NO_UNIT,), (handler.ERROR_CODE,)) - handler.add_method('get_number_of_particles',(), (handler.NO_UNIT, handler.ERROR_CODE,)) - + handler.add_method('get_mass', (handler.NO_UNIT,), (units.kg, handler.ERROR_CODE)) + handler.add_method('set_mass', (handler.NO_UNIT, units.kg,), (handler.ERROR_CODE,)) + handler.add_method('new_particle', (units.kg,), (handler.NO_UNIT, handler.ERROR_CODE)) + handler.add_method('delete_particle', (handler.NO_UNIT,), (handler.ERROR_CODE,)) + handler.add_method('get_number_of_particles', (), (handler.NO_UNIT, handler.ERROR_CODE,)) + handler = instance.get_handler('PARTICLES') handler.define_set('particles', 'id') handler.set_new('particles', 'new_particle') handler.set_delete('particles', 'delete_particle') handler.add_setter('particles', 'set_mass') - handler.add_getter('particles', 'get_mass', names = ('mass',)) - - + handler.add_getter('particles', 'get_mass', names=('mass',)) + local_particles = datamodel.Particles(4) local_particles.mass = units.kg.new_quantity([3.0, 4.0, 5.0, 6.0]) - + remote_particles = instance.particles remote_particles.add_particles(local_particles) - + self.assertEqual(len(original.masses), 4) self.assertEqual(original.masses[0], 3.0) self.assertEqual(original.masses[3], 6.0) - + self.assertEqual(len(instance.particles), 4) self.assertEqual(instance.particles[0].mass, 3.0 | units.kg) - + def test2(self): original = ParticlesWithBindingInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_mass',(handler.NO_UNIT,), (units.kg, handler.ERROR_CODE)) - handler.add_method('set_mass',(handler.NO_UNIT, units.kg,), (handler.ERROR_CODE,)) - handler.add_method('new_particle',(units.kg,), (handler.NO_UNIT, handler.ERROR_CODE)) - handler.add_method('delete_particle',(handler.NO_UNIT,), (handler.ERROR_CODE,)) - handler.add_method('get_number_of_particles',(), (handler.NO_UNIT, handler.ERROR_CODE,)) - handler.add_method('get_colliding_indices',(), (handler.NO_UNIT, handler.NO_UNIT, handler.ERROR_CODE,)) + handler.add_method('get_mass', (handler.NO_UNIT,), (units.kg, handler.ERROR_CODE)) + handler.add_method('set_mass', (handler.NO_UNIT, units.kg,), (handler.ERROR_CODE,)) + handler.add_method('new_particle', (units.kg,), (handler.NO_UNIT, handler.ERROR_CODE)) + handler.add_method('delete_particle', (handler.NO_UNIT,), (handler.ERROR_CODE,)) + handler.add_method('get_number_of_particles', (), (handler.NO_UNIT, handler.ERROR_CODE,)) + handler.add_method('get_colliding_indices', (), (handler.NO_UNIT, handler.NO_UNIT, handler.ERROR_CODE,)) handler = instance.get_handler('PARTICLES') handler.define_set('particles', 'id') handler.set_new('particles', 'new_particle') handler.set_delete('particles', 'delete_particle') handler.add_setter('particles', 'set_mass') - handler.add_getter('particles', 'get_mass', names = ('mass',)) - - - handler.add_query('particles', 'get_colliding_indices', public_name = 'select_colliding') - handler.add_select_from_particle('particles', 'get_next', public_name = 'next') - - + handler.add_getter('particles', 'get_mass', names=('mass',)) + + handler.add_query('particles', 'get_colliding_indices', public_name='select_colliding') + handler.add_select_from_particle('particles', 'get_next', public_name='next') + local_particles = datamodel.Particles(4) local_particles.mass = units.kg.new_quantity([3.0, 4.0, 5.0, 6.0]) - + remote_particles = instance.particles remote_particles.add_particles(local_particles) - + colliding_particles = instance.particles.select_colliding() - + self.assertEqual(len(colliding_particles), 2) self.assertEqual(colliding_particles.mass[0], 4.0 | units.kg) self.assertEqual(colliding_particles.mass[1], 5.0 | units.kg) - + attribute_names = dir(instance) - + self.assertTrue('particles' in attribute_names) self.assertTrue('get_colliding_indices' in attribute_names) - + def test3(self): original = ParticlesWithBindingInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_mass',(handler.NO_UNIT,), (units.kg, handler.ERROR_CODE)) - handler.add_method('set_mass',(handler.NO_UNIT, units.kg,), (handler.ERROR_CODE,)) - handler.add_method('get_next',(handler.INDEX,), (handler.LINK("particles"), handler.ERROR_CODE)) - handler.add_method('new_particle',(units.kg,), (handler.NO_UNIT, handler.ERROR_CODE)) - handler.add_method('delete_particle',(handler.NO_UNIT,), (handler.ERROR_CODE,)) - handler.add_method('get_number_of_particles',(), (handler.NO_UNIT, handler.ERROR_CODE,)) - + handler.add_method('get_mass', (handler.NO_UNIT,), (units.kg, handler.ERROR_CODE)) + handler.add_method('set_mass', (handler.NO_UNIT, units.kg,), (handler.ERROR_CODE,)) + handler.add_method('get_next', (handler.INDEX,), (handler.LINK("particles"), handler.ERROR_CODE)) + handler.add_method('new_particle', (units.kg,), (handler.NO_UNIT, handler.ERROR_CODE)) + handler.add_method('delete_particle', (handler.NO_UNIT,), (handler.ERROR_CODE,)) + handler.add_method('get_number_of_particles', (), (handler.NO_UNIT, handler.ERROR_CODE,)) + handler = instance.get_handler('PARTICLES') handler.define_set('particles', 'id') handler.set_new('particles', 'new_particle') handler.set_delete('particles', 'delete_particle') handler.add_setter('particles', 'set_mass') - handler.add_getter('particles', 'get_mass', names = ('mass',)) - handler.add_getter('particles', 'get_next', names = ('next_particle',)) - - + handler.add_getter('particles', 'get_mass', names=('mass',)) + handler.add_getter('particles', 'get_next', names=('next_particle',)) + local_particles = datamodel.Particles(4) local_particles.mass = units.kg.new_quantity([3.0, 4.0, 5.0, 6.0]) - + remote_particles = instance.particles remote_particles.add_particles(local_particles) - + self.assertEqual(len(instance.particles), 4) self.assertEqual(instance.particles[0].next_particle, instance.particles[1]) self.assertEqual(instance.particles[1].next_particle, instance.particles[2]) self.assertEqual(instance.particles[2].next_particle, instance.particles[3]) self.assertEqual(instance.particles[3].next_particle, None) - - + def test4(self): original = ParticlesWithBindingInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_mass',(handler.NO_UNIT,), (units.kg, handler.ERROR_CODE)) - handler.add_method('set_mass',(handler.NO_UNIT, units.kg,), (handler.ERROR_CODE,)) - handler.add_method('new_particle',(units.kg,), (handler.NO_UNIT, handler.ERROR_CODE)) - handler.add_method('delete_particle',(handler.NO_UNIT,), (handler.ERROR_CODE,)) - handler.add_method('get_number_of_particles',(), (handler.NO_UNIT, handler.ERROR_CODE,)) - - - handler.add_method('add_1_to_mass',(handler.INDEX,), (handler.ERROR_CODE,)) - + handler.add_method('get_mass', (handler.NO_UNIT,), (units.kg, handler.ERROR_CODE)) + handler.add_method('set_mass', (handler.NO_UNIT, units.kg,), (handler.ERROR_CODE,)) + handler.add_method('new_particle', (units.kg,), (handler.NO_UNIT, handler.ERROR_CODE)) + handler.add_method('delete_particle', (handler.NO_UNIT,), (handler.ERROR_CODE,)) + handler.add_method('get_number_of_particles', (), (handler.NO_UNIT, handler.ERROR_CODE,)) + + handler.add_method('add_1_to_mass', (handler.INDEX,), (handler.ERROR_CODE,)) + handler = instance.get_handler('PARTICLES') handler.define_set('particles', 'id') handler.set_new('particles', 'new_particle') handler.set_delete('particles', 'delete_particle') handler.add_setter('particles', 'set_mass') - handler.add_getter('particles', 'get_mass', names = ('mass',)) + handler.add_getter('particles', 'get_mass', names=('mass',)) handler.add_method('particles', 'add_1_to_mass', 'add_one') - - + local_particles = datamodel.Particles(4) local_particles.mass = units.kg.new_quantity([3.0, 4.0, 5.0, 6.0]) - + remote_particles = instance.particles remote_particles.add_particles(local_particles) - + self.assertEqual(len(instance.particles), 4) self.assertEqual(instance.particles.mass, units.kg.new_quantity([3.0, 4.0, 5.0, 6.0])) instance.particles[0].add_one() self.assertEqual(instance.particles.mass, units.kg.new_quantity([4.0, 4.0, 5.0, 6.0])) instance.particles.add_one() self.assertEqual(instance.particles.mass, units.kg.new_quantity([5.0, 5.0, 6.0, 7.0])) - - + def test5(self): original = ParticlesWithBindingInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_mass',(handler.NO_UNIT,), (nbody_system.mass, handler.ERROR_CODE)) - handler.add_method('set_mass',(handler.NO_UNIT, nbody_system.mass,), (handler.ERROR_CODE,)) - handler.add_method('new_particle',(nbody_system.mass,), (handler.NO_UNIT, handler.ERROR_CODE)) - handler.add_method('delete_particle',(handler.NO_UNIT,), (handler.ERROR_CODE,)) - handler.add_method('get_number_of_particles',(), (handler.NO_UNIT, handler.ERROR_CODE,)) - + handler.add_method('get_mass', (handler.NO_UNIT,), (nbody_system.mass, handler.ERROR_CODE)) + handler.add_method('set_mass', (handler.NO_UNIT, nbody_system.mass,), (handler.ERROR_CODE,)) + handler.add_method('new_particle', (nbody_system.mass,), (handler.NO_UNIT, handler.ERROR_CODE)) + handler.add_method('delete_particle', (handler.NO_UNIT,), (handler.ERROR_CODE,)) + handler.add_method('get_number_of_particles', (), (handler.NO_UNIT, handler.ERROR_CODE,)) + handler = instance.get_handler('PARTICLES') handler.define_set('particles', 'id') handler.set_new('particles', 'new_particle') handler.set_delete('particles', 'delete_particle') handler.add_setter('particles', 'set_mass') - handler.add_getter('particles', 'get_mass', names = ('mass',)) - - - convert_nbody = nbody_system.nbody_to_si(10.0 | units.kg, 5.0 | units.m ) - + handler.add_getter('particles', 'get_mass', names=('mass',)) + + convert_nbody = nbody_system.nbody_to_si(10.0 | units.kg, 5.0 | units.m) + handler = instance.get_handler('UNIT') handler.set_nbody_converter(convert_nbody) local_particles = datamodel.Particles(4) local_particles.mass = units.kg.new_quantity([3.0, 4.0, 5.0, 6.0]) - + remote_particles = instance.particles remote_particles.add_particles(local_particles) - + self.assertEqual(len(original.masses), 4) self.assertAlmostEqual(original.masses[0], 0.3, 5) self.assertAlmostEqual(original.masses[3], 0.6, 5) - + self.assertEqual(len(instance.particles), 4) self.assertEqual(instance.particles[0].mass, 3.0 | units.kg) - - - - + def test6(self): original = ParticlesWithBindingInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_mass',(handler.NO_UNIT,), (nbody_system.mass, handler.ERROR_CODE)) - handler.add_method('set_mass',(handler.NO_UNIT, nbody_system.mass,), (handler.ERROR_CODE,)) - handler.add_method('new_particle',(nbody_system.mass,), (handler.NO_UNIT, handler.ERROR_CODE)) - handler.add_method('delete_particle',(handler.NO_UNIT,), (handler.ERROR_CODE,)) - handler.add_method('get_number_of_particles',(), (handler.NO_UNIT, handler.ERROR_CODE,)) - + handler.add_method('get_mass', (handler.NO_UNIT,), (nbody_system.mass, handler.ERROR_CODE)) + handler.add_method('set_mass', (handler.NO_UNIT, nbody_system.mass,), (handler.ERROR_CODE,)) + handler.add_method('new_particle', (nbody_system.mass,), (handler.NO_UNIT, handler.ERROR_CODE)) + handler.add_method('delete_particle', (handler.NO_UNIT,), (handler.ERROR_CODE,)) + handler.add_method('get_number_of_particles', (), (handler.NO_UNIT, handler.ERROR_CODE,)) + handler = instance.get_handler('PARTICLES') handler.define_set('particles', 'id') handler.set_new('particles', 'new_particle') handler.set_delete('particles', 'delete_particle') handler.add_setter('particles', 'set_mass') - handler.add_getter('particles', 'get_mass', names = ('mass',)) - handler.add_subselect_in_set('particles', 'get_heaviest_particle', public_name = 'heaviest') - handler.add_subselect_in_set('particles', 'get_lightest_particles', get_number_of_particles_name = 'get_number_of_lightest_particles', public_name = 'lightest') - - - convert_nbody = nbody_system.nbody_to_si(10.0 | units.kg, 5.0 | units.m ) - + handler.add_getter('particles', 'get_mass', names=('mass',)) + handler.add_subselect_in_set('particles', 'get_heaviest_particle', public_name='heaviest') + handler.add_subselect_in_set('particles', 'get_lightest_particles', get_number_of_particles_name='get_number_of_lightest_particles', public_name='lightest') + + convert_nbody = nbody_system.nbody_to_si(10.0 | units.kg, 5.0 | units.m) + handler = instance.get_handler('UNIT') handler.set_nbody_converter(convert_nbody) - + local_particles = datamodel.Particles(4) local_particles.mass = units.kg.new_quantity([3.0, 4.0, 6.0, 5.0]) - + remote_particles = instance.particles remote_particles.add_particles(local_particles) - + self.assertEqual(len(instance.particles), 4) self.assertEqual(instance.particles[0].mass, 3.0 | units.kg) subset = instance.particles.heaviest() self.assertEqual(len(subset), 1) self.assertEqual(subset[0], local_particles[2]) - + subset = instance.particles.lightest() self.assertEqual(len(subset), 2) self.assertEqual(subset[0], local_particles[0]) self.assertEqual(subset[1], local_particles[1]) - def test7(self): original = ParticlesWithBindingInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_mass',(handler.NO_UNIT,), (nbody_system.mass, handler.ERROR_CODE)) - handler.add_method('set_mass',(handler.NO_UNIT, nbody_system.mass,), (handler.ERROR_CODE,)) - handler.add_method('new_particle',(nbody_system.mass,), (handler.NO_UNIT, handler.ERROR_CODE)) - handler.add_method('delete_particle',(handler.NO_UNIT,), (handler.ERROR_CODE,)) - handler.add_method('get_number_of_particles',(), (handler.NO_UNIT, handler.ERROR_CODE,)) - + handler.add_method('get_mass', (handler.NO_UNIT,), (nbody_system.mass, handler.ERROR_CODE)) + handler.add_method('set_mass', (handler.NO_UNIT, nbody_system.mass,), (handler.ERROR_CODE,)) + handler.add_method('new_particle', (nbody_system.mass,), (handler.NO_UNIT, handler.ERROR_CODE)) + handler.add_method('delete_particle', (handler.NO_UNIT,), (handler.ERROR_CODE,)) + handler.add_method('get_number_of_particles', (), (handler.NO_UNIT, handler.ERROR_CODE,)) + handler = instance.get_handler('PARTICLES') handler.define_set('particles', 'id') handler.set_new('particles', 'new_particle') handler.set_delete('particles', 'delete_particle') handler.add_setter('particles', 'set_mass') - handler.add_getter('particles', 'get_mass', names = ('mass',)) - handler.add_subselect_from_particle('particles', 'get_particle_with_same_mass', get_number_of_particles_name = 'get_number_of_particles_with_same_mass', public_name = 'samemass') - - - convert_nbody = nbody_system.nbody_to_si(1.0 | units.kg, 5.0 | units.m ) - + handler.add_getter('particles', 'get_mass', names=('mass',)) + handler.add_subselect_from_particle('particles', 'get_particle_with_same_mass', get_number_of_particles_name='get_number_of_particles_with_same_mass', public_name='samemass') + + convert_nbody = nbody_system.nbody_to_si(1.0 | units.kg, 5.0 | units.m) + handler = instance.get_handler('UNIT') handler.set_nbody_converter(convert_nbody) - + local_particles = datamodel.Particles(4) local_particles.mass = units.kg.new_quantity([3.5, 4.0, 6.0, 4.5]) - + remote_particles = instance.particles remote_particles.add_particles(local_particles) - + self.assertEqual(len(instance.particles), 4) self.assertEqual(instance.particles[1].mass, 4.0 | units.kg) subset = instance.particles[1].samemass() self.assertEqual(len(subset), 2) self.assertEqual(subset[0], local_particles[0]) self.assertEqual(subset[1], local_particles[3]) - + def test8(self): original = ParticlesWithBindingInterface() original.masses[1] = 10 instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_mass',(handler.NO_UNIT,), (units.kg, handler.ERROR_CODE)) - handler.add_method('get_next',(handler.INDEX,), (handler.LINK("particles"), handler.ERROR_CODE)) + handler.add_method('get_mass', (handler.NO_UNIT,), (units.kg, handler.ERROR_CODE)) + handler.add_method('get_next', (handler.INDEX,), (handler.LINK("particles"), handler.ERROR_CODE)) pickled_handler = pickle.dumps(handler) unpickled_handler = pickle.loads(pickled_handler) method1 = handler.get_attribute('get_mass', original.get_mass) @@ -1225,533 +1162,535 @@ def test8(self): original.masses[1] = 20 self.assertAlmostRelativeEquals(method1([1]), 20 | units.kg) self.assertAlmostRelativeEquals(method2([1]), 10 | units.kg) - + def test9(self): original = ParticlesWithBindingInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_mass',(handler.NO_UNIT,), (units.kg, handler.ERROR_CODE)) - handler.add_method('set_mass',(handler.NO_UNIT, units.kg,), (handler.ERROR_CODE,)) - handler.add_method('new_particle',(units.kg,), (handler.NO_UNIT, handler.ERROR_CODE)) - handler.add_method('delete_particle',(handler.NO_UNIT,), (handler.ERROR_CODE,)) - handler.add_method('get_number_of_particles',(), (handler.NO_UNIT, handler.ERROR_CODE,)) - + handler.add_method('get_mass', (handler.NO_UNIT,), (units.kg, handler.ERROR_CODE)) + handler.add_method('set_mass', (handler.NO_UNIT, units.kg,), (handler.ERROR_CODE,)) + handler.add_method('new_particle', (units.kg,), (handler.NO_UNIT, handler.ERROR_CODE)) + handler.add_method('delete_particle', (handler.NO_UNIT,), (handler.ERROR_CODE,)) + handler.add_method('get_number_of_particles', (), (handler.NO_UNIT, handler.ERROR_CODE,)) + handler = instance.get_handler('PARTICLES') handler.define_set('particles', 'id') handler.set_new('particles', 'new_particle') handler.set_delete('particles', 'delete_particle') handler.add_setter('particles', 'set_mass') - handler.add_getter('particles', 'get_mass', names = ('mass',)) - + handler.add_getter('particles', 'get_mass', names=('mass',)) + local_particles = datamodel.Particles(4) local_particles.mass = units.kg.new_quantity([3.0, 4.0, 5.0, 6.0]) - + remote_particles = instance.particles remote_particles.add_particles(local_particles) - + self.assertEqual(len(original.masses), 4) self.assertEqual(original.masses[0], 3.0) self.assertEqual(original.masses[3], 6.0) - + pickled_instance = pickle.dumps(instance) unpickled_instance = pickle.loads(pickled_instance) - + self.assertEqual(len(unpickled_instance.particles), 4) self.assertEqual(unpickled_instance.particles[1].mass, 4.0 | units.kg) - - + + class TestGridWithBinding(amusetest.TestCase): class TestInterface(object): - - shape = (11,5,5) - + + shape = (11, 5, 5) + def __init__(self): self.storage = numpy.arange( self.shape[0]*self.shape[1]*self.shape[2]).reshape(self.shape) - + def get_range(self): - return (0,self.shape[0]-1,0,self.shape[1]-1,0,self.shape[2]-1) - + return (0, self.shape[0]-1, 0, self.shape[1]-1, 0, self.shape[2]-1) + def get_position(self, i_s, j_s, k_s): return [numpy.asarray(i_s), numpy.asarray(j_s)] - - def get_a(self,i_s,j_s,k_s): - return [numpy.asarray([(self.storage[i][j][k]) for i,j,k in zip(i_s, j_s, k_s)]),] - + + def get_a(self, i_s, j_s, k_s): + return [numpy.asarray([(self.storage[i][j][k]) for i, j, k in zip(i_s, j_s, k_s)]),] + def set_a(self, i_s, j_s, k_s, values): index = 0 - for i,j,k in zip(i_s, j_s, k_s): + for i, j, k in zip(i_s, j_s, k_s): self.storage[i][j][k] = values[index].value_in(units.m) index += 1 - - - - + def test1(self): original = self.TestInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_a',(handler.INDEX, handler.INDEX,handler.INDEX,), (units.kg,)) - handler.add_method('set_a',(handler.INDEX, handler.INDEX,handler.INDEX, units.kg,), ()) - - self.assertEqual(instance.get_a([1],[2],[3]), [38] | units.kg) - + handler.add_method('get_a', (handler.INDEX, handler.INDEX, handler.INDEX,), (units.kg,)) + handler.add_method('set_a', (handler.INDEX, handler.INDEX, handler.INDEX, units.kg,), ()) + + self.assertEqual(instance.get_a([1], [2], [3]), [38] | units.kg) + handler = instance.get_handler('PARTICLES') handler.define_grid('grid',) - handler.add_setter('grid', 'set_a', names = ('mass',)) - handler.add_getter('grid', 'get_a', names = ('mass',)) - + handler.add_setter('grid', 'set_a', names=('mass',)) + handler.add_getter('grid', 'get_a', names=('mass',)) + grid = instance.grid - - + self.assertEqual(grid[1][2][3].mass, 38 | units.kg) self.assertEqual(grid[0:2][1][2][3].mass, 38 | units.kg) self.assertEqual(len(grid[1][2].mass), 5) - self.assertTrue(numpy.all(grid[1][2].mass == [35,36,37,38,39] | units.kg)) - - - + self.assertTrue(numpy.all(grid[1][2].mass == [35, 36, 37, 38, 39] | units.kg)) + def test2(self): original = self.TestInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_position',(handler.INDEX, handler.INDEX,handler.INDEX,), (units.m, units.m,)) - + handler.add_method('get_position', (handler.INDEX, handler.INDEX, handler.INDEX,), (units.m, units.m,)) + handler = instance.get_handler('PARTICLES') - handler.define_grid('grid', axes_names = ['x','y']) - handler.add_getter('grid', 'get_position', names = ('x','y',)) - + handler.define_grid('grid', axes_names=['x', 'y']) + handler.add_getter('grid', 'get_position', names=('x', 'y',)) + grid = instance.grid - - - self.assertEqual(grid[1][2][3].position, [1,2] |units.m) - self.assertEqual(grid[1][2][1].position, [1,2] |units.m) - self.assertEqual(grid[1][2][2].position, [1,2] |units.m) - self.assertEqual(grid[1][2][0].position, [1,2] |units.m) - self.assertEqual(grid[1][2].position, [[1,2],[1,2],[1,2],[1,2],[1,2]] |units.m) - self.assertEqual(grid[0][1][1].position, [0,1] |units.m) + + self.assertEqual(grid[1][2][3].position, [1, 2] | units.m) + self.assertEqual(grid[1][2][1].position, [1, 2] | units.m) + self.assertEqual(grid[1][2][2].position, [1, 2] | units.m) + self.assertEqual(grid[1][2][0].position, [1, 2] | units.m) + self.assertEqual(grid[1][2].position, [[1, 2], [1, 2], [1, 2], [1, 2], [1, 2]] | units.m) + self.assertEqual(grid[0][1][1].position, [0, 1] | units.m) def test3(self): original = self.TestInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_position',(handler.INDEX, handler.INDEX,handler.INDEX,), (units.m, units.m,)) - + handler.add_method('get_position', (handler.INDEX, handler.INDEX, handler.INDEX,), (units.m, units.m,)) + handler = instance.get_handler('PARTICLES') - handler.define_grid('grid', axes_names = ['x','y']) - handler.add_getter('grid', 'get_position', names = ('x','y',)) - + handler.define_grid('grid', axes_names=['x', 'y']) + handler.add_getter('grid', 'get_position', names=('x', 'y',)) + grid = instance.grid - + self.assertEqual(grid.__class__.__name__, "Grid") self.assertTrue(isinstance(grid, datamodel.RegularGrid)) - + def test4(self): original = self.TestInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_position',(handler.INDEX, handler.INDEX,handler.INDEX,), (units.m, units.m,)) - + handler.add_method('get_position', (handler.INDEX, handler.INDEX, handler.INDEX,), (units.m, units.m,)) + handler = instance.get_handler('PARTICLES') - handler.define_grid('grid', axes_names = ['x','y'], grid_class=datamodel.CartesianGrid) - handler.add_getter('grid', 'get_position', names = ('x','y',)) - + handler.define_grid('grid', axes_names=['x', 'y'], grid_class=datamodel.CartesianGrid) + handler.add_getter('grid', 'get_position', names=('x', 'y',)) + grid = instance.grid - + self.assertEqual(grid.__class__.__name__, "CartesianGrid") - + class TestGridWithBinding2(amusetest.TestCase): class TestInterface(object): - - shape = (11,5) - + + shape = (11, 5) + def __init__(self): self.storage = numpy.arange( self.shape[0]*self.shape[1]).reshape(self.shape) - + def get_range(self): - return (0,self.shape[0]-1,0,self.shape[1]-1) - + return (0, self.shape[0]-1, 0, self.shape[1]-1) + def get_position(self, i_s): return [numpy.asarray(i_s)] - - def get_a(self,i_s,j_s): - #print "indices:", i_s, j_s, k_s - #print "values:", numpy.asarray([(self.storage[i][j][k]) for i,j,k in zip(i_s, j_s, k_s)]) - return [numpy.asarray([(self.storage[i][j]) for i,j in zip(i_s, j_s)]),] - + + def get_a(self, i_s, j_s): + # print "indices:", i_s, j_s, k_s + # print "values:", numpy.asarray([(self.storage[i][j][k]) for i,j,k in zip(i_s, j_s, k_s)]) + return [numpy.asarray([(self.storage[i][j]) for i, j in zip(i_s, j_s)]),] + def set_a(self, i_s, j_s, values): index = 0 - for i,j in zip(i_s, j_s): + for i, j in zip(i_s, j_s): self.storage[i][j] = values[index] index += 1 - + def test1(self): original = self.TestInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_a',(handler.INDEX, handler.INDEX,), (units.kg,)) - handler.add_method('set_a',(handler.INDEX, handler.INDEX, units.kg,), ()) - - self.assertEqual(instance.get_a([1],[2]), [7] | units.kg) - + handler.add_method('get_a', (handler.INDEX, handler.INDEX,), (units.kg,)) + handler.add_method('set_a', (handler.INDEX, handler.INDEX, units.kg,), ()) + + self.assertEqual(instance.get_a([1], [2]), [7] | units.kg) + handler = instance.get_handler('PARTICLES') handler.define_grid('grid',) - handler.add_setter('grid', 'set_a', names = ('mass',)) - handler.add_getter('grid', 'get_a', names = ('mass',)) - + handler.add_setter('grid', 'set_a', names=('mass',)) + handler.add_getter('grid', 'get_a', names=('mass',)) + grid = instance.grid - - self.assertEqual(grid[1,2].mass, original.storage[1,2] | units.kg) + + self.assertEqual(grid[1, 2].mass, original.storage[1, 2] | units.kg) self.assertEqual(len(grid[1].mass), len(original.storage[1])) - - grid[1,1:].mass=[5. | units.kg]*4 - self.assertEqual(original.storage[1,1:],5) - self.assertEqual(grid[1,1:].mass, original.storage[1,1:] | units.kg) + grid[1, 1:].mass = [5. | units.kg]*4 + + self.assertEqual(original.storage[1, 1:], 5) + self.assertEqual(grid[1, 1:].mass, original.storage[1, 1:] | units.kg) + class TestGridWithBinding3(amusetest.TestCase): class TestInterface(object): - - shape = (11,5) - + + shape = (11, 5) + def __init__(self): self.storage = numpy.arange( self.shape[0]*self.shape[1]).reshape(self.shape) - + def get_range(self): - return (0,self.shape[0]-1) + return (0, self.shape[0]-1) + def get_range2(self): - return (0,self.shape[1]-1) - - def get_a(self,i_s,j_s): - return [numpy.asarray([(self.storage[i][j]) for i,j in zip(i_s, j_s)]),] - + return (0, self.shape[1]-1) + + def get_a(self, i_s, j_s): + return [numpy.asarray([(self.storage[i][j]) for i, j in zip(i_s, j_s)]),] + def set_a(self, i_s, j_s, values): - for i,j,val in zip(i_s, j_s,values): + for i, j, val in zip(i_s, j_s, values): self.storage[i][j] = val - + def test1(self): original = self.TestInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_a',(handler.INDEX, handler.INDEX,), (units.kg,)) - handler.add_method('set_a',(handler.INDEX, handler.INDEX, units.kg,), ()) - - self.assertEqual(instance.get_a([1],[2]), [7] | units.kg) - + handler.add_method('get_a', (handler.INDEX, handler.INDEX,), (units.kg,)) + handler.add_method('set_a', (handler.INDEX, handler.INDEX, units.kg,), ()) + + self.assertEqual(instance.get_a([1], [2]), [7] | units.kg) + handler = instance.get_handler('PARTICLES') handler.define_grid('grid',) - handler.add_gridded_setter('grid', 'set_a','get_range2', names = ('mass',)) - handler.add_gridded_getter('grid', 'get_a','get_range2', names = ('mass',)) - + handler.add_gridded_setter('grid', 'set_a', 'get_range2', names=('mass',)) + handler.add_gridded_getter('grid', 'get_a', 'get_range2', names=('mass',)) + grid = instance.grid - + self.assertEqual(grid[1].mass, original.storage[1] | units.kg) self.assertEqual(len(grid[1].mass), len(original.storage[1])) self.assertEqual(grid[2:4].mass, original.storage[2:4] | units.kg) self.assertEqual(grid[-3:].mass, original.storage[-3:] | units.kg) - - grid[1].mass=[5.]*5 | units.kg - self.assertEqual(original.storage[1],5) + grid[1].mass = [5.]*5 | units.kg + + self.assertEqual(original.storage[1], 5) self.assertEqual(grid[1].mass, original.storage[1] | units.kg) + class TestGridWithBinding4(amusetest.TestCase): class TestInterface(object): - - shape = (3,4,5) - + + shape = (3, 4, 5) + def __init__(self): self.storage = numpy.arange( self.shape[0]*self.shape[1]*self.shape[2]).reshape(self.shape) - + def get_range(self): return (0, self.shape[0]-1, 0, self.shape[1]-1) + def get_range2(self): return (0, self.shape[2]-1) - + def get_a(self, i_s, j_s, k_s): - return [numpy.asarray([self.storage[i,j,k] for i,j,k in zip(i_s, j_s, k_s)]),] - + return [numpy.asarray([self.storage[i, j, k] for i, j, k in zip(i_s, j_s, k_s)]),] + def set_a(self, i_s, j_s, k_s, values): - for i,j,k,val in zip(i_s, j_s,k_s,values): - self.storage[i,j,k] = val - + for i, j, k, val in zip(i_s, j_s, k_s, values): + self.storage[i, j, k] = val + def test1(self): original = self.TestInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_a',(handler.INDEX, handler.INDEX, handler.INDEX,), (units.kg,)) - handler.add_method('set_a',(handler.INDEX, handler.INDEX,handler.INDEX, units.kg,), ()) - - self.assertEqual(instance.get_a([1],[2],[3]), [33] | units.kg) - + handler.add_method('get_a', (handler.INDEX, handler.INDEX, handler.INDEX,), (units.kg,)) + handler.add_method('set_a', (handler.INDEX, handler.INDEX, handler.INDEX, units.kg,), ()) + + self.assertEqual(instance.get_a([1], [2], [3]), [33] | units.kg) + handler = instance.get_handler('PARTICLES') handler.define_grid('grid',) - handler.add_gridded_setter('grid', 'set_a','get_range2', names = ('mass',)) - handler.add_gridded_getter('grid', 'get_a','get_range2', names = ('mass',)) - + handler.add_gridded_setter('grid', 'set_a', 'get_range2', names=('mass',)) + handler.add_gridded_getter('grid', 'get_a', 'get_range2', names=('mass',)) + grid = instance.grid - - self.assertEqual(grid[1,1].mass, original.storage[1,1] | units.kg) - self.assertEqual(grid[0:2,1:3].mass, original.storage[0:2,1:3] | units.kg) + + self.assertEqual(grid[1, 1].mass, original.storage[1, 1] | units.kg) + self.assertEqual(grid[0:2, 1:3].mass, original.storage[0:2, 1:3] | units.kg) self.assertEqual(len(grid[1].mass), len(original.storage[1])) self.assertEqual(grid[2:4].mass, original.storage[2:4] | units.kg) self.assertEqual(grid[-3:].mass, original.storage[-3:] | units.kg) - - grid[1].mass=numpy.ones((4,5))*5 | units.kg - self.assertEqual(original.storage[1],5) + grid[1].mass = numpy.ones((4, 5))*5 | units.kg + + self.assertEqual(original.storage[1], 5) self.assertEqual(grid[1].mass, original.storage[1] | units.kg) + class TestGridWithBinding5(amusetest.TestCase): class TestInterface(object): - - shape = (3,4,5,6) - + + shape = (3, 4, 5, 6) + def __init__(self): self.storage = numpy.arange( - numpy.product(self.shape)).reshape(self.shape) - + numpy.prod(self.shape)).reshape(self.shape) + def get_range(self): return (0, self.shape[0]-1, 0, self.shape[1]-1) + def get_range2(self): return (0, self.shape[2]-1, 0, self.shape[3]-1) - - def get_a(self, i_s, j_s, k_s,l_s): - return [numpy.asarray([self.storage[i,j,k,l] for i,j,k,l in zip(i_s, j_s, k_s,l_s)]),] - - def set_a(self, i_s, j_s, k_s,l_s, values): - for i,j,k,l,val in zip(i_s, j_s,k_s,l_s,values): - self.storage[i,j,k,l] = val - + + def get_a(self, i_s, j_s, k_s, l_s): + return [numpy.asarray([self.storage[i, j, k, l] for i, j, k, l in zip(i_s, j_s, k_s, l_s)]),] + + def set_a(self, i_s, j_s, k_s, l_s, values): + for i, j, k, l, val in zip(i_s, j_s, k_s, l_s, values): + self.storage[i, j, k, l] = val + def test1(self): original = self.TestInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_a',(handler.INDEX, handler.INDEX,handler.INDEX,handler.INDEX,), (units.kg,)) - handler.add_method('set_a',(handler.INDEX, handler.INDEX,handler.INDEX,handler.INDEX, units.kg,), ()) - - self.assertEqual(instance.get_a([1],[2],[3],[4]), original.storage[1,2,3,4] | units.kg) - + handler.add_method('get_a', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX,), (units.kg,)) + handler.add_method('set_a', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, units.kg,), ()) + + self.assertEqual(instance.get_a([1], [2], [3], [4]), original.storage[1, 2, 3, 4] | units.kg) + handler = instance.get_handler('PARTICLES') handler.define_grid('grid',) - handler.add_gridded_setter('grid', 'set_a','get_range2', names = ('mass',)) - handler.add_gridded_getter('grid', 'get_a','get_range2', names = ('mass',)) - + handler.add_gridded_setter('grid', 'set_a', 'get_range2', names=('mass',)) + handler.add_gridded_getter('grid', 'get_a', 'get_range2', names=('mass',)) + grid = instance.grid - - self.assertEqual(grid[1,1].mass, original.storage[1,1] | units.kg) - self.assertEqual(grid[0:2,1:3].mass, original.storage[0:2,1:3] | units.kg) + + self.assertEqual(grid[1, 1].mass, original.storage[1, 1] | units.kg) + self.assertEqual(grid[0:2, 1:3].mass, original.storage[0:2, 1:3] | units.kg) self.assertEqual(len(grid[1].mass), len(original.storage[1])) self.assertEqual(grid[2:4].mass, original.storage[2:4] | units.kg) self.assertEqual(grid[-3:].mass, original.storage[-3:] | units.kg) - - grid[1].mass=numpy.ones((4,5,6))*5 | units.kg - self.assertEqual(original.storage[1],5) + grid[1].mass = numpy.ones((4, 5, 6))*5 | units.kg + + self.assertEqual(original.storage[1], 5) self.assertEqual(grid[1].mass, original.storage[1] | units.kg) # attempt to test string returns, needs improvement + + class TestGridWithBinding6(amusetest.TestCase): class TestInterface(object): - - shape = (3,4,5,6) - + + shape = (3, 4, 5, 6) + def __init__(self): self.storage = numpy.arange( - numpy.product(self.shape)).reshape(self.shape).astype(numpy.dtype(str)) - + numpy.prod(self.shape)).reshape(self.shape).astype(numpy.dtype(str)) + def get_range(self): return (0, self.shape[0]-1, 0, self.shape[1]-1) + def get_range2(self): return (0, self.shape[2]-1, 0, self.shape[3]-1) - - def get_a(self, i_s, j_s, k_s,l_s): - return [numpy.asarray([self.storage[i,j,k,l] for i,j,k,l in zip(i_s, j_s, k_s,l_s)]),] - - def set_a(self, i_s, j_s, k_s,l_s, values): - for i,j,k,l,val in zip(i_s, j_s,k_s,l_s,values): - self.storage[i,j,k,l] = val - + + def get_a(self, i_s, j_s, k_s, l_s): + return [numpy.asarray([self.storage[i, j, k, l] for i, j, k, l in zip(i_s, j_s, k_s, l_s)]),] + + def set_a(self, i_s, j_s, k_s, l_s, values): + for i, j, k, l, val in zip(i_s, j_s, k_s, l_s, values): + self.storage[i, j, k, l] = val + def test1(self): original = self.TestInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_a',(handler.INDEX, handler.INDEX,handler.INDEX,handler.INDEX,), (handler.NO_UNIT,)) - handler.add_method('set_a',(handler.INDEX, handler.INDEX,handler.INDEX,handler.INDEX, handler.NO_UNIT,), ()) - - self.assertEqual(instance.get_a([1],[2],[3],[4]), original.storage[1,2,3,4] ) - + handler.add_method('get_a', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX,), (handler.NO_UNIT,)) + handler.add_method('set_a', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.NO_UNIT,), ()) + + self.assertEqual(instance.get_a([1], [2], [3], [4]), original.storage[1, 2, 3, 4]) + handler = instance.get_handler('PARTICLES') handler.define_grid('grid',) - handler.add_gridded_setter('grid', 'set_a','get_range2', names = ('mass',)) - handler.add_gridded_getter('grid', 'get_a','get_range2', names = ('mass',)) - + handler.add_gridded_setter('grid', 'set_a', 'get_range2', names=('mass',)) + handler.add_gridded_getter('grid', 'get_a', 'get_range2', names=('mass',)) + grid = instance.grid - - self.assertEqual(grid[1,1].mass, original.storage[1,1] ) - self.assertEqual(grid[0:2,1:3].mass, original.storage[0:2,1:3]) + + self.assertEqual(grid[1, 1].mass, original.storage[1, 1]) + self.assertEqual(grid[0:2, 1:3].mass, original.storage[0:2, 1:3]) self.assertEqual(len(grid[1].mass), len(original.storage[1])) - self.assertEqual(grid[2:4].mass, original.storage[2:4] ) - self.assertEqual(grid[-3:].mass, original.storage[-3:] ) - - grid[1].mass=numpy.ones((4,5,6))*5 + self.assertEqual(grid[2:4].mass, original.storage[2:4]) + self.assertEqual(grid[-3:].mass, original.storage[-3:]) + + grid[1].mass = numpy.ones((4, 5, 6))*5 # self.assertEquals(original.storage[1],'5') self.assertEqual(grid[1].mass, original.storage[1]) + class TestGridWithBinding7(amusetest.TestCase): class TestInterface(object): - + shape = () - + def __init__(self): self.storage = 123. - + def get_range(self): return () - + def get_a(self): return self.storage - + def set_a(self, value): self.storage = value - + def test1(self): original = self.TestInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_a',(), (units.kg,)) - handler.add_method('set_a',(units.kg,), ()) - + handler.add_method('get_a', (), (units.kg,)) + handler.add_method('set_a', (units.kg,), ()) + handler = instance.get_handler('PARTICLES') handler.define_grid('grid',) - handler.add_setter('grid', 'set_a', names = ('mass',)) - handler.add_getter('grid', 'get_a', names = ('mass',)) - + handler.add_setter('grid', 'set_a', names=('mass',)) + handler.add_getter('grid', 'get_a', names=('mass',)) + grid = instance.grid self.assertEqual(grid.mass, 123 | units.kg) def test2(self): original = self.TestInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_a',(), (units.kg,)) - handler.add_method('set_a',(units.kg,), ()) - + handler.add_method('get_a', (), (units.kg,)) + handler.add_method('set_a', (units.kg,), ()) + handler = instance.get_handler('PARTICLES') handler.define_grid('grid',) - handler.add_setter('grid', 'set_a', names = ('mass',)) - handler.add_getter('grid', 'get_a', names = ('mass',)) - + handler.add_setter('grid', 'set_a', names=('mass',)) + handler.add_getter('grid', 'get_a', names=('mass',)) + grid = instance.grid - grid.mass=321| units.kg - self.assertEqual(original.storage,321) + grid.mass = 321 | units.kg + self.assertEqual(original.storage, 321) self.assertEqual(grid.mass, 321 | units.kg) + class TestGridWithBinding8(amusetest.TestCase): class TestInterface(object): - + shape = () - + def __init__(self): self.storage1 = 12. self.storage2 = 123. - + def get_range(self): return () - + def get_a(self): return self.storage1, self.storage2 - + def set_a(self, value1, value2): self.storage1 = value1 self.storage2 = value2 - + def test1(self): original = self.TestInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_a',(), (units.kg,units.m)) - handler.add_method('set_a',(units.kg,units.m), ()) - + handler.add_method('get_a', (), (units.kg, units.m)) + handler.add_method('set_a', (units.kg, units.m), ()) + handler = instance.get_handler('PARTICLES') handler.define_grid('grid',) - handler.add_setter('grid', 'set_a', names = ('mass','l')) - handler.add_getter('grid', 'get_a', names = ('mass','l')) - + handler.add_setter('grid', 'set_a', names=('mass', 'l')) + handler.add_getter('grid', 'get_a', names=('mass', 'l')) + grid = instance.grid self.assertEqual(grid.mass, 12 | units.kg) self.assertEqual(grid.l, 123 | units.m) def test2(self): original = self.TestInterface() - + instance = interface.InCodeComponentImplementation(original) - + handler = instance.get_handler('METHOD') - handler.add_method('get_a',(), (units.kg,units.m)) - handler.add_method('set_a',(units.kg,units.m), ()) - + handler.add_method('get_a', (), (units.kg, units.m)) + handler.add_method('set_a', (units.kg, units.m), ()) + handler = instance.get_handler('PARTICLES') handler.define_grid('grid',) - handler.add_setter('grid', 'set_a', names = ('mass','l')) - handler.add_getter('grid', 'get_a', names = ('mass','l')) - + handler.add_setter('grid', 'set_a', names=('mass', 'l')) + handler.add_getter('grid', 'get_a', names=('mass', 'l')) + grid = instance.grid - grid1=grid.copy() + grid1 = grid.copy() + + grid1.mass = 321 | units.kg + grid1.l = 32 | units.m - grid1.mass=321| units.kg - grid1.l=32| units.m - grid1.new_channel_to(grid).copy_all_attributes() - - self.assertEqual(original.storage1,321) - self.assertEqual(original.storage2,32) + + self.assertEqual(original.storage1, 321) + self.assertEqual(original.storage2, 32) self.assertEqual(grid.mass, 321 | units.kg) self.assertEqual(grid.l, 32 | units.m) - - + class CodeInterfaceAndLegacyFunctionsTest(amusetest.TestCase): - - + def test1(self): class TestClass(object): - + @legacy_function def echo_inputs(): function = LegacyFunctionSpecification() @@ -1761,28 +1700,26 @@ def echo_inputs(): function.addParameter('output2', dtype='d', direction=function.IN) function.result_type = 'i' return function - + original = TestClass() instance = interface.InCodeComponentImplementation(original) - - + handler = instance.get_handler('METHOD') handler.add_method('echo_inputs', (units.m, units.s), (units.s, handler.ERROR_CODE)) - self.assertRaises(exceptions.AmuseException, lambda: instance.echo_inputs, - expected_message = "Incorrect definition of method 'echo_inputs' of class 'InCodeComponentImplementation', " + self.assertRaises(exceptions.AmuseException, lambda: instance.echo_inputs, + expected_message="Incorrect definition of method 'echo_inputs' of class 'InCodeComponentImplementation', " "the number of outputs do not match, expected 3, actual 2.") - + instance = interface.InCodeComponentImplementation(original) handler = instance.get_handler('METHOD') handler.add_method('echo_inputs', (units.m, units.s), (units.s, units.m, units.s, handler.ERROR_CODE)) - self.assertRaises(exceptions.AmuseException, lambda: instance.echo_inputs, - expected_message = "Incorrect definition of method 'echo_inputs' of class 'InCodeComponentImplementation', " + self.assertRaises(exceptions.AmuseException, lambda: instance.echo_inputs, + expected_message="Incorrect definition of method 'echo_inputs' of class 'InCodeComponentImplementation', " "the number of outputs do not match, expected 3, actual 4.") - def test2(self): class TestClass(object): - + @legacy_function def echo_inputs(): function = LegacyFunctionSpecification() @@ -1792,23 +1729,21 @@ def echo_inputs(): function.addParameter('output2', dtype='d', direction=function.IN) function.result_type = 'i' return function - + original = TestClass() - + instance = interface.InCodeComponentImplementation(original) - - + handler = instance.get_handler('METHOD') handler.add_method('echo_inputs', (units.m), (units.s, units.m, handler.ERROR_CODE), ) - self.assertRaises(exceptions.AmuseException, lambda: instance.echo_inputs, - expected_message = "Incorrect definition of method 'echo_inputs' of class 'InCodeComponentImplementation', " + self.assertRaises(exceptions.AmuseException, lambda: instance.echo_inputs, + expected_message="Incorrect definition of method 'echo_inputs' of class 'InCodeComponentImplementation', " "the number of inputs do not match, expected 2, actual 1.") - - + def test3(self): class TestClass(object): - async_request=None - + async_request = None + @legacy_function def echo_inputs(): function = LegacyFunctionSpecification() @@ -1818,7 +1753,7 @@ def echo_inputs(): function.addParameter('output2', dtype='d', direction=function.IN) function.result_type = 'i' return function - + original = TestClass() self.assertRaises(exceptions.CodeException, original.echo_inputs, 1, 2, - expected_message = "Exception when calling function 'echo_inputs', of code 'TestClass', exception was ''TestClass' object has no attribute 'channel''") + expected_message="Exception when calling function 'echo_inputs', of code 'TestClass', exception was ''TestClass' object has no attribute 'channel''") diff --git a/src/amuse/test/suite/core_tests/test_io.py b/src/amuse/test/suite/core_tests/test_io.py index 37e0dc2346..447ee5461e 100644 --- a/src/amuse/test/suite/core_tests/test_io.py +++ b/src/amuse/test/suite/core_tests/test_io.py @@ -8,25 +8,27 @@ from amuse.units import nbody_system from amuse.units import units from amuse import datamodel -class TestFileFormatProcessor(base.FileFormatProcessor): + + +class ForTestFileFormatProcessor(base.FileFormatProcessor): """ Save files in a test format - + long description """ - provided_formats = ['test','123'] + provided_formats = ['test', '123'] instance = None - - def __init__(self, filename = None, set=None, format=None): + + def __init__(self, filename=None, set=None, format=None): base.FileFormatProcessor.__init__(self, filename, set, format) - TestFileFormatProcessor.instance = self + ForTestFileFormatProcessor.instance = self self.stored = False - + @base.format_option def add_comma(self): """if True will add a comma between each value""" return True - + @base.format_option def save_fast(self): """if True will save faster but less accurate""" @@ -34,37 +36,38 @@ def save_fast(self): def store(self): self.stored = True - + def load(self): return 10 - + + class FrameworkTests(amusetest.TestCase): - + def test1(self): - options = TestFileFormatProcessor.get_options() + options = ForTestFileFormatProcessor.get_options() self.assertTrue('add_comma' in options) self.assertTrue('save_fast' in options) - TestFileFormatProcessor.register() + ForTestFileFormatProcessor.register() base.write_set_to_file(None, "test.txt", format="123") - self.assertEqual(TestFileFormatProcessor.instance.set, None) - self.assertEqual(TestFileFormatProcessor.instance.filename, "test.txt") - self.assertEqual(TestFileFormatProcessor.instance.format, "123") - self.assertTrue(TestFileFormatProcessor.instance.stored) - self.assertTrue(TestFileFormatProcessor.instance.add_comma) - + self.assertEqual(ForTestFileFormatProcessor.instance.set, None) + self.assertEqual(ForTestFileFormatProcessor.instance.filename, "test.txt") + self.assertEqual(ForTestFileFormatProcessor.instance.format, "123") + self.assertTrue(ForTestFileFormatProcessor.instance.stored) + self.assertTrue(ForTestFileFormatProcessor.instance.add_comma) + def test2(self): - TestFileFormatProcessor.register() - base.write_set_to_file(None, "test.txt", format="123", add_comma = False) - self.assertFalse(TestFileFormatProcessor.instance.add_comma) - + ForTestFileFormatProcessor.register() + base.write_set_to_file(None, "test.txt", format="123", add_comma=False) + self.assertFalse(ForTestFileFormatProcessor.instance.add_comma) + def test3(self): - TestFileFormatProcessor.register() - documentation = base.write_set_to_file.__doc__ + ForTestFileFormatProcessor.register() + documentation = base.write_set_to_file.__doc__ self.assertTrue("**123**,\n Save files in a test format" in documentation) - + def test4(self): options = base.get_options_for_format('123') - options.sort(key = lambda x: x[0]) + options.sort(key=lambda x: x[0]) name, description, default = options[0] self.assertEqual(name, 'add_comma') self.assertEqual(description, 'if True will add a comma between each value') @@ -73,98 +76,96 @@ def test4(self): self.assertEqual(name, 'save_fast') self.assertEqual(description, 'if True will save faster but less accurate') self.assertEqual(default, False) - + def test5(self): - self.assertRaises(AmuseException, io.read_set_from_file, "non_existent","test", - expected_message = "IO exception: Error: file 'non_existent' does not exist.") - + self.assertRaises(AmuseException, io.read_set_from_file, "non_existent", "test", + expected_message="IO exception: Error: file 'non_existent' does not exist.") + processor = base.FileFormatProcessor(format="test") - self.assertRaises(base.CannotSaveException, processor.store, - expected_message = "You tried to save a file with fileformat 'test', but" + self.assertRaises(base.CannotSaveException, processor.store, + expected_message="You tried to save a file with fileformat 'test', but" " this format is not supported for writing files") - - self.assertRaises(base.CannotLoadException, processor.load, - expected_message = "You tried to load a file with fileformat 'test', but" + + self.assertRaises(base.CannotLoadException, processor.load, + expected_message="You tried to load a file with fileformat 'test', but" " this format is not supported for reading files") class FormatTests(amusetest.TestCase): - + def test1(self): x = datamodel.Particles(2) x.mass = [1.0, 2.0] | nbody_system.mass x.radius = [3.0, 4.0] | nbody_system.length - x.position = [[1,2,3], [3,5,6]] | nbody_system.length - x.velocity = [[1,2,3], [3,5,6]] | nbody_system.speed - io.write_set_to_file(x, "test.tsf","tsf") - y = io.read_set_from_file("test.tsf","tsf") - + x.position = [[1, 2, 3], [3, 5, 6]] | nbody_system.length + x.velocity = [[1, 2, 3], [3, 5, 6]] | nbody_system.speed + io.write_set_to_file(x, "test.tsf", "tsf") + y = io.read_set_from_file("test.tsf", "tsf") + self.assertAlmostEqual(x.mass, y.mass, 8) # self.assertAlmostEquals(x.radius, y.radius, 8) - self.assertAlmostEqual(x.position, y.position,8) - self.assertAlmostEqual(x.velocity, y.velocity,8) + self.assertAlmostEqual(x.position, y.position, 8) + self.assertAlmostEqual(x.velocity, y.velocity, 8) os.remove("test.tsf") - - + def test2(self): x = datamodel.Particles(2) x.mass = [1.0, 2.0] | nbody_system.mass x.radius = [3.0, 4.0] | nbody_system.length - x.position = [[1,2,3], [3,5,6]] | nbody_system.length - x.velocity = [[1,2,3], [3,5,6]] | nbody_system.speed - io.write_set_to_file(x, "test.dyn","dyn") - y = io.read_set_from_file("test.dyn","dyn") - + x.position = [[1, 2, 3], [3, 5, 6]] | nbody_system.length + x.velocity = [[1, 2, 3], [3, 5, 6]] | nbody_system.speed + io.write_set_to_file(x, "test.dyn", "dyn") + y = io.read_set_from_file("test.dyn", "dyn") + self.assertAlmostEqual(x.mass, y.mass, 8) - self.assertAlmostEqual(x.position, y.position,8) - self.assertAlmostEqual(x.velocity, y.velocity,8) - self.assertRaises(AttributeError, lambda: y.radius, - expected_message = "You tried to access attribute 'radius' but this " + self.assertAlmostEqual(x.position, y.position, 8) + self.assertAlmostEqual(x.velocity, y.velocity, 8) + self.assertRaises(AttributeError, lambda: y.radius, + expected_message="You tried to access attribute 'radius' but this " "attribute is not defined for this set.") - + os.remove("test.dyn") - + def test3(self): x = datamodel.Particles(2) convert = nbody_system.nbody_to_si(1 | units.kg, 2 | units.m) x.mass = [1.0, 2.0] | units.kg x.radius = [3.0, 4.0] | units.m - x.position = [[1,2,3], [3,5,6]] | units.m - x.velocity = [[1,2,3], [3,5,6]] | units.m / units.s - io.write_set_to_file(x, "test_unit.dyn","dyn", nbody_to_si_converter = convert) - y = io.read_set_from_file("test_unit.dyn","dyn", nbody_to_si_converter = convert) - + x.position = [[1, 2, 3], [3, 5, 6]] | units.m + x.velocity = [[1, 2, 3], [3, 5, 6]] | units.m / units.s + io.write_set_to_file(x, "test_unit.dyn", "dyn", nbody_to_si_converter=convert) + y = io.read_set_from_file("test_unit.dyn", "dyn", nbody_to_si_converter=convert) + self.assertAlmostEqual(x.mass, y.mass, 8) - self.assertAlmostEqual(x.position, y.position,8) - self.assertAlmostEqual(x.velocity, y.velocity,8) - self.assertRaises(AttributeError, lambda: y.radius, - expected_message = "You tried to access attribute 'radius' but this " + self.assertAlmostEqual(x.position, y.position, 8) + self.assertAlmostEqual(x.velocity, y.velocity, 8) + self.assertRaises(AttributeError, lambda: y.radius, + expected_message="You tried to access attribute 'radius' but this " "attribute is not defined for this set.") - + os.remove("test_unit.dyn") - - + def test4(self): - + x = datamodel.Particles(2) convert = nbody_system.nbody_to_si(1 | units.kg, 2 | units.m) x.mass = [1.0, 2.0] | units.kg x.radius = [3.0, 4.0] | units.m - x.position = [[1,2,3], [3,5,6]] | units.m - x.velocity = [[1,2,3], [3,5,6]] | units.m / units.s - io.write_set_to_file(x, "test_unit.tsf","tsf", nbody_to_si_converter = convert) - y = io.read_set_from_file("test_unit.tsf","tsf", nbody_to_si_converter = convert) - + x.position = [[1, 2, 3], [3, 5, 6]] | units.m + x.velocity = [[1, 2, 3], [3, 5, 6]] | units.m / units.s + io.write_set_to_file(x, "test_unit.tsf", "tsf", nbody_to_si_converter=convert) + y = io.read_set_from_file("test_unit.tsf", "tsf", nbody_to_si_converter=convert) + self.assertAlmostEqual(x.mass, y.mass, 8) - self.assertAlmostEqual(x.position, y.position,8) - self.assertAlmostEqual(x.velocity, y.velocity,8) - self.assertRaises(AttributeError, lambda: y.radius, - expected_message = "You tried to access attribute 'radius' but this " + self.assertAlmostEqual(x.position, y.position, 8) + self.assertAlmostEqual(x.velocity, y.velocity, 8) + self.assertRaises(AttributeError, lambda: y.radius, + expected_message="You tried to access attribute 'radius' but this " "attribute is not defined for this set.") - + os.remove("test_unit.tsf") - + def test5(self): print("Testing HDF5 io") if os.path.exists("test_unit.hdf5"): @@ -172,41 +173,41 @@ def test5(self): x = datamodel.Particles(2) x.mass = [1.0, 2.0] | units.kg x.radius = [3.0, 4.0] | units.m - x.position = [[1,2,3], [3,5,6]] | units.m - x.velocity = [[1,2,3], [3,5,6]] | units.m / units.s - io.write_set_to_file(x, "test_unit.hdf5","hdf5") - y = io.read_set_from_file("test_unit.hdf5","hdf5") - + x.position = [[1, 2, 3], [3, 5, 6]] | units.m + x.velocity = [[1, 2, 3], [3, 5, 6]] | units.m / units.s + io.write_set_to_file(x, "test_unit.hdf5", "hdf5") + y = io.read_set_from_file("test_unit.hdf5", "hdf5") + self.assertAlmostEqual(x.mass, y.mass, 8) self.assertAlmostEqual(x.radius, y.radius, 8) - self.assertAlmostEqual(x.position, y.position,8) - self.assertAlmostEqual(x.velocity, y.velocity,8) - + self.assertAlmostEqual(x.position, y.position, 8) + self.assertAlmostEqual(x.velocity, y.velocity, 8) + os.remove("test_unit.hdf5") - + def test6(self): print("Testing HDF5 io, with options") if os.path.exists("test_unit.hdf5"): os.remove("test_unit.hdf5") x = datamodel.Particles(2) x.mass = [1.0, 2.0] | units.kg - io.write_set_to_file(x, "test_unit.hdf5","hdf5", version="1.0") + io.write_set_to_file(x, "test_unit.hdf5", "hdf5", version="1.0") x.mass = [10.0, 20.0] | units.kg - io.write_set_to_file(x, "test_unit.hdf5","hdf5", append_to_file=True, version="1.0") + io.write_set_to_file(x, "test_unit.hdf5", "hdf5", append_to_file=True, version="1.0") x.mass = [100.0, 200.0] | units.kg - io.write_set_to_file(x, "test_unit.hdf5","hdf5", version="1.0", append_to_file=True) - y = io.read_set_from_file("test_unit.hdf5","hdf5", copy_history=False, close_file=False) - y = y.previous_state() # weirdness for version="1.0" + io.write_set_to_file(x, "test_unit.hdf5", "hdf5", version="1.0", append_to_file=True) + y = io.read_set_from_file("test_unit.hdf5", "hdf5", copy_history=False, close_file=False) + y = y.previous_state() # weirdness for version="1.0" self.assertAlmostEqual(x.mass, y.mass, 8) self.assertAlmostEqual([10.0, 20.0] | units.kg, y.previous_state().mass, 8) self.assertAlmostEqual([1.0, 2.0] | units.kg, y.previous_state().previous_state().mass, 8) self.assertEqual(y.previous_state().previous_state().previous_state(), None) - - io.write_set_to_file(x, "test_unit.hdf5","hdf5", append_to_file=False, overwrite_file=True,version="1.0") - y = io.read_set_from_file("test_unit.hdf5","hdf5") + + io.write_set_to_file(x, "test_unit.hdf5", "hdf5", append_to_file=False, overwrite_file=True, version="1.0") + y = io.read_set_from_file("test_unit.hdf5", "hdf5") self.assertAlmostEqual(x.mass, y.mass, 8) self.assertEqual(y.previous_state().previous_state(), None) - + os.remove("test_unit.hdf5") def test6b(self): @@ -215,23 +216,23 @@ def test6b(self): os.remove("test_unit.hdf5") x = datamodel.Particles(2) x.mass = [1.0, 2.0] | units.kg - io.write_set_to_file(x, "test_unit.hdf5","hdf5", version="1.0") + io.write_set_to_file(x, "test_unit.hdf5", "hdf5", version="1.0") x.mass = [10.0, 20.0] | units.kg - io.write_set_to_file(x, "test_unit.hdf5","hdf5", append_to_file=True, version="1.0") + io.write_set_to_file(x, "test_unit.hdf5", "hdf5", append_to_file=True, version="1.0") x.mass = [100.0, 200.0] | units.kg - io.write_set_to_file(x, "test_unit.hdf5","hdf5", version="1.0", append_to_file=True) - y = io.read_set_from_file("test_unit.hdf5","hdf5", copy_history=True, ) - y = y.previous_state() # weirdness for version="1.0" + io.write_set_to_file(x, "test_unit.hdf5", "hdf5", version="1.0", append_to_file=True) + y = io.read_set_from_file("test_unit.hdf5", "hdf5", copy_history=True, ) + y = y.previous_state() # weirdness for version="1.0" self.assertAlmostEqual(x.mass, y.mass, 8) self.assertAlmostEqual([10.0, 20.0] | units.kg, y.previous_state().mass, 8) self.assertAlmostEqual([1.0, 2.0] | units.kg, y.previous_state().previous_state().mass, 8) self.assertEqual(y.previous_state().previous_state().previous_state(), None) - - io.write_set_to_file(x, "test_unit.hdf5","hdf5", append_to_file=False, overwrite_file=True,version="1.0") - y = io.read_set_from_file("test_unit.hdf5","hdf5") + + io.write_set_to_file(x, "test_unit.hdf5", "hdf5", append_to_file=False, overwrite_file=True, version="1.0") + y = io.read_set_from_file("test_unit.hdf5", "hdf5") self.assertAlmostEqual(x.mass, y.mass, 8) self.assertEqual(y.previous_state().previous_state(), None) - + os.remove("test_unit.hdf5") def test6c(self): @@ -240,22 +241,22 @@ def test6c(self): os.remove("test_unit.hdf5") x = datamodel.Particles(2) x.mass = [1.0, 2.0] | units.kg - io.write_set_to_file(x, "test_unit.hdf5","hdf5", version="2.0") + io.write_set_to_file(x, "test_unit.hdf5", "hdf5", version="2.0") x.mass = [10.0, 20.0] | units.kg - io.write_set_to_file(x, "test_unit.hdf5","hdf5", append_to_file=True, version="2.0") + io.write_set_to_file(x, "test_unit.hdf5", "hdf5", append_to_file=True, version="2.0") x.mass = [100.0, 200.0] | units.kg - io.write_set_to_file(x, "test_unit.hdf5","hdf5", append_to_file=True, version="2.0") - y = io.read_set_from_file("test_unit.hdf5","hdf5", close_file=False, copy_history=False) + io.write_set_to_file(x, "test_unit.hdf5", "hdf5", append_to_file=True, version="2.0") + y = io.read_set_from_file("test_unit.hdf5", "hdf5", close_file=False, copy_history=False) self.assertAlmostEqual(x.mass, y.mass, 8) self.assertAlmostEqual([10.0, 20.0] | units.kg, y.previous_state().mass, 8) self.assertAlmostEqual([1.0, 2.0] | units.kg, y.previous_state().previous_state().mass, 8) self.assertEqual(y.previous_state().previous_state().previous_state(), None) - - io.write_set_to_file(x, "test_unit.hdf5","hdf5", append_to_file=False, overwrite_file=True, version="2.0") - y = io.read_set_from_file("test_unit.hdf5","hdf5", copy_history=False) + + io.write_set_to_file(x, "test_unit.hdf5", "hdf5", append_to_file=False, overwrite_file=True, version="2.0") + y = io.read_set_from_file("test_unit.hdf5", "hdf5", copy_history=False) self.assertAlmostEqual(x.mass, y.mass, 8) self.assertEqual(y.previous_state(), None) - + os.remove("test_unit.hdf5") def test6d(self): @@ -264,25 +265,24 @@ def test6d(self): os.remove("test_unit.hdf5") x = datamodel.Particles(2) x.mass = [1.0, 2.0] | units.kg - io.write_set_to_file(x, "test_unit.hdf5","hdf5", version="2.0") + io.write_set_to_file(x, "test_unit.hdf5", "hdf5", version="2.0") x.mass = [10.0, 20.0] | units.kg - io.write_set_to_file(x, "test_unit.hdf5","hdf5", append_to_file=True, version="2.0") + io.write_set_to_file(x, "test_unit.hdf5", "hdf5", append_to_file=True, version="2.0") x.mass = [100.0, 200.0] | units.kg - io.write_set_to_file(x, "test_unit.hdf5","hdf5", append_to_file=True, version="2.0") - y = io.read_set_from_file("test_unit.hdf5","hdf5", close_file=True, copy_history=True) - y = y.previous_state() # weirdness for version="1.0" + io.write_set_to_file(x, "test_unit.hdf5", "hdf5", append_to_file=True, version="2.0") + y = io.read_set_from_file("test_unit.hdf5", "hdf5", close_file=True, copy_history=True) + y = y.previous_state() # weirdness for version="1.0" self.assertAlmostEqual(x.mass, y.mass, 8) self.assertAlmostEqual([10.0, 20.0] | units.kg, y.previous_state().mass, 8) self.assertAlmostEqual([1.0, 2.0] | units.kg, y.previous_state().previous_state().mass, 8) self.assertEqual(y.previous_state().previous_state().previous_state(), None) - - io.write_set_to_file(x, "test_unit.hdf5","hdf5", append_to_file=False, overwrite_file=True, version="2.0") - y = io.read_set_from_file("test_unit.hdf5","hdf5", copy_history=False) + + io.write_set_to_file(x, "test_unit.hdf5", "hdf5", append_to_file=False, overwrite_file=True, version="2.0") + y = io.read_set_from_file("test_unit.hdf5", "hdf5", copy_history=False) self.assertAlmostEqual(x.mass, y.mass, 8) self.assertEqual(y.previous_state(), None) - - os.remove("test_unit.hdf5") + os.remove("test_unit.hdf5") def test7(self): print("Testing HDF5 io with a ParticlesSuperset") @@ -293,107 +293,107 @@ def test7(self): superset = datamodel.ParticlesSuperset([set1, set2]) superset.mass = [1.0, 2.0, 3.0, 4.0] | units.kg superset.radius = [3.0, 4.0, 5.0, 6.0] | units.m - superset.position = [[1,2,3], [3,5,6], [3,2,1], [-3,-5,-6]] | units.m - superset.velocity = [[1,2,3], [3,5,6], [3,2,1], [-3,-5,-6]] | units.m / units.s - io.write_set_to_file(superset, "test_unit.hdf5","hdf5") - y = io.read_set_from_file("test_unit.hdf5","hdf5") - + superset.position = [[1, 2, 3], [3, 5, 6], [3, 2, 1], [-3, -5, -6]] | units.m + superset.velocity = [[1, 2, 3], [3, 5, 6], [3, 2, 1], [-3, -5, -6]] | units.m / units.s + io.write_set_to_file(superset, "test_unit.hdf5", "hdf5") + y = io.read_set_from_file("test_unit.hdf5", "hdf5") + self.assertAlmostEqual(superset.mass, y.mass, 8) self.assertAlmostEqual(superset.radius, y.radius, 8) - self.assertAlmostEqual(superset.position, y.position,8) - self.assertAlmostEqual(superset.velocity, y.velocity,8) - + self.assertAlmostEqual(superset.position, y.position, 8) + self.assertAlmostEqual(superset.velocity, y.velocity, 8) + os.remove("test_unit.hdf5") - + def test8(self): options = base.get_options_for_format('tsf') - options.sort(key = lambda x: x[0]) + options.sort(key=lambda x: x[0]) name, description, default = options[1] self.assertEqual(name, 'nbody_to_si_converter') self.assertEqual(description, 'NEMO datafiles store nbody data, provide a ' 'converter to store si data (None means no converter)') self.assertEqual(default, None) options = base.get_options_for_format('dyn') - options.sort(key = lambda x: x[0]) + options.sort(key=lambda x: x[0]) name, description, default = options[1] self.assertEqual(name, 'dynamics_mass_units') - + options = base.get_options_for_format('hdf5') - options.sort(key = lambda x: x[0]) + options.sort(key=lambda x: x[0]) name, description, default = options[1] self.assertEqual(name, 'append_to_file') self.assertTrue(description.find('If set to True, new data is appended to HDF5 files.') >= 0) self.assertTrue(description.find('If set to False, the existing file is removed and overwritten.') >= 0) self.assertEqual(default, False) - + def test9(self): x = datamodel.Particles(2) x.mass = [1.0, 2.0] | units.kg - self.assertRaises(AmuseException, io.write_set_to_file, x, "test_unit.bogus", "bogus", - expected_message = "You tried to load or save a file with fileformat 'bogus'" + self.assertRaises(AmuseException, io.write_set_to_file, x, "test_unit.bogus", "bogus", + expected_message="You tried to load or save a file with fileformat 'bogus'" ", but this format is not in the supported formats list") - + def test10(self): print("Testing saving/loading timestamp in Starlab") x = datamodel.Particles(2) convert = nbody_system.nbody_to_si(1 | units.kg, 2 | units.m) x.mass = [1.0, 2.0] | units.kg - x.position = [[1,2,3], [3,5,6]] | units.m - x.velocity = [[1,2,3], [3,5,6]] | units.m / units.s + x.position = [[1, 2, 3], [3, 5, 6]] | units.m + x.velocity = [[1, 2, 3], [3, 5, 6]] | units.m / units.s current_time = 1.0 | units.Myr - io.write_set_to_file(x.savepoint(current_time), "time_test_unit.dyn","dyn", nbody_to_si_converter = convert) - y = io.read_set_from_file("time_test_unit.dyn","dyn", nbody_to_si_converter = convert) + io.write_set_to_file(x.savepoint(current_time), "time_test_unit.dyn", "dyn", nbody_to_si_converter=convert) + y = io.read_set_from_file("time_test_unit.dyn", "dyn", nbody_to_si_converter=convert) self.assertAlmostEqual(current_time, y.previous_state().get_timestamp(), 8, in_units=units.Myr) self.assertAlmostEqual(x.mass, y.mass, 8) - self.assertAlmostEqual(x.position, y.position,8) - self.assertAlmostEqual(x.velocity, y.velocity,8) - + self.assertAlmostEqual(x.position, y.position, 8) + self.assertAlmostEqual(x.velocity, y.velocity, 8) + x = datamodel.Particles(2) x.mass = [1.0, 2.0] | nbody_system.mass - x.position = [[1,2,3], [3,5,6]] | nbody_system.length - x.velocity = [[1,2,3], [3,5,6]] | nbody_system.speed + x.position = [[1, 2, 3], [3, 5, 6]] | nbody_system.length + x.velocity = [[1, 2, 3], [3, 5, 6]] | nbody_system.speed current_time = 1.0 | nbody_system.time - io.write_set_to_file(x.savepoint(current_time), "time_test_unit.dyn","dyn") - y = io.read_set_from_file("time_test_unit.dyn","dyn") + io.write_set_to_file(x.savepoint(current_time), "time_test_unit.dyn", "dyn") + y = io.read_set_from_file("time_test_unit.dyn", "dyn") self.assertAlmostEqual(current_time, y.previous_state().get_timestamp(), 8, in_units=nbody_system.time) self.assertAlmostEqual(x.mass, y.mass, 8) - self.assertAlmostEqual(x.position, y.position,8) - self.assertAlmostEqual(x.velocity, y.velocity,8) - + self.assertAlmostEqual(x.position, y.position, 8) + self.assertAlmostEqual(x.velocity, y.velocity, 8) + os.remove("time_test_unit.dyn") - + def test11(self): print("Testing saving/loading timestamp in NEMO") x = datamodel.Particles(2) convert = nbody_system.nbody_to_si(1 | units.kg, 2 | units.m) x.mass = [1.0, 2.0] | units.kg - x.position = [[1,2,3], [3,5,6]] | units.m - x.velocity = [[1,2,3], [3,5,6]] | units.m / units.s + x.position = [[1, 2, 3], [3, 5, 6]] | units.m + x.velocity = [[1, 2, 3], [3, 5, 6]] | units.m / units.s current_time = 1.0 | units.Myr - io.write_set_to_file(x.savepoint(current_time), "time_test_unit.tsf","tsf", nbody_to_si_converter = convert) - y = io.read_set_from_file("time_test_unit.tsf","tsf", nbody_to_si_converter = convert) - + io.write_set_to_file(x.savepoint(current_time), "time_test_unit.tsf", "tsf", nbody_to_si_converter=convert) + y = io.read_set_from_file("time_test_unit.tsf", "tsf", nbody_to_si_converter=convert) + self.assertAlmostEqual(current_time, y.previous_state().get_timestamp(), 8, in_units=units.Myr) self.assertAlmostEqual(x.mass, y.mass, 8) - self.assertAlmostEqual(x.position, y.position,8) - self.assertAlmostEqual(x.velocity, y.velocity,8) - + self.assertAlmostEqual(x.position, y.position, 8) + self.assertAlmostEqual(x.velocity, y.velocity, 8) + x = datamodel.Particles(2) x.mass = [1.0, 2.0] | nbody_system.mass - x.position = [[1,2,3], [3,5,6]] | nbody_system.length - x.velocity = [[1,2,3], [3,5,6]] | nbody_system.speed + x.position = [[1, 2, 3], [3, 5, 6]] | nbody_system.length + x.velocity = [[1, 2, 3], [3, 5, 6]] | nbody_system.speed current_time = 1.0 | nbody_system.time - io.write_set_to_file(x.savepoint(current_time), "time_test_unit.tsf","tsf") - y = io.read_set_from_file("time_test_unit.tsf","tsf") + io.write_set_to_file(x.savepoint(current_time), "time_test_unit.tsf", "tsf") + y = io.read_set_from_file("time_test_unit.tsf", "tsf") self.assertAlmostEqual(current_time, y.previous_state().get_timestamp(), 8, in_units=nbody_system.time) self.assertAlmostEqual(x.mass, y.mass, 8) - self.assertAlmostEqual(x.position, y.position,8) - self.assertAlmostEqual(x.velocity, y.velocity,8) - + self.assertAlmostEqual(x.position, y.position, 8) + self.assertAlmostEqual(x.velocity, y.velocity, 8) + os.remove("time_test_unit.tsf") - + def test12(self): all_formats = sorted(base.registered_fileformat_processors.keys()) for x in all_formats: @@ -420,7 +420,7 @@ def test_hdf5_compressed(self): self.assertAlmostEqual([10.0, 20.0] | units.kg, y.previous_state().mass, 8) self.assertAlmostEqual([1.0, 2.0] | units.kg, y.previous_state().previous_state().mass, 8) self.assertEqual(y.previous_state().previous_state().previous_state(), None) - + io.write_set_to_file(x, filename, "hdf5", append_to_file=False, overwrite_file=True, **options) y = io.read_set_from_file(filename, "hdf5") self.assertAlmostEqual(x.mass, y.mass, 8) diff --git a/src/amuse/test/suite/core_tests/test_links.py b/src/amuse/test/suite/core_tests/test_links.py index 131aa90f2d..34b15b1e64 100644 --- a/src/amuse/test/suite/core_tests/test_links.py +++ b/src/amuse/test/suite/core_tests/test_links.py @@ -7,156 +7,155 @@ import numpy + class TestParticleLinkToParticle(amusetest.TestCase): """ Tests One-to-One relation between particles """ + def test1(self): - + particles = datamodel.Particles(3) - particles.mass = [2,3,4] | units.kg - + particles.mass = [2, 3, 4] | units.kg + parent = particles[0] child1 = particles[1] child2 = particles[2] - + parent.child1 = child1 parent.child2 = child2 child1.sibling = child2 - + self.assertEqual(len(particles.child1), 3) self.assertEqual(len(particles.child1.as_set().compressed()), 1) self.assertEqual(len(particles.child2), 3) self.assertEqual(len(particles.child2.as_set().compressed()), 1) - + self.assertAlmostRelativeEqual(parent.child1.mass, 3 | units.kg) def test2(self): - - + particles = datamodel.Particles(3) - particles.mass = [2,3,4] | units.kg - + particles.mass = [2, 3, 4] | units.kg + parent = particles[0] child1 = particles[1] child2 = particles[2] - + parent.child1 = child1 parent.child2 = child2 child1.sibling = child2 - - - convert_nbody = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + + convert_nbody = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) particles = datamodel.ParticlesWithUnitsConverted( - particles, + particles, convert_nbody.as_converter_from_generic_to_si() ) self.assertEqual(len(particles.child1), 3) self.assertEqual(len(particles.child1.as_set().compressed()), 1) self.assertEqual(len(particles.child2), 3) self.assertEqual(len(particles.child2.as_set().compressed()), 1) - + self.assertAlmostRelativeEqual(particles[0].child1.mass, 0.3 | nbody_system.mass) self.assertAlmostRelativeEqual(particles[0].child1.mass, 0.3 | nbody_system.mass) - + def test3(self): - + particles = datamodel.Particles(3) - particles.mass = [2,3,4] | units.kg - + particles.mass = [2, 3, 4] | units.kg + parent = particles[0] child1 = particles[1] child2 = particles[2] - + parent.child1 = child1 parent.child2 = child2 child1.sibling = child2 - + other = datamodel.Particles() particles.synchronize_to(other) root = None for x in other: if not x.child1 is None: - root = x - break - + root = x + break + self.assertFalse(root is None) - + self.assertAlmostRelativeEqual(root.child1.mass, 3 | units.kg) self.assertTrue(root.child1.as_set()._original_set() is other) self.assertTrue(root.child1.sibling.as_set()._original_set() is other) - + def test4(self): - + particles = datamodel.Particles(3) - particles.mass = [2,3,4] | units.kg + particles.mass = [2, 3, 4] | units.kg other = particles.copy() - + parent = particles[0] child1 = particles[1] child2 = particles[2] - + parent.child1 = child1 parent.child2 = child2 child1.sibling = child2 - + channel = particles.new_channel_to(other) channel.copy() - + self.assertTrue(other[0].child1.as_set()._original_set() is other) self.assertTrue(other[1].sibling.as_set()._original_set() is other) self.assertAlmostRelativeEqual(other[0].child1.mass, 3 | units.kg) - + def test5(self): - + particles = datamodel.Particles(3) parent = particles[0] child1 = particles[1] child2 = particles[2] - - particles.mass = [2,3,4] | units.kg - + + particles.mass = [2, 3, 4] | units.kg + parent.child1 = child1 parent.child2 = child2 child1.sibling = child2 - + other = particles.copy() - + self.assertAlmostRelativeEqual(other[0].child1.mass, 3 | units.kg) self.assertTrue(other[0].child1.as_set()._original_set() is other) - self.assertTrue(other[1].sibling.as_set()._original_set() is other) - + self.assertTrue(other[1].sibling.as_set()._original_set() is other) + def test6(self): - + binaries = datamodel.Particles(2) - binaries.mass = [4,6] | units.kg - + binaries.mass = [4, 6] | units.kg + stars = datamodel.Particles(4) - stars.mass = [1,3,4,2] | units.kg - + stars.mass = [1, 3, 4, 2] | units.kg + binaries[0].child1 = stars[0] binaries[0].child2 = stars[1] binaries[1].child1 = stars[3] binaries[1].child2 = stars[2] - + other = binaries.copy() - stars.mass = 2 * ([1,3,4,2] | units.kg) + stars.mass = 2 * ([1, 3, 4, 2] | units.kg) self.assertAlmostRelativeEqual(binaries[0].child1.mass, 2 | units.kg) self.assertAlmostRelativeEqual(other[0].child1.mass, 1 | units.kg) self.assertAlmostRelativeEqual(other[0].child2.mass, 3 | units.kg) self.assertAlmostRelativeEqual(binaries[1].child1.mass, 4 | units.kg) self.assertAlmostRelativeEqual(other[1].child1.mass, 2 | units.kg) self.assertAlmostRelativeEqual(other[1].child2.mass, 4 | units.kg) - - + def test7(self): - + binaries = datamodel.Particles(2) - binaries.mass = [4,6] | units.kg - + binaries.mass = [4, 6] | units.kg + stars = datamodel.Particles(4) - stars.mass = [1,3,4,2] | units.kg - + stars.mass = [1, 3, 4, 2] | units.kg + binaries[0].child1 = stars[0] binaries[0].child2 = stars[1] binaries[1].child1 = stars[3] @@ -165,11 +164,11 @@ def test7(self): stars[1].binary = binaries[0] stars[2].binary = binaries[1] stars[3].binary = binaries[1] - + other = binaries.copy() stars.mass *= 2 - binaries.mass *= 2 - + binaries.mass *= 2 + self.assertAlmostRelativeEqual(other[0].child1.mass, 1 | units.kg) self.assertAlmostRelativeEqual(binaries[0].child1.mass, 2 | units.kg) self.assertAlmostRelativeEqual(other[0].child2.mass, 3 | units.kg) @@ -178,523 +177,508 @@ def test7(self): self.assertAlmostRelativeEqual(binaries[0].child1.binary.mass, 8 | units.kg) self.assertAlmostRelativeEqual(other[0].child1.binary.mass, 4 | units.kg) self.assertAlmostRelativeEqual(other[1].child1.binary.mass, 6 | units.kg) - + def test8(self): - + particles = datamodel.Particles(2) - particles.mass = [2,3] | units.kg - + particles.mass = [2, 3] | units.kg + binary = datamodel.Particles(1) binary[0].mass = 5 | units.kg binary[0].child1 = particles[0] binary[0].child2 = particles[1] - + binaries = datamodel.Particles() binaries.add_particles(binary) - + self.assertAlmostRelativeEqual(binaries[0].child1.mass, 2 | units.kg) self.assertAlmostRelativeEqual(binaries[0].child2.mass, 3 | units.kg) - - - + def test9(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg - - particles2 = datamodel.Particles(keys=[13,14,15]) - particles2.mass = [20,21,22] | units.kg + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg + + particles2 = datamodel.Particles(keys=[13, 14, 15]) + particles2.mass = [20, 21, 22] | units.kg particles1[0].particle2 = particles2[0] particles1[1].particle2 = particles2[0] - + particles1_copy = particles1.copy() - + self.assertEqual(particles1_copy[0].particle2.key, 13) self.assertEqual(particles1_copy[1].particle2.key, 13) - + particles1_copy[0].particle2.mass = 30 | units.kg - + self.assertAlmostRelativeEquals(particles1_copy[0].particle2.mass, 30 | units.kg) self.assertAlmostRelativeEquals(particles1_copy[1].particle2.mass, 30 | units.kg) - + class TestParticleLinkToParticles(amusetest.TestCase): """ Tests One-to-Many relation between a particle and particle-sets """ + def test0(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg x = numpy.empty((10,), dtype=object) index = numpy.asarray([1]) x[index] = particles1 print(x) self.assertEqual(len(x[1]), 4) - + def test1(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg - particles2 = datamodel.Particles(keys=[13,14]) - particles2.mass = [20,21] | units.kg + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg + particles2 = datamodel.Particles(keys=[13, 14]) + particles2.mass = [20, 21] | units.kg particles1[1].particles2 = particles2 - self.assertEqual(particles1[1].particles2.key, [13,14]) - self.assertAlmostRelativeEquals(particles1[1].particles2.mass, [20,21] | units.kg) + self.assertEqual(particles1[1].particles2.key, [13, 14]) + self.assertAlmostRelativeEquals(particles1[1].particles2.mass, [20, 21] | units.kg) self.assertEqual(particles1[0].particles2, None) - + def test2(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg - particles2 = datamodel.Particles(keys=[13,14]) - particles2.mass = [20,21] | units.kg + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg + particles2 = datamodel.Particles(keys=[13, 14]) + particles2.mass = [20, 21] | units.kg particles1[1].particles2 = particles2 self.assertEqual(len(particles1.particles2), 4) - self.assertEqual(particles1.particles2[1].key, [13,14]) + self.assertEqual(particles1.particles2[1].key, [13, 14]) self.assertEqual(particles1.particles2[0], None) - + def test3(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg - particles2 = datamodel.Particles(keys=[13,14]) - particles2.mass = [20,21] | units.kg + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg + particles2 = datamodel.Particles(keys=[13, 14]) + particles2.mass = [20, 21] | units.kg particles1[1].particles2 = particles2 - + particles1_copy = particles1.copy() - self.assertEqual(particles1_copy[1].particles2.key, [13,14]) - self.assertAlmostRelativeEquals(particles1_copy[1].particles2.mass, [20,21] | units.kg) + self.assertEqual(particles1_copy[1].particles2.key, [13, 14]) + self.assertAlmostRelativeEquals(particles1_copy[1].particles2.mass, [20, 21] | units.kg) self.assertEqual(particles1_copy[0].particles2, None) self.assertNotEqual(id(particles1_copy[1].particles2), id(particles1[1].particles2)) - - + def test4(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg particles1_copy = particles1.copy() - - particles2 = datamodel.Particles(keys=[13,14]) - particles2.mass = [20,21] | units.kg + + particles2 = datamodel.Particles(keys=[13, 14]) + particles2.mass = [20, 21] | units.kg particles1[1].particles2 = particles2 - + channel = particles1.new_channel_to(particles1_copy) channel.copy() - - self.assertEqual(particles1_copy[1].particles2.key, [13,14]) - self.assertAlmostRelativeEquals(particles1_copy[1].particles2.mass, [20,21] | units.kg) + + self.assertEqual(particles1_copy[1].particles2.key, [13, 14]) + self.assertAlmostRelativeEquals(particles1_copy[1].particles2.mass, [20, 21] | units.kg) self.assertEqual(particles1_copy[0].particles2, None) self.assertEqual(id(particles1_copy[1].particles2), id(particles1[1].particles2)) - + def test5(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg - - particles2 = datamodel.Particles(keys=[13,14]) - particles2.mass = [20,21] | units.kg + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg + + particles2 = datamodel.Particles(keys=[13, 14]) + particles2.mass = [20, 21] | units.kg particles1.particles2 = [None, particles2, None, particles2[0]] - - self.assertEqual(particles1[1].particles2.key, [13,14]) - self.assertEqual(particles1[1].particles2.mass, [20,21] | units.kg) + + self.assertEqual(particles1[1].particles2.key, [13, 14]) + self.assertEqual(particles1[1].particles2.mass, [20, 21] | units.kg) self.assertAlmostRelativeEquals(particles1[3].particles2.key, 13) self.assertAlmostRelativeEquals(particles1[3].particles2.mass, 20 | units.kg) self.assertEqual(particles1[0].particles2, None) self.assertEqual(particles1[2].particles2, None) - - + def test6(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg - - particles2 = datamodel.Particles(keys=[13,14,15]) - particles2.mass = [20,21,22] | units.kg + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg + + particles2 = datamodel.Particles(keys=[13, 14, 15]) + particles2.mass = [20, 21, 22] | units.kg particles1[0].particles2 = particles2[0:2] particles1[1].particles2 = particles2[1:] - + particles1_copy = particles1.copy(keep_structure=False) - - self.assertEqual(particles1_copy[0].particles2.key, [13,14]) - self.assertEqual(particles1_copy[1].particles2.key, [14,15]) - + + self.assertEqual(particles1_copy[0].particles2.key, [13, 14]) + self.assertEqual(particles1_copy[1].particles2.key, [14, 15]) + particles1_copy[0].particles2[1].mass = 30 | units.kg - + self.assertAlmostRelativeEquals(particles1_copy[0].particles2[1].mass, 30 | units.kg) self.assertAlmostRelativeEquals(particles1_copy[1].particles2[0].mass, 21 | units.kg) - + particles1_copy = particles1.copy(keep_structure=True) - - self.assertEqual(particles1_copy[0].particles2.key, [13,14]) - self.assertEqual(particles1_copy[1].particles2.key, [14,15]) - + + self.assertEqual(particles1_copy[0].particles2.key, [13, 14]) + self.assertEqual(particles1_copy[1].particles2.key, [14, 15]) + particles1_copy[0].particles2[1].mass = 30 | units.kg - + self.assertAlmostRelativeEquals(particles1_copy[0].particles2[1].mass, 30 | units.kg) self.assertAlmostRelativeEquals(particles1_copy[1].particles2[0].mass, 30 | units.kg) - + class TestParticleLinkToGridPoint(amusetest.TestCase): """ Tests One-to-One relation between particles and gridpoints """ + def test1(self): - + particles = datamodel.Particles(3) - particles.mass = [2,3,4] | units.kg - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 - + particles.mass = [2, 3, 4] | units.kg + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 + particles[0].point11 = grid[1][1] - - self.assertAlmostRelativeEquals(grid[1][1].rho, 6 | units.kg / units.m**3) - self.assertAlmostRelativeEquals(particles[0].point11.rho, 6 | units.kg / units.m**3) - + + self.assertAlmostRelativeEquals(grid[1][1].rho, 6 | units.kg / units.m**3) + self.assertAlmostRelativeEquals(particles[0].point11.rho, 6 | units.kg / units.m**3) + def test2(self): - + particles = datamodel.Particles(3) - particles.mass = [2,3,4] | units.kg - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 + particles.mass = [2, 3, 4] | units.kg + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 particles[0].point11 = grid[1][1] - + particles_copy = particles.copy() - - self.assertAlmostRelativeEquals(grid[1][1].rho, 6 | units.kg / units.m**3) - self.assertAlmostRelativeEquals(particles_copy[0].point11.rho, 6 | units.kg / units.m**3) - + + self.assertAlmostRelativeEquals(grid[1][1].rho, 6 | units.kg / units.m**3) + self.assertAlmostRelativeEquals(particles_copy[0].point11.rho, 6 | units.kg / units.m**3) + def test3(self): - + particles = datamodel.Particles(3) - particles.mass = [2,3,4] | units.kg - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 - + particles.mass = [2, 3, 4] | units.kg + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 + particles_copy = particles.copy() - + particles[0].point11 = grid[1][1] - + channel = particles.new_channel_to(particles_copy) channel.copy() - - self.assertAlmostRelativeEquals(grid[1][1].rho, 6 | units.kg / units.m**3) - self.assertAlmostRelativeEquals(particles_copy[0].point11.rho, 6 | units.kg / units.m**3) + + self.assertAlmostRelativeEquals(grid[1][1].rho, 6 | units.kg / units.m**3) + self.assertAlmostRelativeEquals(particles_copy[0].point11.rho, 6 | units.kg / units.m**3) class TestParticleLinkToGrids(amusetest.TestCase): """ Tests One-to-Many relation between particles and grids """ - + def test1(self): - + particles = datamodel.Particles(3) - particles.mass = [2,3,4] | units.kg - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 - + particles.mass = [2, 3, 4] | units.kg + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 + particles[0].grid = grid - - self.assertAlmostRelativeEquals(grid[1][1].rho, 6 | units.kg / units.m**3) - self.assertAlmostRelativeEquals(particles[0].grid[1][1].rho, 6 | units.kg / units.m**3) - + + self.assertAlmostRelativeEquals(grid[1][1].rho, 6 | units.kg / units.m**3) + self.assertAlmostRelativeEquals(particles[0].grid[1][1].rho, 6 | units.kg / units.m**3) + def test2(self): - + particles = datamodel.Particles(3) - particles.mass = [2,3,4] | units.kg - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 - + particles.mass = [2, 3, 4] | units.kg + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 + particles[0].grid = grid - - self.assertAlmostRelativeEquals(grid[1][1].rho, 6 | units.kg / units.m**3) - self.assertAlmostRelativeEquals(particles[0].grid[1][1].rho, 6 | units.kg / units.m**3) - + + self.assertAlmostRelativeEquals(grid[1][1].rho, 6 | units.kg / units.m**3) + self.assertAlmostRelativeEquals(particles[0].grid[1][1].rho, 6 | units.kg / units.m**3) + particles_copy = particles.copy() - - grid[1][1].rho = 10 | units.kg / units.m**3 - - self.assertAlmostRelativeEquals(grid[1][1].rho, 10 | units.kg / units.m**3) - self.assertAlmostRelativeEquals(particles[0].grid[1][1].rho, 10 | units.kg / units.m**3) - self.assertAlmostRelativeEquals(particles_copy[0].grid[1][1].rho, 6 | units.kg / units.m**3) - - - + + grid[1][1].rho = 10 | units.kg / units.m**3 + + self.assertAlmostRelativeEquals(grid[1][1].rho, 10 | units.kg / units.m**3) + self.assertAlmostRelativeEquals(particles[0].grid[1][1].rho, 10 | units.kg / units.m**3) + self.assertAlmostRelativeEquals(particles_copy[0].grid[1][1].rho, 6 | units.kg / units.m**3) + def test3(self): - + particles = datamodel.Particles(3) - particles.mass = [2,3,4] | units.kg - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 - + particles.mass = [2, 3, 4] | units.kg + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 + particles_copy = particles.copy() - + particles[0].grid = grid - - self.assertAlmostRelativeEquals(grid[1][1].rho, 6 | units.kg / units.m**3) - self.assertAlmostRelativeEquals(particles[0].grid[1][1].rho, 6 | units.kg / units.m**3) - + + self.assertAlmostRelativeEquals(grid[1][1].rho, 6 | units.kg / units.m**3) + self.assertAlmostRelativeEquals(particles[0].grid[1][1].rho, 6 | units.kg / units.m**3) + channel = particles.new_channel_to(particles_copy) channel.copy() - - self.assertAlmostRelativeEquals(particles_copy[0].grid[1][1].rho, 6 | units.kg / units.m**3) + + self.assertAlmostRelativeEquals(particles_copy[0].grid[1][1].rho, 6 | units.kg / units.m**3) + class TestGridPointLinkToParticle(amusetest.TestCase): """ Tests One-to-One relation between gridpoints and particles """ + def test1(self): - - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 + + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 particles = datamodel.Particles(3) - particles.mass = [2,3,4] | units.kg - + particles.mass = [2, 3, 4] | units.kg + grid[0][0].particle = particles[1] - + self.assertAlmostRelativeEquals(grid[0][0].particle.mass, 3 | units.kg) self.assertEqual(grid[0][0].particle, particles[1]) self.assertEqual(grid[1][1].particle, None) def test2(self): - - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 + + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 particles = datamodel.Particles(3) - particles.mass = [2,3,4] | units.kg - + particles.mass = [2, 3, 4] | units.kg + grid[0][0].particle = particles[1] - + grid_copy = grid.copy() - + self.assertAlmostRelativeEquals(grid_copy[0][0].particle.mass, 3 | units.kg) self.assertEqual(grid_copy[0][0].particle, particles[1]) self.assertEqual(grid_copy[1][1].particle, None) grid[0][0].particle.mass = 5 | units.kg - + self.assertAlmostRelativeEquals(grid_copy[0][0].particle.mass, 3 | units.kg) def test3(self): - - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 + + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 particles = datamodel.Particles(3) - particles.mass = [2,3,4] | units.kg - - + particles.mass = [2, 3, 4] | units.kg + grid_copy = grid.copy() - + grid[0][0].particle = particles[1] - + channel = grid.new_channel_to(grid_copy) channel.copy() - + self.assertAlmostRelativeEquals(grid_copy[0][0].particle.mass, 3 | units.kg) self.assertEqual(grid_copy[0][0].particle, particles[1]) self.assertEqual(grid_copy[1][1].particle, None) + class TestGridPointLinkToParticles(amusetest.TestCase): """ Tests One-to-Many relation between gridpoints and particles """ + def test1(self): - - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 + + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 particles = datamodel.Particles(3) - particles.mass = [2,3,4] | units.kg - + particles.mass = [2, 3, 4] | units.kg + grid[0][0].particles = particles - + self.assertAlmostRelativeEquals(grid[0][0].particles[1].mass, 3 | units.kg) self.assertEqual(grid[0][0].particles[1], particles[1]) self.assertEqual(grid[1][1].particles, None) - - + def test2(self): - - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 + + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 particles = datamodel.Particles(3) - particles.mass = [2,3,4] | units.kg - + particles.mass = [2, 3, 4] | units.kg + grid[0][0].particles = particles - + grid_copy = grid.copy() - + self.assertAlmostRelativeEquals(grid_copy[0][0].particles[1].mass, 3 | units.kg) - + grid[0][0].particles[1].mass = 10 | units.kg - - - + def test3(self): - - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 + + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 particles = datamodel.Particles(3) - particles.mass = [2,3,4] | units.kg - - + particles.mass = [2, 3, 4] | units.kg + grid_copy = grid.copy() grid[0][0].particles = particles - + channel = grid.new_channel_to(grid_copy) channel.copy() - + self.assertAlmostRelativeEquals(grid_copy[0][0].particles[1].mass, 3 | units.kg) - + grid[0][0].particles[1].mass = 10 | units.kg - + self.assertAlmostRelativeEquals(grid_copy[0][0].particles[1].mass, 10 | units.kg) - + class TestGridPointLinkToGridPoint(amusetest.TestCase): """ Tests One-to-One relation between gridpoints """ + def test1(self): - - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 - + + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 + grid[0][0].neighbour = grid[0][1] - - self.assertAlmostRelativeEquals(grid[0][0].neighbour.rho, 3 | units.kg / units.m**3) + + self.assertAlmostRelativeEquals(grid[0][0].neighbour.rho, 3 | units.kg / units.m**3) self.assertEqual(grid[0][0].neighbour, grid[0][1]) self.assertEqual(grid[1][1].neighbour, None) def test2(self): - - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 - + + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 + grid[0][0].neighbour = grid[0][1] - + grid_copy = grid.copy() - - self.assertAlmostRelativeEquals(grid_copy[0][0].neighbour.rho, 3 | units.kg / units.m**3) + + self.assertAlmostRelativeEquals(grid_copy[0][0].neighbour.rho, 3 | units.kg / units.m**3) self.assertEqual(grid_copy[0][0].neighbour, grid_copy[0][1]) self.assertEqual(grid_copy[1][1].neighbour, None) - grid[0][0].neighbour.rho = 5 | units.kg / units.m**3 - - self.assertAlmostRelativeEquals(grid_copy[0][0].neighbour.rho, 3 | units.kg / units.m**3) - + grid[0][0].neighbour.rho = 5 | units.kg / units.m**3 + + self.assertAlmostRelativeEquals(grid_copy[0][0].neighbour.rho, 3 | units.kg / units.m**3) + grid_copy[0][1].rho = 6 | units.kg / units.m**3 - - self.assertAlmostRelativeEquals(grid_copy[0][0].neighbour.rho, 6 | units.kg / units.m**3) - + self.assertAlmostRelativeEquals(grid_copy[0][0].neighbour.rho, 6 | units.kg / units.m**3) def test3(self): - - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 - - + + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 + grid_copy = grid.copy() - + grid[0][0].neighbour = grid[0][1] - + channel = grid.new_channel_to(grid_copy) channel.copy() - - - self.assertAlmostRelativeEquals(grid_copy[0][0].neighbour.rho, 3 | units.kg / units.m**3) + + self.assertAlmostRelativeEquals(grid_copy[0][0].neighbour.rho, 3 | units.kg / units.m**3) self.assertEqual(grid_copy[0][0].neighbour, grid_copy[0][1]) self.assertEqual(grid_copy[1][1].neighbour, None) - grid[0][0].neighbour.rho = 5 | units.kg / units.m**3 - - self.assertAlmostRelativeEquals(grid_copy[0][0].neighbour.rho, 3 | units.kg / units.m**3) - + grid[0][0].neighbour.rho = 5 | units.kg / units.m**3 + + self.assertAlmostRelativeEquals(grid_copy[0][0].neighbour.rho, 3 | units.kg / units.m**3) + grid_copy[0][1].rho = 6 | units.kg / units.m**3 - - self.assertAlmostRelativeEquals(grid_copy[0][0].neighbour.rho, 6 | units.kg / units.m**3) - + + self.assertAlmostRelativeEquals(grid_copy[0][0].neighbour.rho, 6 | units.kg / units.m**3) + class TestGridPointLinkToGrid(amusetest.TestCase): """ Tests One-to-Many relation between gridpoints """ + def test1(self): - - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 - + + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 + grid[0][0].container = grid - - self.assertAlmostRelativeEquals(grid[0][0].container[0][1].rho, 3 | units.kg / units.m**3) + + self.assertAlmostRelativeEquals(grid[0][0].container[0][1].rho, 3 | units.kg / units.m**3) self.assertEqual(grid[0][0].container[0][1], grid[0][1]) self.assertEqual(grid[1][1].container, None) def test2(self): - - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 - + + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 + grid[0][0].container = grid - + grid_copy = grid.copy() - - - self.assertAlmostRelativeEquals(grid_copy[0][0].container[0][1].rho, 3 | units.kg / units.m**3) + + self.assertAlmostRelativeEquals(grid_copy[0][0].container[0][1].rho, 3 | units.kg / units.m**3) self.assertEqual(grid_copy[0][0].container[0][1], grid_copy[0][1]) self.assertEqual(grid_copy[1][1].container, None) + grid[0][0].container[0][1].rho = 5 | units.kg / units.m**3 + + self.assertAlmostRelativeEquals(grid_copy[0][0].container[0][1].rho, 3 | units.kg / units.m**3) - grid[0][0].container[0][1].rho = 5 | units.kg / units.m**3 - - self.assertAlmostRelativeEquals(grid_copy[0][0].container[0][1].rho, 3 | units.kg / units.m**3) - grid_copy[0][1].rho = 6 | units.kg / units.m**3 - - self.assertAlmostRelativeEquals(grid_copy[0][0].container[0][1].rho, 6 | units.kg / units.m**3) - + self.assertAlmostRelativeEquals(grid_copy[0][0].container[0][1].rho, 6 | units.kg / units.m**3) def test3(self): - - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 - - + + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 + grid_copy = grid.copy() - + grid[0][0].container = grid - + channel = grid.new_channel_to(grid_copy) channel.copy() - - - self.assertAlmostRelativeEquals(grid_copy[0][0].container[0][1].rho, 3 | units.kg / units.m**3) + + self.assertAlmostRelativeEquals(grid_copy[0][0].container[0][1].rho, 3 | units.kg / units.m**3) self.assertEqual(grid_copy[0][0].container[0][1], grid_copy[0][1]) self.assertEqual(grid_copy[1][1].container, None) - grid[0][0].container[0][1].rho = 5 | units.kg / units.m**3 - - self.assertAlmostRelativeEquals(grid_copy[0][0].container[0][1].rho, 3 | units.kg / units.m**3) - + grid[0][0].container[0][1].rho = 5 | units.kg / units.m**3 + + self.assertAlmostRelativeEquals(grid_copy[0][0].container[0][1].rho, 3 | units.kg / units.m**3) + grid_copy[0][1].rho = 6 | units.kg / units.m**3 - - self.assertAlmostRelativeEquals(grid_copy[0][0].container[0][1].rho, 6 | units.kg / units.m**3) - - + + self.assertAlmostRelativeEquals(grid_copy[0][0].container[0][1].rho, 6 | units.kg / units.m**3) + def test4(self): - - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 - - grid[...,0].container = grid + + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 + + grid[..., 0].container = grid self.assertEqual(id(grid[0][0].container), id(grid)) - self.assertEqual(id(grid[1][0].container), id(grid)) + self.assertEqual(id(grid[1][0].container), id(grid)) self.assertEqual(grid[0][1].container, None) self.assertEqual(grid[1][1].container, None) - - + def test5(self): - - grid = datamodel.Grid(2,3) - grid.rho = [[2,3,4],[5,6,7]] | units.kg / units.m**3 - + + grid = datamodel.Grid(2, 3) + grid.rho = [[2, 3, 4], [5, 6, 7]] | units.kg / units.m**3 + grid.container = grid for index in numpy.ndindex(*grid.shape): self.assertEqual(id(grid[index].container), id(grid)) - self.assertEqual(grid[index].rho, (index[0] * 3 + index[1] + 2) | units.kg / units.m**3) + self.assertEqual(grid[index].rho, (index[0] * 3 + index[1] + 2) | units.kg / units.m**3) diff --git a/src/amuse/test/suite/core_tests/test_literature.py b/src/amuse/test/suite/core_tests/test_literature.py index 2ff1d931d3..a38d96890a 100644 --- a/src/amuse/test/suite/core_tests/test_literature.py +++ b/src/amuse/test/suite/core_tests/test_literature.py @@ -3,6 +3,7 @@ from amuse.support import literature + class TestLiteratureRefs(unittest.TestCase): def setUp(self): literature.LiteratureReferencesMixIn.literature_list = [] @@ -15,6 +16,7 @@ class ClassLitrefs(literature.LiteratureReferencesMixIn): .. [3] Dude, John, *The Intern. Foo Journal of Bars*, **51**, 1647--1751 (2009) .. [4] Hat, John, *The Ex. Foo Journal of Bars*, **51**, 1647--1751 (2009) """ + def __init__(self): literature.LiteratureReferencesMixIn.__init__(self) @@ -23,7 +25,7 @@ def __init__(self): self.assertFalse("ClassLitrefs" in classname) instance = ClassLitrefs() - + classnames = literature.LiteratureReferencesMixIn.names_of_classes_with_references() for classname in classnames: self.assertTrue("ClassLitrefs" in classname) @@ -36,16 +38,17 @@ class ClassLitrefs(literature.LiteratureReferencesMixIn): .. [3] Dude, John, *The Intern. Foo Journal of Bars*, **51**, 1647--1751 (2009) .. [4] Hat, John, *The Gal. Foo Journal of Bars*, **3**, 16--51 (2009) """ + def __init__(self): literature.LiteratureReferencesMixIn.__init__(self) - + literature.TrackLiteratureReferences.default().registered_classes = set([]) string = literature.LiteratureReferencesMixIn.all_literature_references_string() self.assertTrue("AMUSE" in string) self.assertTrue("2018araa.book.....P" in string) instance = ClassLitrefs() - + string = literature.LiteratureReferencesMixIn.all_literature_references_string() literature.LiteratureReferencesMixIn.print_literature_references() self.assertFalse(".. [#] Gratia, Exem" in string) diff --git a/src/amuse/test/suite/core_tests/test_nbody_units.py b/src/amuse/test/suite/core_tests/test_nbody_units.py index 3d528f2d86..3055737485 100644 --- a/src/amuse/test/suite/core_tests/test_nbody_units.py +++ b/src/amuse/test/suite/core_tests/test_nbody_units.py @@ -2,80 +2,73 @@ from amuse.units import constants from amuse.units.nbody_system import * + class TestNbodyUnits(amusetest.TestCase): def test1(self): - convert_nbody = nbody_to_si(1 | units.parsec, 20 |units.MSun) + convert_nbody = nbody_to_si(1 | units.parsec, 20 | units.MSun) y = 1 | mass self.assertEqual(str(y), '1 mass') y_in_si = convert_nbody.to_si(y) y_in_msun = y_in_si.as_quantity_in(units.MSun) self.assertEqual(str(y_in_msun), '20.0 MSun') - y_in_nbody = convert_nbody.to_nbody(y_in_msun) + y_in_nbody = convert_nbody.to_nbody(y_in_msun) self.assertEqual(str(y_in_nbody), '1.0 mass') - + def test2(self): convert_nbody = nbody_to_si(1 | units.MSun, 149.5e6 | units.km) y = 29800 | units.m / units.s - y_in_nbody = convert_nbody.to_nbody(y) + y_in_nbody = convert_nbody.to_nbody(y) self.assertEqual(str(y_in_nbody.unit), 'length * time**-1') self.assertAlmostEqual(y_in_nbody.number, 1.0, 3) - + def test3(self): convert_nbody = nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) y = 1 | length * (time**-1) - y_in_si = convert_nbody.to_si(y) - #self.assertEqual(str(y_in_nbody.unit), 'length * time**-1') + y_in_si = convert_nbody.to_si(y) + # self.assertEqual(str(y_in_nbody.unit), 'length * time**-1') self.assertAlmostEqual(y_in_si.number, 29795.4, -1) - + def test4(self): convert_nbody = nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km) - y_in_nbody = convert_nbody.to_nbody(constants.G) - self.assertEqual(str(y_in_nbody.unit), 'length**3 * mass**-1 * time**-2' ) + y_in_nbody = convert_nbody.to_nbody(constants.G) + self.assertEqual(str(y_in_nbody.unit), 'length**3 * mass**-1 * time**-2') self.assertAlmostEqual(y_in_nbody.number, 1.0, 9) - + def test5(self): convert_nbody = nbody_to_si(149.5e6 | units.km, 1 | units.MSun) y = 29800 | units.m / units.s - y_in_nbody = convert_nbody.to_nbody(y) + y_in_nbody = convert_nbody.to_nbody(y) self.assertEqual(str(y_in_nbody.unit), 'length * time**-1') self.assertAlmostEqual(y_in_nbody.number, 1.0, 3) - def test6(self): - convert_nbody = nbody_to_si(10 | units.kg, 5 | units.m / units. s ) + convert_nbody = nbody_to_si(10 | units.kg, 5 | units.m / units. s) y = 5 | units.m / units.s - y_in_nbody = convert_nbody.to_nbody(y) + y_in_nbody = convert_nbody.to_nbody(y) self.assertEqual(str(y_in_nbody.unit), 'length * time**-1') self.assertAlmostEqual(y_in_nbody.number, 1.0, 3) - y_in_si = convert_nbody.to_si(y_in_nbody) + y_in_si = convert_nbody.to_si(y_in_nbody) self.assertAlmostEqual(y_in_si.number, 5.0, 3) - + def test7(self): - convert_nbody = nbody_to_si(1 | units.kg, 1 | units.m / units. s ) + convert_nbody = nbody_to_si(1 | units.kg, 1 | units.m / units. s) y = 1 | time - y_in_si = convert_nbody.to_si(y) + y_in_si = convert_nbody.to_si(y) self.assertEqual(str(y_in_si.unit), 's') self.assertAlmostEqual(y_in_si.number, 6.6730000000000296e-11, 3) - + def test8(self): self.assertTrue(is_nbody_unit(time / length)) self.assertFalse(is_nbody_unit(units.s / units.m)) - - + def test9(self): - convert_nbody = nbody_to_si(1 | units.kg, 1 | units.m / units. s ) + convert_nbody = nbody_to_si(1 | units.kg, 1 | units.m / units. s) y = 1.0 | units.none - y_in_nbody = convert_nbody.to_nbody(y) - y_in_si = convert_nbody.to_si(y) + y_in_nbody = convert_nbody.to_nbody(y) + y_in_si = convert_nbody.to_si(y) self.assertEqual(y_in_nbody, 1.0 | units.none) self.assertEqual(y_in_si, 1.0 | units.none) - - - - - def test10(self): - self.assertEqual((time / length).to_array_of_floats(), [1,2,-1, 1, 0, 0, 0, 0, 0]) - self.assertEqual((time / (length * mass ** 2)).to_array_of_floats(), [1,2,-1, 1, -2, 0, 0, 0, 0]) - - + def test10(self): + self.assertEqual((time / length).to_array_of_floats(), [1, 2, -1, 1, 0, 0, 0, 0, 0]) + self.assertEqual((time / (length * mass ** 2)).to_array_of_floats(), [1, 2, -1, 1, -2, 0, 0, 0, 0]) diff --git a/src/amuse/test/suite/core_tests/test_nemo.py b/src/amuse/test/suite/core_tests/test_nemo.py index 90f72da3c1..eab4f6c73b 100644 --- a/src/amuse/test/suite/core_tests/test_nemo.py +++ b/src/amuse/test/suite/core_tests/test_nemo.py @@ -7,23 +7,25 @@ from amuse.units import nbody_system from amuse.units import quantities from amuse import datamodel + + class Test(amusetest.TestCase): - + def setUp(self): directory = os.path.dirname(__file__) with open(os.path.join(directory, 'p10.txt'), "r") as f: self.p10_string = f.read() - + def test1(self): instance = nemotsf.Tsf2Particles() - + particles = instance.convert_to_particles(self.p10_string) - + self.assertEqual(instance.number_of_particles, 10) - self.assertEqual(particles.mass[0], 0.1|nbody_system.mass) + self.assertEqual(particles.mass[0], 0.1 | nbody_system.mass) def test2(self): - convert_nbody = nbody_system.nbody_to_si(1|units.g, 1|units.m) + convert_nbody = nbody_system.nbody_to_si(1 | units.g, 1 | units.m) instance = nemotsf.Tsf2Particles() particles = instance.convert_to_particles(self.p10_string, convert_nbody) self.assertAlmostEqual(particles.mass, units.g.new_quantity(0.1*numpy.ones(10)), constants.precision) @@ -34,7 +36,7 @@ def test3(self): self.assertAlmostEqual(particles.mass[0], 0.1 | nbody_system.mass, constants.precision) def test4(self): - reader = nemotsf.Tsf2Particles() + reader = nemotsf.Tsf2Particles() particles = reader.convert_to_particles(self.p10_string) writer = nemotsf.Particles2Tsf() string = writer.convert_to_string(particles) @@ -42,4 +44,3 @@ def test4(self): print(self.p10_string) self.assertTrue("double PhaseSpace[10][2][3]" in string) self.assertTrue("double Mass[10]" in string) - diff --git a/src/amuse/test/suite/core_tests/test_options.py b/src/amuse/test/suite/core_tests/test_options.py index 6b79c6f860..f038aa3a01 100644 --- a/src/amuse/test/suite/core_tests/test_options.py +++ b/src/amuse/test/suite/core_tests/test_options.py @@ -53,7 +53,7 @@ def test2(self): self.assertEqual(option.__get__(instance, type(instance)), True) option = options.option(OptionsTestsClass.float_option, type="float", global_options=global_options) - self.assertEqual(option.__get__(instance, type(instance)), 1.5) + self.assertEqual(option.__get__(instance, type(instance)), 1.5) def test3(self): global_options = options.GlobalOptions() diff --git a/src/amuse/test/suite/core_tests/test_optparse.py b/src/amuse/test/suite/core_tests/test_optparse.py index 1221b17078..1cfc4d9706 100644 --- a/src/amuse/test/suite/core_tests/test_optparse.py +++ b/src/amuse/test/suite/core_tests/test_optparse.py @@ -13,56 +13,56 @@ from amuse import datamodel from amuse.units import optparse + class TestQuantities(amusetest.TestCase): def test1(self): x = optparse.OptionParser() - x.add_option('-m', unit = units.MSun, dest = "mass", type = float) + x.add_option('-m', unit=units.MSun, dest="mass", type=float) options, args = x.parse_args(['-m', '2.0']) self.assertAlmostRelativeEquals(options.mass, 2.0 | units.MSun) - + def test2(self): x = optparse.OptionParser() - x.add_option('-m', unit = units.MSun, default = 1 | units.MSun, dest = "mass", type = float) + x.add_option('-m', unit=units.MSun, default=1 | units.MSun, dest="mass", type=float) options, args = x.parse_args(['bla']) self.assertAlmostRelativeEquals(options.mass, 1.0 | units.MSun) self.assertEqual(args[0], 'bla') - + def test3(self): x = optparse.OptionParser() - x.add_option('-m', unit = units.MSun, default = '1.5', dest = "mass", type = float) + x.add_option('-m', unit=units.MSun, default='1.5', dest="mass", type=float) options, args = x.parse_args(['bla']) self.assertAlmostRelativeEquals(options.mass, 1.5 | units.MSun) self.assertEqual(args[0], 'bla') - + def test4(self): x = optparse.OptionParser() - x.add_option('-m', unit = units.MSun, help = "(unit: %unit)", default = '1.5', dest = "mass", type = float) + x.add_option('-m', unit=units.MSun, help="(unit: %unit)", default='1.5', dest="mass", type=float) helpstr = x.format_help() - + print(helpstr) self.assertTrue('(unit: MSun)' in helpstr) - + x = optparse.OptionParser() - x.add_option('-m', unit = nbody_system.mass, help = "(unit: %unit)", default = '1.5', dest = "mass", type = float) + x.add_option('-m', unit=nbody_system.mass, help="(unit: %unit)", default='1.5', dest="mass", type=float) helpstr = x.format_help() - + print(helpstr) self.assertTrue('(unit: mass)' in helpstr) - + def test5(self): x = optparse.OptionParser() - x.add_option('-m', unit = units.MSun, default = 1.5, dest = "mass", type = float) + x.add_option('-m', unit=units.MSun, default=1.5, dest="mass", type=float) options, args = x.parse_args(['bla']) self.assertAlmostRelativeEquals(options.mass, 1.5 | units.MSun) self.assertEqual(args[0], 'bla') - + def test6(self): x = optparse.OptionParser() - x.add_option('-m', unit = units.MSun, help = "(default: %default, unit: %unit)", default = '1.5', dest = "mass", type = float) + x.add_option('-m', unit=units.MSun, help="(default: %default, unit: %unit)", default='1.5', dest="mass", type=float) helpstr = x.format_help() - + print(helpstr) self.assertTrue('unit: MSun)' in helpstr) self.assertTrue('(default: 1' in helpstr) - diff --git a/src/amuse/test/suite/core_tests/test_parameters.py b/src/amuse/test/suite/core_tests/test_parameters.py index c88eb91a9d..88a54a3aaf 100644 --- a/src/amuse/test/suite/core_tests/test_parameters.py +++ b/src/amuse/test/suite/core_tests/test_parameters.py @@ -12,16 +12,17 @@ class BaseTestModule(object): def before_get_parameter(self): return - + def before_set_parameter(self): return - + + class TestMethodParameterDefintions(amusetest.TestCase): def test1(self): class TestModule(BaseTestModule): def get_test(self): return 123 | units.m - + o = TestModule() set = parameters.Parameters([parameters.ModuleMethodParameterDefinition( "get_test", @@ -41,20 +42,21 @@ def test2(self): "test_name", "a test parameter", 0.1 | units.m) + class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value - + o = TestModule() set = parameters.Parameters([definition,], o) x = set.get_parameter("test_name") - x.set_value(10|units.m) - self.assertEqual(o.x, 10|units.m) + x.set_value(10 | units.m) + self.assertEqual(o.x, 10 | units.m) value = x.get_value() - self.assertEqual(value, 10|units.m) - + self.assertEqual(value, 10 | units.m) def test3(self): definition = parameters.ModuleMethodParameterDefinition( @@ -63,17 +65,19 @@ def test3(self): "test_name", "a test parameter", 0.1 | units.no_unit) + class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value - + o = TestModule() set = parameters.Parameters([definition,], o) x = set.get_parameter("test_name") - x.set_value(10|units.none) - self.assertEqual(o.x, 10|units.none) + x.set_value(10 | units.none) + self.assertEqual(o.x, 10 | units.none) value = x.get_value() self.assertEqual(value, 10) @@ -89,6 +93,7 @@ def test4(self): class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value @@ -112,7 +117,6 @@ def __init__(self): self.assertEqual(1 | units.km, instance.parameters.test_name) self.assertEqual(1000 | units.m, instance.x) - def test5(self): parameter_definition = parameters.ModuleMethodParameterDefinition( None, @@ -125,6 +129,7 @@ def test5(self): class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value @@ -148,8 +153,6 @@ def __init__(self): self.assertEqual(1 | units.km, instance.parameters.test_name) self.assertEqual(1000 | units.m, instance.x) - - def test6(self): parameter_definition = parameters.ModuleMethodParameterDefinition( "get_test", @@ -162,6 +165,7 @@ def test6(self): class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value @@ -178,15 +182,13 @@ def __init__(self): instance = TestInterface() - instance.parameters.test_name = "bla" self.assertEqual("bla", instance.x) instance.parameters.test_name = "bla" - self.assertEqual("bla", instance.x ) + self.assertEqual("bla", instance.x) - def test8(self): parameter_definition = parameters.ModuleMethodParameterDefinition( "get_test", @@ -199,10 +201,10 @@ def test8(self): class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value - instance = TestModule() p = parameters.Parameters([parameter_definition], instance) @@ -211,7 +213,6 @@ def set_test(self, value): self.assertEqual(11.0 | units.m, instance.x) - def test9(self): parameter_definition = parameters.ModuleMethodParameterDefinition( "get_test", @@ -224,19 +225,19 @@ def test9(self): class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value - instance = TestModule() p = parameters.Parameters([parameter_definition], instance) - self.assertRaises(AmuseException, lambda: p.unknown, - expected_message = "tried to get unknown parameter 'unknown' for a 'TestModule' object") + self.assertRaises(AmuseException, lambda: p.unknown, + expected_message="tried to get unknown parameter 'unknown' for a 'TestModule' object") self.assertRaises(AmuseException, setattr, p, "unknown", 1.0 | units.m, - expected_message = "tried to set unknown parameter 'unknown' for a 'TestModule' object") + expected_message="tried to set unknown parameter 'unknown' for a 'TestModule' object") def test10(self): parameter_definition = parameters.ModuleMethodParameterDefinition( @@ -246,26 +247,25 @@ def test10(self): "a test parameter", 11.0 | units.m ) - + class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value - - + instance = TestModule() - + p = parameters.Parameters([parameter_definition], instance) instance.x = 1 | units.m self.assertEqual(p.test_name, 1 | units.m) - + def try_set_read_only_parameter(parameter_set): parameter_set.test_name = 2 | units.m - - self.assertRaises(AmuseException, try_set_read_only_parameter, p, - expected_message = "Could not set value for parameter 'test_name' of a 'TestModule' object, parameter is read-only") + self.assertRaises(AmuseException, try_set_read_only_parameter, p, + expected_message="Could not set value for parameter 'test_name' of a 'TestModule' object, parameter is read-only") def test11(self): parameter_definition1 = parameters.ModuleMethodParameterDefinition( @@ -275,7 +275,7 @@ def test11(self): "a test parameter", 11.0 | units.m ) - + parameter_definition2 = parameters.ModuleMethodParameterDefinition( "get_test1", "set_test1", @@ -283,32 +283,34 @@ def test11(self): "a test parameter", 12.0 | units.m ) - + class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value + def get_test1(self): return self.y + def set_test1(self, value): self.y = value - - + instance = TestModule() - + p = parameters.Parameters([parameter_definition1, parameter_definition2], instance) instance.x = 1 | units.m instance.y = 2 | units.m self.assertEqual(p.test_name, 1 | units.m) self.assertEqual(p.test_name2, 2 | units.m) - + p.test_name = 20 | units.m p.send_not_set_parameters_to_code() - + self.assertEqual(instance.x, 20 | units.m) self.assertEqual(instance.y, 12 | units.m) - + def test12(self): parameter_definition = parameters.ModuleVectorMethodParameterDefinition( "get_test", @@ -322,7 +324,7 @@ def test12(self): class TestModule(BaseTestModule): def get_test(self): return self.x, self.y, self.z - + def set_test(self, x, y, z): self.x = x self.y = y @@ -344,18 +346,19 @@ def __init__(self): self.assertTrue('test_name' in list(instance.parameters.names())) self.assertEqual([0.1, 0.2, 0.3] | units.km, instance.parameters.test_name) - + instance.parameters.test_name = [1, 2, 3] | units.km self.assertEqual([1, 2, 3] | units.km, instance.parameters.test_name) - + self.assertEqual(1000 | units.m, instance.x) - + + class TestInterfaceParameterDefintions(amusetest.TestCase): def test1(self): class TestModule(BaseTestModule): pass - + o = TestModule() set = parameters.Parameters([parameters.InterfaceParameterDefinition( "test_name", @@ -371,15 +374,16 @@ def test2(self): "test_name", "a test parameter", 0.1 | units.m) + class TestModule(BaseTestModule): pass - + o = TestModule() set = parameters.Parameters([definition,], o) x = set.get_parameter("test_name") - x.set_value(10|units.m) + x.set_value(10 | units.m) value = x.get_value() - self.assertEqual(value, 10|units.m) + self.assertEqual(value, 10 | units.m) def test4(self): parameter_definition = parameters.InterfaceParameterDefinition( @@ -391,6 +395,7 @@ def test4(self): class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value @@ -424,10 +429,12 @@ def test5(self): class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value + def before_(self): - self.before_called=True + self.before_called = True pass class TestModuleBinding(object): @@ -445,11 +452,12 @@ def __init__(self): self.assertTrue('test_name' in list(instance.parameters.names())) - self.assertRaises(Exception,lambda: getattr(instance,"before_called")) + self.assertRaises(Exception, lambda: getattr(instance, "before_called")) instance.parameters.test_name = 1 | units.km self.assertEqual(1 | units.km, instance.parameters.test_name) - self.assertEqual(instance.before_called,True) + self.assertEqual(instance.before_called, True) + class TestParameters(amusetest.TestCase): def test1(self): @@ -466,10 +474,10 @@ class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value - o = TestModule() x = parameters.Parameters([parameter_definition], o) @@ -492,14 +500,13 @@ class TestModule(BaseTestModule): def get_test(self): return self.x - + def set_test(self, value): self.x = value o = TestModule() x = parameters.Parameters([parameter_definition], o) - self.assertEqual(x.test_name, 123 | nbody_system.length) convert_nbody = nbody_system.nbody_to_si(2.0 | units.m, 4.0 | units.kg) @@ -512,13 +519,11 @@ def set_test(self, value): self.assertAlmostEqual(y.test_name.value_in(units.m), 246.0, 6) y.test_name = 500 | units.m - self.assertAlmostEqual(y.test_name.value_in(units.m), 500.0, 6) print(x.test_name, o.x) self.assertAlmostEqual(x.test_name.value_in(nbody_system.length), 250.0, 6) self.assertAlmostEqual(o.x, 250.0 | nbody_system.length, 6) - def test3(self): parameter_definition = parameters.ModuleMethodParameterDefinition( "get_test", @@ -533,6 +538,7 @@ class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value @@ -571,6 +577,7 @@ class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value @@ -607,13 +614,13 @@ class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value o = TestModule() x = parameters.Parameters([parameter_definition], o) - self.assertTrue("test_name" in str(x)) self.assertTrue("123.0 length" in str(x)) @@ -648,10 +655,13 @@ class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value + def get_test1(self): return self.y + def set_test1(self, value): self.y = value @@ -668,8 +678,8 @@ def set_test1(self, value): x, convert_nbody.as_converter_from_si_to_generic() ) - self.assertEqual(getattr(y,"phys_test_name"), 123.0 | units.m) - self.assertAlmostEqual(getattr(y,"nbody_test_name"), 246.0 | units.m) + self.assertEqual(getattr(y, "phys_test_name"), 123.0 | units.m) + self.assertAlmostEqual(getattr(y, "nbody_test_name"), 246.0 | units.m) y.phys_test_name = 1234.0 | units.m self.assertEqual(y.phys_test_name, 1234.0 | units.m) y.nbody_test_name = 12345.0 | nbody_system.length @@ -699,8 +709,9 @@ class TestModule(BaseTestModule): def get_nbody(self): return self.x + def get_string(self): - return str(10 * self.x.number ) + return str(10 * self.x.number) o = TestModule() x = parameters.Parameters([string_parameter_definition, nbody_parameter_definition], o) @@ -715,8 +726,8 @@ def get_string(self): x, convert_nbody.as_converter_from_si_to_generic() ) - self.assertEqual(getattr(y,"string_par_name"), "1230.0") - self.assertAlmostEqual(getattr(y,"nbody_par_name"), 246.0 | units.m) + self.assertEqual(getattr(y, "string_par_name"), "1230.0") + self.assertAlmostEqual(getattr(y, "nbody_par_name"), 246.0 | units.m) def test7(self): parameter_definition1 = parameters.ModuleCachingParameterDefinition( @@ -726,7 +737,7 @@ def test7(self): "a test parameter (1)", 11.0 | units.m ) - + parameter_definition2 = parameters.ModuleCachingParameterDefinition( "initialize_vars", "arg2", @@ -734,16 +745,15 @@ def test7(self): "a test parameter (2)", 12.0 | units.m ) - + class TestModule(BaseTestModule): x = 123 | units.m y = 456 | units.m - + def initialize_vars(self, arg1, arg2): self.x = arg1 self.y = arg2 - - + o = TestModule() x = parameters.Parameters([parameter_definition1, parameter_definition2], o) x.test_par1 = 20 | units.m @@ -755,8 +765,6 @@ def initialize_vars(self, arg1, arg2): x.send_cached_parameters_to_code() self.assertEqual(o.x, 20 | units.m) self.assertEqual(o.y, 12 | units.m) - - def test8(self): parameter_definition1 = parameters.ModuleCachingParameterDefinition( @@ -766,7 +774,7 @@ def test8(self): "a test parameter (1)", 11.0 | units.m ) - + parameter_definition2 = parameters.ModuleCachingParameterDefinition( "initialize_vars", "arg2", @@ -774,7 +782,7 @@ def test8(self): "a test parameter (2)", 12.0 | units.m ) - + parameter_definition3 = parameters.ModuleCachingParameterDefinition( "initialize_vars2", "arg1", @@ -782,31 +790,28 @@ def test8(self): "a test parameter (3)", 14.0 | units.m ) - + class TestModule(BaseTestModule): x = 123 | units.m y = 456 | units.m z = 100 | units.m - + def initialize_vars(self, arg1, arg2): self.x = arg1 self.y = arg2 return 0 - + def initialize_vars2(self, arg1): self.z = arg1 return 0 - - + o = TestModule() x = parameters.Parameters([parameter_definition1, parameter_definition2, parameter_definition3], o) - + x.send_cached_parameters_to_code() self.assertEqual(o.x, 11 | units.m) self.assertEqual(o.y, 12 | units.m) self.assertEqual(o.z, 14 | units.m) - - def test9(self): parameter_definition1 = parameters.ModuleMethodParameterDefinition( @@ -816,7 +821,7 @@ def test9(self): "a test parameter", 11.0 | units.m ) - + parameter_definition2 = parameters.ModuleMethodParameterDefinition( "get_test1", "set_test1", @@ -824,36 +829,38 @@ def test9(self): "a test parameter", 12.0 | units.m ) - + paramer_definition3 = parameters.VectorParameterDefinition( "test_vector", "vector of parameters", ["test_name", "test_name2"], [11.0, 12.0] | units.m ) - + class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value + def get_test1(self): return self.y + def set_test1(self, value): self.y = value - - + instance = TestModule() instance.x = 1 | units.m instance.y = 2 | units.m - + p = parameters.Parameters([parameter_definition1, parameter_definition2, paramer_definition3], instance) - - self.assertEqual(p.test_vector, (1,2) | units.m) - p.test_vector = (3,4) | units.m + + self.assertEqual(p.test_vector, (1, 2) | units.m) + p.test_vector = (3, 4) | units.m self.assertEqual(instance.x, 3 | units.m) self.assertEqual(instance.y, 4 | units.m) - + def test10(self): print("Testing ParametersWithUnitsConverted on vector parameters") definitions = [] @@ -865,38 +872,43 @@ def test10(self): "a test parameter", 10.0 | generic_unit_system.length )) - + definitions.append(parameters.VectorParameterDefinition( "mesh_length", "length of the model in the x, y and z directions", ("length_x", "length_y", "length_z"), [10, 10, 10] | generic_unit_system.length )) - + class TestModule(BaseTestModule): x = 123.0 | generic_unit_system.length y = 456.0 | generic_unit_system.length z = 789.0 | generic_unit_system.length - + def get_length_x(self): return self.x + def set_length_x(self, value): self.x = value + def get_length_y(self): return self.y + def set_length_y(self, value): self.y = value + def get_length_z(self): return self.z + def set_length_z(self, value): self.z = value - + o = TestModule() x = parameters.Parameters(definitions, o) - + self.assertTrue("mesh_length" in str(x)) self.assertTrue("[123.0, 456.0, 789.0] length" in str(x)) - + converter = generic_unit_converter.ConvertBetweenGenericAndSiUnits(2.0 | units.m, 4.0 | units.kg, 6.0 | units.s) y = parameters.ParametersWithUnitsConverted( x, @@ -904,29 +916,33 @@ def set_length_z(self, value): ) self.assertTrue("mesh_length" in str(y)) self.assertTrue("[246.0, 912.0, 1578.0] m" in str(y)) - - + def test11(self): print("Testing ParametersWithUnitsConverted on vector parameters, using add_vector_parameter") - + class TestModule(BaseTestModule): x = 123.0 | generic_unit_system.length y = 456.0 | generic_unit_system.length z = 789.0 | generic_unit_system.length - + def get_length_x(self): return self.x + def set_length_x(self, value): self.x = value + def get_length_y(self): return self.y + def set_length_y(self, value): self.y = value + def get_length_z(self): return self.z + def set_length_z(self, value): self.z = value - + o = TestModule() parameters_handler = HandleParameters(o) parameters_handler.add_vector_parameter( @@ -936,17 +952,17 @@ def set_length_z(self, value): ) for par_name in ["length_x", "length_y", "length_z"]: parameters_handler.add_method_parameter( - "get_"+par_name, + "get_"+par_name, "set_"+par_name, - par_name, - "a test parameter", - default_value = 10.0 | generic_unit_system.length, + par_name, + "a test parameter", + default_value=10.0 | generic_unit_system.length, ) - + x = parameters_handler.get_attribute(None, None) self.assertTrue("mesh_length" in str(x)) self.assertTrue("[123.0, 456.0, 789.0] length" in str(x)) - + converter = generic_unit_converter.ConvertBetweenGenericAndSiUnits(2.0 | units.m, 4.0 | units.kg, 6.0 | units.s) y = parameters.ParametersWithUnitsConverted( x, @@ -954,7 +970,7 @@ def set_length_z(self, value): ) self.assertTrue("mesh_length" in str(y)) self.assertTrue("[246.0, 912.0, 1578.0] m" in str(y)) - + def test12(self): definition = parameters.ModuleMethodParameterDefinition( "get_test", @@ -963,33 +979,35 @@ def test12(self): "a test parameter", 0.1 | units.m ) + class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value - + o = TestModule() set = parameters.Parameters([definition,], o) - set.test_name = 10|units.m - - self.assertEqual(o.x, 10|units.m) - self.assertEqual(set.test_name, 10|units.m) - + set.test_name = 10 | units.m + + self.assertEqual(o.x, 10 | units.m) + self.assertEqual(set.test_name, 10 | units.m) + memento = set.copy() - self.assertEqual(memento.test_name, 10|units.m) - set.test_name = 20|units.m - - self.assertEqual(o.x, 20|units.m) - self.assertEqual(set.test_name, 20|units.m) - self.assertEqual(memento.test_name, 10|units.m) - + self.assertEqual(memento.test_name, 10 | units.m) + set.test_name = 20 | units.m + + self.assertEqual(o.x, 20 | units.m) + self.assertEqual(set.test_name, 20 | units.m) + self.assertEqual(memento.test_name, 10 | units.m) + set.reset_from_memento(memento) - - self.assertEqual(o.x, 10|units.m) - self.assertEqual(set.test_name, 10|units.m) - self.assertEqual(memento.test_name, 10|units.m) - + + self.assertEqual(o.x, 10 | units.m) + self.assertEqual(set.test_name, 10 | units.m) + self.assertEqual(memento.test_name, 10 | units.m) + def test13(self): definition = parameters.ModuleMethodParameterDefinition( "get_test", @@ -998,36 +1016,38 @@ def test13(self): "a read-only test parameter", 0.1 | units.m ) + class TestModule(BaseTestModule): x = 0.1 | units.m + def get_test(self): return self.x - + o = TestModule() set = parameters.Parameters([definition,], o) - + self.assertRaises(AmuseException, setattr, set, "test_name", 1.0 | units.m, - expected_message = "Could not set value for parameter 'test_name' of a 'TestModule' object, parameter is read-only") - - self.assertEqual(o.x, 0.1|units.m) - self.assertEqual(set.test_name, 0.1|units.m) - + expected_message="Could not set value for parameter 'test_name' of a 'TestModule' object, parameter is read-only") + + self.assertEqual(o.x, 0.1 | units.m) + self.assertEqual(set.test_name, 0.1 | units.m) + memento = set.copy() - self.assertEqual(memento.test_name, 0.1|units.m) - + self.assertEqual(memento.test_name, 0.1 | units.m) + set.reset_from_memento(memento) - self.assertEqual(o.x, 0.1|units.m) - self.assertEqual(set.test_name, 0.1|units.m) - + self.assertEqual(o.x, 0.1 | units.m) + self.assertEqual(set.test_name, 0.1 | units.m) + memento.test_name = 2.0 | units.m - self.assertEqual(memento.test_name, 2.0|units.m) + self.assertEqual(memento.test_name, 2.0 | units.m) self.assertRaises(AmuseException, set.reset_from_memento, memento, - expected_message = "tried to change read-only parameter 'test_name' for a 'TestModule' object") - - self.assertEqual(o.x, 0.1|units.m) - self.assertEqual(set.test_name, 0.1|units.m) - self.assertEqual(memento.test_name, 2.0|units.m) + expected_message="tried to change read-only parameter 'test_name' for a 'TestModule' object") + + self.assertEqual(o.x, 0.1 | units.m) + self.assertEqual(set.test_name, 0.1 | units.m) + self.assertEqual(memento.test_name, 2.0 | units.m) def test14(self): definition = parameters.InterfaceParameterDefinition( @@ -1035,20 +1055,21 @@ def test14(self): "a read-only test parameter", 0.1 | units.m ) + class TestModule(BaseTestModule): pass - + o = TestModule() set = parameters.Parameters([definition,], o) - - self.assertEqual(set.test_name, 0.1|units.m) - + + self.assertEqual(set.test_name, 0.1 | units.m) + memento = set.copy() - self.assertEqual(memento.test_name, 0.1|units.m) - memento.test_name=2.|units.m - + self.assertEqual(memento.test_name, 0.1 | units.m) + memento.test_name = 2. | units.m + set.reset_from_memento(memento) - self.assertEqual(set.test_name, 2.|units.m) + self.assertEqual(set.test_name, 2. | units.m) def test15(self): definition = parameters.InterfaceParameterDefinition( @@ -1056,24 +1077,25 @@ def test15(self): "a read-only test parameter", 0.1 ) + class TestModule(BaseTestModule): pass - + o = TestModule() set = parameters.Parameters([definition,], o) - + import numpy - b=numpy.array(2) - set.test_name=b - b*=2 - self.assertEqual(set.test_name,2) - + b = numpy.array(2) + set.test_name = b + b *= 2 + self.assertEqual(set.test_name, 2) + def test16(self): print("Testing add_interface_parameter") - + class TestModule(BaseTestModule): - pass - + pass + o = TestModule() parameters_handler = HandleParameters(o) parameters_handler.add_vector_parameter( @@ -1081,17 +1103,17 @@ class TestModule(BaseTestModule): "length of the model in the x, y and z directions", ("length_x", "length_y", "length_z") ) - for i,par_name in enumerate(["length_x", "length_y", "length_z"]): + for i, par_name in enumerate(["length_x", "length_y", "length_z"]): parameters_handler.add_interface_parameter( - par_name, - "a test parameter", - default_value = i*10.0 | generic_unit_system.length, + par_name, + "a test parameter", + default_value=i*10.0 | generic_unit_system.length, ) - + x = parameters_handler.get_attribute(None, None) self.assertTrue("mesh_length" in str(x)) self.assertTrue("[0.0, 10.0, 20.0] length" in str(x)) - + converter = generic_unit_converter.ConvertBetweenGenericAndSiUnits(2.0 | units.m, 4.0 | units.kg, 6.0 | units.s) y = parameters.ParametersWithUnitsConverted( x, @@ -1099,20 +1121,22 @@ class TestModule(BaseTestModule): ) self.assertTrue("mesh_length" in str(y)) self.assertTrue("[0.0, 20.0, 40.0] m" in str(y)) - + def test17(self): print("Testing ParametersWithUnitsConverted on vector parameters, using add_vector_parameter") - + class TestModule(BaseTestModule): - x = [1.,2.,3.] | generic_unit_system.length - - def get_length(self,i): + x = [1., 2., 3.] | generic_unit_system.length + + def get_length(self, i): return self.x[i] - def set_length(self, i,value): + + def set_length(self, i, value): self.x[i] = value + def range(self): - return 0,len(self.x)-1 - + return 0, len(self.x)-1 + o = TestModule() parameters_handler = HandleParameters(o) parameters_handler.add_array_parameter( @@ -1122,7 +1146,7 @@ def range(self): "length", "description" ) - + x = parameters_handler.get_attribute(None, None) self.assertTrue("length" in str(x)) self.assertTrue("[1.0, 2.0, 3.0] length" in str(x)) @@ -1137,159 +1161,166 @@ def test18(self): "param", "a test parameter" )) - + class TestModule(BaseTestModule): - x = [1.,2.,3.] | generic_unit_system.length - - def get(self,i): + x = [1., 2., 3.] | generic_unit_system.length + + def get(self, i): return self.x[i] - def set(self,i, value): + + def set(self, i, value): self.x[i] = value + def range(self): return 0, len(self.x)-1 - + o = TestModule() x = parameters.Parameters(definitions, o) - - self.assertEqual(x.param, [1.,2.,3.] | generic_unit_system.length) - x.param*=2 - self.assertEqual(x.param, [2.,4.,6.] | generic_unit_system.length) - + + self.assertEqual(x.param, [1., 2., 3.] | generic_unit_system.length) + x.param *= 2 + self.assertEqual(x.param, [2., 4., 6.] | generic_unit_system.length) + def test19(self): print("Testing multiple parameter sets") - + class TestModule(BaseTestModule): x = 123.0 | generic_unit_system.length y = 456.0 | generic_unit_system.length z = 789.0 | generic_unit_system.length - + def get_length_x(self): return self.x + def set_length_x(self, value): self.x = value + def get_length_y(self): return self.y + def set_length_y(self, value): self.y = value + def get_length_z(self): return self.z + def set_length_z(self, value): self.z = value - + o = TestModule() parameters_handler = HandleParameters(o) for par_name in ["length_x", "length_y", "length_z"]: parameters_handler.add_method_parameter( - "get_"+par_name, + "get_"+par_name, "set_"+par_name, - par_name, - "a test parameter", - default_value = 10.0 | generic_unit_system.length, - parameter_set = par_name+"_set" + par_name, + "a test parameter", + default_value=10.0 | generic_unit_system.length, + parameter_set=par_name+"_set" ) - - for i,par_name in enumerate(["length_x", "length_y", "length_z"]): + + for i, par_name in enumerate(["length_x", "length_y", "length_z"]): x = parameters_handler.get_attribute(par_name+"_set", None) - self.assertTrue([123.0, 456.0, 789.0][i] == getattr(x,par_name).number) - + self.assertTrue([123.0, 456.0, 789.0][i] == getattr(x, par_name).number) + def test20(self): print("Testing multiple parameter sets 2") - + class TestInterface(BaseTestModule): - x = 123.0 + x = 123.0 y = 456.0 - + def get_x(self): return self.x + def set_x(self, value): self.x = value + def get_y(self): return self.y + def set_y(self, value): self.y = value - class Testing(InCodeComponentImplementation): - + def __init__(self, **options): - InCodeComponentImplementation.__init__(self, TestInterface(), **options) - - def define_parameters(self,object): - object.add_method_parameter( - "get_x", "set_x", "x", "test parameter", 123. - ) - object.add_method_parameter( - "get_y", "set_y", "y", "test parameter 2", 456., - parameter_set="parameters2" - ) - object.add_alias_parameter( - "y_alias","y", " new y", parameter_set="parameters2" - ) - - t=Testing() - - self.assertEqual(set(t.parameter_set_names()), set(('parameters','parameters2'))) - - self.assertEqual(t.parameters.x,123.) - self.assertEqual(t.parameters2.y,456.) - t.parameters2.y=789. - self.assertEqual(t.parameters2.y,789.) - self.assertEqual(t.parameters2.y_alias,789.) + InCodeComponentImplementation.__init__(self, TestInterface(), **options) + + def define_parameters(self, object): + object.add_method_parameter( + "get_x", "set_x", "x", "test parameter", 123. + ) + object.add_method_parameter( + "get_y", "set_y", "y", "test parameter 2", 456., + parameter_set="parameters2" + ) + object.add_alias_parameter( + "y_alias", "y", " new y", parameter_set="parameters2" + ) + + t = Testing() + + self.assertEqual(set(t.parameter_set_names()), set(('parameters', 'parameters2'))) + + self.assertEqual(t.parameters.x, 123.) + self.assertEqual(t.parameters2.y, 456.) + t.parameters2.y = 789. + self.assertEqual(t.parameters2.y, 789.) + self.assertEqual(t.parameters2.y_alias, 789.) def test21(self): print("Test change in parameter sets") - + class TestInterface(BaseTestModule): - x = 123.0 + x = 123.0 y = 456.0 - + def get_x(self): return self.x + def set_x(self, value): self.x = value + def get_y(self): return self.y + def set_y(self, value): self.y = value - class Testing(InCodeComponentImplementation): - - def __init__(self, **options): - InCodeComponentImplementation.__init__(self, TestInterface(), **options) - - def define_parameters(self,handler): - handler.add_method_parameter( - "get_x", "set_x", "x", "test parameter", 123. - ) - def define_additional_parameters(self): - handler=self.get_handler('PARAMETER') - handler.add_method_parameter( - "get_y", "set_y", "y", "test parameter 2", 456., - parameter_set="parameters2" - ) - handler.add_alias_parameter( - "y_alias","y", " new y", parameter_set="parameters2" - ) - handler.add_method_parameter( - "get_y", "set_y", "y", "test parameter", 456. - ) - + def __init__(self, **options): + InCodeComponentImplementation.__init__(self, TestInterface(), **options) + def define_parameters(self, handler): + handler.add_method_parameter( + "get_x", "set_x", "x", "test parameter", 123. + ) - t=Testing() + def define_additional_parameters(self): + handler = self.get_handler('PARAMETER') + handler.add_method_parameter( + "get_y", "set_y", "y", "test parameter 2", 456., + parameter_set="parameters2" + ) + handler.add_alias_parameter( + "y_alias", "y", " new y", parameter_set="parameters2" + ) + handler.add_method_parameter( + "get_y", "set_y", "y", "test parameter", 456. + ) + + t = Testing() self.assertEqual(set(t.parameter_set_names()), set(('parameters',))) - - - t.define_additional_parameters() - self.assertEqual(set(t.parameter_set_names()), set(('parameters','parameters2'))) - - self.assertEqual(t.parameters.x,123.) - self.assertEqual(t.parameters2.y,456.) - t.parameters2.y=789. - self.assertEqual(t.parameters2.y,789.) - self.assertEqual(t.parameters2.y_alias,789.) - self.assertEqual(t.parameters.y,789.) + t.define_additional_parameters() + self.assertEqual(set(t.parameter_set_names()), set(('parameters', 'parameters2'))) + + self.assertEqual(t.parameters.x, 123.) + self.assertEqual(t.parameters2.y, 456.) + t.parameters2.y = 789. + self.assertEqual(t.parameters2.y, 789.) + self.assertEqual(t.parameters2.y_alias, 789.) + self.assertEqual(t.parameters.y, 789.) diff --git a/src/amuse/test/suite/core_tests/test_particle_attributes.py b/src/amuse/test/suite/core_tests/test_particle_attributes.py index 5b80d63d76..79a63c5b08 100644 --- a/src/amuse/test/suite/core_tests/test_particle_attributes.py +++ b/src/amuse/test/suite/core_tests/test_particle_attributes.py @@ -13,13 +13,14 @@ from amuse.datamodel import Particle, Particles, ParticlesWithUnitsConverted from amuse.datamodel import particle_attributes + class TestParticlesAttributes(amusetest.TestCase): - + def test1(self): print("Test basic particle attributes and scale_to_standard - nbody units") particles = Particles(2) - particles.position = [[-1, 0, 0], [1,0,0]] | nbody_system.length - particles.velocity = [[-1, 0, 0], [1,0,0]] | nbody_system.length/nbody_system.time + particles.position = [[-1, 0, 0], [1, 0, 0]] | nbody_system.length + particles.velocity = [[-1, 0, 0], [1, 0, 0]] | nbody_system.length/nbody_system.time particles.mass = 0.4 | nbody_system.mass self.assertAlmostRelativeEquals(particles.total_mass(), 0.8 | nbody_system.mass) self.assertAlmostRelativeEquals(particles.kinetic_energy(), 0.4 | nbody_system.energy) @@ -30,51 +31,51 @@ def test1(self): self.assertAlmostRelativeEquals(particles.kinetic_energy(), 0.25 | nbody_system.energy) self.assertAlmostRelativeEquals(particles.potential_energy(G=nbody_system.G), -0.5 | nbody_system.energy) self.assertAlmostRelativeEquals(particles.virial_radius(), 1.0 | nbody_system.length) - - particles.scale_to_standard(virial_ratio=1) # unbound + + particles.scale_to_standard(virial_ratio=1) # unbound self.assertAlmostRelativeEquals(particles.kinetic_energy(), 0.5 | nbody_system.energy) self.assertAlmostRelativeEquals(particles.potential_energy(G=nbody_system.G), -0.5 | nbody_system.energy) - particles.scale_to_standard(virial_ratio=0) # velocities zeroed + particles.scale_to_standard(virial_ratio=0) # velocities zeroed self.assertAlmostRelativeEquals(particles.kinetic_energy(), 0 | nbody_system.energy) self.assertAlmostRelativeEquals(particles.potential_energy(G=nbody_system.G), -0.5 | nbody_system.energy) - + def test2(self): print("Test basic particle attributes and scale_to_standard - SI units") convert_nbody = nbody_system.nbody_to_si(1 | units.MSun, 1 | units.parsec) particles = Particles(2) - particles.position = [[-1, 0, 0], [1,0,0]] | units.parsec - particles.velocity = [[-1, 0, 0], [1,0,0]] | units.parsec / units.Myr - particles.mass = 0.5 | units.MSun - + particles.position = [[-1, 0, 0], [1, 0, 0]] | units.parsec + particles.velocity = [[-1, 0, 0], [1, 0, 0]] | units.parsec / units.Myr + particles.mass = 0.5 | units.MSun + self.assertAlmostRelativeEquals(particles.total_mass(), 1.0 | units.MSun) - self.assertAlmostRelativeEquals(particles.kinetic_energy(), 1.0 * (0.5 | units.MSun) * (1 |units.parsec / units.Myr) **2 ) - self.assertAlmostRelativeEquals(particles.potential_energy(), -constants.G * (0.5 | units.MSun) ** 2 / ([2,0,0] | units.parsec).length() ) + self.assertAlmostRelativeEquals(particles.kinetic_energy(), 1.0 * (0.5 | units.MSun) * (1 | units.parsec / units.Myr) ** 2) + self.assertAlmostRelativeEquals(particles.potential_energy(), -constants.G * (0.5 | units.MSun) ** 2 / ([2, 0, 0] | units.parsec).length()) self.assertAlmostRelativeEquals(particles.virial_radius(), 4.0 | units.parsec) - + particles.scale_to_standard(convert_nbody) self.assertAlmostRelativeEquals(particles.total_mass(), convert_nbody.to_si(1.0 | nbody_system.mass)) self.assertAlmostRelativeEquals(particles.kinetic_energy(), convert_nbody.to_si(0.25 | nbody_system.energy)) self.assertAlmostRelativeEquals(particles.potential_energy().as_quantity_in(units.J), convert_nbody.to_si(-0.5 | nbody_system.energy).as_quantity_in(units.J), 12) self.assertAlmostRelativeEquals(particles.virial_radius(), convert_nbody.to_si(1.0 | nbody_system.length)) - - particles.scale_to_standard(convert_nbody, virial_ratio=1) # unbound + + particles.scale_to_standard(convert_nbody, virial_ratio=1) # unbound self.assertAlmostRelativeEquals(particles.kinetic_energy(), 0.5 * constants.G * (1 | units.MSun**2 / units.parsec), 13) self.assertAlmostRelativeEquals(particles.potential_energy(), -0.5 * constants.G * (1 | units.MSun**2 / units.parsec)) - particles.scale_to_standard(convert_nbody, virial_ratio=0) # velocities zeroed + particles.scale_to_standard(convert_nbody, virial_ratio=0) # velocities zeroed self.assertAlmostRelativeEquals(particles.kinetic_energy(), 0 | units.J) self.assertAlmostRelativeEquals(particles.potential_energy(), -0.5 * constants.G * (1 | units.MSun**2 / units.parsec)) - + def test7(self): print("Test minimum_spanning_tree_length") particles = Particles(6) - particles.position = [[-5,0,0], [-1,0,0], [0,0,0], [0,1,0], [0,-2,0], [-1,0.1,0]] | units.m + particles.position = [[-5, 0, 0], [-1, 0, 0], [0, 0, 0], [0, 1, 0], [0, -2, 0], [-1, 0.1, 0]] | units.m self.assertEqual(particles[:1].minimum_spanning_tree_length(), 0 | units.m) self.assertEqual(particles[:2].minimum_spanning_tree_length(), 4 | units.m) self.assertEqual(particles[:3].minimum_spanning_tree_length(), 5 | units.m) self.assertEqual(particles[:4].minimum_spanning_tree_length(), 6 | units.m) self.assertEqual(particles[:5].minimum_spanning_tree_length(), 8 | units.m) self.assertEqual(particles[:6].minimum_spanning_tree_length(), 8.1 | units.m) - + def test8(self): print("Test mass_segregation_ratio") numpy.random.seed(123) @@ -83,15 +84,15 @@ def test8(self): particles = new_plummer_sphere(number_of_particles) particles.r_squared = particles.position.lengths_squared() sorted = particles.sorted_by_attribute("r_squared") - + sorted.mass = numpy.random.uniform(1.0, 2.0, number_of_particles) | nbody_system.mass MSR = sorted.mass_segregation_ratio(number_of_particles=10, number_of_random_sets=10) - + if sys.hexversion > 0x03000000: self.assertAlmostEqual(MSR, 0.7160, 3) else: self.assertAlmostEqual(MSR, 0.8877, 3) - + random.seed(456) result = sorted.mass_segregation_ratio(number_of_particles=10, number_of_random_sets=10, also_compute_uncertainty=True) self.assertTrue(isinstance(result, particle_attributes.MassSegregationRatioResults)) @@ -103,19 +104,19 @@ def test8(self): self.assertAlmostEqual(result.uncertainty, 0.2482, 3) MSR, sigma = sorted.mass_segregation_ratio(number_of_particles=10, number_of_random_sets=50, also_compute_uncertainty=True) self.assertTrue(MSR - sigma < 1.0 < MSR + sigma) - + sorted.mass = numpy.linspace(1.0, 2.0, number_of_particles) | nbody_system.mass - MSR, sigma = sorted.mass_segregation_ratio(number_of_particles=10, number_of_random_sets=20, + MSR, sigma = sorted.mass_segregation_ratio(number_of_particles=10, number_of_random_sets=20, also_compute_uncertainty=True) self.assertTrue(MSR < 0.1) self.assertTrue(sigma < MSR) - + sorted.mass = numpy.linspace(2.0, 1.0, number_of_particles) | nbody_system.mass - MSR, sigma = sorted.mass_segregation_ratio(number_of_particles=10, number_of_random_sets=20, + MSR, sigma = sorted.mass_segregation_ratio(number_of_particles=10, number_of_random_sets=20, also_compute_uncertainty=True) self.assertTrue(MSR > 10.0) self.assertTrue(sigma < MSR) - + def test9(self): print("Test __doc__ and help for particle attributes") particles = Particles(2) @@ -124,45 +125,45 @@ def test9(self): self.assertEqual(particles.kinetic_energy.__class__._function.__name__, "kinetic_energy") # __doc__ must be defined on the __class__ for the Python help to work: self.assertTrue("Returns the total kinetic energy of the\n particles in the particles set." in particles.kinetic_energy.__class__.__doc__) - + # difference between particle function and particleS function: self.assertTrue("Returns the specific kinetic energy of each particle in the set." in particles.specific_kinetic_energy.__doc__) self.assertTrue("Returns the specific kinetic energy of each particle in the set." in particles.specific_kinetic_energy.__class__.__doc__) self.assertTrue("Returns the specific kinetic energy of the particle." in particles[0].specific_kinetic_energy.__doc__) self.assertTrue("Returns the specific kinetic energy of the particle." in particles[0].specific_kinetic_energy.__class__.__doc__) - + self.assertTrue("Returns the potential at the position of each particle in the set." in particles.potential.__doc__) self.assertTrue("Returns the potential at the position of each particle in the set." in particles.potential.__class__.__doc__) self.assertTrue("Returns the potential at the position of the particle." in particles[0].potential.__doc__) self.assertTrue("Returns the potential at the position of the particle." in particles[0].potential.__class__.__doc__) - + def test10(self): particles = Particles(2) - particles.position = [[1, 0, 0], [2,0,0]] | units.m - particles.velocity = [[3, 0, 0], [4,0,0]] | units.m / units.s + particles.position = [[1, 0, 0], [2, 0, 0]] | units.m + particles.velocity = [[3, 0, 0], [4, 0, 0]] | units.m / units.s particles.mass = 1 | units.kg - + self.assertEqual(particles.total_mass(), 2 | units.kg) self.assertEqual(particles.total_momentum(), [7, 0, 0] | units.kg * units.m / units.s) self.assertEqual(particles.total_momentum(), particles.total_mass() * particles.center_of_mass_velocity()) self.assertEqual(particles.total_radius(), 0.5 | units.m) - + convert_nbody = nbody_system.nbody_to_si(1000 | units.kg, 1e-6 | units.m) numpy.random.seed(123) - field = new_plummer_sphere(10000, convert_nbody) # small clump of particles, can be regarded as point mass + field = new_plummer_sphere(10000, convert_nbody) # small clump of particles, can be regarded as point mass self.assertAlmostRelativeEquals(particles.potential_energy_in_field(field), -constants.G * (1500 | units.kg**2 / units.m), 5) self.assertAlmostEqual(particles.potential_energy_in_field(field), -1.001142 | 1e-7 * units.kg * units.m**2 / units.s**2, 5) - - field.position *= ((5 | units.m) / field.position.lengths()).reshape((-1, 1)) # spherical shell around particles + + field.position *= ((5 | units.m) / field.position.lengths()).reshape((-1, 1)) # spherical shell around particles potential_energy = particles.potential_energy_in_field(field) - particles.position += [0, 1, 2] | units.m # as long as particles remain inside the shell, the potential doesn't change + particles.position += [0, 1, 2] | units.m # as long as particles remain inside the shell, the potential doesn't change self.assertAlmostEqual(particles.potential_energy_in_field(field), potential_energy, 5) - + particles.mass = [1, 2] | units.kg self.assertAlmostRelativeEquals(particles.potential(), -constants.G * ([2, 1] | units.kg / units.m)) self.assertAlmostRelativeEquals(particles.potential()[0], particles[0].potential()) self.assertAlmostRelativeEquals(particles.potential()[1], particles[1].potential()) - + def test11(self): print("Test nearest_neighbour") particles = Particles(21) @@ -171,29 +172,30 @@ def test11(self): particles.z = 0.0 | units.m self.assertEqual(particles.nearest_neighbour()[0], particles[1]) self.assertEqual(particles.nearest_neighbour()[1:].key, particles[:-1].key) - + neighbours = Particles(3) neighbours.x = [1.0, 10.0, 100.0] | units.m neighbours.y = 0.0 | units.m neighbours.z = 0.0 | units.m self.assertEqual(particles.nearest_neighbour(neighbours).key, neighbours.key[[0]*8 + [1]*10 + [2]*3]) - + # A few tests to check the correct behaviour of 'max_array_length' (to prevent memory overflow) - nearest_neighbours = particles.nearest_neighbour(max_array_length=3*21*21) # all in one go + nearest_neighbours = particles.nearest_neighbour(max_array_length=3*21*21) # all in one go self.assertEqual(nearest_neighbours[0], particles[1]) self.assertEqual(nearest_neighbours[1:].key, particles[:-1].key) - nearest_neighbours = particles.nearest_neighbour(max_array_length=3*21*21-1) # two passes + nearest_neighbours = particles.nearest_neighbour(max_array_length=3*21*21-1) # two passes self.assertEqual(nearest_neighbours[0], particles[1]) self.assertEqual(nearest_neighbours[1:].key, particles[:-1].key) - nearest_neighbours = particles.nearest_neighbour(max_array_length=1) # 21 passes, one for each particle + nearest_neighbours = particles.nearest_neighbour(max_array_length=1) # 21 passes, one for each particle self.assertEqual(nearest_neighbours[0], particles[1]) self.assertEqual(nearest_neighbours[1:].key, particles[:-1].key) - self.assertEqual(particles.nearest_neighbour(neighbours, max_array_length=189).key, neighbours.key[[0]*8 + [1]*10 + [2]*3]) # all in one go - self.assertEqual(particles.nearest_neighbour(neighbours, max_array_length=188).key, neighbours.key[[0]*8 + [1]*10 + [2]*3]) # two passes - self.assertEqual(particles.nearest_neighbour(neighbours, max_array_length=1).key, neighbours.key[[0]*8 + [1]*10 + [2]*3]) # 21 passes, one for each particle - + self.assertEqual(particles.nearest_neighbour(neighbours, max_array_length=189).key, neighbours.key[[0]*8 + [1]*10 + [2]*3]) # all in one go + self.assertEqual(particles.nearest_neighbour(neighbours, max_array_length=188).key, neighbours.key[[0]*8 + [1]*10 + [2]*3]) # two passes + self.assertEqual(particles.nearest_neighbour(neighbours, max_array_length=1).key, neighbours.key[[0]*8 + [1]*10 + [2]*3]) # 21 passes, one for each particle + def new_koch_star(self, level=5): height = numpy.sqrt(3) / 6.0 + def next_iteration(x_values, y_values): dx = x_values[1:] - x_values[:-1] dy = y_values[1:] - y_values[:-1] @@ -210,7 +212,7 @@ def next_iteration(x_values, y_values): for i in range(level): x, y = next_iteration(x, y) return x, y - + def test12(self): print("Test correlation_dimension") # Particles distributed uniformly in 3D @@ -221,21 +223,21 @@ def test12(self): # Fractal dimension is scale-free particles.position *= 1000 self.assertAlmostRelativeEquals(dimension, particles.correlation_dimension(), 10) - + # Particles distributed in the x-y plane particles.position = numpy.concatenate((numpy.mgrid[0:27.0, 0:27.0].reshape(2, -1), numpy.zeros((1, 729)))).transpose() | units.m dimension = particles.correlation_dimension() self.assertAlmostRelativeEquals(dimension, 2.0, 1) particles.position *= 1000 self.assertAlmostRelativeEquals(dimension, particles.correlation_dimension(), 10) - + # Particles distributed along a line particles.position = numpy.concatenate([numpy.arange(729.0).reshape(1, -1)]*3).transpose() | units.m dimension = particles.correlation_dimension() self.assertAlmostRelativeEquals(dimension, 1.0, 1) particles.position *= 1000 self.assertAlmostRelativeEquals(dimension, particles.correlation_dimension(), 10) - + # Particles on a Koch curve x, y = self.new_koch_star(level=6) numpy.random.seed(123456) @@ -245,7 +247,7 @@ def test12(self): self.assertAlmostRelativeEquals(dimension, 1.26186, 1) particles.position *= 1000 self.assertAlmostRelativeEquals(dimension, particles.correlation_dimension(), 10) - + def test13(self): print("Test box_counting_dimension") # Particles distributed uniformly in 3D @@ -256,21 +258,21 @@ def test13(self): # Fractal dimension is scale-free particles.position *= 1000 self.assertAlmostRelativeEquals(dimension, particles.box_counting_dimension(), 10) - + # Particles distributed in the x-y plane particles.position = numpy.concatenate((numpy.mgrid[0:64.0, 0:64.0].reshape(2, -1), numpy.zeros((1, 4096)))).transpose() | units.m dimension = particles.box_counting_dimension() self.assertAlmostRelativeEquals(dimension, 2.0, 1) particles.position *= 1000 self.assertAlmostRelativeEquals(dimension, particles.box_counting_dimension(), 10) - + # Particles distributed along a line particles.position = numpy.concatenate([numpy.arange(4096.0).reshape(1, -1)]*3).transpose() | units.m dimension = particles.box_counting_dimension() self.assertAlmostRelativeEquals(dimension, 1.0, 1) particles.position *= 1000 self.assertAlmostRelativeEquals(dimension, particles.box_counting_dimension(), 10) - + # Particles on a Koch curve x, y = self.new_koch_star(level=7) numpy.random.seed(123456) @@ -280,7 +282,7 @@ def test13(self): self.assertAlmostRelativeEquals(dimension, 1.26186, 1) particles.position *= 1000 self.assertAlmostRelativeEquals(dimension, particles.box_counting_dimension(), 10) - + def test14(self): print("Test mass_segregation_from_nearest_neighbour") numpy.random.seed(123) @@ -289,31 +291,31 @@ def test14(self): particles = new_plummer_sphere(number_of_particles) particles.r_squared = particles.position.lengths_squared() sorted = particles.sorted_by_attribute("r_squared") - + sorted.mass = numpy.random.uniform(1.0, 2.0, number_of_particles) | nbody_system.mass MSR, sigma = sorted.mass_segregation_from_nearest_neighbour(number_of_particles=10, also_compute_uncertainty=True) - + if sys.hexversion > 0x03000000: self.assertAlmostEqual(MSR, 1.72632, 3) self.assertAlmostEqual(sigma, 0.4127, 3) else: self.assertAlmostEqual(MSR, 1.7355, 3) self.assertAlmostEqual(sigma, 0.3969, 3) - + random.seed(456) MSR_of_nonsegregated_systems = [] for i in range(10): sorted.mass = numpy.random.uniform(1.0, 2.0, number_of_particles) | nbody_system.mass MSR = sorted.mass_segregation_from_nearest_neighbour(number_of_particles=10, number_of_random_sets=50) MSR_of_nonsegregated_systems.append(MSR) - self.assertAlmostEqual((MSR_of_nonsegregated_systems|units.none).mean(), 1.0, 1) - self.assertAlmostEqual((MSR_of_nonsegregated_systems|units.none).std(), 0.3, 1) - + self.assertAlmostEqual((MSR_of_nonsegregated_systems | units.none).mean(), 1.0, 1) + self.assertAlmostEqual((MSR_of_nonsegregated_systems | units.none).std(), 0.3, 1) + sorted.mass = numpy.linspace(2.0, 1.0, number_of_particles) | nbody_system.mass - MSR, sigma = sorted.mass_segregation_from_nearest_neighbour(number_of_particles=10, number_of_random_sets=20, + MSR, sigma = sorted.mass_segregation_from_nearest_neighbour(number_of_particles=10, number_of_random_sets=20, also_compute_uncertainty=True) self.assertTrue(MSR > 5.0) - + if sys.hexversion > 0x03000000: self.assertAlmostEqual(sigma, 0.3, 1) else: @@ -322,38 +324,38 @@ def test14(self): def test15(self): scale_R = 1.0 | units.parsec scale_M = 1000.0 | units.MSun - converter = nbody_system.nbody_to_si(scale_M,scale_R) + converter = nbody_system.nbody_to_si(scale_M, scale_R) for n in range(3162, 3165, 1): stars = new_plummer_sphere( - n, + n, convert_nbody=converter, ) - stars.mass=(numpy.arange(1,n+1)/(1.*n)) | units.MSun + stars.mass = (numpy.arange(1, n+1)/(1.*n)) | units.MSun potential = stars.potential() - for i,x in enumerate(stars): - self.assertAlmostRelativeEqual(potential[i],x.potential()) + for i, x in enumerate(stars): + self.assertAlmostRelativeEqual(potential[i], x.potential()) def test16(self): scale_R = 1.0 | units.parsec scale_M = 1000.0 | units.MSun - converter = nbody_system.nbody_to_si(scale_M,scale_R) + converter = nbody_system.nbody_to_si(scale_M, scale_R) for n in range(0, 50): stars = new_plummer_sphere( - 50, + 50, convert_nbody=converter, ) - stars.mass=numpy.arange(1,51) | units.MSun + stars.mass = numpy.arange(1, 51) | units.MSun potential = stars.potential(block_size=n) - for i,x in enumerate(stars): - self.assertAlmostRelativeEqual(potential[i],x.potential()) + for i, x in enumerate(stars): + self.assertAlmostRelativeEqual(potential[i], x.potential()) class TestParticlesDomainAttributes(amusetest.TestCase): - + def test1(self): particles = Particles(2) particles.add_attribute_domain('a') @@ -361,11 +363,11 @@ def test1(self): particles.a.foo = 1 | units.m particles.b.foo = 2 | units.kg particles.foo = 3 | units.s - + self.assertAlmostRelativeEqual(particles.a.foo, 1 | units.m) self.assertAlmostRelativeEqual(particles.b.foo, 2 | units.kg) self.assertAlmostRelativeEqual(particles.foo, 3 | units.s) - + def test2(self): particles = Particles(2) particles.add_attribute_domain('a') @@ -374,14 +376,14 @@ def test2(self): particles.b.bar = 2 | units.kg particles.foo = 3 | units.s self.assertEqual( - sorted(particles.a.get_attribute_names_defined_in_store()), + sorted(particles.a.get_attribute_names_defined_in_store()), ['foo'] ) self.assertEqual( - sorted(particles.b.get_attribute_names_defined_in_store()), + sorted(particles.b.get_attribute_names_defined_in_store()), ['bar'] ) - + def test3(self): particles = Particles(2) particles.add_attribute_domain('a') @@ -389,22 +391,22 @@ def test3(self): particles.a.foo = 1 | units.m particles.b.foo = 2 | units.kg particles.foo = 3 | units.s - particles.a.add_particle(Particle(foo = 2 | units.m)) - - self.assertAlmostRelativeEqual(particles.a.foo, [1,1,2] | units.m) - self.assertAlmostRelativeEqual(particles.b.foo, [2,2,0] | units.kg) - self.assertAlmostRelativeEqual(particles.foo, [3,3,0] | units.s) - - particles.add_particle(Particle(foo = 2 | units.s)) - self.assertAlmostRelativeEqual(particles.a.foo, [1,1,2,0] | units.m) - self.assertAlmostRelativeEqual(particles.b.foo, [2,2,0,0] | units.kg) - self.assertAlmostRelativeEqual(particles.foo, [3,3,0,2] | units.s) - - + particles.a.add_particle(Particle(foo=2 | units.m)) + + self.assertAlmostRelativeEqual(particles.a.foo, [1, 1, 2] | units.m) + self.assertAlmostRelativeEqual(particles.b.foo, [2, 2, 0] | units.kg) + self.assertAlmostRelativeEqual(particles.foo, [3, 3, 0] | units.s) + + particles.add_particle(Particle(foo=2 | units.s)) + self.assertAlmostRelativeEqual(particles.a.foo, [1, 1, 2, 0] | units.m) + self.assertAlmostRelativeEqual(particles.b.foo, [2, 2, 0, 0] | units.kg) + self.assertAlmostRelativeEqual(particles.foo, [3, 3, 0, 2] | units.s) + def test4(self): particles = Particles(2) particles.add_attribute_domain('a') particles.add_attribute_domain('b') + def set_a(): particles.a = 1 | units.kg self.assertRaises(AttributeError, set_a) @@ -416,21 +418,22 @@ def test5(self): particles.a.foo = 1 | units.m particles.b.foo = 2 | units.kg particles.foo = 3 | units.s - + particles.a[0].foo = 3 | units.m - - self.assertAlmostRelativeEqual(particles.a.foo, [3,1] | units.m) - + + self.assertAlmostRelativeEqual(particles.a.foo, [3, 1] | units.m) + particles[0].a.foo = 4 | units.m - - self.assertAlmostRelativeEqual(particles.a.foo, [4,1] | units.m) - self.assertAlmostRelativeEqual(particles.b.foo, [2,2] | units.kg) - self.assertAlmostRelativeEqual(particles.foo, [3,3] | units.s) + + self.assertAlmostRelativeEqual(particles.a.foo, [4, 1] | units.m) + self.assertAlmostRelativeEqual(particles.b.foo, [2, 2] | units.kg) + self.assertAlmostRelativeEqual(particles.foo, [3, 3] | units.s) def test6(self): particles = Particles(2) particles.add_attribute_domain('a') particles.add_attribute_domain('b') + def set_a(): particles[0].a = 1 | units.kg self.assertRaises(AttributeError, set_a) diff --git a/src/amuse/test/suite/core_tests/test_particles.py b/src/amuse/test/suite/core_tests/test_particles.py index 9441e8a106..1ecca0eecf 100644 --- a/src/amuse/test/suite/core_tests/test_particles.py +++ b/src/amuse/test/suite/core_tests/test_particles.py @@ -24,79 +24,78 @@ class TestParticles(amusetest.TestCase): def test1(self): - particles = datamodel.Particles(keys = [10,11]) - particles.mass = [1,2] | units.kg - self.assertAlmostRelativeEquals(particles.mass, [1,2] | units.kg) + particles = datamodel.Particles(keys=[10, 11]) + particles.mass = [1, 2] | units.kg + self.assertAlmostRelativeEquals(particles.mass, [1, 2] | units.kg) self.assertEqual(len(particles), 2) def test2(self): - particles = datamodel.Particles(keys = [10,11]) - particles.mass = [1,2] | units.kg - particles2 = datamodel.Particles(keys = [20,21]) - particles2.mass = [3,4] | units.kg + particles = datamodel.Particles(keys=[10, 11]) + particles.mass = [1, 2] | units.kg + particles2 = datamodel.Particles(keys=[20, 21]) + particles2.mass = [3, 4] | units.kg particles.add_particles(particles2) self.assertEqual(len(particles), 4) - self.assertAlmostRelativeEquals(particles.mass, [1,2, 3,4] | units.kg) - self.assertEqual(particles.key, [10,11,20,21]) + self.assertAlmostRelativeEquals(particles.mass, [1, 2, 3, 4] | units.kg) + self.assertEqual(particles.key, [10, 11, 20, 21]) def test3(self): - particles = datamodel.Particles(keys = [10,11]) - particles.mass = [1,2] | units.kg - particles2 = datamodel.Particles(keys = [20,21]) - particles2.mass = [3,4] | units.kg + particles = datamodel.Particles(keys=[10, 11]) + particles.mass = [1, 2] | units.kg + particles2 = datamodel.Particles(keys=[20, 21]) + particles2.mass = [3, 4] | units.kg particles.add_particles(particles2) particles.remove_particles(particles2) self.assertEqual(len(particles), 2) - self.assertAlmostRelativeEquals(particles.mass, [1,2] | units.kg) + self.assertAlmostRelativeEquals(particles.mass, [1, 2] | units.kg) def test4(self): - particles = datamodel.Particles(keys = [10,11]) - particles.a = [1,2] - self.assertAlmostRelativeEquals(particles.a, [1,2] ) + particles = datamodel.Particles(keys=[10, 11]) + particles.a = [1, 2] + self.assertAlmostRelativeEquals(particles.a, [1, 2]) def test5(self): - particles = datamodel.Particles(keys = [10,11]) + particles = datamodel.Particles(keys=[10, 11]) particles.add_vector_attribute('position2d', ['x', 'y']) - particles.x = [1,2] | units.m - particles.y = [3,4] | units.m - self.assertAlmostRelativeEquals(particles.position2d, [[1,3], [2,4]] | units.m ) - particles.position2d = [[5,6], [7,8]] | units.m - self.assertAlmostRelativeEquals(particles.x, [5,7] | units.m) - self.assertAlmostRelativeEquals(particles.y, [6,8] | units.m) + particles.x = [1, 2] | units.m + particles.y = [3, 4] | units.m + self.assertAlmostRelativeEquals(particles.position2d, [[1, 3], [2, 4]] | units.m) + particles.position2d = [[5, 6], [7, 8]] | units.m + self.assertAlmostRelativeEquals(particles.x, [5, 7] | units.m) + self.assertAlmostRelativeEquals(particles.y, [6, 8] | units.m) def test6(self): - particles = datamodel.Particles(keys = [10,11]) - particles.add_calculated_attribute("xy", lambda x, y : x * y) - particles.x = [2,3] | units.m - particles.y = [4,5] | units.m - self.assertAlmostRelativeEquals(particles.xy, [8,15] | units.m*units.m) + particles = datamodel.Particles(keys=[10, 11]) + particles.add_calculated_attribute("xy", lambda x, y: x * y) + particles.x = [2, 3] | units.m + particles.y = [4, 5] | units.m + self.assertAlmostRelativeEquals(particles.xy, [8, 15] | units.m*units.m) def test7(self): - particles = datamodel.Particles(keys = [10,11]) - particles.mass = [1,2] | units.kg + particles = datamodel.Particles(keys=[10, 11]) + particles.mass = [1, 2] | units.kg particles2 = particles.copy() - self.assertAlmostRelativeEquals(particles2.mass, [1,2] | units.kg) - particles.mass = [3,4] | units.kg - self.assertAlmostRelativeEquals(particles2.mass, [1,2] | units.kg) - particles2.mass = [5,6] | units.kg - self.assertAlmostRelativeEquals(particles.mass, [3,4] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [1, 2] | units.kg) + particles.mass = [3, 4] | units.kg + self.assertAlmostRelativeEquals(particles2.mass, [1, 2] | units.kg) + particles2.mass = [5, 6] | units.kg + self.assertAlmostRelativeEquals(particles.mass, [3, 4] | units.kg) def test8(self): - particles = datamodel.Particles(keys = [10,11]) - particles.mass = [1,2] | units.kg + particles = datamodel.Particles(keys=[10, 11]) + particles.mass = [1, 2] | units.kg particles2 = particles.copy() - self.assertAlmostRelativeEquals(particles2.mass, [1,2] | units.kg) - particles.mass = [3,4] | units.kg - self.assertAlmostRelativeEquals(particles2.mass, [1,2] | units.kg) - particles2.mass = [5,6] | units.kg - self.assertAlmostRelativeEquals(particles.mass, [3,4] | units.kg) - + self.assertAlmostRelativeEquals(particles2.mass, [1, 2] | units.kg) + particles.mass = [3, 4] | units.kg + self.assertAlmostRelativeEquals(particles2.mass, [1, 2] | units.kg) + particles2.mass = [5, 6] | units.kg + self.assertAlmostRelativeEquals(particles.mass, [3, 4] | units.kg) def test9(self): - particles = datamodel.Particles(keys = [10,11]) - particles.mass = [1,2] | units.kg + particles = datamodel.Particles(keys=[10, 11]) + particles.mass = [1, 2] | units.kg outputstring = str(particles) self.assertEqual(outputstring.strip(), textwrap.dedent(""" @@ -107,24 +106,22 @@ def test9(self): 11 2.000e+00 ==================== ===========""").strip()) - def test10(self): - particles = datamodel.Particles(keys = numpy.arange(50,dtype='int32')) + particles = datamodel.Particles(keys=numpy.arange(50, dtype='int32')) particles.mass = numpy.arange(50) | units.kg outputstring = str(particles) lines = outputstring.splitlines() self.assertEqual(len(lines), 45) - self.assertEqual(lines[22]," 19 1.900e+01" ) - self.assertEqual(lines[23]," ... ..." ) - self.assertEqual(lines[24]," 30 3.000e+01" ) - + self.assertEqual(lines[22], " 19 1.900e+01") + self.assertEqual(lines[23], " ... ...") + self.assertEqual(lines[24], " 30 3.000e+01") def test11(self): - particles1 = datamodel.Particles(keys=[10,11,12,13]) - particles1.mass = (numpy.arange(4) + 1)| units.kg - particles2 = datamodel.Particles(keys=[11,12,14]) - particles2.mass = (numpy.arange(3) + 10)| units.kg + particles1 = datamodel.Particles(keys=[10, 11, 12, 13]) + particles1.mass = (numpy.arange(4) + 1) | units.kg + particles2 = datamodel.Particles(keys=[11, 12, 14]) + particles2.mass = (numpy.arange(3) + 10) | units.kg particles1.synchronize_to(particles2) self.assertEqual(len(particles2), 4) @@ -135,49 +132,47 @@ def test11(self): self.assertFalse(particles2.has_key_in_store(14)) def test12(self): - particles = datamodel.Particles(keys=[10,11,12,13]) - particles.mass = [10,9,8,7] | units.kg - particles.x = [7,8,9,10] | units.kg + particles = datamodel.Particles(keys=[10, 11, 12, 13]) + particles.mass = [10, 9, 8, 7] | units.kg + particles.x = [7, 8, 9, 10] | units.kg sorted = particles.sorted_by_attribute('mass') - self.assertAlmostRelativeEquals(sorted.mass, [7,8,9,10] | units.kg) - self.assertAlmostRelativeEquals(sorted.x, [10,9,8,7] | units.kg) + self.assertAlmostRelativeEquals(sorted.mass, [7, 8, 9, 10] | units.kg) + self.assertAlmostRelativeEquals(sorted.x, [10, 9, 8, 7] | units.kg) def test13(self): - particles = datamodel.Particles(keys=[10,11,12,13]) - particles.mass = [10,9,10,9] | units.kg - particles.x = [2,2,1,1] | units.kg - particles.y = [1,2,3,4] | units.kg + particles = datamodel.Particles(keys=[10, 11, 12, 13]) + particles.mass = [10, 9, 10, 9] | units.kg + particles.x = [2, 2, 1, 1] | units.kg + particles.y = [1, 2, 3, 4] | units.kg sorted = particles.sorted_by_attributes('x', 'mass') - self.assertAlmostRelativeEquals(sorted.mass, [9,9,10,10] | units.kg) - self.assertAlmostRelativeEquals(sorted.x, [1,2,1,2] | units.kg) - self.assertAlmostRelativeEquals(sorted.y, [4,2,3,1] | units.kg) + self.assertAlmostRelativeEquals(sorted.mass, [9, 9, 10, 10] | units.kg) + self.assertAlmostRelativeEquals(sorted.x, [1, 2, 1, 2] | units.kg) + self.assertAlmostRelativeEquals(sorted.y, [4, 2, 3, 1] | units.kg) - sorted = sorted.sorted_by_attributes('mass','x') - - self.assertAlmostRelativeEquals(sorted.mass, [9,10,9,10] | units.kg) - self.assertAlmostRelativeEquals(sorted.x, [1,1,2,2] | units.kg) - self.assertAlmostRelativeEquals(sorted.y, [4,3,2,1] | units.kg) + sorted = sorted.sorted_by_attributes('mass', 'x') + self.assertAlmostRelativeEquals(sorted.mass, [9, 10, 9, 10] | units.kg) + self.assertAlmostRelativeEquals(sorted.x, [1, 1, 2, 2] | units.kg) + self.assertAlmostRelativeEquals(sorted.y, [4, 3, 2, 1] | units.kg) def test14(self): - particles = datamodel.Particles(keys = [10,11]) - particles.mass = [1,2] | units.kg - particles.r = [1,2] | units.m - particles2 = particles.copy(filter_attributes = lambda p, x : x != 'r') + particles = datamodel.Particles(keys=[10, 11]) + particles.mass = [1, 2] | units.kg + particles.r = [1, 2] | units.m + particles2 = particles.copy(filter_attributes=lambda p, x: x != 'r') self.assertTrue(hasattr(particles2, 'mass')) self.assertFalse(hasattr(particles2, 'r')) - def test15(self): - particles = datamodel.Particles(keys = [10,11]) - particles.mass = [1,2] | units.kg + particles = datamodel.Particles(keys=[10, 11]) + particles.mass = [1, 2] | units.kg particles2 = particles.copy_to_new_particles() - self.assertAlmostRelativeEquals(particles2.mass, [1,2] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [1, 2] | units.kg) self.assertAlmostRelativeEquals(particles2[1].mass, 2 | units.kg) self.assertNotEqual(particles[1].key, particles2[1].key) @@ -193,12 +188,11 @@ def test16(self): self.assertEqual(len(particles.difference(subset2)), 6000) # Overlap should be roughly 1000 (0.25 * 0.4 * 10000) number_of_overlapping_particles = len(subset2.get_intersecting_subset_in(subset)) - self.assertTrue(number_of_overlapping_particles > 975) + self.assertTrue(number_of_overlapping_particles > 975) self.assertTrue(number_of_overlapping_particles < 1025) - def test17(self): - names = ('123','1234', '12345') + names = ('123', '1234', '12345') particles = datamodel.Particles(3) particles.name = names for i in range(3): @@ -206,29 +200,27 @@ def test17(self): particles[1].name = '123456' self.assertEqual(particles[1].name, '123456') - - + def test18(self): - particles = datamodel.Particles(keys = [10,11]) - particles.mass = [1,2] | units.kg - particles.radius = [2,3] | units.m - self.assertAlmostRelativeEquals(particles.mass, [1,2] | units.kg) - self.assertAlmostRelativeEquals(particles.radius, [2,3] | units.m) + particles = datamodel.Particles(keys=[10, 11]) + particles.mass = [1, 2] | units.kg + particles.radius = [2, 3] | units.m + self.assertAlmostRelativeEquals(particles.mass, [1, 2] | units.kg) + self.assertAlmostRelativeEquals(particles.radius, [2, 3] | units.m) del particles.radius - particles.radius = [2,3] | units.m*2 - self.assertAlmostRelativeEquals(particles.radius, [2,3] | units.m*2) - + particles.radius = [2, 3] | units.m*2 + self.assertAlmostRelativeEquals(particles.radius, [2, 3] | units.m*2) def test19(self): - particles = datamodel.Particles(keys = [10,11]) - particles.mass = [1,2] | units.kg - - particles2 = datamodel.Particles(keys = [12,13]) - particles2.mass = [3,4] | units.kg + particles = datamodel.Particles(keys=[10, 11]) + particles.mass = [1, 2] | units.kg + + particles2 = datamodel.Particles(keys=[12, 13]) + particles2.mass = [3, 4] | units.kg particles[0].child = particles2[0] particles[1].child = particles2[1] outputstring = str(particles) - + self.assertEqual(outputstring.strip(), textwrap.dedent(""" key child mass - none kg @@ -237,14 +229,12 @@ def test19(self): 11 13 2.000e+00 ==================== =========== ===========""").strip()) - - def test20(self): - particles = datamodel.Particles(keys = [10,11]) - particles.mass = [1,2] | units.kg - - particles2 = datamodel.Particles(keys = [12,13]) - particles2.mass = [3,4] | units.kg + particles = datamodel.Particles(keys=[10, 11]) + particles.mass = [1, 2] | units.kg + + particles2 = datamodel.Particles(keys=[12, 13]) + particles2.mass = [3, 4] | units.kg particles[0].child = particles2[0] particles[1].child = particles2[1] outputstring = str(particles[0]) @@ -252,21 +242,18 @@ def test20(self): self.assertEqual(outputstring.strip(), "Particle(10, set=<{1}>\n , child=Particle(12, set=<{0}>)\n , mass=1.0 kg)".format(id(particles2), id(particles)).strip()) - - - class TestParticle(amusetest.TestCase): def test1(self): - particles = datamodel.Particles(keys = [10,11]) - particles.mass = [1,2] | units.kg + particles = datamodel.Particles(keys=[10, 11]) + particles.mass = [1, 2] | units.kg self.assertAlmostRelativeEquals(particles[0].mass, 1 | units.kg) self.assertAlmostRelativeEquals(particles[1].mass, 2 | units.kg) self.assertAlmostRelativeEquals(particles[0].mass, 1 | units.kg) def test2(self): - particles = datamodel.Particles(keys = [10,11]) - particles.mass = [1,2] | units.kg + particles = datamodel.Particles(keys=[10, 11]) + particles.mass = [1, 2] | units.kg particle = particles[1] self.assertAlmostRelativeEquals(particle.mass, 2 | units.kg) particles.remove_particle(particles[0]) @@ -274,46 +261,46 @@ def test2(self): self.assertAlmostRelativeEquals(particles[0].mass, 2 | units.kg) def test3(self): - particles = datamodel.Particles(keys = [10,11]) - particles.mass = [1,2] | units.kg + particles = datamodel.Particles(keys=[10, 11]) + particles.mass = [1, 2] | units.kg self.assertAlmostRelativeEquals(particles[0].mass, 1 | units.kg) particles[0].mass = 4 | units.kg self.assertAlmostRelativeEquals(particles[0].mass, 4 | units.kg) def test4(self): - particles = datamodel.Particles(keys = [10,11]) - particles.mass = [1,2] | units.kg + particles = datamodel.Particles(keys=[10, 11]) + particles.mass = [1, 2] | units.kg self.assertAlmostRelativeEquals(particles[1].mass, 2 | units.kg) particles.add_particle(datamodel.Particle(mass=3 | units.kg)) self.assertAlmostRelativeEquals(particles[1].mass, 2 | units.kg) self.assertAlmostRelativeEquals(particles[2].mass, 3 | units.kg) def test5(self): - particles = datamodel.Particles(keys = [10,11]) - particles.add_calculated_attribute("xy", lambda x, y : x * y) - particles.x = [2,3] | units.m - particles.y = [4,5] | units.m + particles = datamodel.Particles(keys=[10, 11]) + particles.add_calculated_attribute("xy", lambda x, y: x * y) + particles.x = [2, 3] | units.m + particles.y = [4, 5] | units.m self.assertAlmostRelativeEquals(particles[0].xy, 8 | units.m*units.m) def test6(self): - particles = datamodel.Particles(keys = [10,11]) + particles = datamodel.Particles(keys=[10, 11]) particles.add_vector_attribute('position2d', ['x', 'y']) - particles.x = [1,2] | units.m - particles.y = [3,4] | units.m + particles.x = [1, 2] | units.m + particles.y = [3, 4] | units.m particle = particles[0] - self.assertAlmostRelativeEquals(particle.position2d, [1,3] | units.m) + self.assertAlmostRelativeEquals(particle.position2d, [1, 3] | units.m) - particle.position2d = [5,6] | units.m - self.assertAlmostRelativeEquals(particles.x, [5,2] | units.m) - self.assertAlmostRelativeEquals(particles.y, [6,4] | units.m) - self.assertAlmostRelativeEquals(particle.position2d, [5,6] | units.m) - self.assertAlmostRelativeEquals(particles[0].position2d, [5,6] | units.m) + particle.position2d = [5, 6] | units.m + self.assertAlmostRelativeEquals(particles.x, [5, 2] | units.m) + self.assertAlmostRelativeEquals(particles.y, [6, 4] | units.m) + self.assertAlmostRelativeEquals(particle.position2d, [5, 6] | units.m) + self.assertAlmostRelativeEquals(particles[0].position2d, [5, 6] | units.m) def test7(self): - particles = datamodel.Particles(keys = [10,11]) + particles = datamodel.Particles(keys=[10, 11]) particles.add_vector_attribute('position2d', ['x', 'y']) - particles.x = [1,2] | units.m - particles.y = [3,4] | units.m + particles.x = [1, 2] | units.m + particles.y = [3, 4] | units.m particle = particles[0] attributes = set(dir(particle)) self.assertTrue('x' in attributes) @@ -322,11 +309,11 @@ def test7(self): self.assertFalse('mass' in attributes) def test8(self): - particles1 = datamodel.Particles(keys = [10,11]) - particles1.x = [1,2] | units.m - particles1.y = [3,4] | units.m - particles2 = datamodel.Particles(keys = [10,11]) - particles2.mass = [5,6] | units.kg + particles1 = datamodel.Particles(keys=[10, 11]) + particles1.x = [1, 2] | units.m + particles1.y = [3, 4] | units.m + particles2 = datamodel.Particles(keys=[10, 11]) + particles2.mass = [5, 6] | units.kg particle1 = particles1[0] particle2 = particles2[0] @@ -335,24 +322,24 @@ def test8(self): particle12 = particle1.as_particle_in_set(particles2) self.assertEqual(particle12, particle2) self.assertEqual(particle12, particle1) - self.assertAlmostRelativeEquals(particle12.mass , 5 | units.kg) + self.assertAlmostRelativeEquals(particle12.mass, 5 | units.kg) def test9(self): - particles = datamodel.Particles(keys = [10,11,12,13]) - particles.x = [1,2,3,4] | units.m + particles = datamodel.Particles(keys=[10, 11, 12, 13]) + particles.x = [1, 2, 3, 4] | units.m i = 1 for particle in particles: - self.assertEqual(particle.x , i | units.m) + self.assertEqual(particle.x, i | units.m) i += 1 def test10(self): - particles = datamodel.Particles(keys = [10,11]) - particles.x = [1,2] | units.m - particles.y = [3,4] | units.m + particles = datamodel.Particles(keys=[10, 11]) + particles.x = [1, 2] | units.m + particles.y = [3, 4] | units.m particles.add_function_attribute( "xy", - lambda allparticles, a : (allparticles.x * allparticles.y) + a, - lambda allparticles, one, a : (one.x * one.y) + (2*a) + lambda allparticles, a: (allparticles.x * allparticles.y) + a, + lambda allparticles, one, a: (one.x * one.y) + (2*a) ) print(particles.xy) @@ -366,8 +353,8 @@ def test10(self): ) def test11(self): - particles = datamodel.Particles(keys = [10,11,8,7]) - particles.mass = [1,2,3,4] | units.kg + particles = datamodel.Particles(keys=[10, 11, 8, 7]) + particles.mass = [1, 2, 3, 4] | units.kg particle = particles[1] self.assertAlmostRelativeEquals(particle.mass, 2 | units.kg) particles.remove_particle(particles[0]) @@ -377,16 +364,15 @@ def test11(self): self.assertAlmostRelativeEquals(particles[1].mass, 4 | units.kg) def test12(self): - particles = datamodel.Particles(keys=[9,10,11,12,13,14]) - particles.mass = [1,2,3,4,20,21] | units.kg + particles = datamodel.Particles(keys=[9, 10, 11, 12, 13, 14]) + particles.mass = [1, 2, 3, 4, 20, 21] | units.kg self.assertAlmostRelativeEquals(particles[-3].mass, 4 | units.kg) self.assertAlmostRelativeEquals(particles[-1].mass, 21 | units.kg) - def test1(self): - particles = datamodel.Particles(keys = [10,11]) - particles.mass = [1,2] | units.kg + particles = datamodel.Particles(keys=[10, 11]) + particles.mass = [1, 2] | units.kg self.assertAlmostRelativeEquals(particles[0].mass, 1 | units.kg) copy = particles[0].empty_copy() self.assertFalse(hasattr(copy, 'mass')) @@ -396,162 +382,160 @@ def test1(self): class TestParticlesSubset(amusetest.TestCase): def test1(self): - particles = datamodel.Particles(keys = [10,11,12]) - particles.mass = [1,2,3] | units.kg - self.assertAlmostRelativeEquals(particles[0:2].mass, [1,2] | units.kg) + particles = datamodel.Particles(keys=[10, 11, 12]) + particles.mass = [1, 2, 3] | units.kg + self.assertAlmostRelativeEquals(particles[0:2].mass, [1, 2] | units.kg) self.assertEqual(len(particles[0:2]), 2) - self.assertAlmostRelativeEquals(particles[1::-1].mass, [2,1] | units.kg) + self.assertAlmostRelativeEquals(particles[1::-1].mass, [2, 1] | units.kg) def test2(self): - particles = datamodel.Particles(keys = [10,11,12]) - particles.mass = [1,2,3] | units.kg + particles = datamodel.Particles(keys=[10, 11, 12]) + particles.mass = [1, 2, 3] | units.kg subset = particles[0:2] - self.assertAlmostRelativeEquals(subset.mass, [1,2] | units.kg) - subset.mass = [4,5] | units.kg - self.assertAlmostRelativeEquals(subset.mass, [4,5] | units.kg) - self.assertAlmostRelativeEquals(particles.mass, [4,5,3] | units.kg) + self.assertAlmostRelativeEquals(subset.mass, [1, 2] | units.kg) + subset.mass = [4, 5] | units.kg + self.assertAlmostRelativeEquals(subset.mass, [4, 5] | units.kg) + self.assertAlmostRelativeEquals(particles.mass, [4, 5, 3] | units.kg) def test3(self): - particles = datamodel.Particles(keys = [10,11,12]) - particles.mass = [1,2,3] | units.kg + particles = datamodel.Particles(keys=[10, 11, 12]) + particles.mass = [1, 2, 3] | units.kg subset = particles[1::-1] - self.assertAlmostRelativeEquals(subset.mass, [2,1] | units.kg) - subset.mass = [4,5] | units.kg - self.assertAlmostRelativeEquals(subset.mass, [4,5] | units.kg) - self.assertAlmostRelativeEquals(particles.mass, [5,4,3] | units.kg) + self.assertAlmostRelativeEquals(subset.mass, [2, 1] | units.kg) + subset.mass = [4, 5] | units.kg + self.assertAlmostRelativeEquals(subset.mass, [4, 5] | units.kg) + self.assertAlmostRelativeEquals(particles.mass, [5, 4, 3] | units.kg) def test4(self): - particles = datamodel.Particles(keys = [10,11,12]) - particles.mass = [1,2,3] | units.kg - particles2 = datamodel.Particles(keys = [20,21]) - particles2.mass = [8,9] | units.kg + particles = datamodel.Particles(keys=[10, 11, 12]) + particles.mass = [1, 2, 3] | units.kg + particles2 = datamodel.Particles(keys=[20, 21]) + particles2.mass = [8, 9] | units.kg subset = particles[0:2] - self.assertAlmostRelativeEquals(subset.mass, [1,2] | units.kg) + self.assertAlmostRelativeEquals(subset.mass, [1, 2] | units.kg) particles.add_particles(particles2) - self.assertAlmostRelativeEquals(subset.mass, [1,2] | units.kg) - subset.mass = [4,5] | units.kg - self.assertAlmostRelativeEquals(subset.mass, [4,5] | units.kg) - self.assertAlmostRelativeEquals(particles.mass, [4,5,3,8,9] | units.kg) - + self.assertAlmostRelativeEquals(subset.mass, [1, 2] | units.kg) + subset.mass = [4, 5] | units.kg + self.assertAlmostRelativeEquals(subset.mass, [4, 5] | units.kg) + self.assertAlmostRelativeEquals(particles.mass, [4, 5, 3, 8, 9] | units.kg) def test5(self): - particles = datamodel.Particles(keys = [10,11,12]) - particles.mass = [1,2,3] | units.kg - particles2 = datamodel.Particles(keys = [20,21]) - particles2.mass = [8,9] | units.kg - particles2in1 = particles.add_particles(particles2) - self.assertAlmostRelativeEquals(particles2in1.mass, [8,9] | units.kg) - particles2.mass = [4,5] | units.kg - self.assertAlmostRelativeEquals(particles2in1.mass, [8,9] | units.kg) - self.assertAlmostRelativeEquals(particles.mass, [1,2,3,8,9] | units.kg) - particles2in1.mass = [10,12] | units.kg - self.assertAlmostRelativeEquals(particles2in1.mass, [10,12] | units.kg) - self.assertAlmostRelativeEquals(particles.mass, [1,2,3,10,12] | units.kg) - + particles = datamodel.Particles(keys=[10, 11, 12]) + particles.mass = [1, 2, 3] | units.kg + particles2 = datamodel.Particles(keys=[20, 21]) + particles2.mass = [8, 9] | units.kg + particles2in1 = particles.add_particles(particles2) + self.assertAlmostRelativeEquals(particles2in1.mass, [8, 9] | units.kg) + particles2.mass = [4, 5] | units.kg + self.assertAlmostRelativeEquals(particles2in1.mass, [8, 9] | units.kg) + self.assertAlmostRelativeEquals(particles.mass, [1, 2, 3, 8, 9] | units.kg) + particles2in1.mass = [10, 12] | units.kg + self.assertAlmostRelativeEquals(particles2in1.mass, [10, 12] | units.kg) + self.assertAlmostRelativeEquals(particles.mass, [1, 2, 3, 10, 12] | units.kg) def test6(self): - particles = datamodel.Particles(keys = [10,11,12]) - particles.mass = [1,2,3] | units.kg - particles2 = datamodel.Particles(keys = [20,21]) - particles2.mass = [8,9] | units.kg - particles2in1 = particles.add_particles(particles2) + particles = datamodel.Particles(keys=[10, 11, 12]) + particles.mass = [1, 2, 3] | units.kg + particles2 = datamodel.Particles(keys=[20, 21]) + particles2.mass = [8, 9] | units.kg + particles2in1 = particles.add_particles(particles2) particles.remove_particles(particles[0:2]) - self.assertAlmostRelativeEquals(particles2in1.mass, [8,9] | units.kg) - particles2in1.mass = [10,12] | units.kg - self.assertAlmostRelativeEquals(particles.mass, [3,10,12] | units.kg) + self.assertAlmostRelativeEquals(particles2in1.mass, [8, 9] | units.kg) + particles2in1.mass = [10, 12] | units.kg + self.assertAlmostRelativeEquals(particles.mass, [3, 10, 12] | units.kg) def test7(self): - particles = datamodel.Particles(keys = [10,11,12]) + particles = datamodel.Particles(keys=[10, 11, 12]) particles.mass = [10.0, 20.0, 30.0] | units.kg - subset1 = particles.select(lambda x : x > 25.0 | units.kg, ["mass"]) - self.assertEqual(len(subset1),1) - subset2 = particles.select(lambda x : x < 15.0 | units.kg, ["mass"]) - self.assertEqual(len(subset2),1) + subset1 = particles.select(lambda x: x > 25.0 | units.kg, ["mass"]) + self.assertEqual(len(subset1), 1) + subset2 = particles.select(lambda x: x < 15.0 | units.kg, ["mass"]) + self.assertEqual(len(subset2), 1) union = subset1.union(subset2) - self.assertEqual(len(union),2) + self.assertEqual(len(union), 2) self.assertAlmostRelativeEquals(union.mass, [10.0, 30.0] | units.kg) def test8(self): - particles = datamodel.Particles(keys = [10,11]) - particles.mass = [1,2] | units.kg + particles = datamodel.Particles(keys=[10, 11]) + particles.mass = [1, 2] | units.kg subset = particles[0:2] particle = subset[0] self.assertAlmostRelativeEquals(particle.mass, 1 | units.kg) - self.assertAlmostRelativeEquals(subset.mass, [1,2] | units.kg) + self.assertAlmostRelativeEquals(subset.mass, [1, 2] | units.kg) particle.mass = 3 | units.kg - self.assertAlmostRelativeEquals(particles.mass, [3,2] | units.kg) - self.assertAlmostRelativeEquals(subset.mass, [3,2] | units.kg) + self.assertAlmostRelativeEquals(particles.mass, [3, 2] | units.kg) + self.assertAlmostRelativeEquals(subset.mass, [3, 2] | units.kg) self.assertAlmostRelativeEquals(particle.mass, 3 | units.kg) def test9(self): - particles = datamodel.Particles(keys = [10,11]) - particles.mass = [1,2] | units.kg + particles = datamodel.Particles(keys=[10, 11]) + particles.mass = [1, 2] | units.kg subset = particles[0:2] particle = subset[0] - particles.add_particle(datamodel.Particle(mass = 10|units.kg)) + particles.add_particle(datamodel.Particle(mass=10 | units.kg)) self.assertAlmostRelativeEquals(particle.mass, 1 | units.kg) - self.assertAlmostRelativeEquals(subset.mass, [1,2] | units.kg) + self.assertAlmostRelativeEquals(subset.mass, [1, 2] | units.kg) particles.remove_particle(particles[-1]) particle.mass = 3 | units.kg - self.assertAlmostRelativeEquals(particles.mass, [3,2] | units.kg) - self.assertAlmostRelativeEquals(subset.mass, [3,2] | units.kg) + self.assertAlmostRelativeEquals(particles.mass, [3, 2] | units.kg) + self.assertAlmostRelativeEquals(subset.mass, [3, 2] | units.kg) self.assertAlmostRelativeEquals(particle.mass, 3 | units.kg) def test10(self): - particles = datamodel.Particles(keys = [10,11,12,13,14,15]) - particles.x = [1,2,3,4,5,6] | units.m + particles = datamodel.Particles(keys=[10, 11, 12, 13, 14, 15]) + particles.x = [1, 2, 3, 4, 5, 6] | units.m subset = particles[0:] i = 1 for particle in subset: - self.assertEqual(particle.x , i | units.m) + self.assertEqual(particle.x, i | units.m) i += 1 def test11(self): - particles = datamodel.Particles(keys = [10,11]) - particles.add_calculated_attribute("xy", lambda x, y : x * y) - particles.x = [2,3] | units.m - particles.y = [4,5] | units.m + particles = datamodel.Particles(keys=[10, 11]) + particles.add_calculated_attribute("xy", lambda x, y: x * y) + particles.x = [2, 3] | units.m + particles.y = [4, 5] | units.m subset = particles[0:] - self.assertAlmostRelativeEquals(subset.xy, [8,15] | units.m*units.m) + self.assertAlmostRelativeEquals(subset.xy, [8, 15] | units.m*units.m) self.assertAlmostRelativeEquals(subset[0].xy, 8 | units.m*units.m) def test12(self): - particles = datamodel.Particles(keys = [10,11]) - particles.x = [2,3] | units.m - particles.y = [4,5] | units.m + particles = datamodel.Particles(keys=[10, 11]) + particles.x = [2, 3] | units.m + particles.y = [4, 5] | units.m subset = particles[0:] - subset.add_calculated_attribute("xy", lambda x, y : x * y) + subset.add_calculated_attribute("xy", lambda x, y: x * y) - self.assertAlmostRelativeEquals(subset.xy, [8,15] | units.m*units.m) + self.assertAlmostRelativeEquals(subset.xy, [8, 15] | units.m*units.m) # the particle of a subset is a particle in the set, so it will not have xy - #self.assertAlmostRelativeEquals(subset[0].xy, 8 | units.m*units.m) + # self.assertAlmostRelativeEquals(subset[0].xy, 8 | units.m*units.m) def test13(self): - particles = datamodel.Particles(keys = [10,11,12]) + particles = datamodel.Particles(keys=[10, 11, 12]) particles.add_vector_attribute('position2d', ['x', 'y']) - particles.x = [1,2,3] | units.m - particles.y = [3,4,5] | units.m + particles.x = [1, 2, 3] | units.m + particles.y = [3, 4, 5] | units.m subset = particles[0:2] - self.assertAlmostRelativeEquals(subset.position2d, [[1,3],[2,4]] | units.m) + self.assertAlmostRelativeEquals(subset.position2d, [[1, 3], [2, 4]] | units.m) - subset.position2d = [[5,6],[7,8]] | units.m - self.assertAlmostRelativeEquals(subset.x, [5,7] | units.m) - self.assertAlmostRelativeEquals(subset.y, [6,8] | units.m) - self.assertAlmostRelativeEquals(particles.x, [5,7,3] | units.m) - self.assertAlmostRelativeEquals(particles.y, [6,8,5] | units.m) - self.assertAlmostRelativeEquals(subset[0].position2d, [5,6] | units.m) + subset.position2d = [[5, 6], [7, 8]] | units.m + self.assertAlmostRelativeEquals(subset.x, [5, 7] | units.m) + self.assertAlmostRelativeEquals(subset.y, [6, 8] | units.m) + self.assertAlmostRelativeEquals(particles.x, [5, 7, 3] | units.m) + self.assertAlmostRelativeEquals(particles.y, [6, 8, 5] | units.m) + self.assertAlmostRelativeEquals(subset[0].position2d, [5, 6] | units.m) def test14(self): - particles = datamodel.Particles(keys=[9,10,11,12,13,14]) - particles.mass = [1,2,3,4,20,21] | units.kg + particles = datamodel.Particles(keys=[9, 10, 11, 12, 13, 14]) + particles.mass = [1, 2, 3, 4, 20, 21] | units.kg - self.assertAlmostRelativeEquals(particles[-3:].mass, [4,20,21] | units.kg) - self.assertAlmostRelativeEquals(particles[-3:-1].mass, [4,20] | units.kg) - self.assertAlmostRelativeEquals(particles[::-1].mass, [21,20,4,3,2,1] | units.kg) + self.assertAlmostRelativeEquals(particles[-3:].mass, [4, 20, 21] | units.kg) + self.assertAlmostRelativeEquals(particles[-3:-1].mass, [4, 20] | units.kg) + self.assertAlmostRelativeEquals(particles[::-1].mass, [21, 20, 4, 3, 2, 1] | units.kg) def test16(self): set1 = datamodel.Particles(3) @@ -563,10 +547,9 @@ def test16(self): subset1.remove_particle(subset1[1]) self.assertAlmostRelativeEquals(subset1.x, [1.0] | units.kg) self.assertAlmostRelativeEquals(subset2.x, [3.0] | units.kg) - def test17(self): - set1 = datamodel.Particles(3, storage = memory_storage.InMemoryAttributeStorageUseSortedKeys()) + set1 = datamodel.Particles(3, storage=memory_storage.InMemoryAttributeStorageUseSortedKeys()) set1.x = [1.0, 2.0, 3.0] | units.kg subset1 = set1[0:2] subset2 = set1[1:3] @@ -575,10 +558,9 @@ def test17(self): subset1.remove_particle(subset1[1]) self.assertAlmostRelativeEquals(subset1.x, [1.0] | units.kg) self.assertAlmostRelativeEquals(subset2.x, [3.0] | units.kg) - def test18(self): - set1 = datamodel.Particles(3, storage = memory_storage.InMemoryAttributeStorageUseDictionaryForKeySet()) + set1 = datamodel.Particles(3, storage=memory_storage.InMemoryAttributeStorageUseDictionaryForKeySet()) set1.x = [1.0, 2.0, 3.0] | units.kg subset1 = set1[0:2] subset2 = set1[1:3] @@ -587,16 +569,15 @@ def test18(self): subset1.remove_particle(subset1[1]) self.assertAlmostRelativeEquals(subset1.x, [1.0] | units.kg) self.assertAlmostRelativeEquals(subset2.x, [3.0] | units.kg) - def test19(self): - particles = datamodel.Particles(keys = [10,11]) - particles.x = [1,2] | units.m - particles.y = [3,4] | units.m + particles = datamodel.Particles(keys=[10, 11]) + particles.x = [1, 2] | units.m + particles.y = [3, 4] | units.m particles.add_caching_function_attribute( "xy", - lambda allparticles : (allparticles.x * allparticles.y), - lambda allparticles, one : (one.x * one.y) + lambda allparticles: (allparticles.x * allparticles.y), + lambda allparticles, one: (one.x * one.y) ) self.assertAlmostRelativeEquals( @@ -607,7 +588,7 @@ def test19(self): particles[0].xy(), 3 | units.m*units.m ) - particles.x = [5,6] | units.m + particles.x = [5, 6] | units.m self.assertAlmostRelativeEquals( particles.xy(), [3, 8] | units.m*units.m @@ -616,72 +597,74 @@ def test19(self): particles[0].xy(), 15 | units.m*units.m ) + + class TestParticlesChannel(amusetest.TestCase): def test1(self): - particles1 = datamodel.Particles(keys=[10,11]) - particles1.mass = [1,2] | units.kg - particles1.x = [10,12] | units.kg + particles1 = datamodel.Particles(keys=[10, 11]) + particles1.mass = [1, 2] | units.kg + particles1.x = [10, 12] | units.kg - particles2 = datamodel.Particles(keys=[11,10]) - particles2.mass = [3,4] | units.kg - particles2.x = [11,13] | units.kg + particles2 = datamodel.Particles(keys=[11, 10]) + particles2.mass = [3, 4] | units.kg + particles2.x = [11, 13] | units.kg - self.assertAlmostRelativeEquals(particles2.mass, [3,4] | units.kg) - self.assertAlmostRelativeEquals(particles1.mass,[1,2] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [3, 4] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [1, 2] | units.kg) channel = particles1.new_channel_to(particles2) channel.copy() - self.assertAlmostRelativeEquals(particles2.mass,[2,1] | units.kg) - self.assertAlmostRelativeEquals(particles1.mass,[1,2] | units.kg) - self.assertAlmostRelativeEquals(particles2.x,[12,10] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [2, 1] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [1, 2] | units.kg) + self.assertAlmostRelativeEquals(particles2.x, [12, 10] | units.kg) def test2(self): - particles1 = datamodel.Particles(keys=[10,11]) - particles1.mass = [1,2] | units.kg + particles1 = datamodel.Particles(keys=[10, 11]) + particles1.mass = [1, 2] | units.kg - particles2 = datamodel.Particles(keys=[11,10]) - particles2.mass = [3,4] | units.kg + particles2 = datamodel.Particles(keys=[11, 10]) + particles2.mass = [3, 4] | units.kg - self.assertAlmostRelativeEquals(particles2.mass, [3,4] | units.kg) - self.assertAlmostRelativeEquals(particles1.mass, [1,2] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [3, 4] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [1, 2] | units.kg) channel = particles1.new_channel_to(particles2).reverse() channel.copy() - self.assertAlmostRelativeEquals(particles2.mass, [3,4] | units.kg) - self.assertAlmostRelativeEquals(particles1.mass, [4,3] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [3, 4] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [4, 3] | units.kg) def test3(self): - particles1 = datamodel.Particles(keys=[10,11]) - particles1.mass = [1,2] | units.kg - particles1.x = [10,12] | units.kg + particles1 = datamodel.Particles(keys=[10, 11]) + particles1.mass = [1, 2] | units.kg + particles1.x = [10, 12] | units.kg - particles2 = datamodel.Particles(keys=[11,10]) - particles2.mass = [3,4] | units.kg - particles2.x = [11,13] | units.kg + particles2 = datamodel.Particles(keys=[11, 10]) + particles2.mass = [3, 4] | units.kg + particles2.x = [11, 13] | units.kg - self.assertAlmostRelativeEquals(particles2.mass, [3,4] | units.kg) - self.assertAlmostRelativeEquals(particles1.mass, [1,2] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [3, 4] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [1, 2] | units.kg) channel = particles1.new_channel_to(particles2) channel.copy_attribute("mass", "mass_from_1") - self.assertAlmostRelativeEquals(particles2.mass, [3,4] | units.kg) - self.assertAlmostRelativeEquals(particles2.mass_from_1, [2,1] | units.kg) - self.assertAlmostRelativeEquals(particles2.x, [11,13] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [3, 4] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass_from_1, [2, 1] | units.kg) + self.assertAlmostRelativeEquals(particles2.x, [11, 13] | units.kg) channel.copy_attribute("mass") - self.assertAlmostRelativeEquals(particles2.mass, [2,1] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [2, 1] | units.kg) def test4(self): particles1 = datamodel.Particles(2) - particles1.mass = 1| units.kg + particles1.mass = 1 | units.kg particles2 = particles1.copy() particles2.stellar_mass = range(2) | units.kg @@ -693,167 +676,165 @@ def test4(self): channel.copy_overlapping_attributes() self.assertFalse(hasattr(particles1, 'stellar_mass')) - self.assertEqual(particles1.mass, [0,0] | units.kg) + self.assertEqual(particles1.mass, [0, 0] | units.kg) channel.copy_all_attributes() self.assertTrue(hasattr(particles1, 'stellar_mass')) - self.assertEqual(particles1.mass, [0,0] | units.kg) + self.assertEqual(particles1.mass, [0, 0] | units.kg) def test5(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg - particles2 = datamodel.Particles(keys=[11,10]) - particles2.mass = [20,21] | units.kg + particles2 = datamodel.Particles(keys=[11, 10]) + particles2.mass = [20, 21] | units.kg - self.assertAlmostRelativeEquals(particles2.mass, [20,21] | units.kg) - self.assertAlmostRelativeEquals(particles1.mass, [1,2,3,4] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [20, 21] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [1, 2, 3, 4] | units.kg) channel = particles1.new_channel_to(particles2) channel.copy() - self.assertAlmostRelativeEquals(particles2.mass,[3,2] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [3, 2] | units.kg) def test6(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg - particles2 = datamodel.Particles(keys=[11,10]) - particles2.mass = [20,21] | units.kg + particles2 = datamodel.Particles(keys=[11, 10]) + particles2.mass = [20, 21] | units.kg - self.assertAlmostRelativeEquals(particles2.mass, [20,21] | units.kg) - self.assertAlmostRelativeEquals(particles1.mass, [1,2,3,4] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [20, 21] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [1, 2, 3, 4] | units.kg) channel = particles1.new_channel_to(particles2).reverse() channel.copy() - self.assertAlmostRelativeEquals(particles2.mass,[20,21] | units.kg) - self.assertAlmostRelativeEquals(particles1.mass, [1,21,20,4] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [20, 21] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [1, 21, 20, 4] | units.kg) def test7(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg - particles2 = datamodel.Particles(keys=[11,10]) - particles2.mass = [20,21] | units.kg + particles2 = datamodel.Particles(keys=[11, 10]) + particles2.mass = [20, 21] | units.kg - self.assertAlmostRelativeEquals(particles2.mass, [20,21] | units.kg) - self.assertAlmostRelativeEquals(particles1.mass, [1,2,3,4] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [20, 21] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [1, 2, 3, 4] | units.kg) channel = particles2.new_channel_to(particles1) channel.copy() particles1.remove_particle(particles1[0]) - self.assertAlmostRelativeEquals(particles1.mass, [21,20,4] | units.kg) - particles2.mass = [23,24] | units.kg + self.assertAlmostRelativeEquals(particles1.mass, [21, 20, 4] | units.kg) + particles2.mass = [23, 24] | units.kg channel.copy() - self.assertAlmostRelativeEquals(particles1.mass, [24,23,4] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [24, 23, 4] | units.kg) def test8(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg - particles2 = datamodel.Particles(keys=[11,10]) - particles2.mass = [20,21] | units.kg + particles2 = datamodel.Particles(keys=[11, 10]) + particles2.mass = [20, 21] | units.kg - self.assertAlmostRelativeEquals(particles2.mass, [20,21] | units.kg) - self.assertAlmostRelativeEquals(particles1.mass, [1,2,3,4] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [20, 21] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [1, 2, 3, 4] | units.kg) channel = particles2.new_channel_to(particles1) channel.copy() particles2.remove_particle(particles2[1]) - self.assertAlmostRelativeEquals(particles1.mass, [1,21,20,4] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [1, 21, 20, 4] | units.kg) particles2.mass = 24 | units.kg channel.copy() - self.assertAlmostRelativeEquals(particles1.mass, [1,21,24,4] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [1, 21, 24, 4] | units.kg) def test9(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg - particles2 = datamodel.Particles(keys=[11,10]) - particles2.mass = [20,21] | units.kg + particles2 = datamodel.Particles(keys=[11, 10]) + particles2.mass = [20, 21] | units.kg - self.assertAlmostRelativeEquals(particles2.mass, [20,21] | units.kg) - self.assertAlmostRelativeEquals(particles1.mass, [1,2,3,4] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [20, 21] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [1, 2, 3, 4] | units.kg) channel = particles2.new_channel_to(particles1) channel.copy() particles2.add_particle(particles1[-1]) - self.assertAlmostRelativeEquals(particles1.mass, [1,21,20,4] | units.kg) - particles2.mass = [24,25,26] | units.kg + self.assertAlmostRelativeEquals(particles1.mass, [1, 21, 20, 4] | units.kg) + particles2.mass = [24, 25, 26] | units.kg channel.copy() - self.assertAlmostRelativeEquals(particles1.mass, [1,25,24,26] | units.kg) - + self.assertAlmostRelativeEquals(particles1.mass, [1, 25, 24, 26] | units.kg) def test10(self): - particles1 = datamodel.Particles(keys=[10,11]) - particles1.mass = [1,2] | units.kg - particles1.x = [10,12] | units.kg + particles1 = datamodel.Particles(keys=[10, 11]) + particles1.mass = [1, 2] | units.kg + particles1.x = [10, 12] | units.kg - particles2 = datamodel.Particles(keys=[11,10]) - particles2.mass = [3,4] | units.kg - particles2.x = [11,13] | units.kg + particles2 = datamodel.Particles(keys=[11, 10]) + particles2.mass = [3, 4] | units.kg + particles2.x = [11, 13] | units.kg - self.assertAlmostRelativeEquals(particles2.mass, [3,4] | units.kg) - self.assertAlmostRelativeEquals(particles1.mass,[1,2] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [3, 4] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [1, 2] | units.kg) channel = particles1.new_channel_to(particles2, attributes=['mass']) channel.copy() - self.assertAlmostRelativeEquals(particles2.mass,[2,1] | units.kg) - self.assertAlmostRelativeEquals(particles1.mass,[1,2] | units.kg) - self.assertAlmostRelativeEquals(particles2.x,[11,13] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [2, 1] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [1, 2] | units.kg) + self.assertAlmostRelativeEquals(particles2.x, [11, 13] | units.kg) - particles2.mass = [3,4] | units.kg + particles2.mass = [3, 4] | units.kg reverse_channel = channel.reverse() reverse_channel.copy() - self.assertAlmostRelativeEquals(particles2.mass,[3,4] | units.kg) - self.assertAlmostRelativeEquals(particles1.mass,[4,3] | units.kg) - self.assertAlmostRelativeEquals(particles2.x,[11,13] | units.kg) - + self.assertAlmostRelativeEquals(particles2.mass, [3, 4] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [4, 3] | units.kg) + self.assertAlmostRelativeEquals(particles2.x, [11, 13] | units.kg) def test11(self): - particles1 = datamodel.Particles(keys=[10,11]) - particles1.mass = [1,2] | units.kg - particles1.x = [10,12] | units.kg + particles1 = datamodel.Particles(keys=[10, 11]) + particles1.mass = [1, 2] | units.kg + particles1.x = [10, 12] | units.kg - particles2 = datamodel.Particles(keys=[11,10]) - particles2.mass = [3,4] | units.kg - particles2.x = [11,13] | units.kg + particles2 = datamodel.Particles(keys=[11, 10]) + particles2.mass = [3, 4] | units.kg + particles2.x = [11, 13] | units.kg - self.assertAlmostRelativeEquals(particles2.mass, [3,4] | units.kg) - self.assertAlmostRelativeEquals(particles1.mass,[1,2] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [3, 4] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [1, 2] | units.kg) channel = particles1.new_channel_to(particles2, attributes=['mass'], target_names=['x']) channel.copy() - self.assertAlmostRelativeEquals(particles2.mass,[3,4] | units.kg) - self.assertAlmostRelativeEquals(particles1.mass,[1,2] | units.kg) - self.assertAlmostRelativeEquals(particles2.x,[2,1] | units.kg) - self.assertAlmostRelativeEquals(particles1.x,[10,12] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [3, 4] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [1, 2] | units.kg) + self.assertAlmostRelativeEquals(particles2.x, [2, 1] | units.kg) + self.assertAlmostRelativeEquals(particles1.x, [10, 12] | units.kg) - particles2.x = [13,11] | units.kg + particles2.x = [13, 11] | units.kg reverse_channel = channel.reverse() reverse_channel.copy() - self.assertAlmostRelativeEquals(particles2.mass,[3,4] | units.kg) - self.assertAlmostRelativeEquals(particles1.mass,[11,13] | units.kg) - self.assertAlmostRelativeEquals(particles2.x,[13,11] | units.kg) - self.assertAlmostRelativeEquals(particles1.x,[10,12] | units.kg) + self.assertAlmostRelativeEquals(particles2.mass, [3, 4] | units.kg) + self.assertAlmostRelativeEquals(particles1.mass, [11, 13] | units.kg) + self.assertAlmostRelativeEquals(particles2.x, [13, 11] | units.kg) + self.assertAlmostRelativeEquals(particles1.x, [10, 12] | units.kg) def test12(self): """ Test Channels add channel""" @@ -907,13 +888,13 @@ def test15(self): self.assertAlmostRelativeEquals(p1.x, [11, 13] | units.m) def setup_test_channels(self): - particles1 = datamodel.Particles(keys=[10,11]) - particles1.mass = [1,2] | units.kg - particles1.x = [10,12] | units.m + particles1 = datamodel.Particles(keys=[10, 11]) + particles1.mass = [1, 2] | units.kg + particles1.x = [10, 12] | units.m - particles2 = datamodel.Particles(keys=[10,11]) - particles2.mass = [3,4] | units.kg - particles2.x = [11,13] | units.m + particles2 = datamodel.Particles(keys=[10, 11]) + particles2.mass = [3, 4] | units.kg + particles2.x = [11, 13] | units.m channel1 = particles1.new_channel_to(particles2, attributes=['mass']) channel2 = particles2.new_channel_to(particles1, attributes=['x']) @@ -922,166 +903,163 @@ def setup_test_channels(self): def test16(self): - particles1 = datamodel.Particles(keys=[10,11]) - particles1.mass = [1,2] | units.kg - particles1.vx = [10,12] | units.m/units.s + particles1 = datamodel.Particles(keys=[10, 11]) + particles1.mass = [1, 2] | units.kg + particles1.vx = [10, 12] | units.m/units.s - particles2 = datamodel.Particles(keys=[11,10]) + particles2 = datamodel.Particles(keys=[11, 10]) channel = particles1.new_channel_to(particles2) - channel.transform(["momentum"], lambda x,y: (x*y,),["mass","vx"]) + channel.transform(["momentum"], lambda x, y: (x*y,), ["mass", "vx"]) - self.assertEqual(particles2.momentum,[2*12,1*10] | units.kg*units.m/units.s) + self.assertEqual(particles2.momentum, [2*12, 1*10] | units.kg*units.m/units.s) - channel.transform(["vx_by_another_name"], None,["vx"]) + channel.transform(["vx_by_another_name"], None, ["vx"]) - self.assertEqual(particles2.vx_by_another_name,[12,10] | units.m/units.s) + self.assertEqual(particles2.vx_by_another_name, [12, 10] | units.m/units.s) class TestParticlesSuperset(amusetest.TestCase): def test1(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg - particles2 = datamodel.Particles(keys=[13,14]) - particles2.mass = [20,21] | units.kg - superset = particles1 | particles2 + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg + particles2 = datamodel.Particles(keys=[13, 14]) + particles2.mass = [20, 21] | units.kg + superset = particles1 | particles2 self.assertEqual(len(superset), 6) - self.assertAlmostRelativeEquals(superset.mass, [1,2,3,4,20,21] | units.kg) - + self.assertAlmostRelativeEquals(superset.mass, [1, 2, 3, 4, 20, 21] | units.kg) def test2(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg - particles2 = datamodel.Particles(keys=[13,14]) - particles2.mass = [20,21] | units.kg - superset = particles1 | particles2 + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg + particles2 = datamodel.Particles(keys=[13, 14]) + particles2.mass = [20, 21] | units.kg + superset = particles1 | particles2 self.assertEqual(len(superset), 6) - self.assertAlmostRelativeEquals(superset.mass, [1,2,3,4,20,21] | units.kg) - superset.mass = [7,8,9,10,11,12] | units.kg - self.assertAlmostRelativeEquals(superset.mass, [7,8,9,10,11,12] | units.kg) + self.assertAlmostRelativeEquals(superset.mass, [1, 2, 3, 4, 20, 21] | units.kg) + superset.mass = [7, 8, 9, 10, 11, 12] | units.kg + self.assertAlmostRelativeEquals(superset.mass, [7, 8, 9, 10, 11, 12] | units.kg) def test3(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg - particles2 = datamodel.Particles(keys=[13,14]) - particles2.mass = [5,6] | units.kg - superset = particles1 | particles2 + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg + particles2 = datamodel.Particles(keys=[13, 14]) + particles2.mass = [5, 6] | units.kg + superset = particles1 | particles2 i = 1 for particle in superset: - self.assertEqual(particle.mass , i | units.kg) + self.assertEqual(particle.mass, i | units.kg) i += 1 def test4(self): - particles1 = datamodel.Particles(keys = [10,11]) - particles1.add_calculated_attribute("xy", lambda x, y : x * y) - particles1.x = [2,3] | units.m - particles1.y = [4,5] | units.m - particles2 = datamodel.Particles(keys = [12,13]) - particles2.add_calculated_attribute("xy", lambda x, y : x * y) - particles2.x = [4,5] | units.m - particles2.y = [6,7] | units.m - superset = particles1 | particles2 - - - self.assertAlmostRelativeEquals(superset.xy, [8,15,24,35] | units.m*units.m) + particles1 = datamodel.Particles(keys=[10, 11]) + particles1.add_calculated_attribute("xy", lambda x, y: x * y) + particles1.x = [2, 3] | units.m + particles1.y = [4, 5] | units.m + particles2 = datamodel.Particles(keys=[12, 13]) + particles2.add_calculated_attribute("xy", lambda x, y: x * y) + particles2.x = [4, 5] | units.m + particles2.y = [6, 7] | units.m + superset = particles1 | particles2 + + self.assertAlmostRelativeEquals(superset.xy, [8, 15, 24, 35] | units.m*units.m) self.assertAlmostRelativeEquals(superset[0].xy, 8 | units.m*units.m) self.assertAlmostRelativeEquals(superset[2].xy, 24 | units.m*units.m) def test5(self): - particles1 = datamodel.Particles(keys = [10,11]) + particles1 = datamodel.Particles(keys=[10, 11]) particles1.add_vector_attribute('position2d', ['x', 'y']) - particles1.x = [2,3] | units.m - particles1.y = [4,5] | units.m - particles2 = datamodel.Particles(keys = [12,13]) + particles1.x = [2, 3] | units.m + particles1.y = [4, 5] | units.m + particles2 = datamodel.Particles(keys=[12, 13]) particles2.add_vector_attribute('position2d', ['x', 'y']) - particles2.x = [4,5] | units.m - particles2.y = [6,7] | units.m - superset = particles1 | particles2 + particles2.x = [4, 5] | units.m + particles2.y = [6, 7] | units.m + superset = particles1 | particles2 - - self.assertAlmostRelativeEquals(superset.position2d, [[2,4],[3,5],[4,6],[5,7]] | units.m) - self.assertAlmostRelativeEquals(superset[0].position2d, [2,4] | units.m) - self.assertAlmostRelativeEquals(superset[2].position2d, [4,6] | units.m) - superset[1].position2d = [8,9] | units.m - self.assertAlmostRelativeEquals(superset.position2d, [[2,4],[8,9],[4,6],[5,7]] | units.m) - self.assertAlmostRelativeEquals(particles1[1].position2d, [8,9] | units.m) + self.assertAlmostRelativeEquals(superset.position2d, [[2, 4], [3, 5], [4, 6], [5, 7]] | units.m) + self.assertAlmostRelativeEquals(superset[0].position2d, [2, 4] | units.m) + self.assertAlmostRelativeEquals(superset[2].position2d, [4, 6] | units.m) + superset[1].position2d = [8, 9] | units.m + self.assertAlmostRelativeEquals(superset.position2d, [[2, 4], [8, 9], [4, 6], [5, 7]] | units.m) + self.assertAlmostRelativeEquals(particles1[1].position2d, [8, 9] | units.m) def test6(self): - particles1 = datamodel.Particles(keys = [10,11]) + particles1 = datamodel.Particles(keys=[10, 11]) particles1.add_vector_attribute('position2d', ['x', 'y']) - particles1.x = [2,3] | units.m - particles1.y = [4,5] | units.m - particles2 = datamodel.Particles(keys = [12,13]) + particles1.x = [2, 3] | units.m + particles1.y = [4, 5] | units.m + particles2 = datamodel.Particles(keys=[12, 13]) particles2.add_vector_attribute('position2d', ['y', 'x']) - particles2.x = [4,5] | units.m - particles2.y = [6,7] | units.m - superset = particles1 | particles2 - - self.assertAlmostRelativeEquals(superset.position2d, [[2,4],[3,5],[6,4],[7,5]] | units.m) - self.assertAlmostRelativeEquals(superset[0].position2d, [2,4] | units.m) - self.assertAlmostRelativeEquals(superset[2].position2d, [6,4] | units.m) - superset[2].position2d = [8,9] | units.m - self.assertAlmostRelativeEquals(superset.position2d, [[2,4],[3,5],[8,9],[7,5]] | units.m) - self.assertAlmostRelativeEquals(particles2[0].position2d, [8,9] | units.m) + particles2.x = [4, 5] | units.m + particles2.y = [6, 7] | units.m + superset = particles1 | particles2 + + self.assertAlmostRelativeEquals(superset.position2d, [[2, 4], [3, 5], [6, 4], [7, 5]] | units.m) + self.assertAlmostRelativeEquals(superset[0].position2d, [2, 4] | units.m) + self.assertAlmostRelativeEquals(superset[2].position2d, [6, 4] | units.m) + superset[2].position2d = [8, 9] | units.m + self.assertAlmostRelativeEquals(superset.position2d, [[2, 4], [3, 5], [8, 9], [7, 5]] | units.m) + self.assertAlmostRelativeEquals(particles2[0].position2d, [8, 9] | units.m) self.assertAlmostRelativeEquals(particles2[0].x, 9 | units.m) self.assertAlmostRelativeEquals(particles2[0].y, 8 | units.m) def test7(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg - particles2 = datamodel.Particles(keys=[13,14]) - particles2.mass = [20,21] | units.kg - superset = datamodel.ParticlesSuperset([particles1 , particles2], index_to_default_set = 0) + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg + particles2 = datamodel.Particles(keys=[13, 14]) + particles2.mass = [20, 21] | units.kg + superset = datamodel.ParticlesSuperset([particles1, particles2], index_to_default_set=0) self.assertEqual(len(superset), 6) superset.add_particle(datamodel.Particle(key=30, mass=7 | units.kg)) self.assertEqual(len(superset), 7) - self.assertAlmostRelativeEquals(superset.mass, [1,2,3,4,7,20,21] | units.kg) - particles3 = datamodel.Particles(keys=[31,32]) - particles3.mass = [10,11] | units.kg + self.assertAlmostRelativeEquals(superset.mass, [1, 2, 3, 4, 7, 20, 21] | units.kg) + particles3 = datamodel.Particles(keys=[31, 32]) + particles3.mass = [10, 11] | units.kg superset.add_particles(particles3) self.assertEqual(len(superset), 9) - self.assertAlmostRelativeEquals(superset.mass, [1,2,3,4,7,10,11,20,21] | units.kg) + self.assertAlmostRelativeEquals(superset.mass, [1, 2, 3, 4, 7, 10, 11, 20, 21] | units.kg) def test8(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg - particles2 = datamodel.Particles(keys=[13,14]) - particles2.mass = [20,21] | units.kg - superset = datamodel.ParticlesSuperset([particles1 , particles2], index_to_default_set = 0) + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg + particles2 = datamodel.Particles(keys=[13, 14]) + particles2.mass = [20, 21] | units.kg + superset = datamodel.ParticlesSuperset([particles1, particles2], index_to_default_set=0) superset.remove_particle(particles1[1]) self.assertEqual(len(superset), 5) self.assertEqual(len(particles1), 3) def test9(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg - particles2 = datamodel.Particles(keys=[13,14]) - particles2.mass = [20,21] | units.kg - superset = datamodel.ParticlesSuperset([particles1 , particles2], index_to_default_set = 0) + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg + particles2 = datamodel.Particles(keys=[13, 14]) + particles2.mass = [20, 21] | units.kg + superset = datamodel.ParticlesSuperset([particles1, particles2], index_to_default_set=0) self.assertEqual(superset[-1].mass, 21 | units.kg) self.assertEqual(superset[-3].mass, 4 | units.kg) def test10(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg - particles2 = datamodel.Particles(keys=[13,14]) - particles2.mass = [20,21] | units.kg - superset = datamodel.ParticlesSuperset([particles1 , particles2], index_to_default_set = 0) + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg + particles2 = datamodel.Particles(keys=[13, 14]) + particles2.mass = [20, 21] | units.kg + superset = datamodel.ParticlesSuperset([particles1, particles2], index_to_default_set=0) - self.assertAlmostRelativeEquals(superset[-3:].mass, [4,20,21] | units.kg) - self.assertAlmostRelativeEquals(superset[-3:-1].mass, [4,20] | units.kg) - self.assertAlmostRelativeEquals(superset[::-1].mass, [21,20,4,3,2,1] | units.kg) + self.assertAlmostRelativeEquals(superset[-3:].mass, [4, 20, 21] | units.kg) + self.assertAlmostRelativeEquals(superset[-3:-1].mass, [4, 20] | units.kg) + self.assertAlmostRelativeEquals(superset[::-1].mass, [21, 20, 4, 3, 2, 1] | units.kg) def test11(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg particles1_copy = particles1.copy() - particles1_copy.mass = [5,6,7,8] | units.kg - particles2 = datamodel.Particles(keys=[13,14]) - particles2.mass = [20,21] | units.kg - superset = particles1 | particles2 + particles1_copy.mass = [5, 6, 7, 8] | units.kg + particles2 = datamodel.Particles(keys=[13, 14]) + particles2.mass = [20, 21] | units.kg + superset = particles1 | particles2 particle_in_copy = particles1_copy[1] particle_in_superset = superset[1] self.assertAlmostRelativeEquals(particle_in_copy.mass, 6 | units.kg) @@ -1090,20 +1068,20 @@ def test11(self): self.assertAlmostRelativeEquals(particles_in_original.mass, 2 | units.kg) def test12(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg particles2 = datamodel.Particles() - superset = particles1 | particles2 + superset = particles1 | particles2 self.assertEqual(superset.get_attribute_names_defined_in_store(), ["mass"]) def test13(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg - particles1.other1 = [1,2,3,4] | units.kg - particles2 = datamodel.Particles(keys=[13,14,15,16]) - particles2.mass = [1,2,3,4] | units.kg - particles2.other2 = [1,2,3,4] | units.kg - superset = particles1 | particles2 + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg + particles1.other1 = [1, 2, 3, 4] | units.kg + particles2 = datamodel.Particles(keys=[13, 14, 15, 16]) + particles2.mass = [1, 2, 3, 4] | units.kg + particles2.other2 = [1, 2, 3, 4] | units.kg + superset = particles1 | particles2 self.assertEqual(superset.get_attribute_names_defined_in_store(), ["mass"]) def test14(self): @@ -1111,7 +1089,7 @@ def test14(self): particles1.name = '123' particles2 = datamodel.Particles(3) particles2.name = '1234' - superset = particles1 | particles2 + superset = particles1 | particles2 for i in range(3): self.assertEqual(superset[i].name, '123') self.assertEqual(superset.name[i], '123') @@ -1132,8 +1110,8 @@ class TestParticlesWithFilteredAttributes(amusetest.TestCase): def test1(self): particles = datamodel.Particles(3) - particles.mass = [1,2,3] | units.kg - particles.radius = [1,2,3] | units.m + particles.mass = [1, 2, 3] | units.kg + particles.radius = [1, 2, 3] | units.m particles1 = datamodel.ParticlesWithFilteredAttributes(particles, ["mass"]) self.assertEqual(particles1.get_attribute_names_defined_in_store(), ["mass"]) self.assertEqual(particles1.get_settable_attribute_names_defined_in_store(), ["mass"]) @@ -1145,56 +1123,57 @@ def test1(self): def test2(self): particles = datamodel.Particles(3) - particles.mass = [1,2,3] | units.kg - particles.radius = [1,2,3] | units.m + particles.mass = [1, 2, 3] | units.kg + particles.radius = [1, 2, 3] | units.m particles1 = datamodel.ParticlesWithFilteredAttributes(particles, ["mass"]) - particles1.mass = [4,5,6] | units.kg + particles1.mass = [4, 5, 6] | units.kg print(particles1) - self.assertAlmostRelativeEquals(particles.mass, [4,5,6] | units.kg) + self.assertAlmostRelativeEquals(particles.mass, [4, 5, 6] | units.kg) def test3(self): particles = datamodel.Particles(3) - particles.mass = [1,2,3] | units.kg - particles.radius = [1,2,3] | units.m + particles.mass = [1, 2, 3] | units.kg + particles.radius = [1, 2, 3] | units.m particles1 = datamodel.ParticlesWithFilteredAttributes(particles, ["mass"]) def set_mass(): - particles1.radius = [4,5,6] | units.m + particles1.radius = [4, 5, 6] | units.m self.assertRaises(Exception, set_mass) + class TestParticlesSupersetWithNames(amusetest.TestCase): def test1(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg - particles2 = datamodel.Particles(keys=[13,14]) - particles2.mass = [20,21] | units.kg + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg + particles2 = datamodel.Particles(keys=[13, 14]) + particles2.mass = [20, 21] | units.kg superset = datamodel.ParticlesSuperset( [particles1, particles2], - names = ['one', 'two'] + names=['one', 'two'] ) self.assertEqual(len(superset), 6) - self.assertAlmostRelativeEquals(superset.mass, [1,2,3,4,20,21] | units.kg) + self.assertAlmostRelativeEquals(superset.mass, [1, 2, 3, 4, 20, 21] | units.kg) particles_1 = superset.get_subset('one') - self.assertAlmostRelativeEquals(particles_1.mass, [1,2,3,4] | units.kg) + self.assertAlmostRelativeEquals(particles_1.mass, [1, 2, 3, 4] | units.kg) particles_2 = superset.get_subset('two') - self.assertAlmostRelativeEquals(particles_2.mass, [20,21] | units.kg) + self.assertAlmostRelativeEquals(particles_2.mass, [20, 21] | units.kg) def test2(self): - particles1 = datamodel.Particles(keys=[9,10,11,12]) - particles1.mass = [1,2,3,4] | units.kg - particles2 = datamodel.Particles(keys=[13,14]) - particles2.mass = [20,21] | units.kg + particles1 = datamodel.Particles(keys=[9, 10, 11, 12]) + particles1.mass = [1, 2, 3, 4] | units.kg + particles2 = datamodel.Particles(keys=[13, 14]) + particles2.mass = [20, 21] | units.kg superset = datamodel.ParticlesSuperset( [particles1, particles2], - names = ['one', 'two'] + names=['one', 'two'] ) self.assertEqual(len(superset), 6) - self.assertAlmostRelativeEquals(superset.mass, [1,2,3,4,20,21] | units.kg) + self.assertAlmostRelativeEquals(superset.mass, [1, 2, 3, 4, 20, 21] | units.kg) particles_1 = superset['one'] - self.assertAlmostRelativeEquals(particles_1.mass, [1,2,3,4] | units.kg) + self.assertAlmostRelativeEquals(particles_1.mass, [1, 2, 3, 4] | units.kg) particles_2 = superset['two'] - self.assertAlmostRelativeEquals(particles_2.mass, [20,21] | units.kg) + self.assertAlmostRelativeEquals(particles_2.mass, [20, 21] | units.kg) class TestParticlesExtra(amusetest.TestCase): @@ -1214,8 +1193,8 @@ def test1(self): def test2(self): particles = datamodel.Particles(2) - particles.mass = [1,1]|units.kg - heavy = particles.select(lambda m: m>1|units.kg, ["mass"]) + particles.mass = [1, 1] | units.kg + heavy = particles.select(lambda m: m > 1 | units.kg, ["mass"]) self.assertTrue(heavy.is_empty()) def test3(self): @@ -1231,7 +1210,6 @@ def test3(self): state0 = particles.get_state_at_timestamp(2.6 | units.s) self.assertEqual(state0[0].mass, 4.0 | units.kg) - def test4(self): particles = datamodel.Particles(2) @@ -1261,7 +1239,6 @@ def test5(self): copyof_subset = subset.copy() self.assertEqual(len(copyof_subset), 1) - def test6(self): particles = datamodel.Particles(2) @@ -1273,18 +1250,17 @@ def test6(self): particles.y = 0.0 | units.m particles.z = 0.0 | units.m - Ek=0. | units.J - Ep=0. | units.J + Ek = 0. | units.J + Ep = 0. | units.J for x in particles: - Ek+=x.mass*x.specific_kinetic_energy() - Ep+=x.mass*x.potential()/2 + Ek += x.mass*x.specific_kinetic_energy() + Ep += x.mass*x.potential()/2 self.assertEqual(particles.kinetic_energy(), Ek) self.assertEqual(particles.potential_energy(), Ep) self.assertEqual((particles.mass*particles.specific_kinetic_energy()).sum(), Ek) self.assertEqual(0.5*(particles.mass*particles.potential()).sum(), Ep) - def test7(self): particles = datamodel.Particles(10) @@ -1293,26 +1269,26 @@ def test7(self): def test8(self): particles = datamodel.Particles(4) - particles.mass = [1.,2.,3.,4.] | units.kg + particles.mass = [1., 2., 3., 4.] | units.kg subset = particles[0:2] self.assertEqual(len(subset), 2) self.assertTrue(str(subset).find('kg') > 0) def test9(self): particles = datamodel.Particles(4) - particles.mass = [1.,2.,3.,4.] | units.kg - particles.vy = [1.,2.,3.,4.] | units.m / units.s - particles.vx = [0.,1.,2.,3.] | units.m / units.s - particles.vz = [1.,2.,3.,4.] | units.m / units.s - particles.x = [0., 1.,2.,3.] | units.m - particles.y = [4., 3.,2.,1.] | units.m - particles.z = [4., 3.,2.,1.] | units.m - - Ek=0. | units.J - Ep=0. | units.J + particles.mass = [1., 2., 3., 4.] | units.kg + particles.vy = [1., 2., 3., 4.] | units.m / units.s + particles.vx = [0., 1., 2., 3.] | units.m / units.s + particles.vz = [1., 2., 3., 4.] | units.m / units.s + particles.x = [0., 1., 2., 3.] | units.m + particles.y = [4., 3., 2., 1.] | units.m + particles.z = [4., 3., 2., 1.] | units.m + + Ek = 0. | units.J + Ep = 0. | units.J for x in particles: - Ek+=x.mass*x.specific_kinetic_energy() - Ep+=x.mass*x.potential()/2 + Ek += x.mass*x.specific_kinetic_energy() + Ep += x.mass*x.potential()/2 self.assertEqual(particles.kinetic_energy(), Ek) self.assertEqual(particles.potential_energy(), Ep) @@ -1321,29 +1297,26 @@ def test9(self): def test10(self): particles = datamodel.Particles(4) - particles.mass = [1.,2.,3.,4.] | units.kg + particles.mass = [1., 2., 3., 4.] | units.kg subset = particles[0:2] self.assertEqual(len(subset), 2) masses, = subset.get_values_in_store(None, ['mass']) self.assertEqual(len(masses), 2) subset.mass = 5.0 | units.kg - self.assertAlmostRelativeEquals( particles.mass , [5.,5.,3.,4.] | units.kg) + self.assertAlmostRelativeEquals(particles.mass, [5., 5., 3., 4.] | units.kg) subset.set_values_in_store(None, ['mass'], [6.0 | units.kg,]) - self.assertAlmostRelativeEquals( particles.mass , [6., 6.,3.,4.] | units.kg) - + self.assertAlmostRelativeEquals(particles.mass, [6., 6., 3., 4.] | units.kg) def test11(self): particles = datamodel.Particles(3) - particles.mass = range(3)| units.kg + particles.mass = range(3) | units.kg particles.nounit = range(3) - self.assertAlmostRelativeEquals( particles.mass, [0,1,2] | units.kg) - self.assertAlmostRelativeEquals( particles.nounit , [0, 1, 2]) - - + self.assertAlmostRelativeEquals(particles.mass, [0, 1, 2] | units.kg) + self.assertAlmostRelativeEquals(particles.nounit, [0, 1, 2]) def xtest12(self): particles = datamodel.Particles(3) - particles.mass = range(3)| units.kg + particles.mass = range(3) | units.kg particles[0].child = particles[1] particles[1].child = particles[2] print(particles[0].child) @@ -1353,8 +1326,6 @@ def xtest12(self): self.assertEqual(particles[1].child, particles[2]) self.assertEqual(particles[2].child, None) - - def test15(self): particles = datamodel.Particles(10) @@ -1377,17 +1348,16 @@ def test15(self): def test16(self): particles = datamodel.Particles(2) particles.add_vector_attribute('unitless', ['u1', 'u2', 'u3']) - particles.unitless = [[1,2,3],[4,5,6]] + particles.unitless = [[1, 2, 3], [4, 5, 6]] self.assertEqual(particles[0].u1, 1) self.assertEqual(particles[0].u3, 3) self.assertEqual(particles[1].u2, 5) - self.assertEqual(particles[0].unitless, [1,2,3]) - self.assertEqual(particles.unitless, [[1,2,3],[4,5,6]]) - particles[0].unitless = [7,8,9] - self.assertEqual(particles[0].unitless, [7,8,9]) + self.assertEqual(particles[0].unitless, [1, 2, 3]) + self.assertEqual(particles.unitless, [[1, 2, 3], [4, 5, 6]]) + particles[0].unitless = [7, 8, 9] + self.assertEqual(particles[0].unitless, [7, 8, 9]) self.assertEqual(particles[0].u1, 7) - self.assertEqual(particles.unitless, [ [7,8,9],[4,5,6]]) - + self.assertEqual(particles.unitless, [[7, 8, 9], [4, 5, 6]]) def test17(self): particles = datamodel.Particles(2) @@ -1409,22 +1379,22 @@ def test18(self): self.assertFalse(datamodel.Particle in particles) def test19(self): - particles = datamodel.Particles(mass = [1.0,2.0,3.0] | units.kg, radius = 1 | units.m) + particles = datamodel.Particles(mass=[1.0, 2.0, 3.0] | units.kg, radius=1 | units.m) self.assertEqual(len(particles), 3) - self.assertAlmostRelativeEquals(particles.mass, [1.0,2.0,3.0] | units.kg) - self.assertAlmostRelativeEquals(particles.radius, [1.0,1.0,1.0] | units.m) - particles = datamodel.Particles(b = 1, a = [1.0,2.0,3.0] ) + self.assertAlmostRelativeEquals(particles.mass, [1.0, 2.0, 3.0] | units.kg) + self.assertAlmostRelativeEquals(particles.radius, [1.0, 1.0, 1.0] | units.m) + particles = datamodel.Particles(b=1, a=[1.0, 2.0, 3.0]) self.assertEqual(len(particles), 3) - self.assertAlmostRelativeEquals(particles.a, [1.0,2.0,3.0]) - self.assertAlmostRelativeEquals(particles.b, [1.0,1.0,1.0]) - particles = datamodel.Particles(size = 3,b = 1, a = [1.0,2.0,3.0] ) + self.assertAlmostRelativeEquals(particles.a, [1.0, 2.0, 3.0]) + self.assertAlmostRelativeEquals(particles.b, [1.0, 1.0, 1.0]) + particles = datamodel.Particles(size=3, b=1, a=[1.0, 2.0, 3.0]) self.assertEqual(len(particles), 3) - self.assertAlmostRelativeEquals(particles.a, [1.0,2.0,3.0]) - self.assertAlmostRelativeEquals(particles.b, [1.0,1.0,1.0]) - particles = datamodel.Particles(size = 3,b = 1, a = 2 ) + self.assertAlmostRelativeEquals(particles.a, [1.0, 2.0, 3.0]) + self.assertAlmostRelativeEquals(particles.b, [1.0, 1.0, 1.0]) + particles = datamodel.Particles(size=3, b=1, a=2) self.assertEqual(len(particles), 3) - self.assertAlmostRelativeEquals(particles.a, [2,2,2]) - self.assertAlmostRelativeEquals(particles.b, [1.0,1.0,1.0]) + self.assertAlmostRelativeEquals(particles.a, [2, 2, 2]) + self.assertAlmostRelativeEquals(particles.b, [1.0, 1.0, 1.0]) def test20(self): @@ -1440,7 +1410,6 @@ def test20(self): particles.b = [4, 5, 6] self.assertEqual(particles[0].b, 4 | units.none) - def test21(self): particles = datamodel.Particles(3) particles.z = quantities.zero @@ -1451,7 +1420,6 @@ def test21(self): print(particles[0].z) self.assertEqual(particles.z.unit, units.kg) - def test22(self): particles = datamodel.Particles(3) particles.z = quantities.zero @@ -1460,31 +1428,30 @@ def test22(self): self.assertEqual(particles.z.unit, units.kg) def test23(self): - p=datamodel.Particles(3) + p = datamodel.Particles(3) + + p.a1 = 1. + p.a2 = 1. | units.rad + p.a3 = 1. | units.deg - p.a1=1. - p.a2=1. | units.rad - p.a3=1. | units.deg - # test all combinations: - - p[0].a1=2. - p[0].a2=2. - p[0].a3=2. - - p[1].a1=2. | units.rad - p[1].a2=2. | units.rad - p[1].a3=2. | units.rad - - p[2].a1=2. | units.deg - p[2].a2=2. | units.deg - p[2].a3=2. | units.deg - - self.assertEqual( p.a1, [2.,2., (2. | units.deg).value_in(units.none)]) - self.assertEqual( p.a2, [2.,2., (2. | units.deg).value_in(units.none)]) - self.assertEqual( p.a3, [(2. | units.rad).in_(units.deg), - (2. | units.rad).in_(units.deg) , 2. | units.deg]) - + + p[0].a1 = 2. + p[0].a2 = 2. + p[0].a3 = 2. + + p[1].a1 = 2. | units.rad + p[1].a2 = 2. | units.rad + p[1].a3 = 2. | units.rad + + p[2].a1 = 2. | units.deg + p[2].a2 = 2. | units.deg + p[2].a3 = 2. | units.deg + + self.assertEqual(p.a1, [2., 2., (2. | units.deg).value_in(units.none)]) + self.assertEqual(p.a2, [2., 2., (2. | units.deg).value_in(units.none)]) + self.assertEqual(p.a3, [(2. | units.rad).in_(units.deg), + (2. | units.rad).in_(units.deg), 2. | units.deg]) class TestStars(amusetest.TestCase): @@ -1492,41 +1459,37 @@ class TestStars(amusetest.TestCase): def test1(self): stars = datamodel.Particles(2) stars[0].mass = 10 | units.g - stars[0].position = units.m(numpy.array([1.0,2.0,1.0])) + stars[0].position = units.m(numpy.array([1.0, 2.0, 1.0])) stars[1].mass = 10 | units.g - stars[1].position = units.m(numpy.array([0.0,0.0,0.0])) + stars[1].position = units.m(numpy.array([0.0, 0.0, 0.0])) self.assertEqual(0.5 | units.m, stars.center_of_mass().x) def test2(self): stars = datamodel.Particles(2) stars[0].mass = 10 | units.g - stars[0].velocity = (units.m / units.s)(numpy.array([1.0,2.0,1.0])) + stars[0].velocity = (units.m / units.s)(numpy.array([1.0, 2.0, 1.0])) stars[1].mass = 10 | units.g - stars[1].velocity = (units.m / units.s)(numpy.array([0.0,0.0,0.0])) + stars[1].velocity = (units.m / units.s)(numpy.array([0.0, 0.0, 0.0])) self.assertEqual(0.5 | units.m / units.s, stars.center_of_mass_velocity().x) self.assertEqual(1.0 | units.m / units.s, stars.center_of_mass_velocity().y) - def test3(self): stars = datamodel.Particles(2) stars[0].mass = 10 | units.g - stars[0].velocity = (units.m / units.s)(numpy.array([1.0,2.0,1.0])) - stars[0].position = units.m(numpy.array([1.0,2.0,1.0])) + stars[0].velocity = (units.m / units.s)(numpy.array([1.0, 2.0, 1.0])) + stars[0].position = units.m(numpy.array([1.0, 2.0, 1.0])) stars[1].mass = 10 | units.g - stars[1].velocity = (units.m / units.s)(numpy.array([0.0,0.0,0.0])) - stars[1].position = units.m(numpy.array([0.0,0.0,0.0])) - + stars[1].velocity = (units.m / units.s)(numpy.array([0.0, 0.0, 0.0])) + stars[1].position = units.m(numpy.array([0.0, 0.0, 0.0])) - self.assertEqual(stars.mass[0], 10|units.g) + self.assertEqual(stars.mass[0], 10 | units.g) self.assertEqual(stars.position[0], [1.0, 2.0, 1.0] | units.m) self.assertEqual(stars.velocity[0], [1.0, 2.0, 1.0] | units.m / units.s) - - def test4(self): stars = datamodel.Particles(2) - stars[0].x = 1.0 | units.km + stars[0].x = 1.0 | units.km stars[0].y = 2000.0 | units.m stars[0].z = 3500.0 | units.m @@ -1534,43 +1497,43 @@ def test4(self): def test5(self): stars = datamodel.Particles(2) - stars.x = 1.0 | units.km - stars.md = [[1,2,3],[4,5,6]] | units.km + stars.x = 1.0 | units.km + stars.md = [[1, 2, 3], [4, 5, 6]] | units.km - self.assertEqual(stars[0].md, [1,2,3] | units.km) - self.assertEqual(stars[1].md, [4,5,6] | units.km) + self.assertEqual(stars[0].md, [1, 2, 3] | units.km) + self.assertEqual(stars[1].md, [4, 5, 6] | units.km) - self.assertEqual(stars.md[0], [1,2,3] | units.km) - self.assertEqual(stars.md[1], [4,5,6] | units.km) - stars.md_nounit = [[1,2,3],[4,5,6]] + self.assertEqual(stars.md[0], [1, 2, 3] | units.km) + self.assertEqual(stars.md[1], [4, 5, 6] | units.km) + stars.md_nounit = [[1, 2, 3], [4, 5, 6]] - self.assertEqual(stars[0].md_nounit, [1,2,3]) - self.assertEqual(stars[1].md_nounit, [4,5,6]) - self.assertEqual(stars.md_nounit[0], [1,2,3]) - self.assertEqual(stars.md_nounit[1], [4,5,6]) + self.assertEqual(stars[0].md_nounit, [1, 2, 3]) + self.assertEqual(stars[1].md_nounit, [4, 5, 6]) + self.assertEqual(stars.md_nounit[0], [1, 2, 3]) + self.assertEqual(stars.md_nounit[1], [4, 5, 6]) - stars.md2 = [[[1,3],[2,4],[3,6]],[[4,2],[5,3],[6,1]]] | units.km + stars.md2 = [[[1, 3], [2, 4], [3, 6]], [[4, 2], [5, 3], [6, 1]]] | units.km - self.assertEqual(stars[0].md2, [[1,3],[2,4],[3,6]] | units.km) - self.assertEqual(stars[1].md2, [[4,2],[5,3],[6,1]] | units.km) - self.assertEqual(stars.md2[0], [[1,3],[2,4],[3,6]] | units.km) - self.assertEqual(stars.md2[1], [[4,2],[5,3],[6,1]] | units.km) + self.assertEqual(stars[0].md2, [[1, 3], [2, 4], [3, 6]] | units.km) + self.assertEqual(stars[1].md2, [[4, 2], [5, 3], [6, 1]] | units.km) + self.assertEqual(stars.md2[0], [[1, 3], [2, 4], [3, 6]] | units.km) + self.assertEqual(stars.md2[1], [[4, 2], [5, 3], [6, 1]] | units.km) def test6(self): stars = datamodel.Particles(2) - stars.x = 1.0 | units.km - stars.md = [[1,2,3],[4,5,6]] | units.km + stars.x = 1.0 | units.km + stars.md = [[1, 2, 3], [4, 5, 6]] | units.km - self.assertEqual(stars[0].md, [1,2,3] | units.km) - self.assertEqual(stars[1].md, [4,5,6] | units.km) + self.assertEqual(stars[0].md, [1, 2, 3] | units.km) + self.assertEqual(stars[1].md, [4, 5, 6] | units.km) copy = stars.copy() - self.assertEqual(copy[0].md, [1,2,3] | units.km) - self.assertEqual(copy[1].md, [4,5,6] | units.km) - copy[0].md = [7,8,9] | units.km - self.assertEqual(stars[0].md, [1,2,3] | units.km) - self.assertEqual(copy[0].md, [7,8,9] | units.km) + self.assertEqual(copy[0].md, [1, 2, 3] | units.km) + self.assertEqual(copy[1].md, [4, 5, 6] | units.km) + copy[0].md = [7, 8, 9] | units.km + self.assertEqual(stars[0].md, [1, 2, 3] | units.km) + self.assertEqual(copy[0].md, [7, 8, 9] | units.km) class TestParticlesWithBinding(amusetest.TestCase): @@ -1587,13 +1550,13 @@ def get_mass(self, id): for x in id: masses.append(self.masses[x]) errors.append(0) - return ( masses, errors, ) + return (masses, errors, ) def set_mass(self, id, mass): - for i,m in zip(id,mass): + for i, m in zip(id, mass): self.masses[i] = m - return ( [0] * len(id),) + return ([0] * len(id),) def get_radius(self, id): masses = [] @@ -1601,7 +1564,7 @@ def get_radius(self, id): for x in id: masses.append(1) errors.append(0) - return ( masses, errors, ) + return (masses, errors, ) def get_link(self, id): result = [] @@ -1609,33 +1572,31 @@ def get_link(self, id): for x in id: result.append(self.links[x]) errors.append(0) - return ( result, errors, ) + return (result, errors, ) def set_link(self, id, link): - for i,l in zip(id,link): + for i, l in zip(id, link): self.links[i] = l - return ( [0] * len(id),) - - + return ([0] * len(id),) def get_grid(self, id, index1, index2): result = [] errors = [] - for x,i1,i2 in zip(id, index1, index2): + for x, i1, i2 in zip(id, index1, index2): result.append(self.grids[x][i1][i2]) errors.append(0) - return ( result, errors, ) + return (result, errors, ) def set_grid(self, id, index1, index2, value): errors = [] - for x,i1,i2, v in zip(id, index1, index2, value): + for x, i1, i2, v in zip(id, index1, index2, value): self.grids[x][i1][i2] = v errors.append(0) - return ( 0, ) + return (0, ) def get_grid_range(self): - return ( 0, 3, 0, 2 ) + return (0, 3, 0, 2) def new_particle(self, mass): ids = [] @@ -1643,9 +1604,9 @@ def new_particle(self, mass): for x in mass: index = len(self.masses) - self.masses[index] = x - self.links[index] = -1 - self.grids[index] = numpy.arange(4*3).reshape(4,3) + self.masses[index] = x + self.links[index] = -1 + self.grids[index] = numpy.arange(4*3).reshape(4, 3) ids.append(index) errors.append(0) @@ -1671,28 +1632,27 @@ def __init__(self): InCodeComponentImplementation.__init__(self, TestParticlesWithBinding.TestLegacyCode()) def define_methods(self, handler): - handler.add_method('get_mass',(handler.NO_UNIT,), (units.g, handler.ERROR_CODE)) - handler.add_method('set_mass',(handler.NO_UNIT, units.g,), (handler.ERROR_CODE,)) - handler.add_method('get_link',(handler.NO_UNIT,), (handler.LINK('particles'), handler.ERROR_CODE)) - handler.add_method('set_link',(handler.NO_UNIT, handler.LINK('particles'),), (handler.ERROR_CODE,)) - handler.add_method('get_grid',(handler.NO_UNIT,handler.NO_UNIT,handler.NO_UNIT), (units.g, handler.ERROR_CODE)) - handler.add_method('set_grid',(handler.NO_UNIT,handler.NO_UNIT,handler.NO_UNIT, units.g), ( handler.ERROR_CODE)) - - handler.add_method('new_particle',(units.g,), (handler.INDEX, handler.ERROR_CODE)) - handler.add_method('delete_particle',(handler.NO_UNIT,), (handler.ERROR_CODE,)) - handler.add_method('get_number_of_particles',(), (handler.NO_UNIT, handler.ERROR_CODE,)) + handler.add_method('get_mass', (handler.NO_UNIT,), (units.g, handler.ERROR_CODE)) + handler.add_method('set_mass', (handler.NO_UNIT, units.g,), (handler.ERROR_CODE,)) + handler.add_method('get_link', (handler.NO_UNIT,), (handler.LINK('particles'), handler.ERROR_CODE)) + handler.add_method('set_link', (handler.NO_UNIT, handler.LINK('particles'),), (handler.ERROR_CODE,)) + handler.add_method('get_grid', (handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT), (units.g, handler.ERROR_CODE)) + handler.add_method('set_grid', (handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, units.g), (handler.ERROR_CODE)) + handler.add_method('new_particle', (units.g,), (handler.INDEX, handler.ERROR_CODE)) + handler.add_method('delete_particle', (handler.NO_UNIT,), (handler.ERROR_CODE,)) + handler.add_method('get_number_of_particles', (), (handler.NO_UNIT, handler.ERROR_CODE,)) def define_particle_sets(self, handler): handler.define_set('particles', 'id') handler.set_new('particles', 'new_particle') handler.set_delete('particles', 'delete_particle') handler.add_setter('particles', 'set_mass') - handler.add_getter('particles', 'get_mass', names = ('mass',)) + handler.add_getter('particles', 'get_mass', names=('mass',)) handler.add_setter('particles', 'set_link') - handler.add_getter('particles', 'get_link', names = ('link',)) - handler.add_gridded_getter('particles', 'get_grid','get_grid_range', names = ('grid',)) - handler.add_gridded_setter('particles', 'set_grid','get_grid_range', names = ('grid',)) + handler.add_getter('particles', 'get_link', names=('link',)) + handler.add_gridded_getter('particles', 'get_grid', 'get_grid_range', names=('grid',)) + handler.add_gridded_setter('particles', 'set_grid', 'get_grid_range', names=('grid',)) class TestInterfaceSuperset(InCodeComponentImplementation): @@ -1700,47 +1660,46 @@ def __init__(self): InCodeComponentImplementation.__init__(self, TestParticlesWithBinding.TestLegacyCode()) def define_methods(self, handler): - handler.add_method('get_mass',(handler.NO_UNIT,), (units.g, handler.ERROR_CODE)) - handler.add_method('set_mass',(handler.NO_UNIT, units.g,), (handler.ERROR_CODE,)) - handler.add_method('get_link',(handler.NO_UNIT,), (handler.LINK('particles'), handler.ERROR_CODE)) - handler.add_method('set_link',(handler.NO_UNIT, handler.LINK('particles'),), (handler.ERROR_CODE,)) - handler.add_method('get_grid',(handler.NO_UNIT,handler.NO_UNIT,handler.NO_UNIT), (units.g, handler.ERROR_CODE)) - handler.add_method('set_grid',(handler.NO_UNIT,handler.NO_UNIT,handler.NO_UNIT, units.g), ( handler.ERROR_CODE)) - - handler.add_method('new_particle',(units.g,), (handler.INDEX, handler.ERROR_CODE)) - handler.add_method('delete_particle',(handler.NO_UNIT,), (handler.ERROR_CODE,)) - handler.add_method('get_number_of_particles',(), (handler.NO_UNIT, handler.ERROR_CODE,)) + handler.add_method('get_mass', (handler.NO_UNIT,), (units.g, handler.ERROR_CODE)) + handler.add_method('set_mass', (handler.NO_UNIT, units.g,), (handler.ERROR_CODE,)) + handler.add_method('get_link', (handler.NO_UNIT,), (handler.LINK('particles'), handler.ERROR_CODE)) + handler.add_method('set_link', (handler.NO_UNIT, handler.LINK('particles'),), (handler.ERROR_CODE,)) + handler.add_method('get_grid', (handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT), (units.g, handler.ERROR_CODE)) + handler.add_method('set_grid', (handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, units.g), (handler.ERROR_CODE)) + handler.add_method('new_particle', (units.g,), (handler.INDEX, handler.ERROR_CODE)) + handler.add_method('delete_particle', (handler.NO_UNIT,), (handler.ERROR_CODE,)) + handler.add_method('get_number_of_particles', (), (handler.NO_UNIT, handler.ERROR_CODE,)) def define_particle_sets(self, handler): handler.define_super_set( 'particles', - ['particles1','particles2'], - index_to_default_set = 0 + ['particles1', 'particles2'], + index_to_default_set=0 ) handler.define_set('particles1', 'id') handler.set_new('particles1', 'new_particle') handler.set_delete('particles1', 'delete_particle') handler.add_setter('particles1', 'set_mass') - handler.add_getter('particles1', 'get_mass', names = ('mass',)) + handler.add_getter('particles1', 'get_mass', names=('mass',)) handler.add_setter('particles1', 'set_link') - handler.add_getter('particles1', 'get_link', names = ('link',)) - handler.add_gridded_getter('particles1', 'get_grid','get_grid_range', names = ('grid',)) - handler.add_gridded_setter('particles1', 'set_grid','get_grid_range', names = ('grid',)) + handler.add_getter('particles1', 'get_link', names=('link',)) + handler.add_gridded_getter('particles1', 'get_grid', 'get_grid_range', names=('grid',)) + handler.add_gridded_setter('particles1', 'set_grid', 'get_grid_range', names=('grid',)) handler.define_set('particles2', 'id') handler.set_new('particles2', 'new_particle') handler.set_delete('particles2', 'delete_particle') handler.add_setter('particles2', 'set_mass') - handler.add_getter('particles2', 'get_mass', names = ('mass',)) + handler.add_getter('particles2', 'get_mass', names=('mass',)) handler.add_setter('particles2', 'set_link') - handler.add_getter('particles2', 'get_link', names = ('link',)) - handler.add_gridded_getter('particles2', 'get_grid','get_grid_range', names = ('grid',)) - handler.add_gridded_setter('particles2', 'set_grid','get_grid_range', names = ('grid',)) + handler.add_getter('particles2', 'get_link', names=('link',)) + handler.add_gridded_getter('particles2', 'get_grid', 'get_grid_range', names=('grid',)) + handler.add_gridded_setter('particles2', 'set_grid', 'get_grid_range', names=('grid',)) def test1(self): interface = self.TestInterface() interface.particles.add_particles_to_store( - [1,2], + [1, 2], ["mass"], [[3.0, 4.0] | units.kg] ) @@ -1762,7 +1721,6 @@ def test1(self): self.assertEqual(remote_particles[0].mass.value_in(units.kg), 3.5) self.assertEqual(local_particles[0].mass.value_in(units.kg), 3.5) - def test2(self): interface = self.TestInterface() interface.particles.add_particles_to_store( @@ -1783,7 +1741,7 @@ def test2(self): self.assertEqual(len(remote_particles), 4) - self.assertAlmostRelativeEquals(remote_particles.mass, [3,4,5,6] | units.kg) + self.assertAlmostRelativeEquals(remote_particles.mass, [3, 4, 5, 6] | units.kg) self.assertEqual(remote_particles[0].mass.value_in(units.kg), 3) self.assertEqual(remote_particles[2].mass.value_in(units.kg), 5) @@ -1793,14 +1751,12 @@ def test2(self): self.assertEqual(remote_particles[0].mass.value_in(units.kg), 4) self.assertEqual(remote_particles[1].mass.value_in(units.kg), 6) - def test3(self): interface = self.TestInterface() local_particles = datamodel.Particles(2) local_particles.mass = units.kg.new_quantity([3.0, 4.0]) - remote_particles = interface.particles remote_particles.add_particles(local_particles) @@ -1825,15 +1781,12 @@ def test3(self): self.assertEqual(remote_particles[0].mass.value_in(units.kg), 4) self.assertEqual(remote_particles[1].mass.value_in(units.kg), 6) - - def test4(self): interface = self.TestInterface() local_particles = datamodel.Particles(2) local_particles.mass = units.kg.new_quantity([3.0, 4.0]) - remote_particles = interface.particles remote_particles.add_particles(local_particles) @@ -1845,15 +1798,12 @@ def test4(self): self.assertEqual(len(local_particles), 3) - - def test5(self): interface = self.TestInterface() local_particles1 = datamodel.Particles(2) local_particles1.mass = units.kg.new_quantity([3.0, 4.0]) - remote_particles = interface.particles remote_particles.add_particles(local_particles1) @@ -1871,7 +1821,6 @@ def test5(self): local_particles1.synchronize_to(remote_particles) self.assertEqual(len(remote_particles), 4) - def test6(self): interface = self.TestInterface() @@ -1896,7 +1845,6 @@ def test6(self): remote_particles.remove_particle(local_particle) self.assertEqual(len(remote_particles), 2) - def test7(self): interface = self.TestInterface() @@ -1907,7 +1855,7 @@ def test7(self): remote_particles.add_particles(local_particles) local_particles.unknown_attribute = [3.0, 4.0] | units.m - local_particles.mass = [1,3] | units.kg + local_particles.mass = [1, 3] | units.kg channel = local_particles.new_channel_to(remote_particles) self.assertRaises(Exception, channel.copy_all_attributes) @@ -1916,32 +1864,28 @@ def test7(self): self.assertEqual(remote_particles.mass, local_particles.mass) - def test8(self): interface = self.TestInterface() local_particles1 = datamodel.Particles(2) local_particles1.mass = units.kg.new_quantity([3.0, 4.0]) - remote_particles = interface.particles remote_particles.add_particles(local_particles1) particle_ref = datamodel.LinkedArray([remote_particles[1]]) - interface.set_link([0],particle_ref) + interface.set_link([0], particle_ref) self.assertEqual(interface.legacy_interface.links[0], 1) p = interface.get_link([0]) self.assertEqual(p[0], remote_particles[1]) self.assertEqual(p[0], local_particles1[1]) - def test9(self): interface = self.TestInterface() local_particles1 = datamodel.Particles(2) local_particles1.mass = units.kg.new_quantity([3.0, 4.0]) - remote_particles = interface.particles remote_particles.add_particles(local_particles1) self.assertEqual(remote_particles.link[0], None) @@ -1956,14 +1900,12 @@ def test9(self): self.assertEqual(local_particles1.link[0], local_particles1[1]) self.assertEqual(local_particles1.link[1], None) - def test10(self): interface = self.TestInterface() local_particles = datamodel.Particles(2) local_particles.mass = units.kg.new_quantity([3.0, 4.0]) - remote_particles = interface.particles remote_particles.add_particles(local_particles) self.assertEqual(remote_particles[0].grid[1][2], 5 | units.g) @@ -1975,7 +1917,6 @@ def test11(self): local_particles = datamodel.Particles(2) local_particles.mass = units.kg.new_quantity([3.0, 4.0]) - remote_particles = interface.particles remote_particles.add_particles(local_particles) @@ -1997,11 +1938,11 @@ def test12(self): remote_particles = interface.particles remote_particles.add_particles(local_particles) query = incode_storage.ParticleQueryMethod( - lambda : [0,2] + lambda: [0, 2] ) selected_particles = query.apply(remote_particles) self.assertEqual(len(selected_particles), 2) - self.assertAlmostRelativeEquals(selected_particles.mass, [3.0,5.0] | units.kg) + self.assertAlmostRelativeEquals(selected_particles.mass, [3.0, 5.0] | units.kg) def test13(self): interface = self.TestInterfaceSuperset() @@ -2014,13 +1955,12 @@ def test13(self): interface.particles1.add_particles(local_particles1) interface.particles2.add_particles(local_particles2) query = incode_storage.ParticleQueryMethod( - lambda : [0,2], - query_superset = True + lambda: [0, 2], + query_superset=True ) selected_particles = query.apply(interface.particles) self.assertEqual(len(selected_particles), 2) - self.assertAlmostRelativeEquals(selected_particles.mass, [3.0,5.0] | units.kg) - + self.assertAlmostRelativeEquals(selected_particles.mass, [3.0, 5.0] | units.kg) def test14(self): interface = self.TestInterfaceSuperset() @@ -2033,12 +1973,12 @@ def test14(self): interface.particles1.add_particles(local_particles1) interface.particles2.add_particles(local_particles2) query = incode_storage.ParticleQueryMethod( - lambda : [3,2], - query_superset = True + lambda: [3, 2], + query_superset=True ) selected_particles = query.apply(interface.particles) self.assertEqual(len(selected_particles), 2) - self.assertAlmostRelativeEquals(selected_particles.mass, [6.0,5.0] | units.kg) + self.assertAlmostRelativeEquals(selected_particles.mass, [6.0, 5.0] | units.kg) def test15(self): @@ -2052,25 +1992,25 @@ def test15(self): local_particles.mass = 10 | units.kg - self.assertAlmostRelativeEquals(remote_particles.mass , [3.0, 4.0] | units.kg) + self.assertAlmostRelativeEquals(remote_particles.mass, [3.0, 4.0] | units.kg) channel = remote_particles.new_channel_to(local_particles) channel.copy() - self.assertAlmostRelativeEquals(local_particles.mass , [3.0, 4.0] | units.kg) + self.assertAlmostRelativeEquals(local_particles.mass, [3.0, 4.0] | units.kg) remote_particles._remove_indices_in_attribute_storage([1]) local_particles.mass = 10 | units.kg channel.copy() - self.assertAlmostRelativeEquals(local_particles.mass , [3.0, 10.0] | units.kg) + self.assertAlmostRelativeEquals(local_particles.mass, [3.0, 10.0] | units.kg) remote_particles._add_indices_in_attribute_storage([1]) local_particles.mass = 10 | units.kg channel.copy() - self.assertAlmostRelativeEquals(local_particles.mass , [3.0, 10.0] | units.kg) + self.assertAlmostRelativeEquals(local_particles.mass, [3.0, 10.0] | units.kg) def test16(self): local_particles = datamodel.Particles(2) @@ -2080,9 +2020,7 @@ def test16(self): local_particles.mass_squared = [9.0, 16.0] | units.kg**2 local_particles.add_calculated_attribute("mass", lambda m2: m2.sqrt(), attributes_names=["mass_squared"]) interface.particles.add_particles(local_particles) - self.assertAlmostRelativeEquals(interface.particles.mass , [3.0, 4.0] | units.kg) - - + self.assertAlmostRelativeEquals(interface.particles.mass, [3.0, 4.0] | units.kg) class TestInterface2(InCodeComponentImplementation): @@ -2090,27 +2028,26 @@ def __init__(self): InCodeComponentImplementation.__init__(self, TestParticlesWithBinding.TestLegacyCode()) def define_methods(self, handler): - handler.add_method('get_mass',(handler.NO_UNIT,), (units.g, handler.ERROR_CODE)) - handler.add_method('set_mass',(handler.NO_UNIT, units.g,), (handler.ERROR_CODE,)) - handler.add_method('get_radius',(handler.NO_UNIT,), (units.m, handler.ERROR_CODE)) - - handler.add_method('new_particle',(units.g,), (handler.INDEX, handler.ERROR_CODE)) - handler.add_method('delete_particle',(handler.NO_UNIT,), (handler.ERROR_CODE,)) - handler.add_method('get_number_of_particles',(), (handler.NO_UNIT, handler.ERROR_CODE,)) + handler.add_method('get_mass', (handler.NO_UNIT,), (units.g, handler.ERROR_CODE)) + handler.add_method('set_mass', (handler.NO_UNIT, units.g,), (handler.ERROR_CODE,)) + handler.add_method('get_radius', (handler.NO_UNIT,), (units.m, handler.ERROR_CODE)) + handler.add_method('new_particle', (units.g,), (handler.INDEX, handler.ERROR_CODE)) + handler.add_method('delete_particle', (handler.NO_UNIT,), (handler.ERROR_CODE,)) + handler.add_method('get_number_of_particles', (), (handler.NO_UNIT, handler.ERROR_CODE,)) def define_particle_sets(self, handler): handler.define_set('particles', 'id') handler.set_new('particles', 'new_particle') handler.set_delete('particles', 'delete_particle') handler.add_setter('particles', 'set_mass') - handler.add_getter('particles', 'get_mass', names = ('mass',)) - handler.add_getter('particles', 'get_radius', names = ('radius',)) + handler.add_getter('particles', 'get_mass', names=('mass',)) + handler.add_getter('particles', 'get_radius', names=('radius',)) def test17(self): interface = self.TestInterface2() interface.particles.add_particles_to_store( - [1,2], + [1, 2], ["mass"], [[3.0, 4.0] | units.kg] ) @@ -2126,12 +2063,12 @@ def test17(self): channel.copy() self.assertEqual(remote_particles[0].mass.value_in(units.kg), 3.5) - + def test18(self): interface = self.TestInterface() local_set = datamodel.Particles(5) local_set.mass = [1.0, 2.0, 3.0, 4.0, 5.0] | units.kg - + interface.particles.add_particles(local_set) set1 = interface.particles @@ -2143,6 +2080,7 @@ def test18(self): self.assertAlmostRelativeEquals(subset1.mass, [1.0] | units.kg) self.assertAlmostRelativeEquals(subset2.mass, [3.0] | units.kg) + class TestParticlesWithUnitsConverted(amusetest.TestCase): def test1(self): @@ -2169,14 +2107,12 @@ def from_target_to_source(self, quantity): self.assertEqual(stars[0].mass, 10 | units.g) self.assertEqual(converted_stars[0].mass, 10 | units.m) - converted_stars[0].mass = 30 | units.m self.assertEqual(stars[0].mass, 30 | units.g) - def test2(self): - convert_nbody = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + convert_nbody = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) stars = datamodel.Particles(1) stars[0].mass = 10 | nbody_system.mass @@ -2184,7 +2120,6 @@ def test2(self): stars[0].y = 20.0 | nbody_system.length stars[0].z = 30.0 | nbody_system.length - converted_stars = datamodel.ParticlesWithUnitsConverted( stars, convert_nbody.as_converter_from_si_to_generic()) @@ -2205,28 +2140,24 @@ def test2(self): for i in range(3): self.assertAlmostEqual(star.position[i], expected[i], 6) - - def test3(self): - convert_nbody = nbody_system.nbody_to_si(10 | units.kg, 1 | units.m ) + convert_nbody = nbody_system.nbody_to_si(10 | units.kg, 1 | units.m) - particles = datamodel.Particles(keys = [10,11,12,13]) - particles.x = [1,2,3,4] | units.m + particles = datamodel.Particles(keys=[10, 11, 12, 13]) + particles.x = [1, 2, 3, 4] | units.m particles = datamodel.ParticlesWithUnitsConverted( particles, convert_nbody.as_converter_from_generic_to_si() ) - self.assertAlmostRelativeEquals(particles.x, [1,2,3,4] | nbody_system.length) + self.assertAlmostRelativeEquals(particles.x, [1, 2, 3, 4] | nbody_system.length) i = 1 for particle in particles: - self.assertEqual(particle.x , i | nbody_system.length) + self.assertEqual(particle.x, i | nbody_system.length) i += 1 - - def test4(self): - convert_nbody = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + convert_nbody = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) stars = datamodel.Particles(1) @@ -2243,7 +2174,6 @@ def test4(self): self.assertEqual(converted_stars[0].stellar_type, units.stellar_type("Main Sequence star")) - class TestParticlesWithTransformedAttributes(amusetest.TestCase): def test1(self): @@ -2265,8 +2195,7 @@ def set_function(attribute, quantity): self.assertEqual(stars[0].mass, 10 | units.g) self.assertEqual(converted_stars[0].mass, 20 | units.g) - self.assertEqual(converted_stars.mass, [20,40] | units.g) - + self.assertEqual(converted_stars.mass, [20, 40] | units.g) converted_stars[0].mass = 40 | units.g @@ -2289,13 +2218,13 @@ def set_function(attribute, quantity): set_function ) - p=datamodel.Particle(mass=50. | units.g) + p = datamodel.Particle(mass=50. | units.g) converted_stars.add_particle(p) self.assertEqual(stars[2].mass, 25. | units.g) self.assertEqual(converted_stars[2].mass, 50 | units.g) - p=datamodel.Particle(mass=100. | units.g) + p = datamodel.Particle(mass=100. | units.g) stars.add_particle(p) self.assertEqual(stars[3].mass, 100. | units.g) @@ -2319,10 +2248,10 @@ def set_function(attribute, quantity): set_function ) - sub=converted_stars[0:2] + sub = converted_stars[0:2] self.assertEqual(sub[0].mass, 20 | units.g) self.assertEqual(sub[1].mass, 40 | units.g) - stars[0].mass=1 | units.g + stars[0].mass = 1 | units.g self.assertEqual(converted_stars[0].mass, 2 | units.g) self.assertEqual(sub[0].mass, 2 | units.g) @@ -2330,12 +2259,12 @@ def test4(self): stars = datamodel.Particles(2) stars[0].mass = 1 | units.MSun - stars[0].position = [0,0,0] | units.AU - stars[0].velocity = [0,1,0] | units.kms + stars[0].position = [0, 0, 0] | units.AU + stars[0].velocity = [0, 1, 0] | units.kms stars[1].mass = 1 | units.MSun - stars[1].position = [1,0,0] | units.AU - stars[1].velocity = [0,2,0] | units.kms + stars[1].position = [1, 0, 0] | units.AU + stars[1].velocity = [0, 2, 0] | units.kms com = stars.center_of_mass() cov = stars.center_of_mass_velocity() @@ -2348,12 +2277,13 @@ def test4(self): com1 = converted_stars.center_of_mass() cov1 = converted_stars.center_of_mass_velocity() - self.assertAlmostRelativeEquals(com1, [0,0,0] | units.AU) - self.assertAlmostRelativeEquals(cov1, [0,0,0] | units.kms) - self.assertAlmostRelativeEquals(converted_stars[0].position, [-0.5,0,0] | units.AU) - self.assertAlmostRelativeEquals(converted_stars[1].position, [0.5,0,0] | units.AU) - self.assertAlmostRelativeEquals(converted_stars[0].velocity, [0,-0.5,0] | units.kms) - self.assertAlmostRelativeEquals(converted_stars[1].velocity, [0,0.5,0] | units.kms) + self.assertAlmostRelativeEquals(com1, [0, 0, 0] | units.AU) + self.assertAlmostRelativeEquals(cov1, [0, 0, 0] | units.kms) + self.assertAlmostRelativeEquals(converted_stars[0].position, [-0.5, 0, 0] | units.AU) + self.assertAlmostRelativeEquals(converted_stars[1].position, [0.5, 0, 0] | units.AU) + self.assertAlmostRelativeEquals(converted_stars[0].velocity, [0, -0.5, 0] | units.kms) + self.assertAlmostRelativeEquals(converted_stars[1].velocity, [0, 0.5, 0] | units.kms) + class TestTransformedParticles(amusetest.TestCase): @@ -2378,7 +2308,7 @@ def backward_transformation(mass): self.assertEqual(stars[0].mass, 10 | units.g) self.assertEqual(converted_stars[0].mass, 20 | units.g) - self.assertEqual(converted_stars.mass, [20,40] | units.g) + self.assertEqual(converted_stars.mass, [20, 40] | units.g) converted_stars[0].mass = 40 | units.g @@ -2387,85 +2317,85 @@ def backward_transformation(mass): def test2(self): stars = datamodel.Particles(2) - stars.mass = [10,20] | units.g - stars.x = [0,1] | units.m - stars.y = [1,0] | units.m + stars.mass = [10, 20] | units.g + stars.x = [0, 1] | units.m + stars.y = [1, 0] | units.m - def forward_transformation(x,y): - return (x+y,x-y) + def forward_transformation(x, y): + return (x+y, x-y) - def backward_transformation(x,y): + def backward_transformation(x, y): return [(x+y)/2, (x-y)/2] converted_stars = datamodel.TransformedParticles( stars, - ["x","y"], + ["x", "y"], forward_transformation, - ["x","y"], + ["x", "y"], backward_transformation ) self.assertEqual(stars[0].mass, 10 | units.g) self.assertEqual(converted_stars[0].mass, 10 | units.g) - self.assertEqual(converted_stars.mass, [10,20] | units.g) - + self.assertEqual(converted_stars.mass, [10, 20] | units.g) + converted_stars[0].mass = 20 | units.g self.assertEqual(stars[0].mass, 20 | units.g) self.assertEqual(converted_stars[0].mass, 20 | units.g) - self.assertEqual(converted_stars.x, [1,1]| units.m) - self.assertEqual(converted_stars.y, [-1,1]| units.m) + self.assertEqual(converted_stars.x, [1, 1] | units.m) + self.assertEqual(converted_stars.y, [-1, 1] | units.m) - converted_stars[0].x=10. | units.m - converted_stars[0].y=20. | units.m + converted_stars[0].x = 10. | units.m + converted_stars[0].y = 20. | units.m - self.assertEqual(converted_stars.x, [10,1]| units.m) - self.assertEqual(converted_stars.y, [20,1]| units.m) + self.assertEqual(converted_stars.x, [10, 1] | units.m) + self.assertEqual(converted_stars.y, [20, 1] | units.m) - self.assertEqual(stars.x, [15,1]| units.m) - self.assertEqual(stars.y, [-5,0]| units.m) + self.assertEqual(stars.x, [15, 1] | units.m) + self.assertEqual(stars.y, [-5, 0] | units.m) def test3(self): stars = datamodel.Particles(2) - stars.mass = [10,20] | units.g - stars.x = [0,1] | units.m - stars.y = [1,0] | units.m + stars.mass = [10, 20] | units.g + stars.x = [0, 1] | units.m + stars.y = [1, 0] | units.m - def forward_transformation(x,y): - return (x+y,x-y) + def forward_transformation(x, y): + return (x+y, x-y) - def backward_transformation(x,y): + def backward_transformation(x, y): return [(x+y)/2, (x-y)/2] converted_stars = datamodel.TransformedParticles( stars, - ["x","y"], + ["x", "y"], forward_transformation, - ["x","y"], + ["x", "y"], backward_transformation ) - p=datamodel.Particle(mass=1.| units.kg) + p = datamodel.Particle(mass=1. | units.kg) converted_stars.add_particle(p) - self.assertEqual(stars.y, [1,0,0] | units.m) - self.assertEqual(stars.mass, [10,20,1000] | units.g) + self.assertEqual(stars.y, [1, 0, 0] | units.m) + self.assertEqual(stars.mass, [10, 20, 1000] | units.g) - p=datamodel.Particle(mass=1.| units.kg,x=10.| units.m, y=20.| units.m) + p = datamodel.Particle(mass=1. | units.kg, x=10. | units.m, y=20. | units.m) converted_stars.add_particle(p) - self.assertEqual(converted_stars.y, [-1,1,0,20] | units.m) - self.assertEqual(stars.y, [1,0,0,-5] | units.m) - self.assertEqual(stars.mass, [10,20,1000,1000] | units.g) + self.assertEqual(converted_stars.y, [-1, 1, 0, 20] | units.m) + self.assertEqual(stars.y, [1, 0, 0, -5] | units.m) + self.assertEqual(stars.mass, [10, 20, 1000, 1000] | units.g) def test4(self): stars = datamodel.Particles(2) stars[0].mass = 1 | units.MSun - stars[0].position = [0,0,0] | units.AU - stars[0].velocity = [0,1,0] | units.kms + stars[0].position = [0, 0, 0] | units.AU + stars[0].velocity = [0, 1, 0] | units.kms stars[1].mass = 1 | units.MSun - stars[1].position = [1,0,0] | units.AU - stars[1].velocity = [0,2,0] | units.kms + stars[1].position = [1, 0, 0] | units.AU + stars[1].velocity = [0, 2, 0] | units.kms com = stars.center_of_mass() cov = stars.center_of_mass_velocity() @@ -2478,26 +2408,26 @@ def test4(self): com1 = converted_stars.center_of_mass() cov1 = converted_stars.center_of_mass_velocity() - self.assertAlmostRelativeEquals(com1, [0,0,0] | units.AU) - self.assertAlmostRelativeEquals(cov1, [0,0,0] | units.kms) - self.assertAlmostRelativeEquals(converted_stars[0].position, [-0.5,0,0] | units.AU) - self.assertAlmostRelativeEquals(converted_stars[1].position, [0.5,0,0] | units.AU) - self.assertAlmostRelativeEquals(converted_stars[0].velocity, [0,-0.5,0] | units.kms) - self.assertAlmostRelativeEquals(converted_stars[1].velocity, [0,0.5,0] | units.kms) - + self.assertAlmostRelativeEquals(com1, [0, 0, 0] | units.AU) + self.assertAlmostRelativeEquals(cov1, [0, 0, 0] | units.kms) + self.assertAlmostRelativeEquals(converted_stars[0].position, [-0.5, 0, 0] | units.AU) + self.assertAlmostRelativeEquals(converted_stars[1].position, [0.5, 0, 0] | units.AU) + self.assertAlmostRelativeEquals(converted_stars[0].velocity, [0, -0.5, 0] | units.kms) + self.assertAlmostRelativeEquals(converted_stars[1].velocity, [0, 0.5, 0] | units.kms) + def test5(self): stars = datamodel.Particles(2) stars[0].mass = 1 | units.MSun - stars[0].position = [1,0,0] | units.AU - stars[0].velocity = [0,2*numpy.pi,0] | units.AU/units.yr + stars[0].position = [1, 0, 0] | units.AU + stars[0].velocity = [0, 2*numpy.pi, 0] | units.AU/units.yr stars[1].mass = 1 | units.MSun - stars[1].position = [0,1,0] | units.AU - stars[1].velocity = [0,0,0] | units.AU/units.yr + stars[1].position = [0, 1, 0] | units.AU + stars[1].velocity = [0, 0, 0] | units.AU/units.yr - angle=0.*numpy.pi - omega=2* numpy.pi| units.rad/units.yr + angle = 0.*numpy.pi + omega = 2 * numpy.pi | units.rad/units.yr converted_stars = datamodel.TransformedParticles.rotate_z( stars, @@ -2505,13 +2435,13 @@ def test5(self): omega ) - self.assertAlmostRelativeEquals(converted_stars[0].position, [1,0,0] | units.AU) - self.assertAlmostRelativeEquals(converted_stars[1].position, [0,1,0] | units.AU) - self.assertAlmostRelativeEquals(converted_stars[0].velocity, [0,0,0] | units.AU/units.yr) - self.assertAlmostRelativeEquals(converted_stars[1].velocity, [2*numpy.pi,0,0] | units.AU/units.yr) + self.assertAlmostRelativeEquals(converted_stars[0].position, [1, 0, 0] | units.AU) + self.assertAlmostRelativeEquals(converted_stars[1].position, [0, 1, 0] | units.AU) + self.assertAlmostRelativeEquals(converted_stars[0].velocity, [0, 0, 0] | units.AU/units.yr) + self.assertAlmostRelativeEquals(converted_stars[1].velocity, [2*numpy.pi, 0, 0] | units.AU/units.yr) - angle=numpy.pi/2 - omega=2* numpy.pi| units.rad/units.yr + angle = numpy.pi/2 + omega = 2 * numpy.pi | units.rad/units.yr converted_stars = datamodel.TransformedParticles.rotate_z( stars, @@ -2519,12 +2449,10 @@ def test5(self): omega ) - self.assertAlmostRelativeEquals(converted_stars[0].position, [0,-1,0] | units.AU) - self.assertAlmostRelativeEquals(converted_stars[1].position, [1,0,0] | units.AU) - self.assertAlmostRelativeEquals(converted_stars[0].velocity, [0,0,0] | units.AU/units.yr) - self.assertAlmostRelativeEquals(converted_stars[1].velocity, [0.,-2*numpy.pi,0] | units.AU/units.yr) - - + self.assertAlmostRelativeEquals(converted_stars[0].position, [0, -1, 0] | units.AU) + self.assertAlmostRelativeEquals(converted_stars[1].position, [1, 0, 0] | units.AU) + self.assertAlmostRelativeEquals(converted_stars[0].velocity, [0, 0, 0] | units.AU/units.yr) + self.assertAlmostRelativeEquals(converted_stars[1].velocity, [0., -2*numpy.pi, 0] | units.AU/units.yr) class TestParticlesWithChildren(amusetest.TestCase): @@ -2540,7 +2468,6 @@ def test1(self): parent.add_child(child1) parent.add_child(child2) - self.assertEqual(child1.parent.key, parent.key) self.assertEqual(child2.parent.key, parent.key) @@ -2553,10 +2480,9 @@ def test2(self): code1 = TestParticlesWithBinding.TestInterface() code2 = TestParticlesWithBinding.TestInterface() - particles = datamodel.Particles(3) particles.mass = [4.0, 3.0, 1.0] | units.kg - #for x in particles: + # for x in particles: # x.grid = numpy.arange(12).reshape(4,3) parent = particles[0] child1 = particles[1] @@ -2585,20 +2511,16 @@ def test2(self): self.assertEqual(parent.mass, 10.0 | units.kg) self.assertEqual(child1.mass, 3.0 | units.kg) - code2.particles.new_channel_to(particles).copy_attribute("mass") self.assertEqual(parent.mass, 10.0 | units.kg) self.assertEqual(child1.mass, 9.0 | units.kg) - - def test3(self): code1 = TestParticlesWithBinding.TestInterface() code2 = TestParticlesWithBinding.TestInterface() - particles = datamodel.Particles(5) particles.mass = [4.0, 3.0, 1.0, 6.0, 5.0] | units.kg parent = particles[0] @@ -2612,7 +2534,6 @@ def test3(self): self.assertEqual(child1.parent, parent) self.assertEqual(child2.parent, parent) - all_except_children = particles.difference(parent.children()) code1.particles.add_particles(all_except_children) code2.particles.add_particles(parent.children()) @@ -2669,9 +2590,11 @@ class Dummy(object): @property def definition(self): return self + @property def handler(self): return self + @property def interface(self): return self._interface @@ -2686,13 +2609,13 @@ def __init__(self): self.definition._interface = self def get_number_of_particles(self): - return self.number_of_particles + return self.number_of_particles - def get_mass(self,index): + def get_mass(self, index): data_to_return = [self.data[i][0] for i in index] return units.kg(data_to_return) - def get_children(self,index): + def get_children(self, index): return self.convert_link([self.data[i][1] for i in index]), self.convert_link([self.data[i][2] for i in index]) def convert_link(self, number): @@ -2700,7 +2623,7 @@ def convert_link(self, number): def new_particle(self, mass): mass = mass.value_in(units.kg) - self.data = [[x,-1,-1] for x in mass] + self.data = [[x, -1, -1] for x in mass] self.number_of_particles = len(self.data) return [i for i in range(len(mass))] @@ -2712,27 +2635,27 @@ def new_particle(self, mass): ) storage = incode_storage.InCodeAttributeStorage( code, - incode_storage.NewParticleMethod(code.new_particle,("mass",)), + incode_storage.NewParticleMethod(code.new_particle, ("mass",)), None, code.get_number_of_particles, [], [ - incode_storage.ParticleGetAttributesMethod(code.get_mass,("mass",)), + incode_storage.ParticleGetAttributesMethod(code.get_mass, ("mass",)), children_getter ], - name_of_the_index = "index" + name_of_the_index="index" ) storage.add_particles_to_store( - numpy.asarray([100,200,300,400], dtype='uint64'), + numpy.asarray([100, 200, 300, 400], dtype='uint64'), ["mass"], [ - units.kg([1,2,3,4]), + units.kg([1, 2, 3, 4]), ] ) code.data[0][1] = 1 code.data[0][2] = 2 - code.particles = datamodel.Particles(storage = storage) + code.particles = datamodel.Particles(storage=storage) x = code.particles print(code.get_children([0])) print(x[0].child1) @@ -2742,7 +2665,6 @@ def new_particle(self, mass): self.assertEqual(x[1].child1, None) self.assertEqual(x[1].child2, None) - code.data[1][1] = 3 code.data[1][2] = 2 @@ -2756,9 +2678,11 @@ class Dummy(object): @property def definition(self): return self + @property def handler(self): return self + @property def interface(self): return self._interface @@ -2773,13 +2697,13 @@ def __init__(self): self.definition.wrapped_object = self def get_number_of_particles(self): - return self.number_of_particles + return self.number_of_particles - def get_mass(self,index): + def get_mass(self, index): data_to_return = [self.data[i][0] for i in index] return units.kg(data_to_return) - def get_children(self,index): + def get_children(self, index): return self.convert_link([self.data[i][1] for i in index]), self.convert_link([self.data[i][2] for i in index]) def convert_link(self, number): @@ -2787,7 +2711,7 @@ def convert_link(self, number): def new_particle(self, mass): mass = mass.value_in(units.kg) - self.data = [[x,-1,-1] for x in mass] + self.data = [[x, -1, -1] for x in mass] self.number_of_particles = len(self.data) return [i for i in range(len(mass))] @@ -2800,22 +2724,21 @@ def new_particle(self, mass): storage = incode_storage.InCodeAttributeStorage( code, - incode_storage.NewParticleMethod(code.new_particle,("mass",)), + incode_storage.NewParticleMethod(code.new_particle, ("mass",)), None, code.get_number_of_particles, [], [ - incode_storage.ParticleGetAttributesMethod(code.get_mass,("mass",)), + incode_storage.ParticleGetAttributesMethod(code.get_mass, ("mass",)), children_getter ], - name_of_the_index = "index" + name_of_the_index="index" ) - - code_particles = datamodel.Particles(storage = storage) + code_particles = datamodel.Particles(storage=storage) code.particles = code_particles - memory_particles = datamodel.Particles(keys = 100 * (1 + numpy.arange(10)) ) + memory_particles = datamodel.Particles(keys=100 * (1 + numpy.arange(10))) memory_particles.mass = range(10) | units.kg code_particles.add_particles(memory_particles) @@ -2848,7 +2771,7 @@ def test8(self): particles = datamodel.Particles(keys=(1,)) - children = datamodel.Particles(keys=(10,11)) + children = datamodel.Particles(keys=(10, 11)) parent = particles[0] child1 = children[0] @@ -2861,21 +2784,19 @@ def test8(self): parent.child2 = child2 copy_of_parent = parent.copy() - self.assertEqual(copy_of_parent.child1.key,10) - self.assertEqual(copy_of_parent.child2.key,11) - self.assertAlmostRelativeEquals(copy_of_parent.child1.mass,1 | units.kg) - self.assertAlmostRelativeEquals(copy_of_parent.child2.mass,2 | units.kg) - + self.assertEqual(copy_of_parent.child1.key, 10) + self.assertEqual(copy_of_parent.child2.key, 11) + self.assertAlmostRelativeEquals(copy_of_parent.child1.mass, 1 | units.kg) + self.assertAlmostRelativeEquals(copy_of_parent.child2.mass, 2 | units.kg) def test9(self): - particles = datamodel.Particles(keys=(1,10,11)) + particles = datamodel.Particles(keys=(1, 10, 11)) parent = particles[0] child1 = particles[1] child2 = particles[2] - child1.mass = 1 | units.kg child2.mass = 2 | units.kg @@ -2883,10 +2804,11 @@ def test9(self): parent.child2 = child2 copy_of_parent = parent.copy() - self.assertEqual(copy_of_parent.child1.key,10) - self.assertEqual(copy_of_parent.child2.key,11) - self.assertAlmostRelativeEquals(copy_of_parent.child1.mass,1 | units.kg) - self.assertAlmostRelativeEquals(copy_of_parent.child2.mass,2 | units.kg) + self.assertEqual(copy_of_parent.child1.key, 10) + self.assertEqual(copy_of_parent.child2.key, 11) + self.assertAlmostRelativeEquals(copy_of_parent.child1.mass, 1 | units.kg) + self.assertAlmostRelativeEquals(copy_of_parent.child2.mass, 2 | units.kg) + class TestParticlesSupersetComplex(amusetest.TestCase): @@ -2903,17 +2825,17 @@ def test1(self): for x in [particle1, set2, particle2]: superset = datamodel.ParticlesSuperset([superset, x.as_set()]) self.assertTrue(isinstance(superset, datamodel.ParticlesSuperset)) - self.assertEqual(len(superset),6) - self.assertEqual(superset.x, ([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]|units.m)) - self.assertEqual(superset[1].x, 2.0 |units.m) - self.assertEqual(superset[0:2][1].x, 2.0 |units.m) + self.assertEqual(len(superset), 6) + self.assertEqual(superset.x, ([1.0, 2.0, 3.0, 4.0, 5.0, 6.0] | units.m)) + self.assertEqual(superset[1].x, 2.0 | units.m) + self.assertEqual(superset[0:2][1].x, 2.0 | units.m) # Check whether it returns the right value for the right key when the key order is 'random' indices = superset.get_all_indices_in_store() - shuffled_indices = indices[numpy.asarray([5,1,3,0,2,4], dtype='int32')] + shuffled_indices = indices[numpy.asarray([5, 1, 3, 0, 2, 4], dtype='int32')] print(shuffled_indices) indices = numpy.asarray(shuffled_indices) - values = superset.get_values_in_store(indices,['x'])[0] - self.assertEqual(values, [6.0, 2.0, 4.0, 1.0, 3.0, 5.0]|units.m) + values = superset.get_values_in_store(indices, ['x'])[0] + self.assertEqual(values, [6.0, 2.0, 4.0, 1.0, 3.0, 5.0] | units.m) def test2(self): print("Test2: setting attributes of a particle superset.") @@ -2925,33 +2847,32 @@ def test2(self): for x in [particle1, set2, particle2]: superset = datamodel.ParticlesSuperset([superset, x.as_set()]) self.assertTrue(isinstance(superset, datamodel.ParticlesSuperset)) - self.assertEqual(len(superset),6) + self.assertEqual(len(superset), 6) superset.x = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] | units.m - self.assertEqual(superset.x, ([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]|units.m)) + self.assertEqual(superset.x, ([1.0, 2.0, 3.0, 4.0, 5.0, 6.0] | units.m)) superset.y = 9.0 | units.m - self.assertEqual(superset.y, ([9.0, 9.0, 9.0, 9.0, 9.0, 9.0]|units.m)) + self.assertEqual(superset.y, ([9.0, 9.0, 9.0, 9.0, 9.0, 9.0] | units.m)) superset.z = [-1.0, 1.0] | units.m - self.assertEqual(superset.z, ([-1.0, 1.0, -1.0, 1.0, -1.0, 1.0]|units.m)) + self.assertEqual(superset.z, ([-1.0, 1.0, -1.0, 1.0, -1.0, 1.0] | units.m)) # Check whether it sets the value of the right particle when the key order is 'random' indices = superset.get_all_indices_in_store() - shuffled_indices = indices[numpy.asarray([5,1,3,0,2,4], dtype='int32')] - - sorted_values = superset.get_values_in_store(shuffled_indices,['x'])[0] - superset.set_values_in_store(shuffled_indices,['zz'],[sorted_values]) - self.assertEqual(sorted_values, [6.0, 2.0, 4.0, 1.0, 3.0, 5.0]|units.m) - self.assertEqual(firstset.zz, [1.0, 2.0]|units.m) - self.assertEqual(set2.zz, [4.0, 5.0]|units.m) + shuffled_indices = indices[numpy.asarray([5, 1, 3, 0, 2, 4], dtype='int32')] + sorted_values = superset.get_values_in_store(shuffled_indices, ['x'])[0] + superset.set_values_in_store(shuffled_indices, ['zz'], [sorted_values]) + self.assertEqual(sorted_values, [6.0, 2.0, 4.0, 1.0, 3.0, 5.0] | units.m) + self.assertEqual(firstset.zz, [1.0, 2.0] | units.m) + self.assertEqual(set2.zz, [4.0, 5.0] | units.m) def test3(self): set1 = datamodel.Particles(2) set2 = datamodel.Particles(3) - set1.x = [1.0 , 2.0] | units.m - set1.y = [3.0 , 4.0] | units.m - set2.x = [5.0 , 6.0, 7.0] | units.m - set2.y = [1.0 , 2.0, 3.0] | units.m - set1.add_calculated_attribute("xtimesy", lambda x, y : x * y) - set2.add_calculated_attribute("xtimesy", lambda x, y : x * y) + set1.x = [1.0, 2.0] | units.m + set1.y = [3.0, 4.0] | units.m + set2.x = [5.0, 6.0, 7.0] | units.m + set2.y = [1.0, 2.0, 3.0] | units.m + set1.add_calculated_attribute("xtimesy", lambda x, y: x * y) + set2.add_calculated_attribute("xtimesy", lambda x, y: x * y) superset = datamodel.ParticlesSuperset([set1, set2]) self.assertEqual(len(superset), 5) self.assertEqual(superset.x, ([1.0, 2.0, 5.0, 6.0, 7.0] | units.m)) @@ -2960,12 +2881,12 @@ def test3(self): def test4(self): set1 = datamodel.Particles(2) set2 = datamodel.Particles(3) - set1.x = [1.0 , 2.0] | units.m - set1.y = [3.0 , 4.0] | units.m - set2.x = [5.0 , 6.0, 7.0] | units.m - set2.y = [1.0 , 2.0, 3.0] | units.m - set1.add_function_attribute("xtimesypluso", lambda p, o : p.x * p.y - o, lambda ap, p, o : p.x * p.y - o) - set2.add_function_attribute("xtimesypluso", lambda p, o : p.x * p.y + o, lambda ap, p, o : p.x * p.y - o) + set1.x = [1.0, 2.0] | units.m + set1.y = [3.0, 4.0] | units.m + set2.x = [5.0, 6.0, 7.0] | units.m + set2.y = [1.0, 2.0, 3.0] | units.m + set1.add_function_attribute("xtimesypluso", lambda p, o: p.x * p.y - o, lambda ap, p, o: p.x * p.y - o) + set2.add_function_attribute("xtimesypluso", lambda p, o: p.x * p.y + o, lambda ap, p, o: p.x * p.y - o) superset = datamodel.ParticlesSuperset([set1, set2]) self.assertEqual(len(superset), 5) self.assertEqual(superset.x, ([1.0, 2.0, 5.0, 6.0, 7.0] | units.m)) @@ -2977,12 +2898,12 @@ def test4(self): def test5(self): set1 = datamodel.Particles(2) set2 = datamodel.Particles() - set1.x = [1.0 , 2.0] | units.m - set1.y = [3.0 , 4.0] | units.m + set1.x = [1.0, 2.0] | units.m + set1.y = [3.0, 4.0] | units.m set2.x = [] | units.m set2.y = [] | units.m - set1.add_function_attribute("xtimesypluso", lambda p, o : p.x * p.y - o) - set2.add_function_attribute("xtimesypluso", lambda p, o : p.x * p.y + o) + set1.add_function_attribute("xtimesypluso", lambda p, o: p.x * p.y - o) + set2.add_function_attribute("xtimesypluso", lambda p, o: p.x * p.y + o) superset = datamodel.ParticlesSuperset([set2, set1]) self.assertEqual(len(superset), 2) self.assertEqual(superset.x, ([1.0, 2.0] | units.m)) @@ -2997,12 +2918,12 @@ def test5(self): def test6(self): set1 = datamodel.Particles(2) set2 = datamodel.Particles() - set1.x = [1.0 , 2.0] | units.m - set1.y = [3.0 , 4.0] | units.m + set1.x = [1.0, 2.0] | units.m + set1.y = [3.0, 4.0] | units.m set2.x = [] | units.m set2.y = [] | units.m - set1.add_calculated_attribute("xtimesy", lambda x, y : x * y) - set2.add_calculated_attribute("xtimesy", lambda x, y : x * y) + set1.add_calculated_attribute("xtimesy", lambda x, y: x * y) + set2.add_calculated_attribute("xtimesy", lambda x, y: x * y) superset = datamodel.ParticlesSuperset([set1, set2]) self.assertEqual(len(superset), 2) self.assertEqual(superset.x, ([1.0, 2.0] | units.m)) @@ -3013,16 +2934,16 @@ def test6(self): self.assertEqual(superset.xtimesy, ([3.0, 8.0] | units.m ** 2)) def test7(self): - def xtimesy1(x,y): + def xtimesy1(x, y): raise Exception("error querying function on empty set") set1 = datamodel.Particles(2) set2 = datamodel.Particles() - set1.x = [1.0 , 2.0] | units.m - set1.y = [3.0 , 4.0] | units.m + set1.x = [1.0, 2.0] | units.m + set1.y = [3.0, 4.0] | units.m set2.x = [] | units.m set2.y = [] | units.m - set1.add_function_attribute("xtimesy", lambda p : p.x * p.y) + set1.add_function_attribute("xtimesy", lambda p: p.x * p.y) set2.add_function_attribute("xtimesy", xtimesy1) superset = datamodel.ParticlesSuperset([set1, set2]) self.assertEqual(len(superset), 2) @@ -3036,19 +2957,18 @@ def xtimesy1(x,y): def test8(self): set1 = datamodel.Particles(2) set2 = datamodel.Particles(3) - set1.x = [1.0 , 2.0] | units.m - set1.y = [3.0 , 4.0] | units.m - set2.x = [5.0 , 6.0, 7.0] | units.m - set2.y = [1.0 , 2.0, 3.0] | units.m - set1.add_function_attribute("xtimesypluso", lambda p, o : p.x * p.y - o, lambda all, p, o : p.x * p.x - o) - set2.add_function_attribute("xtimesypluso", lambda p, o : p.x * p.y + o, lambda all, p, o : p.x * p.x - o) + set1.x = [1.0, 2.0] | units.m + set1.y = [3.0, 4.0] | units.m + set2.x = [5.0, 6.0, 7.0] | units.m + set2.y = [1.0, 2.0, 3.0] | units.m + set1.add_function_attribute("xtimesypluso", lambda p, o: p.x * p.y - o, lambda all, p, o: p.x * p.x - o) + set2.add_function_attribute("xtimesypluso", lambda p, o: p.x * p.y + o, lambda all, p, o: p.x * p.x - o) superset = datamodel.ParticlesSuperset([set1, set2]) self.assertEqual(len(superset), 5) self.assertEqual(superset.x, ([1.0, 2.0, 5.0, 6.0, 7.0] | units.m)) self.assertEqual(superset[1].xtimesypluso(0.0 | units.m ** 2), (4.0 | units.m ** 2)) self.assertEqual(list(superset)[1].xtimesypluso(0.0 | units.m ** 2), (4.0 | units.m ** 2)) - def test9(self): particles1 = datamodel.Particles(2) @@ -3073,15 +2993,15 @@ def test10(self): superset = datamodel.ParticlesSuperset([particles1, particles2]) self.assertTrue(hasattr(superset, 'u1')) - self.assertEqual(superset.u1 , [10,10,20,20]) + self.assertEqual(superset.u1, [10, 10, 20, 20]) self.assertFalse(hasattr(superset, 'u2')) particles1.u2 = 30 self.assertFalse(hasattr(superset, 'u2')) particles2.u2 = 20 self.assertTrue(hasattr(superset, 'u2')) - self.assertEqual(superset.u2 , [30,30,20,20]) + self.assertEqual(superset.u2, [30, 30, 20, 20]) superset.u2 = 15 - self.assertEqual(superset.u2 , [15,15,15,15]) + self.assertEqual(superset.u2, [15, 15, 15, 15]) def test11(self): print("ParticlesSuperset from one set, of one particle") @@ -3096,12 +3016,12 @@ def test11(self): particles1.y = 3 | units.m self.assertTrue(hasattr(superset, 'y')) - self.assertEqual(superset.y , [3] | units.m) + self.assertEqual(superset.y, [3] | units.m) self.assertEqual(len(superset.y), 1) particles1.x = [1.0] | units.m particles1.y = [3.0] | units.m - particles1.add_function_attribute("xtimesypluso", lambda p, o : p.x * p.y + o, lambda ap, p, o : p.x * p.y + o) + particles1.add_function_attribute("xtimesypluso", lambda p, o: p.x * p.y + o, lambda ap, p, o: p.x * p.y + o) superset = datamodel.ParticlesSuperset([particles1]) self.assertEqual(len(superset), 1) self.assertEqual(superset.x, [1.0] | units.m) @@ -3114,7 +3034,7 @@ def test12(self): print("ParticlesSuperset - query") set1 = datamodel.Particles(4) set1.x = [-1.0, 1.0, 2.0, 3.0] | units.m - set1.add_function_attribute("greater_than", lambda p, o : p[p.x > o], lambda ap, p, o : p if p.x > o else None) + set1.add_function_attribute("greater_than", lambda p, o: p[p.x > o], lambda ap, p, o: p if p.x > o else None) superset = datamodel.ParticlesSuperset([set1]) self.assertEqual(len(set1.greater_than(-2.0 | units.m)), 4) @@ -3139,7 +3059,7 @@ def test12(self): set2 = datamodel.Particles(1) set2.x = [4.0] | units.m - set2.add_function_attribute("greater_than", lambda p, o : p[p.x > o], lambda ap, p, o : p if p.x > o else None) + set2.add_function_attribute("greater_than", lambda p, o: p[p.x > o], lambda ap, p, o: p if p.x > o else None) superset = datamodel.ParticlesSuperset([set1, set2]) self.assertEqual(len(superset.greater_than(-2.0 | units.m)), 5) self.assertTrue(isinstance(superset.greater_than(-2.0 | units.m), datamodel.ParticlesSuperset)) @@ -3147,14 +3067,13 @@ def test12(self): self.assertTrue(isinstance(superset.greater_than(3.0 | units.m), datamodel.ParticlesSuperset)) self.assertEqual(superset.greater_than(2.0 | units.m).x, [3.0, 4.0] | units.m) - superset.add_function_attribute("greater_than", lambda p, o : p[p.x > o], lambda ap, p, o : p if p.x > o else None) + superset.add_function_attribute("greater_than", lambda p, o: p[p.x > o], lambda ap, p, o: p if p.x > o else None) self.assertEqual(len(superset.greater_than(-2.0 | units.m)), 5) self.assertTrue(isinstance(superset.greater_than(-2.0 | units.m), datamodel.ParticlesSubset)) self.assertEqual(len(superset.greater_than(3.0 | units.m)), 1) self.assertTrue(isinstance(superset.greater_than(3.0 | units.m), datamodel.ParticlesSubset)) self.assertEqual(superset.greater_than(2.0 | units.m).x, [3.0, 4.0] | units.m) - def test13(self): set1 = datamodel.Particles(2) set1.x = [[1.0, 2.0], [3.0, 4.0]] | units.m @@ -3163,12 +3082,13 @@ def test13(self): superset = datamodel.ParticlesSuperset([set1, set2]) print(superset.x) - self.assertEqual(superset.x.shape, (4,2) ) + self.assertEqual(superset.x.shape, (4, 2)) print(superset.x[2]) print(superset[2].x) - self.assertEqual(superset.x[2], [5.0, 6.0] | units.m ) - self.assertEqual(superset[2].x, [5.0, 6.0] | units.m ) + self.assertEqual(superset.x[2], [5.0, 6.0] | units.m) + self.assertEqual(superset[2].x, [5.0, 6.0] | units.m) + class TestSliceParticles(amusetest.TestCase): @@ -3177,16 +3097,16 @@ def test1(self): number_of_particles = 10 original_set = datamodel.Particles(number_of_particles) self.assertTrue(isinstance(original_set, datamodel.Particles)) - self.assertEqual(len(original_set),number_of_particles) + self.assertEqual(len(original_set), number_of_particles) print("Defining all kind of slices of the particle set...") subset1 = original_set[:2] # contains first two particles subset2 = original_set[2:] # contains the rest of the particles odd = original_set[1::2] # contains all particles with odd indices even = original_set[::2] # contains all particles with even indices - reverse = original_set[::-1]# contains all particles in reverse order + reverse = original_set[::-1] # contains all particles in reverse order all = original_set[:] # contains all particles one = original_set[3] # contains one particle (Particle) - another = original_set[5:6] # contains one particle (ParticlesSubset) + another = original_set[5:6] # contains one particle (ParticlesSubset) empty = original_set[2:2] # contains no particle print("Checking their type (slicing returns a subset, indexing returns a particle)... ", end=' ') self.assertTrue(isinstance(subset1, datamodel.ParticlesSubset)) @@ -3211,6 +3131,7 @@ def test1(self): self.assertEqual(len(empty), 0) print("ok!") + class TestAddParticles(amusetest.TestCase): def test1(self): @@ -3224,16 +3145,16 @@ def test1(self): new_set = particleset + particle self.assertTrue(isinstance(new_set, datamodel.ParticlesSubset)) - self.assertEqual(len(new_set),len(particleset)+1) + self.assertEqual(len(new_set), len(particleset)+1) print(new_set.x) print(particleset.x) print(particle.x) - self.assertEqual(new_set.x, ([1.0, 2.0, 3.0]|units.m)) + self.assertEqual(new_set.x, ([1.0, 2.0, 3.0] | units.m)) particleset += particle self.assertTrue(isinstance(particleset, datamodel.ParticlesSubset)) - self.assertEqual(len(particleset),3) - self.assertEqual(particleset.x, ([1.0, 2.0, 3.0]|units.m)) + self.assertEqual(len(particleset), 3) + self.assertEqual(particleset.x, ([1.0, 2.0, 3.0] | units.m)) def test2(self): print("Test2: create a particle subset by adding a set to a set.") @@ -3246,13 +3167,13 @@ def test2(self): new_set = set1 + set2 self.assertTrue(isinstance(new_set, datamodel.ParticlesSubset)) - self.assertEqual(len(new_set),len(set1)+len(set2)) - self.assertEqual(new_set.x, ([1.0, 2.0, 3.0, 4.0]|units.m)) + self.assertEqual(len(new_set), len(set1)+len(set2)) + self.assertEqual(new_set.x, ([1.0, 2.0, 3.0, 4.0] | units.m)) set1 += set2 self.assertTrue(isinstance(set1, datamodel.ParticlesSubset)) - self.assertEqual(len(set1),4) - self.assertEqual(set1.x, ([1.0, 2.0, 3.0, 4.0]|units.m)) + self.assertEqual(len(set1), 4) + self.assertEqual(set1.x, ([1.0, 2.0, 3.0, 4.0] | units.m)) def test3(self): print("Test3: create a particle superset by adding a particle to a set.") @@ -3263,15 +3184,15 @@ def test3(self): superset = datamodel.ParticlesSuperset([particleset, particle.as_set()]) self.assertTrue(isinstance(superset, datamodel.ParticlesSuperset)) - self.assertEqual(len(superset),len(particleset)+1) - self.assertEqual(superset.x, ([1.0, 2.0, 3.0]|units.m)) + self.assertEqual(len(superset), len(particleset)+1) + self.assertEqual(superset.x, ([1.0, 2.0, 3.0] | units.m)) particleset2 = datamodel.Particles(2) particleset2.x = [3.0, 4.0] | units.m superset = datamodel.ParticlesSuperset([particleset, particleset2]) self.assertTrue(isinstance(superset, datamodel.ParticlesSuperset)) - self.assertEqual(len(superset),len(particleset)+len(particleset2)) - self.assertEqual(superset.x, ([1.0, 2.0, 3.0, 4.0]|units.m)) + self.assertEqual(len(superset), len(particleset)+len(particleset2)) + self.assertEqual(superset.x, ([1.0, 2.0, 3.0, 4.0] | units.m)) def test4(self): print("Test4: check if the particle is already part of the set.") @@ -3279,12 +3200,12 @@ def test4(self): particle = datamodel.Particle() particleset = datamodel.ParticlesSuperset([particleset, particle.as_set()]) self.assertRaises(AmuseException, datamodel.ParticlesSuperset, [particleset, particle.as_set()], - expected_message = "Unable to add a particle, because it was already part of this set.") - self.assertEqual(len(particleset),3) + expected_message="Unable to add a particle, because it was already part of this set.") + self.assertEqual(len(particleset), 3) other_particleset = datamodel.Particles(2) other_particleset = datamodel.ParticlesSuperset([other_particleset, particle.as_set()]) self.assertRaises(AmuseException, datamodel.ParticlesSuperset, [particleset, other_particleset], - expected_message = "Unable to add a particle, because it was already part of this set.") + expected_message="Unable to add a particle, because it was already part of this set.") def test5(self): print("Test5: recursive addition, create a new superset from supersets.") @@ -3298,7 +3219,7 @@ def test5(self): for x in [particle, set3, superset2]: supersuperset = datamodel.ParticlesSuperset([superset1, x.as_set()]) self.assertTrue(isinstance(supersuperset, datamodel.ParticlesSuperset)) - self.assertEqual(len(supersuperset),len(superset1)+len(x.as_set())) + self.assertEqual(len(supersuperset), len(superset1)+len(x.as_set())) supersuperset.mass = 1 | units.kg self.assertEqual(x.mass, 1 | units.kg) @@ -3308,10 +3229,10 @@ def test6(self): set2 = datamodel.Particles(2) particle = set2[0] self.assertRaises(AmuseException, lambda: set1 + set2, - expected_message = "Can't create new subset from particles belonging to " + expected_message="Can't create new subset from particles belonging to " "separate particle sets. Try creating a superset instead.") self.assertRaises(AmuseException, lambda: set1 + particle, - expected_message = "Can't create new subset from particles belonging to " + expected_message="Can't create new subset from particles belonging to " "separate particle sets. Try creating a superset instead.") def test7(self): @@ -3325,10 +3246,11 @@ def test7(self): self.assertTrue(isinstance(particleset, datamodel.ParticlesSubset)) new_particleset = particle1 + particle2 self.assertTrue(isinstance(new_particleset, datamodel.ParticlesSubset)) - self.assertEqual(len(new_particleset),2) + self.assertEqual(len(new_particleset), 2) new_particleset = particle1 + particleset self.assertTrue(isinstance(new_particleset, datamodel.ParticlesSubset)) - self.assertEqual(len(new_particleset),3) + self.assertEqual(len(new_particleset), 3) + class TestSubtractParticles(amusetest.TestCase): @@ -3341,13 +3263,13 @@ def test1(self): new_particleset = particleset - particle self.assertTrue(isinstance(new_particleset, datamodel.ParticlesSubset)) - self.assertEqual(len(new_particleset),len(particleset)-1) - self.assertEqual(new_particleset.x, ([1.0, 2.0, 3.0]|units.m)) + self.assertEqual(len(new_particleset), len(particleset)-1) + self.assertEqual(new_particleset.x, ([1.0, 2.0, 3.0] | units.m)) particleset -= particle self.assertTrue(isinstance(particleset, datamodel.ParticlesSubset)) - self.assertEqual(len(particleset),3) - self.assertEqual(particleset.x, ([1.0, 2.0, 3.0]|units.m)) + self.assertEqual(len(particleset), 3) + self.assertEqual(particleset.x, ([1.0, 2.0, 3.0] | units.m)) def test2(self): print("Test2: create a particle subset by removing a set from a set.") @@ -3359,21 +3281,20 @@ def test2(self): new_set = set1 - set2 self.assertTrue(isinstance(new_set, datamodel.ParticlesSubset)) - self.assertEqual(len(new_set),len(set1)-len(set2)) - self.assertEqual(new_set.x, ([1.0, 2.0, 3.0, 4.0]|units.m)) + self.assertEqual(len(new_set), len(set1)-len(set2)) + self.assertEqual(new_set.x, ([1.0, 2.0, 3.0, 4.0] | units.m)) set1 -= set2 self.assertTrue(isinstance(set1, datamodel.ParticlesSubset)) - self.assertEqual(len(set1),4) - self.assertEqual(set1.x, ([1.0, 2.0, 3.0, 4.0]|units.m)) - + self.assertEqual(len(set1), 4) + self.assertEqual(set1.x, ([1.0, 2.0, 3.0, 4.0] | units.m)) def test3(self): print("Test3: check if the particle is actually part of the set.") particleset = datamodel.Particles(2) particle = datamodel.Particle() self.assertRaises(AmuseException, lambda: particleset - particle, - expected_message = "Unable to subtract a particle, because it is not part of this set.") + expected_message="Unable to subtract a particle, because it is not part of this set.") def test4(self): print("Test4: recursive subtraction, remove particles until the set is empty.") @@ -3387,10 +3308,10 @@ def test5(self): print("Test5: check if it's possible to subtract particle(s) from a particle.") particle = datamodel.Particle() self.assertRaises(AmuseException, lambda: particle - particle, - expected_message = "Cannot subtract particle(s) from a particle.") + expected_message="Cannot subtract particle(s) from a particle.") particle2 = datamodel.Particle() self.assertRaises(AmuseException, lambda: particle - particle2, - expected_message = "Cannot subtract particle(s) from a particle.") + expected_message="Cannot subtract particle(s) from a particle.") class TestIterateOverParticles(amusetest.TestCase): @@ -3403,7 +3324,6 @@ def iterate_over_particles(self, particles): for x in particles: x.key - def test1(self): self.total_number_of_points = 10000 @@ -3450,7 +3370,7 @@ def __init__(self): particles = datamodel.Particles(self.total_number_of_points) particles.radius = 2.0 | nbody_system.length t0 = time.time() - #self.iterate_over_array(particles) + # self.iterate_over_array(particles) for key in particles.get_all_keys_in_store(): key t1 = time.time() @@ -3467,6 +3387,7 @@ def __init__(self): self.assertTrue((dt1 / dt0) < 1000) + class TestParticlesIndexing(amusetest.TestCase): def test1(self): @@ -3475,28 +3396,28 @@ def test1(self): self.assertAlmostRelativeEquals(particles.mass, numpy.arange(10) | units.kg) self.assertAlmostRelativeEquals(particles[5].mass, 5 | units.kg) - self.assertAlmostRelativeEquals(particles[[1,3,2,6]].mass, [1,3,2,6] | units.kg) - self.assertAlmostRelativeEquals(particles[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass, [0,2,4,6,8] | units.kg) + self.assertAlmostRelativeEquals(particles[[1, 3, 2, 6]].mass, [1, 3, 2, 6] | units.kg) + self.assertAlmostRelativeEquals(particles[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass, [0, 2, 4, 6, 8] | units.kg) def test2(self): particles = datamodel.Particles(10) particles.mass = numpy.arange(10) | units.kg - self.assertAlmostRelativeEquals(particles[5:].mass, [5,6,7,8,9] | units.kg) - self.assertAlmostRelativeEquals(particles[1:3].mass, [1,2] | units.kg) - self.assertAlmostRelativeEquals(particles[:5].mass, [0,1,2,3,4] | units.kg) + self.assertAlmostRelativeEquals(particles[5:].mass, [5, 6, 7, 8, 9] | units.kg) + self.assertAlmostRelativeEquals(particles[1:3].mass, [1, 2] | units.kg) + self.assertAlmostRelativeEquals(particles[:5].mass, [0, 1, 2, 3, 4] | units.kg) def test3(self): particles = datamodel.Particles(10) particles.mass = numpy.arange(10) | units.kg - self.assertAlmostRelativeEquals(particles[5:][:2].mass, [5,6] | units.kg) + self.assertAlmostRelativeEquals(particles[5:][:2].mass, [5, 6] | units.kg) self.assertAlmostRelativeEquals(particles[1:3][:1].mass, 1 | units.kg) - self.assertAlmostRelativeEquals(particles[:5][2:].mass, [2,3,4] | units.kg) - self.assertAlmostRelativeEquals(particles[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass, [0,2] | units.kg) + self.assertAlmostRelativeEquals(particles[:5][2:].mass, [2, 3, 4] | units.kg) + self.assertAlmostRelativeEquals(particles[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass, [0, 2] | units.kg) def test4(self): - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) particles = datamodel.Particles(10) particles.mass = numpy.arange(10) | units.kg @@ -3508,11 +3429,11 @@ def test4(self): self.assertAlmostRelativeEquals(converted.mass, numpy.arange(10) * 0.1 | nbody_system.mass) self.assertAlmostRelativeEquals(converted[5].mass, 0.5 | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[[1,3,2,6]].mass, [0.1,0.3,0.2,0.6] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass, [0,.2,.4,.6,.8] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[[1, 3, 2, 6]].mass, [0.1, 0.3, 0.2, 0.6] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass, [0, .2, .4, .6, .8] | nbody_system.mass) def test5(self): - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) particles = datamodel.Particles(10) particles.mass = numpy.arange(10) | units.kg @@ -3521,13 +3442,13 @@ def test5(self): converter.as_converter_from_generic_to_si() ) - self.assertAlmostRelativeEquals(converted.mass, numpy.arange(10) * 0.1| nbody_system.mass) - self.assertAlmostRelativeEquals(converted[5:].mass, [0.5,0.6,0.7,0.8,0.9] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[1:3].mass, [0.1,0.2] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[:5].mass, [0,0.1,0.2,0.3,0.4] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted.mass, numpy.arange(10) * 0.1 | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[5:].mass, [0.5, 0.6, 0.7, 0.8, 0.9] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[1:3].mass, [0.1, 0.2] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[:5].mass, [0, 0.1, 0.2, 0.3, 0.4] | nbody_system.mass) def test6(self): - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) particles = datamodel.Particles(10) particles.mass = numpy.arange(10) | units.kg @@ -3535,10 +3456,10 @@ def test6(self): particles, converter.as_converter_from_generic_to_si() ) - self.assertAlmostRelativeEquals(converted[5:][:2].mass, [0.5,0.6] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[5:][:2].mass, [0.5, 0.6] | nbody_system.mass) self.assertAlmostRelativeEquals(converted[1:3][:1].mass, 0.1 | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[:5][2:].mass, [0.2,0.3,0.4] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass, [0,0.2] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[:5][2:].mass, [0.2, 0.3, 0.4] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass, [0, 0.2] | nbody_system.mass) def test7(self): @@ -3550,9 +3471,8 @@ def test7(self): self.assertAlmostRelativeEquals(particles.mass, numpy.arange(10) | units.kg) self.assertAlmostRelativeEquals(particles[5].mass, 5 | units.kg) - self.assertAlmostRelativeEquals(particles[[1,3,2,6]].mass, [1,3,2,6] | units.kg) - self.assertAlmostRelativeEquals(particles[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass, [0,2,4,6,8] | units.kg) - + self.assertAlmostRelativeEquals(particles[[1, 3, 2, 6]].mass, [1, 3, 2, 6] | units.kg) + self.assertAlmostRelativeEquals(particles[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass, [0, 2, 4, 6, 8] | units.kg) def test8(self): @@ -3562,9 +3482,9 @@ def test8(self): set2.mass = numpy.arange(5) + 5 | units.kg particles = datamodel.ParticlesSuperset([set1, set2]) - self.assertAlmostRelativeEquals(particles[5:].mass, [5,6,7,8,9] | units.kg) - self.assertAlmostRelativeEquals(particles[1:3].mass, [1,2] | units.kg) - self.assertAlmostRelativeEquals(particles[:5].mass, [0,1,2,3,4] | units.kg) + self.assertAlmostRelativeEquals(particles[5:].mass, [5, 6, 7, 8, 9] | units.kg) + self.assertAlmostRelativeEquals(particles[1:3].mass, [1, 2] | units.kg) + self.assertAlmostRelativeEquals(particles[:5].mass, [0, 1, 2, 3, 4] | units.kg) def test9(self): set1 = datamodel.Particles(5) @@ -3573,15 +3493,14 @@ def test9(self): set2.mass = numpy.arange(5) + 5 | units.kg particles = datamodel.ParticlesSuperset([set1, set2]) - self.assertAlmostRelativeEquals(particles[5:][0].mass, 5 | units.kg) - self.assertAlmostRelativeEquals(particles[5:][:2].mass, [5,6] | units.kg) + self.assertAlmostRelativeEquals(particles[5:][:2].mass, [5, 6] | units.kg) self.assertAlmostRelativeEquals(particles[1:3][:1].mass, 1 | units.kg) - self.assertAlmostRelativeEquals(particles[:5][2:].mass, [2,3,4] | units.kg) - self.assertAlmostRelativeEquals(particles[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass, [0,2] | units.kg) + self.assertAlmostRelativeEquals(particles[:5][2:].mass, [2, 3, 4] | units.kg) + self.assertAlmostRelativeEquals(particles[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass, [0, 2] | units.kg) def test10(self): - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) set1 = datamodel.Particles(5) set1.mass = numpy.arange(5) | units.kg @@ -3596,11 +3515,11 @@ def test10(self): self.assertAlmostRelativeEquals(converted.mass, numpy.arange(10) * 0.1 | nbody_system.mass) self.assertAlmostRelativeEquals(converted[5].mass, 0.5 | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[[1,2,3]].mass, [0.1,0.2,0.3] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass, [0,.2,.4,.6,.8] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[[1, 2, 3]].mass, [0.1, 0.2, 0.3] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass, [0, .2, .4, .6, .8] | nbody_system.mass) def test11(self): - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) set1 = datamodel.Particles(5) set1.mass = numpy.arange(5) | units.kg @@ -3611,13 +3530,12 @@ def test11(self): particles, converter.as_converter_from_generic_to_si() ) - self.assertAlmostRelativeEquals(converted[5:][:2].mass, [0.5,0.6] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[5:][:2].mass, [0.5, 0.6] | nbody_system.mass) self.assertAlmostRelativeEquals(converted[1:3][:1].mass, 0.1 | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[:5][2:].mass, [0.2,0.3,0.4] | nbody_system.mass) - + self.assertAlmostRelativeEquals(converted[:5][2:].mass, [0.2, 0.3, 0.4] | nbody_system.mass) def test12(self): - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) particles = datamodel.Particles(10) particles.mass = numpy.arange(10) | units.kg @@ -3625,10 +3543,10 @@ def test12(self): particles, converter.as_converter_from_generic_to_si() ) - self.assertAlmostRelativeEquals(converted[5:][:2].mass, [0.5,0.6] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[5:][:2].mass, [0.5, 0.6] | nbody_system.mass) self.assertAlmostRelativeEquals(converted[1:3][:1].mass, 0.1 | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[:5][2:].mass, [0.2,0.3,0.4] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass, [0,0.2] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[:5][2:].mass, [0.2, 0.3, 0.4] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass, [0, 0.2] | nbody_system.mass) class TestParticlesIndexingWithBinding(amusetest.TestCase): @@ -3645,13 +3563,13 @@ def get_mass(self, id): for x in id: masses.append(self.masses[x-self.offset]) errors.append(0) - return ( masses, errors, ) + return (masses, errors, ) def set_mass(self, id, mass): - for i,m in zip(id,mass): + for i, m in zip(id, mass): self.masses[i-self.offset] = m - return ( [0] * len(id),) + return ([0] * len(id),) def new_particle(self, mass): ids = [] @@ -3659,7 +3577,7 @@ def new_particle(self, mass): for x in mass: id = len(self.masses) - self.masses[len(self.masses)] = x + self.masses[len(self.masses)] = x ids.append(id + self.offset) errors.append(0) return (ids, errors) @@ -3679,61 +3597,60 @@ def get_number_of_particles(self): class TestInterface(InCodeComponentImplementation): - def __init__(self, offset = 2): + def __init__(self, offset=2): InCodeComponentImplementation.__init__(self, TestParticlesIndexingWithBinding.TestLegacyCode(offset=offset)) def define_methods(self, handler): - handler.add_method('get_mass',(handler.NO_UNIT,), (units.g, handler.ERROR_CODE)) - handler.add_method('set_mass',(handler.NO_UNIT, units.g,), (handler.ERROR_CODE,)) - handler.add_method('new_particle',(units.g,), (handler.INDEX, handler.ERROR_CODE)) - handler.add_method('delete_particle',(handler.NO_UNIT,), (handler.ERROR_CODE,)) - handler.add_method('get_number_of_particles',(), (handler.NO_UNIT, handler.ERROR_CODE,)) + handler.add_method('get_mass', (handler.NO_UNIT,), (units.g, handler.ERROR_CODE)) + handler.add_method('set_mass', (handler.NO_UNIT, units.g,), (handler.ERROR_CODE,)) + handler.add_method('new_particle', (units.g,), (handler.INDEX, handler.ERROR_CODE)) + handler.add_method('delete_particle', (handler.NO_UNIT,), (handler.ERROR_CODE,)) + handler.add_method('get_number_of_particles', (), (handler.NO_UNIT, handler.ERROR_CODE,)) def define_particle_sets(self, handler): handler.define_set('particles', 'id') handler.set_new('particles', 'new_particle') handler.set_delete('particles', 'delete_particle') handler.add_setter('particles', 'set_mass') - handler.add_getter('particles', 'get_mass', names = ('mass',)) + handler.add_getter('particles', 'get_mass', names=('mass',)) def test1(self): particles = self.TestInterface().particles particles.add_particles_to_store( numpy.arange(10), ["mass"], - [ numpy.arange(10) | units.kg] + [numpy.arange(10) | units.kg] ) - self.assertAlmostRelativeEquals(particles.mass, numpy.arange(10) | units.kg) self.assertAlmostRelativeEquals(particles[5].mass, 5 | units.kg) - self.assertAlmostRelativeEquals(particles[[1,3,2,6]].mass, [1,3,2,6] | units.kg) - self.assertAlmostRelativeEquals(particles[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass, [0,2,4,6,8] | units.kg) + self.assertAlmostRelativeEquals(particles[[1, 3, 2, 6]].mass, [1, 3, 2, 6] | units.kg) + self.assertAlmostRelativeEquals(particles[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass, [0, 2, 4, 6, 8] | units.kg) def test2(self): particles = self.TestInterface().particles particles.add_particles_to_store( numpy.arange(10), ["mass"], - [ numpy.arange(10) | units.kg] + [numpy.arange(10) | units.kg] ) - self.assertAlmostRelativeEquals(particles[5:].mass, [5,6,7,8,9] | units.kg) - self.assertAlmostRelativeEquals(particles[1:3].mass, [1,2] | units.kg) - self.assertAlmostRelativeEquals(particles[:5].mass, [0,1,2,3,4] | units.kg) + self.assertAlmostRelativeEquals(particles[5:].mass, [5, 6, 7, 8, 9] | units.kg) + self.assertAlmostRelativeEquals(particles[1:3].mass, [1, 2] | units.kg) + self.assertAlmostRelativeEquals(particles[:5].mass, [0, 1, 2, 3, 4] | units.kg) def test3(self): particles = self.TestInterface().particles particles.add_particles_to_store( numpy.arange(10), ["mass"], - [ numpy.arange(10) | units.kg] + [numpy.arange(10) | units.kg] ) - self.assertAlmostRelativeEquals(particles[5:][:2].mass, [5,6] | units.kg) + self.assertAlmostRelativeEquals(particles[5:][:2].mass, [5, 6] | units.kg) self.assertAlmostRelativeEquals(particles[1:3][:1].mass, 1 | units.kg) - self.assertAlmostRelativeEquals(particles[:5][2:].mass, [2,3,4] | units.kg) - self.assertAlmostRelativeEquals(particles[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass, [0,2] | units.kg) + self.assertAlmostRelativeEquals(particles[:5][2:].mass, [2, 3, 4] | units.kg) + self.assertAlmostRelativeEquals(particles[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass, [0, 2] | units.kg) def test4(self): @@ -3741,11 +3658,10 @@ def test4(self): particles.add_particles_to_store( numpy.arange(10), ["mass"], - [ numpy.arange(10) | units.kg] + [numpy.arange(10) | units.kg] ) - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) - + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) converted = datamodel.ParticlesWithUnitsConverted( particles, @@ -3754,8 +3670,8 @@ def test4(self): self.assertAlmostRelativeEquals(converted.mass, numpy.arange(10) * 0.1 | nbody_system.mass) self.assertAlmostRelativeEquals(converted[5].mass, 0.5 | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[[1,3,2,6]].mass, [0.1,0.3,0.2,0.6] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass, [0,.2,.4,.6,.8] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[[1, 3, 2, 6]].mass, [0.1, 0.3, 0.2, 0.6] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass, [0, .2, .4, .6, .8] | nbody_system.mass) def test5(self): @@ -3763,60 +3679,59 @@ def test5(self): particles.add_particles_to_store( numpy.arange(10), ["mass"], - [ numpy.arange(10) | units.kg] + [numpy.arange(10) | units.kg] ) - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) converted = datamodel.ParticlesWithUnitsConverted( particles, converter.as_converter_from_generic_to_si() ) - self.assertAlmostRelativeEquals(converted.mass, numpy.arange(10) * 0.1| nbody_system.mass) - self.assertAlmostRelativeEquals(converted[5:].mass, [0.5,0.6,0.7,0.8,0.9] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[1:3].mass, [0.1,0.2] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[:5].mass, [0,0.1,0.2,0.3,0.4] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted.mass, numpy.arange(10) * 0.1 | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[5:].mass, [0.5, 0.6, 0.7, 0.8, 0.9] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[1:3].mass, [0.1, 0.2] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[:5].mass, [0, 0.1, 0.2, 0.3, 0.4] | nbody_system.mass) def test6(self): particles = self.TestInterface().particles particles.add_particles_to_store( numpy.arange(10), ["mass"], - [ numpy.arange(10) | units.kg] + [numpy.arange(10) | units.kg] ) - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) converted = datamodel.ParticlesWithUnitsConverted( particles, converter.as_converter_from_generic_to_si() ) - self.assertAlmostRelativeEquals(converted[5:][:2].mass, [0.5,0.6] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[5:][:2].mass, [0.5, 0.6] | nbody_system.mass) self.assertAlmostRelativeEquals(converted[1:3][:1].mass, 0.1 | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[:5][2:].mass, [0.2,0.3,0.4] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass, [0,0.2] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[:5][2:].mass, [0.2, 0.3, 0.4] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass, [0, 0.2] | nbody_system.mass) def test7(self): set1 = self.TestInterface().particles set1.add_particles_to_store( numpy.arange(5), ["mass"], - [ numpy.arange(5) | units.kg] + [numpy.arange(5) | units.kg] ) set2 = self.TestInterface().particles set2.add_particles_to_store( numpy.arange(5)+5, ["mass"], - [ numpy.arange(5) +5 | units.kg] + [numpy.arange(5) + 5 | units.kg] ) particles = datamodel.ParticlesSuperset([set1, set2]) self.assertAlmostRelativeEquals(particles.mass, numpy.arange(10) | units.kg) self.assertAlmostRelativeEquals(particles[5].mass, 5 | units.kg) - self.assertAlmostRelativeEquals(particles[[1,3,2,6]].mass, [1,3,2,6] | units.kg) - self.assertAlmostRelativeEquals(particles[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass, [0,2,4,6,8] | units.kg) - + self.assertAlmostRelativeEquals(particles[[1, 3, 2, 6]].mass, [1, 3, 2, 6] | units.kg) + self.assertAlmostRelativeEquals(particles[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass, [0, 2, 4, 6, 8] | units.kg) def test8(self): @@ -3824,58 +3739,57 @@ def test8(self): set1.add_particles_to_store( numpy.arange(5), ["mass"], - [ numpy.arange(5) | units.kg] + [numpy.arange(5) | units.kg] ) set2 = self.TestInterface().particles set2.add_particles_to_store( numpy.arange(5)+5, ["mass"], - [ numpy.arange(5) +5 | units.kg] + [numpy.arange(5) + 5 | units.kg] ) particles = datamodel.ParticlesSuperset([set1, set2]) - self.assertAlmostRelativeEquals(particles[5:].mass, [5,6,7,8,9] | units.kg) - self.assertAlmostRelativeEquals(particles[1:3].mass, [1,2] | units.kg) - self.assertAlmostRelativeEquals(particles[:5].mass, [0,1,2,3,4] | units.kg) + self.assertAlmostRelativeEquals(particles[5:].mass, [5, 6, 7, 8, 9] | units.kg) + self.assertAlmostRelativeEquals(particles[1:3].mass, [1, 2] | units.kg) + self.assertAlmostRelativeEquals(particles[:5].mass, [0, 1, 2, 3, 4] | units.kg) def test9(self): set1 = self.TestInterface().particles set1.add_particles_to_store( numpy.arange(5), ["mass"], - [ numpy.arange(5) | units.kg] + [numpy.arange(5) | units.kg] ) set2 = self.TestInterface().particles set2.add_particles_to_store( numpy.arange(5)+5, ["mass"], - [ numpy.arange(5) +5 | units.kg] + [numpy.arange(5) + 5 | units.kg] ) particles = datamodel.ParticlesSuperset([set1, set2]) - self.assertAlmostRelativeEquals(particles[5:][0].mass, 5 | units.kg) - self.assertAlmostRelativeEquals(particles[5:][:2].mass, [5,6] | units.kg) + self.assertAlmostRelativeEquals(particles[5:][:2].mass, [5, 6] | units.kg) self.assertAlmostRelativeEquals(particles[1:3][:1].mass, 1 | units.kg) - self.assertAlmostRelativeEquals(particles[:5][2:].mass, [2,3,4] | units.kg) - self.assertAlmostRelativeEquals(particles[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass, [0,2] | units.kg) + self.assertAlmostRelativeEquals(particles[:5][2:].mass, [2, 3, 4] | units.kg) + self.assertAlmostRelativeEquals(particles[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass, [0, 2] | units.kg) def test10(self): set1 = self.TestInterface().particles set1.add_particles_to_store( numpy.arange(5), ["mass"], - [ numpy.arange(5) | units.kg] + [numpy.arange(5) | units.kg] ) set2 = self.TestInterface().particles set2.add_particles_to_store( numpy.arange(5)+5, ["mass"], - [ numpy.arange(5) +5 | units.kg] + [numpy.arange(5) + 5 | units.kg] ) particles = datamodel.ParticlesSuperset([set1, set2]) - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) converted = datamodel.ParticlesWithUnitsConverted( particles, converter.as_converter_from_generic_to_si() @@ -3883,58 +3797,57 @@ def test10(self): self.assertAlmostRelativeEquals(converted.mass, numpy.arange(10) * 0.1 | nbody_system.mass) self.assertAlmostRelativeEquals(converted[5].mass, 0.5 | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[[1,2,3]].mass, [0.1,0.2,0.3] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass, [0,.2,.4,.6,.8] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[[1, 2, 3]].mass, [0.1, 0.2, 0.3] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass, [0, .2, .4, .6, .8] | nbody_system.mass) def test11(self): set1 = self.TestInterface().particles set1.add_particles_to_store( numpy.arange(5), ["mass"], - [ numpy.arange(5) | units.kg] + [numpy.arange(5) | units.kg] ) set2 = self.TestInterface().particles set2.add_particles_to_store( numpy.arange(5)+5, ["mass"], - [ numpy.arange(5) +5 | units.kg] + [numpy.arange(5) + 5 | units.kg] ) particles = datamodel.ParticlesSuperset([set1, set2]) - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) converted = datamodel.ParticlesWithUnitsConverted( particles, converter.as_converter_from_generic_to_si() ) - self.assertAlmostRelativeEquals(converted[5:][:2].mass, [0.5,0.6] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[5:][:2].mass, [0.5, 0.6] | nbody_system.mass) self.assertAlmostRelativeEquals(converted[1:3][:1].mass, 0.1 | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[:5][2:].mass, [0.2,0.3,0.4] | nbody_system.mass) - + self.assertAlmostRelativeEquals(converted[:5][2:].mass, [0.2, 0.3, 0.4] | nbody_system.mass) def test12(self): set1 = self.TestInterface().particles set1.add_particles_to_store( numpy.arange(5), ["mass"], - [ numpy.arange(5) | units.kg] + [numpy.arange(5) | units.kg] ) set2 = self.TestInterface().particles set2.add_particles_to_store( numpy.arange(5)+5, ["mass"], - [ numpy.arange(5) +5 | units.kg] + [numpy.arange(5) + 5 | units.kg] ) particles = datamodel.ParticlesSuperset([set1, set2]) - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) converted = datamodel.ParticlesWithUnitsConverted( particles, converter.as_converter_from_generic_to_si() ) - self.assertAlmostRelativeEquals(converted[5:][:2].mass, [0.5,0.6] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[5:][:2].mass, [0.5, 0.6] | nbody_system.mass) self.assertAlmostRelativeEquals(converted[1:3][:1].mass, 0.1 | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[:5][2:].mass, [0.2,0.3,0.4] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass, [0,0.2] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[:5][2:].mass, [0.2, 0.3, 0.4] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass, [0, 0.2] | nbody_system.mass) def test13(self): set1 = self.TestInterface().particles @@ -3944,6 +3857,7 @@ def test13(self): self.assertEqual(particles.mass, []) + class TestParticlesIndexingWithSet(amusetest.TestCase): # @@ -3952,61 +3866,61 @@ class TestParticlesIndexingWithSet(amusetest.TestCase): def test1(self): particles = datamodel.Particles(10) particles.mass = numpy.arange(10) | units.kg - particles.multidimensional = numpy.arange(60).reshape(10,2,3) + particles.multidimensional = numpy.arange(60).reshape(10, 2, 3) self.assertAlmostRelativeEquals(particles.mass, numpy.arange(10) | units.kg) - self.assertAlmostRelativeEquals(particles.multidimensional, numpy.arange(60).reshape(10,2,3)) + self.assertAlmostRelativeEquals(particles.multidimensional, numpy.arange(60).reshape(10, 2, 3)) particles[5].mass = 15 | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,15,6,7,8,9) | units.kg ) + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 15, 6, 7, 8, 9) | units.kg) particles[5].multidimensional = 15 - self.assertAlmostRelativeEquals(particles.multidimensional[5], [[15,15,15],[15,15,15]] ) + self.assertAlmostRelativeEquals(particles.multidimensional[5], [[15, 15, 15], [15, 15, 15]]) particles.mass = numpy.arange(10) | units.kg - particles[[1,3,2,6]].mass = (11, 13, 12, 16) | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,11,12,13,4,5,16,7,8,9) | units.kg ) + particles[[1, 3, 2, 6]].mass = (11, 13, 12, 16) | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 11, 12, 13, 4, 5, 16, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass = [10,12,14,16,18] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (10,1,12,3,14,5,16,7,18,9) | units.kg ) + particles[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass = [10, 12, 14, 16, 18] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (10, 1, 12, 3, 14, 5, 16, 7, 18, 9) | units.kg) def test2(self): particles = datamodel.Particles(10) particles.mass = numpy.arange(10) | units.kg - particles[5:].mass = [15,16,17,18,19] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,15,16,17,18,19) | units.kg ) + particles[5:].mass = [15, 16, 17, 18, 19] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 15, 16, 17, 18, 19) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[1:3].mass = [11,12] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,11,12,3,4,5,6,7,8,9) | units.kg ) + particles[1:3].mass = [11, 12] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 11, 12, 3, 4, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[:5].mass = [10,11,12,13,14] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (10,11,12,13,14,5,6,7,8,9) | units.kg ) + particles[:5].mass = [10, 11, 12, 13, 14] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (10, 11, 12, 13, 14, 5, 6, 7, 8, 9) | units.kg) def test3(self): particles = datamodel.Particles(10) particles.mass = numpy.arange(10) | units.kg - particles[5:][:2].mass = [15,16] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,15,16,7,8,9) | units.kg ) + particles[5:][:2].mass = [15, 16] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 15, 16, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[1:3][:1].mass = 11 | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,11,2,3,4,5,6,7,8,9) | units.kg ) + particles[1:3][:1].mass = 11 | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 11, 2, 3, 4, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[:5][2:].mass = [12,13,14] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,1,12,13,14,5,6,7,8,9) | units.kg ) + particles[:5][2:].mass = [12, 13, 14] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 12, 13, 14, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass = [10,12] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (10,1,12,3,4,5,6,7,8,9) | units.kg ) - + particles[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass = [10, 12] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (10, 1, 12, 3, 4, 5, 6, 7, 8, 9) | units.kg) # # Converted unit sets # + def test4(self): - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) particles = datamodel.Particles(10) particles.mass = numpy.arange(10) | units.kg @@ -4018,19 +3932,18 @@ def test4(self): self.assertAlmostRelativeEquals(particles.mass, numpy.arange(10) | units.kg) converted[5].mass = 15 | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,150,6,7,8,9) | units.kg ) + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 150, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[[1,3,2,6]].mass = (11, 13, 12, 16) | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,110,120,130,4,5,160,7,8,9) | units.kg ) + converted[[1, 3, 2, 6]].mass = (11, 13, 12, 16) | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 110, 120, 130, 4, 5, 160, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass = [10,12,14,16,18] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (100,1,120,3,140,5,160,7,180,9) | units.kg ) - + converted[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass = [10, 12, 14, 16, 18] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (100, 1, 120, 3, 140, 5, 160, 7, 180, 9) | units.kg) def test5(self): - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) particles = datamodel.Particles(10) particles.mass = numpy.arange(10) | units.kg @@ -4039,21 +3952,20 @@ def test5(self): converter.as_converter_from_generic_to_si() ) - particles.mass = numpy.arange(10) | units.kg - converted[5:].mass = [15,16,17,18,19] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,150,160,170,180,190) | units.kg ) + converted[5:].mass = [15, 16, 17, 18, 19] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 150, 160, 170, 180, 190) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[1:3].mass = [11,12] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,110,120,3,4,5,6,7,8,9) | units.kg ) + converted[1:3].mass = [11, 12] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 110, 120, 3, 4, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[:5].mass = [10,11,12,13,14] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (100,110,120,130,140,5,6,7,8,9) | units.kg ) + converted[:5].mass = [10, 11, 12, 13, 14] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (100, 110, 120, 130, 140, 5, 6, 7, 8, 9) | units.kg) def test6(self): - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) particles = datamodel.Particles(10) particles.mass = numpy.arange(10) | units.kg @@ -4062,28 +3974,26 @@ def test6(self): converter.as_converter_from_generic_to_si() ) - particles.mass = numpy.arange(10) | units.kg - converted[5:][:2].mass = [15,16] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,150,160,7,8,9) | units.kg ) + converted[5:][:2].mass = [15, 16] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 150, 160, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[1:3][:1].mass = 11 | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,110,2,3,4,5,6,7,8,9) | units.kg ) + converted[1:3][:1].mass = 11 | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 110, 2, 3, 4, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[:5][2:].mass = [12,13,14] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,1,120,130,140,5,6,7,8,9) | units.kg ) + converted[:5][2:].mass = [12, 13, 14] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 120, 130, 140, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass = [10,12] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (100,1,120,3,4,5,6,7,8,9) | units.kg ) - - + converted[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass = [10, 12] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (100, 1, 120, 3, 4, 5, 6, 7, 8, 9) | units.kg) # # Particles super sets # + def test7(self): set1 = datamodel.Particles(5) @@ -4093,15 +4003,15 @@ def test7(self): particles = datamodel.ParticlesSuperset([set1, set2]) particles[5].mass = 15 | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,15,6,7,8,9) | units.kg ) + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 15, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[[1,3,2,6]].mass = (11, 13, 12, 16) | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,11,12,13,4,5,16,7,8,9) | units.kg ) + particles[[1, 3, 2, 6]].mass = (11, 13, 12, 16) | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 11, 12, 13, 4, 5, 16, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass = [10,12,14,16,18] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (10,1,12,3,14,5,16,7,18,9) | units.kg ) + particles[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass = [10, 12, 14, 16, 18] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (10, 1, 12, 3, 14, 5, 16, 7, 18, 9) | units.kg) def test8(self): @@ -4112,17 +4022,16 @@ def test8(self): particles = datamodel.ParticlesSuperset([set1, set2]) particles.mass = numpy.arange(10) | units.kg - particles[5:].mass = [15,16,17,18,19] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,15,16,17,18,19) | units.kg ) + particles[5:].mass = [15, 16, 17, 18, 19] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 15, 16, 17, 18, 19) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[1:3].mass = [11,12] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,11,12,3,4,5,6,7,8,9) | units.kg ) + particles[1:3].mass = [11, 12] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 11, 12, 3, 4, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[:5].mass = [10,11,12,13,14] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (10,11,12,13,14,5,6,7,8,9) | units.kg ) - + particles[:5].mass = [10, 11, 12, 13, 14] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (10, 11, 12, 13, 14, 5, 6, 7, 8, 9) | units.kg) def test9(self): set1 = datamodel.Particles(5) @@ -4133,26 +4042,26 @@ def test9(self): particles.mass = numpy.arange(10) | units.kg particles[5:][0].mass = [15] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,15,6,7,8,9) | units.kg ) + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 15, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[5:][:2].mass = [15,16] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,15,16,7,8,9) | units.kg ) + particles[5:][:2].mass = [15, 16] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 15, 16, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[1:3][:1].mass = 11 | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,11,2,3,4,5,6,7,8,9) | units.kg ) + particles[1:3][:1].mass = 11 | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 11, 2, 3, 4, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[:5][2:].mass = [12,13,14] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,1,12,13,14,5,6,7,8,9) | units.kg ) + particles[:5][2:].mass = [12, 13, 14] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 12, 13, 14, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass = [10,12] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (10,1,12,3,4,5,6,7,8,9) | units.kg ) + particles[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass = [10, 12] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (10, 1, 12, 3, 4, 5, 6, 7, 8, 9) | units.kg) def test10(self): - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) set1 = datamodel.Particles(5) set1.mass = numpy.arange(5) | units.kg @@ -4167,14 +4076,14 @@ def test10(self): self.assertAlmostRelativeEquals(converted.mass, numpy.arange(10) * 0.1 | nbody_system.mass) self.assertAlmostRelativeEquals(converted[5].mass, 0.5 | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[[1,2,3]].mass, [0.1,0.2,0.3] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass, [0,.2,.4,.6,.8] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[[1, 2, 3]].mass, [0.1, 0.2, 0.3] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass, [0, .2, .4, .6, .8] | nbody_system.mass) # # superset with conversion # def test11(self): - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) set1 = datamodel.Particles(5) set1.mass = numpy.arange(5) | units.kg @@ -4187,19 +4096,19 @@ def test11(self): ) particles.mass = numpy.arange(10) | units.kg - converted[5:].mass = [15,16,17,18,19] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,150,160,170,180,190) | units.kg ) + converted[5:].mass = [15, 16, 17, 18, 19] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 150, 160, 170, 180, 190) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[1:3].mass = [11,12] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,110,120,3,4,5,6,7,8,9) | units.kg ) + converted[1:3].mass = [11, 12] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 110, 120, 3, 4, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[:5].mass = [10,11,12,13,14] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (100,110,120,130,140,5,6,7,8,9) | units.kg ) + converted[:5].mass = [10, 11, 12, 13, 14] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (100, 110, 120, 130, 140, 5, 6, 7, 8, 9) | units.kg) def test12(self): - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) particles = datamodel.Particles(10) particles.mass = numpy.arange(10) | units.kg @@ -4209,24 +4118,25 @@ def test12(self): ) particles.mass = numpy.arange(10) | units.kg - converted[5:][0].mass = [15] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,150,6,7,8,9) | units.kg ) + converted[5:][0].mass = [15] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 150, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[5:][:2].mass = [15,16] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,150,160,7,8,9) | units.kg ) + converted[5:][:2].mass = [15, 16] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 150, 160, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[1:3][:1].mass = 11 | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,110,2,3,4,5,6,7,8,9) | units.kg ) + converted[1:3][:1].mass = 11 | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 110, 2, 3, 4, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[:5][2:].mass = [12,13,14] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,1,120,130,140,5,6,7,8,9) | units.kg ) + converted[:5][2:].mass = [12, 13, 14] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 120, 130, 140, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass = [10,12] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (100,1,120,3,4,5,6,7,8,9) | units.kg ) + converted[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass = [10, 12] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (100, 1, 120, 3, 4, 5, 6, 7, 8, 9) | units.kg) + class TestParticlesIndexingWithBindingAndSet(amusetest.TestCase): class TestLegacyCode(object): @@ -4242,18 +4152,18 @@ def get_mass(self, id): for x in id: masses.append(self.masses[x-self.offset]) errors.append(0) - return ( masses, errors, ) + return (masses, errors, ) def set_mass(self, id, mass): try: - for i,m in zip(id,mass): + for i, m in zip(id, mass): self.masses[i-self.offset] = m except: if len(id) == 1: self.masses[id[0]-self.offset] = mass - return ( [0] * len(id),) + return ([0] * len(id),) def new_particle(self, mass): ids = [] @@ -4261,7 +4171,7 @@ def new_particle(self, mass): for x in mass: id = len(self.masses) - self.masses[len(self.masses)] = x + self.masses[len(self.masses)] = x ids.append(id + self.offset) errors.append(0) return (ids, errors) @@ -4281,22 +4191,22 @@ def get_number_of_particles(self): class TestInterface(InCodeComponentImplementation): - def __init__(self, offset = 2): + def __init__(self, offset=2): InCodeComponentImplementation.__init__(self, TestParticlesIndexingWithBindingAndSet.TestLegacyCode(offset=offset)) def define_methods(self, handler): - handler.add_method('get_mass',(handler.NO_UNIT,), (units.g, handler.ERROR_CODE)) - handler.add_method('set_mass',(handler.NO_UNIT, units.g,), (handler.ERROR_CODE,)) - handler.add_method('new_particle',(units.g,), (handler.INDEX, handler.ERROR_CODE)) - handler.add_method('delete_particle',(handler.NO_UNIT,), (handler.ERROR_CODE,)) - handler.add_method('get_number_of_particles',(), (handler.NO_UNIT, handler.ERROR_CODE,)) + handler.add_method('get_mass', (handler.NO_UNIT,), (units.g, handler.ERROR_CODE)) + handler.add_method('set_mass', (handler.NO_UNIT, units.g,), (handler.ERROR_CODE,)) + handler.add_method('new_particle', (units.g,), (handler.INDEX, handler.ERROR_CODE)) + handler.add_method('delete_particle', (handler.NO_UNIT,), (handler.ERROR_CODE,)) + handler.add_method('get_number_of_particles', (), (handler.NO_UNIT, handler.ERROR_CODE,)) def define_particle_sets(self, handler): handler.define_set('particles', 'id') handler.set_new('particles', 'new_particle') handler.set_delete('particles', 'delete_particle') handler.add_setter('particles', 'set_mass') - handler.add_getter('particles', 'get_mass', names = ('mass',)) + handler.add_getter('particles', 'get_mass', names=('mass',)) # # normal set @@ -4306,62 +4216,62 @@ def test1(self): particles.add_particles_to_store( numpy.arange(10), ["mass"], - [ numpy.arange(10) | units.kg] + [numpy.arange(10) | units.kg] ) self.assertAlmostRelativeEquals(particles.mass, numpy.arange(10) | units.kg) particles[5].mass = 15 | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,15,6,7,8,9) | units.kg ) + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 15, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[[1,3,2,6]].mass = (11, 13, 12, 16) | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,11,12,13,4,5,16,7,8,9) | units.kg ) + particles[[1, 3, 2, 6]].mass = (11, 13, 12, 16) | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 11, 12, 13, 4, 5, 16, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass = [10,12,14,16,18] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (10,1,12,3,14,5,16,7,18,9) | units.kg ) + particles[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass = [10, 12, 14, 16, 18] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (10, 1, 12, 3, 14, 5, 16, 7, 18, 9) | units.kg) def test2(self): particles = self.TestInterface().particles particles.add_particles_to_store( numpy.arange(10), ["mass"], - [ numpy.arange(10) | units.kg] + [numpy.arange(10) | units.kg] ) particles.mass = numpy.arange(10) | units.kg - particles[5:].mass = [15,16,17,18,19] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,15,16,17,18,19) | units.kg ) + particles[5:].mass = [15, 16, 17, 18, 19] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 15, 16, 17, 18, 19) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[1:3].mass = [11,12] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,11,12,3,4,5,6,7,8,9) | units.kg ) + particles[1:3].mass = [11, 12] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 11, 12, 3, 4, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[:5].mass = [10,11,12,13,14] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (10,11,12,13,14,5,6,7,8,9) | units.kg ) + particles[:5].mass = [10, 11, 12, 13, 14] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (10, 11, 12, 13, 14, 5, 6, 7, 8, 9) | units.kg) def test3(self): particles = self.TestInterface().particles particles.add_particles_to_store( numpy.arange(10), ["mass"], - [ numpy.arange(10) | units.kg] + [numpy.arange(10) | units.kg] ) particles.mass = numpy.arange(10) | units.kg - particles[5:][:2].mass = [15,16] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,15,16,7,8,9) | units.kg ) + particles[5:][:2].mass = [15, 16] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 15, 16, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[1:3][:1].mass = 11 | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,11,2,3,4,5,6,7,8,9) | units.kg ) + particles[1:3][:1].mass = 11 | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 11, 2, 3, 4, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[:5][2:].mass = [12,13,14] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,1,12,13,14,5,6,7,8,9) | units.kg ) + particles[:5][2:].mass = [12, 13, 14] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 12, 13, 14, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass = [10,12] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (10,1,12,3,4,5,6,7,8,9) | units.kg ) + particles[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass = [10, 12] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (10, 1, 12, 3, 4, 5, 6, 7, 8, 9) | units.kg) # # units converted @@ -4372,11 +4282,10 @@ def test4(self): particles.add_particles_to_store( numpy.arange(10), ["mass"], - [ numpy.arange(10) | units.kg] + [numpy.arange(10) | units.kg] ) - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) - + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) converted = datamodel.ParticlesWithUnitsConverted( particles, @@ -4385,15 +4294,15 @@ def test4(self): self.assertAlmostRelativeEquals(particles.mass, numpy.arange(10) | units.kg) converted[5].mass = 15 | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,150,6,7,8,9) | units.kg ) + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 150, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[[1,3,2,6]].mass = (11, 13, 12, 16) | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,110,120,130,4,5,160,7,8,9) | units.kg ) + converted[[1, 3, 2, 6]].mass = (11, 13, 12, 16) | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 110, 120, 130, 4, 5, 160, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass = [10,12,14,16,18] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (100,1,120,3,140,5,160,7,180,9) | units.kg ) + converted[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass = [10, 12, 14, 16, 18] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (100, 1, 120, 3, 140, 5, 160, 7, 180, 9) | units.kg) def test5(self): @@ -4401,10 +4310,10 @@ def test5(self): particles.add_particles_to_store( numpy.arange(10), ["mass"], - [ numpy.arange(10) | units.kg] + [numpy.arange(10) | units.kg] ) - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) converted = datamodel.ParticlesWithUnitsConverted( particles, @@ -4412,26 +4321,26 @@ def test5(self): ) particles.mass = numpy.arange(10) | units.kg - converted[5:].mass = [15,16,17,18,19] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,150,160,170,180,190) | units.kg ) + converted[5:].mass = [15, 16, 17, 18, 19] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 150, 160, 170, 180, 190) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[1:3].mass = [11,12] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,110,120,3,4,5,6,7,8,9) | units.kg ) + converted[1:3].mass = [11, 12] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 110, 120, 3, 4, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[:5].mass = [10,11,12,13,14] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (100,110,120,130,140,5,6,7,8,9) | units.kg ) + converted[:5].mass = [10, 11, 12, 13, 14] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (100, 110, 120, 130, 140, 5, 6, 7, 8, 9) | units.kg) def test6(self): particles = self.TestInterface().particles particles.add_particles_to_store( numpy.arange(10), ["mass"], - [ numpy.arange(10) | units.kg] + [numpy.arange(10) | units.kg] ) - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) converted = datamodel.ParticlesWithUnitsConverted( particles, @@ -4439,24 +4348,24 @@ def test6(self): ) particles.mass = numpy.arange(10) | units.kg - converted[5:][0].mass = [15] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,150,6,7,8,9) | units.kg ) + converted[5:][0].mass = [15] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 150, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[5:][:2].mass = [15,16] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,150,160,7,8,9) | units.kg ) + converted[5:][:2].mass = [15, 16] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 150, 160, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[1:3][:1].mass = 11 | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,110,2,3,4,5,6,7,8,9) | units.kg ) + converted[1:3][:1].mass = 11 | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 110, 2, 3, 4, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[:5][2:].mass = [12,13,14] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,1,120,130,140,5,6,7,8,9) | units.kg ) + converted[:5][2:].mass = [12, 13, 14] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 120, 130, 140, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass = [10,12] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (100,1,120,3,4,5,6,7,8,9) | units.kg ) + converted[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass = [10, 12] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (100, 1, 120, 3, 4, 5, 6, 7, 8, 9) | units.kg) # # supersets @@ -4466,27 +4375,26 @@ def test7(self): set1.add_particles_to_store( numpy.arange(5), ["mass"], - [ numpy.arange(5) | units.kg] + [numpy.arange(5) | units.kg] ) set2 = self.TestInterface().particles set2.add_particles_to_store( numpy.arange(5)+5, ["mass"], - [ numpy.arange(5) +5 | units.kg] + [numpy.arange(5) + 5 | units.kg] ) particles = datamodel.ParticlesSuperset([set1, set2]) - particles[5].mass = 15 | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,15,6,7,8,9) | units.kg ) + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 15, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[[1,3,2,6]].mass = (11, 13, 12, 16) | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,11,12,13,4,5,16,7,8,9) | units.kg ) + particles[[1, 3, 2, 6]].mass = (11, 13, 12, 16) | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 11, 12, 13, 4, 5, 16, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass = [10,12,14,16,18] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (10,1,12,3,14,5,16,7,18,9) | units.kg ) + particles[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass = [10, 12, 14, 16, 18] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (10, 1, 12, 3, 14, 5, 16, 7, 18, 9) | units.kg) def test8(self): @@ -4494,63 +4402,62 @@ def test8(self): set1.add_particles_to_store( numpy.arange(5), ["mass"], - [ numpy.arange(5) | units.kg] + [numpy.arange(5) | units.kg] ) set2 = self.TestInterface().particles set2.add_particles_to_store( numpy.arange(5)+5, ["mass"], - [ numpy.arange(5) +5 | units.kg] + [numpy.arange(5) + 5 | units.kg] ) particles = datamodel.ParticlesSuperset([set1, set2]) particles.mass = numpy.arange(10) | units.kg - particles[5:].mass = [15,16,17,18,19] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,15,16,17,18,19) | units.kg ) + particles[5:].mass = [15, 16, 17, 18, 19] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 15, 16, 17, 18, 19) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[1:3].mass = [11,12] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,11,12,3,4,5,6,7,8,9) | units.kg ) + particles[1:3].mass = [11, 12] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 11, 12, 3, 4, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[:5].mass = [10,11,12,13,14] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (10,11,12,13,14,5,6,7,8,9) | units.kg ) + particles[:5].mass = [10, 11, 12, 13, 14] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (10, 11, 12, 13, 14, 5, 6, 7, 8, 9) | units.kg) def test9(self): set1 = self.TestInterface().particles set1.add_particles_to_store( numpy.arange(5), ["mass"], - [ numpy.arange(5) | units.kg] + [numpy.arange(5) | units.kg] ) set2 = self.TestInterface().particles set2.add_particles_to_store( numpy.arange(5)+5, ["mass"], - [ numpy.arange(5) +5 | units.kg] + [numpy.arange(5) + 5 | units.kg] ) particles = datamodel.ParticlesSuperset([set1, set2]) - particles.mass = numpy.arange(10) | units.kg particles[5:][0].mass = [15] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,15,6,7,8,9) | units.kg ) + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 15, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[5:][:2].mass = [15,16] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,15,16,7,8,9) | units.kg ) + particles[5:][:2].mass = [15, 16] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 15, 16, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[1:3][:1].mass = 11 | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,11,2,3,4,5,6,7,8,9) | units.kg ) + particles[1:3][:1].mass = 11 | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 11, 2, 3, 4, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[:5][2:].mass = [12,13,14] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (0,1,12,13,14,5,6,7,8,9) | units.kg ) + particles[:5][2:].mass = [12, 13, 14] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 12, 13, 14, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - particles[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass = [10,12] | units.kg - self.assertAlmostRelativeEquals(particles.mass, (10,1,12,3,4,5,6,7,8,9) | units.kg ) + particles[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass = [10, 12] | units.kg + self.assertAlmostRelativeEquals(particles.mass, (10, 1, 12, 3, 4, 5, 6, 7, 8, 9) | units.kg) # # superset and unit conversion @@ -4560,17 +4467,17 @@ def test10(self): set1.add_particles_to_store( numpy.arange(5), ["mass"], - [ numpy.arange(5) | units.kg] + [numpy.arange(5) | units.kg] ) set2 = self.TestInterface().particles set2.add_particles_to_store( numpy.arange(5)+5, ["mass"], - [ numpy.arange(5) +5 | units.kg] + [numpy.arange(5) + 5 | units.kg] ) particles = datamodel.ParticlesSuperset([set1, set2]) - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) converted = datamodel.ParticlesWithUnitsConverted( particles, converter.as_converter_from_generic_to_si() @@ -4578,94 +4485,91 @@ def test10(self): self.assertAlmostRelativeEquals(particles.mass, numpy.arange(10) | units.kg) converted[5].mass = 15 | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,150,6,7,8,9) | units.kg ) + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 150, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[[1,3,2,6]].mass = (11, 13, 12, 16) | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,110,120,130,4,5,160,7,8,9) | units.kg ) + converted[[1, 3, 2, 6]].mass = (11, 13, 12, 16) | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 110, 120, 130, 4, 5, 160, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass = [10,12,14,16,18] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (100,1,120,3,140,5,160,7,180,9) | units.kg ) + converted[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass = [10, 12, 14, 16, 18] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (100, 1, 120, 3, 140, 5, 160, 7, 180, 9) | units.kg) def test11(self): set1 = self.TestInterface().particles set1.add_particles_to_store( numpy.arange(5), ["mass"], - [ numpy.arange(5) | units.kg] + [numpy.arange(5) | units.kg] ) set2 = self.TestInterface().particles set2.add_particles_to_store( numpy.arange(5)+5, ["mass"], - [ numpy.arange(5) +5 | units.kg] + [numpy.arange(5) + 5 | units.kg] ) particles = datamodel.ParticlesSuperset([set1, set2]) - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) converted = datamodel.ParticlesWithUnitsConverted( particles, converter.as_converter_from_generic_to_si() ) particles.mass = numpy.arange(10) | units.kg - converted[5:].mass = [15,16,17,18,19] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,150,160,170,180,190) | units.kg ) + converted[5:].mass = [15, 16, 17, 18, 19] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 150, 160, 170, 180, 190) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[1:3].mass = [11,12] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,110,120,3,4,5,6,7,8,9) | units.kg ) + converted[1:3].mass = [11, 12] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 110, 120, 3, 4, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[:5].mass = [10,11,12,13,14] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (100,110,120,130,140,5,6,7,8,9) | units.kg ) + converted[:5].mass = [10, 11, 12, 13, 14] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (100, 110, 120, 130, 140, 5, 6, 7, 8, 9) | units.kg) def test12(self): set1 = self.TestInterface().particles set1.add_particles_to_store( numpy.arange(5), ["mass"], - [ numpy.arange(5) | units.kg] + [numpy.arange(5) | units.kg] ) set2 = self.TestInterface().particles set2.add_particles_to_store( numpy.arange(5)+5, ["mass"], - [ numpy.arange(5) +5 | units.kg] + [numpy.arange(5) + 5 | units.kg] ) particles = datamodel.ParticlesSuperset([set1, set2]) - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) converted = datamodel.ParticlesWithUnitsConverted( particles, converter.as_converter_from_generic_to_si() ) particles.mass = numpy.arange(10) | units.kg - converted[5:][0].mass = [15] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,150,6,7,8,9) | units.kg ) + converted[5:][0].mass = [15] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 150, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[5:][:2].mass = [15,16] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,1,2,3,4,150,160,7,8,9) | units.kg ) + converted[5:][:2].mass = [15, 16] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 2, 3, 4, 150, 160, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[1:3][:1].mass = 11 | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,110,2,3,4,5,6,7,8,9) | units.kg ) + converted[1:3][:1].mass = 11 | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 110, 2, 3, 4, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[:5][2:].mass = [12,13,14] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (0,1,120,130,140,5,6,7,8,9) | units.kg ) + converted[:5][2:].mass = [12, 13, 14] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (0, 1, 120, 130, 140, 5, 6, 7, 8, 9) | units.kg) particles.mass = numpy.arange(10) | units.kg - converted[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass = [10,12] | nbody_system.mass - self.assertAlmostRelativeEquals(particles.mass, (100,1,120,3,4,5,6,7,8,9) | units.kg ) - - + converted[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass = [10, 12] | nbody_system.mass + self.assertAlmostRelativeEquals(particles.mass, (100, 1, 120, 3, 4, 5, 6, 7, 8, 9) | units.kg) class TestParticlesIndexingAfterPickle(amusetest.TestCase): - def copy_with_pickle(self, set): return pickle.loads(pickle.dumps(set)) @@ -4677,8 +4581,8 @@ def test1(self): self.assertAlmostRelativeEquals(particles.mass, numpy.arange(10) | units.kg) self.assertAlmostRelativeEquals(particles[5].mass, 5 | units.kg) - self.assertAlmostRelativeEquals(particles[[1,3,2,6]].mass, [1,3,2,6] | units.kg) - self.assertAlmostRelativeEquals(particles[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass, [0,2,4,6,8] | units.kg) + self.assertAlmostRelativeEquals(particles[[1, 3, 2, 6]].mass, [1, 3, 2, 6] | units.kg) + self.assertAlmostRelativeEquals(particles[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass, [0, 2, 4, 6, 8] | units.kg) def test2(self): particles = datamodel.Particles(10) @@ -4686,9 +4590,9 @@ def test2(self): particles = self.copy_with_pickle(particles) - self.assertAlmostRelativeEquals(particles[5:].mass, [5,6,7,8,9] | units.kg) - self.assertAlmostRelativeEquals(particles[1:3].mass, [1,2] | units.kg) - self.assertAlmostRelativeEquals(particles[:5].mass, [0,1,2,3,4] | units.kg) + self.assertAlmostRelativeEquals(particles[5:].mass, [5, 6, 7, 8, 9] | units.kg) + self.assertAlmostRelativeEquals(particles[1:3].mass, [1, 2] | units.kg) + self.assertAlmostRelativeEquals(particles[:5].mass, [0, 1, 2, 3, 4] | units.kg) def test3(self): particles = datamodel.Particles(10) @@ -4696,13 +4600,13 @@ def test3(self): particles = self.copy_with_pickle(particles) - self.assertAlmostRelativeEquals(particles[5:][:2].mass, [5,6] | units.kg) + self.assertAlmostRelativeEquals(particles[5:][:2].mass, [5, 6] | units.kg) self.assertAlmostRelativeEquals(particles[1:3][:1].mass, 1 | units.kg) - self.assertAlmostRelativeEquals(particles[:5][2:].mass, [2,3,4] | units.kg) - self.assertAlmostRelativeEquals(particles[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass, [0,2] | units.kg) + self.assertAlmostRelativeEquals(particles[:5][2:].mass, [2, 3, 4] | units.kg) + self.assertAlmostRelativeEquals(particles[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass, [0, 2] | units.kg) def test4(self): - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) particles = datamodel.Particles(10) particles.mass = numpy.arange(10) | units.kg @@ -4716,11 +4620,11 @@ def test4(self): self.assertAlmostRelativeEquals(converted.mass, numpy.arange(10) * 0.1 | nbody_system.mass) self.assertAlmostRelativeEquals(converted[5].mass, 0.5 | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[[1,3,2,6]].mass, [0.1,0.3,0.2,0.6] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass, [0,.2,.4,.6,.8] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[[1, 3, 2, 6]].mass, [0.1, 0.3, 0.2, 0.6] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass, [0, .2, .4, .6, .8] | nbody_system.mass) def test5(self): - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) particles = datamodel.Particles(10) particles.mass = numpy.arange(10) | units.kg @@ -4731,13 +4635,13 @@ def test5(self): converted = self.copy_with_pickle(converted) - self.assertAlmostRelativeEquals(converted.mass, numpy.arange(10) * 0.1| nbody_system.mass) - self.assertAlmostRelativeEquals(converted[5:].mass, [0.5,0.6,0.7,0.8,0.9] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[1:3].mass, [0.1,0.2] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[:5].mass, [0,0.1,0.2,0.3,0.4] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted.mass, numpy.arange(10) * 0.1 | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[5:].mass, [0.5, 0.6, 0.7, 0.8, 0.9] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[1:3].mass, [0.1, 0.2] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[:5].mass, [0, 0.1, 0.2, 0.3, 0.4] | nbody_system.mass) def test6(self): - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) particles = datamodel.Particles(10) particles.mass = numpy.arange(10) | units.kg @@ -4746,10 +4650,10 @@ def test6(self): converter.as_converter_from_generic_to_si() ) converted = self.copy_with_pickle(converted) - self.assertAlmostRelativeEquals(converted[5:][:2].mass, [0.5,0.6] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[5:][:2].mass, [0.5, 0.6] | nbody_system.mass) self.assertAlmostRelativeEquals(converted[1:3][:1].mass, 0.1 | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[:5][2:].mass, [0.2,0.3,0.4] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass, [0,0.2] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[:5][2:].mass, [0.2, 0.3, 0.4] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass, [0, 0.2] | nbody_system.mass) def test7(self): @@ -4763,9 +4667,8 @@ def test7(self): self.assertAlmostRelativeEquals(particles.mass, numpy.arange(10) | units.kg) self.assertAlmostRelativeEquals(particles[5].mass, 5 | units.kg) - self.assertAlmostRelativeEquals(particles[[1,3,2,6]].mass, [1,3,2,6] | units.kg) - self.assertAlmostRelativeEquals(particles[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass, [0,2,4,6,8] | units.kg) - + self.assertAlmostRelativeEquals(particles[[1, 3, 2, 6]].mass, [1, 3, 2, 6] | units.kg) + self.assertAlmostRelativeEquals(particles[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass, [0, 2, 4, 6, 8] | units.kg) def test8(self): @@ -4777,9 +4680,9 @@ def test8(self): particles = self.copy_with_pickle(particles) - self.assertAlmostRelativeEquals(particles[5:].mass, [5,6,7,8,9] | units.kg) - self.assertAlmostRelativeEquals(particles[1:3].mass, [1,2] | units.kg) - self.assertAlmostRelativeEquals(particles[:5].mass, [0,1,2,3,4] | units.kg) + self.assertAlmostRelativeEquals(particles[5:].mass, [5, 6, 7, 8, 9] | units.kg) + self.assertAlmostRelativeEquals(particles[1:3].mass, [1, 2] | units.kg) + self.assertAlmostRelativeEquals(particles[:5].mass, [0, 1, 2, 3, 4] | units.kg) def test9(self): set1 = datamodel.Particles(5) @@ -4790,16 +4693,14 @@ def test9(self): particles = self.copy_with_pickle(particles) - - self.assertAlmostRelativeEquals(particles[5:][0].mass, 5 | units.kg) - self.assertAlmostRelativeEquals(particles[5:][:2].mass, [5,6] | units.kg) + self.assertAlmostRelativeEquals(particles[5:][:2].mass, [5, 6] | units.kg) self.assertAlmostRelativeEquals(particles[1:3][:1].mass, 1 | units.kg) - self.assertAlmostRelativeEquals(particles[:5][2:].mass, [2,3,4] | units.kg) - self.assertAlmostRelativeEquals(particles[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass, [0,2] | units.kg) + self.assertAlmostRelativeEquals(particles[:5][2:].mass, [2, 3, 4] | units.kg) + self.assertAlmostRelativeEquals(particles[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass, [0, 2] | units.kg) def test10(self): - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) set1 = datamodel.Particles(5) set1.mass = numpy.arange(5) | units.kg @@ -4814,11 +4715,11 @@ def test10(self): self.assertAlmostRelativeEquals(converted.mass, numpy.arange(10) * 0.1 | nbody_system.mass) self.assertAlmostRelativeEquals(converted[5].mass, 0.5 | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[[1,2,3]].mass, [0.1,0.2,0.3] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[numpy.array([True,False,True,False,True,False,True,False,True,False])].mass, [0,.2,.4,.6,.8] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[[1, 2, 3]].mass, [0.1, 0.2, 0.3] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[numpy.array([True, False, True, False, True, False, True, False, True, False])].mass, [0, .2, .4, .6, .8] | nbody_system.mass) def test11(self): - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) set1 = datamodel.Particles(5) set1.mass = numpy.arange(5) | units.kg @@ -4832,13 +4733,12 @@ def test11(self): converted = self.copy_with_pickle(converted) - self.assertAlmostRelativeEquals(converted[5:][:2].mass, [0.5,0.6] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[5:][:2].mass, [0.5, 0.6] | nbody_system.mass) self.assertAlmostRelativeEquals(converted[1:3][:1].mass, 0.1 | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[:5][2:].mass, [0.2,0.3,0.4] | nbody_system.mass) - + self.assertAlmostRelativeEquals(converted[:5][2:].mass, [0.2, 0.3, 0.4] | nbody_system.mass) def test12(self): - converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m ) + converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m) particles = datamodel.Particles(10) particles.mass = numpy.arange(10) | units.kg @@ -4849,10 +4749,11 @@ def test12(self): converted = self.copy_with_pickle(converted) - self.assertAlmostRelativeEquals(converted[5:][:2].mass, [0.5,0.6] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[5:][:2].mass, [0.5, 0.6] | nbody_system.mass) self.assertAlmostRelativeEquals(converted[1:3][:1].mass, 0.1 | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[:5][2:].mass, [0.2,0.3,0.4] | nbody_system.mass) - self.assertAlmostRelativeEquals(converted[numpy.array([True,False,True,False,True,False,True,False,True,False])][:2].mass, [0,0.2] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[:5][2:].mass, [0.2, 0.3, 0.4] | nbody_system.mass) + self.assertAlmostRelativeEquals(converted[numpy.array([True, False, True, False, True, False, True, False, True, False])][:2].mass, [0, 0.2] | nbody_system.mass) + class TestParticlesOverlay(amusetest.TestCase): @@ -4871,7 +4772,7 @@ def test2(self): set1.x = [1.0, 2.0] | units.kg set2 = datamodel.ParticlesOverlay(set1) set2.y = [4.0, 5.0] | units.m - set2.add_particle(datamodel.Particle(x=3.0 | units.kg, y = 6.0 | units.m)) + set2.add_particle(datamodel.Particle(x=3.0 | units.kg, y=6.0 | units.m)) self.assertAlmostRelativeEquals(set2.x, [1.0, 2.0, 3.0] | units.kg) self.assertAlmostRelativeEquals(set2.y, [4.0, 5.0, 6.0] | units.m) self.assertAlmostRelativeEquals(set1.x, [1.0, 2.0, 3.0] | units.kg) @@ -4885,7 +4786,6 @@ def test3(self): self.assertAlmostRelativeEquals(particle.x, 1.0 | units.kg) self.assertAlmostRelativeEquals(particle.y, 4.0 | units.m) - def test4(self): set1 = datamodel.Particles(2) set1.x = [1.0, 2.0] | units.kg @@ -4906,7 +4806,7 @@ def test5(self): self.assertEqual(len(subset), 2) self.assertAlmostRelativeEquals(subset.x, [2.0, 3.0] | units.kg) self.assertAlmostRelativeEquals(subset.y, [5.0, 6.0] | units.m) - xy = subset.get_values_in_store(subset.get_all_indices_in_store(), ['x','y']) + xy = subset.get_values_in_store(subset.get_all_indices_in_store(), ['x', 'y']) self.assertAlmostRelativeEquals(xy[0], [2.0, 3.0] | units.kg) self.assertAlmostRelativeEquals(xy[1], [5.0, 6.0] | units.m) @@ -4915,11 +4815,10 @@ def test6(self): set1.x = [1.0, 2.0, 3.0] | units.kg set2 = datamodel.ParticlesOverlay(set1) set2.y = [4.0, 5.0, 6.0] | units.m - set2.x = [7.0,8.0,9.0] | units.kg - - self.assertAlmostRelativeEquals(set2.x, [7.0,8.0,9.0] | units.kg) - self.assertAlmostRelativeEquals(set1.x, [7.0,8.0,9.0] | units.kg) + set2.x = [7.0, 8.0, 9.0] | units.kg + self.assertAlmostRelativeEquals(set2.x, [7.0, 8.0, 9.0] | units.kg) + self.assertAlmostRelativeEquals(set1.x, [7.0, 8.0, 9.0] | units.kg) def test7(self): set1 = datamodel.Particles(2) @@ -4938,15 +4837,16 @@ def test8(self): print(set2) set1.remove_particle(set1[0]) set1.remove_particle(set1[4]) - set1.add_particle(datamodel.Particle(x = 10 | units.kg)) - set1.add_particle(datamodel.Particle(x = 10 | units.kg)) + set1.add_particle(datamodel.Particle(x=10 | units.kg)) + set1.add_particle(datamodel.Particle(x=10 | units.kg)) set1.remove_particle(set1[-2]) print(set2) self.assertAlmostRelativeEquals(set1.x, set2.x) + class TestParticlesWithSpecificDtypes(amusetest.TestCase): - + def new_set_with_specific_dtype(self): m_float32 = unit_with_specific_dtype(units.m, numpy.float32) m_int32 = unit_with_specific_dtype(units.m, numpy.int32) @@ -4955,7 +4855,7 @@ def new_set_with_specific_dtype(self): set.y = [1.3, 2.7, numpy.pi] | m_float32 set.z = [1.3, 2.7, numpy.pi] | m_int32 return set - + def test1(self): print("Unit with dtype is stored on set, number gets same dtype") set = self.new_set_with_specific_dtype() @@ -4970,7 +4870,7 @@ def test1(self): self.assertFalse((set.y.number == [1.3, 2.7, numpy.pi]).any()) self.assertAlmostEqual(set.y.number, [1.3, 2.7, numpy.pi], 6) self.assertEqual(set.z.number, [1, 2, 3]) - + def test2(self): if compare_version_strings(numpy.__version__, '1.8.0') < 0: self.skip("test does a conversion that is not supported on older numpy versions") @@ -4991,7 +4891,6 @@ def test2(self): self.assertAlmostEqual(set.y.number, [1.0, 2.0, 3.0], 6) self.assertEqual(set.z.number, [2, 5, 6]) - def test3(self): print("Adding particles: stored unit with dtype remains") set = self.new_set_with_specific_dtype() @@ -5008,4 +4907,3 @@ def test3(self): self.assertTrue((set.x.number == [1.3, 2.7, numpy.pi, 1.3, 2.7, numpy.pi]).all()) self.assertAlmostEqual(set.y.number, [1.3, 2.7, numpy.pi, 1.3, 2.7, numpy.pi], 6) self.assertEqual(set.z.number, [1, 2, 3, 1, 2, 3]) - diff --git a/src/amuse/test/suite/core_tests/test_particles_properties.py b/src/amuse/test/suite/core_tests/test_particles_properties.py index 99cdc9f489..90ba9e0e24 100644 --- a/src/amuse/test/suite/core_tests/test_particles_properties.py +++ b/src/amuse/test/suite/core_tests/test_particles_properties.py @@ -12,45 +12,45 @@ from amuse import datamodel + class TestParticlesProperties(amusetest.TestCase): - + def test1(self): - + particles = datamodel.Particles(2) particles.mass = 10 | units.kg - + self.assertTrue(hasattr(particles, 'collection_attributes')) - + particles.collection_attributes.timestamp = 1 | units.yr self.assertEqual(particles.collection_attributes.timestamp, 1 | units.yr) - - particles.collection_attributes.a = 2 + + particles.collection_attributes.a = 2 self.assertEqual(particles.collection_attributes.a, 2) - - + def test2(self): - + particles = datamodel.Particles(2) particles.collection_attributes.timestamp = 1 | units.yr - + self.assertEqual(str(particles.collection_attributes), "timestamp: 1 yr") - + particles.collection_attributes.a = 2 self.assertEqual(str(particles.collection_attributes), "timestamp: 1 yr\na: 2") - + def test3(self): - + particles1 = datamodel.Particles(2) particles1.collection_attributes.timestamp = 1 | units.yr particles1.collection_attributes.a = 2 particles2 = particles1.copy() - + self.assertEqual(particles2.collection_attributes.timestamp, 1 | units.yr) self.assertEqual(particles2.collection_attributes.a, 2) self.assertEqual(str(particles2.collection_attributes), "timestamp: 1 yr\na: 2") - + def test4(self): - + particles1 = datamodel.Particles(2) particles1.collection_attributes.timestamp = 1 | units.yr particles1.collection_attributes.a = 2 @@ -58,6 +58,3 @@ def test4(self): particles2 = pickle.loads(pickled_string) self.assertEqual(particles2.collection_attributes.timestamp, 1 | units.yr) self.assertEqual(particles2.collection_attributes.a, 2) - - - diff --git a/src/amuse/test/suite/core_tests/test_phigrape.py b/src/amuse/test/suite/core_tests/test_phigrape.py index 1a91abe421..067f7578d5 100644 --- a/src/amuse/test/suite/core_tests/test_phigrape.py +++ b/src/amuse/test/suite/core_tests/test_phigrape.py @@ -7,17 +7,18 @@ from amuse.units import nbody_system from amuse.units import quantities from amuse import datamodel -class Test(amusetest.TestCase): +class Test(amusetest.TestCase): + def test(self): directory = os.path.dirname(__file__) instance = phigrape.Inp2Particles() instance.convert_to_particles(os.path.join(directory, 'plummer_100.ini')) rev_instance = phigrape.Particles2Inp() output = os.path.join(self.get_path_to_results(), 'plummer_back_100.ini') - rev_instance.convert_to_inp(instance.Particles,output) - + rev_instance.convert_to_inp(instance.Particles, output) + control_instance = phigrape.Inp2Particles() control_instance.convert_to_particles(os.path.join(directory, output)) diff --git a/src/amuse/test/suite/core_tests/test_pickle.py b/src/amuse/test/suite/core_tests/test_pickle.py index f208e3c47c..eff6d02817 100644 --- a/src/amuse/test/suite/core_tests/test_pickle.py +++ b/src/amuse/test/suite/core_tests/test_pickle.py @@ -19,6 +19,7 @@ import sys import os + class TestPicklingOfUnitsAndQuantities(amusetest.TestCase): def test1(self): @@ -28,7 +29,6 @@ def test1(self): unpickled_km = pickle.loads(pickled_km) self.assertEqual(1000, unpickled_km.value_in(m)) - def test2(self): km = 1000 * m quantity = 12.0 | km @@ -37,23 +37,17 @@ def test2(self): unpickled_quantity = pickle.loads(pickled_quantity) self.assertEqual(12000, unpickled_quantity.value_in(m)) self.assertEqual(quantity, unpickled_quantity) - - def test3(self): pickled_si_sytem = pickle.dumps(si.system) unpickled_si_sytem = pickle.loads(pickled_si_sytem) self.assertTrue(unpickled_si_sytem is si.system) - - def test4(self): quantity = 12.0 | nbody_system.energy pickled_quantity = pickle.dumps(quantity) unpickled_quantity = pickle.loads(pickled_quantity) self.assertEqual(quantity, unpickled_quantity) - - def test5(self): quantity = 12.0 | parsec @@ -62,8 +56,6 @@ def test5(self): self.assertEqual(quantity, unpickled_quantity) self.assertEqual(str(quantity), str(unpickled_quantity)) self.assertEqual(12.0, unpickled_quantity.value_in(parsec)) - - def test6(self): quantity = [12.0, 15.0] | parsec @@ -71,8 +63,6 @@ def test6(self): unpickled_quantity = pickle.loads(pickled_quantity) self.assertEqual(quantity, unpickled_quantity) self.assertEqual(str(quantity), str(unpickled_quantity)) - - def test7(self): quantity = zero @@ -81,7 +71,7 @@ def test7(self): self.assertEqual(quantity, unpickled_quantity) self.assertTrue(quantity is unpickled_quantity) self.assertEqual(str(quantity), str(unpickled_quantity)) - + def test8(self): quantity = 1 | nbody_system.time pickled_quantity = pickle.dumps(quantity) @@ -91,57 +81,49 @@ def test8(self): def test9(self): quantity = 1.3 | nbody_system.time - path=os.path.abspath(os.path.join(self.get_path_to_results(), "test9.pickle")) + path = os.path.abspath(os.path.join(self.get_path_to_results(), "test9.pickle")) - with open(path, "wb") as stream: + with open(path, "wb") as stream: pickle.dump(quantity, stream) - + pythonpath = os.pathsep.join(sys.path) env = os.environ.copy() env['PYTHONPATH'] = pythonpath code = "import pickle;stream = open('{0}', 'rb'); print(str(pickle.load(stream)));stream.close()".format(path) - + process = subprocess.Popen([ sys.executable, "-c", code, "--no-report-references" - ] - , stdout=subprocess.PIPE - , stderr=subprocess.PIPE - ,env = env + ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env ) unpickled_quantity_string, error_string = process.communicate() - self.assertEqual(process.returncode, 0) - self.assertEqual(str(quantity),unpickled_quantity_string.strip().decode('utf-8')) - - + self.assertEqual(process.returncode, 0) + self.assertEqual(str(quantity), unpickled_quantity_string.strip().decode('utf-8')) + def test10(self): - quantity = 1 | parsec - path=os.path.abspath(os.path.join(self.get_path_to_results(), "test10.pickle")) - with open(path, "wb") as stream: + quantity = 1 | parsec + path = os.path.abspath(os.path.join(self.get_path_to_results(), "test10.pickle")) + with open(path, "wb") as stream: pickle.dump(quantity, stream) - + pythonpath = os.pathsep.join(sys.path) env = os.environ.copy() env['PYTHONPATH'] = pythonpath code = "import pickle;stream = open('{0}', 'rb'); print(str(pickle.load(stream)));stream.close()".format(path) - + process = subprocess.Popen([ sys.executable, "-c", code, "--no-report-references" - ] - , stdout=subprocess.PIPE - , stderr=subprocess.PIPE - , env = env + ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env ) unpickled_quantity_string, error_string = process.communicate() self.assertEqual(process.returncode, 0) - self.assertEqual(str(quantity),unpickled_quantity_string.strip().decode('utf-8')) - - + self.assertEqual(str(quantity), unpickled_quantity_string.strip().decode('utf-8')) + def test11(self): value = 1 | stellar_type self.assertEqual(1 | stellar_type, value) @@ -149,16 +131,16 @@ def test11(self): unpickled_value = pickle.loads(pickled) self.assertEqual(1 | stellar_type, unpickled_value) - + class TestPicklingOfParticleSets(amusetest.TestCase): def test1(self): particles = Particles(4) - particles.mass = [1,2,3,4] | km + particles.mass = [1, 2, 3, 4] | km pickled_particles = pickle.dumps(particles) unpickled_particles = pickle.loads(pickled_particles) - self.assertAlmostRelativeEquals(unpickled_particles.mass, [1,2,3,4] | km) - + self.assertAlmostRelativeEquals(unpickled_particles.mass, [1, 2, 3, 4] | km) + def test2(self): particles = Particles(4) particles.mass = [1, 2, 3, 6] | kg @@ -168,7 +150,6 @@ def test2(self): unpickled_particles = pickle.loads(pickled_particles) self.assertAlmostRelativeEquals(unpickled_particles.mass, [1, 2, 3, 6] | kg) self.assertEqual(unpickled_particles.center_of_mass(), [2, 3, 0] | m) - def test3(self): particles = Particles(4) @@ -177,7 +158,7 @@ def test3(self): self.assertEqual(particles.center_of_mass(), [2, 3, 0] | m) pickled_particles = pickle.dumps(particles) unpickled_particles = pickle.loads(pickled_particles) - pickled_particles = pickle.dumps(particles) #dump it twice! + pickled_particles = pickle.dumps(particles) # dump it twice! unpickled_particles = pickle.loads(pickled_particles) self.assertAlmostRelativeEquals(unpickled_particles.mass, [1, 2, 3, 6] | kg) self.assertEqual(unpickled_particles.center_of_mass(), [2, 3, 0] | m) @@ -188,23 +169,22 @@ def test4(self): particles.position = [[0, 0, 0], [3, 0, 0], [0, 4, 0], [3, 4, 0]] | m pickled_particles = pickle.dumps(list(particles)) unpickled_particles = pickle.loads(pickled_particles) - self.assertEqual(len(unpickled_particles) , 4) + self.assertEqual(len(unpickled_particles), 4) unpickled_particles = Particles(particles=unpickled_particles) self.assertAlmostRelativeEquals(unpickled_particles.mass, [1, 2, 3, 6] | kg) self.assertEqual(unpickled_particles.center_of_mass(), [2, 3, 0] | m) - - class BaseTestModule(object): def before_get_parameter(self): return - + def before_set_parameter(self): return - + + class TestPicklingOfParameters(amusetest.TestCase): - + def test1(self): definition = parameters.ModuleMethodParameterDefinition( "get_test", @@ -213,25 +193,25 @@ def test1(self): "a test parameter", 0.1 | m ) + class TestModule(BaseTestModule): def get_test(self): return self.x + def set_test(self, value): self.x = value - + o = TestModule() set = parameters.Parameters([definition,], o) - set.test_name = 10| m - - self.assertEqual(o.x, 10|m) - self.assertEqual(set.test_name, 10|m) - + set.test_name = 10 | m + + self.assertEqual(o.x, 10 | m) + self.assertEqual(set.test_name, 10 | m) + memento = set.copy() - self.assertEqual(memento.test_name, 10|m) + self.assertEqual(memento.test_name, 10 | m) + + pickled_memento = pickle.dumps(memento) + unpickled_memento = pickle.loads(pickled_memento) - pickled_memento=pickle.dumps(memento) - unpickled_memento=pickle.loads(pickled_memento) - self.assertEqual(memento.test_name, unpickled_memento.test_name) - - diff --git a/src/amuse/test/suite/core_tests/test_plot.py b/src/amuse/test/suite/core_tests/test_plot.py index 8a668c9c3a..58cc0436bd 100644 --- a/src/amuse/test/suite/core_tests/test_plot.py +++ b/src/amuse/test/suite/core_tests/test_plot.py @@ -13,6 +13,7 @@ except ImportError: HAS_MATPLOTLIB = False + class TestPlot(amusetest.TestCase): def test1(self): @@ -65,9 +66,8 @@ def test3(self): self.assertEqual("[Myr]", self.xaxis().get_label_text()) self.assertEqual("[AU]", self.yaxis().get_label_text()) - self.assertAlmostRelativeEquals( 0., pyplot.xlim()[0], 2) + self.assertAlmostRelativeEquals(0., pyplot.xlim()[0], 2) self.assertAlmostRelativeEquals(0.0001, pyplot.xlim()[1], 1) - def test4(self): """ Test text in a plot """ @@ -81,7 +81,7 @@ def test4(self): aplot.plot(x, y) - text = aplot.text(50|units.yr, 0.5|units.AU, "test text") + text = aplot.text(50 | units.yr, 0.5 | units.AU, "test text") self.assertEqual(50., text.get_position()[0]) self.assertAlmostEqual(107.546995464, text.get_position()[1]) @@ -97,7 +97,7 @@ def test5(self): y = numpy.linspace(0, 200, 100) | units.RSun yerr = [2e5]*len(y) | units.km - line = aplot.errorbar(x, y, yerr=yerr, capsize = 10) + line = aplot.errorbar(x, y, yerr=yerr, capsize=10) points, caps, bars = line bottoms, tops = caps error_height = tops.get_ydata()[0] - bottoms.get_ydata()[0] @@ -116,7 +116,7 @@ def test6(self): line = aplot.plot(x, y) - aplot.xlim(0|units.yr, 2e9|units.s) + aplot.xlim(0 | units.yr, 2e9 | units.s) self.assertAlmostEqual(0, pyplot.xlim()[0]) self.assertAlmostEqual(63.37752924, pyplot.xlim()[1]) @@ -143,11 +143,11 @@ def test7(self): self.assertEqual(-10, pyplot.xlim()[0]) self.assertEqual(90, pyplot.xlim()[1]) - aplot.ylim([-12, 110]|units.RSun) + aplot.ylim([-12, 110] | units.RSun) self.assertEqual(-12, pyplot.ylim()[0]) self.assertEqual(110, pyplot.ylim()[1]) - aplot.ylim(ymin=1e6|units.km) + aplot.ylim(ymin=1e6 | units.km) self.assertAlmostEqual(1.43781452, pyplot.ylim()[0]) self.assertEqual(110, pyplot.ylim()[1]) @@ -185,11 +185,11 @@ def test9(self): self.assertEqual("[m]", self.xaxis().get_label_text()) self.assertEqual("[m]", self.yaxis().get_label_text()) - con = aplot.contour(X, Y, Z, levels=[500000, 1000000]|units.cm**2) + con = aplot.contour(X, Y, Z, levels=[500000, 1000000] | units.cm**2) self.assertEqual([50, 100], con.get_array()) - con = aplot.contour(X, Y, Z, [0.0002, 0.0003]|units.km**2) + con = aplot.contour(X, Y, Z, [0.0002, 0.0003] | units.km**2) self.assertEqual([200, 300], con.get_array()) diff --git a/src/amuse/test/suite/core_tests/test_quantities.py b/src/amuse/test/suite/core_tests/test_quantities.py index 38dfc1a103..6d82c07836 100644 --- a/src/amuse/test/suite/core_tests/test_quantities.py +++ b/src/amuse/test/suite/core_tests/test_quantities.py @@ -15,6 +15,8 @@ from amuse import datamodel + + class TestQuantities(amusetest.TestCase): def test1(self): @@ -29,14 +31,12 @@ def test2(self): xy = x * y self.assertTrue(isinstance(xy, VectorQuantity)) - def test3(self): x = [1.0, 2.0, 3.0] | si.kg y = [2.0, 3.0, 4.0] | si.kg self.assertTrue(isinstance(x[0], ScalarQuantity)) self.assertEqual(str(x[1]), "2.0 kg") - def test4(self): g = si.kg / 1000 x = [1.0, 2.0, 3.0] | si.kg @@ -47,11 +47,10 @@ def test4(self): def test5(self): number_of_stars = 10 stars = datamodel.Particles(number_of_stars) - stars.position = [0,0,0] | units.km + stars.position = [0, 0, 0] | units.km for i, star in enumerate(stars): star.position = units.km.new_quantity([float(i+1), float((i+1)*2), float(-1 * (i+1))]) - minpos = [float(sys.maxsize)] * 3 | units.m maxpos = [-float(sys.maxsize)] * 3 | units.m for star in stars: @@ -76,7 +75,6 @@ def test7(self): y = 1 / x self.assertEqual(y.value_in(1/si.kg), 0.5) - def test8(self): x = (1.0, 2.0, 3.0) | si.kg self.assertTrue(isinstance(x, VectorQuantity)) @@ -88,130 +86,130 @@ def test9(self): def test10(self): self.assertEqual(1 | units.m, 1 | units.m) - self.assertTrue (1 | units.m == 1 | units.m) + self.assertTrue(1 | units.m == 1 | units.m) self.assertFalse(1 | units.m == 2 | units.m) - self.assertTrue (1 | units.m != 2 | units.m) + self.assertTrue(1 | units.m != 2 | units.m) self.assertFalse(1 | units.m != 1 | units.m) - self.assertTrue (1 | units.m >= 1 | units.m) + self.assertTrue(1 | units.m >= 1 | units.m) self.assertFalse(1 | units.m >= 2 | units.m) - self.assertTrue (1 | units.m <= 1 | units.m) + self.assertTrue(1 | units.m <= 1 | units.m) self.assertFalse(1 | units.m <= 0 | units.m) - self.assertTrue (1 | units.m > 0 | units.m) - self.assertFalse(1 | units.m > 1 | units.m) - self.assertTrue (1 | units.m < 3 | units.m) - self.assertFalse(1 | units.m < 0 | units.m) + self.assertTrue(1 | units.m > 0 | units.m) + self.assertFalse(1 | units.m > 1 | units.m) + self.assertTrue(1 | units.m < 3 | units.m) + self.assertFalse(1 | units.m < 0 | units.m) def test11(self): self.assertEqual([1] | units.m, [1] | units.m) - self.assertTrue ([1] | units.m == [1] | units.m) + self.assertTrue([1] | units.m == [1] | units.m) self.assertFalse([1] | units.m == [2] | units.m) - self.assertTrue ([1] | units.m != [2] | units.m) + self.assertTrue([1] | units.m != [2] | units.m) self.assertFalse([1] | units.m != [1] | units.m) - self.assertTrue ([1] | units.m >= [1] | units.m) + self.assertTrue([1] | units.m >= [1] | units.m) self.assertFalse([1] | units.m >= [2] | units.m) - self.assertTrue ([1] | units.m <= [1] | units.m) + self.assertTrue([1] | units.m <= [1] | units.m) self.assertFalse([1] | units.m <= [0] | units.m) - self.assertTrue ([1] | units.m > [0] | units.m) - self.assertFalse([1] | units.m > [1] | units.m) - self.assertTrue ([1] | units.m < [3] | units.m) - self.assertFalse([1] | units.m < [0] | units.m) + self.assertTrue([1] | units.m > [0] | units.m) + self.assertFalse([1] | units.m > [1] | units.m) + self.assertTrue([1] | units.m < [3] | units.m) + self.assertFalse([1] | units.m < [0] | units.m) def test12(self): self.assertEqual(zero, zero) - self.assertTrue (zero == zero) + self.assertTrue(zero == zero) self.assertFalse(zero == zero + (1 | units.m)) self.assertFalse(zero + (1 | units.m) == zero) - self.assertTrue (zero != zero + (1 | units.m)) + self.assertTrue(zero != zero + (1 | units.m)) self.assertFalse(zero != zero) - self.assertTrue (zero >= zero) + self.assertTrue(zero >= zero) self.assertFalse(zero >= zero + (1 | units.m)) - self.assertTrue (zero <= zero + (1 | units.m)) + self.assertTrue(zero <= zero + (1 | units.m)) self.assertFalse(zero <= zero - (1 | units.m)) - self.assertTrue (zero > zero - (1 | units.m)) - self.assertFalse(zero > zero) - self.assertTrue (zero < zero + (1 | units.m)) - self.assertFalse(zero < zero - (1 | units.m)) - self.assertTrue (zero == 0 | units.m) + self.assertTrue(zero > zero - (1 | units.m)) + self.assertFalse(zero > zero) + self.assertTrue(zero < zero + (1 | units.m)) + self.assertFalse(zero < zero - (1 | units.m)) + self.assertTrue(zero == 0 | units.m) def test13(self): self.assertEqual('a', 'a') - self.assertTrue ('a' == 'a') + self.assertTrue('a' == 'a') self.assertFalse('a' == 'ab') - self.assertTrue ('a' != 'A') + self.assertTrue('a' != 'A') self.assertFalse('a' != 'a') - self.assertTrue ('b' >= 'a') + self.assertTrue('b' >= 'a') self.assertFalse('B' >= 'a') - self.assertTrue ('a' <= 'ab') + self.assertTrue('a' <= 'ab') self.assertFalse('a' <= 'A') - self.assertTrue ('a' > 'A') - self.assertFalse('a' > 'a') - self.assertTrue ('a' < 'b') - self.assertFalse('a' < 'B') + self.assertTrue('a' > 'A') + self.assertFalse('a' > 'a') + self.assertTrue('a' < 'b') + self.assertFalse('a' < 'B') def test14(self): # Tests for 'is_quantity' - self.assertTrue( is_quantity(0 | units.kg) ) - self.assertTrue( is_quantity(1 | units.none) ) - self.assertTrue( is_quantity([1.0, 2.0, 3.0] | units.m) ) - self.assertFalse( is_quantity(1) ) - self.assertFalse( is_quantity(1.0) ) - self.assertFalse( is_quantity("string") ) + self.assertTrue(is_quantity(0 | units.kg)) + self.assertTrue(is_quantity(1 | units.none)) + self.assertTrue(is_quantity([1.0, 2.0, 3.0] | units.m)) + self.assertFalse(is_quantity(1)) + self.assertFalse(is_quantity(1.0)) + self.assertFalse(is_quantity("string")) def test15(self): # Tests for 'to_quantity' - self.assertTrue( is_quantity(to_quantity(0 | units.kg)) ) - self.assertTrue( is_quantity(to_quantity(1 | units.none)) ) - self.assertTrue( is_quantity(to_quantity([1.0, 2.0, 3.0] | units.m)) ) - self.assertTrue( is_quantity(to_quantity(1)) ) - self.assertTrue( is_quantity(to_quantity(1.0)) ) + self.assertTrue(is_quantity(to_quantity(0 | units.kg))) + self.assertTrue(is_quantity(to_quantity(1 | units.none))) + self.assertTrue(is_quantity(to_quantity([1.0, 2.0, 3.0] | units.m))) + self.assertTrue(is_quantity(to_quantity(1))) + self.assertTrue(is_quantity(to_quantity(1.0))) masses = [1, 2, 3] | units.kg - self.assertTrue( to_quantity(masses) is masses ) + self.assertTrue(to_quantity(masses) is masses) numbers = [1, 2, 3] - self.assertFalse( to_quantity(numbers) is numbers | units.none ) - self.assertTrue( numpy.all(to_quantity(numbers) == numbers | units.none) ) + self.assertFalse(to_quantity(numbers) is numbers | units.none) + self.assertTrue(numpy.all(to_quantity(numbers) == numbers | units.none)) def test16(self): # Tests for add/sub of quantity (with none unit) and number - self.assertEqual( (2.0 | units.none) + 1.0, 3.0 ) - self.assertEqual( (2.0 | units.none) - 1.0, 1.0 ) - self.assertEqual( 1.0 + (2.0 | units.none), 3.0 ) - self.assertEqual( 1.0 - (2.0 | units.none), -1.0 ) + self.assertEqual((2.0 | units.none) + 1.0, 3.0) + self.assertEqual((2.0 | units.none) - 1.0, 1.0) + self.assertEqual(1.0 + (2.0 | units.none), 3.0) + self.assertEqual(1.0 - (2.0 | units.none), -1.0) def test17(self): # Tests for add/sub of quantity (with other unit) and number number = 1.0 quantity = 2.0 | units.m - self.assertTrue( number.__add__(quantity) is NotImplemented) + self.assertTrue(number.__add__(quantity) is NotImplemented) self.assertRaises(AmuseException, quantity.__radd__, number) - self.assertTrue( number.__radd__(quantity) is NotImplemented) + self.assertTrue(number.__radd__(quantity) is NotImplemented) self.assertRaises(AmuseException, quantity.__add__, number) - self.assertTrue( number.__sub__(quantity) is NotImplemented) + self.assertTrue(number.__sub__(quantity) is NotImplemented) self.assertRaises(AmuseException, quantity.__rsub__, number) - self.assertTrue( number.__rsub__(quantity) is NotImplemented) + self.assertTrue(number.__rsub__(quantity) is NotImplemented) self.assertRaises(AmuseException, quantity.__sub__, number) # in other words... self.assertRaises(AmuseException, lambda: number + quantity, - expected_message = "Cannot express none in m, the units do not have the same bases") + expected_message="Cannot express none in m, the units do not have the same bases") self.assertRaises(AmuseException, lambda: quantity + number, - expected_message = "Cannot express none in m, the units do not have the same bases") + expected_message="Cannot express none in m, the units do not have the same bases") self.assertRaises(AmuseException, lambda: number - quantity, - expected_message = "Cannot express none in m, the units do not have the same bases") + expected_message="Cannot express none in m, the units do not have the same bases") self.assertRaises(AmuseException, lambda: quantity - number, - expected_message = "Cannot express none in m, the units do not have the same bases") + expected_message="Cannot express none in m, the units do not have the same bases") def test18(self): quantity = 'string' - self.assertEqual(quantity , 'string') + self.assertEqual(quantity, 'string') quantity = 'string' - self.assertEqual(quantity , 'string') + self.assertEqual(quantity, 'string') def test19(self): x = 1.0 | si.kg - self.assertTrue(x==x.amin()) - self.assertTrue(x==x.prod()) - self.assertTrue(x==x.sorted()) - self.assertTrue(x==x.amax()) - self.assertTrue(x==x.sum()) + self.assertTrue(x == x.amin()) + self.assertTrue(x == x.prod()) + self.assertTrue(x == x.sorted()) + self.assertTrue(x == x.amax()) + self.assertTrue(x == x.sum()) def test20(self): lengths = [] | units.m @@ -254,22 +252,20 @@ def test21(self): self.assertEqual(zero_vector[0:2], zero.as_vector_with_length(2)) - def test22(self): - x = numpy.asarray([1,2,3,4]) + x = numpy.asarray([1, 2, 3, 4]) y = 2 | units.m self.assertTrue(is_quantity(y * x)) - self.assertAlmostRelativeEquals(y*x, [2,4,6,8] | units.m) + self.assertAlmostRelativeEquals(y*x, [2, 4, 6, 8] | units.m) self.assertTrue(is_quantity(x * y)) - self.assertAlmostRelativeEquals(x*y, [2,4,6,8] | units.m) + self.assertAlmostRelativeEquals(x*y, [2, 4, 6, 8] | units.m) def test23(self): z = zero.as_vector_with_length(2) self.assertEqual(len(z), 2) z += 1 | units.kg self.assertEqual(z.unit, units.kg) - self.assertEqual(z, [1,1] | units.kg) - + self.assertEqual(z, [1, 1] | units.kg) def xtest24(self): rhs = 2 | units.MSun / units.AU @@ -279,16 +275,14 @@ def xtest24(self): print(product) self.assertTrue(product_unit is units.MSun) - def xtest25(self): rhs = 2.0 | (2 * units.MSun)**2 / units.AU lhs = 3.0 | units.MSun product = rhs / lhs product_unit = product.unit print(product) - self.assertEqual(product_unit , units.MSun / units.AU) - self.assertEqual(product_unit.local_factor , 4) - + self.assertEqual(product_unit, units.MSun / units.AU) + self.assertEqual(product_unit.local_factor, 4) def xtest26(self): rhs = 2.0 | units.AU / (2 * units.MSun)**2 @@ -297,129 +291,129 @@ def xtest26(self): product_unit = product.unit print(product) print(type(product_unit)) - self.assertEqual(product_unit , units.AU / units.MSun) - self.assertEqual(product_unit.local_factor , 1/4.0) + self.assertEqual(product_unit, units.AU / units.MSun) + self.assertEqual(product_unit.local_factor, 1/4.0) def test27(self): - a=[1.|units.kg,2.|units.kg,3000.| units.g, 4.| (1000*units.g)] - b=VectorQuantity.new_from_scalar_quantities(*a) - c=[1.,2.,3.,4.] | units.kg - print(a[0].unit==a[2].unit) - self.assertEqual(b,c) + a = [1. | units.kg, 2. | units.kg, 3000. | units.g, 4. | (1000*units.g)] + b = VectorQuantity.new_from_scalar_quantities(*a) + c = [1., 2., 3., 4.] | units.kg + print(a[0].unit == a[2].unit) + self.assertEqual(b, c) def test28(self): - a=[1.|units.kg,2.|units.kg,3000.| units.m, 4.| (1000*units.g)] + a = [1. | units.kg, 2. | units.kg, 3000. | units.m, 4. | (1000*units.g)] try: - b=VectorQuantity.new_from_scalar_quantities(*a) - raise Exception("expect error") + b = VectorQuantity.new_from_scalar_quantities(*a) + raise Exception("expect error") except: - pass - + pass + def test29(self): one_inch = 2.54 | units.cm self.assertFalse(isinstance(one_inch, core.unit)) self.assertTrue(isinstance(one_inch.as_unit(), core.unit)) self.assertEqual(one_inch.as_unit(), 2.54 * units.cm) self.assertEqual(1 | one_inch.as_unit(), 2.54 | units.cm) - + def test30(self): - a=1.5| units.km - b=1000. | units.m - self.assertEqual(a%b,500. | units.m) - a=[1.5,1.75]| units.km - b=1000. | units.m - self.assertEqual(a%b,[500.,750] | units.m) - a=[1.5,1.75]| units.km - b=[1000.,500.] | units.m - self.assertEqual(a%b,[500.,250.] | units.m) - a=[1.5]| units.km - b=[1000.,500.] | units.m - self.assertEqual(a%b,[500.,0.] | units.m) + a = 1.5 | units.km + b = 1000. | units.m + self.assertEqual(a % b, 500. | units.m) + a = [1.5, 1.75] | units.km + b = 1000. | units.m + self.assertEqual(a % b, [500., 750] | units.m) + a = [1.5, 1.75] | units.km + b = [1000., 500.] | units.m + self.assertEqual(a % b, [500., 250.] | units.m) + a = [1.5] | units.km + b = [1000., 500.] | units.m + self.assertEqual(a % b, [500., 0.] | units.m) def test31(self): """ test trigonometric unit stuff """ - self.assertEqual(units.pi,numpy.pi) - a=units.pi + self.assertEqual(units.pi, numpy.pi) + a = units.pi self.assertEqual(trigo.to_rad(a), numpy.pi | units.rad) self.assertEqual(trigo.to_deg(a), 180. | units.deg) self.assertEqual(trigo.to_rev(a), 0.5 | units.rev) - a=90 | units.deg + a = 90 | units.deg self.assertEqual(trigo.to_rad(a), numpy.pi/2 | units.rad) self.assertEqual(trigo.to_deg(a), 90. | units.deg) self.assertEqual(trigo.to_rev(a), 0.25 | units.rev) - a=0.75 | units.rev + a = 0.75 | units.rev self.assertEqual(trigo.to_rad(a), 3/2.*numpy.pi | units.rad) self.assertEqual(trigo.to_deg(a), 270. | units.deg) self.assertEqual(trigo.to_rev(a), 0.75 | units.rev) - a=2*numpy.pi + a = 2*numpy.pi self.assertEqual(trigo.to_rad(a), 2*numpy.pi | units.rad) self.assertEqual(trigo.to_deg(a), 360. | units.deg) self.assertEqual(trigo.to_rev(a), 1. | units.rev) - a=45. | units.deg - self.assertEqual(trigo.sin(a),numpy.sin(45./180*numpy.pi)) - self.assertEqual(trigo.cos(a),numpy.cos(45./180*numpy.pi)) - self.assertEqual(trigo.tan(a),numpy.tan(45./180*numpy.pi)) + a = 45. | units.deg + self.assertEqual(trigo.sin(a), numpy.sin(45./180*numpy.pi)) + self.assertEqual(trigo.cos(a), numpy.cos(45./180*numpy.pi)) + self.assertEqual(trigo.tan(a), numpy.tan(45./180*numpy.pi)) - a=1. | units.rad - self.assertEqual(trigo.sin(a),numpy.sin(1.)) - self.assertEqual(trigo.cos(a),numpy.cos(1.)) - self.assertEqual(trigo.tan(a),numpy.tan(1.)) + a = 1. | units.rad + self.assertEqual(trigo.sin(a), numpy.sin(1.)) + self.assertEqual(trigo.cos(a), numpy.cos(1.)) + self.assertEqual(trigo.tan(a), numpy.tan(1.)) - a=0.125 | units.rev - self.assertEqual(trigo.sin(a),numpy.sin(45./180*numpy.pi)) - self.assertEqual(trigo.cos(a),numpy.cos(45./180*numpy.pi)) - self.assertEqual(trigo.tan(a),numpy.tan(45./180*numpy.pi)) + a = 0.125 | units.rev + self.assertEqual(trigo.sin(a), numpy.sin(45./180*numpy.pi)) + self.assertEqual(trigo.cos(a), numpy.cos(45./180*numpy.pi)) + self.assertEqual(trigo.tan(a), numpy.tan(45./180*numpy.pi)) - a=45. | units.deg - self.assertAlmostEqual(trigo.arcsin(trigo.sin(a)),45. | units.deg,13) - self.assertAlmostEqual(trigo.arccos(trigo.cos(a)),45. | units.deg,13) - self.assertAlmostEqual(trigo.arctan(trigo.tan(a)),45. | units.deg,13) + a = 45. | units.deg + self.assertAlmostEqual(trigo.arcsin(trigo.sin(a)), 45. | units.deg, 13) + self.assertAlmostEqual(trigo.arccos(trigo.cos(a)), 45. | units.deg, 13) + self.assertAlmostEqual(trigo.arctan(trigo.tan(a)), 45. | units.deg, 13) def test32(self): - a=numpy.array([[1.,2.,3.],[4.,5.,6.]]) | units.m - b=numpy.array([[1.,2.,3.],[4.,5.,6.]]) + a = numpy.array([[1., 2., 3.], [4., 5., 6.]]) | units.m + b = numpy.array([[1., 2., 3.], [4., 5., 6.]]) self.assertEqual(list(a.flatten()), list(a.flat)) - flat1=b.flat - flat2=a.flat - self.assertEqual(flat1[2:5],flat2[2:5].number) + flat1 = b.flat + flat2 = a.flat + self.assertEqual(flat1[2:5], flat2[2:5].number) next(flat1) next(flat2) - self.assertEqual(flat1.index,flat2.index) - self.assertEqual(flat1.base,flat2.base.number) - self.assertEqual(flat1.copy(),flat2.copy().number) + self.assertEqual(flat1.index, flat2.index) + self.assertEqual(flat1.base, flat2.base.number) + self.assertEqual(flat1.copy(), flat2.copy().number) def test32b(self): - a=numpy.array([[1.,2.,3.],[4.,5.,6.]]) | units.m - b=numpy.array([[1.,2.,3.],[4.,5.,6.]]) - flat1=b.flat - flat2=a.flat - self.assertEqual(flat1[2:5],flat2[2:5].number) - self.assertEqual(flat1,flat2.number) - - flat2[:]=numpy.arange(6) | units.cm - a_=numpy.array([[0.,1.,2.],[3.,4.,5.]]) | units.cm + a = numpy.array([[1., 2., 3.], [4., 5., 6.]]) | units.m + b = numpy.array([[1., 2., 3.], [4., 5., 6.]]) + flat1 = b.flat + flat2 = a.flat + self.assertEqual(flat1[2:5], flat2[2:5].number) + self.assertEqual(flat1, flat2.number) + + flat2[:] = numpy.arange(6) | units.cm + a_ = numpy.array([[0., 1., 2.], [3., 4., 5.]]) | units.cm self.assertEqual(a, a_) def test33(self): - a=[1,2,3,4] - b=new_quantity_nonone(a,units.none) - self.assertEqual(len(a),len(b)) - b=new_quantity_nonone(a,2*units.none) - self.assertEqual(len(a),len(b)) + a = [1, 2, 3, 4] + b = new_quantity_nonone(a, units.none) + self.assertEqual(len(a), len(b)) + b = new_quantity_nonone(a, 2*units.none) + self.assertEqual(len(a), len(b)) def test34(self): - a= [1,2,3,4,5] | units.m - x= a.value_in(units.cm) - x[0]=-1 - self.assertEqual(a, [1,2,3,4,5] | units.m) + a = [1, 2, 3, 4, 5] | units.m + x = a.value_in(units.cm) + x[0] = -1 + self.assertEqual(a, [1, 2, 3, 4, 5] | units.m) - a= [1,2,3,4,5] | units.m - x= a.value_in(units.m) - x[0]=-1 - self.assertEqual(a, [1,2,3,4,5] | units.m) + a = [1, 2, 3, 4, 5] | units.m + x = a.value_in(units.m) + x[0] = -1 + self.assertEqual(a, [1, 2, 3, 4, 5] | units.m) class TestAdaptingVectorQuantities(amusetest.TestCase): @@ -455,15 +449,15 @@ def test2(self): def test3(self): x = AdaptingVectorQuantity() - x.extend([1,2,3] | units.kg) + x.extend([1, 2, 3] | units.kg) self.assertEqual(x.unit, units.kg) self.assertEqual(len(x), 3) - self.assertEqual(x.number, numpy.array([1,2,3])) + self.assertEqual(x.number, numpy.array([1, 2, 3])) - x.extend([1,2,3] | units.g) + x.extend([1, 2, 3] | units.g) self.assertEqual(x.unit, units.kg) self.assertEqual(len(x), 6) - self.assertAlmostRelativeEquals(x, [1000,2000,3000,1,2,3] | units.g) + self.assertAlmostRelativeEquals(x, [1000, 2000, 3000, 1, 2, 3] | units.g) def test4(self): x = AdaptingVectorQuantity() @@ -479,23 +473,24 @@ def test4(self): def test5(self): # Everything mixed... x = AdaptingVectorQuantity() - x.extend([3,4,5] | units.kg) + x.extend([3, 4, 5] | units.kg) x.append(6 | units.kg) x.prepend(2 | units.kg) - x.extend([7000,8000,9000] | units.g) + x.extend([7000, 8000, 9000] | units.g) x.prepend(1000 | units.g) x.append(10000 | units.g) self.assertEqual(x.unit, units.kg) self.assertEqual(len(x), 10) - self.assertEqual(x.number, numpy.array([1,2,3,4,5,6,7,8,9,10])) - self.assertEqual(x, [1,2,3,4,5,6,7,8,9,10]|units.kg) + self.assertEqual(x.number, numpy.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) + self.assertEqual(x, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | units.kg) def test6(self): - x = 6 | units.kg - y = 5 | units.kg - self.assertEqual(x/y, 6/5) - self.assertEqual(x//y, 6//5) - self.assertEqual(operator.__truediv__(x,y), 1.2) + x = 6 | units.kg + y = 5 | units.kg + self.assertEqual(x/y, 6/5) + self.assertEqual(x//y, 6//5) + self.assertEqual(operator.__truediv__(x, y), 1.2) + class TestNumpyFunctionWithUnits(amusetest.TestCase): @@ -504,21 +499,19 @@ def test1(self): self.assertEqual(len(array), 10) self.assertAlmostRelativeEquals(array, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | units.kg) - def test2(self): array = quantities.linspace(0 | units.kg, 10 | units.kg, 11) self.assertEqual(len(array), 11) self.assertAlmostRelativeEquals(array, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | units.kg) - def test3(self): - array = quantities.linspace(0 , 10 , 11) + array = quantities.linspace(0, 10, 11) self.assertEqual(len(array), 11) self.assertAlmostRelativeEquals(array, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) def test4(self): x = quantities.arange(0 | units.yr, 10 | units.yr, 1 | units.yr) - y = (2.0|units.km) * (x/ (2.0|units.yr))**2 + (20.0|units.km) + y = (2.0 | units.km) * (x / (2.0 | units.yr))**2 + (20.0 | units.km) fit = quantities.polyfit(x, y, 2) @@ -533,12 +526,10 @@ def test4(self): self.assertAlmostRelativeEquals(y, fit_values, 1) def test5(self): - a=[1,2,3] | units.m - b=[4,5,6] | units.m - - ab1=quantities.column_stack((a,b)) - ab2=quantities.column_stack((a.number,b.number)) | units.m - - self.assertEqual(ab1,ab2) - + a = [1, 2, 3] | units.m + b = [4, 5, 6] | units.m + + ab1 = quantities.column_stack((a, b)) + ab2 = quantities.column_stack((a.number, b.number)) | units.m + self.assertEqual(ab1, ab2) diff --git a/src/amuse/test/suite/core_tests/test_rotation.py b/src/amuse/test/suite/core_tests/test_rotation.py index 5b48ea2ccd..ca0eff8d0a 100644 --- a/src/amuse/test/suite/core_tests/test_rotation.py +++ b/src/amuse/test/suite/core_tests/test_rotation.py @@ -9,66 +9,68 @@ from amuse.datamodel import rotation from amuse.datamodel import particles + class TestRotations(amusetest.TestCase): def test01(self): - x = rotation.new_rotation_matrix(0,0,0) - self.assertAlmostRelativeEquals(x, ((1,0,0),(0,1,0),(0,0,1))) + x = rotation.new_rotation_matrix(0, 0, 0) + self.assertAlmostRelativeEquals(x, ((1, 0, 0), (0, 1, 0), (0, 0, 1))) - x = rotation.new_rotation_matrix(numpy.pi,0,0) + x = rotation.new_rotation_matrix(numpy.pi, 0, 0) print(x) - self.assertAlmostRelativeEquals(x, ((1,0,0),(0,-1,0),(0,0,-1))) - x = rotation.new_rotation_matrix(0,numpy.pi,0) - self.assertAlmostRelativeEquals(x, ((-1,0,0),(0,1,0),(0,0,-1))) + self.assertAlmostRelativeEquals(x, ((1, 0, 0), (0, -1, 0), (0, 0, -1))) + x = rotation.new_rotation_matrix(0, numpy.pi, 0) + self.assertAlmostRelativeEquals(x, ((-1, 0, 0), (0, 1, 0), (0, 0, -1))) x = rotation.new_rotation_matrix(0, 0, numpy.pi) - self.assertAlmostRelativeEquals(x, ((-1,0,0),(0,-1,0),(0,0,1))) + self.assertAlmostRelativeEquals(x, ((-1, 0, 0), (0, -1, 0), (0, 0, 1))) + def test02(self): - x = rotation.new_rotation_matrix(numpy.pi / 2.0,0,0) + x = rotation.new_rotation_matrix(numpy.pi / 2.0, 0, 0) print(x) - self.assertAlmostRelativeEquals(x, ((1,0,0),(0,0, -1),(0,1,0))) - x = rotation.new_rotation_matrix(0,numpy.pi / 2.0,0) + self.assertAlmostRelativeEquals(x, ((1, 0, 0), (0, 0, -1), (0, 1, 0))) + x = rotation.new_rotation_matrix(0, numpy.pi / 2.0, 0) print(x) - self.assertAlmostRelativeEquals(x, ((0,0,1),(0,1,0),(-1,0,0))) + self.assertAlmostRelativeEquals(x, ((0, 0, 1), (0, 1, 0), (-1, 0, 0))) x = rotation.new_rotation_matrix(0, 0, numpy.pi / 2.0) print(x) - self.assertAlmostRelativeEquals(x, ((0,-1,0),(1,0,0),(0,0,1))) - x = rotation.new_rotation_matrix(numpy.pi / 2.0,numpy.pi / 2.0,0) + self.assertAlmostRelativeEquals(x, ((0, -1, 0), (1, 0, 0), (0, 0, 1))) + x = rotation.new_rotation_matrix(numpy.pi / 2.0, numpy.pi / 2.0, 0) print(x) - self.assertAlmostRelativeEquals(x, ((0,1,0),(0,0,-1),(-1,0,0))) + self.assertAlmostRelativeEquals(x, ((0, 1, 0), (0, 0, -1), (-1, 0, 0))) def test03(self): - positions = [ [1.0, 2.0, 3.0 ] ] | units.m + positions = [[1.0, 2.0, 3.0]] | units.m rotated = rotation.rotated(positions, 0.0, 0.0, 0.0) - + print(rotated) - - self.assertAlmostRelativeEquals(rotated, [ [1.0, 2.0, 3.0 ] ] | units.m) + + self.assertAlmostRelativeEquals(rotated, [[1.0, 2.0, 3.0]] | units.m) rotated = rotation.rotated(positions, numpy.pi, 0.0, 0.0) - + print(rotated) - - self.assertAlmostRelativeEquals(rotated, [ [1.0, -2.0, -3.0 ] ] | units.m) + + self.assertAlmostRelativeEquals(rotated, [[1.0, -2.0, -3.0]] | units.m) def test04(self): - positions = [ [1.0, 2.0, 3.0 ] , [4.0, 5.0, 6.0] ] | units.m + positions = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] | units.m rotated = rotation.rotated(positions, 0.0, 0.0, 0.0) - + print(rotated) - - self.assertAlmostRelativeEquals(rotated, [ [1.0, 2.0, 3.0 ], [4.0, 5.0, 6.0] ] | units.m) - + + self.assertAlmostRelativeEquals(rotated, [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] | units.m) + rotated = rotation.rotated(positions, numpy.pi, 0.0, 0.0) print(rotated) - - self.assertAlmostRelativeEquals(rotated, [ [1.0, -2.0, -3.0 ], [4.0, -5.0, -6.0] ] | units.m) + + self.assertAlmostRelativeEquals(rotated, [[1.0, -2.0, -3.0], [4.0, -5.0, -6.0]] | units.m) def test05(self): - positions = [ [1.0, 2.0, 3.0 ] , [4.0, 5.0, 6.0] ] | units.m + positions = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] | units.m rotated = rotation.rotated(positions, numpy.pi/2, 0.0, 0.0) - + print(rotated) - - self.assertAlmostRelativeEquals(rotated, [ [1.0, -3.0, 2.0 ], [4.0, -6.0, 5.0] ] | units.m) + + self.assertAlmostRelativeEquals(rotated, [[1.0, -3.0, 2.0], [4.0, -6.0, 5.0]] | units.m) def test06(self): particles = new_plummer_model(100) @@ -76,8 +78,7 @@ def test06(self): potential_energy0 = particles.potential_energy(G=nbody_system.G) particles.position = rotation.rotated(particles.position, numpy.pi/2, 0.0, 0.0) particles.velocity = rotation.rotated(particles.velocity, numpy.pi/2, 0.0, 0.0) - - + kinetic_energy1 = particles.kinetic_energy() potential_energy1 = particles.potential_energy(G=nbody_system.G) self.assertAlmostRelativeEquals(kinetic_energy1, kinetic_energy0) @@ -89,103 +90,95 @@ def test07(self): potential_energy0 = particles.potential_energy(G=nbody_system.G) particles.position = rotation.rotated(particles.position, numpy.pi/3, numpy.pi/2, 0.0) particles.velocity = rotation.rotated(particles.velocity, numpy.pi/3, numpy.pi/2, 0.0) - - + kinetic_energy1 = particles.kinetic_energy() potential_energy1 = particles.potential_energy(G=nbody_system.G) self.assertAlmostRelativeEquals(kinetic_energy1, kinetic_energy0) self.assertAlmostRelativeEquals(potential_energy1, potential_energy0) - + def test08(self): particles = new_plummer_model(100) kinetic_energy0 = particles.kinetic_energy() potential_energy0 = particles.potential_energy(G=nbody_system.G) - + particles.move_to_center() particles.position += [3, 0, 2] | nbody_system.length particles.rotate(numpy.pi/4, numpy.pi/2, 0.0) - self.assertAlmostRelativeEquals(particles.center_of_mass(), + self.assertAlmostRelativeEquals(particles.center_of_mass(), [numpy.sqrt(2), -numpy.sqrt(2), -3] | nbody_system.length, 7) - + kinetic_energy1 = particles.kinetic_energy() potential_energy1 = particles.potential_energy(G=nbody_system.G) self.assertAlmostRelativeEquals(kinetic_energy1, kinetic_energy0) self.assertAlmostRelativeEquals(potential_energy1, potential_energy0) - + def test09(self): print("Test add_spin particle attribute, to add rigid body rotation") numpy.random.seed(123456) particles = new_plummer_model(1000) kinetic_energy0 = particles.kinetic_energy() potential_energy0 = particles.potential_energy(G=nbody_system.G) - + particles.position += [3, 0, 2] | nbody_system.length particles.velocity += [1, 10, 100] | nbody_system.speed particles.add_spin(3.0 | nbody_system.time**-1) - + self.assertAlmostRelativeEquals(particles.center_of_mass(), [3, 0, 2] | nbody_system.length, 12) self.assertAlmostRelativeEquals(particles.potential_energy(G=nbody_system.G), potential_energy0, 12) self.assertAlmostRelativeEquals(particles.center_of_mass_velocity(), [1, 10, 100] | nbody_system.speed, 12) - + r = particles.position - particles.center_of_mass() v = particles.velocity - particles.center_of_mass_velocity() spin_direction = (r).cross(v).mean(axis=0) spin_direction /= spin_direction.length() R = r - r*spin_direction - omega = ((R).cross(v) / R.lengths_squared().reshape((-1,1))).mean(axis=0).length() + omega = ((R).cross(v) / R.lengths_squared().reshape((-1, 1))).mean(axis=0).length() self.assertAlmostEqual(spin_direction, [0, 0, 1.0], 1) self.assertAlmostEqual(omega, 3.0 | nbody_system.time**-1, 1) - + particles.add_spin([1.0, 0, -3.0] | nbody_system.time**-1) v = particles.velocity - particles.center_of_mass_velocity() spin_direction = (r).cross(v).mean(axis=0) spin_direction /= spin_direction.length() R = r - r*spin_direction - omega = ((R).cross(v) / R.lengths_squared().reshape((-1,1))).mean(axis=0).length() + omega = ((R).cross(v) / R.lengths_squared().reshape((-1, 1))).mean(axis=0).length() self.assertAlmostEqual(omega, 1.0 | nbody_system.time**-1, 1) - + def test10(self): print("test conservation of dot, transformation of cross") - p=particles.Particles(1) - p.position=[1.,2.,3.] - p.velocity=[-4,5,6.] - - dot1=p[0].position.dot(p[0].velocity) - cross1=numpy.cross(p[0].position,p[0].velocity) - - rm=rotation.new_rotation_matrix(0.1,0.5,3.5) - p.rotate(0.1,0.5,3.5) - - dot2=p[0].position.dot(p[0].velocity) - cross2=numpy.cross(p[0].position,p[0].velocity) - - self.assertAlmostRelativeEquals(dot1,dot2) - self.assertAlmostRelativeEquals(cross2,cross1.dot(numpy.linalg.inv(rm))) + p = particles.Particles(1) + p.position = [1., 2., 3.] + p.velocity = [-4, 5, 6.] + + dot1 = p[0].position.dot(p[0].velocity) + cross1 = numpy.cross(p[0].position, p[0].velocity) + + rm = rotation.new_rotation_matrix(0.1, 0.5, 3.5) + p.rotate(0.1, 0.5, 3.5) + + dot2 = p[0].position.dot(p[0].velocity) + cross2 = numpy.cross(p[0].position, p[0].velocity) + + self.assertAlmostRelativeEquals(dot1, dot2) + self.assertAlmostRelativeEquals(cross2, cross1.dot(numpy.linalg.inv(rm))) def test11(self): print("test conservation of dot, transformation of cross with units") - p=particles.Particles(5) - p.position=[1.,2.,3.] | units.km - p.velocity=[-4,5,6.] | units.kms - - p[1:].position*=0 - p[1:].velocity*=0 - - dot1=p[0].position.dot(p[0].velocity) - cross1=p[0].position.cross(p[0].velocity) - - rm=rotation.new_rotation_matrix(0.1,0.5,3.5) - p.rotate(0.1,0.5,3.5) - - dot2=p[0].position.dot(p[0].velocity) - cross2=p[0].position.cross(p[0].velocity) - - self.assertAlmostRelativeEquals(dot1.value_in(units.km**2/units.s),dot2.value_in(units.km**2/units.s)) - self.assertAlmostRelativeEquals(cross2.value_in(units.km**2/units.s),cross1.dot(numpy.linalg.inv(rm)).value_in(units.km**2/units.s)) - - - - - - + p = particles.Particles(5) + p.position = [1., 2., 3.] | units.km + p.velocity = [-4, 5, 6.] | units.kms + + p[1:].position *= 0 + p[1:].velocity *= 0 + + dot1 = p[0].position.dot(p[0].velocity) + cross1 = p[0].position.cross(p[0].velocity) + + rm = rotation.new_rotation_matrix(0.1, 0.5, 3.5) + p.rotate(0.1, 0.5, 3.5) + + dot2 = p[0].position.dot(p[0].velocity) + cross2 = p[0].position.cross(p[0].velocity) + self.assertAlmostRelativeEquals(dot1.value_in(units.km**2/units.s), dot2.value_in(units.km**2/units.s)) + self.assertAlmostRelativeEquals(cross2.value_in(units.km**2/units.s), cross1.dot(numpy.linalg.inv(rm)).value_in(units.km**2/units.s)) diff --git a/src/amuse/test/suite/core_tests/test_scaling_converter.py b/src/amuse/test/suite/core_tests/test_scaling_converter.py index 26cad354fa..89f94362c8 100644 --- a/src/amuse/test/suite/core_tests/test_scaling_converter.py +++ b/src/amuse/test/suite/core_tests/test_scaling_converter.py @@ -3,23 +3,23 @@ from amuse.test import amusetest + class TestScalingConverter(amusetest.TestCase): def test1(self): converter = scaling_converter.ScalingConverter( - length = 0.2, - time = 0.1, + length=0.2, + time=0.1, ) input = 1 | nbody_system.time output = converter.convert(input) self.assertAlmostRelativeEquals(output, 0.1 | nbody_system.time) - - + def test2(self): converter = scaling_converter.ScalingConverter( - length = 0.2, - time = 0.1, + length=0.2, + time=0.1, ) input = 1 | nbody_system.length ** 2 output = converter.convert(input) - self.assertAlmostRelativeEquals(output, 0.2 * 0.2 | nbody_system.length ** 2) \ No newline at end of file + self.assertAlmostRelativeEquals(output, 0.2 * 0.2 | nbody_system.length ** 2) diff --git a/src/amuse/test/suite/core_tests/test_staggeredgrid.py b/src/amuse/test/suite/core_tests/test_staggeredgrid.py index 6b590cfb43..eb8d913e4f 100644 --- a/src/amuse/test/suite/core_tests/test_staggeredgrid.py +++ b/src/amuse/test/suite/core_tests/test_staggeredgrid.py @@ -7,28 +7,28 @@ from amuse.datamodel.grids import * from amuse.datamodel.staggeredgrid import StaggeredGrid -class TestStaggeredGrid(amusetest.TestCase): +class TestStaggeredGrid(amusetest.TestCase): - #create a structured staggered grid with a nodes grid that is 1 grid-point larger in each dimension - #remap the values from elements to nodes and back and check sum + # create a structured staggered grid with a nodes grid that is 1 grid-point larger in each dimension + # remap the values from elements to nodes and back and check sum def test1(self): - #generate corners for a simple structured grid - shape = [5,5] - ind = numpy.indices( (shape[0]+1,shape[1]+1)) - lats = numpy.array( ind[0] , dtype=numpy.float64) + # generate corners for a simple structured grid + shape = [5, 5] + ind = numpy.indices((shape[0]+1, shape[1]+1)) + lats = numpy.array(ind[0], dtype=numpy.float64) lats = (0.5-lats/shape[1]) * numpy.pi lats[0] = lats[0] - 1e-14 - lats = lats[::-1,:] - lons = numpy.array( ind[1] , dtype=numpy.float64) + lats = lats[::-1, :] + lons = numpy.array(ind[1], dtype=numpy.float64) lons = lons/ind.shape[1] * 2.0*numpy.pi - corners = numpy.array([lons,lats]) + corners = numpy.array([lons, lats]) elements = new_structured_grid(shape, corners, axes_names=['lon', 'lat']) - #let the north east corners of each cell be the position of the nodes - positions = numpy.array([lons[1:,1:], lats[1:,1:]]) + # let the north east corners of each cell be the position of the nodes + positions = numpy.array([lons[1:, 1:], lats[1:, 1:]]) nodes = StructuredGrid(*ind[0].shape) nodes.lat = (lats | units.rad) @@ -49,30 +49,30 @@ def test1(self): self.assertEqual(after_sum, before_sum, msg="Sum of values before and after remapping should be the same") + # create a structured staggered grid with a nodes grid that is of the same size in each dimension + # remap the values from elements to nodes and back and check sum - #create a structured staggered grid with a nodes grid that is of the same size in each dimension - #remap the values from elements to nodes and back and check sum def test2(self): - #generate corners for a simple structured grid - shape = [5,5] - ind = numpy.indices( (shape[0]+1,shape[1]+1)) - lats = numpy.array( ind[0] , dtype=numpy.float64) + # generate corners for a simple structured grid + shape = [5, 5] + ind = numpy.indices((shape[0]+1, shape[1]+1)) + lats = numpy.array(ind[0], dtype=numpy.float64) lats = (0.5-lats/shape[1]) * numpy.pi lats[0] = lats[0] - 1e-14 - lats = lats[::-1,:] - lons = numpy.array( ind[1] , dtype=numpy.float64) + lats = lats[::-1, :] + lons = numpy.array(ind[1], dtype=numpy.float64) lons = lons/ind.shape[1] * 2.0*numpy.pi - corners = numpy.array([lons,lats]) + corners = numpy.array([lons, lats]) elements = new_structured_grid(shape, corners, axes_names=['lon', 'lat']) - #let the north east corners of each cell be the position of the nodes - positions = numpy.array([lons[1:,1:], lats[1:,1:]]) + # let the north east corners of each cell be the position of the nodes + positions = numpy.array([lons[1:, 1:], lats[1:, 1:]]) nodes = StructuredGrid(*shape) - nodes.lat = (lats[1:,1:] | units.rad) - nodes.lon = (lons[1:,1:] | units.rad) + nodes.lat = (lats[1:, 1:] | units.rad) + nodes.lon = (lons[1:, 1:] | units.rad) grid = StaggeredGrid(elements, nodes, get_corners=lambda: numpy.array([lons, lats])) @@ -88,13 +88,12 @@ def test2(self): self.assertEqual(after_sum, before_sum, msg="Sum of values before and after remapping should be the same") + # create an unstructured staggered grid - - #create an unstructured staggered grid def test3(self): - #define nodal points and triangles of a small test grid - #got this grid from http://matplotlib.org/examples/pylab_examples/triplot_demo.html + # define nodal points and triangles of a small test grid + # got this grid from http://matplotlib.org/examples/pylab_examples/triplot_demo.html xy = numpy.asarray([ [-0.101, 0.872], [-0.080, 0.883], [-0.069, 0.888], [-0.054, 0.890], [-0.045, 0.897], [-0.057, 0.895], [-0.073, 0.900], [-0.087, 0.898], @@ -108,19 +107,19 @@ def test3(self): [-0.052, 1.022], [-0.052, 1.017], [-0.069, 1.010], [-0.064, 1.005], [-0.048, 1.005], [-0.031, 1.005], [-0.031, 0.996], [-0.040, 0.987], [-0.045, 0.980], [-0.052, 0.975], [-0.040, 0.973], [-0.026, 0.968], - [-0.020, 0.954], [-0.006, 0.947], [ 0.003, 0.935], [ 0.006, 0.926], - [ 0.005, 0.921], [ 0.022, 0.923], [ 0.033, 0.912], [ 0.029, 0.905], - [ 0.017, 0.900], [ 0.012, 0.895], [ 0.027, 0.893], [ 0.019, 0.886], - [ 0.001, 0.883], [-0.012, 0.884], [-0.029, 0.883], [-0.038, 0.879], + [-0.020, 0.954], [-0.006, 0.947], [0.003, 0.935], [0.006, 0.926], + [0.005, 0.921], [0.022, 0.923], [0.033, 0.912], [0.029, 0.905], + [0.017, 0.900], [0.012, 0.895], [0.027, 0.893], [0.019, 0.886], + [0.001, 0.883], [-0.012, 0.884], [-0.029, 0.883], [-0.038, 0.879], [-0.057, 0.881], [-0.062, 0.876], [-0.078, 0.876], [-0.087, 0.872], [-0.030, 0.907], [-0.007, 0.905], [-0.057, 0.916], [-0.025, 0.933], [-0.077, 0.990], [-0.059, 0.993]]) triangles = numpy.asarray([ - [67, 66, 1], [65, 2, 66], [ 1, 66, 2], [64, 2, 65], [63, 3, 64], - [60, 59, 57], [ 2, 64, 3], [ 3, 63, 4], [ 0, 67, 1], [62, 4, 63], - [57, 59, 56], [59, 58, 56], [61, 60, 69], [57, 69, 60], [ 4, 62, 68], - [ 6, 5, 9], [61, 68, 62], [69, 68, 61], [ 9, 5, 70], [ 6, 8, 7], - [ 4, 70, 5], [ 8, 6, 9], [56, 69, 57], [69, 56, 52], [70, 10, 9], + [67, 66, 1], [65, 2, 66], [1, 66, 2], [64, 2, 65], [63, 3, 64], + [60, 59, 57], [2, 64, 3], [3, 63, 4], [0, 67, 1], [62, 4, 63], + [57, 59, 56], [59, 58, 56], [61, 60, 69], [57, 69, 60], [4, 62, 68], + [6, 5, 9], [61, 68, 62], [69, 68, 61], [9, 5, 70], [6, 8, 7], + [4, 70, 5], [8, 6, 9], [56, 69, 57], [69, 56, 52], [70, 10, 9], [54, 53, 55], [56, 55, 53], [68, 70, 4], [52, 56, 53], [11, 10, 12], [69, 71, 68], [68, 13, 70], [10, 70, 13], [51, 50, 52], [13, 68, 71], [52, 71, 69], [12, 10, 13], [71, 52, 50], [71, 14, 13], [50, 49, 71], @@ -133,16 +132,15 @@ def test3(self): [42, 41, 40], [72, 33, 31], [32, 31, 33], [39, 38, 72], [33, 72, 38], [33, 38, 34], [37, 35, 38], [34, 38, 35], [35, 37, 36]]) - num_elems = len(triangles) elements = UnstructuredGrid(num_elems) - elements.n1 = triangles[:,0] - 1 - elements.n2 = triangles[:,1] - 1 - elements.n3 = triangles[:,2] - 1 + elements.n1 = triangles[:, 0] - 1 + elements.n2 = triangles[:, 1] - 1 + elements.n3 = triangles[:, 2] - 1 nodes = UnstructuredGrid(len(xy)) - nodes.lon = (xy[:,0] | units.rad) - nodes.lat = (xy[:,1] | units.rad) + nodes.lon = (xy[:, 0] | units.rad) + nodes.lat = (xy[:, 1] | units.rad) grid = StaggeredGrid(elements, nodes) @@ -157,14 +155,3 @@ def test3(self): after_sum = remapped_values.sum() self.assertAlmostEqual(after_sum, before_sum, msg="Sum of values before and after remapping should be the same") - - - - - - - - - - - diff --git a/src/amuse/test/suite/core_tests/test_starlab.py b/src/amuse/test/suite/core_tests/test_starlab.py index a588e05a54..594c7d38eb 100644 --- a/src/amuse/test/suite/core_tests/test_starlab.py +++ b/src/amuse/test/suite/core_tests/test_starlab.py @@ -190,11 +190,12 @@ )Particle """ + class Test(amusetest.TestCase): def test1(self): """test_starlab.test1 - + +---------------------------------------------------------------------+ | Particle tree of test_subub.dyn | | | @@ -219,51 +220,53 @@ def test1(self): """ directory = os.path.dirname(__file__) - convert_nbody = nbody_system.nbody_to_si(1|units.kg, 1|units.m) + convert_nbody = nbody_system.nbody_to_si(1 | units.kg, 1 | units.m) I = starlab.ParticlesFromDyn(os.path.join(directory, 'test_subsub.dyn')) All = I.Particles self.assertEqual(len(All), 7) - self.assertEqual(len(All[0].descendents()),6) + self.assertEqual(len(All[0].descendents()), 6) self.assertEqual(All[0].children().mass.value_in(nbody_system.mass)[0], 8.0) self.assertEqual(All[1].children().mass.value_in(nbody_system.mass)[0], 4.0) self.assertEqual(All[5].children().mass.value_in(nbody_system.mass)[0], 2.0) def test2(self): directory = os.path.dirname(__file__) - convert_nbody = nbody_system.nbody_to_si(1|units.kg, 1|units.m) + convert_nbody = nbody_system.nbody_to_si(1 | units.kg, 1 | units.m) I = starlab.ParticlesFromDyn(os.path.join(directory, 'test_subsub.dyn'), convert_nbody) All = I.Particles self.assertEqual(len(All), 7) - self.assertEqual(len(All[0].descendents()),6) + self.assertEqual(len(All[0].descendents()), 6) self.assertEqual(All[0].children().mass.value_in(units.kg)[0], 8.0) self.assertEqual(All[1].children().mass.value_in(units.kg)[0], 4.0) self.assertEqual(All[5].children().mass.value_in(units.kg)[0], 2.0) - + def test3(self): directory = os.path.dirname(__file__) set = io.read_set_from_file(os.path.join(directory, 'plummer.dyn'), 'starlab') self.assertEqual(len(set), 10) self.assertAlmostRelativeEquals(set.mass, 0.1 | nbody_system.mass) - + def test4(self): - set = starlab.StarlabFileFormatProcessor().load_string(plummer_scaled_content) - self.assertEqual(len(set), 5) - print(set.mass.as_quantity_in(units.MSun)) - self.assertTrue(numpy.all(set.mass > 0.2 |units.MSun)) - self.assertTrue(numpy.all(set.mass < 1.1 |units.MSun)) - self.assertTrue(numpy.all(set.x > -1 | units.parsec)) - self.assertTrue(numpy.all(set.x < 1 | units.parsec)) - self.assertTrue(numpy.all(set.y > -1 | units.parsec)) - self.assertTrue(numpy.all(set.y < 1 | units.parsec)) - self.assertTrue(numpy.all(set.z > -1 | units.parsec)) - self.assertTrue(numpy.all(set.z < 1 | units.parsec)) - + particle_set = starlab.StarlabFileFormatProcessor().load_string(plummer_scaled_content) + self.assertEqual(len(particle_set), 5) + print(particle_set.mass.as_quantity_in(units.MSun)) + print(particle_set.mass.as_quantity_in(units.kg)) + print(particle_set) + self.assertTrue(numpy.all(particle_set.mass > 0.2 | units.MSun)) + self.assertTrue(numpy.all(particle_set.mass < 1.1 | units.MSun)) + self.assertTrue(numpy.all(particle_set.x > -1 | units.parsec)) + self.assertTrue(numpy.all(particle_set.x < 1 | units.parsec)) + self.assertTrue(numpy.all(particle_set.y > -1 | units.parsec)) + self.assertTrue(numpy.all(particle_set.y < 1 | units.parsec)) + self.assertTrue(numpy.all(particle_set.z > -1 | units.parsec)) + self.assertTrue(numpy.all(particle_set.z < 1 | units.parsec)) + def test5(self): set = starlab.StarlabFileFormatProcessor().load_string(with_stellar_structure) self.assertEqual(len(set), 2) @@ -274,29 +277,28 @@ def test5(self): self.assertAlmostRelativeEquals(set[0].effective_luminocity, 0.00122847524117014736 | units.LSun) self.assertAlmostRelativeEquals(set[0].stellar_type, units.stellar_type("Main Sequence star")) self.assertAlmostRelativeEquals(set[1].relative_mass, set[1].mass, 10) - + def test6(self): directory = os.path.dirname(__file__) set = io.read_set_from_file(os.path.join(directory, 'evolved.dyn'), 'starlab') self.assertEqual(len(set), 20) - - self.assertAlmostRelativeEquals(set.time, set.age, 4) #only accurate to 4, starlab stellar evolution time scale? - + + self.assertAlmostRelativeEquals(set.time, set.age, 4) # only accurate to 4, starlab stellar evolution time scale? + self.assertAlmostRelativeEquals(set[0].velocity, [177.579717905, 38.5027308364, -35.8571344243] | units.km / units.hour, 8) self.assertAlmostRelativeEquals(set[0].acceleration, [-0.000648471729782, 0.000309476774701, -0.000356623346185] | units.parsec / (units.Myr ** 2), 8) self.assertAlmostRelativeEquals(set.unconverted_set()[0].specific_potential, -0.32735384622167929 | nbody_system.potential) - #select the main sequence star, the dwarf masses don't match - main_sequence_stars = set.select(lambda stellar_type : stellar_type == units.stellar_type("Main Sequence star"), ["stellar_type"]) + # select the main sequence star, the dwarf masses don't match + main_sequence_stars = set.select(lambda stellar_type: stellar_type == units.stellar_type("Main Sequence star"), ["stellar_type"]) self.assertAlmostRelativeEquals(main_sequence_stars.mass, main_sequence_stars.relative_mass, 10) - carbon_dwarfs = set.select(lambda stellar_type : stellar_type == units.stellar_type("Carbon/Oxygen White Dwarf") , ["stellar_type"]) + carbon_dwarfs = set.select(lambda stellar_type: stellar_type == units.stellar_type("Carbon/Oxygen White Dwarf"), ["stellar_type"]) self.assertAlmostRelativeEquals(carbon_dwarfs.mass, carbon_dwarfs.core_mass, 10) - + def test7(self): directory = os.path.dirname(__file__) - set, converter = io.read_set_from_file(os.path.join(directory, 'evolved.dyn'), 'starlab', return_converter = True) + set, converter = io.read_set_from_file(os.path.join(directory, 'evolved.dyn'), 'starlab', return_converter=True) self.assertEqual(len(set), 20) - - unconverted_set = io.read_set_from_file(os.path.join(directory, 'evolved.dyn'), 'starlab', must_scale = False) + + unconverted_set = io.read_set_from_file(os.path.join(directory, 'evolved.dyn'), 'starlab', must_scale=False) self.assertEqual(len(unconverted_set), 20) self.assertAlmostRelativeEquals(converter.to_nbody(set.x), unconverted_set.x) - diff --git a/src/amuse/test/suite/core_tests/test_stopping_conditions.py b/src/amuse/test/suite/core_tests/test_stopping_conditions.py index d45305ec8d..54df19ed4d 100644 --- a/src/amuse/test/suite/core_tests/test_stopping_conditions.py +++ b/src/amuse/test/suite/core_tests/test_stopping_conditions.py @@ -8,18 +8,17 @@ class TestStoppingCondition(amusetest.TestCase): - def test1(self): - + class AllEnabled(object): - + def is_stopping_condition_enabled(self, sc_type): return 1 - + def has_stopping_condition(self, sc_type): return 1 - + instance = StoppingConditions(AllEnabled()) self.assertTrue(instance.collision_detection.is_supported()) self.assertTrue(instance.collision_detection.is_enabled()) @@ -27,17 +26,17 @@ def has_stopping_condition(self, sc_type): self.assertTrue(instance.escaper_detection.is_enabled()) self.assertTrue(instance.timeout_detection.is_supported()) self.assertTrue(instance.timeout_detection.is_enabled()) - + def test2(self): - + class OneEnabled(object): - + def is_stopping_condition_enabled(self, sc_type): return 1 if sc_type == 0 else 0 - + def has_stopping_condition(self, sc_type): return 1 if sc_type == 0 else 0 - + instance = StoppingConditions(OneEnabled()) self.assertTrue(instance.collision_detection.is_supported()) self.assertTrue(instance.collision_detection.is_enabled()) @@ -45,50 +44,47 @@ def has_stopping_condition(self, sc_type): self.assertFalse(instance.escaper_detection.is_enabled()) self.assertFalse(instance.timeout_detection.is_supported()) self.assertFalse(instance.timeout_detection.is_enabled()) - - + def test3(self): - + class OneSettable(object): is_enabled = 0 - + def is_stopping_condition_enabled(self, sc_type): return self.is_enabled if sc_type == 0 else 0 - + def has_stopping_condition(self, sc_type): return 1 if sc_type == 0 else 0 - + def enable_stopping_condition(self, sc_type): if sc_type == 0: self.is_enabled = 1 - + instance = StoppingConditions(OneSettable()) self.assertTrue(instance.collision_detection.is_supported()) self.assertFalse(instance.collision_detection.is_enabled()) instance.collision_detection.enable() self.assertTrue(instance.collision_detection.is_enabled()) - - - + def test4(self): - + class OneSettable(object): is_enabled = 0 - + def is_stopping_condition_enabled(self, sc_type): return self.is_enabled if sc_type == 0 else 0 - + def has_stopping_condition(self, sc_type): return 1 if sc_type == 0 else 0 - + def enable_stopping_condition(self, sc_type): if sc_type == 0: self.is_enabled = 1 - + def disable_stopping_condition(self, sc_type): if sc_type == 0: self.is_enabled = 0 - + instance = StoppingConditions(OneSettable()) self.assertTrue(instance.collision_detection.is_supported()) self.assertFalse(instance.collision_detection.is_enabled()) @@ -96,88 +92,86 @@ def disable_stopping_condition(self, sc_type): self.assertTrue(instance.collision_detection.is_enabled()) instance.collision_detection.disable() self.assertFalse(instance.collision_detection.is_enabled()) - + def test5(self): - + class OneEnabled(object): - + def is_stopping_condition_enabled(self, sc_type): return 1 if sc_type == 0 else 0 - + def has_stopping_condition(self, sc_type): return 1 if sc_type == 0 else 0 - + instance = StoppingConditions(OneEnabled()) self.assertFalse(instance.escaper_detection.is_supported()) self.assertFalse(instance.escaper_detection.is_enabled()) self.assertRaises(AmuseException, instance.escaper_detection.enable) self.assertRaises(AmuseException, instance.escaper_detection.disable) - - + def test6(self): - + class Collision(object): - + def is_stopping_condition_enabled(self, sc_type): return 1 if sc_type == 0 else 0 - + def has_stopping_condition(self, sc_type): return 1 if sc_type == 0 else 0 - + def is_stopping_condition_set(self, sc_type): return 1 if sc_type == 0 else 0 - + def get_number_of_stopping_conditions_set(self): return 1 - + def get_stopping_condition_info(self, indices): - return [0],[1] - + return [0], [1] + instance = StoppingConditions(Collision()) instance.code.particles = datamodel.Particles(3) - instance.code.particles.mass = (1,2,3) | units.kg + instance.code.particles.mass = (1, 2, 3) | units.kg instance.code.particles.add_function_attribute( "get_stopping_condition_particle_index", - lambda particles, indices, sc_type : particles[indices] + lambda particles, indices, sc_type: particles[indices] ) self.assertTrue(instance.collision_detection.is_set()) particles = instance.collision_detection.particles(0) - self.assertEqual(len(particles),1) - self.assertAlmostRelativeEqual(particles[0].mass, 1|units.kg) - - + self.assertEqual(len(particles), 1) + self.assertAlmostRelativeEqual(particles[0].mass, 1 | units.kg) + def test7(self): - + class Collision(object): - + def is_stopping_condition_enabled(self, sc_type): return 1 if sc_type == 0 else 0 - + def has_stopping_condition(self, sc_type): return 1 if sc_type == 0 else 0 - + def is_stopping_condition_set(self, sc_type): return 1 if sc_type == 0 else 0 - + def get_number_of_stopping_conditions_set(self): return 1 - + def get_stopping_condition_info(self, indices): - return [0],[3] - + return [0], [3] + instance = StoppingConditions(Collision()) instance.code.particles = datamodel.Particles(3) - instance.code.particles.mass = (1,2,3) | units.kg + instance.code.particles.mass = (1, 2, 3) | units.kg instance.code.particles.add_function_attribute( "get_stopping_condition_particle_index", - lambda particles, indices, sc_type : particles[indices] + lambda particles, indices, sc_type: particles[indices] ) self.assertTrue(instance.collision_detection.is_set()) particles = instance.collision_detection.particles(0) - self.assertEqual(len(particles),1) + self.assertEqual(len(particles), 1) particles = instance.collision_detection.particles(1) - self.assertEqual(len(particles),1) + self.assertEqual(len(particles), 1) particles = instance.collision_detection.particles(2) - self.assertEqual(len(particles),1) + self.assertEqual(len(particles), 1) particles = instance.collision_detection.particles(3) - self.assertEqual(len(particles),0) + self.assertEqual(len(particles), 0) diff --git a/src/amuse/test/suite/core_tests/test_store.py b/src/amuse/test/suite/core_tests/test_store.py index 7b829bd40e..d6532a8145 100644 --- a/src/amuse/test/suite/core_tests/test_store.py +++ b/src/amuse/test/suite/core_tests/test_store.py @@ -16,16 +16,14 @@ from amuse.datamodel import ParticlesSuperset - - class _AbstractTestStoreHDF(object): - + def store_factory(self): raise NotImplementedError - + def store_version(self): raise NotImplementedError - + def get_version_in_store(self, container): raise NotImplementedError @@ -49,7 +47,7 @@ def test1(self): previous_mass_in_kg = p.mass.value_in(units.kg) for expected, actual in zip(previous_mass_in_kg, loaded_mass_in_kg): self.assertEqual(expected, actual) - + instance.close() def test2(self): @@ -108,9 +106,9 @@ def test4(self): particles.x = 2.0 | units.m x = particles.savepoint(2.0 | units.s) - io.write_set_to_file(x,output_file, format='amuse', version = self.store_version()) + io.write_set_to_file(x, output_file, format='amuse', version=self.store_version()) - particles_from_file = io.read_set_from_file(output_file, format='amuse', version = self.store_version(), close_file = True) + particles_from_file = io.read_set_from_file(output_file, format='amuse', version=self.store_version(), close_file=True) particles_in_memory = particles_from_file.copy() self.assertAlmostRelativeEquals(particles_in_memory.mass[1], 1.0 | units.kg) @@ -118,14 +116,14 @@ def test4(self): particles_in_memory.savepoint(4.0 | units.s) self.assertAlmostRelativeEquals(particles_from_file.mass[2], 1.0 | units.kg) - + def test5(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test5_grid"+self.store_version()+".hdf5") if os.path.exists(output_file): os.remove(output_file) instance = self.store_factory()(output_file) - + shape = 10, 10, 10 p = Grid(*shape) p.mass = ([x * 2.0 for x in range(p.size)] | units.kg).reshape(shape) @@ -136,38 +134,38 @@ def test5(self): loaded_grid = instance.load_grid() self.assertEqual(loaded_grid.shape, shape) - + loaded_mass_in_kg = loaded_grid.mass.value_in(units.kg) previous_mass_in_kg = p.mass.value_in(units.kg) for expected, actual in zip(previous_mass_in_kg, loaded_mass_in_kg): self.assertEqual(expected, actual) - + instance.close() - + def test6(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test6_grid"+self.store_version()+".hdf5") if os.path.exists(output_file): os.remove(output_file) instance = self.store_factory()(output_file) - + shape = 10, 10, 10 p = Grid(*shape) p.mass = ([x * 2.0 for x in range(p.size)] | units.kg).reshape(shape) p.model_time = 2.0 | units.s - - instance.store_grid(p.savepoint(1| units.Myr)) + + instance.store_grid(p.savepoint(1 | units.Myr)) loaded_grid = self.get_version_in_store(instance.load_grid()) - - self.assertAlmostRelativeEquals(loaded_grid.get_timestamp(), 1| units.Myr) - + + self.assertAlmostRelativeEquals(loaded_grid.get_timestamp(), 1 | units.Myr) + self.assertEqual(loaded_grid.shape, shape) self.assertEqual(loaded_grid[0][0][0].mass, 0 | units.kg) - self.assertAlmostRelativeEquals(loaded_grid[...,1,1].mass, p[...,1,1].mass) + self.assertAlmostRelativeEquals(loaded_grid[..., 1, 1].mass, p[..., 1, 1].mass) instance.close() - + def test7(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test7"+self.store_version()+".hdf5") @@ -182,31 +180,31 @@ def test7(self): instance.store(p) instance.close() - + instance = self.store_factory()(output_file) - loaded_particles = self.get_version_in_store(instance.load()) + loaded_particles = self.get_version_in_store(instance.load()) loaded_particles.mass = [x * 3.0 for x in range(number_of_particles)] | units.kg previous_mass_in_kg = [x * 3.0 for x in range(number_of_particles)] instance.close() - + instance = self.store_factory()(output_file) loaded_particles = instance.load() loaded_mass_in_kg = loaded_particles.mass.value_in(units.kg) for expected, actual in zip(previous_mass_in_kg, loaded_mass_in_kg): self.assertEqual(expected, actual) - + instance.close() - + instance = self.store_factory()(output_file) loaded_particles = self.get_version_in_store(instance.load()) loaded_particles[2].mass = 44 | units.kg instance.close() instance = self.store_factory()(output_file) loaded_particles = self.get_version_in_store(instance.load()) - self.assertEqual( 44 | units.kg, loaded_particles[2].mass) + self.assertEqual(44 | units.kg, loaded_particles[2].mass) instance.close() - + def test8(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test8"+self.store_version()+".hdf5") @@ -225,7 +223,6 @@ def test8(self): loaded_particles = instance.load() self.assertAlmostRelativeEquals(p.mass[1], 2.0) instance.close() - def test9(self): test_results_path = self.get_path_to_results() @@ -241,21 +238,20 @@ def test9(self): io.write_set_to_file( p, output_file, - "hdf5", - timestamp = 2 | units.Myr, - scale = 1 | units.kg, - version = self.store_version(), - close_file = True + "hdf5", + timestamp=2 | units.Myr, + scale=1 | units.kg, + version=self.store_version(), + close_file=True ) - + loaded_particles = io.read_set_from_file( - output_file, + output_file, "hdf5", - version = self.store_version() + version=self.store_version() ) loaded_particles = self.get_version_in_store(loaded_particles) - - + a = loaded_particles.collection_attributes self.assertAlmostRelativeEquals(a.timestamp, 2 | units.Myr) self.assertAlmostRelativeEquals(a.scale, 1 | units.kg) @@ -266,15 +262,14 @@ def test10(self): if os.path.exists(output_file): os.remove(output_file) - shape = 10, 10, 10 p = Grid(*shape) p.mass = ([x * 2.0 for x in range(p.size)] | units.kg).reshape(shape) p.model_time = 2.0 | units.s - io.write_set_to_file(p, output_file, "hdf5", timestamp = 2 | units.Myr, scale = 1 | units.kg, version = self.store_version()) - - loaded_particles = io.read_set_from_file(output_file, "hdf5", version = self.store_version()) + io.write_set_to_file(p, output_file, "hdf5", timestamp=2 | units.Myr, scale=1 | units.kg, version=self.store_version()) + + loaded_particles = io.read_set_from_file(output_file, "hdf5", version=self.store_version()) loaded_particles = self.get_version_in_store(loaded_particles) a = loaded_particles.collection_attributes self.assertAlmostRelativeEquals(a.timestamp, 2 | units.Myr) @@ -291,35 +286,33 @@ def test11(self): p.mass = [x * 2.0 for x in range(number_of_particles)] | units.kg p.model_time = 2.0 | units.s - io.write_set_to_file(p.savepoint(timestamp = 2 | units.Myr, scale = 1 | units.kg), output_file, "hdf5", version = self.store_version()) - - loaded_particles = io.read_set_from_file(output_file, "hdf5", version = self.store_version()) + io.write_set_to_file(p.savepoint(timestamp=2 | units.Myr, scale=1 | units.kg), output_file, "hdf5", version=self.store_version()) + + loaded_particles = io.read_set_from_file(output_file, "hdf5", version=self.store_version()) loaded_particles = self.get_version_in_store(loaded_particles) a = loaded_particles.collection_attributes self.assertAlmostRelativeEquals(a.timestamp, 2 | units.Myr) self.assertAlmostRelativeEquals(a.scale, 1 | units.kg) - - + def test12(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test12"+self.store_version()+".hdf5") if os.path.exists(output_file): os.remove(output_file) - shape = 10, 10, 10 p = Grid(*shape) p.mass = ([x * 2.0 for x in range(p.size)] | units.kg).reshape(shape) p.model_time = 2.0 | units.s - io.write_set_to_file(p.savepoint(timestamp = 2 | units.Myr, scale = 1 | units.kg), output_file, "hdf5", version = self.store_version()) - - loaded_particles = io.read_set_from_file(output_file, "hdf5", version = self.store_version()) + io.write_set_to_file(p.savepoint(timestamp=2 | units.Myr, scale=1 | units.kg), output_file, "hdf5", version=self.store_version()) + + loaded_particles = io.read_set_from_file(output_file, "hdf5", version=self.store_version()) loaded_particles = self.get_version_in_store(loaded_particles) a = loaded_particles.collection_attributes self.assertAlmostRelativeEquals(a.timestamp, 2 | units.Myr) self.assertAlmostRelativeEquals(a.scale, 1 | units.kg) - + def test13(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test13"+self.store_version()+".hdf5") @@ -327,23 +320,21 @@ def test13(self): os.remove(output_file) stars = Particles(2) - stars.x = 1.0 | units.km - stars.md = [[1,2,3],[4,5,6]] | units.km - - - io.write_set_to_file(stars, output_file, "hdf5", version = self.store_version()) - - loaded = io.read_set_from_file(output_file, "hdf5", version = self.store_version()) - self.assertEqual(loaded[0].md, [1,2,3] | units.km) - self.assertEqual(loaded[1].md, [4,5,6] | units.km) - - self.assertEqual(loaded.md[0], [1,2,3] | units.km) - self.assertEqual(loaded.md[1], [4,5,6] | units.km) - - self.assertEqual(self.get_version_in_store(loaded)[0].md, [1,2,3] | units.km) - #self.assertEquals(self.get_version_in_store(loaded)[0].md, [7,8,9] | units.km) - - + stars.x = 1.0 | units.km + stars.md = [[1, 2, 3], [4, 5, 6]] | units.km + + io.write_set_to_file(stars, output_file, "hdf5", version=self.store_version()) + + loaded = io.read_set_from_file(output_file, "hdf5", version=self.store_version()) + self.assertEqual(loaded[0].md, [1, 2, 3] | units.km) + self.assertEqual(loaded[1].md, [4, 5, 6] | units.km) + + self.assertEqual(loaded.md[0], [1, 2, 3] | units.km) + self.assertEqual(loaded.md[1], [4, 5, 6] | units.km) + + self.assertEqual(self.get_version_in_store(loaded)[0].md, [1, 2, 3] | units.km) + # self.assertEquals(self.get_version_in_store(loaded)[0].md, [7,8,9] | units.km) + def test14(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test14"+self.store_version()+".hdf5") @@ -351,42 +342,40 @@ def test14(self): os.remove(output_file) stars = Particles(2) - stars.x = 1.0 | units.km - stars.md = [[[1,3],[2,4],[3,5]],[[4,6],[5,7],[6,8]]] - - - io.write_set_to_file(stars, output_file, "hdf5", version = self.store_version()) - - loaded = io.read_set_from_file(output_file, "hdf5", version = self.store_version()) - self.assertEqual(loaded[0].md, [[1,3],[2,4],[3,5]]) - self.assertEqual(loaded[1].md, [[4,6],[5,7],[6,8]]) - - self.assertEqual(loaded.md[0], [[1,3],[2,4],[3,5]]) - self.assertEqual(loaded.md[1], [[4,6],[5,7],[6,8]]) - + stars.x = 1.0 | units.km + stars.md = [[[1, 3], [2, 4], [3, 5]], [[4, 6], [5, 7], [6, 8]]] + + io.write_set_to_file(stars, output_file, "hdf5", version=self.store_version()) + + loaded = io.read_set_from_file(output_file, "hdf5", version=self.store_version()) + self.assertEqual(loaded[0].md, [[1, 3], [2, 4], [3, 5]]) + self.assertEqual(loaded[1].md, [[4, 6], [5, 7], [6, 8]]) + + self.assertEqual(loaded.md[0], [[1, 3], [2, 4], [3, 5]]) + self.assertEqual(loaded.md[1], [[4, 6], [5, 7], [6, 8]]) + def test15(self): - + test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test15"+self.store_version()+".hdf5") if os.path.exists(output_file): os.remove(output_file) stars = Particles(2) - stars.x = 1.0 | units.km - stars.md = [[[1,3],[2,4],[3,5]],[[4,6],[5,7],[6,8]]] - + stars.x = 1.0 | units.km + stars.md = [[[1, 3], [2, 4], [3, 5]], [[4, 6], [5, 7], [6, 8]]] - io.write_set_to_file(stars, output_file, "hdf5", version = self.store_version()) - processor = self.store_factory()(output_file, True, open_for_writing = True) + io.write_set_to_file(stars, output_file, "hdf5", version=self.store_version()) + processor = self.store_factory()(output_file, True, open_for_writing=True) loaded = processor.load() - self.get_version_in_store(loaded)[0].md = [[3,1],[3,4],[5,2]] - self.assertEqual(self.get_version_in_store(loaded)[0].md, [[3,1],[3,4],[5,2]] ) + self.get_version_in_store(loaded)[0].md = [[3, 1], [3, 4], [5, 2]] + self.assertEqual(self.get_version_in_store(loaded)[0].md, [[3, 1], [3, 4], [5, 2]]) processor.close() - - loaded = io.read_set_from_file(output_file, "hdf5", version = self.store_version()) - self.assertEqual(loaded[0].md, [[3,1],[3,4],[5,2]]) - self.assertEqual(loaded[1].md, [[4,6],[5,7],[6,8]]) - + + loaded = io.read_set_from_file(output_file, "hdf5", version=self.store_version()) + self.assertEqual(loaded[0].md, [[3, 1], [3, 4], [5, 2]]) + self.assertEqual(loaded[1].md, [[4, 6], [5, 7], [6, 8]]) + def test16(self): import h5py test_results_path = self.get_path_to_results() @@ -395,38 +384,36 @@ def test16(self): os.remove(output_file) stars = Particles(2) - stars[0].x = 1.0 | units.km - stars[1].x = 2.0 | units.km + stars[0].x = 1.0 | units.km + stars[1].x = 2.0 | units.km stars[0].nn = stars[1] stars[1].nn = stars[0] - - self.assertEqual(stars[0].nn,stars[1]) - self.assertEqual(stars[1].nn,stars[0]) - - io.write_set_to_file(stars, output_file, "hdf5", version = self.store_version()) - processor = self.store_factory()(output_file, True, open_for_writing = True) + self.assertEqual(stars[0].nn, stars[1]) + self.assertEqual(stars[1].nn, stars[0]) + + io.write_set_to_file(stars, output_file, "hdf5", version=self.store_version()) + processor = self.store_factory()(output_file, True, open_for_writing=True) loaded = processor.load() - - self.assertEqual(loaded[0].nn,loaded[1]) - self.assertEqual(loaded[1].nn,loaded[0]) - self.assertEqual(loaded[0].nn.key,stars[1].key) - self.assertEqual(loaded[0].nn.x,stars[1].x) - - + + self.assertEqual(loaded[0].nn, loaded[1]) + self.assertEqual(loaded[1].nn, loaded[0]) + self.assertEqual(loaded[0].nn.key, stars[1].key) + self.assertEqual(loaded[0].nn.x, stars[1].x) + def test17(self): - + test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test17"+self.store_version()+".hdf5") if os.path.exists(output_file): os.remove(output_file) stars = Particles(4) - stars[0].x = 1.0 | units.km - stars[1].x = 2.0 | units.km - stars[2].x = 3.0 | units.km - stars[3].x = 4.0 | units.km - + stars[0].x = 1.0 | units.km + stars[1].x = 2.0 | units.km + stars[2].x = 3.0 | units.km + stars[3].x = 4.0 | units.km + binaries = Particles(2) binaries[0].y = 1.0 | units.km binaries[1].y = 2.0 | units.km @@ -435,27 +422,27 @@ def test17(self): binaries[1].child1 = stars[2] binaries[1].child2 = stars[3] - self.assertEqual(binaries[0].child1,stars[0]) - self.assertEqual(binaries[1].child1,stars[2]) - - io.write_set_to_file(binaries, output_file, "hdf5", version = self.store_version()) - - loaded = io.read_set_from_file(output_file, "hdf5", version = self.store_version()) - - self.assertEqual(loaded[0].child1.key,stars[0].key) - self.assertEqual(loaded[1].child1.key,stars[2].key) - + self.assertEqual(binaries[0].child1, stars[0]) + self.assertEqual(binaries[1].child1, stars[2]) + + io.write_set_to_file(binaries, output_file, "hdf5", version=self.store_version()) + + loaded = io.read_set_from_file(output_file, "hdf5", version=self.store_version()) + + self.assertEqual(loaded[0].child1.key, stars[0].key) + self.assertEqual(loaded[1].child1.key, stars[2].key) + def test18(self): - + test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test18"+self.store_version()+".hdf5") if os.path.exists(output_file): os.remove(output_file) stars = Particles(2) - stars[0].x = 1.0 | units.km - stars[1].x = 2.0 | units.km - + stars[0].x = 1.0 | units.km + stars[1].x = 2.0 | units.km + binaries = Particles(1) binaries[0].y = 1.0 | units.km binaries[0].child1 = stars[0] @@ -463,23 +450,23 @@ def test18(self): stars[0].parent = binaries[0] stars[1].parent = binaries[0] - - self.assertEqual(binaries[0].child1,stars[0]) - self.assertEqual(binaries[0].child2,stars[1]) - self.assertEqual(binaries[0].child1.parent,binaries[0]) - self.assertEqual(binaries[0].child2.parent,binaries[0]) - - io.write_set_to_file(binaries, output_file, "hdf5", version = self.store_version()) - - loaded = io.read_set_from_file(output_file, "hdf5", version = self.store_version()) - - self.assertEqual(loaded[0].child1.key,stars[0].key) - self.assertEqual(loaded[0].child2.key,stars[1].key) - self.assertEqual(loaded[0].child1,stars[0]) - self.assertEqual(loaded[0].child2,stars[1]) - self.assertEqual(loaded[0].child1.parent,loaded[0]) - self.assertEqual(loaded[0].child2.parent,loaded[0]) - + + self.assertEqual(binaries[0].child1, stars[0]) + self.assertEqual(binaries[0].child2, stars[1]) + self.assertEqual(binaries[0].child1.parent, binaries[0]) + self.assertEqual(binaries[0].child2.parent, binaries[0]) + + io.write_set_to_file(binaries, output_file, "hdf5", version=self.store_version()) + + loaded = io.read_set_from_file(output_file, "hdf5", version=self.store_version()) + + self.assertEqual(loaded[0].child1.key, stars[0].key) + self.assertEqual(loaded[0].child2.key, stars[1].key) + self.assertEqual(loaded[0].child1, stars[0]) + self.assertEqual(loaded[0].child2, stars[1]) + self.assertEqual(loaded[0].child1.parent, loaded[0]) + self.assertEqual(loaded[0].child2.parent, loaded[0]) + def test19(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test19"+self.store_version()+".hdf5") @@ -487,98 +474,93 @@ def test19(self): os.remove(output_file) stars = Particles(2) - stars[0].x = 1.0 | units.km - stars[1].x = 2.0 | units.km - + stars[0].x = 1.0 | units.km + stars[1].x = 2.0 | units.km + binaries = Particles(1) binaries[0].y = 1.0 | units.km binaries[0].child1 = stars[0] binaries[0].child2 = stars[1] - + stars[0].parent = binaries[0] stars[1].parent = binaries[0] - - self.assertEqual(binaries[0].child1,stars[0]) - self.assertEqual(binaries[0].child2,stars[1]) - self.assertEqual(binaries[0].child1.parent,binaries[0]) - self.assertEqual(binaries[0].child2.parent,binaries[0]) - - io.write_set_to_file([binaries,stars], output_file, "hdf5", names = ['binaries', 'children'], version = self.store_version()) - - loader_binaries, loaded_stars = io.read_set_from_file(output_file, "hdf5", names = ['binaries', 'children'], version = self.store_version()) - - self.assertEqual(loader_binaries[0].child1.key,stars[0].key) - self.assertEqual(loader_binaries[0].child2.key,stars[1].key) - self.assertEqual(loader_binaries[0].child1,loaded_stars[0]) - self.assertEqual(loader_binaries[0].child2,loaded_stars[1]) - self.assertEqual(loader_binaries[0].child1.parent,loader_binaries[0]) - self.assertEqual(loader_binaries[0].child2.parent,loader_binaries[0]) + + self.assertEqual(binaries[0].child1, stars[0]) + self.assertEqual(binaries[0].child2, stars[1]) + self.assertEqual(binaries[0].child1.parent, binaries[0]) + self.assertEqual(binaries[0].child2.parent, binaries[0]) + + io.write_set_to_file([binaries, stars], output_file, "hdf5", names=['binaries', 'children'], version=self.store_version()) + + loader_binaries, loaded_stars = io.read_set_from_file(output_file, "hdf5", names=['binaries', 'children'], version=self.store_version()) + + self.assertEqual(loader_binaries[0].child1.key, stars[0].key) + self.assertEqual(loader_binaries[0].child2.key, stars[1].key) + self.assertEqual(loader_binaries[0].child1, loaded_stars[0]) + self.assertEqual(loader_binaries[0].child2, loaded_stars[1]) + self.assertEqual(loader_binaries[0].child1.parent, loader_binaries[0]) + self.assertEqual(loader_binaries[0].child2.parent, loader_binaries[0]) def test20(self): - + test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test20"+self.store_version()+".hdf5") if os.path.exists(output_file): os.remove(output_file) - shape = 10, 10, 10 p = Grid(*shape) p.mass = (numpy.asarray([x * 2.0 for x in range(p.size)])).reshape(shape) - io.write_set_to_file(p, output_file, "hdf5", version = self.store_version()) - - loaded = io.read_set_from_file(output_file, "hdf5", version = self.store_version()) + io.write_set_to_file(p, output_file, "hdf5", version=self.store_version()) + + loaded = io.read_set_from_file(output_file, "hdf5", version=self.store_version()) loaded = self.get_version_in_store(loaded) - + self.assertAlmostRelativeEquals(p.mass[0][1][2], 24) self.assertAlmostRelativeEquals(p[0][1][2].mass, 24) - + def test21(self): - + test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test21"+self.store_version()+".hdf5") if os.path.exists(output_file): os.remove(output_file) stars = Particles(2) - stars.x = 1.0 | units.km - stars.md = [[[1,3],[2,4],[3,5]],[[4,6],[5,7],[6,8]]] - - - io.write_set_to_file(stars, output_file, "hdf5", version = self.store_version()) - - loaded = io.read_set_from_file(output_file, "hdf5", close_file = True, version = self.store_version(), copy_history=False) - - self.assertEqual(loaded[0].md, [[1,3],[2,4],[3,5]]) - self.assertEqual(loaded[1].md, [[4,6],[5,7],[6,8]]) - + stars.x = 1.0 | units.km + stars.md = [[[1, 3], [2, 4], [3, 5]], [[4, 6], [5, 7], [6, 8]]] + + io.write_set_to_file(stars, output_file, "hdf5", version=self.store_version()) + + loaded = io.read_set_from_file(output_file, "hdf5", close_file=True, version=self.store_version(), copy_history=False) + + self.assertEqual(loaded[0].md, [[1, 3], [2, 4], [3, 5]]) + self.assertEqual(loaded[1].md, [[4, 6], [5, 7], [6, 8]]) + previous = loaded.previous_state() self.assertEqual(previous, None) - def test22(self): - + test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test22"+self.store_version()+".hdf5") if os.path.exists(output_file): os.remove(output_file) stars = Particles(2) - stars.x = 1.0 | units.km - + stars.x = 1.0 | units.km + overlay = ParticlesOverlay(stars) - overlay.y = 2.0 | units.km + overlay.y = 2.0 | units.km + io.write_set_to_file(overlay, output_file, "hdf5", version=self.store_version()) + + loaded = io.read_set_from_file(output_file, "hdf5", close_file=True, version=self.store_version()) - io.write_set_to_file(overlay, output_file, "hdf5", version = self.store_version()) - - loaded = io.read_set_from_file(output_file, "hdf5", close_file = True, version = self.store_version()) - self.assertEqual(loaded[0].x, 1.0 | units.km) self.assertEqual(loaded[1].y, 2.0 | units.km) - - + def test23(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test23"+self.store_version()+".hdf5") @@ -587,12 +569,12 @@ def test23(self): particles = Particles() - io.write_set_to_file(particles, output_file, format='amuse', version = self.store_version()) + io.write_set_to_file(particles, output_file, format='amuse', version=self.store_version()) + + particles_from_file = io.read_set_from_file(output_file, format='amuse', version=self.store_version()) - particles_from_file = io.read_set_from_file(output_file, format='amuse', version = self.store_version()) - self.assertEqual(len(particles_from_file), 0) - + def test24(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test24"+self.store_version()+".hdf5") @@ -600,21 +582,21 @@ def test24(self): os.remove(output_file) particles = Particles(20) -#~ particles = Particles(1000000) # For testing memory usage +# ~ particles = Particles(1000000) # For testing memory usage particles.mass = 1.0 | units.kg particles.position = [0.0, 0.0, 0.0] | units.m - + for i in range(10): particles.position += [1.0, 2.0, 3.0] | units.m - io.write_set_to_file(particles, output_file, format='amuse', version = self.store_version(), append_to_file=True) - - particles_from_file = io.read_set_from_file(output_file, format='amuse', version = self.store_version()) + io.write_set_to_file(particles, output_file, format='amuse', version=self.store_version(), append_to_file=True) + + particles_from_file = io.read_set_from_file(output_file, format='amuse', version=self.store_version()) os.remove(output_file) self.assertEqual(len(list(particles_from_file.history)), 10) for i, snap in enumerate(particles_from_file.history): self.assertEqual(len(snap), 20) self.assertEqual((i+1) * ([1.0, 2.0, 3.0] | units.m), snap.center_of_mass()) - + def test25(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test25"+self.store_version()+".hdf5") @@ -622,16 +604,16 @@ def test25(self): os.remove(output_file) particles = Particles(20) -#~ particles = Particles(1000000) # For testing memory usage +# ~ particles = Particles(1000000) # For testing memory usage particles.mass = 1.0 | units.kg particles.position = [0.0, 0.0, 0.0] | units.m - + for i in range(10): particles.position += [1.0, 2.0, 3.0] | units.m - io.write_set_to_file(particles, output_file, format='amuse', version = self.store_version(), append_to_file=True) - - particles_from_file = io.read_set_from_file(output_file, format='amuse', version = self.store_version(), copy_history = True, close_file = True) - + io.write_set_to_file(particles, output_file, format='amuse', version=self.store_version(), append_to_file=True) + + particles_from_file = io.read_set_from_file(output_file, format='amuse', version=self.store_version(), copy_history=True, close_file=True) + history = list(particles_from_file.history) self.assertEqual(len(history), 10) self.assertFalse("HDF" in str(type(history[1]._private.attribute_storage))) @@ -639,7 +621,7 @@ def test25(self): self.assertEqual(len(snap), 20) self.assertEqual((i+1) * ([1.0, 2.0, 3.0] | units.m), snap.center_of_mass()) os.remove(output_file) - + def test26(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test26"+self.store_version()+".hdf5") @@ -647,9 +629,9 @@ def test26(self): os.remove(output_file) p = Grid(20) - - io.write_set_to_file(p, output_file, format='amuse', version = self.store_version()) - + + io.write_set_to_file(p, output_file, format='amuse', version=self.store_version()) + os.remove(output_file) def test27(self): @@ -658,7 +640,7 @@ def test27(self): if os.path.exists(output_file): os.remove(output_file) instance = self.store_factory()(output_file) - + shape = 10, p = Grid(*shape) p.mass = ([x * 2.0 for x in range(p.size)] | units.kg).reshape(shape) @@ -669,27 +651,25 @@ def test27(self): loaded_grid = instance.load_grid() self.assertEqual(loaded_grid.shape, shape) - + loaded_mass_in_kg = loaded_grid.mass.value_in(units.kg) previous_mass_in_kg = p.mass.value_in(units.kg) for expected, actual in zip(previous_mass_in_kg, loaded_mass_in_kg): self.assertEqual(expected, actual) - + instance.close() def test28(self): - + test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test28"+self.store_version()+".hdf5") if os.path.exists(output_file): os.remove(output_file) - - stars = Particles(2) - stars[0].x = 1.0 | units.km - stars[1].x = 2.0 | units.km - + stars[0].x = 1.0 | units.km + stars[1].x = 2.0 | units.km + binaries = Particles(1) binaries[0].y = 1.0 | units.km binaries[0].child1 = stars[0] @@ -697,22 +677,22 @@ def test28(self): stars[0].parent = binaries[0] stars[1].parent = binaries[0] - - self.assertEqual(binaries[0].child1,stars[0]) - self.assertEqual(binaries[0].child2,stars[1]) - self.assertEqual(binaries[0].child1.parent,binaries[0]) - self.assertEqual(binaries[0].child2.parent,binaries[0]) - - io.write_set_to_file(binaries, output_file, "hdf5", version = self.store_version()) - - with io.read_set_from_file(output_file, "hdf5", version = self.store_version(), return_context = True) as loaded: - - self.assertEqual(loaded[0].child1.key,stars[0].key) - self.assertEqual(loaded[0].child2.key,stars[1].key) - self.assertEqual(loaded[0].child1,stars[0]) - self.assertEqual(loaded[0].child2,stars[1]) - self.assertEqual(loaded[0].child1.parent,loaded[0]) - self.assertEqual(loaded[0].child2.parent,loaded[0]) + + self.assertEqual(binaries[0].child1, stars[0]) + self.assertEqual(binaries[0].child2, stars[1]) + self.assertEqual(binaries[0].child1.parent, binaries[0]) + self.assertEqual(binaries[0].child2.parent, binaries[0]) + + io.write_set_to_file(binaries, output_file, "hdf5", version=self.store_version()) + + with io.read_set_from_file(output_file, "hdf5", version=self.store_version(), return_context=True) as loaded: + + self.assertEqual(loaded[0].child1.key, stars[0].key) + self.assertEqual(loaded[0].child2.key, stars[1].key) + self.assertEqual(loaded[0].child1, stars[0]) + self.assertEqual(loaded[0].child2, stars[1]) + self.assertEqual(loaded[0].child1.parent, loaded[0]) + self.assertEqual(loaded[0].child2.parent, loaded[0]) def test29(self): test_results_path = self.get_path_to_results() @@ -724,11 +704,11 @@ def test29(self): particles.attribute1 = "normal" particles.attribute2 = "unicode" - io.write_set_to_file(particles,output_file, format='amuse', version = self.store_version()) - + io.write_set_to_file(particles, output_file, format='amuse', version=self.store_version()) + output = io.read_set_from_file(output_file, format='amuse') self.assertEqual(output[0].attribute2, "unicode") - + def test30(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test30"+self.store_version()+".hdf5") @@ -738,60 +718,60 @@ def test30(self): particles = Particles(10) particles.mass = 10 | units.kg - io.write_set_to_file(particles,output_file, format='amuse', version = self.store_version()) - - output = io.read_set_from_file(output_file, format='amuse', allow_writing = True) - output.new_attribute= 2 * output.mass + io.write_set_to_file(particles, output_file, format='amuse', version=self.store_version()) + + output = io.read_set_from_file(output_file, format='amuse', allow_writing=True) + output.new_attribute = 2 * output.mass self.assertEqual(output.new_attribute, 2 * output.mass) output = next(output.iter_history()) - output.new_attribute= 2 * output.mass + output.new_attribute = 2 * output.mass self.assertEqual(output.new_attribute, 2 * output.mass) - + def test31(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test31"+self.store_version()+".h5") if os.path.exists(output_file): os.remove(output_file) - p=Particles(10) - p.mass=numpy.arange(10) - q=Particles(3) - q[0].link=p[1] - q[1].link=p[3] - q[2].link=p[4] - io.write_set_to_file(q,output_file,"amuse",version=self.store_version()) - r=io.read_set_from_file(output_file,"amuse") - self.assertEqual(len(r.link.shape),1) - self.assertEqual(r[0].link.mass,1) - self.assertEqual(r[1].link.mass,3) - self.assertEqual(r[2].link.mass,4) - + p = Particles(10) + p.mass = numpy.arange(10) + q = Particles(3) + q[0].link = p[1] + q[1].link = p[3] + q[2].link = p[4] + io.write_set_to_file(q, output_file, "amuse", version=self.store_version()) + r = io.read_set_from_file(output_file, "amuse") + self.assertEqual(len(r.link.shape), 1) + self.assertEqual(r[0].link.mass, 1) + self.assertEqual(r[1].link.mass, 3) + self.assertEqual(r[2].link.mass, 4) class TestStoreHDFV1(amusetest.TestCase, _AbstractTestStoreHDF): - + def store_factory(self): return store_v1.StoreHDF - + def store_version(self): return '1.0' - + def get_version_in_store(self, container): return container.previous_state() - + + class TestStoreHDFV2(amusetest.TestCase, _AbstractTestStoreHDF): - + def store_factory(self): return store_v2.StoreHDF - + def store_version(self): return '2.0' - + def get_version_in_store(self, container): return container - + def test52(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test52"+self.store_version()+".hdf5") @@ -799,24 +779,22 @@ def test52(self): os.remove(output_file) stars = Particles(2) - stars[0].x = 1.0 | units.km - stars[1].x = 2.0 | units.km - + stars[0].x = 1.0 | units.km + stars[1].x = 2.0 | units.km + gas = Particles(1) gas[0].y = 1.0 | units.km - + stars[0].gas = gas - - - io.write_set_to_file(stars, output_file, "hdf5", version = self.store_version()) - - loaded_stars = io.read_set_from_file(output_file, "hdf5", version = self.store_version()) - - self.assertEqual(loaded_stars[0].gas[0].key,gas[0].key) - self.assertAlmostRelativeEquals(loaded_stars[0].gas[0].y,1.0 | units.km) + + io.write_set_to_file(stars, output_file, "hdf5", version=self.store_version()) + + loaded_stars = io.read_set_from_file(output_file, "hdf5", version=self.store_version()) + + self.assertEqual(loaded_stars[0].gas[0].key, gas[0].key) + self.assertAlmostRelativeEquals(loaded_stars[0].gas[0].y, 1.0 | units.km) self.assertEqual(loaded_stars[1].gas, None) - def test53(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test53"+self.store_version()+".hdf5") @@ -824,19 +802,19 @@ def test53(self): os.remove(output_file) stars = Particles(2) - stars[0].x = 1.0 | units.km - stars[1].x = 2.0 | units.km - - gas = Grid(2,3) - gas.y = [[1.0, 2.0, 3.0], [4.0,5.0,6.0]] | units.km - + stars[0].x = 1.0 | units.km + stars[1].x = 2.0 | units.km + + gas = Grid(2, 3) + gas.y = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] | units.km + stars[0].gas = gas - - io.write_set_to_file(stars, output_file, "hdf5", version = self.store_version()) - loaded_stars = io.read_set_from_file(output_file, "hdf5", version = self.store_version()) - - self.assertAlmostRelativeEquals(loaded_stars[0].gas[0][0].y,1.0 | units.km) - self.assertAlmostRelativeEquals(loaded_stars[0].gas[0][2].y,3.0 | units.km) + + io.write_set_to_file(stars, output_file, "hdf5", version=self.store_version()) + loaded_stars = io.read_set_from_file(output_file, "hdf5", version=self.store_version()) + + self.assertAlmostRelativeEquals(loaded_stars[0].gas[0][0].y, 1.0 | units.km) + self.assertAlmostRelativeEquals(loaded_stars[0].gas[0][2].y, 3.0 | units.km) self.assertEqual(loaded_stars[1].gas, None) def test54(self): @@ -846,23 +824,23 @@ def test54(self): os.remove(output_file) stars = Particles(2) - stars[0].x = 1.0 | units.km - stars[1].x = 2.0 | units.km - - gas = Grid(2,3) - gas.y = [[1.0, 2.0, 3.0], [4.0,5.0,6.0]] | units.km - + stars[0].x = 1.0 | units.km + stars[1].x = 2.0 | units.km + + gas = Grid(2, 3) + gas.y = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] | units.km + stars[0].gas = gas[0][0] stars[1].gas = gas[1][0] - - self.assertAlmostRelativeEquals(stars[0].gas.y,1.0 | units.km) - self.assertAlmostRelativeEquals(stars[1].gas.y,4.0 | units.km) - - io.write_set_to_file(stars, output_file, "hdf5", version = self.store_version()) - loaded_stars = io.read_set_from_file(output_file, "hdf5", version = self.store_version()) - - self.assertAlmostRelativeEquals(loaded_stars[0].gas.y,1.0 | units.km) - self.assertAlmostRelativeEquals(loaded_stars[1].gas.y,4.0 | units.km) + + self.assertAlmostRelativeEquals(stars[0].gas.y, 1.0 | units.km) + self.assertAlmostRelativeEquals(stars[1].gas.y, 4.0 | units.km) + + io.write_set_to_file(stars, output_file, "hdf5", version=self.store_version()) + loaded_stars = io.read_set_from_file(output_file, "hdf5", version=self.store_version()) + + self.assertAlmostRelativeEquals(loaded_stars[0].gas.y, 1.0 | units.km) + self.assertAlmostRelativeEquals(loaded_stars[1].gas.y, 4.0 | units.km) def test54b(self): test_results_path = self.get_path_to_results() @@ -871,40 +849,39 @@ def test54b(self): os.remove(output_file) stars = Particles(2) - stars[0].x = 1.0 | units.km - stars[1].x = 2.0 | units.km - - gas = Grid(2,3) - gas.y = [[1.0, 2.0, 3.0], [4.0,5.0,6.0]] | units.km + stars[0].x = 1.0 | units.km + stars[1].x = 2.0 | units.km + + gas = Grid(2, 3) + gas.y = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] | units.km gas[0][0].particle = stars[0] gas[1][2].particle = stars[0] gas[1][0].particle = stars[1] - - #stars[0].gas = gas[0][0] - #stars[1].gas = gas[1][0] - - self.assertAlmostRelativeEquals(gas[0][0].particle.x,1.0 | units.km) - self.assertAlmostRelativeEquals(gas[1][2].particle.x,1.0 | units.km) - self.assertAlmostRelativeEquals(gas[1][0].particle.x,2.0 | units.km) - - io.write_set_to_file(gas, output_file, "hdf5", version = self.store_version()) - loaded_gas = io.read_set_from_file(output_file, "hdf5", version = self.store_version()) - + + # stars[0].gas = gas[0][0] + # stars[1].gas = gas[1][0] + + self.assertAlmostRelativeEquals(gas[0][0].particle.x, 1.0 | units.km) + self.assertAlmostRelativeEquals(gas[1][2].particle.x, 1.0 | units.km) + self.assertAlmostRelativeEquals(gas[1][0].particle.x, 2.0 | units.km) + + io.write_set_to_file(gas, output_file, "hdf5", version=self.store_version()) + loaded_gas = io.read_set_from_file(output_file, "hdf5", version=self.store_version()) + self.assertAlmostRelativeEquals(loaded_gas[0][0].particle.x, 1.0 | units.km) self.assertAlmostRelativeEquals(loaded_gas[1][2].particle.x, 1.0 | units.km) self.assertAlmostRelativeEquals(loaded_gas[1][0].particle.x, 2.0 | units.km) self.assertEqual(id(loaded_gas[0][0].particle.get_containing_set()), id(loaded_gas[1][2].particle.get_containing_set())) - + self.assertEqual(loaded_gas.particle.shape, loaded_gas.shape) - + gas_copy = loaded_gas.copy() gas_copy[0][0].particle.x = 3 | units.km self.assertAlmostRelativeEquals(loaded_gas[0][0].particle.x, 1.0 | units.km) self.assertAlmostRelativeEquals(gas_copy[0][0].particle.x, 3.0 | units.km) self.assertAlmostRelativeEquals(gas_copy[1][2].particle.x, 3.0 | units.km) - - + def test55(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test25"+self.store_version()+".hdf5") @@ -912,25 +889,22 @@ def test55(self): os.remove(output_file) particles1 = Particles(2) - particles1[0].x = 1.0 | units.km - particles1[1].x = 2.0 | units.km + particles1[0].x = 1.0 | units.km + particles1[1].x = 2.0 | units.km particles2 = Particles(2) - particles2[0].x = 3.0 | units.km - particles2[1].x = 4.0 | units.km - + particles2[0].x = 3.0 | units.km + particles2[1].x = 4.0 | units.km + particles_superset = ParticlesSuperset([particles1, particles2]) - - - self.assertAlmostRelativeEquals(particles_superset[0].x,1.0 | units.km) - self.assertAlmostRelativeEquals(particles_superset[2].x,3.0 | units.km) - - io.write_set_to_file(particles_superset, output_file, "hdf5", version = self.store_version()) - loaded_particles_superset = io.read_set_from_file(output_file, "hdf5", version = self.store_version()) - - self.assertAlmostRelativeEquals(loaded_particles_superset[0].x,1.0 | units.km) - self.assertAlmostRelativeEquals(loaded_particles_superset[2].x,3.0 | units.km) - - + + self.assertAlmostRelativeEquals(particles_superset[0].x, 1.0 | units.km) + self.assertAlmostRelativeEquals(particles_superset[2].x, 3.0 | units.km) + + io.write_set_to_file(particles_superset, output_file, "hdf5", version=self.store_version()) + loaded_particles_superset = io.read_set_from_file(output_file, "hdf5", version=self.store_version()) + + self.assertAlmostRelativeEquals(loaded_particles_superset[0].x, 1.0 | units.km) + self.assertAlmostRelativeEquals(loaded_particles_superset[2].x, 3.0 | units.km) def test56(self): test_results_path = self.get_path_to_results() @@ -943,26 +917,26 @@ def test56(self): p.mass = [x * 2.0 for x in range(number_of_particles)] | units.kg p.model_time = 2.0 | units.s - gas = Grid(2,3) - gas.y = [[1.0, 2.0, 3.0], [4.0,5.0,6.0]] | units.km - + gas = Grid(2, 3) + gas.y = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] | units.km + io.write_set_to_file( p, output_file, - "hdf5", - particle = p[1], - particles = p, - gridpoint = gas[0][0], - grid = gas, - version = self.store_version() + "hdf5", + particle=p[1], + particles=p, + gridpoint=gas[0][0], + grid=gas, + version=self.store_version() ) - + loaded_particles = io.read_set_from_file( - output_file, + output_file, "hdf5", - version = self.store_version(), copy_history=False, close_file=False + version=self.store_version(), copy_history=False, close_file=False ) - + attributes = loaded_particles.collection_attributes self.assertAlmostRelativeEquals(attributes.particle.mass, loaded_particles[1].mass) self.assertEquals(attributes.particle.key, loaded_particles[1].key) @@ -979,40 +953,41 @@ def test57(self): x = Particles(2) x.sub = None x[0].sub = Particles(2) - io.write_set_to_file(x, output_file,"amuse", version=self.store_version()) - y = io.read_set_from_file(output_file,"amuse") - + io.write_set_to_file(x, output_file, "amuse", version=self.store_version()) + y = io.read_set_from_file(output_file, "amuse") + self.assertEqual(len(x), len(y)) self.assertEqual(len(x[0].sub), len(y[0].sub)) - self.assertTrue(y[1].sub==x[1].sub==None) + self.assertTrue(y[1].sub == x[1].sub == None) os.remove(output_file) + def test58(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test58"+self.store_version()+".h5") if os.path.exists(output_file): os.remove(output_file) - x = Particles(keys = (1,2)) - x.mass = [1,2] | units.kg - y = Particles(keys = (11,12,13,14)) - y.mass = [40,50,60,70] | units.kg - + x = Particles(keys=(1, 2)) + x.mass = [1, 2] | units.kg + y = Particles(keys=(11, 12, 13, 14)) + y.mass = [40, 50, 60, 70] | units.kg + x.sub = None x[0].sub = y[0:2] y[0].sub = y[2:] - - io.write_set_to_file(x, output_file,"amuse", version=self.store_version()) - z = io.read_set_from_file(output_file,"amuse") - + + io.write_set_to_file(x, output_file, "amuse", version=self.store_version()) + z = io.read_set_from_file(output_file, "amuse") + self.assertEqual(len(x), len(z)) self.assertEqual(len(x[0].sub), len(z[0].sub)) - self.assertEqual(x[0].sub[0].sub.key, (13,14)) - self.assertEqual(z[0].sub[0].sub.key, (13,14)) + self.assertEqual(x[0].sub[0].sub.key, (13, 14)) + self.assertEqual(z[0].sub[0].sub.key, (13, 14)) self.assertEqual(id(x[0].sub._original_set()), id(x[0].sub[0].sub._original_set())) # no more subsets, could this be fixed, would be very nice to do so # self.assertEqual(id(z[0].sub._original_set()), id(z[0].sub[0].sub._original_set())) - self.assertTrue(z[1].sub==x[1].sub==None) + self.assertTrue(z[1].sub == x[1].sub == None) os.remove(output_file) @@ -1022,56 +997,51 @@ def test59(self): if os.path.exists(output_file): os.remove(output_file) - g=Grid(10,10) + g = Grid(10, 10) + + p = Particles(2) - p=Particles(2) + p[0].sub = g[0:5] - p[0].sub=g[0:5] + io.write_set_to_file(p, output_file, "amuse", version=self.store_version()) + z = io.read_set_from_file(output_file, "amuse") - io.write_set_to_file(p, output_file,"amuse", version=self.store_version()) - z = io.read_set_from_file(output_file,"amuse") - os.remove(output_file) + def test60(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test60"+self.store_version()+".h5") if os.path.exists(output_file): os.remove(output_file) - x = Particles(2) x.mass = 1 | units.kg y = Particles(2) y.mass = 2 | units.kg - io.write_set_to_file((x,y), output_file,"amuse", version=self.store_version(), names = ("x", "y")) - z = io.read_set_from_file(output_file,"amuse") - + io.write_set_to_file((x, y), output_file, "amuse", version=self.store_version(), names=("x", "y")) + z = io.read_set_from_file(output_file, "amuse") + os.remove(output_file) self.assertTrue("x" in z) self.assertTrue("y" in z) self.assertAlmostRelativeEquals(z["x"].mass, 1 | units.kg) self.assertAlmostRelativeEquals(z["y"].mass, 2 | units.kg) - def test61(self): test_results_path = self.get_path_to_results() output_file = os.path.join(test_results_path, "test61"+self.store_version()+".h5") if os.path.exists(output_file): os.remove(output_file) - x = Particles(10) x.mass = 1 | units.kg y = Particles(20) y.id = range(20) x[0].y = y[5:7] - io.write_set_to_file(x, output_file,"amuse", version=self.store_version()) - z = io.read_set_from_file(output_file,"amuse") + io.write_set_to_file(x, output_file, "amuse", version=self.store_version()) + z = io.read_set_from_file(output_file, "amuse") self.assertEqual(x[0].y[0].id, 5) self.assertEqual(z[0].y[0].id, 5) os.remove(output_file) - - - diff --git a/src/amuse/test/suite/core_tests/test_textio.py b/src/amuse/test/suite/core_tests/test_textio.py index af48abf997..8a5fbb22f6 100644 --- a/src/amuse/test/suite/core_tests/test_textio.py +++ b/src/amuse/test/suite/core_tests/test_textio.py @@ -3,6 +3,7 @@ import textwrap import os import numpy +import tempfile from amuse import io from amuse.io import text @@ -11,13 +12,14 @@ from amuse.units import generic_unit_system from amuse import datamodel + class CursorTests(amusetest.TestCase): - + def test1(self): contents = "1\n2\n3" data_file = StringIO(contents) instance = text.LineBasedFileCursor(data_file) - + self.assertEqual("1", instance.line()) self.assertEqual("1", instance.line()) instance.forward() @@ -25,12 +27,12 @@ def test1(self): instance.forward() self.assertEqual("3", instance.line()) self.assertEqual("3", instance.line()) - + def test2(self): contents = "1\n2\n3" data_file = StringIO(contents) instance = text.LineBasedFileCursor(data_file) - + self.assertFalse(instance.is_at_end()) instance.forward() self.assertFalse(instance.is_at_end()) @@ -38,254 +40,260 @@ def test2(self): self.assertFalse(instance.is_at_end()) instance.forward() self.assertTrue(instance.is_at_end()) - + + class TableFormattedTextTests(amusetest.TestCase): - + def test1(self): contents = "#header\n1 2 3\n4 5 6\n \n7 8 9\n " data_file = StringIO(contents) instance = text.TableFormattedText("test.txt", data_file) instance.attribute_names = ['a', 'b', 'c'] particles = instance.load() - + self.assertEqual(len(particles), 3) self.assertEqual(particles[0].a, 1) self.assertFalse(quantities.is_quantity(particles[0].a)) - + def test2(self): p = datamodel.Particles(2) p.a = [1, 4] | units.m p.b = [2, 5] | units.m p.c = [3, 6] | units.m - + data_file = StringIO() instance = text.TableFormattedText("test.txt", data_file, p) instance.attribute_types = [units.m, units.m, units.m] instance.store() - + contents = data_file.getvalue() self.assertEqual("#a b c\n#m m m\n1.0 2.0 3.0\n4.0 5.0 6.0\n", contents) - + def test3(self): x = datamodel.Particles(2) x.mass = [1.0, 2.0] | units.MSun x.radius = [3.0, 4.0] | units.RSun - io.write_set_to_file(x, "test.csv","txt", attribute_types = (units.MSun, units.RSun)) - with open("test.csv", "r") as f: - contents = f.read() + with tempfile.NamedTemporaryFile() as tmp: + filename = tmp.name + io.write_set_to_file(x, filename, "txt", attribute_types=(units.MSun, units.RSun)) + with open(filename, "r") as f: + contents = f.read() self.assertEqual("#mass radius\n#MSun RSun\n1.0 3.0\n2.0 4.0\n", contents) - - os.remove("test.csv") - def test4(self): - mass = [1.0,2.0,3.0] | generic_unit_system.mass - length = [3.0,4.0,5.0] | generic_unit_system.length - + mass = [1.0, 2.0, 3.0] | generic_unit_system.mass + length = [3.0, 4.0, 5.0] | generic_unit_system.length + stream = StringIO() - output = text.TableFormattedText(stream = stream) + output = text.TableFormattedText(stream=stream) output.quantities = (mass, length) output.store() contents = stream.getvalue() self.assertEqual("#col(0) col(1)\n#mass length\n1.0 3.0\n2.0 4.0\n3.0 5.0\n", contents) - + def test5(self): x = datamodel.Particles(2) x.mass = [1.0, 2.0] | units.MSun x.radius = [3.0, 4.0] | units.RSun - + expected = [ "#mass radius\n#MSun RSun\n{0} 1.0 3.0\n{1} 2.0 4.0\n".format(x[0].key, x[1].key), "#mass radius\n#MSun RSun\n1.0 {0} 3.0\n2.0 {1} 4.0\n".format(x[0].key, x[1].key), "#mass radius\n#MSun RSun\n1.0 3.0 {0}\n2.0 4.0 {1}\n".format(x[0].key, x[1].key), ] for column_index, expected_content in enumerate(expected): - io.write_set_to_file( - x, - "test.csv", - "txt", - key_in_column = column_index, - attribute_types = (units.MSun, units.RSun) - ) - - with open("test.csv", "r") as f: - contents = f.read() - - self.assertEqual(expected_content, contents) - - y = io.read_set_from_file( - "test.csv", - "txt", - key_in_column = column_index, - attribute_types = (units.MSun, units.RSun), - attribute_names = ('mass', 'radius') - ) - + with tempfile.NamedTemporaryFile() as tmp: + filename = tmp.name + io.write_set_to_file( + x, + filename, + "txt", + key_in_column=column_index, + attribute_types=(units.MSun, units.RSun) + ) + + with open(filename, "r") as f: + contents = f.read() + + self.assertEqual(expected_content, contents) + + y = io.read_set_from_file( + filename, + "txt", + key_in_column=column_index, + attribute_types=(units.MSun, units.RSun), + attribute_names=('mass', 'radius') + ) + self.assertEqual(y[0], x[0]) self.assertEqual(y[1], x[1]) - os.remove("test.csv") - - - + def test6(self): p = datamodel.Particles(2) p.a = [1., 4.] p.b = [2, 5] | units.m p.c = [3, 6] | units.m - + data_file = StringIO() instance = text.TableFormattedText("test.txt", data_file, p) instance.attribute_types = [None, units.m, units.m] instance.store() - + contents = data_file.getvalue() self.assertEqual("#a b c\n#- m m\n1.0 2.0 3.0\n4.0 5.0 6.0\n", contents) - + def test7(self): p = datamodel.Particles(2) p.a = [1.0, 4.0] p.b = [2, 5] | units.m p.c = [3, 6] | units.m - + data_file = StringIO() instance = text.TableFormattedText("test.txt", data_file, p) instance.store() - + contents = data_file.getvalue() self.assertEqual("#a b c\n#- m m\n1.0 2.0 3.0\n4.0 5.0 6.0\n", contents) - + def test8(self): - table = io.ReportTable( - "test.csv", - "txt", - attribute_types = (units.MSun, units.RSun) - ) - table.add_row(1.0 | units.MSun, 3.0 | units.RSun) - table.add_row(2.0 | units.MSun, 4.0 | units.RSun) - table.close() - - with open("test.csv", "r") as f: - contents = f.read() + with tempfile.NamedTemporaryFile() as tmp: + filename = tmp.name + table = io.ReportTable( + filename, + "txt", + attribute_types=(units.MSun, units.RSun) + ) + table.add_row(1.0 | units.MSun, 3.0 | units.RSun) + table.add_row(2.0 | units.MSun, 4.0 | units.RSun) + table.close() + + with open(filename, "r") as f: + contents = f.read() self.assertEqual("#MSun RSun\n1.0 3.0\n2.0 4.0\n", contents) - - - os.remove("test.csv") - + def test9(self): p = datamodel.Particles(5) p.a = [1.0, 2.0, 3.0, 4.0, 5.0] p.b = [10, 11, 12, 13, 14] | units.m p.c = [20, 21, 22, 23, 24] | units.m - - io.write_set_to_file( - p, - "test.csv", - "txt", - attribute_names = ('a', 'b', 'c'), - attribute_types = (None, units.m, units.m), - maximum_number_of_lines_buffered = 1, - ) - with open("test.csv", "r") as f: - contents = f.read() - - expected_contents = '#a b c\n#- m m\n1.0 10.0 20.0\n2.0 11.0 21.0\n3.0 12.0 22.0\n4.0 13.0 23.0\n5.0 14.0 24.0\n' - self.assertEqual(expected_contents, contents) - p2 = io.read_set_from_file( - "test.csv", - "txt", - attribute_names = ('a', 'b', 'c'), - attribute_types = (None, units.m, units.m), - maximum_number_of_lines_buffered = 1, - ) + + with tempfile.NamedTemporaryFile() as tmp: + filename = tmp.name + io.write_set_to_file( + p, + filename, + "txt", + attribute_names=('a', 'b', 'c'), + attribute_types=(None, units.m, units.m), + maximum_number_of_lines_buffered=1, + ) + with open(filename, "r") as f: + contents = f.read() + + expected_contents = '#a b c\n#- m m\n1.0 10.0 20.0\n2.0 11.0 21.0\n3.0 12.0 22.0\n4.0 13.0 23.0\n5.0 14.0 24.0\n' + self.assertEqual(expected_contents, contents) + p2 = io.read_set_from_file( + filename, + "txt", + attribute_names=('a', 'b', 'c'), + attribute_types=(None, units.m, units.m), + maximum_number_of_lines_buffered=1, + ) self.assertAlmostRelativeEquals(p2.a, p.a) self.assertAlmostRelativeEquals(p2.b, p.b) self.assertAlmostRelativeEquals(p2.c, p.c) - + def test10(self): - p = datamodel.Particles(keys=[30,31,32,33,34]) + p = datamodel.Particles(keys=[30, 31, 32, 33, 34]) p.a = [1.0, 2.0, 3.0, 4.0, 5.0] p.b = [10, 11, 12, 13, 14] | units.m p.c = [20, 21, 22, 23, 24] | units.m - io.write_set_to_file( - p, - "test.csv", - "txt", - attribute_names = ('a', 'b', 'c'), - attribute_types = (None, units.m, units.m), - maximum_number_of_lines_buffered = 1, - key_in_column = 0 - ) - with open("test.csv", "r") as f: - contents = f.read() - expected_contents = '#a b c\n#- m m\n30 1.0 10.0 20.0\n31 2.0 11.0 21.0\n32 3.0 12.0 22.0\n33 4.0 13.0 23.0\n34 5.0 14.0 24.0\n' - self.assertEqual(expected_contents, contents) - p2 = io.read_set_from_file( - "test.csv", - "txt", - attribute_names = ('a', 'b', 'c'), - attribute_types = (None, units.m, units.m), - maximum_number_of_lines_buffered = 1, - key_in_column = 0 - ) + with tempfile.NamedTemporaryFile() as tmp: + filename = tmp.name + io.write_set_to_file( + p, + filename, + "txt", + attribute_names=('a', 'b', 'c'), + attribute_types=(None, units.m, units.m), + maximum_number_of_lines_buffered=1, + key_in_column=0 + ) + with open(filename, "r") as f: + contents = f.read() + expected_contents = '#a b c\n#- m m\n30 1.0 10.0 20.0\n31 2.0 11.0 21.0\n32 3.0 12.0 22.0\n33 4.0 13.0 23.0\n34 5.0 14.0 24.0\n' + self.assertEqual(expected_contents, contents) + p2 = io.read_set_from_file( + filename, + "txt", + attribute_names=('a', 'b', 'c'), + attribute_types=(None, units.m, units.m), + maximum_number_of_lines_buffered=1, + key_in_column=0 + ) self.assertEqual(p2.key, p.key) self.assertAlmostRelativeEquals(p2.a, p.a) self.assertAlmostRelativeEquals(p2.b, p.b) self.assertAlmostRelativeEquals(p2.c, p.c) - + def test11(self): p = datamodel.Particles(200) p.a = 2 | units.m - - io.write_set_to_file( - p, - "test.csv", - "txt", - attribute_names = ('a'), - attribute_types = (units.m,), - maximum_number_of_lines_buffered = 10, - key_in_column = 0 - ) - p2 = io.read_set_from_file( - "test.csv", - "txt", - attribute_names = ('a'), - attribute_types = (units.m,), - maximum_number_of_lines_buffered = 10, - key_in_column = 0 - ) + + with tempfile.NamedTemporaryFile() as tmp: + filename = tmp.name + io.write_set_to_file( + p, + filename, + "txt", + attribute_names=('a'), + attribute_types=(units.m,), + maximum_number_of_lines_buffered=10, + key_in_column=0 + ) + p2 = io.read_set_from_file( + filename, + "txt", + attribute_names=('a'), + attribute_types=(units.m,), + maximum_number_of_lines_buffered=10, + key_in_column=0 + ) self.assertEqual(p2.key, p.key) self.assertAlmostRelativeEquals(p2.a, p.a) - + def test12(self): print("Test Text IO with specific data types (string, int, float)") - daltons = datamodel.Particles(keys=[30,31,32,33]) + daltons = datamodel.Particles(keys=[30, 31, 32, 33]) daltons.name = ["Joe", "William", "Jack", "Averell"] daltons.length = [1.1, 1.4, 1.7, 2.0] | core.unit_with_specific_dtype(units.m, "float32") daltons.age = [21, 20, 19, 18] | core.unit_with_specific_dtype(units.yr, "int32") - path=os.path.abspath(os.path.join(self.get_path_to_results(), "daltons.txt")) - io.write_set_to_file( - daltons, - path, - "txt", - attribute_names = ('name', 'length', 'age'), - attribute_types = (None, units.m, units.yr), - maximum_number_of_lines_buffered = 2, - key_in_column = 0 - ) - with open(path, "r") as f: - contents = f.read() - expected_contents = '#name length age\n#- m yr\n30 Joe 1.1 21\n31 William 1.4 20\n32 Jack 1.7 19\n33 Averell 2.0 18\n' - self.assertEqual(expected_contents, contents) - - read = io.read_set_from_file( - path, - "txt", - attribute_names = ('name', 'length', 'age'), - attribute_types = (None, units.m, units.yr), - attribute_dtypes = ("str", "float32", "int32"), - maximum_number_of_lines_buffered = 2, - key_in_column = 0 - ) + with tempfile.NamedTemporaryFile() as tmp: + filename = tmp.name + path = os.path.abspath(os.path.join(self.get_path_to_results(), filename)) + io.write_set_to_file( + daltons, + path, + "txt", + attribute_names=('name', 'length', 'age'), + attribute_types=(None, units.m, units.yr), + maximum_number_of_lines_buffered=2, + key_in_column=0 + ) + with open(path, "r") as f: + contents = f.read() + expected_contents = '#name length age\n#- m yr\n30 Joe 1.1 21\n31 William 1.4 20\n32 Jack 1.7 19\n33 Averell 2.0 18\n' + self.assertEqual(expected_contents, contents) + + read = io.read_set_from_file( + path, + "txt", + attribute_names=('name', 'length', 'age'), + attribute_types=(None, units.m, units.yr), + attribute_dtypes=("str", "float32", "int32"), + maximum_number_of_lines_buffered=2, + key_in_column=0 + ) self.assertEqual(read.key, daltons.key) self.assertEqual(read.name, daltons.name) self.assertEqual(read.length, daltons.length) @@ -293,61 +301,59 @@ def test12(self): self.assertTrue(read.name.dtype.kind in ["S", "U"]) self.assertEqual(str(read.length.value_in(units.m).dtype), "float32") self.assertEqual(str(read.age.value_in(units.yr).dtype), "int32") - def test13(self): p = datamodel.Particles(100) - p.a = numpy.arange(0,1,0.01) | units.m - - path=os.path.abspath(os.path.join(self.get_path_to_results(), "test.csv")) + p.a = numpy.arange(0, 1, 0.01) | units.m - io.write_set_to_file( - p, - path, - "amuse-txt", - attribute_names = ('a'), - maximum_number_of_lines_buffered = 10, - key_in_column = 0 - ) - p2 = io.read_set_from_file( - path, - "txt", - maximum_number_of_lines_buffered = 10, - key_in_column = 0 - ) + with tempfile.NamedTemporaryFile() as tmp: + filename = tmp.name + path = os.path.abspath(os.path.join(self.get_path_to_results(), filename)) + + io.write_set_to_file( + p, + path, + "amuse-txt", + attribute_names=('a'), + maximum_number_of_lines_buffered=10, + key_in_column=0 + ) + p2 = io.read_set_from_file( + path, + "txt", + maximum_number_of_lines_buffered=10, + key_in_column=0 + ) self.assertEqual(p2.key, p.key) self.assertAlmostRelativeEquals(p2.a, p.a) - - def test14(self): p = datamodel.Particles(100) - p.a = numpy.arange(0,1,0.01) | units.m - p.b = numpy.arange(0,1,0.01) - - io.write_set_to_file( - p, - "test.csv", - "amuse-txt", - maximum_number_of_lines_buffered = 10, - key_in_column = 0 - ) - p2 = io.read_set_from_file( - "test.csv", - "txt", - maximum_number_of_lines_buffered = 10, - key_in_column = 0 - ) + p.a = numpy.arange(0, 1, 0.01) | units.m + p.b = numpy.arange(0, 1, 0.01) + + with tempfile.NamedTemporaryFile() as tmp: + filename = tmp.name + io.write_set_to_file( + p, + filename, + "amuse-txt", + maximum_number_of_lines_buffered=10, + key_in_column=0 + ) + p2 = io.read_set_from_file( + filename, + "txt", + maximum_number_of_lines_buffered=10, + key_in_column=0 + ) self.assertEqual(p2.key, p.key) self.assertAlmostRelativeEquals(p2.a, p.a) self.assertAlmostRelativeEquals(p2.b, p.b) - - class CsvFileTextTests(amusetest.TestCase): - - + def test1(self): print("Test 1: Read comma separated values (CSV) - specified attributes") contents = "#header\n1,2,3\n4,5,6\n7,8,9\n" @@ -360,7 +366,7 @@ def test1(self): self.assertEqual(particles.a, [1, 4, 7] | units.none) self.assertEqual(particles.b, [2, 5, 8] | units.m) self.assertEqual(particles.c, [3, 6, 9] | units.m / units.s) - + def test2(self): print("Test 2: Read comma separated values (CSV) - attributes defined in header") contents = ("#a, b, c\n#no_system.get('none'),system.get('S.I.').base('length')," @@ -373,7 +379,7 @@ def test2(self): self.assertEqual(particles.a, [1, 4, 7] | units.none) self.assertEqual(particles.b, [2, 5, 8] | units.m) self.assertEqual(particles.c, [3, 6, 9] | units.m / units.s) - + def test3(self): print("Test 3: Read comma separated values (CSV) - generic units") contents = ("#a,b,c\n" @@ -388,42 +394,42 @@ def test3(self): self.assertEqual(particles.a, [1, 4] | generic_unit_system.mass) self.assertEqual(particles.b, [2, 5] | generic_unit_system.length) self.assertEqual(particles.c, [3, 6] | generic_unit_system.energy) - + def test4(self): print("Test 4: Write comma separated values (CSV) - specified attributes") particles = datamodel.Particles(2) particles.a = [1, 4] | units.none particles.b = [2, 5] | units.m particles.c = [3, 6] | units.kg / units.m**3 - + data_stream = StringIO() instance = text.CsvFileText(None, data_stream, particles) instance.attribute_names = ['a', 'b'] instance.attribute_types = [units.none, 100*units.cm] instance.store() - + contents = data_stream.getvalue() self.assertEqual("#a,b\n" "#no_system.get('none'),system.get('S.I.').base('length')\n" "#none,100 * cm\n1.0,2.0\n4.0,5.0\n", contents) - + def test5(self): print("Test 5: Write comma separated values (CSV) - attributes defined automatically") particles = datamodel.Particles(2) particles.a = [1, 4] | units.none particles.b = [2, 5] | units.m particles.c = [3, 6] | units.kg / units.m**3 - + data_stream = StringIO() instance = text.CsvFileText(None, data_stream, particles) instance.store() - + contents = data_stream.getvalue() self.assertEqual("#a,b,c\n" "#no_system.get('none'),system.get('S.I.').base('length')," "((system.get('S.I.').base('length')**-3) * system.get('S.I.').base('mass'))\n" "#none,m,m**-3 * kg\n1.0,2.0,3.0\n4.0,5.0,6.0\n", contents) - + def test6(self): print("Test 6: Write comma separated values (CSV) - generic units") particles = datamodel.Particles(2) @@ -431,23 +437,23 @@ def test6(self): particles.b = [2, 5] | generic_unit_system.length particles.c = [3, 6] | generic_unit_system.energy particles.d = [4, 7] | generic_unit_system.temperature - + data_stream = StringIO() instance = text.CsvFileText(None, data_stream, particles) instance.store() - + contents = data_stream.getvalue() self.assertEqual("#a,b,c,d\n" "#system.get('generic').base('mass'),system.get('generic').base('length')," "(((system.get('generic').base('length')**2) * (system.get('generic').base('time')**-2)) * " "system.get('generic').base('mass')),system.get('generic').base('thermodynamic temperature')\n" "#mass,length,length**2 * time**-2 * mass,thermodynamic temperature\n1.0,2.0,3.0,4.0\n4.0,5.0,6.0,7.0\n", contents) - + def test7(self): print("Test 7: Write CSV - quantities instead of set, names and types unspecified") a = [1.0, 4] | units.none b = [2.0, 5] | units.m - + data_stream = StringIO() instance = text.CsvFileText(None, data_stream) instance.quantities = [a, b] @@ -455,70 +461,69 @@ def test7(self): self.assertEqual("#col(0),col(1)\n" "#no_system.get('none'),system.get('S.I.').base('length')\n" "#none,m\n1.0,2.0\n4.0,5.0\n", data_stream.getvalue()) - + def test8(self): print("Test 8: Write CSV - quantities instead of set, types unspecified") a = [1.0, 4] | units.none b = [2.0, 5] | units.m - + data_stream = StringIO() instance = text.CsvFileText(None, data_stream) instance.quantities = [a, b] instance.attribute_names = ['a', 'b'] instance.store() - + self.assertEqual("#a,b\n" "#no_system.get('none'),system.get('S.I.').base('length')\n" "#none,m\n1.0,2.0\n4.0,5.0\n", data_stream.getvalue()) - + def test9(self): print("Test 9: Write CSV - quantities instead of set, names and types specified") a = [1.0, 4] | units.none b = [2.0, 5] | units.m - + data_stream = StringIO() instance = text.CsvFileText(None, data_stream) instance.quantities = [a, b] instance.attribute_names = ['a', 'b'] instance.attribute_types = [units.none, 100*units.cm] instance.store() - + self.assertEqual("#a,b\n" "#no_system.get('none'),system.get('S.I.').base('length')\n" "#none,100 * cm\n1.0,2.0\n4.0,5.0\n", data_stream.getvalue()) - + def test10(self): print("Test 10: User interface (write_set_to_file and read_set_from_file)") particles = datamodel.Particles(2) particles.a = [1, 4] | units.none particles.b = [2, 5] | units.m particles.c = [3, 6] | units.kg / units.m**3 - io.write_set_to_file(particles, "test_textio.csv","csv") - - read_particles = io.read_set_from_file("test_textio.csv", format = "csv") + io.write_set_to_file(particles, "test_textio.csv", "csv") + + read_particles = io.read_set_from_file("test_textio.csv", format="csv") self.assertEqual(len(read_particles), 2) self.assertEqual(read_particles.a, [1, 4] | units.none) self.assertEqual(read_particles.b, [2, 5] | units.m) self.assertEqual(read_particles.c, [3, 6] | units.kg / units.m**3) os.remove("test_textio.csv") - - + def test11(self): particles = datamodel.Particles(2) particles.a = [1, 4] particles.b = [2, 5] | units.m particles.c = [3, 6] | units.kg / units.m**3 io.write_set_to_file( - particles, + particles, "test_textio.csv", "csv", attribute_type=(None, units.kg / units.m**3, units.m), attribute_name=('a', 'c', 'b') ) - + read_particles = io.read_set_from_file( - "test_textio.csv", - format = "csv" + "test_textio.csv", + format="csv" ) self.assertEqual(len(read_particles), 2) self.assertEqual(read_particles.a, [1, 4]) @@ -526,8 +531,9 @@ def test11(self): self.assertEqual(read_particles.c, [3, 6] | units.kg / units.m**3) os.remove("test_textio.csv") + class Athena3DTextTests(amusetest.TestCase): - + def test1(self): contents = """\ # Nx1 = 128 @@ -541,14 +547,8 @@ def test1(self): data_file = StringIO(textwrap.dedent(contents)) instance = text.Athena3DText("test.tab", data_file) particles = instance.load() - + self.assertEqual(len(particles), 1) - self.assertEqual(particles[0].x1, 3.90625e-03 |units.none) - self.assertEqual(particles[0].i_zone, 4 |units.none) - self.assertEqual(particles[0].M1, -8.66511e-07 |units.none) - - - - - - + self.assertEqual(particles[0].x1, 3.90625e-03 | units.none) + self.assertEqual(particles[0].i_zone, 4 | units.none) + self.assertEqual(particles[0].M1, -8.66511e-07 | units.none) diff --git a/src/amuse/test/suite/core_tests/test_trees.py b/src/amuse/test/suite/core_tests/test_trees.py index 844d1e21e1..6f3b6f6cac 100644 --- a/src/amuse/test/suite/core_tests/test_trees.py +++ b/src/amuse/test/suite/core_tests/test_trees.py @@ -11,46 +11,49 @@ from amuse.datamodel import trees from amuse.datamodel import Particles + + class TestBinaryTree(amusetest.TestCase): - + def test1(self): particles = Particles(10) particles.mass = range(10) | units.kg particles[0].child1 = particles[1] particles[0].child2 = particles[2] - + self.assertEqual(particles[0].mass, 0 | units.kg) self.assertEqual(particles[0].child1.mass, 1 | units.kg) self.assertEqual(particles[1].child1, None) - + children1 = particles.child1.as_set().compressed() children2 = particles.child2.as_set().compressed() children = children1 + children2 roots = particles - children - + self.assertEqual(len(roots), 8) self.assertEqual(len(children), 2) - + def test2(self): n = 100000 particles = Particles(n) particles.mass = range(n) | units.kg particles[n-1].child1 = particles[0] particles[n-1].child2 = particles[1] - + self.assertEqual(particles[0].mass, 0 | units.kg) self.assertEqual(particles[n-1].child1.mass, 0 | units.kg) self.assertEqual(particles[n-1].child2.mass, 1 | units.kg) - + children1 = particles.child1.as_set().compressed() children2 = particles.child2.as_set().compressed() children = children1 + children2 roots = particles - children - + self.assertEqual(len(roots), n - 2) self.assertEqual(len(children), 2) - binaries = particles.select_array(lambda x : x != [None], ['child1',]) + binaries = particles.select_array(lambda x: x != [None], ['child1',]) self.assertEqual(len(binaries), 1) + def test3(self): n = 10 particles = Particles(n) @@ -59,22 +62,21 @@ def test3(self): particles[0].child2 = particles[2] particles[1].child1 = particles[3] particles[1].child2 = particles[4] - + self.assertEqual(particles[0].child1.child1.mass, 3 | units.kg) - - binaries = particles.select_array(lambda x : x != [None], ["child1",]) - + + binaries = particles.select_array(lambda x: x != [None], ["child1",]) + self.assertEqual(len(binaries), 2) - - binaries_children1 = binaries.child1.as_set().compressed().select_array(lambda x : x != [None], ["child1",]) - binaries_children2 = binaries.child2.as_set().compressed().select_array(lambda x : x != [None], ["child1",]) + + binaries_children1 = binaries.child1.as_set().compressed().select_array(lambda x: x != [None], ["child1",]) + binaries_children2 = binaries.child2.as_set().compressed().select_array(lambda x: x != [None], ["child1",]) binaries_roots = binaries - (binaries_children1 + binaries_children2) - + self.assertEqual(len(binaries_roots), 1) self.assertEqual(binaries_roots[0].mass, 0 | units.kg) - def test4(self): particles = Particles(10) particles.mass = range(10) | units.kg @@ -82,15 +84,14 @@ def test4(self): particles[0].child2 = particles[2] particles[1].child1 = particles[3] particles[1].child2 = particles[4] - - + x = trees.BinaryTreesOnAParticleSet(particles, "child1", "child2") roots = list(x.iter_roots()) - + self.assertEqual(len(roots), 1) x = [x.mass.value_in(units.kg) for x in roots[0].iter_descendants()] - self.assertEqual(x, [1,2,3,4]) - self.assertEqual(roots[0].get_descendants_subset().mass, [1,2,3,4] | units.kg) + self.assertEqual(x, [1, 2, 3, 4]) + self.assertEqual(roots[0].get_descendants_subset().mass, [1, 2, 3, 4] | units.kg) def test5(self): particles = Particles(10) @@ -99,63 +100,63 @@ def test5(self): particles[0].child2 = particles[2] particles[1].child1 = particles[3] particles[1].child2 = particles[4] - + x = trees.BinaryTreesOnAParticleSet(particles, "child1", "child2") roots = list(x.iter_roots()) - + self.assertEqual(len(roots), 1) y = [(event, x.mass.value_in(units.kg)) for event, x in roots[0].iter_events()] - self.assertEqual(y, + self.assertEqual(y, [ - ('start', 0.0), - ('start', 1.0), - ('start', 3.0), + ('start', 0.0), + ('start', 1.0), + ('start', 3.0), ('end', 3.0), ('start', 4.0), ('end', 4.0), - ('end', 1.0), - ('start', 2.0), - ('end', 2.0), + ('end', 1.0), + ('start', 2.0), + ('end', 2.0), ('end', 0.0) ] ) def test6(self): - + particles = Particles(10) particles.mass = range(10) | units.kg particles[0].child1 = particles[1] particles[0].child2 = particles[2] particles[1].child1 = particles[3] particles[1].child2 = particles[4] - + x = trees.BinaryTreesOnAParticleSet(particles, "child1", "child2") roots = list(x.iter_roots()) - + self.assertEqual(len(roots), 1) y = [(event, x.mass.value_in(units.kg)) for event, x in roots[0].iter_levels()] - self.assertEqual(y, + self.assertEqual(y, [ - (0, 0.0), - (1, 1.0), - (2, 3.0), + (0, 0.0), + (1, 1.0), + (2, 3.0), (2, 4.0), (1, 2.0), ] ) - + def test7(self): - + particles = Particles(10) particles.mass = range(10) | units.kg particles[0].child1 = particles[1] particles[0].child2 = particles[2] particles[1].child1 = particles[3] particles[1].child2 = particles[4] - + x = trees.BinaryTreesOnAParticleSet(particles, "child1", "child2") roots = list(x.iter_roots()) - + self.assertEqual(len(roots), 1) binary = roots[0] output = '' @@ -163,7 +164,7 @@ def test7(self): output += '..' * level output += str(particle.mass.value_in(units.kg)) output += '\n' - + self.assertEqual(output, """0.0 ..1.0 ....3.0 @@ -171,7 +172,6 @@ def test7(self): ..2.0 """) - def test8(self): particles = Particles(10) particles.mass = range(10) | units.kg @@ -179,25 +179,24 @@ def test8(self): particles[0].child2 = particles[2] particles[1].child1 = particles[3] particles[1].child2 = particles[4] - - + x = trees.BinaryTreesOnAParticleSet(particles, "child1", "child2") self.assertEqual(len(list(x.iter_roots())), 1) self.assertEqual(len(x.particles_not_in_a_multiple()), 5) - + class TestChildTree(amusetest.TestCase): - + def test1(self): particles = Particles(10) particles.mass = range(10) | units.kg particles[0].child1 = particles[1] particles[0].child2 = particles[2] - + self.assertEqual(particles[0].mass, 0 | units.kg) self.assertEqual(particles[0].child1.mass, 1 | units.kg) self.assertEqual(particles[1].child1, None) - + tree = particles.as_binary_tree() self.assertFalse(tree.is_leaf()) self.assertEqual(len(list(tree.iter_children())), 8) @@ -207,19 +206,17 @@ def test1(self): self.assertEqual(len(list(branches[0].iter_children())), 2) self.assertEqual(len(list(branches[0].iter_branches())), 0) self.assertEqual(len(list(branches[0].iter_leafs())), 2) - - - + def test2(self): particles = Particles(10) particles.mass = range(10) | units.kg particles[0].child1 = particles[1] particles[0].child2 = particles[2] - + self.assertEqual(particles[0].mass, 0 | units.kg) self.assertEqual(particles[0].child1.mass, 1 | units.kg) self.assertEqual(particles[1].child1, None) - + tree = particles.as_binary_tree() self.assertFalse(tree.is_leaf()) self.assertEqual(len(list(tree.iter_descendant_leafs())), 9) @@ -228,7 +225,6 @@ def test2(self): self.assertEqual(len(list(branches[0].iter_descendant_leafs())), 2) self.assertEqual(len(list(branches[0].iter_descendant_branches())), 0) - def test3(self): particles = Particles(10) particles.mass = range(10) | units.kg @@ -238,8 +234,7 @@ def test3(self): particles[1].child2 = particles[4] particles[2].child1 = particles[5] particles[2].child2 = particles[6] - - + tree = particles.as_binary_tree() self.assertFalse(tree.is_leaf()) self.assertEqual(len(list(tree.iter_children())), 4) @@ -253,7 +248,7 @@ def test3(self): self.assertEqual(len(list(branches[0].iter_leafs())), 0) self.assertEqual(len(list(branches[0].iter_descendant_leafs())), 4) self.assertEqual(len(list(branches[0].iter_descendant_branches())), 2) - + def test4(self): particles = Particles(10) particles.mass = range(10) | units.kg @@ -263,7 +258,7 @@ def test4(self): particles[1].child2 = particles[3] particles[2].child1 = particles[6] particles[2].child2 = particles[5] - + tree = particles.as_binary_tree() masses = [] | units.kg stack = list(reversed(tree.get_children())) @@ -271,21 +266,21 @@ def test4(self): x = stack.pop() masses.append(x.particle.mass) stack.extend(reversed(x.get_children())) - - self.assertEqual(masses, [0,2,6,5,1,4,3,7,8,9] | units.kg) - + + self.assertEqual(masses, [0, 2, 6, 5, 1, 4, 3, 7, 8, 9] | units.kg) + def test5(self): - + particles = Particles(10) particles.mass = range(10) | units.kg particles[0].child1 = particles[1] particles[0].child2 = particles[2] particles[1].child1 = particles[3] particles[1].child2 = particles[4] - + x = particles.as_binary_tree() roots = list(x.iter_branches()) - + self.assertEqual(len(roots), 1) binary = roots[0] output = '' @@ -293,11 +288,10 @@ def test5(self): output += '..' * level output += str(node.particle.mass.value_in(units.kg)) output += '\n' - + self.assertEqual(output, """0.0 ..1.0 ....3.0 ....4.0 ..2.0 """) - diff --git a/src/amuse/test/suite/core_tests/test_unit_conversion.py b/src/amuse/test/suite/core_tests/test_unit_conversion.py index ce787dbfe7..1ce8f83549 100644 --- a/src/amuse/test/suite/core_tests/test_unit_conversion.py +++ b/src/amuse/test/suite/core_tests/test_unit_conversion.py @@ -4,90 +4,87 @@ from amuse.support.exceptions import AmuseException - from amuse.units import core from amuse.units.units import * from amuse.units.constants import * + + class TestUnitConversions(amusetest.TestCase): def test1(self): km = 1000 * m self.assertEqual(1000, km.value_in(m)) self.assertEqual(0.001, m.value_in(km)) - + def test2(self): km = 1000 * m val = km(10) self.assertEqual(10000, val.value_in(m)) - + def test3(self): km = 1000.0 * m val = km(10) self.assertEqual("10 1000.0 * m", str(val)) - - km = named('kilometer','km',1000 * m) + + km = named('kilometer', 'km', 1000 * m) val = km(10) self.assertEqual("10 km", str(val)) - + def test4(self): - km = named('kilometer','km',1000 * m) - h = named('hour','h',60 * 60 * s) + km = named('kilometer', 'km', 1000 * m) + h = named('hour', 'h', 60 * 60 * s) kmh = km/h ms = m/s val = 10 | m/s - self.assertEqual(36,val.value_in(kmh)) - + self.assertEqual(36, val.value_in(kmh)) + def test5(self): - km = named('kilometer','km',1000 * m) - h = named('hour','h',60 * 60 * s) + km = named('kilometer', 'km', 1000 * m) + h = named('hour', 'h', 60 * 60 * s) kmh = km/h ms = m/s val = 10 | ms - self.assertEqual(36,val.value_in(kmh)) - + self.assertEqual(36, val.value_in(kmh)) + def test6(self): no1 = m / m no2 = no_unit self.assertEqual("m / m", str(no1)) self.assertTrue(no1.has_same_base_as(no2)) - def test7(self): - x = (100 * kg ** 2) / kg + x = (100 * kg ** 2) / kg self.assertEqual("100 * kg**2 / kg", str(x)) self.assertEqual("100.0 * kg", str(x.to_simple_form())) - - + def test8(self): - x = (10 | g) * (2 | m) + x = (10 | g) * (2 | m) self.assertEqual("20 0.001 * m * kg", str(x)) self.assertEqual("0.02 kg * m", str(x.as_quantity_in(kg * m))) - x = (10 | kg) * (2000 | g) + x = (10 | kg) * (2000 | g) self.assertEqual("20000 0.001 * kg**2", str(x)) - + def test9(self): speed_of_light = 1 | (lightyear * yr**-1) time = 1e-9 | s length = speed_of_light * time length_in_m = length.value_in(m) self.assertAlmostEqual(0.2997988, length_in_m, 6) - + def test10(self): eps0_1 = mu0**-1*c**-2 eps0_2 = (1 | none)/(mu0*(c**2)) self.assertTrue((eps0_1 - eps0_2) / eps0_1 < (1e-10 | none)) - b =((1.|e)**2) - f = (hbar*c*4.*numpy.pi* eps0)**-1 + b = ((1. | e)**2) + f = (hbar*c*4.*numpy.pi * eps0)**-1 fine_structure_constant_calculated = (b * f) fine_structure_constant = 7.297352537650e-3 self.assertAlmostEqual(fine_structure_constant_calculated, fine_structure_constant, 5) - - def test11(self): vel1 = 1 | m / s - self.assertRaises(core.IncompatibleUnitsException, vel1.as_quantity_in, s / m, - expected_message = "Cannot express m / s in s / m, the units do not have the same bases") - + self.assertRaises(core.IncompatibleUnitsException, vel1.as_quantity_in, s / m, + expected_message="Cannot express m / s in s / m, the units do not have the same bases") + def test12(self): self.assertEqual((1234 | g).as_string_in(g), '1234 g') self.assertEqual((1234 | g).as_string_in(kg), '1.234 kg') @@ -97,84 +94,80 @@ def test12(self): self.assertEqual((1.0 | km / s).as_string_in((10*J/g)**0.5), '10.0 (10 * J / g)**0.5') def test13(self): - self.assertAlmostRelativeEquals((1234 | km ** (5/3.)).value_in( (km ** 5.0) ** (1.0/3.0) ), 1234.0, 12) - self.assertAlmostRelativeEquals((1234 | km ** (5/3.)).value_in( (m ** 5.0) ** (1.0/3.0) ), 123400000.0) - + self.assertAlmostRelativeEquals((1234 | km ** (5/3.)).value_in((km ** 5.0) ** (1.0/3.0)), 1234.0, 12) + self.assertAlmostRelativeEquals((1234 | km ** (5/3.)).value_in((m ** 5.0) ** (1.0/3.0)), 123400000.0) + def test15(self): - self.assertAlmostRelativeEquals( (m / s).to_array_of_floats(), [1, 1, 1, 0, -1, 0, 0, 0, 0]) - self.assertAlmostRelativeEquals( (s / m).to_array_of_floats(), [1, 1, -1, 0, 1, 0, 0, 0, 0]) - self.assertAlmostRelativeEquals( (kg ** 2/ s).to_array_of_floats(), [1, 1, 0, 2, -1, 0, 0, 0, 0]) - + self.assertAlmostRelativeEquals((m / s).to_array_of_floats(), [1, 1, 1, 0, -1, 0, 0, 0, 0]) + self.assertAlmostRelativeEquals((s / m).to_array_of_floats(), [1, 1, -1, 0, 1, 0, 0, 0, 0]) + self.assertAlmostRelativeEquals((kg ** 2 / s).to_array_of_floats(), [1, 1, 0, 2, -1, 0, 0, 0, 0]) class TestNonNumericUnits(amusetest.TestCase): def test1(self): string1 = "string" | string - self.assertRaises(AmuseException, string1.as_quantity_in, m, - expected_message = "Cannot convert non-numeric quantities in to another unit") + self.assertRaises(AmuseException, string1.as_quantity_in, m, + expected_message="Cannot convert non-numeric quantities in to another unit") def test2(self): x = "test" | string - self.assertEqual("test", x.value_in(string)) - + self.assertEqual("test", x.value_in(string)) + def test3(self): test_unit = core.enumeration_unit( - "test", "test", - [1,2,3], + "test", + [1, 2, 3], ["one", "two", "three"] ) x = 1 | test_unit - self.assertEqual(1, x.value_in(test_unit)) - self.assertEqual("one", str(x)) - self.assertRaises(Exception, lambda: 4 | test_unit, - expected_message = "<4> is not a valid value for unit") - + self.assertEqual(1, x.value_in(test_unit)) + self.assertEqual("one", str(x)) + self.assertRaises(Exception, lambda: 4 | test_unit, + expected_message="<4> is not a valid value for unit") + def test4(self): - self.assertRaises(Exception, lambda: 1 | string, - expected_message = "<1> is not a valid value for unit") - + self.assertRaises(Exception, lambda: 1 | string, + expected_message="<1> is not a valid value for unit") + def test5(self): test_unit = core.enumeration_unit( - "test", "test", - [1,2,3], + "test", + [1, 2, 3], ["one", "two", "three"] ) - self.assertEqual(3, len(list(test_unit.quantities()))) - for x, y in zip(test_unit.quantities(), ["one", "two", "three"]): + self.assertEqual(3, len(list(test_unit.quantities()))) + for x, y in zip(test_unit.quantities(), ["one", "two", "three"]): self.assertEqual(str(x), y) - - + def test6(self): test_unit = core.enumeration_unit( - "test", "test", - [1,4,7] + "test", + [1, 4, 7] ) - self.assertEqual(3, len(list(test_unit.quantities()))) - for x, y in zip(test_unit.quantities(), ["1", "4", "7"]): + self.assertEqual(3, len(list(test_unit.quantities()))) + for x, y in zip(test_unit.quantities(), ["1", "4", "7"]): self.assertEqual(str(x), y) - + def test7(self): test_unit = core.enumeration_unit( - "test", + "test", "test", range(5) ) self.assertEqual(5, len(list(test_unit.quantities()))) self.assertEqual(1 | test_unit, 1 | test_unit) - self.assertTrue (1 | test_unit == 1 | test_unit) + self.assertTrue(1 | test_unit == 1 | test_unit) self.assertFalse(1 | test_unit == 2 | test_unit) - self.assertTrue (1 | test_unit != 2 | test_unit) + self.assertTrue(1 | test_unit != 2 | test_unit) self.assertFalse(1 | test_unit != 1 | test_unit) - self.assertTrue (1 | test_unit >= 1 | test_unit) + self.assertTrue(1 | test_unit >= 1 | test_unit) self.assertFalse(1 | test_unit >= 2 | test_unit) - self.assertTrue (1 | test_unit <= 1 | test_unit) + self.assertTrue(1 | test_unit <= 1 | test_unit) self.assertFalse(1 | test_unit <= 0 | test_unit) - self.assertTrue (1 | test_unit > 0 | test_unit) - self.assertFalse(1 | test_unit > 1 | test_unit) - self.assertTrue (1 | test_unit < 3 | test_unit) - self.assertFalse(1 | test_unit < 0 | test_unit) - - + self.assertTrue(1 | test_unit > 0 | test_unit) + self.assertFalse(1 | test_unit > 1 | test_unit) + self.assertTrue(1 | test_unit < 3 | test_unit) + self.assertFalse(1 | test_unit < 0 | test_unit) diff --git a/src/amuse/test/suite/core_tests/test_vtkio.py b/src/amuse/test/suite/core_tests/test_vtkio.py index e9e1a93de9..8970fd1792 100644 --- a/src/amuse/test/suite/core_tests/test_vtkio.py +++ b/src/amuse/test/suite/core_tests/test_vtkio.py @@ -12,77 +12,76 @@ from amuse.units import generic_unit_system from amuse import datamodel + class VtkStructuredGridTests(amusetest.TestCase): - + def test1(self): - grid = datamodel. new_regular_grid([2,3,4], [1,1,1] | generic_unit_system.length) + grid = datamodel. new_regular_grid([2, 3, 4], [1, 1, 1] | generic_unit_system.length) grid.rho = grid.x * (0.1 | generic_unit_system.mass / generic_unit_system.length ** 4) data_file = StringIO() instance = vtk.VtkStructuredGrid("test.vts", data_file, grid) instance.store() - + contents = data_file.getvalue() - self.assertTrue(contents.find('WholeExtent="0 2 0 3 0 4"')> 0) - self.assertTrue(contents.find('')> 0) - self.assertTrue(contents.find('')> 0) - + self.assertTrue(contents.find('WholeExtent="0 2 0 3 0 4"') > 0) + self.assertTrue(contents.find('') > 0) + self.assertTrue(contents.find('') > 0) def test2(self): - grid = datamodel. new_regular_grid([4,5,6], [1,1,1] | generic_unit_system.length) - grid.mass = generic_unit_system.density(numpy.random.rand(4,5,6)) + grid = datamodel. new_regular_grid([4, 5, 6], [1, 1, 1] | generic_unit_system.length) + grid.mass = generic_unit_system.density(numpy.random.rand(4, 5, 6)) data_file = StringIO() instance = vtk.VtkStructuredGrid("test.vts", data_file, grid) instance.store() - + contents = data_file.getvalue() - self.assertTrue(contents.find('')> 0) - self.assertTrue(contents.find('')> 0) - self.assertTrue(contents.find('')> 0) - self.assertTrue(contents.find('')> 0) - self.assertTrue(contents.find('')> 0) - + self.assertTrue(contents.find('') > 0) + self.assertTrue(contents.find('') > 0) + self.assertTrue(contents.find('') > 0) + self.assertTrue(contents.find('') > 0) + self.assertTrue(contents.find('') > 0) + + class VtkUnstructuredGridTests(amusetest.TestCase): - + def test1(self): - grid = datamodel. new_regular_grid([2,3,4], [1,1,1] | generic_unit_system.length) + grid = datamodel. new_regular_grid([2, 3, 4], [1, 1, 1] | generic_unit_system.length) grid.rho = grid.x * (0.1 | generic_unit_system.mass / generic_unit_system.length ** 4) data_file = StringIO() instance = vtk.VtkUnstructuredGrid("test.vtu", data_file, grid) instance.store() contents = data_file.getvalue() - - self.assertTrue(contents.find(' 0) - self.assertTrue(contents.find('DataArray type="Int32" NumberOfComponents="1" Name="connectivity">')> 0) - self.assertTrue(contents.find('DataArray type="Int32" NumberOfComponents="1" Name="offsets">')> 0) - self.assertTrue(contents.find('11 11 11')> 0) - self.assertTrue(contents.find('8 16 24')> 0) - self.assertTrue(contents.find('DataArray type="Float64" NumberOfComponents="3" Name="points">')> 0) - - + + self.assertTrue(contents.find(' 0) + self.assertTrue(contents.find('DataArray type="Int32" NumberOfComponents="1" Name="connectivity">') > 0) + self.assertTrue(contents.find('DataArray type="Int32" NumberOfComponents="1" Name="offsets">') > 0) + self.assertTrue(contents.find('11 11 11') > 0) + self.assertTrue(contents.find('8 16 24') > 0) + self.assertTrue(contents.find('DataArray type="Float64" NumberOfComponents="3" Name="points">') > 0) + def test2(self): - grid = datamodel. new_regular_grid([2,2,2], [1,1,1] | generic_unit_system.length) + grid = datamodel. new_regular_grid([2, 2, 2], [1, 1, 1] | generic_unit_system.length) grid.rho = grid.x * (0.1 | generic_unit_system.mass / generic_unit_system.length ** 4) data_file = StringIO() instance = vtk.VtkUnstructuredGrid("test.vtu", data_file, grid) instance.store() contents = data_file.getvalue() - - self.assertTrue(contents.find(' 0) - self.assertTrue(contents.find('DataArray type="Int32" NumberOfComponents="1" Name="connectivity">')> 0) - self.assertTrue(contents.find('DataArray type="Int32" NumberOfComponents="1" Name="offsets">')> 0) - self.assertTrue(contents.find('11 11 11')> 0) - self.assertTrue(contents.find('56 64')> 0) - self.assertTrue(contents.find('DataArray type="Float64" NumberOfComponents="3" Name="points">')> 0) - self.assertTrue(contents.find('')>0) - - + + self.assertTrue(contents.find(' 0) + self.assertTrue(contents.find('DataArray type="Int32" NumberOfComponents="1" Name="connectivity">') > 0) + self.assertTrue(contents.find('DataArray type="Int32" NumberOfComponents="1" Name="offsets">') > 0) + self.assertTrue(contents.find('11 11 11') > 0) + self.assertTrue(contents.find('56 64') > 0) + self.assertTrue(contents.find('DataArray type="Float64" NumberOfComponents="3" Name="points">') > 0) + self.assertTrue(contents.find('') > 0) + def test3(self): - grid1 = datamodel. new_regular_grid([2,2,2], [1,1,1] | generic_unit_system.length) + grid1 = datamodel. new_regular_grid([2, 2, 2], [1, 1, 1] | generic_unit_system.length) grid1.rho = grid1.x * (0.1 | generic_unit_system.mass / generic_unit_system.length ** 4) - grid2 = datamodel. new_regular_grid([2,2,2], [1,1,1] | generic_unit_system.length) - grid2.position += [1.0,0.0,0.0] | generic_unit_system.length + grid2 = datamodel. new_regular_grid([2, 2, 2], [1, 1, 1] | generic_unit_system.length) + grid2.position += [1.0, 0.0, 0.0] | generic_unit_system.length grid2.rho = grid2.x * (0.1 | generic_unit_system.mass / generic_unit_system.length ** 4) - + data_file = StringIO() instance = vtk.VtkUnstructuredGrid("test.vtu", data_file, [grid1, grid2]) instance.store() @@ -91,10 +90,9 @@ def test3(self): index_of_piece_2 = contents.find(' 0) self.assertTrue(index_of_piece_2 > 0) - self.assertTrue(contents.find('DataArray type="Int32" NumberOfComponents="1" Name="connectivity">')> 0) - self.assertTrue(contents.find('DataArray type="Int32" NumberOfComponents="1" Name="offsets">')> 0) - self.assertTrue(contents.find('11 11 11')> 0) - self.assertTrue(contents.find('56 64')> 0) - self.assertTrue(contents.find('DataArray type="Float64" NumberOfComponents="3" Name="points">')> 0) - self.assertTrue(contents.find('')>0) - + self.assertTrue(contents.find('DataArray type="Int32" NumberOfComponents="1" Name="connectivity">') > 0) + self.assertTrue(contents.find('DataArray type="Int32" NumberOfComponents="1" Name="offsets">') > 0) + self.assertTrue(contents.find('11 11 11') > 0) + self.assertTrue(contents.find('56 64') > 0) + self.assertTrue(contents.find('DataArray type="Float64" NumberOfComponents="3" Name="points">') > 0) + self.assertTrue(contents.find('') > 0) diff --git a/src/amuse/test/suite/ext_tests/test_boss_bodenheimer.py b/src/amuse/test/suite/ext_tests/test_boss_bodenheimer.py index e9ca702835..88d0ab5153 100644 --- a/src/amuse/test/suite/ext_tests/test_boss_bodenheimer.py +++ b/src/amuse/test/suite/ext_tests/test_boss_bodenheimer.py @@ -8,25 +8,25 @@ numpy.random.seed(1234567) + class BossBodenheimerTests(amusetest.TestCase): def test1(self): numpy.random.seed(1234) - mc=bb79_cloud(targetN=1000).result - self.assertEqual(len(mc),1000) - ek=mc.kinetic_energy() - ep=mc.potential_energy(G=nbody_system.G) - eth=mc.thermal_energy() + mc = bb79_cloud(targetN=1000).result + self.assertEqual(len(mc), 1000) + ek = mc.kinetic_energy() + ep = mc.potential_energy(G=nbody_system.G) + eth = mc.thermal_energy() self.assertAlmostEqual(eth/ep, -0.25, 2) self.assertAlmostEqual(ek/ep, -0.2, 2) def test2(self): numpy.random.seed(1234) - convert=nbody_system.nbody_to_si(1. | units.MSun,3.2e16| units.cm) - mc=bb79_cloud(targetN=1000,convert_nbody=convert).result - self.assertEqual(len(mc),1000) - ek=mc.kinetic_energy() - ep=mc.potential_energy() - eth=mc.thermal_energy() + convert = nbody_system.nbody_to_si(1. | units.MSun, 3.2e16 | units.cm) + mc = bb79_cloud(targetN=1000, convert_nbody=convert).result + self.assertEqual(len(mc), 1000) + ek = mc.kinetic_energy() + ep = mc.potential_energy() + eth = mc.thermal_energy() self.assertAlmostEqual(eth/ep, -0.25, 2) self.assertAlmostEqual(ek/ep, -0.2, 2) - diff --git a/src/amuse/test/suite/ext_tests/test_brokenimf.py b/src/amuse/test/suite/ext_tests/test_brokenimf.py index 8ec5e855f1..63a71b142d 100644 --- a/src/amuse/test/suite/ext_tests/test_brokenimf.py +++ b/src/amuse/test/suite/ext_tests/test_brokenimf.py @@ -7,8 +7,9 @@ # Instead of random, use evenly distributed numbers, just for testing default_options = dict(random=False) + class TestMultiplePartIMF(amusetest.TestCase): - + def test1(self): print("Test MultiplePartIMF with default mass_boundaries and alphas, i.e. Salpeter") instance = MultiplePartIMF(mass_max=100.0 | units.MSun) @@ -17,28 +18,28 @@ def test1(self): self.assertEqual(instance.number_of_bins, 1) self.assertEqual(instance.fraction_per_bin, [1.0]) self.assertEqual(instance.cumulative_fractions, [0.0, 1.0]) - + self.assertAlmostEqual(instance.mass([0.0]), 0.1 | units.MSun) self.assertAlmostEqual(instance.mass([1.0]), 100.0 | units.MSun) self.assertAlmostEqual(instance.mass_mean(), 0.351 | units.MSun, 3) - + def test2(self): print("Test MultiplePartIMF with mass_boundaries and alphas") - instance = MultiplePartIMF(mass_boundaries = [1.0, 10.0, 100.0] | units.MSun, - alphas = [1.3, -3.3], **default_options) + instance = MultiplePartIMF(mass_boundaries=[1.0, 10.0, 100.0] | units.MSun, + alphas=[1.3, -3.3], **default_options) self.assertEqual(instance.mass_boundaries, [1.0, 10.0, 100.0] | units.MSun) self.assertEqual(instance.alphas, [1.3, -3.3]) self.assertEqual(instance.number_of_bins, 2) self.assertAlmostEqual(instance.fraction_per_bin, numpy.array([0.5, 0.5])) self.assertEqual(instance.cumulative_fractions, [0.0, 0.5, 1.0]) - + self.assertAlmostEqual(instance.mass([0.0]), 1.0 | units.MSun) self.assertAlmostEqual(instance.mass([0.5]), 10.0 | units.MSun) self.assertAlmostEqual(instance.mass([1.0]), 100.0 | units.MSun) - + self.assertAlmostEqual(instance.mass_mean(), 11.9457684987 | units.MSun) self.assertAlmostEqual(instance.mass_mean(), instance.next_mass(10000).mean(), 2) - + def test3(self): print("Test new_broken_power_law_mass_distribution with default mass_boundaries and alphas, i.e. Salpeter") masses = new_broken_power_law_mass_distribution(10000, mass_max=100.0 | units.MSun, **default_options) @@ -46,27 +47,27 @@ def test3(self): self.assertTrue((masses <= 100.0 | units.MSun).all()) self.assertAlmostEqual(min(masses), 0.1 | units.MSun) self.assertAlmostEqual(max(masses), 100.0 | units.MSun) - - mass_mean = MultiplePartIMF(mass_boundaries=[0.1, 100.0]|units.MSun, + + mass_mean = MultiplePartIMF(mass_boundaries=[0.1, 100.0] | units.MSun, alphas=[-2.35]).mass_mean() self.assertAlmostEqual(mass_mean, 0.35136877959 | units.MSun) self.assertAlmostRelativeEqual(masses.mean(), 0.351 | units.MSun, 1) - + def test4(self): print("Test new_broken_power_law_mass_distribution with mass_boundaries and alphas") - masses = new_broken_power_law_mass_distribution(10000, - mass_boundaries = [1.0, 10.0, 100.0] | units.MSun, - alphas = [1.3, -3.3], **default_options) + masses = new_broken_power_law_mass_distribution(10000, + mass_boundaries=[1.0, 10.0, 100.0] | units.MSun, + alphas=[1.3, -3.3], **default_options) self.assertTrue((masses >= 1.0 | units.MSun).all()) self.assertTrue((masses <= 100.0 | units.MSun).all()) self.assertAlmostEqual(min(masses), 1.0 | units.MSun) self.assertAlmostEqual(max(masses), 100.0 | units.MSun) - - mass_mean = MultiplePartIMF(mass_boundaries=[1.0, 10.0, 100.0]|units.MSun, + + mass_mean = MultiplePartIMF(mass_boundaries=[1.0, 10.0, 100.0] | units.MSun, alphas=[1.3, -3.3]).mass_mean() self.assertAlmostEqual(mass_mean, 11.9457684987 | units.MSun) self.assertAlmostRelativeEqual(masses.mean(), 11.9457684987 | units.MSun, 1) - + def test5(self): print("Test new_scalo_mass_distribution") masses = new_scalo_mass_distribution(10000, **default_options) @@ -74,12 +75,12 @@ def test5(self): self.assertTrue((masses <= 125.0 | units.MSun).all()) self.assertAlmostEqual(min(masses), 0.1 | units.MSun) self.assertAlmostEqual(max(masses), 125.0 | units.MSun) - - mass_mean = MultiplePartIMF(mass_boundaries=[0.10, 0.18, 0.42, 0.62, 1.18, 3.5, 125.0]|units.MSun, + + mass_mean = MultiplePartIMF(mass_boundaries=[0.10, 0.18, 0.42, 0.62, 1.18, 3.5, 125.0] | units.MSun, alphas=[1.6, -1.01, -2.75, -2.08, -3.5, -2.63]).mass_mean() self.assertAlmostEqual(mass_mean, 0.487756751788 | units.MSun) self.assertAlmostRelativeEqual(masses.mean(), 0.487756751788 | units.MSun, 1) - + def test6(self): print("Test new_miller_scalo_mass_distribution") masses = new_miller_scalo_mass_distribution(10000, **default_options) @@ -87,12 +88,12 @@ def test6(self): self.assertTrue((masses <= 125.0 | units.MSun).all()) self.assertAlmostEqual(min(masses), 0.1 | units.MSun) self.assertAlmostEqual(max(masses), 125.0 | units.MSun) - - mass_mean = MultiplePartIMF(mass_boundaries=[0.1, 1.0, 2.0, 10.0, 125.0]|units.MSun, + + mass_mean = MultiplePartIMF(mass_boundaries=[0.1, 1.0, 2.0, 10.0, 125.0] | units.MSun, alphas=[-1.25, -2.0, -2.3, -3.3]).mass_mean() self.assertAlmostEqual(mass_mean, 0.885783055149 | units.MSun) self.assertAlmostRelativeEqual(masses.mean(), 0.885783055149 | units.MSun, 1) - + def test7(self): print("Test new_kroupa_mass_distribution") masses = new_kroupa_mass_distribution(10000, **default_options) @@ -101,31 +102,29 @@ def test7(self): self.assertTrue((masses <= (100.0 * roundoff) | units.MSun).all()) self.assertAlmostEqual(min(masses), 0.01 | units.MSun) self.assertAlmostEqual(max(masses), 100.0 | units.MSun) - - mass_mean = MultiplePartIMF(mass_boundaries=[0.01, 0.08, 0.5, 100.0]|units.MSun, + + mass_mean = MultiplePartIMF(mass_boundaries=[0.01, 0.08, 0.5, 100.0] | units.MSun, alphas=[-0.3, -1.3, -2.3]).mass_mean() self.assertAlmostEqual(mass_mean, 0.376175542639 | units.MSun) self.assertAlmostRelativeEqual(masses.mean(), 0.376175542639 | units.MSun, 1) - + def test8(self): print("Test with problematic alphas (new_salpeter_mass_distribution would give zero division errors)") - masses = new_broken_power_law_mass_distribution(10000, - mass_boundaries = [1.0, 10.0, 100.0] | units.MSun, - alphas = [-1, -2], **default_options) + masses = new_broken_power_law_mass_distribution(10000, + mass_boundaries=[1.0, 10.0, 100.0] | units.MSun, + alphas=[-1, -2], **default_options) self.assertTrue((masses >= 1.0 | units.MSun).all()) roundoff = 1.0 + 1.0e-12 self.assertTrue((masses <= (100.0 * roundoff) | units.MSun).all()) self.assertAlmostEqual(min(masses), 1.0 | units.MSun) self.assertAlmostEqual(max(masses), 100.0 | units.MSun) - - mass_mean = MultiplePartIMF(mass_boundaries=[1.0, 10.0, 100.0] | units.MSun, + + mass_mean = MultiplePartIMF(mass_boundaries=[1.0, 10.0, 100.0] | units.MSun, alphas=[-1, -2]).mass_mean() self.assertAlmostEqual(mass_mean, 10.0 | units.MSun) self.assertAlmostRelativeEqual(masses.mean(), 10.0 | units.MSun, 1) - - masses = new_broken_power_law_mass_distribution(101, - mass_boundaries = [1.0, 100.0] | units.MSun, - alphas = [-1], **default_options) - self.assertAlmostEqual(masses.median(), 10.0 | units.MSun) - + masses = new_broken_power_law_mass_distribution(101, + mass_boundaries=[1.0, 100.0] | units.MSun, + alphas=[-1], **default_options) + self.assertAlmostEqual(masses.median(), 10.0 | units.MSun) diff --git a/src/amuse/test/suite/ext_tests/test_cloud.py b/src/amuse/test/suite/ext_tests/test_cloud.py index e1ec1b8cd7..57e1367890 100644 --- a/src/amuse/test/suite/ext_tests/test_cloud.py +++ b/src/amuse/test/suite/ext_tests/test_cloud.py @@ -10,59 +10,58 @@ from amuse.units import units from amuse.units import generic_unit_system from amuse import datamodel + + class CloudTests(amusetest.TestCase): def test1(self): - grid = datamodel.Grid.create((10,10,10), [10.0, 10.0, 10.0] | units.m) - + grid = datamodel.Grid.create((10, 10, 10), [10.0, 10.0, 10.0] | units.m) + grid.rho = 0.0 | units.kg / units.m**3 grid.rhovx = 0.0 | units.kg / (units.s * units.m**2) grid.rhovy = 0.0 | units.kg / (units.s * units.m**2) grid.rhovz = 0.0 | units.kg / (units.s * units.m**2) grid.energy = 1.0 | units.kg / ((units.s**2) * units.m) - - datamodel.Grid.add_global_vector_attribute("position", ["x","y","z"]) - + + datamodel.Grid.add_global_vector_attribute("position", ["x", "y", "z"]) + cloud.fill_grid_with_spherical_cloud( - grid, - center = [5.0, 5.0, 5.0] | units.m, - radius = 2.0 | units.m, - rho = 1.0 | units.kg / units.m**3, - rhovx = 0.0 | units.kg / (units.s * units.m**2), - rhovy = 0.1 | units.kg / (units.s * units.m**2), - rhovz = 0.0 | units.kg / (units.s * units.m**2), - energy = 1.0 | units.kg / ((units.s**2) * units.m) + grid, + center=[5.0, 5.0, 5.0] | units.m, + radius=2.0 | units.m, + rho=1.0 | units.kg / units.m**3, + rhovx=0.0 | units.kg / (units.s * units.m**2), + rhovy=0.1 | units.kg / (units.s * units.m**2), + rhovz=0.0 | units.kg / (units.s * units.m**2), + energy=1.0 | units.kg / ((units.s**2) * units.m) ) - - self.assertEqual(grid.shape, (10,10,10)) + + self.assertEqual(grid.shape, (10, 10, 10)) self.assertEqual(grid.rho[5][5][5], 1.0 | units.kg / units.m**3) - - #from mpl_toolkits.axes_grid1 import ImageGrid - #from matplotlib import pyplot - #figure = pyplot.figure() - #grids = ImageGrid(figure, 111, nrows_ncols = (2, 2), axes_pad=0.1) - #for i in range(4): + + # from mpl_toolkits.axes_grid1 import ImageGrid + # from matplotlib import pyplot + # figure = pyplot.figure() + # grids = ImageGrid(figure, 111, nrows_ncols = (2, 2), axes_pad=0.1) + # for i in range(4): # z = grid.rho[i+2].value_in( units.kg / units.m**3,) # grids[i].imshow(z) - #figure.savefig('ax.png') - - self.assertEqual(grid.rho[5][6][5], 0.828125| units.kg / units.m**3) - self.assertEqual(grid.rho[5][3][5], 0.828125| units.kg / units.m**3) - self.assertEqual(grid.rho[5][5][6], 0.828125| units.kg / units.m**3) - self.assertEqual(grid.rho[5][5][3], 0.828125| units.kg / units.m**3) + # figure.savefig('ax.png') + self.assertEqual(grid.rho[5][6][5], 0.828125 | units.kg / units.m**3) + self.assertEqual(grid.rho[5][3][5], 0.828125 | units.kg / units.m**3) + self.assertEqual(grid.rho[5][5][6], 0.828125 | units.kg / units.m**3) + self.assertEqual(grid.rho[5][5][3], 0.828125 | units.kg / units.m**3) def test2(self): n = 10 - grid = datamodel.Grid.create((n,n,n), [10.0, 10.0, 10.0] | generic_unit_system.length) - datamodel.Grid.add_global_vector_attribute("position", ["x","y","z"]) - + grid = datamodel.Grid.create((n, n, n), [10.0, 10.0, 10.0] | generic_unit_system.length) + datamodel.Grid.add_global_vector_attribute("position", ["x", "y", "z"]) + cloud.fill_grid_with_cloud_shock( - grid, - center = [5.0, 5.0, 5.0] | generic_unit_system.length, - radius = 1.0 | generic_unit_system.length, + grid, + center=[5.0, 5.0, 5.0] | generic_unit_system.length, + radius=1.0 | generic_unit_system.length, ) - + self.assertAlmostRelativeEquals(grid.rho[5][4][4], 0.5921875 | generic_unit_system.mass / generic_unit_system.length**3) - - diff --git a/src/amuse/test/suite/ext_tests/test_collision_handler.py b/src/amuse/test/suite/ext_tests/test_collision_handler.py index f112f567c8..f7ac21a1f8 100644 --- a/src/amuse/test/suite/ext_tests/test_collision_handler.py +++ b/src/amuse/test/suite/ext_tests/test_collision_handler.py @@ -8,255 +8,250 @@ class CollisionCodeForTesting(object): - + class ParametersForTesting(object): def __init__(self): self.mass_unit = units.kg - + stellar_evolution_code_required = False gravity_code_required = False - - def __init__(self, next_mass = 1 | units.kg): + + def __init__(self, next_mass=1 | units.kg): self.next_mass = next_mass self.parameters = self.ParametersForTesting() - + def handle_collision(self, primary, secondary, stellar_evolution_code=None): result = Particles(1) result.mass = self.next_mass.as_quantity_in(self.parameters.mass_unit) self.next_mass += 1 | units.kg - + if not stellar_evolution_code is None: se_colliders = (primary + secondary).get_intersecting_subset_in(stellar_evolution_code.particles) result.radius = se_colliders.radius.sum() - + def get_internal_structure(set, particle=None): return dict(mass=result.mass, radius=result.radius) - + result.add_function_attribute("get_internal_structure", None, get_internal_structure) - + return result - + class GravityCodeForTesting(object): - + def __init__(self): self.particles = Particles(6) self.particles.mass = 1 | units.MSun self.particles.radius = 3 | units.RSun - self.particles.position = [[i,2*i,3*i] for i in range(6)] | units.AU - self.particles.velocity = [[i,i**2,i**3] for i in range(6)] | units.km / units.s - + self.particles.position = [[i, 2*i, 3*i] for i in range(6)] | units.AU + self.particles.velocity = [[i, i**2, i**3] for i in range(6)] | units.km / units.s + class StellarEvolutionCodeForTesting(object): - + def __init__(self, particles=Particles(6)): particles.mass = 1 | units.MSun particles.radius = range(1, len(particles)+1) | units.RSun self.particles = particles - + class StellarEvolutionCodeWithInternalStructureForTesting(object): - + def __init__(self, particles=Particles(6)): particles.mass = 1 | units.MSun particles.radius = range(1, len(particles)+1) | units.RSun - particles.type = "native star" + particles.type = "native star" self.particles = particles - + def new_particle_from_model(self, internal_structure, current_age, key=None): tmp_star = Particle(key=key) tmp_star.mass = internal_structure["mass"] tmp_star.radius = internal_structure["radius"] - tmp_star.type = "new particle from model" + tmp_star.type = "new particle from model" return self.particles.add_particle(tmp_star) - class TestCollisionHandler(TestCase): - + def test1(self): print("Test CollisionHandler with collision code class (creates new instance for each collision)") colliders = Particles(2) handler = CollisionHandler(CollisionCodeForTesting) - + result = handler.handle_collision(colliders[0], colliders[1]) self.assertTrue(isinstance(result, Particles)) self.assertEqual(result.mass, 1 | units.kg) - + result = handler.handle_collision(colliders[0], colliders[1]) self.assertEqual(result.mass, 1 | units.kg) - + def test2(self): print("Test CollisionHandler with collision code instance (same instance for each collision)") colliders = Particles(2) handler = CollisionHandler(CollisionCodeForTesting()) - + result = handler.handle_collision(colliders[0], colliders[1]) self.assertTrue(isinstance(result, Particles)) self.assertEqual(result.mass, 1 | units.kg) - + result = handler.handle_collision(colliders[0], colliders[1]) self.assertEqual(result.mass, 2 | units.kg) - + def test3(self): print("Test CollisionHandler with collision code class, arguments and parameters") colliders = Particles(2) handler = CollisionHandler( - CollisionCodeForTesting, - collision_code_arguments=dict(next_mass=5|units.kg), + CollisionCodeForTesting, + collision_code_arguments=dict(next_mass=5 | units.kg), collision_code_parameters=dict(mass_unit=units.g) ) - + result = handler.handle_collision(colliders[0], colliders[1]) self.assertTrue(isinstance(result, Particles)) self.assertEqual(result.mass, 5 | units.kg) self.assertTrue(result.mass.unit is units.g) - + result = handler.handle_collision(colliders[0], colliders[1]) self.assertEqual(result.mass, 5 | units.kg) self.assertTrue(result.mass.unit is units.g) - - handler.collision_code_arguments = dict(next_mass=42|units.kg) + + handler.collision_code_arguments = dict(next_mass=42 | units.kg) handler.collision_code_parameters = dict(mass_unit=units.MSun) result = handler.handle_collision(colliders[0], colliders[1]) self.assertEqual(result.mass, 42 | units.kg) self.assertTrue(result.mass.unit is units.MSun) - + def test4(self): print("Test handle_collisions") colliders = Particles(8) handler = CollisionHandler(CollisionCodeForTesting) - + result = handler.handle_collisions(colliders[:4], colliders[4:]) self.assertTrue(isinstance(result, Particles)) self.assertEqual(len(result), 4) self.assertEqual(result.mass, [1, 1, 1, 1] | units.kg) - + def test5(self): print("Test CollisionHandler with gravity code") gravity = GravityCodeForTesting() self.assertEqual(len(gravity.particles), 6) - + handler = CollisionHandler(CollisionCodeForTesting, gravity_code=gravity) merged = handler.handle_collisions(gravity.particles[::2], gravity.particles[1::2]) self.assertTrue(isinstance(merged, Particles)) self.assertEqual(len(merged), 3) self.assertEqual(merged.mass, [1, 1, 1] | units.kg) - + self.assertEqual(len(gravity.particles), 3) self.assertEqual(gravity.particles.mass, [1, 1, 1] | units.kg) self.assertEqual(gravity.particles.radius, [3, 3, 3] | units.RSun) - self.assertAlmostEqual(gravity.particles.position, + self.assertAlmostEqual(gravity.particles.position, [[0.5, 1.0, 1.5], [2.5, 5.0, 7.5], [4.5, 9.0, 13.5]] | units.AU) - self.assertAlmostEqual(gravity.particles.velocity, + self.assertAlmostEqual(gravity.particles.velocity, [[0.5, 0.5, 0.5], [2.5, 6.5, 17.5], [4.5, 20.5, 94.5]] | units.km / units.s) - + def test6(self): print("Test CollisionHandler with stellar evolution code, type I") stellar_evolution = StellarEvolutionCodeForTesting() self.assertEqual(len(stellar_evolution.particles), 6) - + collision_code = CollisionCodeForTesting() collision_code.stellar_evolution_code_required = True - - self.assertRaises(AmuseException, CollisionHandler, collision_code, expected_message= - "CollisionCodeForTesting requires a stellar evolution code: " + + self.assertRaises(AmuseException, CollisionHandler, collision_code, expected_message="CollisionCodeForTesting requires a stellar evolution code: " "CollisionHandler(..., stellar_evolution_code=x)") - + handler = CollisionHandler(collision_code, stellar_evolution_code=stellar_evolution) merged = handler.handle_collisions(stellar_evolution.particles[::2], stellar_evolution.particles[1::2]) self.assertTrue(isinstance(merged, Particles)) self.assertEqual(len(merged), 3) self.assertEqual(merged.mass, [1, 2, 3] | units.kg) - + self.assertEqual(len(stellar_evolution.particles), 3) self.assertEqual(stellar_evolution.particles.mass, [1, 2, 3] | units.kg) self.assertEqual(stellar_evolution.particles.radius, [3, 7, 11] | units.RSun) - + def test7(self): print("Test CollisionHandler with stellar evolution code, type II") stellar_evolution = StellarEvolutionCodeWithInternalStructureForTesting() self.assertEqual(len(stellar_evolution.particles), 6) - self.assertEqual(stellar_evolution.particles.type, ["native star"]*6 ) - + self.assertEqual(stellar_evolution.particles.type, ["native star"]*6) + collision_code = CollisionCodeForTesting() collision_code.stellar_evolution_code_required = True - - self.assertRaises(AmuseException, CollisionHandler, collision_code, expected_message= - "CollisionCodeForTesting requires a stellar evolution code: " + + self.assertRaises(AmuseException, CollisionHandler, collision_code, expected_message="CollisionCodeForTesting requires a stellar evolution code: " "CollisionHandler(..., stellar_evolution_code=x)") - + handler = CollisionHandler(collision_code, stellar_evolution_code=stellar_evolution) merged = handler.handle_collisions(stellar_evolution.particles[::2], stellar_evolution.particles[1::2]) self.assertTrue(isinstance(merged, Particles)) self.assertEqual(len(merged), 3) self.assertEqual(merged.mass, [1, 2, 3] | units.kg) - + self.assertEqual(len(stellar_evolution.particles), 3) self.assertEqual(stellar_evolution.particles.mass, [1, 2, 3] | units.kg) self.assertEqual(stellar_evolution.particles.radius, [3, 7, 11] | units.RSun) - self.assertEqual(stellar_evolution.particles.type, ["new particle from model"]*3 ) - + self.assertEqual(stellar_evolution.particles.type, ["new particle from model"]*3) + def test8(self): print("Test CollisionHandler with stellar evolution and gravity code") gravity = GravityCodeForTesting() self.assertEqual(len(gravity.particles), 6) - + stellar_evolution = StellarEvolutionCodeForTesting(particles=gravity.particles.copy()) self.assertEqual(len(stellar_evolution.particles), 6) - + collision_code = CollisionCodeForTesting() collision_code.stellar_evolution_code_required = True - - self.assertRaises(AmuseException, CollisionHandler, collision_code, expected_message= - "CollisionCodeForTesting requires a stellar evolution code: " + + self.assertRaises(AmuseException, CollisionHandler, collision_code, expected_message="CollisionCodeForTesting requires a stellar evolution code: " "CollisionHandler(..., stellar_evolution_code=x)") - + handler = CollisionHandler( - collision_code, - stellar_evolution_code=stellar_evolution, + collision_code, + stellar_evolution_code=stellar_evolution, gravity_code=gravity ) merged = handler.handle_collisions(stellar_evolution.particles[::2], stellar_evolution.particles[1::2]) self.assertTrue(isinstance(merged, Particles)) self.assertEqual(len(merged), 3) self.assertEqual(merged.mass, [1, 2, 3] | units.kg) - + self.assertEqual(len(stellar_evolution.particles), 3) self.assertEqual(stellar_evolution.particles.mass, [1, 2, 3] | units.kg) self.assertEqual(stellar_evolution.particles.radius, [3, 7, 11] | units.RSun) - + self.assertEqual(len(gravity.particles), 3) self.assertEqual(gravity.particles.mass, [1, 2, 3] | units.kg) self.assertEqual(gravity.particles.radius, [3, 7, 11] | units.RSun) - self.assertAlmostEqual(gravity.particles.position, + self.assertAlmostEqual(gravity.particles.position, [[0.5, 1.0, 1.5], [2.5, 5.0, 7.5], [4.5, 9.0, 13.5]] | units.AU) - self.assertAlmostEqual(gravity.particles.velocity, + self.assertAlmostEqual(gravity.particles.velocity, [[0.5, 0.5, 0.5], [2.5, 6.5, 17.5], [4.5, 20.5, 94.5]] | units.km / units.s) - + def test9(self): print("Test CollisionHandler with gravity code and StickySpheres collision code") gravity = GravityCodeForTesting() self.assertEqual(len(gravity.particles), 6) gravity.particles.mass = [1, 1, 2, 2, 3, 3,] | units.MSun gravity.particles.radius = range(101, 107) | units.RSun - + collision_code = StickySpheres(mass_loss=0.1) - + handler = CollisionHandler( - collision_code, + collision_code, gravity_code=gravity ) merged = handler.handle_collisions(gravity.particles[::2], gravity.particles[1::2]) self.assertTrue(isinstance(merged, Particles)) self.assertEqual(len(merged), 3) self.assertEqual(merged.mass, 0.9 * ([2, 4, 6] | units.MSun)) - + self.assertEqual(len(gravity.particles), 3) self.assertEqual(gravity.particles.mass, 0.9 * ([2, 4, 6] | units.MSun)) self.assertEqual(gravity.particles.radius, [102, 104, 106] | units.RSun) - self.assertAlmostEqual(gravity.particles.position, + self.assertAlmostEqual(gravity.particles.position, [[0.5, 1.0, 1.5], [2.5, 5.0, 7.5], [4.5, 9.0, 13.5]] | units.AU) - self.assertAlmostEqual(gravity.particles.velocity, + self.assertAlmostEqual(gravity.particles.velocity, [[0.5, 0.5, 0.5], [2.5, 6.5, 17.5], [4.5, 20.5, 94.5]] | units.km / units.s) - diff --git a/src/amuse/test/suite/ext_tests/test_composition_methods.py b/src/amuse/test/suite/ext_tests/test_composition_methods.py index 7b6e80d76d..d433ac3fc1 100644 --- a/src/amuse/test/suite/ext_tests/test_composition_methods.py +++ b/src/amuse/test/suite/ext_tests/test_composition_methods.py @@ -3,118 +3,130 @@ class harmonic_oscillator(object): - def __init__(self,x,v,method=None): - self.x=x - self.v=v - self.model_time=0 - self.method=method - def kick(self,dt): - self.v+=-self.x*dt - def drift(self,dt): - self.x+=self.v*dt - def total_energy(self): - return (self.v**2+self.x**2)/2 - def evolve_step(self,dt): - self.method(self.kick,self.drift,dt) - self.model_time+=dt - -def run_harmonic_oscillator(dt,method): - h=harmonic_oscillator(0.,1.,method=method) - tend=100*2*numpy.pi - - data=dict() - data['x']=[] - data['time']=[] - data['de']=[] - E0=h.total_energy() - - while h.model_time0)) - - filenames=decode_and_load(filenames_in) - if reference_in!=0: - raise Exception("reference_in hould be zero here!") - real_particles, local_offset, local_size, global_size = self.references_to_particles[reference_in] - start=self.rank*ceil(len(filenames),self.number_of_processes) - end=(self.rank+1)*ceil(len(filenames),self.number_of_processes) - for i in range(start,end): - if i< len(filenames): - p=read_set_from_file(filenames[i],fileformat) - real_particles.add_particles(p) + ceil = lambda x, y: (x//y+(x % y > 0)) + + filenames = decode_and_load(filenames_in) + if reference_in != 0: + raise Exception("reference_in hould be zero here!") + real_particles, local_offset, local_size, global_size = self.references_to_particles[reference_in] + start = self.rank*ceil(len(filenames), self.number_of_processes) + end = (self.rank+1)*ceil(len(filenames), self.number_of_processes) + for i in range(start, end): + if i < len(filenames): + p = read_set_from_file(filenames[i], fileformat) + real_particles.add_particles(p) input = numpy.zeros(1, dtype='int64') output = numpy.zeros(self.number_of_processes, dtype='int64') - + input[0] = len(real_particles) self.mpi_comm.Allgather( - [input, MPI.INTEGER], + [input, MPI.INTEGER], [output, MPI.INTEGER] ) total_size = 0 local_offset = 0 - for i,current_size in enumerate(output): + for i, current_size in enumerate(output): if i < self.rank: local_offset += current_size total_size += current_size @@ -479,354 +487,353 @@ def read_set_from_file(self, reference_in, filenames_in, fileformat): self.references_to_particles[reference_in] = referenced_particles return 0 -def generate_set_example_function(start,end,*args,**kwargs): + +def generate_set_example_function(start, end, *args, **kwargs): from amuse.datamodel import Particles - p=Particles(end-start) - p.index=range(start,end) + p = Particles(end-start) + p.index = range(start, end) return p -def distributed_king_generator(start,end,*args,**kwargs): + +def distributed_king_generator(start, end, *args, **kwargs): from amuse.ic.kingmodel import MakeKingModel import numpy numpy.random.seed(1234567) numpy.random.uniform(size=start*6) - total_number_of_particles=args[0] + total_number_of_particles = args[0] + class PartialKingModel(MakeKingModel): def makeking(self): - m,p,v=MakeKingModel.makeking(self) - m=0.*m+(1.0 / total_number_of_particles) - return m,p,v - kwargs['center_model']=False - kwargs['do_scale']=False - args=(end-start,)+args[1:] - return PartialKingModel(*args,**kwargs).result + m, p, v = MakeKingModel.makeking(self) + m = 0.*m+(1.0 / total_number_of_particles) + return m, p, v + kwargs['center_model'] = False + kwargs['do_scale'] = False + args = (end-start,)+args[1:] + return PartialKingModel(*args, **kwargs).result + def select_example_function(x): return x > 5 - + + class TestDistributedParticles(TestWithMPI): def setUp(self): if MPI is None or CodeInterface(must_start_worker=False).channel_type != 'mpi': self.skip("test needs mpi") - + def test1(self): x = DistributedParticles( - size = 3, - number_of_workers = 1 + size=3, + number_of_workers=1 ) - self.assertEqual(len(x) , 3) + self.assertEqual(len(x), 3) x.mass = 10 | units.MSun - self.assertEqual(x.mass, [10, 10, 10]| units.MSun) - + self.assertEqual(x.mass, [10, 10, 10] | units.MSun) def test2(self): x = DistributedParticles( - size = 3, - number_of_workers = 1 + size=3, + number_of_workers=1 ) - self.assertEqual(len(x) , 3) + self.assertEqual(len(x), 3) x.mass = 10 | units.MSun y = x[0:2] - self.assertEqual(len(y) , 2) - self.assertEqual(y.mass, [10, 10]| units.MSun) - + self.assertEqual(len(y), 2) + self.assertEqual(y.mass, [10, 10] | units.MSun) def test3(self): x = DistributedParticles( - size = 3, - number_of_workers = 1 + size=3, + number_of_workers=1 ) - self.assertEqual(len(x) , 3) - x.mass = [1,2,3]| units.MSun + self.assertEqual(len(x), 3) + x.mass = [1, 2, 3] | units.MSun y = x[0:2] z = x[1:] - self.assertEqual(len(y) , 2) - self.assertEqual(y.mass, [1,2]| units.MSun) - self.assertEqual(len(z) , 2) - self.assertEqual(z.mass, [2,3]| units.MSun) - z.mass = [4,5] | units.MSun - self.assertEqual(y.mass, [1,4]| units.MSun) - self.assertEqual(z.mass, [4,5]| units.MSun) - self.assertEqual(x.mass, [1,4,5]| units.MSun) - - + self.assertEqual(len(y), 2) + self.assertEqual(y.mass, [1, 2] | units.MSun) + self.assertEqual(len(z), 2) + self.assertEqual(z.mass, [2, 3] | units.MSun) + z.mass = [4, 5] | units.MSun + self.assertEqual(y.mass, [1, 4] | units.MSun) + self.assertEqual(z.mass, [4, 5] | units.MSun) + self.assertEqual(x.mass, [1, 4, 5] | units.MSun) + def test4(self): x = DistributedParticles( - size = 3, - number_of_workers = 1 + size=3, + number_of_workers=1 ) - x.mass = [1,2,3]| units.MSun + x.mass = [1, 2, 3] | units.MSun y = x[1] self.assertEqual(y.mass, 2 | units.MSun) y.mass = 10 | units.MSun self.assertEqual(y.mass, 10 | units.MSun) - self.assertEqual(x.mass, [1,10,3]| units.MSun) + self.assertEqual(x.mass, [1, 10, 3] | units.MSun) - def test5(self): x = DistributedParticles( - size = 8, - number_of_workers = 2 + size=8, + number_of_workers=2 ) - self.assertEqual(len(x) , 8) - x.mass = [1,2,3,4,5,6,7,8] | units.MSun + self.assertEqual(len(x), 8) + x.mass = [1, 2, 3, 4, 5, 6, 7, 8] | units.MSun for index in range(len(x)): - self.assertEqual(x[index].mass, (index+1)| units.MSun) - - + self.assertEqual(x[index].mass, (index+1) | units.MSun) + def test6(self): x = DistributedParticles( - size = 9, - number_of_workers = 2 + size=9, + number_of_workers=2 ) - self.assertEqual(len(x) , 9) - x.mass = [1,2,3,4,5,6,7,8,9] | units.MSun + self.assertEqual(len(x), 9) + x.mass = [1, 2, 3, 4, 5, 6, 7, 8, 9] | units.MSun for index in range(len(x)): - self.assertEqual(x[index].mass, (index+1)| units.MSun) - + self.assertEqual(x[index].mass, (index+1) | units.MSun) + def test7(self): x = DistributedParticles( - size = 8, - number_of_workers = 2 + size=8, + number_of_workers=2 ) - self.assertEqual(len(x) , 8) - x.mass = [1,2,3,4,5,6,7,8] | units.MSun + self.assertEqual(len(x), 8) + x.mass = [1, 2, 3, 4, 5, 6, 7, 8] | units.MSun self.assertEqual(len(x[3:7]), 4) - x[3:7].mass = [10,11,12,13] | units.MSun - expected = [1,2,3,10,11,12,13,8]| units.MSun + x[3:7].mass = [10, 11, 12, 13] | units.MSun + expected = [1, 2, 3, 10, 11, 12, 13, 8] | units.MSun for index in range(len(x)): - self.assertEqual(x[index].mass, expected[index] ) - + self.assertEqual(x[index].mass, expected[index]) + def test8(self): x = DistributedParticles( - size = 8, - number_of_workers = 2 + size=8, + number_of_workers=2 ) - self.assertEqual(len(x) , 8) - x.mass = [1,2,3,4,5,6,7,8] | units.MSun + self.assertEqual(len(x), 8) + x.mass = [1, 2, 3, 4, 5, 6, 7, 8] | units.MSun self.assertEqual(len(x[3:7]), 4) - x[3:7].mass = [10,11,12,13] | units.MSun - - self.assertEqual(x[2:6].mass, [3,10,11,12]| units.MSun) - + x[3:7].mass = [10, 11, 12, 13] | units.MSun + + self.assertEqual(x[2:6].mass, [3, 10, 11, 12] | units.MSun) + def test9(self): x = DistributedParticles( - size = 8, - number_of_workers = 2 + size=8, + number_of_workers=2 ) - self.assertEqual(len(x) , 8) - x.mass = [1,2,3,4,5,6,7,8] + self.assertEqual(len(x), 8) + x.mass = [1, 2, 3, 4, 5, 6, 7, 8] self.assertEqual(len(x[3:7]), 4) - x[3:7].mass = [10,11,12,13] - - self.assertEqual(x[2:6].mass, [3,10,11,12]) - + x[3:7].mass = [10, 11, 12, 13] + + self.assertEqual(x[2:6].mass, [3, 10, 11, 12]) + def test10(self): x = DistributedParticles( - size = 40, - number_of_workers = 4 + size=40, + number_of_workers=4 ) - self.assertEqual(len(x) , 40) - x.mass = range(40) + self.assertEqual(len(x), 40) + x.mass = range(40) self.assertEqual(len(x[15:25]), 10) - self.assertEqual(x[15:25].mass, list(range(15,25))) + self.assertEqual(x[15:25].mass, list(range(15, 25))) x[15:25].mass = range(10) self.assertEqual(x[15:25].mass, list(range(10))) - + def test11(self): from .test_distributed_particles import generate_set_example_function - y=generate_set_example_function(0,10) - + y = generate_set_example_function(0, 10) + x = DistributedParticles( - size = 10, - number_of_workers = 2 + size=10, + number_of_workers=2 ) x.set_from_generator(generate_set_example_function) - self.assertEqual(y.index,x.index) + self.assertEqual(y.index, x.index) def test12(self): from .test_distributed_particles import generate_set_example_function from .test_distributed_particles import select_example_function - y=generate_set_example_function(0,10) - + y = generate_set_example_function(0, 10) + x = DistributedParticles( - size = 10, - number_of_workers = 2 + size=10, + number_of_workers=2 ) x.set_from_generator(generate_set_example_function) - self.assertEqual(y.index,x.index) + self.assertEqual(y.index, x.index) + + highy = y.select_array(select_example_function, ("index",)) + highx = x.select_array(select_example_function, ("index",)) + self.assertEqual(highy.index, highx.index) - highy=y.select_array( select_example_function, ("index",)) - highx=x.select_array( select_example_function, ("index",)) - self.assertEqual(highy.index,highx.index) - def test13(self): x = DistributedParticles( - size = 8, - number_of_workers = 2 + size=8, + number_of_workers=2 ) - x.index= [0,10,10,10,0,0,10,0] - x.mass = [1, 2, 3, 4,5,6, 7,8] | units.MSun - highx=x.select_array( select_example_function, ("index",)) - self.assertEqual(highx.mass, [2,3,4,7] | units.MSun) + x.index = [0, 10, 10, 10, 0, 0, 10, 0] + x.mass = [1, 2, 3, 4, 5, 6, 7, 8] | units.MSun + highx = x.select_array(select_example_function, ("index",)) + self.assertEqual(highx.mass, [2, 3, 4, 7] | units.MSun) def test14(self): test_results_path = self.get_path_to_results() - output_files=[] - filebase=os.path.join(test_results_path, "test_distributed_sets") - for i in [0,1]: - output_file = filebase+"_%6.6i"%i - output_files.append(output_file) - - if os.path.exists(output_file): - os.remove(output_file) + output_files = [] + filebase = os.path.join(test_results_path, "test_distributed_sets") + for i in [0, 1]: + output_file = filebase+"_%6.6i" % i + output_files.append(output_file) + + if os.path.exists(output_file): + os.remove(output_file) x = DistributedParticles( - size = 8, - number_of_workers = 2 - ) - x.index= [0,10,10,10,0,0,10,0] - x.mass = [1, 2, 3, 4,5,6, 7,8] | units.MSun - files=x.write_set_to_file(filebase,"amuse") - self.assertEqual(files,output_files) - for i,f in enumerate(files): - self.assertTrue( os.path.isfile(f) ) - p=read_set_from_file(f,"amuse") - self.assertEqual(len(p),4) - self.assertEqual(p.collection_attributes.global_size,8) - self.assertEqual(p.collection_attributes.local_size,4) + size=8, + number_of_workers=2 + ) + x.index = [0, 10, 10, 10, 0, 0, 10, 0] + x.mass = [1, 2, 3, 4, 5, 6, 7, 8] | units.MSun + files = x.write_set_to_file(filebase, "amuse") + self.assertEqual(files, output_files) + for i, f in enumerate(files): + self.assertTrue(os.path.isfile(f)) + p = read_set_from_file(f, "amuse") + self.assertEqual(len(p), 4) + self.assertEqual(p.collection_attributes.global_size, 8) + self.assertEqual(p.collection_attributes.local_size, 4) def test15(self): test_results_path = self.get_path_to_results() - output_files=[] - filebase=os.path.join(test_results_path, "test_distributed_sets") - for i in [0,1]: - output_file = filebase+"_%6.6i"%i - output_files.append(output_file) - - if os.path.exists(output_file): - os.remove(output_file) + output_files = [] + filebase = os.path.join(test_results_path, "test_distributed_sets") + for i in [0, 1]: + output_file = filebase+"_%6.6i" % i + output_files.append(output_file) + + if os.path.exists(output_file): + os.remove(output_file) x = DistributedParticles( - size = 8, - number_of_workers = 2 - ) - x.index= [0,10,10,10,0,0,10,0] - x.mass = [1, 2, 3, 4,5,6, 7,8] | units.MSun - highx=x.select_array( select_example_function, ("index",)) - files=highx.write_set_to_file(filebase,"amuse") - self.assertEqual(files,output_files) - expected_local_sizes=[3,1] - for i,f in enumerate(files): - self.assertTrue( os.path.isfile(f) ) - p=read_set_from_file(f,"amuse") - self.assertEqual(len(p),expected_local_sizes[i]) - self.assertEqual(p.collection_attributes.global_size,4) - self.assertEqual(p.collection_attributes.local_size,expected_local_sizes[i]) + size=8, + number_of_workers=2 + ) + x.index = [0, 10, 10, 10, 0, 0, 10, 0] + x.mass = [1, 2, 3, 4, 5, 6, 7, 8] | units.MSun + highx = x.select_array(select_example_function, ("index",)) + files = highx.write_set_to_file(filebase, "amuse") + self.assertEqual(files, output_files) + expected_local_sizes = [3, 1] + for i, f in enumerate(files): + self.assertTrue(os.path.isfile(f)) + p = read_set_from_file(f, "amuse") + self.assertEqual(len(p), expected_local_sizes[i]) + self.assertEqual(p.collection_attributes.global_size, 4) + self.assertEqual(p.collection_attributes.local_size, expected_local_sizes[i]) def test16(self): test_results_path = self.get_path_to_results() - filebase=os.path.join(test_results_path, "test_distributed_sets") - for i in [0,1]: - output_file = filebase+"_%6.6i"%i - - if os.path.exists(output_file): - os.remove(output_file) + filebase = os.path.join(test_results_path, "test_distributed_sets") + for i in [0, 1]: + output_file = filebase+"_%6.6i" % i + + if os.path.exists(output_file): + os.remove(output_file) x = DistributedParticles( - size = 8, - number_of_workers = 2 + size=8, + number_of_workers=2 ) - x.index= [0,10,10,10,0,0,10,0] - x.mass = [1, 2, 3, 4,5,6, 7,8] | units.MSun - files=x.write_set_to_file(filebase,"amuse") + x.index = [0, 10, 10, 10, 0, 0, 10, 0] + x.mass = [1, 2, 3, 4, 5, 6, 7, 8] | units.MSun + files = x.write_set_to_file(filebase, "amuse") - y= DistributedParticles( - size = 0, - number_of_workers = 2 + y = DistributedParticles( + size=0, + number_of_workers=2 ) - y.read_set_from_file(files,"amuse") - self.assertEqual(len(y), len(x) ) - self.assertEqual(y.index, x.index ) - self.assertEqual(y.mass, x.mass ) - + y.read_set_from_file(files, "amuse") + self.assertEqual(len(y), len(x)) + self.assertEqual(y.index, x.index) + self.assertEqual(y.mass, x.mass) + def test17(self): test_results_path = self.get_path_to_results() - filebase=os.path.join(test_results_path, "test_distributed_sets") - for i in [0,1]: - output_file = filebase+"_%6.6i"%i - - if os.path.exists(output_file): - os.remove(output_file) + filebase = os.path.join(test_results_path, "test_distributed_sets") + for i in [0, 1]: + output_file = filebase+"_%6.6i" % i + + if os.path.exists(output_file): + os.remove(output_file) x = DistributedParticles( - size = 8, - number_of_workers = 4 + size=8, + number_of_workers=4 ) - x.index= [0,10,10,10,0,0,10,0] - x.mass = [1, 2, 3, 4,5,6, 7,8] | units.MSun - files=x.write_set_to_file(filebase,"amuse") + x.index = [0, 10, 10, 10, 0, 0, 10, 0] + x.mass = [1, 2, 3, 4, 5, 6, 7, 8] | units.MSun + files = x.write_set_to_file(filebase, "amuse") - y= DistributedParticles( - size = 0, - number_of_workers = 2 + y = DistributedParticles( + size=0, + number_of_workers=2 ) - y.read_set_from_file(files,"amuse") - self.assertEqual(len(y), len(x) ) - self.assertEqual(y.index, x.index ) - self.assertEqual(y.mass, x.mass ) + y.read_set_from_file(files, "amuse") + self.assertEqual(len(y), len(x)) + self.assertEqual(y.index, x.index) + self.assertEqual(y.mass, x.mass) # number of workers > number of files # still problematic, because of non-existing attributes if nothing read def test18(self): test_results_path = self.get_path_to_results() - filebase=os.path.join(test_results_path, "test_distributed_sets") - for i in [0,1]: - output_file = filebase+"_%6.6i"%i - - if os.path.exists(output_file): - os.remove(output_file) + filebase = os.path.join(test_results_path, "test_distributed_sets") + for i in [0, 1]: + output_file = filebase+"_%6.6i" % i + + if os.path.exists(output_file): + os.remove(output_file) x = DistributedParticles( - size = 8, - number_of_workers = 2 + size=8, + number_of_workers=2 ) - x.index= [0,10,10,10,0,0,10,0] - x.mass = [1, 2, 3, 4,5,6, 7,8] | units.MSun - files=x.write_set_to_file(filebase,"amuse") + x.index = [0, 10, 10, 10, 0, 0, 10, 0] + x.mass = [1, 2, 3, 4, 5, 6, 7, 8] | units.MSun + files = x.write_set_to_file(filebase, "amuse") - z= DistributedParticles( - size = 0, - number_of_workers = 4 + z = DistributedParticles( + size=0, + number_of_workers=4 ) - z.read_set_from_file(files,"amuse") - self.assertEqual(len(x), len(z) ) - self.assertEqual(x.index, z.index ) - self.assertEqual(x.mass, z.mass ) + z.read_set_from_file(files, "amuse") + self.assertEqual(len(x), len(z)) + self.assertEqual(x.index, z.index) + self.assertEqual(x.mass, z.mass) def test19(self): from .test_distributed_particles import distributed_king_generator from amuse.ic.kingmodel import MakeKingModel - - N=100 - W0=7. + + N = 100 + W0 = 7. numpy.random.seed(1234567) - y=MakeKingModel(N,W0,center_model=False).result - - x = DistributedParticles( - size = N, - number_of_workers = 4 - ) - x.set_from_generator(distributed_king_generator,args=(N,W0)) - self.assertEqual(y.mass,x.mass) - self.assertEqual(y.x,x.x) - self.assertEqual(y.y,x.y) - self.assertEqual(y.z,x.z) - self.assertEqual(y.vx,x.vx) - self.assertEqual(y.vy,x.vy) - self.assertEqual(y.vz,x.vz) + y = MakeKingModel(N, W0, center_model=False).result + x = DistributedParticles( + size=N, + number_of_workers=4 + ) + x.set_from_generator(distributed_king_generator, args=(N, W0)) + self.assertEqual(y.mass, x.mass) + self.assertEqual(y.x, x.x) + self.assertEqual(y.y, x.y) + self.assertEqual(y.z, x.z) + self.assertEqual(y.vx, x.vx) + self.assertEqual(y.vy, x.vy) + self.assertEqual(y.vz, x.vz) diff --git a/src/amuse/test/suite/ext_tests/test_evrardmodel.py b/src/amuse/test/suite/ext_tests/test_evrardmodel.py index 0c8c1685d1..e1f25e6812 100644 --- a/src/amuse/test/suite/ext_tests/test_evrardmodel.py +++ b/src/amuse/test/suite/ext_tests/test_evrardmodel.py @@ -5,13 +5,15 @@ from amuse.units import nbody_system as nbody from amuse.units import units + + class TestEvrardModel(amusetest.TestCase): def test1(self): print("First test: making an Evrard gas sphere model.") target_number_of_particles = 1000 gas_parts = new_evrard_gas_sphere(target_number_of_particles, seed=1234) self.assertEqual(len(gas_parts), 1000) - + def test2(self): print("Testing properties of an Evrard model.") target_number_of_particles = 1000 @@ -19,13 +21,12 @@ def test2(self): self.assertEqual(len(gas_parts), 1000) self.assertAlmostEqual(gas_parts.kinetic_energy(), 0.00 | nbody.energy) self.assertAlmostEqual(gas_parts.potential_energy(G=nbody.G), -0.50 | nbody.energy) - self.assertAlmostEqual(gas_parts.center_of_mass(), [0,0,0] | nbody.length) - self.assertAlmostEqual(gas_parts.center_of_mass_velocity(), [0,0,0] | nbody.speed) + self.assertAlmostEqual(gas_parts.center_of_mass(), [0, 0, 0] | nbody.length) + self.assertAlmostEqual(gas_parts.center_of_mass_velocity(), [0, 0, 0] | nbody.speed) self.assertAlmostEqual(gas_parts.mass.sum(), 1.00 | nbody.mass) - + def test3(self): print("Testing virial radius of an Evrard model.") target_number_of_particles = 100 gas_parts = new_evrard_gas_sphere(target_number_of_particles, do_scale=True, seed=1234) self.assertAlmostEqual(gas_parts.virial_radius(), 1.00 | nbody.length) - diff --git a/src/amuse/test/suite/ext_tests/test_fallback_stellar_evolution.py b/src/amuse/test/suite/ext_tests/test_fallback_stellar_evolution.py index 2b7dbfb022..dcdb07ea69 100644 --- a/src/amuse/test/suite/ext_tests/test_fallback_stellar_evolution.py +++ b/src/amuse/test/suite/ext_tests/test_fallback_stellar_evolution.py @@ -3,7 +3,7 @@ import numpy from amuse.units import units -from amuse.datamodel import Particles,Particle +from amuse.datamodel import Particles, Particle from amuse.support.exceptions import AmuseException from amuse.test.amusetest import TestCase, get_path_to_results @@ -13,6 +13,7 @@ from amuse.couple.fallback_stellar_evolution import FallbackStellarEvolution + class TestFallbackStellarEvolution(TestCase): def test1(self): @@ -26,8 +27,8 @@ def xtest2(self): # results of original code (not really check the numbers, tests have been relaxed because # different timestepping of evolve_model and evolve_one_step) - results=dict() - results["10.0 MSun"]=dict(sse_age=3644655.52487 | units.yr, + results = dict() + results["10.0 MSun"] = dict(sse_age=3644655.52487 | units.yr, sse_mass=9.99289747724 | units.MSun, sse_rad=4.24764389443 | units.RSun, sse_L=5993.72678228 | units.LSun, @@ -35,56 +36,54 @@ def xtest2(self): evtwin_mass=9.99832250931 | units.MSun, evtwin_rad=4.1727904434 | units.RSun, evtwin_L=6175.5214329 | units.LSun) - results["20.0 MSun"]=dict(sse_age= 2609167.84395| units.yr, - sse_mass= 19.8895071502| units.MSun, - sse_rad=7.07713598137| units.RSun, - sse_L=51232.436257| units.LSun, - evtwin_age= 2999999.99792| units.yr, - evtwin_mass=19.877338008| units.MSun, - evtwin_rad=6.77369109826| units.RSun, - evtwin_L= 54123.7589452| units.LSun) - results["40.0 MSun"]=dict(sse_age= 2627093.59096| units.yr, - sse_mass=38.3702723816| units.MSun, + results["20.0 MSun"] = dict(sse_age=2609167.84395 | units.yr, + sse_mass=19.8895071502 | units.MSun, + sse_rad=7.07713598137 | units.RSun, + sse_L=51232.436257 | units.LSun, + evtwin_age=2999999.99792 | units.yr, + evtwin_mass=19.877338008 | units.MSun, + evtwin_rad=6.77369109826 | units.RSun, + evtwin_L=54123.7589452 | units.LSun) + results["40.0 MSun"] = dict(sse_age=2627093.59096 | units.yr, + sse_mass=38.3702723816 | units.MSun, sse_rad=13.6137662257 | units.RSun, sse_L=303498.877464 | units.LSun, - evtwin_age= 2999999.99923| units.yr, + evtwin_age=2999999.99923 | units.yr, evtwin_mass=37.0862227121 | units.MSun, - evtwin_rad= 13.5982316053| units.RSun, - evtwin_L=320099.608846| units.LSun) - + evtwin_rad=13.5982316053 | units.RSun, + evtwin_L=320099.608846 | units.LSun) - for m in [40.]| units.MSun:#,20.,10.] | units.MSun: - instance = FallbackStellarEvolution() - instance._main_se.parameters.max_age_stop_condition=3.| units.Myr + for m in [40.] | units.MSun: # ,20.,10.] | units.MSun: + instance = FallbackStellarEvolution() + instance._main_se.parameters.max_age_stop_condition = 3. | units.Myr - star = Particle(1) - star.mass = m - star = instance.particles.add_particle(star) - instance.commit_particles() + star = Particle(1) + star.mass = m + star = instance.particles.add_particle(star) + instance.commit_particles() - while instance.ActiveModel[star].__class__.__name__=="EVtwin": - instance.evolve_model() + while instance.ActiveModel[star].__class__.__name__ == "EVtwin": + instance.evolve_model() - print("%s\t%s\t%s\t%s\t%s\t%s" % (star.age, star.mass, star.radius, - star.luminosity, star.stellar_type, instance.ActiveModel[star].__class__.__name__)) + print("%s\t%s\t%s\t%s\t%s\t%s" % (star.age, star.mass, star.radius, + star.luminosity, star.stellar_type, instance.ActiveModel[star].__class__.__name__)) - self.assertAlmostRelativeEqual(results[str(m)]["sse_age"],instance._FBTimeseries[star].particles[0].SSEAgeAtSwitch,7) - self.assertAlmostRelativeEqual(results[str(m)]["sse_mass"],star.mass,7) - self.assertAlmostRelativeEqual(results[str(m)]["sse_rad"],star.radius,7) - self.assertAlmostRelativeEqual(results[str(m)]["sse_L"],star.luminosity,7) + self.assertAlmostRelativeEqual(results[str(m)]["sse_age"], instance._FBTimeseries[star].particles[0].SSEAgeAtSwitch, 7) + self.assertAlmostRelativeEqual(results[str(m)]["sse_mass"], star.mass, 7) + self.assertAlmostRelativeEqual(results[str(m)]["sse_rad"], star.radius, 7) + self.assertAlmostRelativeEqual(results[str(m)]["sse_L"], star.luminosity, 7) + star = instance._main_se.particles[0] - star=instance._main_se.particles[0] + self.assertAlmostRelativeEqual(results[str(m)]["evtwin_age"], star.age, 7) + self.assertAlmostRelativeEqual(results[str(m)]["evtwin_mass"], star.mass, 2) + self.assertAlmostRelativeEqual(results[str(m)]["evtwin_rad"], star.radius, 2) + self.assertAlmostRelativeEqual(results[str(m)]["evtwin_L"], star.luminosity, 2) - self.assertAlmostRelativeEqual(results[str(m)]["evtwin_age"],star.age,7) - self.assertAlmostRelativeEqual(results[str(m)]["evtwin_mass"],star.mass,2) - self.assertAlmostRelativeEqual(results[str(m)]["evtwin_rad"],star.radius,2) - self.assertAlmostRelativeEqual(results[str(m)]["evtwin_L"],star.luminosity,2) + print("%s\t%s\t%s\t%s\t%s" % (star.age, star.mass, star.radius, + star.luminosity, star.stellar_type)) - print("%s\t%s\t%s\t%s\t%s" % (star.age, star.mass, star.radius, - star.luminosity, star.stellar_type)) - - instance.stop() + instance.stop() def slowtest3(self): print("Testing FallbackStellarEvolution: evolve 3 stars at the same time") @@ -92,64 +91,62 @@ def slowtest3(self): # results of original code (not really check the numbers, tests have been relaxed because # different timestepping of evolve_model and evolve_one_step) - results=dict() - results["10.0 MSun"]=dict(sse_age=3644655.52487 | units.yr, + results = dict() + results["10.0 MSun"] = dict(sse_age=3644655.52487 | units.yr, sse_mass=9.99289747724 | units.MSun, sse_rad=4.35949272485 | units.RSun, - sse_L=6180.22077675| units.LSun, + sse_L=6180.22077675 | units.LSun, evtwin_age=2999999.99732 | units.yr, evtwin_mass=9.99832250931 | units.MSun, evtwin_rad=4.1727904434 | units.RSun, evtwin_L=6175.5214329 | units.LSun) - results["20.0 MSun"]=dict(sse_age= 2609167.84395| units.yr, - sse_mass= 19.8895071502| units.MSun, - sse_rad=7.30432858615| units.RSun, - sse_L=51232.436257| units.LSun, - evtwin_age= 2999999.99792| units.yr, - evtwin_mass=19.877338008| units.MSun, - evtwin_rad=6.77369109826| units.RSun, - evtwin_L= 54123.7589452| units.LSun) - results["40.0 MSun"]=dict(sse_age= 2869735.64001| units.yr, # for some reason this is not 2617093.59096 - sse_mass=37.9172423183| units.MSun, - sse_rad=15.1388511451| units.RSun, - sse_L=322674.980598| units.LSun, - evtwin_age= 2999999.99923| units.yr, + results["20.0 MSun"] = dict(sse_age=2609167.84395 | units.yr, + sse_mass=19.8895071502 | units.MSun, + sse_rad=7.30432858615 | units.RSun, + sse_L=51232.436257 | units.LSun, + evtwin_age=2999999.99792 | units.yr, + evtwin_mass=19.877338008 | units.MSun, + evtwin_rad=6.77369109826 | units.RSun, + evtwin_L=54123.7589452 | units.LSun) + results["40.0 MSun"] = dict(sse_age=2869735.64001 | units.yr, # for some reason this is not 2617093.59096 + sse_mass=37.9172423183 | units.MSun, + sse_rad=15.1388511451 | units.RSun, + sse_L=322674.980598 | units.LSun, + evtwin_age=2999999.99923 | units.yr, evtwin_mass=37.0862227121 | units.MSun, - evtwin_rad= 13.5982316053| units.RSun, - evtwin_L=320099.608846| units.LSun) - + evtwin_rad=13.5982316053 | units.RSun, + evtwin_L=320099.608846 | units.LSun) instance = FallbackStellarEvolution() - instance._main_se.parameters.max_age_stop_condition=3.| units.Myr + instance._main_se.parameters.max_age_stop_condition = 3. | units.Myr - stars = Particles(3,mass=[10.,20.,40.] | units.MSun) + stars = Particles(3, mass=[10., 20., 40.] | units.MSun) stars = instance.particles.add_particles(stars) - stars.initial_mass=stars.mass + stars.initial_mass = stars.mass instance.commit_particles() - while instance.model_time<.05| units.Myr: - instance.evolve_model() + while instance.model_time < .05 | units.Myr: + instance.evolve_model() for star in stars: - self.assertEqual(instance.ActiveModel[star].__class__.__name__,"EVtwin") + self.assertEqual(instance.ActiveModel[star].__class__.__name__, "EVtwin") - while instance.model_time<=3.| units.Myr: - instance.evolve_model() + while instance.model_time <= 3. | units.Myr: + instance.evolve_model() for star in stars: - self.assertEqual(instance.ActiveModel[star].__class__.__name__,"SSE") + self.assertEqual(instance.ActiveModel[star].__class__.__name__, "SSE") for star in stars: - m=star.initial_mass - self.assertAlmostRelativeEqual(results[str(m)]["sse_age"],instance._FBTimeseries[star].particles[0].SSEAgeAtSwitch,3) + m = star.initial_mass + self.assertAlmostRelativeEqual(results[str(m)]["sse_age"], instance._FBTimeseries[star].particles[0].SSEAgeAtSwitch, 3) - evstar=star.as_particle_in_set(instance._main_se.particles) - - self.assertAlmostRelativeEqual(results[str(m)]["evtwin_age"],evstar.age,7) - self.assertAlmostRelativeEqual(results[str(m)]["evtwin_mass"],evstar.mass,2) - self.assertAlmostRelativeEqual(results[str(m)]["evtwin_rad"],evstar.radius,2) - self.assertAlmostRelativeEqual(results[str(m)]["evtwin_L"],evstar.luminosity,2) + evstar = star.as_particle_in_set(instance._main_se.particles) + self.assertAlmostRelativeEqual(results[str(m)]["evtwin_age"], evstar.age, 7) + self.assertAlmostRelativeEqual(results[str(m)]["evtwin_mass"], evstar.mass, 2) + self.assertAlmostRelativeEqual(results[str(m)]["evtwin_rad"], evstar.radius, 2) + self.assertAlmostRelativeEqual(results[str(m)]["evtwin_L"], evstar.luminosity, 2) instance.stop() @@ -157,24 +154,24 @@ def slowtest4(self): print("Testing FallbackStellarEvolution: evolve same 3 stars at the same time") instance = FallbackStellarEvolution() - instance._main_se.parameters.max_age_stop_condition=3.| units.Myr + instance._main_se.parameters.max_age_stop_condition = 3. | units.Myr - stars = Particles(3,mass=[40.,40.,40.] | units.MSun) + stars = Particles(3, mass=[40., 40., 40.] | units.MSun) stars = instance.particles.add_particles(stars) instance.commit_particles() - while instance.model_time<=3.| units.Myr: - instance.evolve_model() + while instance.model_time <= 3. | units.Myr: + instance.evolve_model() for star in stars: - self.assertEqual(instance.ActiveModel[star].__class__.__name__,"SSE") + self.assertEqual(instance.ActiveModel[star].__class__.__name__, "SSE") - age1=instance._FBTimeseries[stars[0]].particles[0].SSEAgeAtSwitch - age2=instance._FBTimeseries[stars[1]].particles[0].SSEAgeAtSwitch - age3=instance._FBTimeseries[stars[2]].particles[0].SSEAgeAtSwitch + age1 = instance._FBTimeseries[stars[0]].particles[0].SSEAgeAtSwitch + age2 = instance._FBTimeseries[stars[1]].particles[0].SSEAgeAtSwitch + age3 = instance._FBTimeseries[stars[2]].particles[0].SSEAgeAtSwitch - self.assertEqual(age1,age2) - self.assertEqual(age2,age3) + self.assertEqual(age1, age2) + self.assertEqual(age2, age3) instance.stop() @@ -182,18 +179,18 @@ def slowtest5(self): print("Testing FallbackStellarEvolution: evolve with end time") instance = FallbackStellarEvolution() - instance._main_se.parameters.max_age_stop_condition=0.1| units.Myr + instance._main_se.parameters.max_age_stop_condition = 0.1 | units.Myr - stars = Particles(3,mass=[10.,20.,30.] | units.MSun) + stars = Particles(3, mass=[10., 20., 30.] | units.MSun) stars = instance.particles.add_particles(stars) instance.commit_particles() instance.evolve_model(.101 | units.Myr) for star in stars: - self.assertEqual(instance.ActiveModel[star].__class__.__name__,"SSE") + self.assertEqual(instance.ActiveModel[star].__class__.__name__, "SSE") - self.assertTrue(.101| units.Myr0 is approaching 1 - phi_at_0 = nfw_profile.get_potential_at_point(0.|units.m,0.|units.m,0.|units.m,1.e-10|units.kpc) + phi_at_0 = nfw_profile.get_potential_at_point(0. | units.m, 0. | units.m, 0. | units.m, 1.e-10 | units.kpc) self.assertAlmostEqual(phi_at_0/phi0, 1.0, 4) - + # relative force at (r/rs)->0 is approaching -1/2 - ar_at_0 = nfw_profile.radial_force(1.e-5|units.kpc) + ar_at_0 = nfw_profile.radial_force(1.e-5 | units.kpc) self.assertAlmostEqual(ar_at_0/ar0, -0.5, 4) - + # relative force at (r/rs)->inf is approaching 0 - ar_at_inf = nfw_profile.radial_force(1.e10|units.kpc) + ar_at_inf = nfw_profile.radial_force(1.e10 | units.kpc) self.assertAlmostEqual(ar_at_inf/ar0, 0.0, 5) - + # relative circular velocity has maximum at r/r_s=2.16258 vc_eq_max = nfw_profile.circular_velocity(2.16258*rs) vc_at_r_lt_max = nfw_profile.circular_velocity(2.16248*rs) vc_at_r_gt_max = nfw_profile.circular_velocity(2.16268*rs) self.assertTrue(vc_at_r_lt_max < vc_eq_max) self.assertTrue(vc_at_r_gt_max < vc_eq_max) - + + class TestPlummerProfile(amusetest.TestCase): def test1(self): - mass = 6.e6|units.MSun - a = 6.|units.parsec - plummer_profile = Plummer_profile(mass,a) + mass = 6.e6 | units.MSun + a = 6. | units.parsec + plummer_profile = Plummer_profile(mass, a) rho0 = mass/(4./3.*numpy.pi*a**3) phi0 = -constants.G*mass/a - + # enclosed mass at R>>a is total mass m_tot = plummer_profile.enclosed_mass(a*1.e5) self.assertAlmostEqual(m_tot/mass, 1.0, 5) - + # mass density at the center - rho_cen = plummer_profile.mass_density(0.|units.m) + rho_cen = plummer_profile.mass_density(0. | units.m) self.assertAlmostEqual(rho_cen/rho0, 1.0, 5) - + # potential at r=a is phi0/sqrt(2) - phi_at_a = plummer_profile.get_potential_at_point(0.|units.m,0.|units.m,0.|units.m,a) + phi_at_a = plummer_profile.get_potential_at_point(0. | units.m, 0. | units.m, 0. | units.m, a) self.assertAlmostEqual(phi_at_a/phi0*numpy.sqrt(2.), 1.0, 5) - + + class TestMiyamotoNagaiProfile(amusetest.TestCase): def test1(self): - mass = 6.6e10|units.MSun - a = 3.33|units.kpc - b = 0.666|units.kpc - profile = MiyamotoNagai_profile(mass,a,b) - - r_force = profile.force_R(0.1*a,0.2*b,1.2*a).in_(units.parsec/units.Myr**2) - z_force = profile.force_z(0.1*a,0.2*b,1.2*a).in_(units.parsec/units.Myr**2) - potential = profile.get_potential_at_point(0.|units.m,a*0.1,a*5.,b*0.5).in_(units.kpc**2/units.Myr**2) - ax,ay,az = profile.get_gravity_at_point(0.|units.m,a*0.1,a*5.,b*0.5) - density = profile.mass_density(0.1*a,-0.5*b,1.2*a).in_(units.MSun/units.kpc**3) + mass = 6.6e10 | units.MSun + a = 3.33 | units.kpc + b = 0.666 | units.kpc + profile = MiyamotoNagai_profile(mass, a, b) + + r_force = profile.force_R(0.1*a, 0.2*b, 1.2*a).in_(units.parsec/units.Myr**2) + z_force = profile.force_z(0.1*a, 0.2*b, 1.2*a).in_(units.parsec/units.Myr**2) + potential = profile.get_potential_at_point(0. | units.m, a*0.1, a*5., b*0.5).in_(units.kpc**2/units.Myr**2) + ax, ay, az = profile.get_gravity_at_point(0. | units.m, a*0.1, a*5., b*0.5) + density = profile.mass_density(0.1*a, -0.5*b, 1.2*a).in_(units.MSun/units.kpc**3) vc = profile.circular_velocity_at_z0(1.0*a).in_(units.kms) m_r = profile.equivalent_enclosed_mass_in_plane(100.*a).in_(units.MSun) - - self.assertAlmostEqual(r_force, -0.263920797645|units.parsec/units.Myr**2, 12) - self.assertAlmostEqual(z_force, -5.35763387945 |units.parsec/units.Myr**2, 11) - self.assertAlmostEqual(potential, -0.017321166943|units.kpc**2/units.Myr**2, 12) - self.assertAlmostEqual(ax, -0.0196231550925|units.parsec/units.Myr**2, 12) - self.assertAlmostEqual(ay, -0.981157754625|units.parsec/units.Myr**2, 12) - self.assertAlmostEqual(az, -0.107380572532 |units.parsec/units.Myr**2, 12) - self.assertAlmostEqual(density, 1336672.32264|units.MSun/units.kpc**3, 5) - self.assertAlmostEqual(vc, 149.569512197|units.kms, 9) - self.assertAlmostEqual(m_r, 65.9857465656|1.e9*units.MSun, 9) - + + self.assertAlmostEqual(r_force, -0.263920797645 | units.parsec/units.Myr**2, 12) + self.assertAlmostEqual(z_force, -5.35763387945 | units.parsec/units.Myr**2, 11) + self.assertAlmostEqual(potential, -0.017321166943 | units.kpc**2/units.Myr**2, 12) + self.assertAlmostEqual(ax, -0.0196231550925 | units.parsec/units.Myr**2, 12) + self.assertAlmostEqual(ay, -0.981157754625 | units.parsec/units.Myr**2, 12) + self.assertAlmostEqual(az, -0.107380572532 | units.parsec/units.Myr**2, 12) + self.assertAlmostEqual(density, 1336672.32264 | units.MSun/units.kpc**3, 5) + self.assertAlmostEqual(vc, 149.569512197 | units.kms, 9) + self.assertAlmostEqual(m_r, 65.9857465656 | 1.e9*units.MSun, 9) + def test2(self): - mass = 1.984e4|units.MSun - a = 0.0|units.parsec - b = 6.66|units.parsec - nm_profile = MiyamotoNagai_profile(mass,a,b) - plummer_profile = Plummer_profile(mass,b) - - pot_nm = nm_profile.get_potential_at_point(0.|units.m,b*0.1,b*5.,b*0.2) - pot_p = plummer_profile.get_potential_at_point(0.|units.m,b*0.1,b*5.,b*0.2) - self.assertEqual(pot_nm,pot_p) - - ax_nm,ay_nm,az_nm = nm_profile.get_gravity_at_point(0.|units.m,b*0.1,b*5.,b*0.1) - ax_p,ay_p,az_p = plummer_profile.get_gravity_at_point(0.|units.m,b*0.1,b*5.,b*0.1) + mass = 1.984e4 | units.MSun + a = 0.0 | units.parsec + b = 6.66 | units.parsec + nm_profile = MiyamotoNagai_profile(mass, a, b) + plummer_profile = Plummer_profile(mass, b) + + pot_nm = nm_profile.get_potential_at_point(0. | units.m, b*0.1, b*5., b*0.2) + pot_p = plummer_profile.get_potential_at_point(0. | units.m, b*0.1, b*5., b*0.2) + self.assertEqual(pot_nm, pot_p) + + ax_nm, ay_nm, az_nm = nm_profile.get_gravity_at_point(0. | units.m, b*0.1, b*5., b*0.1) + ax_p, ay_p, az_p = plummer_profile.get_gravity_at_point(0. | units.m, b*0.1, b*5., b*0.1) print(ax_nm.in_(units.parsec/units.Myr**2), ax_p.in_(units.parsec/units.Myr**2)) - self.assertAlmostEqual(ax_nm.in_(units.parsec/units.Myr**2),ax_p.in_(units.parsec/units.Myr**2), 12) - self.assertAlmostEqual(ay_nm.in_(units.parsec/units.Myr**2),ay_p.in_(units.parsec/units.Myr**2), 12) - self.assertAlmostEqual(az_nm.in_(units.parsec/units.Myr**2),az_p.in_(units.parsec/units.Myr**2), 12) - - rho_nm = nm_profile.mass_density(b*0.,b*0.,b*6.6) + self.assertAlmostEqual(ax_nm.in_(units.parsec/units.Myr**2), ax_p.in_(units.parsec/units.Myr**2), 12) + self.assertAlmostEqual(ay_nm.in_(units.parsec/units.Myr**2), ay_p.in_(units.parsec/units.Myr**2), 12) + self.assertAlmostEqual(az_nm.in_(units.parsec/units.Myr**2), az_p.in_(units.parsec/units.Myr**2), 12) + + rho_nm = nm_profile.mass_density(b*0., b*0., b*6.6) rho_p = plummer_profile.mass_density(b*6.6) - self.assertEqual(rho_nm,rho_p) + self.assertEqual(rho_nm, rho_p) + class TestPowerLawCutoff_profile(amusetest.TestCase): def test1(self): - rho0 = 12.|units.MSun/units.parsec**3 - r0 = 1.6|units.parsec + rho0 = 12. | units.MSun/units.parsec**3 + r0 = 1.6 | units.parsec alpha = 1.6 - rc = 0.66|units.kpc - power_law = PowerLawCutoff_profile(rho0,r0,alpha,rc) + rc = 0.66 | units.kpc + power_law = PowerLawCutoff_profile(rho0, r0, alpha, rc) r_force = power_law.radial_force(0.1*r0).in_(units.parsec/units.Myr**2) - potential = power_law.get_potential_at_point(0.|units.m,r0*0.1,r0*5.,r0*0.5).in_(units.kpc**2/units.Myr**2) - ax,ay,az = power_law.get_gravity_at_point(0.|units.m,r0*0.1,r0*5.,r0*0.5) + potential = power_law.get_potential_at_point(0. | units.m, r0*0.1, r0*5., r0*0.5).in_(units.kpc**2/units.Myr**2) + ax, ay, az = power_law.get_gravity_at_point(0. | units.m, r0*0.1, r0*5., r0*0.5) density = power_law.mass_density(6.6*r0).in_(units.MSun/units.parsec**3) vc = power_law.circular_velocity(r0).in_(units.kms) m_r = power_law.enclosed_mass(100.*r0).in_(units.MSun) - - self.assertAlmostEqual(r_force, -3.08704194743 |units.parsec/units.Myr**2, 10) - self.assertAlmostEqual(potential, -5.91677122595e-06 |units.kpc**2/units.Myr**2, 10) - self.assertAlmostEqual(ax, -0.00585557189412|units.parsec/units.Myr**2, 10) - self.assertAlmostEqual(ay, -0.292778594706|units.parsec/units.Myr**2, 10) - self.assertAlmostEqual(az, -0.0292778594706|units.parsec/units.Myr**2, 10) - self.assertAlmostEqual(density, 0.585867989506 |units.MSun/units.parsec**3, 10) - self.assertAlmostEqual(vc, 1.0891472277|units.kms, 10) - self.assertAlmostEqual(m_r, 2.71756907682 |1.e5*units.MSun, 9) + + self.assertAlmostEqual(r_force, -3.08704194743 | units.parsec/units.Myr**2, 10) + self.assertAlmostEqual(potential, -5.91677122595e-06 | units.kpc**2/units.Myr**2, 10) + self.assertAlmostEqual(ax, -0.00585557189412 | units.parsec/units.Myr**2, 10) + self.assertAlmostEqual(ay, -0.292778594706 | units.parsec/units.Myr**2, 10) + self.assertAlmostEqual(az, -0.0292778594706 | units.parsec/units.Myr**2, 10) + self.assertAlmostEqual(density, 0.585867989506 | units.MSun/units.parsec**3, 10) + self.assertAlmostEqual(vc, 1.0891472277 | units.kms, 10) + self.assertAlmostEqual(m_r, 2.71756907682 | 1.e5*units.MSun, 9) def test2(self): - rho0 = 12.|units.MSun/units.parsec**3 - r0 = 1.6|units.parsec + rho0 = 12. | units.MSun/units.parsec**3 + r0 = 1.6 | units.parsec alpha = 1.6 - rc = 0.66|units.kpc - power_law = PowerLawCutoff_profile(rho0,r0,alpha,rc) - - r=2*rc*numpy.arange(100001)/100000. - - pot=power_law.get_potential_at_point(0. | units.kpc, r, 0.*r,0*r) - rho=power_law.mass_density( r) - - d=r[1]-r[0] - rpot=r*pot - lapl=(rpot[2:]-2*rpot[1:-1]+rpot[:-2])/d**2/r[1:-1] - rcheck=r[1:-1] - - rho1=(-lapl/(4*units.pi*constants.G)) - rho2=rho[1:-1] - d=((rho1[1:]-rho2[1:])/rho2[1:]) - # seems to be ok: - self.assertTrue(d.max()< 0.025) - self.assertTrue(d.mean()< 1.e-6) - - + rc = 0.66 | units.kpc + power_law = PowerLawCutoff_profile(rho0, r0, alpha, rc) + + r = 2*rc*numpy.arange(100001)/100000. + + pot = power_law.get_potential_at_point(0. | units.kpc, r, 0.*r, 0*r) + rho = power_law.mass_density(r) + + d = r[1]-r[0] + rpot = r*pot + lapl = (rpot[2:]-2*rpot[1:-1]+rpot[:-2])/d**2/r[1:-1] + rcheck = r[1:-1] + + rho1 = (-lapl/(4*units.pi*constants.G)) + rho2 = rho[1:-1] + d = ((rho1[1:]-rho2[1:])/rho2[1:]) + # seems to be ok: + self.assertTrue(d.max() < 0.025) + self.assertTrue(d.mean() < 1.e-6) + def setUp(self): if not scipy_imported: self.skip("scipy not installed") + class TestMWpotentialBovy2015(amusetest.TestCase): def test1(self): """ See Table 1 of Bovy 2015, http://adsabs.harvard.edu/abs/2015ApJS..216...29B """ mw = MWpotentialBovy2015() - r0 = 8.|units.kpc - v0 = 220.|units.kms - + r0 = 8. | units.kpc + v0 = 220. | units.kms + # total mass density at r=r0,z=0 - rho_r0_z0 = mw.mass_density(r0,0.|units.m,0.|units.m) - self.assertAlmostEqual(rho_r0_z0, 0.10|units.MSun/units.parsec**3, 2) - + rho_r0_z0 = mw.mass_density(r0, 0. | units.m, 0. | units.m) + self.assertAlmostEqual(rho_r0_z0, 0.10 | units.MSun/units.parsec**3, 2) + # halo mass density at r0 rho_halo_at_r0 = mw.halo.mass_density(r0) - self.assertAlmostEqual(rho_halo_at_r0, 0.008|units.MSun/units.parsec**3, 3) - + self.assertAlmostEqual(rho_halo_at_r0, 0.008 | units.MSun/units.parsec**3, 3) + # mass enclosed in 60kpc - mass_in_60 = mw.enclosed_mass(60.|units.kpc) + mass_in_60 = mw.enclosed_mass(60. | units.kpc) print(mass_in_60.in_(units.MSun)) - self.assertAlmostEqual((mass_in_60/1.e11).in_(units.MSun), 4.08|units.MSun, 2) - + self.assertAlmostEqual((mass_in_60/1.e11).in_(units.MSun), 4.08 | units.MSun, 2) + # normalization factor for bulge fr_r0_v0 = v0**2 / r0 fr_r0_bulge = -mw.bulge.radial_force(r0) self.assertAlmostEqual(fr_r0_bulge/fr_r0_v0, 0.05, 3) - + # normalization factor for disk - fr_r0_disk = -mw.disk.force_R(r0,0.|units.m,0.|units.m) + fr_r0_disk = -mw.disk.force_R(r0, 0. | units.m, 0. | units.m) self.assertAlmostEqual(fr_r0_disk/fr_r0_v0, 0.6, 3) - + # normalization factor for halo fr_r0_halo = -mw.halo.radial_force(r0) print(fr_r0_halo/fr_r0_v0) self.assertAlmostEqual(fr_r0_halo/fr_r0_v0, 0.35, 3) - + def setUp(self): if not scipy_imported: self.skip("scipy not installed") diff --git a/src/amuse/test/suite/ext_tests/test_galactics_model.py b/src/amuse/test/suite/ext_tests/test_galactics_model.py index e9b4717b4d..37869ea98a 100644 --- a/src/amuse/test/suite/ext_tests/test_galactics_model.py +++ b/src/amuse/test/suite/ext_tests/test_galactics_model.py @@ -8,141 +8,139 @@ # testing the gas models is *very* slow + class NewGalactICsModelTests(TestWithMPI): - + def test1(self): halo_number_of_particles = 100 - particles = new_galactics_model(halo_number_of_particles, generate_bulge_flag = False, - generate_disk_flag = False, order_of_multipole_expansion = 0, halo_random_seed = -1, - do_scale = True) - + particles = new_galactics_model(halo_number_of_particles, generate_bulge_flag=False, + generate_disk_flag=False, order_of_multipole_expansion=0, halo_random_seed=-1, + do_scale=True) + self.assertEqual(len(particles), halo_number_of_particles) self.assertAlmostEqual(particles.total_mass(), 1.0 | nbody_system.mass) - self.assertAlmostEqual(particles.kinetic_energy(), + self.assertAlmostEqual(particles.kinetic_energy(), 0.25 | nbody_system.energy) - + def test2(self): self.assertTrue("GalactICs documentation:" in new_galactics_model.__doc__) self.assertTrue("GalactICs allows to generate self-consistent disc-bulge-halo galaxy models." in new_galactics_model.__doc__) - + self.assertTrue("Parameters:" in new_galactics_model.__doc__) self.assertTrue("generate_disk_flag" in new_galactics_model.__doc__) self.assertTrue("halo_streaming_fraction" in new_galactics_model.__doc__) - + print(new_galactics_model.__doc__) - + def slowtest3(self): print("Generate a model for M31, using defaults (100k disk, 50k bulge, 200k halo) - Nbody units") halo_number_of_particles = 20000 - particles = new_galactics_model(halo_number_of_particles, do_scale = True, + particles = new_galactics_model(halo_number_of_particles, do_scale=True, bulge_number_of_particles=5000, disk_number_of_particles=10000) - + self.assertEqual(len(particles), 35000) self.assertAlmostEqual(particles.total_mass(), 1.0 | nbody_system.mass) self.assertAlmostEqual(particles.kinetic_energy(), 0.25 | nbody_system.energy) - + write_set_to_file(particles, os.path.join(get_path_to_results(), 'M31_galactICs.amuse'), 'amuse') - + def slowtest4(self): print("Generate a model for a disk galaxy (10k disk, no bulge, 20k halo) - SI units") halo_number_of_particles = 20000 converter = generic_unit_converter.ConvertBetweenGenericAndSiUnits(constants.G, 1.0e12 | units.MSun, 50.0 | units.kpc) - particles = new_galactics_model(halo_number_of_particles, disk_number_of_particles=10000, + particles = new_galactics_model(halo_number_of_particles, disk_number_of_particles=10000, generate_bulge_flag=False, do_scale=True, unit_system_converter=converter) - + self.assertEqual(len(particles), 30000) self.assertAlmostRelativeEquals(particles.total_mass(), 1.0e12 | units.MSun, 10) self.assertAlmostRelativeEquals(particles.kinetic_energy(), converter.to_si(0.25 | nbody_system.energy), 10) - + disk = particles[:10000] self.assertAlmostRelativeEquals(disk.total_mass(), 2.156e10 | units.MSun, 3) self.assertAlmostRelativeEquals(disk.position.lengths_squared().amax().sqrt().in_(units.kpc), 15.584 | units.kpc, 3) - + self.assertAlmostRelativeEquals(disk.position.std(axis=0).in_(units.kpc), [3.5934, 3.6768, 0.17078] | units.kpc, 3) - + write_set_to_file(particles, os.path.join(get_path_to_results(), 'disk_galactICs.amuse'), 'amuse') - + def test5(self): halo_number_of_particles = 1000 - - conv=nbody_system.nbody_to_si(1.e12 | units.MSun, 100. | units.kpc) - - particles1 = new_galactics_model(halo_number_of_particles, generate_bulge_flag = False, - generate_disk_flag = False, order_of_multipole_expansion = 0, halo_random_seed = -1, - do_scale = False) - particles2 = new_galactics_model(halo_number_of_particles, conv, generate_bulge_flag = False, - generate_disk_flag = False, order_of_multipole_expansion = 0, halo_random_seed = -1, - do_scale = False) - particles3 = new_galactics_model(halo_number_of_particles, generate_bulge_flag = False, - generate_disk_flag = False, order_of_multipole_expansion = 0, halo_random_seed = -1, - do_scale = True) - particles4 = new_galactics_model(halo_number_of_particles, conv,generate_bulge_flag = False, - generate_disk_flag = False, order_of_multipole_expansion = 0, halo_random_seed = -1, - do_scale = True) - - + + conv = nbody_system.nbody_to_si(1.e12 | units.MSun, 100. | units.kpc) + + particles1 = new_galactics_model(halo_number_of_particles, generate_bulge_flag=False, + generate_disk_flag=False, order_of_multipole_expansion=0, halo_random_seed=-1, + do_scale=False) + particles2 = new_galactics_model(halo_number_of_particles, conv, generate_bulge_flag=False, + generate_disk_flag=False, order_of_multipole_expansion=0, halo_random_seed=-1, + do_scale=False) + particles3 = new_galactics_model(halo_number_of_particles, generate_bulge_flag=False, + generate_disk_flag=False, order_of_multipole_expansion=0, halo_random_seed=-1, + do_scale=True) + particles4 = new_galactics_model(halo_number_of_particles, conv, generate_bulge_flag=False, + generate_disk_flag=False, order_of_multipole_expansion=0, halo_random_seed=-1, + do_scale=True) + self.assertEqual(len(particles1), halo_number_of_particles) self.assertEqual(len(particles2), halo_number_of_particles) self.assertEqual(len(particles3), halo_number_of_particles) self.assertEqual(len(particles4), halo_number_of_particles) - + self.assertAlmostEqual(conv.to_nbody(particles2.total_mass()), particles1.total_mass()) self.assertAlmostEqual(conv.to_nbody(particles4.total_mass()), particles3.total_mass()) self.assertAlmostEqual(particles3.total_mass(), 1. | nbody_system.mass) - self.assertAlmostRelativeEquals(particles4.total_mass(), conv.to_si(1. | nbody_system.mass),12) + self.assertAlmostRelativeEquals(particles4.total_mass(), conv.to_si(1. | nbody_system.mass), 12) - r1=particles1.position.lengths().std() - r2=particles2.position.lengths().std() - r3=particles3.position.lengths().std() - r4=particles4.position.lengths().std() + r1 = particles1.position.lengths().std() + r2 = particles2.position.lengths().std() + r3 = particles3.position.lengths().std() + r4 = particles4.position.lengths().std() self.assertAlmostEqual(conv.to_nbody(r2), r1) self.assertAlmostEqual(conv.to_nbody(r4), r3) - self.assertTrue(r1/r3>100) # for the default parameters the scaling is quite drastic - self.assertTrue(r2/r4>100) - print(r1,r3) - print(r2,r4) + self.assertTrue(r1/r3 > 100) # for the default parameters the scaling is quite drastic + self.assertTrue(r2/r4 > 100) + print(r1, r3) + print(r2, r4) def test6(self): halo_number_of_particles = 1000 - - conv=nbody_system.nbody_to_si(1.e12 | units.MSun, 100. | units.kpc) - - particles1 = new_galactics_gas_model(halo_number_of_particles, bulge_type_parameter=0, - disk_type_parameter=0, order_of_multipole_expansion = 0, halo_random_seed = -1, - do_scale = False, reuse_cached_model=False, verbose=True) - particles2 = new_galactics_gas_model(halo_number_of_particles, conv, bulge_type_parameter=0, - disk_type_parameter=0, order_of_multipole_expansion = 0, halo_random_seed = -1, - do_scale = False, verbose=True) - particles3 = new_galactics_gas_model(halo_number_of_particles, bulge_type_parameter=0, - disk_type_parameter=0, order_of_multipole_expansion = 0, halo_random_seed = -1, - do_scale = True, verbose=True) - particles4 = new_galactics_gas_model(halo_number_of_particles, conv, bulge_type_parameter=0, - disk_type_parameter=0, order_of_multipole_expansion = 0, halo_random_seed = -1, - do_scale = True, verbose=True) - - + + conv = nbody_system.nbody_to_si(1.e12 | units.MSun, 100. | units.kpc) + + particles1 = new_galactics_gas_model(halo_number_of_particles, bulge_type_parameter=0, + disk_type_parameter=0, order_of_multipole_expansion=0, halo_random_seed=-1, + do_scale=False, reuse_cached_model=False, verbose=True) + particles2 = new_galactics_gas_model(halo_number_of_particles, conv, bulge_type_parameter=0, + disk_type_parameter=0, order_of_multipole_expansion=0, halo_random_seed=-1, + do_scale=False, verbose=True) + particles3 = new_galactics_gas_model(halo_number_of_particles, bulge_type_parameter=0, + disk_type_parameter=0, order_of_multipole_expansion=0, halo_random_seed=-1, + do_scale=True, verbose=True) + particles4 = new_galactics_gas_model(halo_number_of_particles, conv, bulge_type_parameter=0, + disk_type_parameter=0, order_of_multipole_expansion=0, halo_random_seed=-1, + do_scale=True, verbose=True) + self.assertEqual(len(particles1), halo_number_of_particles) self.assertEqual(len(particles2), halo_number_of_particles) self.assertEqual(len(particles3), halo_number_of_particles) self.assertEqual(len(particles4), halo_number_of_particles) - + self.assertAlmostEqual(conv.to_nbody(particles2.total_mass()), particles1.total_mass()) self.assertAlmostEqual(conv.to_nbody(particles4.total_mass()), particles3.total_mass()) self.assertAlmostEqual(particles3.total_mass(), 1. | nbody_system.mass) - self.assertAlmostRelativeEquals(particles4.total_mass(), conv.to_si(1. | nbody_system.mass),12) + self.assertAlmostRelativeEquals(particles4.total_mass(), conv.to_si(1. | nbody_system.mass), 12) - r1=particles1.position.lengths().std() - r2=particles2.position.lengths().std() - r3=particles3.position.lengths().std() - r4=particles4.position.lengths().std() + r1 = particles1.position.lengths().std() + r2 = particles2.position.lengths().std() + r3 = particles3.position.lengths().std() + r4 = particles4.position.lengths().std() self.assertAlmostEqual(conv.to_nbody(r2), r1) self.assertAlmostEqual(conv.to_nbody(r4), r3) - self.assertTrue(r1/r3>30) # for the default parameters the scaling is quite drastic - self.assertTrue(r2/r4>30) - print(r1,r3) - print(r2,r4) - + self.assertTrue(r1/r3 > 30) # for the default parameters the scaling is quite drastic + self.assertTrue(r2/r4 > 30) + print(r1, r3) + print(r2, r4) - #~ self.assertAlmostEquals(particles.kinetic_energy(), - #~ 0.25 | nbody_system.energy) + # ~ self.assertAlmostEquals(particles.kinetic_energy(), + # ~ 0.25 | nbody_system.energy) diff --git a/src/amuse/test/suite/ext_tests/test_gasplummer.py b/src/amuse/test/suite/ext_tests/test_gasplummer.py index 83c27f689a..3aa80995d7 100644 --- a/src/amuse/test/suite/ext_tests/test_gasplummer.py +++ b/src/amuse/test/suite/ext_tests/test_gasplummer.py @@ -5,13 +5,14 @@ from amuse.units import units from amuse.ic.gasplummer import new_plummer_gas_model, MakePlummerGasModel + class TestPlummerGasModel(amusetest.TestCase): - + def test1(self): print("Test 1: testing low-level interface (no units or datamodel)") numpy.random.seed(345672) mpgm = MakePlummerGasModel(2) - mass, x,y,z, vx,vy,vz, u = mpgm.new_model() + mass, x, y, z, vx, vy, vz, u = mpgm.new_model() self.assertEqual(mass[0], 0.5) self.assertEqual(mass[1], 0.5) self.assertAlmostEqual(x, [-0.02295788, 0.12829775]) @@ -21,48 +22,47 @@ def test1(self): self.assertAlmostEqual(vy, [0.0, 0.0]) self.assertAlmostEqual(vz, [0.0, 0.0]) self.assertAlmostEqual(u, [0.28413716, 0.39898137]) - + def test2(self): print("Test 2: testing user interface, with convert_nbody -> SI units") - convert_nbody = nbody_system.nbody_to_si(6|units.kg, 7 | units.m) - gas = new_plummer_gas_model(2, convert_nbody) + convert_nbody = nbody_system.nbody_to_si(6 | units.kg, 7 | units.m) + gas = new_plummer_gas_model(2, convert_nbody) self.assertEqual(gas[0].mass.value_in(units.kg), 3.0) self.assertEqual(gas[1].mass.value_in(units.kg), 3.0) - + def test3(self): print("Test 3: testing user interface, without convert_nbody -> nbody units") - gas = new_plummer_gas_model(2, None) + gas = new_plummer_gas_model(2, None) self.assertEqual(gas[0].mass.value_in(nbody_system.mass), 0.5) self.assertEqual(gas[1].mass.value_in(nbody_system.mass), 0.5) - + def test4(self): print("Test 4: test new_plummer_gas_model, model properties") numpy.random.seed(345672) gas = new_plummer_gas_model(100) - + self.assertEqual(len(gas), 100) self.assertAlmostEqual(gas.kinetic_energy(), 0.00 | nbody_system.energy) - self.assertIsOfOrder( gas.thermal_energy(), 0.25 | nbody_system.energy) + self.assertIsOfOrder(gas.thermal_energy(), 0.25 | nbody_system.energy) self.assertAlmostEqual(gas.thermal_energy(), 0.238075609078 | nbody_system.energy) - self.assertIsOfOrder( gas.potential_energy(G=nbody_system.G), -0.50 | nbody_system.energy) + self.assertIsOfOrder(gas.potential_energy(G=nbody_system.G), -0.50 | nbody_system.energy) self.assertAlmostEqual(gas.potential_energy(G=nbody_system.G), -0.447052244411 | nbody_system.energy) - - self.assertAlmostEqual(gas.center_of_mass(), [0,0,0] | nbody_system.length) - self.assertAlmostEqual(gas.center_of_mass_velocity(), [0,0,0] | nbody_system.speed) + + self.assertAlmostEqual(gas.center_of_mass(), [0, 0, 0] | nbody_system.length) + self.assertAlmostEqual(gas.center_of_mass_velocity(), [0, 0, 0] | nbody_system.speed) self.assertAlmostEqual(gas.total_mass(), 1.00 | nbody_system.mass) self.assertIsOfOrder(gas.virial_radius(), 1.00 | nbody_system.length) self.assertAlmostEqual(gas.virial_radius(), 1.11843751206 | nbody_system.length) - + def test5(self): print("Test 5: test new_plummer_gas_model with do_scale") - gas = new_plummer_gas_model(100, do_scale = True) - + gas = new_plummer_gas_model(100, do_scale=True) + self.assertEqual(len(gas), 100) self.assertAlmostEqual(gas.kinetic_energy(), 0.00 | nbody_system.energy) self.assertAlmostEqual(gas.thermal_energy(), 0.25 | nbody_system.energy) self.assertAlmostEqual(gas.potential_energy(G=nbody_system.G), -0.50 | nbody_system.energy) - self.assertAlmostEqual(gas.center_of_mass(), [0,0,0] | nbody_system.length) - self.assertAlmostEqual(gas.center_of_mass_velocity(), [0,0,0] | nbody_system.speed) + self.assertAlmostEqual(gas.center_of_mass(), [0, 0, 0] | nbody_system.length) + self.assertAlmostEqual(gas.center_of_mass_velocity(), [0, 0, 0] | nbody_system.speed) self.assertAlmostEqual(gas.total_mass(), 1.00 | nbody_system.mass) self.assertAlmostEqual(gas.virial_radius(), 1.00 | nbody_system.length) - diff --git a/src/amuse/test/suite/ext_tests/test_grid_remappers.py b/src/amuse/test/suite/ext_tests/test_grid_remappers.py index 2dc2f5e380..449cd5f0c4 100644 --- a/src/amuse/test/suite/ext_tests/test_grid_remappers.py +++ b/src/amuse/test/suite/ext_tests/test_grid_remappers.py @@ -13,6 +13,7 @@ from amuse.datamodel.grids import * from amuse.datamodel.staggeredgrid import StaggeredGrid + class TestGridRemappers(TestCase): def setUp(self): @@ -20,108 +21,106 @@ def setUp(self): self.skip("matplotlib not available") def test1(self): - source=new_cartesian_grid((10,20),1.) - target=new_cartesian_grid((5,10),2.,offset=[0.,0.15]) - - source.xcopy=source.x - source.ycopy=source.y - - remapper=grid_remappers.interpolating_2D_remapper(source,target) - remapper.forward_mapping(["xcopy","ycopy"]) - self.assertEqual(target.x,target.xcopy) - self.assertEqual(target.y,target.ycopy) + source = new_cartesian_grid((10, 20), 1.) + target = new_cartesian_grid((5, 10), 2., offset=[0., 0.15]) + + source.xcopy = source.x + source.ycopy = source.y + + remapper = grid_remappers.interpolating_2D_remapper(source, target) + remapper.forward_mapping(["xcopy", "ycopy"]) + self.assertEqual(target.x, target.xcopy) + self.assertEqual(target.y, target.ycopy) def test2(self): - source=new_cartesian_grid((10,20),1. | units.m) - target=new_cartesian_grid((5,10),2. | units.m,offset=[0.,0.15] | units.m) - - source.xcopy=source.x - source.ycopy=source.y - - remapper=grid_remappers.interpolating_2D_remapper(source,target) - remapper.forward_mapping(["xcopy","ycopy"]) - self.assertEqual(target.x,target.xcopy) - self.assertEqual(target.y,target.ycopy) + source = new_cartesian_grid((10, 20), 1. | units.m) + target = new_cartesian_grid((5, 10), 2. | units.m, offset=[0., 0.15] | units.m) + + source.xcopy = source.x + source.ycopy = source.y + + remapper = grid_remappers.interpolating_2D_remapper(source, target) + remapper.forward_mapping(["xcopy", "ycopy"]) + self.assertEqual(target.x, target.xcopy) + self.assertEqual(target.y, target.ycopy) + class TestGridRemappers_bilinear(TestCase): def test1(self): - source=new_cartesian_grid((10,20),1.) - target=new_cartesian_grid((5,10),2.,offset=[0.,0.25]) - - source.xcopy=source.x - source.ycopy=source.y - - remapper=grid_remappers.bilinear_2D_remapper(source,target) - remapper.forward_mapping(["xcopy","ycopy"]) - self.assertEqual(target.x,target.xcopy) - self.assertEqual(target.y,target.ycopy) + source = new_cartesian_grid((10, 20), 1.) + target = new_cartesian_grid((5, 10), 2., offset=[0., 0.25]) + + source.xcopy = source.x + source.ycopy = source.y + + remapper = grid_remappers.bilinear_2D_remapper(source, target) + remapper.forward_mapping(["xcopy", "ycopy"]) + self.assertEqual(target.x, target.xcopy) + self.assertEqual(target.y, target.ycopy) def test2(self): - source=new_cartesian_grid((10,20),1.) - target=new_cartesian_grid((8,8),0.125,offset=[0.5,0.5]) - - source.xcopy=source.x - source.ycopy=source.y - - remapper=grid_remappers.bilinear_2D_remapper(source,target) - remapper.forward_mapping(["xcopy","ycopy"]) - self.assertEqual(target.x,target.xcopy) - self.assertEqual(target.y,target.ycopy) + source = new_cartesian_grid((10, 20), 1.) + target = new_cartesian_grid((8, 8), 0.125, offset=[0.5, 0.5]) + + source.xcopy = source.x + source.ycopy = source.y + remapper = grid_remappers.bilinear_2D_remapper(source, target) + remapper.forward_mapping(["xcopy", "ycopy"]) + self.assertEqual(target.x, target.xcopy) + self.assertEqual(target.y, target.ycopy) def test3(self): - source=new_cartesian_grid((10,20),1. | units.m) - target=new_cartesian_grid((5,10),2. | units.m,offset=[0.,0.25] | units.m) - - source.xcopy=source.x - source.ycopy=source.y - - remapper=grid_remappers.bilinear_2D_remapper(source,target) - remapper.forward_mapping(["xcopy","ycopy"]) - self.assertEqual(target.x,target.xcopy) - self.assertEqual(target.y,target.ycopy) + source = new_cartesian_grid((10, 20), 1. | units.m) + target = new_cartesian_grid((5, 10), 2. | units.m, offset=[0., 0.25] | units.m) + + source.xcopy = source.x + source.ycopy = source.y + + remapper = grid_remappers.bilinear_2D_remapper(source, target) + remapper.forward_mapping(["xcopy", "ycopy"]) + self.assertEqual(target.x, target.xcopy) + self.assertEqual(target.y, target.ycopy) def test4(self): - source=new_cartesian_grid((10,20),1.) - target=new_cartesian_grid((10,20),1.5,offset=[-0.5,-0.5]) - - source.xcopy=source.x - source.ycopy=source.y - - remapper=grid_remappers.bilinear_2D_remapper(source,target, check_inside=False) - remapper.forward_mapping(["xcopy","ycopy"]) - self.assertEqual(target.xcopy,numpy.clip(target.x,0.5,9.5)) - self.assertEqual(target.ycopy,numpy.clip(target.y,0.5,19.5)) + source = new_cartesian_grid((10, 20), 1.) + target = new_cartesian_grid((10, 20), 1.5, offset=[-0.5, -0.5]) + + source.xcopy = source.x + source.ycopy = source.y + + remapper = grid_remappers.bilinear_2D_remapper(source, target, check_inside=False) + remapper.forward_mapping(["xcopy", "ycopy"]) + self.assertEqual(target.xcopy, numpy.clip(target.x, 0.5, 9.5)) + self.assertEqual(target.ycopy, numpy.clip(target.y, 0.5, 19.5)) def test5(self): - source=new_regular_grid((10,20, 5),[1.*10,1.*20,1.]) - target=new_regular_grid((10,20, 5),[1.5*10,1.5*20,1.],offset=[-0.5,-0.5, 0.]) - - source.xcopy=source.x - source.ycopy=source.y - - remapper=grid_remappers.bilinear_2D_remapper(source,target, check_inside=False, do_slices=True) - remapper.forward_mapping(["xcopy","ycopy"]) - self.assertEqual(target.xcopy,numpy.clip(target.x,0.5,9.5)) - self.assertEqual(target.ycopy,numpy.clip(target.y,0.5,19.5)) + source = new_regular_grid((10, 20, 5), [1.*10, 1.*20, 1.]) + target = new_regular_grid((10, 20, 5), [1.5*10, 1.5*20, 1.], offset=[-0.5, -0.5, 0.]) + + source.xcopy = source.x + source.ycopy = source.y + remapper = grid_remappers.bilinear_2D_remapper(source, target, check_inside=False, do_slices=True) + remapper.forward_mapping(["xcopy", "ycopy"]) + self.assertEqual(target.xcopy, numpy.clip(target.x, 0.5, 9.5)) + self.assertEqual(target.ycopy, numpy.clip(target.y, 0.5, 19.5)) class TestGridRemappers_nearest(TestCase): def test1(self): - source=new_cartesian_grid((10,20),1.) - target=new_cartesian_grid((5,10),1.,offset=[0.,0.]) - - source.xcopy=source.x - source.ycopy=source.y - - remapper=grid_remappers.nearest_2D_remapper(source,target) - remapper.forward_mapping(["xcopy","ycopy"]) - self.assertEqual(target.x,target.xcopy) - self.assertEqual(target.y,target.ycopy) + source = new_cartesian_grid((10, 20), 1.) + target = new_cartesian_grid((5, 10), 1., offset=[0., 0.]) + + source.xcopy = source.x + source.ycopy = source.y + remapper = grid_remappers.nearest_2D_remapper(source, target) + remapper.forward_mapping(["xcopy", "ycopy"]) + self.assertEqual(target.x, target.xcopy) + self.assertEqual(target.y, target.ycopy) class TestConservativeSphericalRemapper(TestCase): @@ -132,11 +131,11 @@ def setUp(self): except: self.skip("conservative spherical remapper requires omuse.community.cdo.interface") - #this test creates a structured staggered grid and an unstructured staggered grid - #and then uses the conservative_spherical_remapper to remap values between the grids + # this test creates a structured staggered grid and an unstructured staggered grid + # and then uses the conservative_spherical_remapper to remap values between the grids - #define nodal points and triangles of a small test grid - #got this grid from http://matplotlib.org/examples/pylab_examples/triplot_demo.html + # define nodal points and triangles of a small test grid + # got this grid from http://matplotlib.org/examples/pylab_examples/triplot_demo.html xy = numpy.asarray([ [-0.101, 0.872], [-0.080, 0.883], [-0.069, 0.888], [-0.054, 0.890], [-0.045, 0.897], [-0.057, 0.895], [-0.073, 0.900], [-0.087, 0.898], @@ -150,19 +149,19 @@ def setUp(self): [-0.052, 1.022], [-0.052, 1.017], [-0.069, 1.010], [-0.064, 1.005], [-0.048, 1.005], [-0.031, 1.005], [-0.031, 0.996], [-0.040, 0.987], [-0.045, 0.980], [-0.052, 0.975], [-0.040, 0.973], [-0.026, 0.968], - [-0.020, 0.954], [-0.006, 0.947], [ 0.003, 0.935], [ 0.006, 0.926], - [ 0.005, 0.921], [ 0.022, 0.923], [ 0.033, 0.912], [ 0.029, 0.905], - [ 0.017, 0.900], [ 0.012, 0.895], [ 0.027, 0.893], [ 0.019, 0.886], - [ 0.001, 0.883], [-0.012, 0.884], [-0.029, 0.883], [-0.038, 0.879], + [-0.020, 0.954], [-0.006, 0.947], [0.003, 0.935], [0.006, 0.926], + [0.005, 0.921], [0.022, 0.923], [0.033, 0.912], [0.029, 0.905], + [0.017, 0.900], [0.012, 0.895], [0.027, 0.893], [0.019, 0.886], + [0.001, 0.883], [-0.012, 0.884], [-0.029, 0.883], [-0.038, 0.879], [-0.057, 0.881], [-0.062, 0.876], [-0.078, 0.876], [-0.087, 0.872], [-0.030, 0.907], [-0.007, 0.905], [-0.057, 0.916], [-0.025, 0.933], [-0.077, 0.990], [-0.059, 0.993]]) triangles = numpy.asarray([ - [67, 66, 1], [65, 2, 66], [ 1, 66, 2], [64, 2, 65], [63, 3, 64], - [60, 59, 57], [ 2, 64, 3], [ 3, 63, 4], [ 0, 67, 1], [62, 4, 63], - [57, 59, 56], [59, 58, 56], [61, 60, 69], [57, 69, 60], [ 4, 62, 68], - [ 6, 5, 9], [61, 68, 62], [69, 68, 61], [ 9, 5, 70], [ 6, 8, 7], - [ 4, 70, 5], [ 8, 6, 9], [56, 69, 57], [69, 56, 52], [70, 10, 9], + [67, 66, 1], [65, 2, 66], [1, 66, 2], [64, 2, 65], [63, 3, 64], + [60, 59, 57], [2, 64, 3], [3, 63, 4], [0, 67, 1], [62, 4, 63], + [57, 59, 56], [59, 58, 56], [61, 60, 69], [57, 69, 60], [4, 62, 68], + [6, 5, 9], [61, 68, 62], [69, 68, 61], [9, 5, 70], [6, 8, 7], + [4, 70, 5], [8, 6, 9], [56, 69, 57], [69, 56, 52], [70, 10, 9], [54, 53, 55], [56, 55, 53], [68, 70, 4], [52, 56, 53], [11, 10, 12], [69, 71, 68], [68, 13, 70], [10, 70, 13], [51, 50, 52], [13, 68, 71], [52, 71, 69], [12, 10, 13], [71, 52, 50], [71, 14, 13], [50, 49, 71], @@ -177,45 +176,45 @@ def setUp(self): num_elems = len(triangles) elements = UnstructuredGrid(num_elems) - elements.n1 = triangles[:,0] - 1 - elements.n2 = triangles[:,1] - 1 - elements.n3 = triangles[:,2] - 1 + elements.n1 = triangles[:, 0] - 1 + elements.n2 = triangles[:, 1] - 1 + elements.n3 = triangles[:, 2] - 1 lons = numpy.zeros(num_elems, dtype=numpy.double) lats = numpy.zeros(num_elems, dtype=numpy.double) for i in range(num_elems): for n in triangles[i]: - lons[i] += xy[n,0]/3.0 - lats[i] += xy[n,1]/3.0 + lons[i] += xy[n, 0]/3.0 + lats[i] += xy[n, 1]/3.0 elements.lon = (lons | units.rad) elements.lat = (lats | units.rad) nodes = UnstructuredGrid(len(xy)) - nodes.lon = (xy[:,0] | units.rad) - nodes.lat = (xy[:,1] | units.rad) + nodes.lon = (xy[:, 0] | units.rad) + nodes.lat = (xy[:, 1] | units.rad) self.unstructured = StaggeredGrid(elements, nodes) - #generate corners for a simple structured grid as source grid - shape = [5,5] - lon_range = xy[:,0].max() - xy[:,0].min() + 0.025 - lon_min = xy[:,0].min() -0.0125 - lat_range = xy[:,1].max() - xy[:,1].min() + 0.025 - lat_min = xy[:,1].min() -0.0125 - ind = numpy.indices( (shape[0]+1,shape[1]+1)) - lats = numpy.array( ind[1] , dtype=numpy.float) + # generate corners for a simple structured grid as source grid + shape = [5, 5] + lon_range = xy[:, 0].max() - xy[:, 0].min() + 0.025 + lon_min = xy[:, 0].min() - 0.0125 + lat_range = xy[:, 1].max() - xy[:, 1].min() + 0.025 + lat_min = xy[:, 1].min() - 0.0125 + ind = numpy.indices((shape[0]+1, shape[1]+1)) + lats = numpy.array(ind[1], dtype=numpy.float) lats = lat_min + lats/shape[1] * lat_range - lons = numpy.array( ind[0] , dtype=numpy.float) - lons = lon_min + lons/shape[0] * lon_range + lons = numpy.array(ind[0], dtype=numpy.float) + lons = lon_min + lons/shape[0] * lon_range - corners = numpy.array([lons,lats]) + corners = numpy.array([lons, lats]) elements = new_structured_grid(shape, corners, axes_names=['lon', 'lat']) nodes = StructuredGrid(*ind[0].shape) nodes.lat = (lats | units.rad) nodes.lon = (lons | units.rad) self.structured = StaggeredGrid(elements, nodes) - corners += 0.01 #shift the grid + corners += 0.01 # shift the grid nodes = StructuredGrid(*ind[0].shape) nodes.lat = (corners[1] | units.rad) nodes.lon = (corners[0] | units.rad) @@ -225,7 +224,7 @@ def test1(self): target = self.unstructured source = self.structured - #set some values on the grid + # set some values on the grid constant_field = numpy.zeros(source.nodes.shape, dtype=numpy.double) constant_field += 1.0 source.nodes.const = constant_field @@ -234,10 +233,10 @@ def test1(self): constant_field += 1.0 source.elements.const2 = constant_field - #create remapper + # create remapper remapper = grid_remappers.conservative_spherical_remapper(source, target) - #remap values + # remap values remapper.forward_mapping(["const", "const2"]) self.assertTrue(numpy.all(target.nodes.const >= 0.0), msg="Expecting all remapped values values to be larger than zero") @@ -247,7 +246,7 @@ def test2(self): target = self.structured2 source = self.structured - #set some values on the grid + # set some values on the grid constant_field = numpy.zeros(source.nodes.shape, dtype=numpy.double) constant_field += 1.0 source.nodes.const = constant_field @@ -256,10 +255,10 @@ def test2(self): constant_field += 1.0 source.elements.const2 = constant_field - #create remapper + # create remapper remapper = grid_remappers.conservative_spherical_remapper(source, target) - #remap values + # remap values remapper.forward_mapping(["const", "const2"]) self.assertTrue(numpy.all(target.nodes.const >= 0.0), msg="Expecting all remapped values values to be larger than zero") @@ -269,7 +268,7 @@ def test3(self): target = self.unstructured source = self.structured - #set some values on the grid + # set some values on the grid constant_field = numpy.zeros(source.nodes.shape, dtype=numpy.double) constant_field += 1.0 source.nodes.const = constant_field @@ -278,45 +277,43 @@ def test3(self): constant_field += 1.0 source.elements.const2 = constant_field - #use a remapping channel + # use a remapping channel channel = source.new_remapping_channel_to(target, remapper=grid_remappers.conservative_spherical_remapper) - #remap values + # remap values channel.copy_attributes(["const", "const2"]) self.assertTrue(numpy.all(target.nodes.const >= 0.0), msg="Expecting all remapped values values to be larger than zero") self.assertTrue(numpy.all(target.elements.const2 >= 0.0), msg="Expecting all remapped values values to be larger than zero") - - class TestGridRemappingChannel(TestCase): def setUp(self): if not grid_remappers.matplotlib_available: self.skip("matplotlib not available") def test1(self): - source=new_cartesian_grid((10,20),1.) - target=new_cartesian_grid((5,10),2.,offset=[0.,0.5]) - - channel=source.new_remapping_channel_to(target,grid_remappers.interpolating_2D_remapper) - - source.xcopy=source.x - source.ycopy=source.y - - channel.copy_attributes(["xcopy","ycopy"]) - self.assertEqual(target.x,target.xcopy) - self.assertEqual(target.y,target.ycopy) + source = new_cartesian_grid((10, 20), 1.) + target = new_cartesian_grid((5, 10), 2., offset=[0., 0.5]) + + channel = source.new_remapping_channel_to(target, grid_remappers.interpolating_2D_remapper) + + source.xcopy = source.x + source.ycopy = source.y + + channel.copy_attributes(["xcopy", "ycopy"]) + self.assertEqual(target.x, target.xcopy) + self.assertEqual(target.y, target.ycopy) def test2(self): - source=new_cartesian_grid((10,20),1. | units.m) - target=new_cartesian_grid((5,10),2. | units.m ,offset=[0.,0.5] | units.m) - - channel=source.new_remapping_channel_to(target,grid_remappers.interpolating_2D_remapper) - - source.xcopy=source.x - source.ycopy=source.y - - channel.copy_attributes(["xcopy","ycopy"]) - self.assertEqual(target.x,target.xcopy) - self.assertEqual(target.y,target.ycopy) + source = new_cartesian_grid((10, 20), 1. | units.m) + target = new_cartesian_grid((5, 10), 2. | units.m, offset=[0., 0.5] | units.m) + + channel = source.new_remapping_channel_to(target, grid_remappers.interpolating_2D_remapper) + + source.xcopy = source.x + source.ycopy = source.y + + channel.copy_attributes(["xcopy", "ycopy"]) + self.assertEqual(target.x, target.xcopy) + self.assertEqual(target.y, target.ycopy) diff --git a/src/amuse/test/suite/ext_tests/test_grid_to_sph.py b/src/amuse/test/suite/ext_tests/test_grid_to_sph.py index 3c030f461c..16d71f75b5 100644 --- a/src/amuse/test/suite/ext_tests/test_grid_to_sph.py +++ b/src/amuse/test/suite/ext_tests/test_grid_to_sph.py @@ -20,42 +20,44 @@ from amuse.datamodel import ParticlesSuperset from amuse.datamodel import Grid + def create_grid(*arg): - grid=Grid.create(*arg) - grid.add_vector_attribute("momentum", ["rhovx","rhovy","rhovz"]) - return grid + grid = Grid.create(*arg) + grid.add_vector_attribute("momentum", ["rhovx", "rhovy", "rhovz"]) + return grid + class TestGrid2SPH(TestWithMPI): - + def setup_simple_grid(self): - test_grid = create_grid((4,3,2), [1.0, 1.0, 1.0] | units.m) + test_grid = create_grid((4, 3, 2), [1.0, 1.0, 1.0] | units.m) test_grid.rho = numpy.linspace(1.0, 2.0, num=24).reshape(test_grid.shape) | units.kg/units.m**3 test_grid.rhovx = test_grid.rho * (3.0 | units.m/units.s) test_grid.rhovy = test_grid.rho * (4.0 | units.m/units.s) test_grid.rhovz = test_grid.rho * (0.0 | units.m/units.s) test_grid.energy = test_grid.rho * ((1.0 | (units.m/units.s)**2) + 0.5 * (5.0 | units.m/units.s)**2) return test_grid - + def test0(self): print("Testing the simple example grid") test_grid = self.setup_simple_grid() - self.assertEqual(test_grid.position[ 0][ 0][ 0], [1.0/8.0, 1.0/6.0, 1.0/4.0] | units.m) + self.assertEqual(test_grid.position[0][0][0], [1.0/8.0, 1.0/6.0, 1.0/4.0] | units.m) self.assertEqual(test_grid.position[-1][-1][-1], [7.0/8.0, 5.0/6.0, 3.0/4.0] | units.m) - self.assertEqual(test_grid.momentum[ 0][ 0][ 0], [3.0, 4.0, 0.0] | (units.kg/units.m**3) * (units.m/units.s)) + self.assertEqual(test_grid.momentum[0][0][0], [3.0, 4.0, 0.0] | (units.kg/units.m**3) * (units.m/units.s)) self.assertEqual(test_grid.momentum[-1][-1][-1], [6.0, 8.0, 0.0] | (units.kg/units.m**3) * (units.m/units.s)) - self.assertEqual(test_grid.energy[ 0][ 0][ 0], 13.5 | (units.J/units.m**3)) + self.assertEqual(test_grid.energy[0][0][0], 13.5 | (units.J/units.m**3)) self.assertEqual(test_grid.energy[-1][-1][-1], 27.0 | (units.J/units.m**3)) - + def test1(self): print("Testing the converter") number_of_particles = 10000 test_grid = self.setup_simple_grid() converter = Grid2SPH(test_grid, number_of_particles) self.assertTrue(converter.grid is test_grid) - self.assertEqual(converter.shape, (4,3,2)) + self.assertEqual(converter.shape, (4, 3, 2)) self.assertEqual(converter.number_of_sph_particles, number_of_particles) self.assertEqual(converter.base_distribution_type, "uniform") - + converter.setup_lookup_tables() converter.setup_variates() self.assertEqual(converter.cumulative_weight[0], 1.0/(1.5*4*3*2)) @@ -71,11 +73,11 @@ def test1(self): self.assertAlmostEqual(converter.mass, 1.5 | units.kg) # The number of particles in a cell should scale with the amount of mass in the cell: self.assertAlmostRelativeEqual( - converter.mass * numpy.histogram(converter.indices, bins=4*3*2)[0] * 1.0/number_of_particles, - test_grid.rho.flatten()*test_grid.cellsize().prod(), - places = 2 + converter.mass * numpy.histogram(converter.indices, bins=4*3*2)[0] * 1.0/number_of_particles, + test_grid.rho.flatten()*test_grid.cellsize().prod(), + places=2 ) - + def test2(self): print("Testing the user interface") number_of_particles = 10000 @@ -88,47 +90,46 @@ def test2(self): # The number of particles in a cell should scale with the amount of mass in the cell: self.assertAlmostRelativeEqual( (1.5 | units.kg)/number_of_particles * numpy.histogramdd( - sph_particles.position.value_in(units.m), bins=(4,3,2))[0], - test_grid.rho*test_grid.cellsize().prod(), - places = 2 + sph_particles.position.value_in(units.m), bins=(4, 3, 2))[0], + test_grid.rho*test_grid.cellsize().prod(), + places=2 ) self.assertAlmostEqual(sph_particles.h_smooth, (50.0/number_of_particles)**(1.0/3) | units.m) - + def test3(self): print("Testing the user interface, random base_distribution_type") number_of_particles = 10000 test_grid = self.setup_simple_grid() - sph_particles = convert_grid_to_SPH(test_grid, number_of_particles, - base_distribution_type = "random", seed = 12345) + sph_particles = convert_grid_to_SPH(test_grid, number_of_particles, + base_distribution_type="random", seed=12345) self.assertEqual(len(sph_particles), number_of_particles) self.assertAlmostEqual(sph_particles.mass.sum(), 1.5 | units.kg) self.assertAlmostEqual(sph_particles.velocity, [3.0, 4.0, 0.0] | units.m/units.s) self.assertAlmostEqual(sph_particles.u, 1.0 | (units.m/units.s)**2) - # For 'random', the number of particles in a cell should scale only on average + # For 'random', the number of particles in a cell should scale only on average # with the amount of mass in the cell: self.assertAlmostRelativeEqual( ((1.5 | units.kg)/number_of_particles * numpy.histogramdd( - sph_particles.position.value_in(units.m), bins=(4,3,2))[0]).sum(), - (test_grid.rho*test_grid.cellsize().prod()).sum(), - places = 2 + sph_particles.position.value_in(units.m), bins=(4, 3, 2))[0]).sum(), + (test_grid.rho*test_grid.cellsize().prod()).sum(), + places=2 ) - self.assertRaises(AssertionError, + self.assertRaises(AssertionError, self.assertAlmostRelativeEqual, - (1.5 | units.kg)/number_of_particles * numpy.histogramdd(sph_particles.position.value_in(units.m), bins=(4,3,2))[0], - test_grid.rho*test_grid.cellsize().prod(), - places = 2, + (1.5 | units.kg)/number_of_particles * numpy.histogramdd(sph_particles.position.value_in(units.m), bins=(4, 3, 2))[0], + test_grid.rho*test_grid.cellsize().prod(), + places=2, ) self.assertAlmostEqual(sph_particles.h_smooth, (50.0/number_of_particles)**(1.0/3) | units.m) - + def test4(self): print("Testing exceptions") number_of_particles = 10000 test_grid = self.setup_simple_grid() self.assertEqual(test_grid[0].number_of_dimensions(), 2) self.assertRaises(AmuseException, convert_grid_to_SPH, test_grid[0], number_of_particles, - expected_message = "Grid must be 3D") - self.assertRaises(AmuseException, convert_grid_to_SPH, test_grid, - number_of_particles, base_distribution_type = "bogus", - expected_message = "Unknown base_distribution_type: bogus. Possible " + expected_message="Grid must be 3D") + self.assertRaises(AmuseException, convert_grid_to_SPH, test_grid, + number_of_particles, base_distribution_type="bogus", + expected_message="Unknown base_distribution_type: bogus. Possible " "options are: 'random' or 'uniform'.") - diff --git a/src/amuse/test/suite/ext_tests/test_halogen_model.py b/src/amuse/test/suite/ext_tests/test_halogen_model.py index d8b194e359..67e6c45779 100644 --- a/src/amuse/test/suite/ext_tests/test_halogen_model.py +++ b/src/amuse/test/suite/ext_tests/test_halogen_model.py @@ -4,40 +4,37 @@ from amuse.ext.halogen_model import new_halogen_model from amuse.units import nbody_system, units + class NewHalogenModelTests(TestWithMPI): - + def test1(self): number_of_particles = 100 - particles = new_halogen_model(number_of_particles, alpha = 2.0, beta = 5.0, gamma = 0.0, random_seed = 1.0) - + particles = new_halogen_model(number_of_particles, alpha=2.0, beta=5.0, gamma=0.0, random_seed=1.0) + self.assertEqual(len(particles), number_of_particles) self.assertAlmostEqual(particles.total_mass(), 1.0 | nbody_system.mass) - self.assertAlmostEqual(particles.kinetic_energy(), - 0.17345836639 | nbody_system.energy) # for number_of_particles = 100 - - self.assertRaises(AmuseException, new_halogen_model, number_of_particles, expected_message = - "Error when calling 'commit_parameters' of a 'Halogen', errorcode is -2, error is " + self.assertAlmostEqual(particles.kinetic_energy(), + 0.17345836639 | nbody_system.energy) # for number_of_particles = 100 + + self.assertRaises(AmuseException, new_halogen_model, number_of_particles, expected_message="Error when calling 'commit_parameters' of a 'Halogen', errorcode is -2, error is " "'Missing or bad parameter for halo (see amuse/community/halogen/src/doc for details on required parameters).'") - + def test2(self): number_of_particles = 1000 black_hole_mass = 1.0e6 | units.MSun stellar_mass = number_of_particles | units.MSun scale_radius = 0.1 | units.parsec - - + converter = nbody_system.nbody_to_si(black_hole_mass, scale_radius) - - particles = new_halogen_model(number_of_particles, convert_nbody=converter, - alpha=1.0, beta=3.0, gamma=1.0, # NFW + + particles = new_halogen_model(number_of_particles, convert_nbody=converter, + alpha=1.0, beta=3.0, gamma=1.0, # NFW random_seed=1.0, redirection='none', black_hole_mass=black_hole_mass, total_mass=stellar_mass, cutoff_radius=10.0*scale_radius, scale_radius=scale_radius) - + self.assertEqual(len(particles), number_of_particles + 1) self.assertAlmostEqual(particles[-1].mass, black_hole_mass) self.assertAlmostEqual(particles.total_mass(), black_hole_mass + stellar_mass) - self.assertAlmostRelativeEquals(particles.kinetic_energy(), + self.assertAlmostRelativeEquals(particles.kinetic_energy(), 2.27538127277e+43 | units.J, 10) - - diff --git a/src/amuse/test/suite/ext_tests/test_hydro_collision.py b/src/amuse/test/suite/ext_tests/test_hydro_collision.py index 2be1805934..6c583cb5f0 100644 --- a/src/amuse/test/suite/ext_tests/test_hydro_collision.py +++ b/src/amuse/test/suite/ext_tests/test_hydro_collision.py @@ -15,8 +15,9 @@ from amuse.ext.plotting_hydro import new_plotting_hydrodynamics_code from amuse.ext.hydro_collision import StellarEncounterInHydrodynamics + class TestStellarEncounterInHydrodynamics(TestWithMPI): - + def new_colliders(self): colliders = Particles(2) colliders.mass = [5, 2] | units.MSun @@ -24,82 +25,82 @@ def new_colliders(self): colliders.velocity = [[0.0, 0.0, 0.0], [0.0, 2000.0, 0.0]] | units.km / units.s colliders.move_to_center() return colliders - + def test1(self): print("Test collect_required_attributes") in_memory = self.new_colliders() - gravity = BHTree(nbody_system.nbody_to_si(1|units.MSun, 1.0|units.RSun)) + gravity = BHTree(nbody_system.nbody_to_si(1 | units.MSun, 1.0 | units.RSun)) gravity.particles.add_particles(in_memory) stellar = SeBa() stellar.particles.add_particles(in_memory) - + collision = StellarEncounterInHydrodynamics(None, None, verbose=True) - + self.assertFalse(hasattr(in_memory, "radius")) collision.collect_required_attributes(in_memory, gravity, stellar) self.assertTrue(hasattr(in_memory, "radius")) self.assertAlmostRelativeEqual(in_memory.radius.sum(), 4.2458 | units.RSun, 3) - + from_stellar = stellar.particles.copy() for attribute in ["x", "y", "z", "vx", "vy", "vz"]: self.assertFalse(hasattr(from_stellar, attribute)) collision.collect_required_attributes(from_stellar, gravity, stellar) - + gravity.stop() stellar.stop() - + for attribute in ["x", "y", "z", "vx", "vy", "vz"]: self.assertTrue(hasattr(from_stellar, attribute)) self.assertAlmostEqual(from_stellar.position, in_memory.position) self.assertAlmostEqual(from_stellar.velocity, in_memory.velocity) - + def test2(self): print("Test backtrack_particles") colliders = self.new_colliders() colliders.radius = [1, 2] | units.RSun - + collision = StellarEncounterInHydrodynamics(None, None, verbose=True) - + relative_position = colliders[1].position - colliders[0].position self.assertAlmostRelativeEqual(relative_position.length(), 1.0 | units.RSun, 7) - + total_energy_before = colliders.kinetic_energy() + colliders.potential_energy() self.assertTrue(total_energy_before > zero) - + collision.backtrack_particles(colliders) collision.kepler.stop() - + relative_position = colliders[1].position - colliders[0].position self.assertAlmostRelativeEqual(relative_position.length(), 15 | units.RSun, 3) - + total_energy_after = colliders.kinetic_energy() + colliders.potential_energy() self.assertAlmostRelativeEqual(total_energy_after, total_energy_before, 7) - + def test3(self): print("Test convert_stars") colliders = self.new_colliders() colliders.position = [[-100.0, 0.0, 0.0], [100.0, 0.0, 0.0]] | units.RSun stellar = EVtwin() stellar.particles.add_particles(colliders) - + collision = StellarEncounterInHydrodynamics(700, None, relax_sph_models=False, verbose=True) gas_particles = collision.convert_stars(colliders, stellar) stellar.stop() - + self.assertEqual(gas_particles.mass, 0.01 | units.MSun) self.assertTrue(numpy.all(gas_particles[:500].x < zero)) self.assertTrue(numpy.all(gas_particles[500:].x > zero)) - + self.assertIsOfOrder(( gas_particles[:500].position - ([-100.0, 0.0, 0.0] | units.RSun) ).lengths_squared().amax().sqrt(), 1 | units.RSun) self.assertIsOfOrder(( gas_particles[500:].position - ([100.0, 0.0, 0.0] | units.RSun) ).lengths_squared().amax().sqrt(), 1 | units.RSun) - - self.assertAlmostEqual(gas_particles[500:].center_of_mass_velocity().y - + + self.assertAlmostEqual(gas_particles[500:].center_of_mass_velocity().y - gas_particles[:500].center_of_mass_velocity().y, 2000.0 | units.km / units.s) - + def test4(self): print("Test binary_will_collide") collision = StellarEncounterInHydrodynamics(None, None, verbose=True) @@ -122,7 +123,7 @@ def test4(self): colliders.velocity = [[0.0, 0.0, 0.0], [0.0, -1000.0, 0.0]] | units.km / units.s self.assertTrue(collision.binary_will_collide(colliders[0], colliders[1])) collision.kepler.stop() - + def test5(self): print("Test group_bound_particles") colliders = self.new_colliders() @@ -130,19 +131,19 @@ def test5(self): colliders.velocity = [[0.0, 0.0, 0.0], [10000, 0.0, 0.0]] | units.km / units.s stellar = EVtwin() stellar.particles.add_particles(colliders) - - collision = StellarEncounterInHydrodynamics(7000, None, relax_sph_models=False, verbose=True, + + collision = StellarEncounterInHydrodynamics(7000, None, relax_sph_models=False, verbose=True, star_to_sph_arguments=dict(base_grid_options=dict(type="sobol"))) collision.dynamical_timescale = zero gas_particles = collision.convert_stars(colliders, stellar) stellar.stop() - + collision.hop = collision.new_hop(gas_particles) collision.start_kepler(7 | units.MSun, 10 | units.RSun) self.assertTrue(collision.encounter_is_over(gas_particles)) collision.hop.stop() collision.kepler.stop() - + groups = collision.groups_after_encounter self.assertEqual(len(groups), 2) self.assertTrue(4500 < len(groups[0]) < 5000) @@ -151,30 +152,30 @@ def test5(self): self.assertAlmostEqual(groups[0].center_of_mass()[0], 0 | units.RSun, 1) self.assertAlmostEqual(groups[1].center_of_mass()[0], 1.1 | units.RSun, 0) self.assertIsOfOrder(groups[1].center_of_mass_velocity()[0], 10000 | units.km / units.s) - + def test6(self): print("Test handle_collision") position_offset = [100.0, 200.0, 300.0] | units.RSun velocity_offset = [10000.0, 20000.0, 30000.0] | units.km / units.s colliders = self.new_colliders() - colliders.position *= 1.5 # Grazing collision + colliders.position *= 1.5 # Grazing collision colliders.position += position_offset colliders.velocity += velocity_offset - + class GravityCodeStub(object): def __init__(self, particles): self.particles = particles gravity = GravityCodeStub(colliders) - + stellar = EVtwin() stellar.particles.add_particles(colliders) - + collision = StellarEncounterInHydrodynamics(280, # For speed Gadget2, relax_sph_models=False, # For speed verbose=True) - collision.extra_steps_when_encounter_is_over = 0 # For speed, no extra steps... - collision.dynamical_timescales_per_step = 1.3 # ... but then we need to evolve a bit longer in the first step + collision.extra_steps_when_encounter_is_over = 0 # For speed, no extra steps... + collision.dynamical_timescales_per_step = 1.3 # ... but then we need to evolve a bit longer in the first step result = collision.handle_collision(colliders[0], colliders[1], gravity_code=gravity, stellar_evolution_code=stellar) stellar.stop() print(result) @@ -183,7 +184,7 @@ def __init__(self, particles): self.assertAlmostEqual(result.mass, [5.0, 2.0] | units.MSun, 1) self.assertAlmostRelativeEqual(result.center_of_mass(), position_offset, 2) self.assertAlmostRelativeEqual(result.center_of_mass_velocity(), velocity_offset, 2) - + def slowtest7(self): print("Test handle_collision") position_offset = [100.0, 200.0, 300.0] | units.RSun @@ -191,23 +192,23 @@ def slowtest7(self): colliders = self.new_colliders() colliders.position += position_offset colliders.velocity += velocity_offset - + class GravityCodeStub(object): def __init__(self, particles): self.particles = particles gravity = GravityCodeStub(colliders) - + stellar = EVtwin() stellar.particles.add_particles(colliders) - + collision = StellarEncounterInHydrodynamics( - #28000, # Bit too slow, even for a slowtest... - 2800, - new_plotting_hydrodynamics_code(Gadget2, 0.2|units.hour, - plot_function = pynbody_column_density_plot if HAS_PYNBODY else None, - plot_function_arguments = dict(width=20|units.RSun, vmin=29, vmax=35) if HAS_PYNBODY else dict(width=20|units.RSun)), - hydrodynamics_arguments = dict(redirection="file", redirect_file="hydro_collision_slowtest7_gadget_out.log"), - hydrodynamics_parameters = dict(time_limit_cpu=1|units.day, gas_epsilon=0.01|units.RSun), + # 28000, # Bit too slow, even for a slowtest... + 2800, + new_plotting_hydrodynamics_code(Gadget2, 0.2 | units.hour, + plot_function=pynbody_column_density_plot if HAS_PYNBODY else None, + plot_function_arguments=dict(width=20 | units.RSun, vmin=29, vmax=35) if HAS_PYNBODY else dict(width=20 | units.RSun)), + hydrodynamics_arguments=dict(redirection="file", redirect_file="hydro_collision_slowtest7_gadget_out.log"), + hydrodynamics_parameters=dict(time_limit_cpu=1 | units.day, gas_epsilon=0.01 | units.RSun), verbose=True, debug=False ) @@ -219,5 +220,3 @@ def __init__(self, particles): self.assertTrue((result.mass < [5.0, 2.0] | units.MSun).all()) self.assertAlmostRelativeEqual(result.center_of_mass(), position_offset, 2) self.assertAlmostRelativeEqual(result.center_of_mass_velocity(), velocity_offset, 2) - - diff --git a/src/amuse/test/suite/ext_tests/test_isotropic_cloud.py b/src/amuse/test/suite/ext_tests/test_isotropic_cloud.py index c4fb42c52a..9033b56b65 100644 --- a/src/amuse/test/suite/ext_tests/test_isotropic_cloud.py +++ b/src/amuse/test/suite/ext_tests/test_isotropic_cloud.py @@ -4,32 +4,33 @@ from amuse.ext.orbital_elements import orbital_elements_from_binary from amuse.datamodel import Particles + class TestSphericalIsotropicCloud(amusetest.TestCase): - - def test1(self): - cloud = new_isotropic_cloud(2, m_cloud=0.|units.MSun) - self.assertEqual(len(cloud),2) - self.assertEqual(cloud.mass.sum(), 0.|units.MSun) - - def test2(self): - m_star = 0.666|units.MSun - a_min=666.|units.AU - a_max=6666.|units.AU - q_min=6.|units.AU - cloud = new_isotropic_cloud(66, - m_star=m_star, - a_min=a_min, - a_max=a_max, - q_min=q_min) - binary = Particles(1) - binary[0].mass = m_star - binary[0].position = (0.,0.,0.) | units.AU - binary[0].velocity = (0.,0.,0.) | units.kms - for comet in cloud: - binary.add_particle(comet) - mass1, mass2, semimajor_axis, eccentricity, true_anomaly, inclination, long_asc_node, arg_per = \ - orbital_elements_from_binary(binary, G=constants.G) - print(mass1, mass2, semimajor_axis, eccentricity, true_anomaly, inclination, long_asc_node, arg_per) - self.assertTrue( a_min < semimajor_axis < a_max ) - self.assertTrue( q_min < semimajor_axis*(1.-eccentricity) ) - binary.remove_particle(comet) + + def test1(self): + cloud = new_isotropic_cloud(2, m_cloud=0. | units.MSun) + self.assertEqual(len(cloud), 2) + self.assertEqual(cloud.mass.sum(), 0. | units.MSun) + + def test2(self): + m_star = 0.666 | units.MSun + a_min = 666. | units.AU + a_max = 6666. | units.AU + q_min = 6. | units.AU + cloud = new_isotropic_cloud(66, + m_star=m_star, + a_min=a_min, + a_max=a_max, + q_min=q_min) + binary = Particles(1) + binary[0].mass = m_star + binary[0].position = (0., 0., 0.) | units.AU + binary[0].velocity = (0., 0., 0.) | units.kms + for comet in cloud: + binary.add_particle(comet) + mass1, mass2, semimajor_axis, eccentricity, true_anomaly, inclination, long_asc_node, arg_per = \ + orbital_elements_from_binary(binary, G=constants.G) + print(mass1, mass2, semimajor_axis, eccentricity, true_anomaly, inclination, long_asc_node, arg_per) + self.assertTrue(a_min < semimajor_axis < a_max) + self.assertTrue(q_min < semimajor_axis*(1.-eccentricity)) + binary.remove_particle(comet) diff --git a/src/amuse/test/suite/ext_tests/test_jobserver.py b/src/amuse/test/suite/ext_tests/test_jobserver.py index 6c77f0d5c5..1c5f4dae53 100644 --- a/src/amuse/test/suite/ext_tests/test_jobserver.py +++ b/src/amuse/test/suite/ext_tests/test_jobserver.py @@ -1,41 +1,44 @@ from amuse.test import amusetest -from amuse.ext.job_server import RemoteCodeInterface,JobServer +from amuse.ext.job_server import RemoteCodeInterface, JobServer from socket import gethostname import os from amuse.ic.plummer import new_plummer_model -def example_parallel_jobs(N,Nhosts=1): - - jobserver=JobServer(hosts=[gethostname()]*Nhosts) - - for i in range(1,N+1): - jobserver.submit_job(new_plummer_model, (i,)) - - result=dict() - while jobserver.wait(): - job=jobserver.last_finished_job - result[job.args[0]]=job.result - - return result - -def example_parallel_jobs2(N,Nhosts=1): - - jobserver=JobServer(hosts=[gethostname()]*Nhosts) - - for i in range(1,N+1): - jobserver.submit_job(new_plummer_model, (i,)) - - jobserver.waitall() - - result=dict() - - for job in jobserver.finished_jobs: - result[job.args[0]]=job.result - - return result + +def example_parallel_jobs(N, Nhosts=1): + + jobserver = JobServer(hosts=[gethostname()]*Nhosts) + + for i in range(1, N+1): + jobserver.submit_job(new_plummer_model, (i,)) + + result = dict() + while jobserver.wait(): + job = jobserver.last_finished_job + result[job.args[0]] = job.result + + return result + + +def example_parallel_jobs2(N, Nhosts=1): + + jobserver = JobServer(hosts=[gethostname()]*Nhosts) + + for i in range(1, N+1): + jobserver.submit_job(new_plummer_model, (i,)) + + jobserver.waitall() + + result = dict() + + for job in jobserver.finished_jobs: + result[job.args[0]] = job.result + + return result + class TestRemoteCode(amusetest.TestCase): @@ -43,70 +46,69 @@ def check_not_in_mpiexec(self): """ The tests will fork another process, if the test run is itself an mpi process, the tests may fail. - + For the hydra process manager the tests will fail. So skip the tests if we detect hydra """ - + if 'HYDRA_CONTROL_FD' in os.environ or 'PMI_FD' in os.environ: self.skip('cannot run the socket tests under mpi process manager') - def test1(self): - remote=RemoteCodeInterface() - - var=123 - remote.assign("var",var) - var_=remote.evaluate("var+1") - self.assertEqual(var_,var+1) - remote.execute("var=var*2") - var_=remote.evaluate("var") - self.assertEqual(var_,var*2) - + remote = RemoteCodeInterface() + + var = 123 + remote.assign("var", var) + var_ = remote.evaluate("var+1") + self.assertEqual(var_, var+1) + remote.execute("var=var*2") + var_ = remote.evaluate("var") + self.assertEqual(var_, var*2) + def test2(self): - remote=RemoteCodeInterface() - - from math import sqrt - result=remote.func(sqrt, 64) - self.assertEqual(result,8) + remote = RemoteCodeInterface() + + from math import sqrt + result = remote.func(sqrt, 64) + self.assertEqual(result, 8) def test3(self): - remote=RemoteCodeInterface() - - var=new_plummer_model(100) - remote.assign("var",var) - var_=remote.evaluate("var.mass") - self.assertEqual(var_,var.mass) + remote = RemoteCodeInterface() + + var = new_plummer_model(100) + remote.assign("var", var) + var_ = remote.evaluate("var.mass") + self.assertEqual(var_, var.mass) def test4(self): - self.check_not_in_mpiexec() - remote=RemoteCodeInterface(channel_type="sockets") - - var=123 - remote.assign("var",var) - var_=remote.evaluate("var+1") - self.assertEqual(var_,var+1) - remote.execute("var=var*2") - var_=remote.evaluate("var") - self.assertEqual(var_,var*2) + self.check_not_in_mpiexec() + remote = RemoteCodeInterface(channel_type="sockets") + + var = 123 + remote.assign("var", var) + var_ = remote.evaluate("var+1") + self.assertEqual(var_, var+1) + remote.execute("var=var*2") + var_ = remote.evaluate("var") + self.assertEqual(var_, var*2) class TestJobServer(amusetest.TestCase): def test1(self): - - result=example_parallel_jobs(10) - for arg,res in result.items(): - self.assertEqual(arg,len(res)) + + result = example_parallel_jobs(10) + for arg, res in result.items(): + self.assertEqual(arg, len(res)) def test2(self): - - result=example_parallel_jobs(10,4) - for arg,res in result.items(): - self.assertEqual(arg,len(res)) + + result = example_parallel_jobs(10, 4) + for arg, res in result.items(): + self.assertEqual(arg, len(res)) def test3(self): - - result=example_parallel_jobs2(10,4) - for arg,res in result.items(): - self.assertEqual(arg,len(res)) + + result = example_parallel_jobs2(10, 4) + for arg, res in result.items(): + self.assertEqual(arg, len(res)) diff --git a/src/amuse/test/suite/ext_tests/test_kingmodel.py b/src/amuse/test/suite/ext_tests/test_kingmodel.py index 169829d499..51831d53e3 100644 --- a/src/amuse/test/suite/ext_tests/test_kingmodel.py +++ b/src/amuse/test/suite/ext_tests/test_kingmodel.py @@ -6,41 +6,42 @@ from amuse.units import units from amuse.ic.kingmodel import new_king_model + class TestKingModel(amusetest.TestCase): def test1(self): print("First test: making a King model.") number_of_particles = 10 particles = new_king_model(number_of_particles, 6.0) self.assertAlmostEqual(particles.mass.sum(), 1 | nbody_system.mass) - self.assertAlmostEqual(particles[0].mass , 0.1 | nbody_system.mass) + self.assertAlmostEqual(particles[0].mass, 0.1 | nbody_system.mass) print(particles) self.assertFalse(particles[0].mass.is_vector()) - + def test2(self): print("Testing kinetic and potential energy of a King model realisation.") convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) number_of_particles = 500 - particles = new_king_model(number_of_particles, 6.0, convert_nbody, do_scale = True) + particles = new_king_model(number_of_particles, 6.0, convert_nbody, do_scale=True) self.assertEqual(len(particles), number_of_particles) - self.assertAlmostEqual(particles[0].mass, (1.0|units.MSun)/number_of_particles, 3, in_units=units.MSun) + self.assertAlmostEqual(particles[0].mass, (1.0 | units.MSun)/number_of_particles, 3, in_units=units.MSun) self.assertAlmostEqual(convert_nbody.to_nbody(particles.kinetic_energy()), 0.25 | nbody_system.energy) self.assertAlmostEqual(convert_nbody.to_nbody(particles.potential_energy()), -0.5 | nbody_system.energy) - + def slowtest3(self): print("King models with varying King dimensionless depth W0.") number_of_particles = 10 for w_0 in [1.0, 6.0, 11.0, 16.0]: - particles = new_king_model(number_of_particles, W0 = w_0) + particles = new_king_model(number_of_particles, W0=w_0) self.assertEqual(len(particles), number_of_particles) - + def test4(self): print("Testing maximal/minimal value of King dimensionless depth W0.") number_of_particles = 10 - self.assertRaises(AmuseException, new_king_model, number_of_particles, W0 = 16.5, - expected_message = "makeking: must specify w0 < 16") - - self.assertRaises(ZeroDivisionError, new_king_model, number_of_particles, W0 = 0.0) - + self.assertRaises(AmuseException, new_king_model, number_of_particles, W0=16.5, + expected_message="makeking: must specify w0 < 16") + + self.assertRaises(ZeroDivisionError, new_king_model, number_of_particles, W0=0.0) + def test5(self): print("Testing a specific King model realisation.") numpy.random.seed(345672) @@ -49,8 +50,7 @@ def test5(self): self.assertEqual(len(particles), 500) self.assertAlmostEqual(particles.total_mass(), 1.0 | units.MSun) self.assertAlmostEqual(particles.mass, 1.0 / 500 | units.MSun) - self.assertAlmostEqual(particles.center_of_mass(), [0,0,0] | units.AU) - self.assertAlmostEqual(particles.center_of_mass_velocity(), [0,0,0] | units.km / units.s) - self.assertAlmostEqual(particles[:3].position, [[-0.23147381,-0.19421449,-0.01165137], - [-0.09283025,-0.06444658,-0.07922396], [-0.44189946,0.23786357,0.39115629]] | units.AU) - + self.assertAlmostEqual(particles.center_of_mass(), [0, 0, 0] | units.AU) + self.assertAlmostEqual(particles.center_of_mass_velocity(), [0, 0, 0] | units.km / units.s) + self.assertAlmostEqual(particles[:3].position, [[-0.23147381, -0.19421449, -0.01165137], + [-0.09283025, -0.06444658, -0.07922396], [-0.44189946, 0.23786357, 0.39115629]] | units.AU) diff --git a/src/amuse/test/suite/ext_tests/test_limepy.py b/src/amuse/test/suite/ext_tests/test_limepy.py index 09033bc05a..0841341482 100644 --- a/src/amuse/test/suite/ext_tests/test_limepy.py +++ b/src/amuse/test/suite/ext_tests/test_limepy.py @@ -5,26 +5,27 @@ from amuse.units import units from amuse.ic import limepy + class TestLimepy(amusetest.TestCase): def test1(self): - cluster=limepy.Limepy(5, 1, N=100).result + cluster = limepy.Limepy(5, 1, N=100).result - self.assertAlmostEqual(cluster.total_mass().number, 1.0) - self.assertEqual(len(cluster),100) + self.assertAlmostEqual(cluster.total_mass().number, 1.0) + self.assertEqual(len(cluster), 100) def test2(self): - cluster = limepy.new_limepy_model(7, 2, N=10000) + cluster = limepy.new_limepy_model(7, 2, N=10000) - self.assertAlmostEqual(cluster.total_mass().number, 1.0) - self.assertEqual(len(cluster),10000) + self.assertAlmostEqual(cluster.total_mass().number, 1.0) + self.assertEqual(len(cluster), 10000) def test3(self): - c = nbody_system.nbody_to_si(200 | units.MSun, 2 | units.parsec) - cluster = limepy.new_limepy_model(7, 2, N=100, converter=c) + c = nbody_system.nbody_to_si(200 | units.MSun, 2 | units.parsec) + cluster = limepy.new_limepy_model(7, 2, N=100, converter=c) - self.assertAlmostEqual(cluster.total_mass(), 200. | units.MSun) - self.assertEqual(len(cluster),100) + self.assertAlmostEqual(cluster.total_mass(), 200. | units.MSun) + self.assertEqual(len(cluster), 100) def setUp(self): - if not limepy.scipy_imported: + if not limepy.scipy_imported: self.skip("scipy not installed") diff --git a/src/amuse/test/suite/ext_tests/test_mameclot.py b/src/amuse/test/suite/ext_tests/test_mameclot.py index 6ad1099127..469ef92d98 100644 --- a/src/amuse/test/suite/ext_tests/test_mameclot.py +++ b/src/amuse/test/suite/ext_tests/test_mameclot.py @@ -5,24 +5,24 @@ from amuse.units import units from amuse.ic.mameclot import mameclot + class TestPlummer(amusetest.TestCase): def test1(self): - cluster=mameclot().result - - self.assertAlmostEqual(cluster.total_mass().number, 1.0) - self.assertEqual(len(cluster),10000) - + cluster = mameclot().result + + self.assertAlmostEqual(cluster.total_mass().number, 1.0) + self.assertEqual(len(cluster), 10000) + def test2(self): - clusters,c1,c2=mameclot().result_split - - self.assertAlmostEqual((c1.total_mass()+c2.total_mass()).number, 1.0) - self.assertEqual(len(c1),10000) - self.assertEqual(len(c2),0) + clusters, c1, c2 = mameclot().result_split + + self.assertAlmostEqual((c1.total_mass()+c2.total_mass()).number, 1.0) + self.assertEqual(len(c1), 10000) + self.assertEqual(len(c2), 0) def test3(self): - clusters,c1,c2=mameclot(mass_ratio=0.25).result_split - - self.assertAlmostEqual((c1.total_mass()+c2.total_mass()).number, 1.0) - self.assertEqual(len(c1),8000) - self.assertEqual(len(c2),2000) + clusters, c1, c2 = mameclot(mass_ratio=0.25).result_split + self.assertAlmostEqual((c1.total_mass()+c2.total_mass()).number, 1.0) + self.assertEqual(len(c1), 8000) + self.assertEqual(len(c2), 2000) diff --git a/src/amuse/test/suite/ext_tests/test_molecular_cloud.py b/src/amuse/test/suite/ext_tests/test_molecular_cloud.py index 3e8bdab62d..2e14402ea6 100644 --- a/src/amuse/test/suite/ext_tests/test_molecular_cloud.py +++ b/src/amuse/test/suite/ext_tests/test_molecular_cloud.py @@ -9,30 +9,31 @@ numpy.random.seed(1234567) + class MolecularCloudTests(amusetest.TestCase): def test1(self): - mc=molecular_cloud(targetN=1000,base_grid=sobol_unit_cube).result - self.assertEqual(len(mc),995) - ek=mc.kinetic_energy() - ep=mc.potential_energy(G=nbody_system.G) - eth=mc.thermal_energy() - self.assertAlmostRelativeEqual(eth/ep, -0.01,2) - self.assertAlmostRelativeEqual(ek/ep, -1.,2) + mc = molecular_cloud(targetN=1000, base_grid=sobol_unit_cube).result + self.assertEqual(len(mc), 995) + ek = mc.kinetic_energy() + ep = mc.potential_energy(G=nbody_system.G) + eth = mc.thermal_energy() + self.assertAlmostRelativeEqual(eth/ep, -0.01, 2) + self.assertAlmostRelativeEqual(ek/ep, -1., 2) def test2(self): - mc=molecular_cloud(targetN=1000,ethep_ratio=0.05,base_grid=sobol_unit_cube).result - self.assertEqual(len(mc),995) - ek=mc.kinetic_energy() - ep=mc.potential_energy(G=nbody_system.G) - eth=mc.thermal_energy() - self.assertAlmostRelativeEqual(eth/ep, -0.05,2) - self.assertAlmostRelativeEqual(ek/ep, -1.,2) + mc = molecular_cloud(targetN=1000, ethep_ratio=0.05, base_grid=sobol_unit_cube).result + self.assertEqual(len(mc), 995) + ek = mc.kinetic_energy() + ep = mc.potential_energy(G=nbody_system.G) + eth = mc.thermal_energy() + self.assertAlmostRelativeEqual(eth/ep, -0.05, 2) + self.assertAlmostRelativeEqual(ek/ep, -1., 2) def test3(self): - mc=molecular_cloud(targetN=1000,ekep_ratio=2.,base_grid=sobol_unit_cube).result - self.assertEqual(len(mc),995) - ek=mc.kinetic_energy() - ep=mc.potential_energy(G=nbody_system.G) - eth=mc.thermal_energy() - self.assertAlmostRelativeEqual(eth/ep, -0.01,2) - self.assertAlmostRelativeEqual(ek/ep, -2.,2) + mc = molecular_cloud(targetN=1000, ekep_ratio=2., base_grid=sobol_unit_cube).result + self.assertEqual(len(mc), 995) + ek = mc.kinetic_energy() + ep = mc.potential_energy(G=nbody_system.G) + eth = mc.thermal_energy() + self.assertAlmostRelativeEqual(eth/ep, -0.01, 2) + self.assertAlmostRelativeEqual(ek/ep, -2., 2) diff --git a/src/amuse/test/suite/ext_tests/test_orbital_elements.py b/src/amuse/test/suite/ext_tests/test_orbital_elements.py index 731217576c..966328f822 100644 --- a/src/amuse/test/suite/ext_tests/test_orbital_elements.py +++ b/src/amuse/test/suite/ext_tests/test_orbital_elements.py @@ -95,68 +95,67 @@ def test2(self): binary.velocity -= binary[0].velocity self.assertAlmostRelativeEquals( - binary[0].position, [0,0,0] | nbody_system.length) + binary[0].position, [0, 0, 0] | nbody_system.length) self.assertAlmostRelativeEquals( - binary[1].position, [-1,0,0] | nbody_system.length) + binary[1].position, [-1, 0, 0] | nbody_system.length) self.assertAlmostRelativeEquals( - binary[0].velocity, [0,0,0] | nbody_system.speed) + binary[0].velocity, [0, 0, 0] | nbody_system.speed) self.assertAlmostRelativeEquals( - binary[1].velocity, [0,-numpy.sqrt(2),0] | nbody_system.speed) - + binary[1].velocity, [0, -numpy.sqrt(2), 0] | nbody_system.speed) + binary = new_binary_from_orbital_elements( mass1, mass2, 1 | nbody_system.length, - eccentricity = 0, - true_anomaly = 270, + eccentricity=0, + true_anomaly=270, ) - + self.assertEqual(len(binary), 2) - binary.position-=binary[0].position - binary.velocity-=binary[0].velocity + binary.position -= binary[0].position + binary.velocity -= binary[0].velocity + + self.assertAlmostRelativeEquals(binary[0].position, [0, 0, 0] | nbody_system.length) + self.assertAlmostRelativeEquals(binary[1].position, [0, -1, 0] | nbody_system.length) + self.assertAlmostRelativeEquals(binary[0].velocity, [0, 0, 0] | nbody_system.speed) + self.assertAlmostRelativeEquals(binary[1].velocity, [numpy.sqrt(2), 0, 0] | nbody_system.speed) - self.assertAlmostRelativeEquals(binary[0].position, [0,0,0] | nbody_system.length) - self.assertAlmostRelativeEquals(binary[1].position, [0,-1,0] | nbody_system.length) - self.assertAlmostRelativeEquals(binary[0].velocity, [0,0,0] | nbody_system.speed) - self.assertAlmostRelativeEquals(binary[1].velocity, [numpy.sqrt(2),0,0] | nbody_system.speed) - binary = new_binary_from_orbital_elements( mass1, mass2, 1 | nbody_system.length, - eccentricity = 0, - true_anomaly = 45, + eccentricity=0, + true_anomaly=45, ) - - self.assertEqual(len(binary), 2) - binary.position-=binary[0].position - binary.velocity-=binary[0].velocity + self.assertEqual(len(binary), 2) - self.assertAlmostRelativeEquals(binary[0].position, [0,0,0] | nbody_system.length) - self.assertAlmostRelativeEquals(binary[1].position, [0.5 * numpy.sqrt(2),0.5 * numpy.sqrt(2),0] | nbody_system.length) - self.assertAlmostRelativeEquals(binary[0].velocity, [0,0,0] | nbody_system.speed) - self.assertAlmostRelativeEquals(binary[1].velocity, [-1,1,0] | nbody_system.speed) + binary.position -= binary[0].position + binary.velocity -= binary[0].velocity + self.assertAlmostRelativeEquals(binary[0].position, [0, 0, 0] | nbody_system.length) + self.assertAlmostRelativeEquals(binary[1].position, [0.5 * numpy.sqrt(2), 0.5 * numpy.sqrt(2), 0] | nbody_system.length) + self.assertAlmostRelativeEquals(binary[0].velocity, [0, 0, 0] | nbody_system.speed) + self.assertAlmostRelativeEquals(binary[1].velocity, [-1, 1, 0] | nbody_system.speed) def test3(self): - mass1 = 1. | nbody_system.mass + mass1 = 1. | nbody_system.mass mass2 = 1. | nbody_system.mass - + binary = new_binary_from_orbital_elements( mass1, mass2, 1. | nbody_system.length, - eccentricity = 0. + eccentricity=0. ) - + self.assertEqual(len(binary), 2) - self.assertAlmostRelativeEquals(binary[0].position, [-0.5,0,0] | nbody_system.length) - self.assertAlmostRelativeEquals(binary[1].position, [0.5,0,0] | nbody_system.length) - self.assertAlmostRelativeEquals(binary[0].velocity, [0,-1/numpy.sqrt(2),0] | nbody_system.speed) - self.assertAlmostRelativeEquals(binary[1].velocity, [0,1/numpy.sqrt(2),0] | nbody_system.speed) - + self.assertAlmostRelativeEquals(binary[0].position, [-0.5, 0, 0] | nbody_system.length) + self.assertAlmostRelativeEquals(binary[1].position, [0.5, 0, 0] | nbody_system.length) + self.assertAlmostRelativeEquals(binary[0].velocity, [0, -1/numpy.sqrt(2), 0] | nbody_system.speed) + self.assertAlmostRelativeEquals(binary[1].velocity, [0, 1/numpy.sqrt(2), 0] | nbody_system.speed) + def test4(self): numpy.random.seed(3456789) N = 100 @@ -204,7 +203,7 @@ def test5(self): G=constants.G) for i, (copy, org) in enumerate(zip(arg_, arg)): self.assertAlmostEqual(copy, org) - + def test6(self): """ testing orbital_elements_for_rel_posvel_arrays for N particles @@ -212,45 +211,45 @@ def test6(self): """ numpy.random.seed(666) N = 100 - + mass_sun = 1. | units.MSun mass1 = numpy.ones(N) * mass_sun mass2 = numpy.zeros(N) | units.MSun - semi_major_axis=(-numpy.log(random.random(N))) | units.AU + semi_major_axis = (-numpy.log(random.random(N))) | units.AU eccentricity = random.random(N) true_anomaly = 360.*random.random(N)-180. inclination = 180*random.random(N) longitude_of_the_ascending_node = 360*random.random(N)-180 - argument_of_periapsis = 360*random.random(N)-180 - + argument_of_periapsis = 360*random.random(N)-180 + comets = datamodel.Particles(N) - for i,arg in enumerate(zip(mass1,mass2,semi_major_axis,eccentricity,true_anomaly,inclination, - longitude_of_the_ascending_node,argument_of_periapsis)): - sun_and_comet = new_binary_from_orbital_elements(*arg,G=constants.G) + for i, arg in enumerate(zip(mass1, mass2, semi_major_axis, eccentricity, true_anomaly, inclination, + longitude_of_the_ascending_node, argument_of_periapsis)): + sun_and_comet = new_binary_from_orbital_elements(*arg, G=constants.G) comets[i].mass = sun_and_comet[1].mass comets[i].position = sun_and_comet[1].position comets[i].velocity = sun_and_comet[1].velocity - + semi_major_axis_ext, eccentricity_ext, ta_ext, inclination_ext, \ longitude_of_the_ascending_node_ext, argument_of_periapsis_ext = \ orbital_elements_for_rel_posvel_arrays(comets.position, comets.velocity, comets.mass + mass_sun, - G=constants.G) + G=constants.G) - self.assertAlmostEqual(semi_major_axis,semi_major_axis_ext) - self.assertAlmostEqual(eccentricity,eccentricity_ext) - self.assertAlmostEqual(inclination ,inclination_ext) - self.assertAlmostEqual(longitude_of_the_ascending_node ,longitude_of_the_ascending_node_ext) - self.assertAlmostEqual(argument_of_periapsis ,argument_of_periapsis_ext) - self.assertAlmostEqual(true_anomaly,ta_ext) + self.assertAlmostEqual(semi_major_axis, semi_major_axis_ext) + self.assertAlmostEqual(eccentricity, eccentricity_ext) + self.assertAlmostEqual(inclination, inclination_ext) + self.assertAlmostEqual(longitude_of_the_ascending_node, longitude_of_the_ascending_node_ext) + self.assertAlmostEqual(argument_of_periapsis, argument_of_periapsis_ext) + self.assertAlmostEqual(true_anomaly, ta_ext) def test7(self): """ testing orbital_elements_for_rel_posvel_arrays for the case of one particle """ numpy.random.seed(999) - + mass1 = 0.5 | units.MSun mass2 = 0.8 | units.MSun sem = 12. | units.AU @@ -259,8 +258,8 @@ def test7(self): lon = 10. arg = 0.4 ta = 360.*random.random()-180. - - binary = new_binary_from_orbital_elements(mass1, + + binary = new_binary_from_orbital_elements(mass1, mass2, sem, ecc, @@ -275,14 +274,14 @@ def test7(self): mass_12 = binary[1].mass + binary[0].mass sem_ext, ecc_ext, ta_ext, inc_ext, lon_ext, arg_ext = \ orbital_elements_for_rel_posvel_arrays(rel_pos, rel_vel, mass_12, G=constants.G) - + self.assertAlmostEqual(sem, sem_ext) self.assertAlmostEqual(ecc, ecc_ext) self.assertAlmostEqual(inc, inc_ext) self.assertAlmostEqual(lon, lon_ext) self.assertAlmostEqual(arg, arg_ext) - self.assertAlmostEqual(ta,ta_ext) - + self.assertAlmostEqual(ta, ta_ext) + def test8(self): """ testing orbital_elements_for_rel_posvel_arrays for extreme cases @@ -299,31 +298,31 @@ def test8(self): mass12 = [] rel_position = [] rel_velocity = [] - for i,arg in enumerate(zip(mass1,mass2,semi_major_axis,eccentricity,true_anomaly,inclination, - longitude_of_the_ascending_node,argument_of_periapsis)): - sun_and_comet = new_binary_from_orbital_elements(*arg,G=constants.G) + for i, arg in enumerate(zip(mass1, mass2, semi_major_axis, eccentricity, true_anomaly, inclination, + longitude_of_the_ascending_node, argument_of_periapsis)): + sun_and_comet = new_binary_from_orbital_elements(*arg, G=constants.G) mass12.append(sun_and_comet[0].mass + sun_and_comet[1].mass) rel_position.append(sun_and_comet[1].position - sun_and_comet[0].position) rel_velocity.append(sun_and_comet[1].velocity - sun_and_comet[0].velocity) - + # to convert lists to vector quantities rel_pos = numpy.array([vec_i.value_in(units.AU) for vec_i in rel_position]) | units.AU rel_vel = numpy.array([vec_i.value_in(units.kms) for vec_i in rel_velocity]) | units.kms mass_12 = numpy.array([m_i.value_in(units.MSun) for m_i in mass12]) | units.MSun - + semi_major_axis_ext, eccentricity_ext, ta_ext, inclination_ext, \ longitude_of_the_ascending_node_ext, argument_of_periapsis_ext = \ orbital_elements_for_rel_posvel_arrays(rel_pos, rel_vel, mass_12, - G=constants.G) + G=constants.G) - self.assertAlmostEqual(semi_major_axis,semi_major_axis_ext) - self.assertAlmostEqual(eccentricity,eccentricity_ext) - self.assertAlmostEqual(inclination,inclination_ext) - self.assertAlmostEqual(longitude_of_the_ascending_node,longitude_of_the_ascending_node_ext) - self.assertAlmostEqual(argument_of_periapsis,argument_of_periapsis_ext) - self.assertAlmostEqual(true_anomaly,ta_ext) + self.assertAlmostEqual(semi_major_axis, semi_major_axis_ext) + self.assertAlmostEqual(eccentricity, eccentricity_ext) + self.assertAlmostEqual(inclination, inclination_ext) + self.assertAlmostEqual(longitude_of_the_ascending_node, longitude_of_the_ascending_node_ext) + self.assertAlmostEqual(argument_of_periapsis, argument_of_periapsis_ext) + self.assertAlmostEqual(true_anomaly, ta_ext) def test9(self): """ @@ -332,37 +331,37 @@ def test9(self): """ numpy.random.seed(666) N = 100 - + mass_sun = 1. | nbody_system.mass mass1 = numpy.ones(N) * mass_sun mass2 = numpy.zeros(N) | nbody_system.mass - semi_major_axis=(-numpy.log(random.random(N))) | nbody_system.length + semi_major_axis = (-numpy.log(random.random(N))) | nbody_system.length eccentricity = random.random(N) true_anomaly = 360.*random.random(N)-180. inclination = 180*random.random(N) longitude_of_the_ascending_node = 360*random.random(N)-180 - argument_of_periapsis = 360*random.random(N)-180 - + argument_of_periapsis = 360*random.random(N)-180 + comets = datamodel.Particles(N) - for i,arg in enumerate(zip(mass1,mass2,semi_major_axis,eccentricity,true_anomaly,inclination, - longitude_of_the_ascending_node,argument_of_periapsis)): - sun_and_comet = new_binary_from_orbital_elements(*arg,G=nbody_system.G) + for i, arg in enumerate(zip(mass1, mass2, semi_major_axis, eccentricity, true_anomaly, inclination, + longitude_of_the_ascending_node, argument_of_periapsis)): + sun_and_comet = new_binary_from_orbital_elements(*arg, G=nbody_system.G) comets[i].mass = sun_and_comet[1].mass comets[i].position = sun_and_comet[1].position comets[i].velocity = sun_and_comet[1].velocity - + semi_major_axis_ext, eccentricity_ext, ta_ext, inclination_ext, \ longitude_of_the_ascending_node_ext, argument_of_periapsis_ext = \ orbital_elements_for_rel_posvel_arrays(comets.position, comets.velocity, comets.mass + mass_sun, G=nbody_system.G) - self.assertAlmostEqual(semi_major_axis,semi_major_axis_ext) - self.assertAlmostEqual(eccentricity,eccentricity_ext) - self.assertAlmostEqual(inclination,inclination_ext) - self.assertAlmostEqual(longitude_of_the_ascending_node,longitude_of_the_ascending_node_ext) - self.assertAlmostEqual(argument_of_periapsis,argument_of_periapsis_ext) - self.assertAlmostEqual(true_anomaly,ta_ext) + self.assertAlmostEqual(semi_major_axis, semi_major_axis_ext) + self.assertAlmostEqual(eccentricity, eccentricity_ext) + self.assertAlmostEqual(inclination, inclination_ext) + self.assertAlmostEqual(longitude_of_the_ascending_node, longitude_of_the_ascending_node_ext) + self.assertAlmostEqual(argument_of_periapsis, argument_of_periapsis_ext) + self.assertAlmostEqual(true_anomaly, ta_ext) def xtest10(self): """ @@ -371,25 +370,25 @@ def xtest10(self): """ numpy.random.seed(666) N = 100 - - mass_sun = 1. + + mass_sun = 1. mass1 = numpy.ones(N) * mass_sun - mass2 = numpy.zeros(N) - semi_major_axis=(-numpy.log(random.random(N))) + mass2 = numpy.zeros(N) + semi_major_axis = (-numpy.log(random.random(N))) eccentricity = random.random(N) true_anomaly = 360.*random.random(N)-180. inclination = 180*random.random(N) longitude_of_the_ascending_node = 360*random.random(N)-180 - argument_of_periapsis = 360*random.random(N)-180 - + argument_of_periapsis = 360*random.random(N)-180 + comets = datamodel.Particles(N) - for i,arg in enumerate(zip(mass1,mass2,semi_major_axis,eccentricity,true_anomaly,inclination, - longitude_of_the_ascending_node,argument_of_periapsis)): - sun_and_comet = new_binary_from_orbital_elements(*arg,G=1) + for i, arg in enumerate(zip(mass1, mass2, semi_major_axis, eccentricity, true_anomaly, inclination, + longitude_of_the_ascending_node, argument_of_periapsis)): + sun_and_comet = new_binary_from_orbital_elements(*arg, G=1) comets[i].mass = sun_and_comet[1].mass comets[i].position = sun_and_comet[1].position comets[i].velocity = sun_and_comet[1].velocity - + semi_major_axis_ext, eccentricity_ext, ta_ext, inclination_ext, \ longitude_of_the_ascending_node_ext, argument_of_periapsis_ext = \ orbital_elements_for_rel_posvel_arrays(comets.position, @@ -397,60 +396,59 @@ def xtest10(self): comets.mass + mass_sun, G=1) - self.assertAlmostEqual(semi_major_axis,semi_major_axis_ext) - self.assertAlmostEqual(eccentricity,eccentricity_ext) - self.assertAlmostEqual(inclination,inclination_ext) - self.assertAlmostEqual(longitude_of_the_ascending_node,longitude_of_the_ascending_node_ext) - self.assertAlmostEqual(argument_of_periapsis,argument_of_periapsis_ext) - self.assertAlmostEqual(true_anomaly,ta_ext) - - + self.assertAlmostEqual(semi_major_axis, semi_major_axis_ext) + self.assertAlmostEqual(eccentricity, eccentricity_ext) + self.assertAlmostEqual(inclination, inclination_ext) + self.assertAlmostEqual(longitude_of_the_ascending_node, longitude_of_the_ascending_node_ext) + self.assertAlmostEqual(argument_of_periapsis, argument_of_periapsis_ext) + self.assertAlmostEqual(true_anomaly, ta_ext) + def test11(self): """ testing orbital_elements_for_rel_posvel_arrays for unbound orbits """ - + from amuse.community.kepler.interface import Kepler - + numpy.random.seed(66) N = 10 - + mass_sun = 1. | units.MSun mass1 = numpy.ones(N) * mass_sun mass2 = numpy.zeros(N) | units.MSun - semi_major_axis=-1000.*(random.random(N)) | units.AU + semi_major_axis = -1000.*(random.random(N)) | units.AU eccentricity = (1.+random.random(N))*10.-9. inclination = numpy.pi*random.random(N) longitude_of_the_ascending_node = 2.*numpy.pi*random.random(N)-numpy.pi - argument_of_periapsis = 2.*numpy.pi*random.random(N)-numpy.pi - + argument_of_periapsis = 2.*numpy.pi*random.random(N)-numpy.pi + # kepler.initialize_from_elements initializes orbits with mean_anomaly=0 and true_anomaly=0 true_anomaly = 0.*(360.*random.random(N)-180.) - + comets = datamodel.Particles(N) - - converter = nbody_system.nbody_to_si(1|units.MSun,1|units.AU) + + converter = nbody_system.nbody_to_si(1 | units.MSun, 1 | units.AU) kepler = Kepler(converter) kepler.initialize_code() - for i,arg in enumerate(zip(mass1,mass2,semi_major_axis,eccentricity,true_anomaly,inclination, - longitude_of_the_ascending_node,argument_of_periapsis)): + for i, arg in enumerate(zip(mass1, mass2, semi_major_axis, eccentricity, true_anomaly, inclination, + longitude_of_the_ascending_node, argument_of_periapsis)): kepler.initialize_from_elements(mass=(mass1[i]+mass2[i]), semi=semi_major_axis[i], ecc=eccentricity[i]) ri = kepler.get_separation_vector() vi = kepler.get_velocity_vector() - + om = longitude_of_the_ascending_node[i] w = argument_of_periapsis[i] incl = inclination[i] a1 = ([numpy.cos(om), -numpy.sin(om), 0.0], [numpy.sin(om), numpy.cos(om), 0.0], [0.0, 0.0, 1.0]) a2 = ([1.0, 0.0, 0.0], [0.0, numpy.cos(incl), -numpy.sin(incl)], [0.0, numpy.sin(incl), numpy.cos(incl)]) a3 = ([numpy.cos(w), -numpy.sin(w), 0.0], [numpy.sin(w), numpy.cos(w), 0.0], [0.0, 0.0, 1.0]) - A = numpy.dot(numpy.dot(a1,a2),a3) + A = numpy.dot(numpy.dot(a1, a2), a3) + + r_vec = numpy.dot(A, numpy.reshape(ri, 3, 1)) + v_vec = numpy.dot(A, numpy.reshape(vi, 3, 1)) - r_vec = numpy.dot(A,numpy.reshape(ri,3,1)) - v_vec = numpy.dot(A,numpy.reshape(vi,3,1)) - r = (0.0, 0.0, 0.0) | units.AU v = (0.0, 0.0, 0.0) | (units.AU / units.day) r[0] = r_vec[0] @@ -459,26 +457,26 @@ def test11(self): v[0] = v_vec[0] v[1] = v_vec[1] v[2] = v_vec[2] - + comets[i].mass = mass2[i] comets[i].position = r_vec comets[i].velocity = v_vec - + kepler.stop() - + semi_major_axis_ext, eccentricity_ext, ta_ext, inclination_ext, \ longitude_of_the_ascending_node_ext, argument_of_periapsis_ext = \ orbital_elements(comets.position, comets.velocity, comets.mass + mass_sun, G=constants.G) - - self.assertAlmostEqual(semi_major_axis,semi_major_axis_ext.in_(units.AU)) - self.assertAlmostEqual(eccentricity,eccentricity_ext) - self.assertAlmostEqual(inclination,inclination_ext) - self.assertAlmostEqual(longitude_of_the_ascending_node,longitude_of_the_ascending_node_ext) - self.assertAlmostEqual(argument_of_periapsis,argument_of_periapsis_ext) - self.assertAlmostEqual(true_anomaly,ta_ext) + + self.assertAlmostEqual(semi_major_axis, semi_major_axis_ext.in_(units.AU)) + self.assertAlmostEqual(eccentricity, eccentricity_ext) + self.assertAlmostEqual(inclination, inclination_ext) + self.assertAlmostEqual(longitude_of_the_ascending_node, longitude_of_the_ascending_node_ext) + self.assertAlmostEqual(argument_of_periapsis, argument_of_periapsis_ext) + self.assertAlmostEqual(true_anomaly, ta_ext) def test12(self): """ @@ -653,13 +651,11 @@ def test15(self): def test16(self): """ tests a mismatch in shape in generate_binaries """ - m1=[1]*5 | nbody_system.mass - m2=[0]*5 | nbody_system.mass - a=[1.]*5 | nbody_system.length - ecc=numpy.array([0,0,.99999,0.1,0.5]) - ta=[180,180,20,30,0]| units.deg - primaries,secondaries=generate_binaries(m1,m2,a,eccentricity=ecc,true_anomaly=ta) - m1_,m2_,a_,ecc_,ta_,i_,lasc_,ap_= get_orbital_elements_from_binaries(primaries,secondaries) - self.assertAlmostEqual(ecc,ecc_) - - + m1 = [1]*5 | nbody_system.mass + m2 = [0]*5 | nbody_system.mass + a = [1.]*5 | nbody_system.length + ecc = numpy.array([0, 0, .99999, 0.1, 0.5]) + ta = [180, 180, 20, 30, 0] | units.deg + primaries, secondaries = generate_binaries(m1, m2, a, eccentricity=ecc, true_anomaly=ta) + m1_, m2_, a_, ecc_, ta_, i_, lasc_, ap_ = get_orbital_elements_from_binaries(primaries, secondaries) + self.assertAlmostEqual(ecc, ecc_) diff --git a/src/amuse/test/suite/ext_tests/test_parallel_stellar_evolution.py b/src/amuse/test/suite/ext_tests/test_parallel_stellar_evolution.py index 0b90c187fa..a167316cda 100644 --- a/src/amuse/test/suite/ext_tests/test_parallel_stellar_evolution.py +++ b/src/amuse/test/suite/ext_tests/test_parallel_stellar_evolution.py @@ -14,27 +14,27 @@ from amuse.couple.parallel_stellar_evolution import ParallelStellarEvolution -default_options = dict(must_run_threaded = False) # Always thread-safe -#~default_options = dict() # Really really parallel +default_options = dict(must_run_threaded=False) # Always thread-safe +# ~default_options = dict() # Really really parallel class TestParallelStellarEvolution(TestCase): - + code_factory = SSE - + def test1(self): print("Testing ParallelStellarEvolution initialization") instance = ParallelStellarEvolution(self.code_factory, number_of_workers=3, **default_options) instance.initialize_code() instance.cleanup_code() instance.stop() - + def test2(self): print("Testing ParallelStellarEvolution particles") instance = ParallelStellarEvolution(self.code_factory, number_of_workers=2, **default_options) instance.initialize_code() instance.commit_parameters() - + particles = Particles(5) particles.mass = range(1, 1+len(particles)) | units.MSun incode = instance.particles.add_particles(particles) @@ -42,20 +42,20 @@ def test2(self): self.assertAlmostEqual(incode.mass, range(1, 1+len(particles)) | units.MSun) print("Note that the order of instance.particles is different from the", end=' ') print("original particle order, since particles are distributed over 2 processes") - self.assertAlmostEqual(instance.particles.mass, [1,3,5, 2,4] | units.MSun) - + self.assertAlmostEqual(instance.particles.mass, [1, 3, 5, 2, 4] | units.MSun) + instance.stop() - + def slowtest3(self): print("Testing ParallelStellarEvolution evolve_model") particles = Particles(4) particles.mass = range(1, 1+len(particles)) | units.MSun - + serial = MESA() inserial = serial.particles.add_particles(particles) self.assertAlmostEqual(inserial.mass, range(1, 1+len(particles)) | units.MSun) serial.evolve_model(0.2 | units.Myr) - + parallel = ParallelStellarEvolution(MESA, number_of_workers=3, **default_options) inparallel = parallel.particles.add_particles(particles) self.assertAlmostEqual(inparallel.mass, range(1, 1+len(particles)) | units.MSun) @@ -63,13 +63,13 @@ def slowtest3(self): self.assertEqual(parallel.model_time, 0.2 | units.Myr) self.assertTrue(numpy.all(inparallel.age >= (0.2 | units.Myr))) self.assertTrue(numpy.all(inparallel.age - inparallel.time_step <= (0.2 | units.Myr))) - + self.assertEqual(inserial.luminosity, inparallel.luminosity) self.assertEqual(inserial.time_step, inparallel.time_step) self.assertEqual(inserial.temperature, inparallel.temperature) serial.stop() parallel.stop() - + def test4(self): print("Testing ParallelStellarEvolution parameters") parallel = ParallelStellarEvolution(self.code_factory, number_of_workers=3, **default_options) @@ -78,22 +78,22 @@ def test4(self): for code in parallel.code_instances: self.assertEqual(code.parameters.metallicity, 0.01) parallel.stop() - + def test5(self): print("Testing ParallelStellarEvolution individual options") base_name = os.path.join(get_path_to_results(), "parallel_stellar_evolution_out_") for filename in [base_name+str(i) for i in range(3)]: if os.path.exists(filename): os.remove(filename) - - parallel = ParallelStellarEvolution(self.code_factory, number_of_workers=3, + + parallel = ParallelStellarEvolution(self.code_factory, number_of_workers=3, individual_options=[dict(redirect_file=base_name+str(i)) for i in range(3)], redirection="file", **default_options) - + for filename in [base_name+str(i) for i in range(3)]: self.assertTrue(os.path.exists(filename)) - + parallel.stop() - + def xtest6(self): print("Testing ParallelStellarEvolution exception handling") self.code_factory = EVtwin @@ -103,16 +103,15 @@ def xtest6(self): expected_message = ("Error when calling 'evolve_for' of a 'EVtwin', errorcode is 5, error is 'PRINTB -- age greater than limit'") else: self.skip("Skipping test: {0} has no parameter max_age_stop_condition".format(self.code_factory)) - + parallel = ParallelStellarEvolution(self.code_factory, number_of_workers=2, **default_options) parallel.parameters.max_age_stop_condition = 0.1 | units.Myr - -#~ parallel.particles.add_particles(Particles(2, mass=[1,2]|units.MSun)) # Test speed-up: - parallel.particles.add_particles(Particles(1, mass=1|units.MSun)) - - self.assertRaises(AmuseException, parallel.evolve_model, 1.0|units.Myr, - expected_message = expected_message) + +# ~ parallel.particles.add_particles(Particles(2, mass=[1,2]|units.MSun)) # Test speed-up: + parallel.particles.add_particles(Particles(1, mass=1 | units.MSun)) + + self.assertRaises(AmuseException, parallel.evolve_model, 1.0 | units.Myr, + expected_message=expected_message) self.assertTrue((parallel.particles.age >= 0.1 | units.Myr).all()) self.assertTrue((parallel.particles.age-parallel.particles.time_step <= 0.1 | units.Myr).all()) parallel.stop() - diff --git a/src/amuse/test/suite/ext_tests/test_particles_with_color.py b/src/amuse/test/suite/ext_tests/test_particles_with_color.py index 472a378154..f7c2dc6bcd 100644 --- a/src/amuse/test/suite/ext_tests/test_particles_with_color.py +++ b/src/amuse/test/suite/ext_tests/test_particles_with_color.py @@ -6,14 +6,14 @@ class TestParticlesWithColor(TestCase): - + def test1(self): print("Test new_particles_with_color") with_color = new_particles_with_color( - Particles(mass=[0.1, 1, 2, 3]|units.MSun), - lambda mass: numpy.select([mass < 2.5|units.MSun], [1]), - lambda mass: numpy.select([numpy.logical_and(0.5|units.MSun < mass, mass < 2.5|units.MSun)], [1]), - lambda mass: numpy.select([mass > 1.5|units.MSun], [1]) + Particles(mass=[0.1, 1, 2, 3] | units.MSun), + lambda mass: numpy.select([mass < 2.5 | units.MSun], [1]), + lambda mass: numpy.select([numpy.logical_and(0.5 | units.MSun < mass, mass < 2.5 | units.MSun)], [1]), + lambda mass: numpy.select([mass > 1.5 | units.MSun], [1]) ) self.assertEqual(with_color.red, [1, 1, 1, 0]) self.assertEqual(with_color.green, [0, 1, 1, 0]) @@ -24,23 +24,21 @@ def test1(self): self.assertEqual(with_color.green, [0, 1, 1, 0]) self.assertEqual(with_color.blue, [1, 1, 0, 0]) self.assertEqual(with_color.color, [[0, 0, 1], [1, 1, 1], [1, 1, 0], [1, 0, 0]]) - + def test2(self): print("Test new_particles_with_blackbody_color from temperature") - original = Particles(temperature=[100, 1000, 2000, 5000, 10000, 40000]|units.K) + original = Particles(temperature=[100, 1000, 2000, 5000, 10000, 40000] | units.K) with_color = new_particles_with_blackbody_color(original) self.assertAlmostEqual(with_color.red, [1.0000, 1.0000, 1.0000, 1.0000, 0.6324, 0.3565], 3) self.assertAlmostEqual(with_color.green, [0.0337, 0.0337, 0.2434, 0.7872, 0.7081, 0.4747], 3) self.assertAlmostEqual(with_color.blue, [0.0000, 0.0000, 0.0000, 0.5797, 1.0000, 1.0000], 3) self.assertEqual(with_color.color.shape, (6, 3)) - + def test3(self): print("Test new_particles_with_blackbody_color from internal energy") - original = Particles(u=u_from_T([100, 1000, 2000, 5000, 10000, 40000]|units.K)) + original = Particles(u=u_from_T([100, 1000, 2000, 5000, 10000, 40000] | units.K)) with_color = new_particles_with_blackbody_color(original) self.assertAlmostEqual(with_color.red, [1.0000, 1.0000, 1.0000, 1.0000, 0.6324, 0.3565], 3) self.assertAlmostEqual(with_color.green, [0.0337, 0.0337, 0.2434, 0.7872, 0.7081, 0.4747], 3) self.assertAlmostEqual(with_color.blue, [0.0000, 0.0000, 0.0000, 0.5797, 1.0000, 1.0000], 3) self.assertEqual(with_color.color.shape, (6, 3)) - - diff --git a/src/amuse/test/suite/ext_tests/test_plummer.py b/src/amuse/test/suite/ext_tests/test_plummer.py index bdec6e9e29..d715a8ac25 100644 --- a/src/amuse/test/suite/ext_tests/test_plummer.py +++ b/src/amuse/test/suite/ext_tests/test_plummer.py @@ -5,39 +5,40 @@ from amuse.units import units from amuse.ic.plummer import new_plummer_model, MakePlummerModel + class TestData(amusetest.TestCase): pass - + + class TestPlummer(TestData): def test1(self): numpy.random.seed(0) - #print numpy.random.get_state() + # print numpy.random.get_state() m = MakePlummerModel(2) m1, p, v = m.new_model() - self.assertEqual(m1[0,0], 0.5) - self.assertEqual(m1[1,0], 0.5) - self.assertAlmostEqual(p[0,0], -0.729636617171, 5) - self.assertAlmostEqual(p[1,0], -0.713272921751 , 5) - self.assertAlmostEqual(p[0,1], 0.379570256435, 5) - self.assertAlmostEqual(p[1,1], -0.930290757081, 5) - + self.assertEqual(m1[0, 0], 0.5) + self.assertEqual(m1[1, 0], 0.5) + self.assertAlmostEqual(p[0, 0], -0.729636617171, 5) + self.assertAlmostEqual(p[1, 0], -0.713272921751, 5) + self.assertAlmostEqual(p[0, 1], 0.379570256435, 5) + self.assertAlmostEqual(p[1, 1], -0.930290757081, 5) + def test2(self): - convert_nbody = nbody_system.nbody_to_si(6|units.kg, 7 | units.m) - stars = new_plummer_model(2, convert_nbody) + convert_nbody = nbody_system.nbody_to_si(6 | units.kg, 7 | units.m) + stars = new_plummer_model(2, convert_nbody) self.assertEqual(stars[0].mass.value_in(units.kg), 3.0) self.assertEqual(stars[1].mass.value_in(units.kg), 3.0) - + def test3(self): - stars = new_plummer_model(2, None) + stars = new_plummer_model(2, None) self.assertEqual(stars[0].mass.value_in(nbody_system.mass), 0.5) self.assertEqual(stars[1].mass.value_in(nbody_system.mass), 0.5) - + def test4(self): - stars = new_plummer_model(2, do_scale = True) + stars = new_plummer_model(2, do_scale=True) self.assertAlmostEqual(stars.kinetic_energy(), 0.25 | nbody_system.energy) self.assertAlmostEqual(stars.potential_energy(G=nbody_system.G), -0.50 | nbody_system.energy) - self.assertAlmostEqual(stars.center_of_mass(), [0,0,0] | nbody_system.length) - self.assertAlmostEqual(stars.center_of_mass_velocity(), [0,0,0] | nbody_system.speed) + self.assertAlmostEqual(stars.center_of_mass(), [0, 0, 0] | nbody_system.length) + self.assertAlmostEqual(stars.center_of_mass_velocity(), [0, 0, 0] | nbody_system.speed) self.assertAlmostEqual(stars.mass.sum(), 1.00 | nbody_system.mass) self.assertAlmostEqual(stars.virial_radius(), 1.00 | nbody_system.length) - diff --git a/src/amuse/test/suite/ext_tests/test_roche_radius.py b/src/amuse/test/suite/ext_tests/test_roche_radius.py index a9965e1938..6d79d17c2c 100644 --- a/src/amuse/test/suite/ext_tests/test_roche_radius.py +++ b/src/amuse/test/suite/ext_tests/test_roche_radius.py @@ -5,6 +5,7 @@ from amuse.ext.roche_radius import Roche_Orbit, sepinsky_formula + class TestRocheRadius(amusetest.TestCase): def test1(self): @@ -23,7 +24,6 @@ def test1(self): self.assertIsOfOrder(sepinsky_formula(q=1e4, A=a_values), answers) - def test2(self): """ Test the Roche_Orbit class """ diff --git a/src/amuse/test/suite/ext_tests/test_rotating_bridge.py b/src/amuse/test/suite/ext_tests/test_rotating_bridge.py index 59b2e0730a..41268968fa 100644 --- a/src/amuse/test/suite/ext_tests/test_rotating_bridge.py +++ b/src/amuse/test/suite/ext_tests/test_rotating_bridge.py @@ -9,115 +9,119 @@ from amuse.datamodel import Particles + class drift_without_gravity(object): """ This class evolves the motion of the test particles (no gravity) """ - def __init__(self, particles, time= 0 |units.Myr): + + def __init__(self, particles, time=0 | units.Myr): self.particles = particles self.model_time = time + def evolve_model(self, t_end): dt = t_end - self.model_time self.particles.position += self.particles.velocity*dt self.model_time = t_end + @property def potential_energy(self): return quantities.zero - @property + + @property def kinetic_energy(self): return (0.5*self.particles.mass*self.particles.velocity.lengths()**2).sum() + class TestRotatingBridge(amusetest.TestCase): def test1(self): - p0=Particles(1) + p0 = Particles(1) p0.position = [0.0, 1.0, 0.0] p0.velocity = [1.0, 0.0, 0.0] - - pos1=p0.position.copy() - vel1=p0.velocity.copy() - - omega=1. - N=0.25 - dt=0.01 + + pos1 = p0.position.copy() + vel1 = p0.velocity.copy() + + omega = 1. + N = 0.25 + dt = 0.01 method = SPLIT_6TH_SS_M13 - tend=N*2*numpy.pi/omega - dt=dt*2*numpy.pi/omega + tend = N*2*numpy.pi/omega + dt = dt*2*numpy.pi/omega - pr=inertial_to_rotating(0,omega, p0) - - drift=drift_without_gravity(pr, time=0) - sys=Rotating_Bridge(omega, timestep=dt, method=method) + pr = inertial_to_rotating(0, omega, p0) + + drift = drift_without_gravity(pr, time=0) + sys = Rotating_Bridge(omega, timestep=dt, method=method) sys.add_system(drift) - + sys.evolve_model(tend) - - pi=rotating_to_inertial(tend, omega,pr) - - pos2=pi.position.copy() - - - self.assertAlmostEqual(sys.model_time,tend) - self.assertAlmostEqual(pos1+vel1*tend,pos2,12) - - pi.velocity=-pi.velocity - - pr=inertial_to_rotating(0,-omega,pi) - drift=drift_without_gravity(pr,time=0) - sys=Rotating_Bridge(-omega, timestep=dt,method=method) + + pi = rotating_to_inertial(tend, omega, pr) + + pos2 = pi.position.copy() + + self.assertAlmostEqual(sys.model_time, tend) + self.assertAlmostEqual(pos1+vel1*tend, pos2, 12) + + pi.velocity = -pi.velocity + + pr = inertial_to_rotating(0, -omega, pi) + drift = drift_without_gravity(pr, time=0) + sys = Rotating_Bridge(-omega, timestep=dt, method=method) sys.add_system(drift) - - sys.evolve_model(tend) - pi=rotating_to_inertial(tend,-omega,pr) - - pos3=pi.position.copy() - - self.assertAlmostEqual(pos1,pos3,12) + sys.evolve_model(tend) + + pi = rotating_to_inertial(tend, -omega, pr) + + pos3 = pi.position.copy() + + self.assertAlmostEqual(pos1, pos3, 12) def test2(self): - p0=Particles(1) + p0 = Particles(1) p0.position = [0.0, 1.0, 0.0] | units.m p0.velocity = [1.0, 0.0, 0.0] | units.m/units.s - - pos1=p0.position.copy() - vel1=p0.velocity.copy() - - omega=1. | units.s**-1 - N=0.25 - dt=0.01 + + pos1 = p0.position.copy() + vel1 = p0.velocity.copy() + + omega = 1. | units.s**-1 + N = 0.25 + dt = 0.01 method = SPLIT_6TH_SS_M13 - tend=N*2*numpy.pi/omega - dt=dt*2*numpy.pi/omega + tend = N*2*numpy.pi/omega + dt = dt*2*numpy.pi/omega - pr=inertial_to_rotating(0*dt,omega, p0) - - drift=drift_without_gravity(pr, time=0 | units.s) - sys=Rotating_Bridge(omega, timestep=dt, method=method) + pr = inertial_to_rotating(0*dt, omega, p0) + + drift = drift_without_gravity(pr, time=0 | units.s) + sys = Rotating_Bridge(omega, timestep=dt, method=method) sys.add_system(drift) - + sys.evolve_model(tend) - - pi=rotating_to_inertial(tend, omega,pr) - - pos2=pi.position.copy() - - - self.assertAlmostEqual(sys.model_time,tend) - self.assertAlmostEqual(pos1+vel1*tend,pos2,12) - - pi.velocity=-pi.velocity - - pr=inertial_to_rotating(0*dt,-omega,pi) - drift=drift_without_gravity(pr,time=0| units.s) - sys=Rotating_Bridge(-omega, timestep=dt,method=method) + + pi = rotating_to_inertial(tend, omega, pr) + + pos2 = pi.position.copy() + + self.assertAlmostEqual(sys.model_time, tend) + self.assertAlmostEqual(pos1+vel1*tend, pos2, 12) + + pi.velocity = -pi.velocity + + pr = inertial_to_rotating(0*dt, -omega, pi) + drift = drift_without_gravity(pr, time=0 | units.s) + sys = Rotating_Bridge(-omega, timestep=dt, method=method) sys.add_system(drift) - - sys.evolve_model(tend) - - pi=rotating_to_inertial(tend,-omega,pr) - - pos3=pi.position.copy() - - self.assertAlmostEqual(pos1,pos3,12) + + sys.evolve_model(tend) + + pi = rotating_to_inertial(tend, -omega, pr) + + pos3 = pi.position.copy() + + self.assertAlmostEqual(pos1, pos3, 12) diff --git a/src/amuse/test/suite/ext_tests/test_salpeter.py b/src/amuse/test/suite/ext_tests/test_salpeter.py index b8a415a9d7..065da5ea2b 100644 --- a/src/amuse/test/suite/ext_tests/test_salpeter.py +++ b/src/amuse/test/suite/ext_tests/test_salpeter.py @@ -8,52 +8,51 @@ from amuse.ic.salpeter import new_salpeter_mass_distribution from amuse.ic.salpeter import new_salpeter_mass_distribution_nbody + class SalpeterIMFTests(amusetest.TestCase): - + def test1(self): - instance = SalpeterIMF(0.1 | units.MSun, 100 | units.MSun, alpha = -2.35) + instance = SalpeterIMF(0.1 | units.MSun, 100 | units.MSun, alpha=-2.35) self.assertAlmostEqual(instance.mass_mean().value_in(units.MSun), 0.351, 3) - + def test2(self): - instance = SalpeterIMF(0.1 | units.MSun, 100 | units.MSun, alpha = -2.35) + instance = SalpeterIMF(0.1 | units.MSun, 100 | units.MSun, alpha=-2.35) self.assertAlmostEqual(instance.mass(1.0), 100 | units.MSun) self.assertAlmostEqual(instance.mass(0.0), 0.1 | units.MSun) - + def test3(self): numpy.random.seed(345672) - instance = SalpeterIMF(0.1 | units.MSun, 100 | units.MSun, alpha = -2.35) + instance = SalpeterIMF(0.1 | units.MSun, 100 | units.MSun, alpha=-2.35) n = 10000 total_mass, set_of_masses = instance.next_set(n) - + self.assertAlmostEqual(instance.mass_mean(), 0.35136877959 | units.MSun) self.assertAlmostEqual(total_mass / n, 0.35136877959 | units.MSun, 1) self.assertAlmostEqual(total_mass / n, 0.33999456911 | units.MSun) self.assertAlmostEqual(instance.mass(0.5), set_of_masses.median(), 2) - + def test4(self): - instance = SalpeterIMF(0.1 | units.MSun, 125 | units.MSun, alpha = -2.35) + instance = SalpeterIMF(0.1 | units.MSun, 125 | units.MSun, alpha=-2.35) self.assertAlmostEqual(instance.mass_mean(), 0.353943475903 | units.MSun) - + def test5(self): print("Test 5: testing user interface (SI units)") numpy.random.seed(345672) masses = new_salpeter_mass_distribution(1000) - + self.assertEqual(len(masses), 1000) self.assertAlmostEqual(masses.mean(), 0.334475937397 | units.MSun) self.assertAlmostRelativeEqual(masses.mean(), SalpeterIMF().mass_mean(), 1) self.assertAlmostEqual(masses.amin(), 0.10017909529 | units.MSun) self.assertAlmostEqual(masses.amax(), 19.7132849297 | units.MSun) - + def test6(self): print("Test 6: testing user interface (nbody units)") numpy.random.seed(345672) masses = new_salpeter_mass_distribution_nbody(1000) - + self.assertEqual(len(masses), 1000) self.assertAlmostEqual(masses.sum(), 1.0 | nbody_system.mass) self.assertAlmostEqual(masses.mean(), 1.0 / 1000 | nbody_system.mass) self.assertAlmostEqual(masses.amin(), 0.10017909529 / 0.334475937397 / 1000 | nbody_system.mass) self.assertAlmostEqual(masses.amax(), 19.7132849297 / 0.334475937397 / 1000 | nbody_system.mass) - - diff --git a/src/amuse/test/suite/ext_tests/test_sink.py b/src/amuse/test/suite/ext_tests/test_sink.py index 69351f1d88..7fc0d0846f 100644 --- a/src/amuse/test/suite/ext_tests/test_sink.py +++ b/src/amuse/test/suite/ext_tests/test_sink.py @@ -18,11 +18,11 @@ class TestSinkParticles(TestCase): - looping_over="sinks" + looping_over = "sinks" def test1(self): print("Testing SinkParticles initialization from new (blank) particle") - sinks = SinkParticles(Particles(2), sink_radius=[42.0,43.0]|units.RSun) + sinks = SinkParticles(Particles(2), sink_radius=[42.0, 43.0] | units.RSun) self.assertEqual(sinks.sink_radius, [42.0, 43.0] | units.RSun) self.assertEqual(sinks.mass, 0.0 | units.MSun) @@ -30,9 +30,9 @@ def test1(self): self.assertEqual(sinks.velocity, [0.0, 0.0, 0.0] | units.km/units.s) self.assertEqual(sinks.angular_momentum, [0.0, 0.0, 0.0] | units.kg*units.km**2/units.s) - sinks = SinkParticles(Particles(2), sink_radius=24.0|units.RSun, mass=[1.0,2.0]|units.MSun, - position=[1,2,3]|nbody_system.length, velocity=[4,5,6]|nbody_system.length/nbody_system.time, - angular_momentum=[9,8,7] | nbody_system.mass*nbody_system.length**2/nbody_system.time) + sinks = SinkParticles(Particles(2), sink_radius=24.0 | units.RSun, mass=[1.0, 2.0] | units.MSun, + position=[1, 2, 3] | nbody_system.length, velocity=[4, 5, 6] | nbody_system.length/nbody_system.time, + angular_momentum=[9, 8, 7] | nbody_system.mass*nbody_system.length**2/nbody_system.time) self.assertEqual(sinks.sink_radius, 24.0 | units.RSun) self.assertEqual(sinks.mass, [1.0, 2.0] | units.MSun) self.assertEqual(sinks.position, [1.0, 2.0, 3.0] | nbody_system.length) @@ -42,25 +42,22 @@ def test1(self): def test2(self): print("Testing SinkParticles initialization from existing particles") original = Particles(3) - self.assertRaises(AttributeError, SinkParticles, original, expected_message= - "You tried to access attribute 'radius' but this attribute is not defined for this set.") + self.assertRaises(AttributeError, SinkParticles, original, expected_message="You tried to access attribute 'radius' but this attribute is not defined for this set.") original.radius = 42.0 | units.RSun original.mass = 10.0 | units.MSun original.position = [[i, -i, 2*i] for i in range(3)] | units.parsec sinks = SinkParticles(original) self.assertEqual(sinks.sink_radius, 42.0 | units.RSun) self.assertEqual(sinks.mass, 10.0 | units.MSun) - self.assertEqual(sinks.position, [[0,0,0], [1,-1,2], [2,-2,4]] | units.parsec) - self.assertRaises(AttributeError, getattr, sinks, "bogus", expected_message= - "You tried to access attribute 'bogus' but this attribute is not defined for this set.") + self.assertEqual(sinks.position, [[0, 0, 0], [1, -1, 2], [2, -2, 4]] | units.parsec) + self.assertRaises(AttributeError, getattr, sinks, "bogus", expected_message="You tried to access attribute 'bogus' but this attribute is not defined for this set.") def test3(self): print("Testing SinkParticles initialization from existing particles in set") particles = Particles(10) - self.assertRaises(AttributeError, SinkParticles, particles[[4, 7]], expected_message= - "You tried to access attribute 'radius' but this attribute is not defined for this set.") + self.assertRaises(AttributeError, SinkParticles, particles[[4, 7]], expected_message="You tried to access attribute 'radius' but this attribute is not defined for this set.") particles.radius = 42.0 | units.RSun - particles.mass = range(1,11) | units.MSun + particles.mass = range(1, 11) | units.MSun particles.position = [[i, 2*i, 3*i] for i in range(10)] | units.parsec sinks = SinkParticles(particles[[4]]) @@ -69,13 +66,13 @@ def test3(self): self.assertEqual(sinks.radius, 42.0 | units.RSun) self.assertEqual(sinks.position, [4.0, 8.0, 12.0] | units.parsec) - sinks = SinkParticles(particles[[4, 7]], sink_radius=[1,2]|units.AU) + sinks = SinkParticles(particles[[4, 7]], sink_radius=[1, 2] | units.AU) self.assertEqual(sinks.sink_radius, [1.0, 2.0] | units.AU) self.assertEqual(sinks.radius, 42.0 | units.RSun) self.assertEqual(sinks.mass, [5.0, 8.0] | units.MSun) self.assertEqual(sinks.position, [[4, 8, 12], [7, 14, 21]] | units.parsec) - self.assertEqual(set(['key', 'mass', 'radius', 'x', 'y', 'z', 'sink_radius', 'vx','vy','vz','lx','ly','lz']), + self.assertEqual(set(['key', 'mass', 'radius', 'x', 'y', 'z', 'sink_radius', 'vx', 'vy', 'vz', 'lx', 'ly', 'lz']), set(str(sinks).split("\n")[0].split())) self.assertEqual(set(['key', 'mass', 'radius', 'x', 'y', 'z']), set(str(particles).split("\n")[0].split())) @@ -84,77 +81,78 @@ def test4(self): print("Testing SinkParticles accrete") particles = Particles(10) particles.radius = 42.0 | units.RSun - particles.mass = range(1,11) | units.MSun + particles.mass = range(1, 11) | units.MSun particles.position = [[i, 2*i, 3*i] for i in range(10)] | units.parsec particles.velocity = [[i, 0, -i] for i in range(10)] | units.km/units.s particles.age = range(10) | units.Myr copy = particles.copy() - sinks = SinkParticles(particles[[3, 7]], sink_radius=[4,5]|units.parsec,looping_over=self.looping_over) + sinks = SinkParticles(particles[[3, 7]], sink_radius=[4, 5] | units.parsec, looping_over=self.looping_over) self.assertEqual(sinks.sink_radius, [4.0, 5.0] | units.parsec) self.assertEqual(sinks.mass, [4.0, 8.0] | units.MSun) self.assertEqual(sinks.position, [[3, 6, 9], [7, 14, 21]] | units.parsec) accreted = sinks.accrete(particles) - self.assertEqual(len(accreted), 4) # 4 particles were accreted + self.assertEqual(len(accreted), 4) # 4 particles were accreted self.assertEqual(len(particles), 6) - self.assertEqual(sinks.mass, [12.0, 24.0] | units.MSun) # mass of sinks increased + self.assertEqual(sinks.mass, [12.0, 24.0] | units.MSun) # mass of sinks increased self.assertEqual(sinks.get_intersecting_subset_in(particles).mass, - [12.0, 24.0] | units.MSun) # original particles' masses match - self.assertEqual(particles.total_mass(), copy.total_mass()) # total mass is conserved - self.assertEqual(particles.center_of_mass(), copy.center_of_mass()) # center of mass is conserved - self.assertEqual(particles.center_of_mass_velocity(), copy.center_of_mass_velocity()) # center of mass velocity is conserved - self.assertEqual(particles.total_momentum(), copy.total_momentum()) # momentum is conserved - self.assertEqual(particles.total_angular_momentum()+sinks.angular_momentum.sum(axis=0), copy.total_angular_momentum()) # angular_momentum is conserved + [12.0, 24.0] | units.MSun) # original particles' masses match + self.assertEqual(particles.total_mass(), copy.total_mass()) # total mass is conserved + self.assertEqual(particles.center_of_mass(), copy.center_of_mass()) # center of mass is conserved + self.assertEqual(particles.center_of_mass_velocity(), copy.center_of_mass_velocity()) # center of mass velocity is conserved + self.assertEqual(particles.total_momentum(), copy.total_momentum()) # momentum is conserved + self.assertEqual(particles.total_angular_momentum()+sinks.angular_momentum.sum(axis=0), copy.total_angular_momentum()) # angular_momentum is conserved sinks.sink_radius = [4.0, 8.0] | units.parsec accreted = sinks.accrete(particles) - self.assertEqual(len(accreted), 2) # another 2 particles were accreted + self.assertEqual(len(accreted), 2) # another 2 particles were accreted self.assertEqual(len(particles), 4) - self.assertEqual(sinks.mass, [12.0, 40.0] | units.MSun) # mass of sinks increased + self.assertEqual(sinks.mass, [12.0, 40.0] | units.MSun) # mass of sinks increased self.assertEqual(sinks.get_intersecting_subset_in(particles).mass, - [12.0, 40.0] | units.MSun) # original particles' masses match - self.assertEqual(particles.total_mass(), copy.total_mass()) # total mass is conserved - self.assertEqual(particles.center_of_mass(), copy.center_of_mass()) # center of mass is conserved - self.assertEqual(particles.center_of_mass_velocity(), copy.center_of_mass_velocity()) # center of mass velocity is conserved - self.assertEqual(particles.total_momentum(), copy.total_momentum()) # momentum is conserved - self.assertEqual(particles.total_angular_momentum()+sinks.angular_momentum.sum(axis=0), copy.total_angular_momentum()) # angular_momentum is conserved + [12.0, 40.0] | units.MSun) # original particles' masses match + self.assertEqual(particles.total_mass(), copy.total_mass()) # total mass is conserved + self.assertEqual(particles.center_of_mass(), copy.center_of_mass()) # center of mass is conserved + self.assertEqual(particles.center_of_mass_velocity(), copy.center_of_mass_velocity()) # center of mass velocity is conserved + self.assertEqual(particles.total_momentum(), copy.total_momentum()) # momentum is conserved + self.assertEqual(particles.total_angular_momentum()+sinks.angular_momentum.sum(axis=0), copy.total_angular_momentum()) # angular_momentum is conserved def test5(self): print("Testing SinkParticles accrete, one particle within two sinks' radii") particles = Particles(10) particles.radius = 42.0 | units.RSun - particles.mass = range(1,11) | units.MSun + particles.mass = range(1, 11) | units.MSun particles.position = [[i, 2*i, 3*i] for i in range(10)] | units.parsec particles.velocity = [[i, 0, -i] for i in range(10)] | units.km/units.s particles.age = range(10) | units.Myr copy = particles.copy() - sinks = SinkParticles(particles[[3, 7]], sink_radius=[4,12]|units.parsec,looping_over=self.looping_over) + sinks = SinkParticles(particles[[3, 7]], sink_radius=[4, 12] | units.parsec, looping_over=self.looping_over) self.assertEqual(sinks.sink_radius, [4.0, 12.0] | units.parsec) self.assertEqual(sinks.mass, [4.0, 8.0] | units.MSun) self.assertEqual(sinks.position, [[3, 6, 9], [7, 14, 21]] | units.parsec) sinks.accrete(particles) - self.assertEqual(len(particles), 4) # 6 particles were accreted - self.assertEqual(sinks.mass, [12.0, 40.0] | units.MSun) # mass of sinks increased + self.assertEqual(len(particles), 4) # 6 particles were accreted + self.assertEqual(sinks.mass, [12.0, 40.0] | units.MSun) # mass of sinks increased self.assertEqual(sinks.get_intersecting_subset_in(particles).mass, - [12.0, 40.0] | units.MSun) # original particles' masses match - self.assertEqual(particles.total_mass(), copy.total_mass()) # total mass is conserved - self.assertEqual(particles.center_of_mass(), copy.center_of_mass()) # center of mass is conserved - self.assertEqual(particles.center_of_mass_velocity(), copy.center_of_mass_velocity()) # center of mass velocity is conserved - self.assertEqual(particles.total_momentum(), copy.total_momentum()) # momentum is conserved - self.assertEqual(particles.total_angular_momentum()+sinks.angular_momentum.sum(axis=0), copy.total_angular_momentum()) # angular_momentum is conserved + [12.0, 40.0] | units.MSun) # original particles' masses match + self.assertEqual(particles.total_mass(), copy.total_mass()) # total mass is conserved + self.assertEqual(particles.center_of_mass(), copy.center_of_mass()) # center of mass is conserved + self.assertEqual(particles.center_of_mass_velocity(), copy.center_of_mass_velocity()) # center of mass velocity is conserved + self.assertEqual(particles.total_momentum(), copy.total_momentum()) # momentum is conserved + self.assertEqual(particles.total_angular_momentum()+sinks.angular_momentum.sum(axis=0), copy.total_angular_momentum()) # angular_momentum is conserved class TestSinkParticlesLoopingOverSources(TestSinkParticles): - looping_over="sources" + looping_over = "sources" + class TestNewSinkParticles(TestCase): - looping_over="sinks" + looping_over = "sinks" def test1(self): print("Test the documentation for new_sink_particles") @@ -166,7 +164,7 @@ def test2(self): cloud.mass = 1 | units.MSun cloud.position = [[0, 0, 0], [100, 100, 100], [200, 200, 200], [300, 300, 300]]*25 | units.parsec cloud.velocity = [[0, 0, 0], [1, 1, 1]]*50 | units.km / units.s - unit_converter = ConvertBetweenGenericAndSiUnits(1|units.m, 1|units.kg, 1|units.s) + unit_converter = ConvertBetweenGenericAndSiUnits(1 | units.m, 1 | units.kg, 1 | units.s) sph_code = Stub(unit_converter) sph_code.parameters.stopping_condition_maximum_density = 1 | units.kg / units.m**3 sph_code.gas_particles.add_particles(cloud) @@ -183,7 +181,7 @@ def test2(self): clumps = density_limit_detection.particles().copy() sph_code.gas_particles.remove_particles(clumps) - sinks = new_sink_particles(clumps, sink_radius=1|units.parsec,looping_over=self.looping_over) + sinks = new_sink_particles(clumps, sink_radius=1 | units.parsec, looping_over=self.looping_over) self.assertEqual(sinks.sink_radius, 1.0 | units.parsec) self.assertEqual(sinks.mass, 1.0 | units.MSun) self.assertEqual(sinks.position, @@ -229,14 +227,14 @@ def test3(self): sph_code.gas_particles.remove_particles(clumps) clumps_in_code = sph_code.dm_particles.add_particles(clumps) - sinks = new_sink_particles(clumps_in_code,looping_over=self.looping_over) + sinks = new_sink_particles(clumps_in_code, looping_over=self.looping_over) self.assertEqual(sinks.sink_radius, clumps.radius) self.assertAlmostRelativeEqual(sinks.mass, UnitMass / number_gas_particles, 10) self.assertAlmostRelativeEqual(sinks.position, clumps.position, 10) self.assertEqual(len(sph_code.gas_particles), number_gas_particles - 1) self.assertAlmostRelativeEqual(sph_code.particles.total_mass(), UnitMass, 10) self.assertAlmostRelativeEqual(sph_code.gas_particles.total_mass(), UnitMass - sinks.total_mass(), 10) - self.assertEqual(set(sinks.get_attribute_names_defined_in_store()) - set(["sink_radius","lx","ly","lz"]), + self.assertEqual(set(sinks.get_attribute_names_defined_in_store()) - set(["sink_radius", "lx", "ly", "lz"]), set(sph_code.particles.get_attribute_names_defined_in_store())) sinks.accrete(sph_code.gas_particles) @@ -245,7 +243,7 @@ def test3(self): self.assertAlmostRelativeEqual(sph_code.particles.total_mass(), UnitMass, 10) self.assertAlmostRelativeEqual(sph_code.gas_particles.total_mass(), UnitMass - sinks.total_mass(), 10) - sinks.accrete(sph_code.particles) # Nothing happens: gas already gone, and cannot accrete itself + sinks.accrete(sph_code.particles) # Nothing happens: gas already gone, and cannot accrete itself self.assertAlmostRelativeEqual(sinks.mass, 3 * UnitMass / number_gas_particles, 10) self.assertAlmostRelativeEqual(sph_code.particles.total_mass(), UnitMass, 10) @@ -275,7 +273,7 @@ def test3(self): sph_code.gas_particles.remove_particles(clumps) clumps_in_code = sph_code.dm_particles.add_particles(clumps) - sinks.add_sinks(clumps_in_code, sink_radius=0.1|units.kpc) + sinks.add_sinks(clumps_in_code, sink_radius=0.1 | units.kpc) self.assertEqual(sinks[1:].sink_radius, 0.1 | units.kpc) self.assertEqual(len(sph_code.gas_particles), number_gas_particles - 12) self.assertAlmostRelativeEqual(sinks.mass[1:], UnitMass / number_gas_particles, 10) @@ -288,59 +286,60 @@ def test3(self): self.assertAlmostRelativeEqual(sph_code.particles.total_mass().as_quantity_in(units.MSun), UnitMass, 10) self.assertAlmostRelativeEqual(sinks.mass, [7.0, 13.0, 15.0, 9.0, 11.0, 11.0] * UnitMass / number_gas_particles, 10) + class TestNewSinkParticlesLoopingOverSources(TestNewSinkParticles): - looping_over="sources" + looping_over = "sources" class TestNonSphericalSinkParticles(TestCase): def test1(self): """ Test creating shapes and combining them """ - shapes = sink.Sphere(1|units.RSun) | sink.Sphere(2|units.RSun) + shapes = sink.Sphere(1 | units.RSun) | sink.Sphere(2 | units.RSun) self.assertEqual(len(shapes.sub_shapes), 2) - shapes = sink.Sphere(1|units.RSun) | sink.Sphere(2|units.RSun) | sink.Spheroid([0.5, 0.5, 10]|units.RSun) + shapes = sink.Sphere(1 | units.RSun) | sink.Sphere(2 | units.RSun) | sink.Spheroid([0.5, 0.5, 10] | units.RSun) self.assertEqual(len(shapes.sub_shapes), 3) def test2(self): """ Test Spheroid sink accretion """ particles = self.create_particle_grid() - spheroid = sink.Spheroid([5., 4., 1.]|units.RSun) - sink_particles = Particles(1, mass=10.|units.MSun, radius=0.|units.RSun, position=[[1., 1., 1.]]|units.RSun) + spheroid = sink.Spheroid([5., 4., 1.] | units.RSun) + sink_particles = Particles(1, mass=10. | units.MSun, radius=0. | units.RSun, position=[[1., 1., 1.]] | units.RSun) sinks = new_sink_particles(sink_particles, shapes=spheroid) accreted = sinks.accrete(particles) self.assertEqual(len(accreted), 161) self.assertEqual(len(particles), 1839) - self.assertEqual(accreted.x.max(), 4|units.RSun) - self.assertEqual(accreted.y.max(), 3|units.RSun) - self.assertEqual(accreted.z.max(), 0.5|units.RSun) + self.assertEqual(accreted.x.max(), 4 | units.RSun) + self.assertEqual(accreted.y.max(), 3 | units.RSun) + self.assertEqual(accreted.z.max(), 0.5 | units.RSun) spheroid.dimensions[2] = 3 | units.RSun accreted = sinks.accrete(particles) self.assertEqual(len(accreted), 324) self.assertEqual(len(particles), 1515) - self.assertEqual(accreted.x.max(), 4|units.RSun) - self.assertEqual(accreted.y.max(), 3|units.RSun) - self.assertEqual(accreted.z.max(), 2.5|units.RSun) - self.assertIsSubvector([3, 2, 2.5]|units.RSun, particles.position) + self.assertEqual(accreted.x.max(), 4 | units.RSun) + self.assertEqual(accreted.y.max(), 3 | units.RSun) + self.assertEqual(accreted.z.max(), 2.5 | units.RSun) + self.assertIsSubvector([3, 2, 2.5] | units.RSun, particles.position) def test3(self): """ Test compound sink accretion """ particles = self.create_particle_grid() - shape = sink.Sphere(3.|units.RSun) | sink.Disc(*[5., 1.]|units.RSun) - sink_particles = Particles(1, mass=10.|units.MSun, radius=0.|units.RSun, position=[[1., 1., 1.]]|units.RSun) + shape = sink.Sphere(3. | units.RSun) | sink.Disc(*[5., 1.] | units.RSun) + sink_particles = Particles(1, mass=10. | units.MSun, radius=0. | units.RSun, position=[[1., 1., 1.]] | units.RSun) sinks = new_sink_particles(sink_particles, shapes=shape) accreted = sinks.accrete(particles) self.assertEqual(len(accreted), 319) self.assertEqual(len(particles), 1681) - self.assertEqual(accreted.x.max(), 4|units.RSun) - self.assertEqual(accreted.y.max(), 4|units.RSun) - self.assertEqual(accreted.z.max(), 2.5|units.RSun) - self.assertIsSubvector([2, 2, 1]|units.RSun, particles.position) + self.assertEqual(accreted.x.max(), 4 | units.RSun) + self.assertEqual(accreted.y.max(), 4 | units.RSun) + self.assertEqual(accreted.z.max(), 2.5 | units.RSun) + self.assertIsSubvector([2, 2, 1] | units.RSun, particles.position) def create_particle_grid(self): particles = Particles(2000) @@ -469,7 +468,7 @@ def evolve_model(self, time): class Stub(GravitationalDynamics): - def __init__(self, unit_converter = None, **options): + def __init__(self, unit_converter=None, **options): self.stopping_conditions = StoppingConditions(self) GravitationalDynamics.__init__( @@ -485,7 +484,7 @@ def define_parameters(self, object): "set_stopping_condition_maximum_density_parameter", "stopping_condition_maximum_density", "maximum density of a gas particle", - default_value = -1.0 | generic_unit_system.density + default_value=-1.0 | generic_unit_system.density ) def define_methods(self, object): @@ -496,8 +495,8 @@ def define_methods(self, object): (object.INDEX, object.ERROR_CODE)) def define_particle_sets(self, object): - object.define_super_set('particles', ['dm_particles','gas_particles'], - index_to_default_set = 0) + object.define_super_set('particles', ['dm_particles', 'gas_particles'], + index_to_default_set=0) object.define_set('dm_particles', 'index_of_the_particle') object.set_new('dm_particles', 'new_particle') @@ -515,5 +514,3 @@ def define_particle_sets(self, object): object.add_getter('gas_particles', 'get_velocity', names=("vx", "vy", "vz")) object.add_query('particles', 'get_stopping_condition_particle_index') - - diff --git a/src/amuse/test/suite/ext_tests/test_solarsystem.py b/src/amuse/test/suite/ext_tests/test_solarsystem.py index 8f4fe2741f..47de6b9253 100644 --- a/src/amuse/test/suite/ext_tests/test_solarsystem.py +++ b/src/amuse/test/suite/ext_tests/test_solarsystem.py @@ -5,41 +5,41 @@ from amuse.ext.solarsystem import new_solar_system, new_solar_system_for_mercury from amuse.units import units from amuse.units import constants + + class TestSolarSystem(TestCase): - + def test1(self): print("Test 1: testing new_solar_system_for_mercury") sun, orbiters = new_solar_system_for_mercury() - + expected_attributes = set(["name", "mass", "radius", "j2", "j4", "j6", "lx", "ly", "lz"]) self.assertEqual(set(sun.get_attribute_names_defined_in_store()), expected_attributes) - + expected_attributes = set(["name", "mass", "radius", "density", "x", "y", "z", "vx", "vy", "vz", "Lx", "Ly", "Lz", "celimit"]) self.assertEqual(set(orbiters.get_attribute_names_defined_in_store()), expected_attributes) - + def test2(self): print("Test 2: testing new_solar_system") particles = new_solar_system() print(particles) - + expected_attributes = set(["name", "mass", "radius", "x", "y", "z", "vx", "vy", "vz"]) self.assertEqual(set(particles.get_attribute_names_defined_in_store()), expected_attributes) - - self.assertAlmostEqual(particles.center_of_mass(), [0, 0, 0] | units.m, in_units = units.AU) - self.assertAlmostEqual(particles.center_of_mass_velocity(), [0, 0, 0] | units.m/units.s, in_units = units.AUd) + + self.assertAlmostEqual(particles.center_of_mass(), [0, 0, 0] | units.m, in_units=units.AU) + self.assertAlmostEqual(particles.center_of_mass_velocity(), [0, 0, 0] | units.m/units.s, in_units=units.AUd) # Particles are in center-of-mass(-velocity) coordinates, move them to heliocentric coordinates: self.assertTrue(particles[0].name == "SUN") particles.position -= particles[0].position particles.velocity -= particles[0].velocity - + # Data from Carroll & Ostlie, An introduction to modern astrophysics, 1996 eccentricity = numpy.asarray([0.2056, 0.0068, 0.0167, 0.0934, 0.0483, 0.0560, 0.0461, 0.0097, 0.2482]) semimajor_axis = [0.3871, 0.7233, 1.0000, 1.5237, 5.2028, 9.5388, 19.1914, 30.0611, 39.5294] | units.AU - + self.assertAlmostRelativeEqual(particles[2:-1].position.lengths_squared(), semimajor_axis[1:-1]**2, 1) - + # Somewhat more complicated test for more eccentric orbiters Mercury and Pluto: expected = (constants.G * (particles[1:].mass + particles[0].mass) * semimajor_axis * (1 - eccentricity**2)).sqrt() self.assertAlmostRelativeEqual(particles[1:].position.cross(particles[1:].velocity).lengths(), expected, 2) - - diff --git a/src/amuse/test/suite/ext_tests/test_sph_to_grid.py b/src/amuse/test/suite/ext_tests/test_sph_to_grid.py index 10949f5c30..000daa006f 100644 --- a/src/amuse/test/suite/ext_tests/test_sph_to_grid.py +++ b/src/amuse/test/suite/ext_tests/test_sph_to_grid.py @@ -9,11 +9,12 @@ from amuse.community.gadget2.interface import Gadget2 from amuse.community.fi.interface import Fi + class TestSPH2Grid(TestWithMPI): - + def setup_sph_code(self, sph_code, number_of_particles, L, rho, u): converter = ConvertBetweenGenericAndSiUnits(L, rho, constants.G) - sph_code = sph_code(converter, mode = 'periodic')#, redirection = 'none') + sph_code = sph_code(converter, mode='periodic') # , redirection = 'none') sph_code.parameters.periodic_box_size = 10.0 | units.parsec gas = Particles(number_of_particles) gas.mass = (rho * L**3) / number_of_particles @@ -30,126 +31,127 @@ def setup_sph_code(self, sph_code, number_of_particles, L, rho, u): sph_code.parameters.timestep = 0.1 | generic_unit_system.time gas.h_smooth = L / number_of_particles**(1/3.0) gas.position -= 0.5 * L - + sph_code.gas_particles.add_particles(gas) sph_code.commit_particles() -#~ sph_code.evolve_model(0.01 | units.Myr) +# ~ sph_code.evolve_model(0.01 | units.Myr) return sph_code - + def test1(self): print("Testing convert_SPH_to_grid with Gadget2") number_of_particles = 10000 L = 10.0 | units.parsec rho = 1.14 | units.amu/units.cm**3 u = 5.e11 | units.cm**2 / units.s**2 - + sph_code = self.setup_sph_code(Gadget2, number_of_particles, L, rho, u) - grid = convert_SPH_to_grid(sph_code, (10,10,10)) + grid = convert_SPH_to_grid(sph_code, (10, 10, 10)) sph_code.stop() - - self.assertEqual(grid.shape, (10,10,10)) + + self.assertEqual(grid.shape, (10, 10, 10)) self.assertAlmostEqual(grid.cellsize(), (L/10).as_vector_with_length(3)) - self.assertAlmostEqual(grid[0,0,0].position, (L/20).as_vector_with_length(3)) + self.assertAlmostEqual(grid[0, 0, 0].position, (L/20).as_vector_with_length(3)) self.assertEqual( - grid.contains([[x,x,x] for x in numpy.linspace(-1.0, 11.0, 4)] | units.parsec), + grid.contains([[x, x, x] for x in numpy.linspace(-1.0, 11.0, 4)] | units.parsec), [False, True, True, False]) self.assertAlmostEqual(grid.get_volume(), 1000.0 | units.parsec**3) - + mean_rho = grid.rho.mean() print("Mean density:", mean_rho.as_quantity_in(units.amu/units.cm**3), " - original:", rho) self.assertAlmostRelativeEqual(mean_rho, rho, 1) self.assertAlmostRelativeEqual(grid.energy.mean(), mean_rho * u, 1) self.assertEqual(grid.momentum, 0 * mean_rho * u.sqrt()) - + def test2(self): print("Testing convert_SPH_to_grid with Fi") number_of_particles = 10000 L = 10.0 | units.parsec rho = 1.14 | units.amu/units.cm**3 u = 5.e11 | units.cm**2 / units.s**2 - + sph_code = self.setup_sph_code(Fi, number_of_particles, L, rho, u) - grid = convert_SPH_to_grid(sph_code, (10,10,10)) + grid = convert_SPH_to_grid(sph_code, (10, 10, 10)) sph_code.stop() - - self.assertEqual(grid.shape, (10,10,10)) + + self.assertEqual(grid.shape, (10, 10, 10)) self.assertAlmostEqual(grid.cellsize(), (L/10).as_vector_with_length(3)) - self.assertAlmostEqual(grid[0,0,0].position, (L/20).as_vector_with_length(3)) + self.assertAlmostEqual(grid[0, 0, 0].position, (L/20).as_vector_with_length(3)) self.assertEqual( - grid.contains([[x,x,x] for x in numpy.linspace(-1.0, 11.0, 4)] | units.parsec), + grid.contains([[x, x, x] for x in numpy.linspace(-1.0, 11.0, 4)] | units.parsec), [False, True, True, False]) self.assertAlmostEqual(grid.get_volume(), 1000.0 | units.parsec**3) - + mean_rho = grid.rho.mean() print("Mean density:", mean_rho.as_quantity_in(units.amu/units.cm**3), " - original:", rho) self.assertAlmostRelativeEqual(mean_rho, rho, 1) self.assertAlmostRelativeEqual(grid.energy.mean(), mean_rho * u, 1) self.assertEqual(grid.momentum, 0 * mean_rho * u.sqrt()) - + def test3(self): print("Testing convert_SPH_to_grid with Gadget2 and do_scale") number_of_particles = 10000 L = 10.0 | units.parsec rho = 1.14 | units.amu/units.cm**3 u = 5.e11 | units.cm**2 / units.s**2 - + sph_code = self.setup_sph_code(Gadget2, number_of_particles, L, rho, u) - grid = convert_SPH_to_grid(sph_code, (10,10,10), do_scale = True) + grid = convert_SPH_to_grid(sph_code, (10, 10, 10), do_scale=True) sph_code.stop() - - self.assertEqual(grid.shape, (10,10,10)) + + self.assertEqual(grid.shape, (10, 10, 10)) self.assertAlmostEqual(grid.cellsize(), (L/10).as_vector_with_length(3)) - self.assertAlmostEqual(grid[0,0,0].position, (L/20).as_vector_with_length(3)) + self.assertAlmostEqual(grid[0, 0, 0].position, (L/20).as_vector_with_length(3)) self.assertEqual( - grid.contains([[x,x,x] for x in numpy.linspace(-1.0, 11.0, 4)] | units.parsec), + grid.contains([[x, x, x] for x in numpy.linspace(-1.0, 11.0, 4)] | units.parsec), [False, True, True, False]) self.assertAlmostEqual(grid.get_volume(), 1000.0 | units.parsec**3) - + mean_rho = grid.rho.mean() print("Mean density:", mean_rho.as_quantity_in(units.amu/units.cm**3), " - original:", rho) self.assertAlmostRelativeEqual(mean_rho, rho, 7) self.assertAlmostRelativeEqual(grid.energy.mean(), mean_rho * u, 7) self.assertEqual(grid.momentum, 0 * mean_rho * u.sqrt()) - + def test4(self): print("Testing convert_SPH_to_grid with Fi and do_scale") number_of_particles = 10000 L = 10.0 | units.parsec rho = 1.14 | units.amu/units.cm**3 u = 5.e11 | units.cm**2 / units.s**2 - + sph_code = self.setup_sph_code(Fi, number_of_particles, L, rho, u) - grid = convert_SPH_to_grid(sph_code, (10,10,10), do_scale = True) + grid = convert_SPH_to_grid(sph_code, (10, 10, 10), do_scale=True) sph_code.stop() - - self.assertEqual(grid.shape, (10,10,10)) + + self.assertEqual(grid.shape, (10, 10, 10)) self.assertAlmostEqual(grid.cellsize(), (L/10).as_vector_with_length(3)) - self.assertAlmostEqual(grid[0,0,0].position, (L/20).as_vector_with_length(3)) + self.assertAlmostEqual(grid[0, 0, 0].position, (L/20).as_vector_with_length(3)) self.assertEqual( - grid.contains([[x,x,x] for x in numpy.linspace(-1.0, 11.0, 4)] | units.parsec), + grid.contains([[x, x, x] for x in numpy.linspace(-1.0, 11.0, 4)] | units.parsec), [False, True, True, False]) self.assertAlmostEqual(grid.get_volume(), 1000.0 | units.parsec**3) - + mean_rho = grid.rho.mean() print("Mean density:", mean_rho.as_quantity_in(units.amu/units.cm**3), " - original:", rho) self.assertAlmostRelativeEqual(mean_rho, rho, 7) self.assertAlmostRelativeEqual(grid.energy.mean(), mean_rho * u, 7) self.assertEqual(grid.momentum, 0 * mean_rho * u.sqrt()) - + def test5(self): print("Testing exceptions") + class BogusHydroCode(object): MODE_PERIODIC_BOUNDARIES = "periodic" - def __init__(self, mode = "normal"): + + def __init__(self, mode="normal"): self.mode = mode - - self.assertRaises(AmuseException, convert_SPH_to_grid, BogusHydroCode(), (10,10,10), - expected_message = "Only periodic boundary conditions supported") - - self.assertRaises(AmuseException, convert_SPH_to_grid, BogusHydroCode(mode = 'periodic'), (10,10), - expected_message = "Argument dimensions must contain exactly three numbers") - - self.assertRaises(AmuseException, convert_SPH_to_grid, BogusHydroCode(mode = 'periodic'), (10,10,10), - expected_message = "Unknown hydrodynamics code: BogusHydroCode - don't know whether the " + + self.assertRaises(AmuseException, convert_SPH_to_grid, BogusHydroCode(), (10, 10, 10), + expected_message="Only periodic boundary conditions supported") + + self.assertRaises(AmuseException, convert_SPH_to_grid, BogusHydroCode(mode='periodic'), (10, 10), + expected_message="Argument dimensions must contain exactly three numbers") + + self.assertRaises(AmuseException, convert_SPH_to_grid, BogusHydroCode(mode='periodic'), (10, 10, 10), + expected_message="Unknown hydrodynamics code: BogusHydroCode - don't know whether the " "box runs from 0 to L or from -0.5 L to 0.5 L.") - diff --git a/src/amuse/test/suite/ext_tests/test_sph_to_star.py b/src/amuse/test/suite/ext_tests/test_sph_to_star.py index 71c3f81f61..920cf8e094 100644 --- a/src/amuse/test/suite/ext_tests/test_sph_to_star.py +++ b/src/amuse/test/suite/ext_tests/test_sph_to_star.py @@ -5,7 +5,7 @@ from amuse.test.amusetest import get_path_to_results, TestWithMPI try: from matplotlib import pyplot - from amuse.plot import scatter, xlabel, ylabel, plot,loglog,semilogx,semilogy, sph_particles_plot + from amuse.plot import scatter, xlabel, ylabel, plot, loglog, semilogx, semilogy, sph_particles_plot from amuse.plot import pynbody_column_density_plot, HAS_PYNBODY HAS_MATPLOTLIB = True except ImportError: @@ -29,156 +29,155 @@ class TestSPH2StellarModel(TestWithMPI): - + def new_particles(self): input_file = os.path.join(get_path_to_results(), "test_sph_to_star_input.hdf5") if os.path.exists(input_file): return read_set_from_file(input_file, "hdf5") - + stellar_evolution = EVtwin() - stellar_evolution.particles.add_particle(Particle(mass=1.0|units.MSun)) - stellar_evolution.evolve_model(100.0|units.Myr) + stellar_evolution.particles.add_particle(Particle(mass=1.0 | units.MSun)) + stellar_evolution.evolve_model(100.0 | units.Myr) particles = convert_stellar_model_to_SPH( - stellar_evolution.particles[0], - 500, + stellar_evolution.particles[0], + 500, seed=12345 ).gas_particles stellar_evolution.stop() - - hydrodynamics = Gadget2(ConvertBetweenGenericAndSiUnits(1.0|units.MSun, 1.0|units.RSun, 1.0e3|units.s)) + + hydrodynamics = Gadget2(ConvertBetweenGenericAndSiUnits(1.0 | units.MSun, 1.0 | units.RSun, 1.0e3 | units.s)) hydrodynamics.gas_particles.add_particles(particles) - hydrodynamics.evolve_model(1.0|units.s) + hydrodynamics.evolve_model(1.0 | units.s) hydrodynamics.gas_particles.copy_values_of_attributes_to(["density", "u", "pressure"], particles) hydrodynamics.stop() write_set_to_file(particles, input_file, "hdf5") return particles - + def test1(self): print("Test SPH2StellarModel") converter = SPH2StellarModel(self.new_particles()) model = converter.derive_stellar_structure() - for variable in ['dmass', 'radius', 'rho', 'temperature', 'luminosity', 'X_H', + for variable in ['dmass', 'radius', 'rho', 'temperature', 'luminosity', 'X_H', 'X_He', 'X_C', 'X_N', 'X_O', 'X_Ne', 'X_Mg', 'X_Si', 'X_Fe']: self.assertTrue(hasattr(model, variable)) self.assertEqual(len(getattr(model, variable)), 500) - + def test2(self): print("Test SPH2StellarModel result properties") converter = SPH2StellarModel(self.new_particles()) - model = converter.derive_stellar_structure() # model is from center to surface - self.assertTrue(numpy.all(model.radius[:-1] <= model.radius[1:])) # monotonically increasing - self.assertTrue(numpy.all(model.mass[:-1] <= model.mass[1:])) # monotonically increasing - n=50 # following properties are not strictly monotonic, because of randomness in the particle distribution + model = converter.derive_stellar_structure() # model is from center to surface + self.assertTrue(numpy.all(model.radius[:-1] <= model.radius[1:])) # monotonically increasing + self.assertTrue(numpy.all(model.mass[:-1] <= model.mass[1:])) # monotonically increasing + n = 50 # following properties are not strictly monotonic, because of randomness in the particle distribution self.assertTrue(numpy.all(model.temperature[:-n:n] >= model.temperature[n::n])) self.assertTrue(numpy.all(model.rho[:-n:n] >= model.rho[n::n])) self.assertTrue(numpy.all(model.X_H[:-n:n] <= model.X_H[n::n])) - + def test3(self): print("Test convert_SPH_to_stellar_model with particles_per_zone") model = convert_SPH_to_stellar_model(self.new_particles(), particles_per_zone=50) - for variable in ['dmass', 'radius', 'rho', 'temperature', 'luminosity', 'X_H', + for variable in ['dmass', 'radius', 'rho', 'temperature', 'luminosity', 'X_H', 'X_He', 'X_C', 'X_N', 'X_O', 'X_Ne', 'X_Mg', 'X_Si', 'X_Fe']: self.assertTrue(hasattr(model, variable)) self.assertEqual(len(getattr(model, variable)), 10) - - self.assertTrue(numpy.all(model.radius[:-1] <= model.radius[1:])) # monotonically increasing - self.assertTrue(numpy.all(model.mass[:-1] <= model.mass[1:])) # monotonically increasing + + self.assertTrue(numpy.all(model.radius[:-1] <= model.radius[1:])) # monotonically increasing + self.assertTrue(numpy.all(model.mass[:-1] <= model.mass[1:])) # monotonically increasing self.assertTrue(numpy.all(model.temperature[:-1] >= model.temperature[1:])) self.assertTrue(numpy.all(model.rho[:-1] >= model.rho[1:])) self.assertTrue(numpy.all(model.X_H[:-1] <= model.X_H[1:])) - + lowres_model = convert_SPH_to_stellar_model(self.new_particles(), particles_per_zone=100) - self.assertAlmostRelativeEqual(model.dmass.sum(), 1|units.MSun, 3) - self.assertAlmostRelativeEqual(lowres_model.dmass.sum(), 1|units.MSun, 3) + self.assertAlmostRelativeEqual(model.dmass.sum(), 1 | units.MSun, 3) + self.assertAlmostRelativeEqual(lowres_model.dmass.sum(), 1 | units.MSun, 3) self.assertAlmostRelativeEqual(lowres_model.radius, model.radius[1::2], 7) self.assertAlmostRelativeEqual(lowres_model.X_H, (model.X_H[0::2]+model.X_H[1::2])/2.0, 7) - + def slowtest4(self): print("Test convert_SPH_to_stellar_model result in MESA") stellar_evolution = self.new_instance(MESA) - stellar_evolution.particles.add_particle(Particle(mass=1.0|units.MSun)) # reference particle - stellar_evolution.evolve_model(100.0|units.Myr) - - model = convert_SPH_to_stellar_model(self.new_particles()) # model is from center to surface - stellar_evolution.new_particle_from_model(model, 0.0|units.Myr) + stellar_evolution.particles.add_particle(Particle(mass=1.0 | units.MSun)) # reference particle + stellar_evolution.evolve_model(100.0 | units.Myr) + + model = convert_SPH_to_stellar_model(self.new_particles()) # model is from center to surface + stellar_evolution.new_particle_from_model(model, 0.0 | units.Myr) print(stellar_evolution.particles) self.assertAlmostEqual(stellar_evolution.particles.age, [118.18, 0.0] | units.Myr, 1) - stellar_evolution.evolve_model(200.0|units.Myr) + stellar_evolution.evolve_model(200.0 | units.Myr) print(stellar_evolution.particles) self.assertAlmostEqual(stellar_evolution.particles.age, [204.59, 103.02] | units.Myr, 1) - self.assertAlmostRelativeEqual(stellar_evolution.particles[0].temperature, + self.assertAlmostRelativeEqual(stellar_evolution.particles[0].temperature, stellar_evolution.particles[1].temperature, 2) - self.assertAlmostRelativeEqual(stellar_evolution.particles[0].luminosity, + self.assertAlmostRelativeEqual(stellar_evolution.particles[0].luminosity, stellar_evolution.particles[1].luminosity, 2) stellar_evolution.stop() - + def slowtest5(self): print("Test convert_SPH_to_stellar_model result in EVtwin") stellar_evolution = EVtwin() stellar_evolution.parameters.verbosity = True - stellar_evolution.particles.add_particle(Particle(mass=1.0|units.MSun)) # reference particle - stellar_evolution.evolve_model(100.0|units.Myr) - - model = convert_SPH_to_stellar_model(self.new_particles()) # model is from center to surface - stellar_evolution.new_particle_from_model(model, 0.0|units.Myr) + stellar_evolution.particles.add_particle(Particle(mass=1.0 | units.MSun)) # reference particle + stellar_evolution.evolve_model(100.0 | units.Myr) + + model = convert_SPH_to_stellar_model(self.new_particles()) # model is from center to surface + stellar_evolution.new_particle_from_model(model, 0.0 | units.Myr) print(stellar_evolution.particles) self.assertAlmostEqual(stellar_evolution.particles.age, [100.0, 0.0] | units.Myr, 1) - stellar_evolution.evolve_model(200.0|units.Myr) + stellar_evolution.evolve_model(200.0 | units.Myr) print(stellar_evolution.particles) self.assertAlmostEqual(stellar_evolution.particles.age, [200.0, 100.0] | units.Myr, 1) - self.assertAlmostRelativeEqual(stellar_evolution.particles[0].temperature, + self.assertAlmostRelativeEqual(stellar_evolution.particles[0].temperature, stellar_evolution.particles[1].temperature, 2) - self.assertAlmostRelativeEqual(stellar_evolution.particles[0].luminosity, + self.assertAlmostRelativeEqual(stellar_evolution.particles[0].luminosity, stellar_evolution.particles[1].luminosity, 2) stellar_evolution.stop() - class TestMergerProductToStar(TestWithMPI): - + def slowtest1(self): stellar_evolution = self.new_instance(MESA) - stellar_evolution.particles.add_particles(Particles(2, mass=[1.0, 5.0]|units.MSun)) + stellar_evolution.particles.add_particles(Particles(2, mass=[1.0, 5.0] | units.MSun)) stellar_evolution.evolve_model(10.0 | units.Myr) initial_separation = stellar_evolution.particles.radius.sum() - + sph_particles_1 = convert_stellar_model_to_SPH( - stellar_evolution.particles[0], - 200, + stellar_evolution.particles[0], + 200, seed=12345 ).gas_particles sph_particles_2 = convert_stellar_model_to_SPH( - stellar_evolution.particles[1], - 1000, + stellar_evolution.particles[1], + 1000, seed=12345 ).gas_particles stellar_evolution.stop() - + initial_speed = 10.0 | units.km / units.s - sph_particles_2.x += initial_separation + sph_particles_2.x += initial_separation sph_particles_1.vx += initial_speed all_sph_particles = ParticlesSuperset([sph_particles_1, sph_particles_2]) all_sph_particles.move_to_center() - + t_end = 4.0e3 | units.s print("Evolving to:", t_end) n_steps = 4 - + unit_system_converter = ConvertBetweenGenericAndSiUnits(1.0 | units.RSun, 1.0 | units.MSun, t_end) hydro_code = Gadget2(unit_system_converter) hydro_code.gas_particles.add_particles(all_sph_particles) - + pyplot.ion() for time in [i*t_end/n_steps for i in range(1, n_steps+1)]: hydro_code.evolve_model(time) pyplot.close('all') pyplot.figure() - pynbody_column_density_plot(hydro_code.gas_particles, width=10|units.RSun) + pynbody_column_density_plot(hydro_code.gas_particles, width=10 | units.RSun) pyplot.draw() pyplot.figure() loglog(hydro_code.gas_particles.position.lengths_squared(), hydro_code.gas_particles.pressure, 'bo') pyplot.draw() - + hydro_code.stop() sleep(3) pyplot.ioff() diff --git a/src/amuse/test/suite/ext_tests/test_spherical_model.py b/src/amuse/test/suite/ext_tests/test_spherical_model.py index f6ee411350..d9d5d4093d 100644 --- a/src/amuse/test/suite/ext_tests/test_spherical_model.py +++ b/src/amuse/test/suite/ext_tests/test_spherical_model.py @@ -6,7 +6,7 @@ class TestUniformSphericalDistribution(TestCase): - + def test1(self): instance = UniformSphericalDistribution(4200) x, y, z = instance.result @@ -14,7 +14,7 @@ def test1(self): r_squared = x*x + y*y + z*z self.assertAlmostEqual(r_squared.max(), 1.0, places=4) self.assertAlmostEqual(r_squared.min(), 0.0, places=1) - + def test2(self): numpy.random.seed(12345) for n_i in [1003, 3210]: @@ -26,7 +26,7 @@ def test2(self): r_squared = x*x + y*y + z*z self.assertAlmostEqual(r_squared.max(), 1.0, 2) self.assertAlmostEqual(r_squared.min(), 0.0, 1) - + def test3(self): instance = UniformSphericalDistribution(1234, type="cubic", offset=(0.07974498, 0.77741132, 0.2993995)) x, y, z = instance.result @@ -36,9 +36,9 @@ def test3(self): self.assertAlmostEqual(grid_spacing_x, grid_spacing_y) self.assertAlmostEqual(grid_spacing_x, grid_spacing_z) r_squared = x*x + y*y + z*z - min_r_squared = sum([(grid_spacing_x * min(x,1-x))**2 for x in instance.offset]) + min_r_squared = sum([(grid_spacing_x * min(x, 1-x))**2 for x in instance.offset]) self.assertAlmostEqual(min(r_squared), min_r_squared) - + def test4(self): instance = UniformSphericalDistribution(1234, type="bcc", offset=(0.07974498, 0.77741132, 0.2993995)) x, y, z = instance.result @@ -49,11 +49,11 @@ def test4(self): self.assertAlmostEqual(grid_spacing_x, grid_spacing_z) r_squared = x*x + y*y + z*z min_r_squared = min( - sum([(2*grid_spacing_x * min(x,1-x))**2 for x in instance.offset]), + sum([(2*grid_spacing_x * min(x, 1-x))**2 for x in instance.offset]), sum([(2*grid_spacing_x * abs(x-.5))**2 for x in instance.offset]) ) self.assertAlmostEqual(min(r_squared), min_r_squared) - + def test6(self): print("Test new_uniform_spherical_particle_distribution") particles = new_uniform_spherical_particle_distribution(14321, 1 | units.m, 1 | units.kg, type="cubic") @@ -65,62 +65,61 @@ def test6(self): select_half_radius = numpy.where(r_squared < (0.5 | units.m)**2) self.assertAlmostEqual(particles.mass[select_half_radius].sum(), 1.0/8.0 | units.kg, places=3) self.assertAlmostEqual(particles.center_of_mass(), [0.0, 0.0, 0.0] | units.m, places=2) - + def test7(self): print("Test new_spherical_particle_distribution with total_mass specified") - particles = new_spherical_particle_distribution(4200, radii = [2,4,3,1] | units.m, - densities = [80, 30, 50, 100] | (units.kg/units.m**3), total_mass = 10000 | units.kg) + particles = new_spherical_particle_distribution(4200, radii=[2, 4, 3, 1] | units.m, + densities=[80, 30, 50, 100] | (units.kg/units.m**3), total_mass=10000 | units.kg) self.assertEqual(len(particles), 4200) self.assertAlmostEqual(particles.total_mass(), 10000 | units.kg) r_squared = particles.position.lengths_squared() - self.assertTrue(numpy.all( r_squared < (4.0 | units.m)**2)) - self.assertFalse(numpy.all( r_squared < (3.5 | units.m)**2 )) + self.assertTrue(numpy.all(r_squared < (4.0 | units.m)**2)) + self.assertFalse(numpy.all(r_squared < (3.5 | units.m)**2)) self.assertAlmostEqual(particles.center_of_mass(), [0.0, 0.0, 0.0] | units.m, places=2) - + def test8(self): print("Test new_spherical_particle_distribution without radii, densities tables") - + def my_density_func(radius): return (1 + radius.value_in(units.m)**2)**-2.5 | units.kg/units.m**3 - - self.assertRaises(AmuseException, new_spherical_particle_distribution, 42, - radial_density_func = my_density_func, total_mass = 10000 | units.kg, expected_message = - "Using an arbitrary radial density function is not yet supported. Radius and density tables must be passed instead.") - + + self.assertRaises(AmuseException, new_spherical_particle_distribution, 42, + radial_density_func=my_density_func, total_mass=10000 | units.kg, expected_message="Using an arbitrary radial density function is not yet supported. Radius and density tables must be passed instead.") + def test9(self): print("Test new_spherical_particle_distribution without total_mass") - rad = [2,4,3,1] | units.m + rad = [2, 4, 3, 1] | units.m rho = [80, 30, 50, 100] | (units.kg/units.m**3) - - particles = new_spherical_particle_distribution(142, radii = rad, - densities = rho, size = 1.5 | units.m) + + particles = new_spherical_particle_distribution(142, radii=rad, + densities=rho, size=1.5 | units.m) self.assertEqual(len(particles), 142) - self.assertAlmostEqual(particles.total_mass(), - numpy.pi * 4.0/3.0 *(100 * 1.0**3 + 80*(1.5**3-1.0**3)) | units.kg) + self.assertAlmostEqual(particles.total_mass(), + numpy.pi * 4.0/3.0 * (100 * 1.0**3 + 80*(1.5**3-1.0**3)) | units.kg) r_squared = particles.position.lengths_squared() - self.assertTrue(numpy.all( r_squared < (1.5 | units.m)**2)) - self.assertFalse(numpy.all( r_squared < (1.4 | units.m)**2 )) - - particles = new_spherical_particle_distribution(14200, radii = rad, densities = rho) + self.assertTrue(numpy.all(r_squared < (1.5 | units.m)**2)) + self.assertFalse(numpy.all(r_squared < (1.4 | units.m)**2)) + + particles = new_spherical_particle_distribution(14200, radii=rad, densities=rho) self.assertEqual(len(particles), 14200) interpolator = EnclosedMassInterpolator(rad, rho) self.assertAlmostEqual(particles.total_mass(), interpolator.get_enclosed_mass(max(rad))) r_squared = particles.position.lengths_squared() - self.assertTrue(numpy.all( r_squared < max(rad)**2 )) - self.assertFalse(numpy.all( r_squared < (0.9*max(rad))**2 )) + self.assertTrue(numpy.all(r_squared < max(rad)**2)) + self.assertFalse(numpy.all(r_squared < (0.9*max(rad))**2)) self.assertAlmostEqual(particles.center_of_mass(), [0.0, 0.0, 0.0] | units.m, places=2) - + def test10(self): print("Test new_uniform_spherical_particle_distribution, glass") numpy.random.seed(12345) # setting target_rms to 30% for test speed-up - particles = new_uniform_spherical_particle_distribution(1421, 1|units.m, 1|units.kg, + particles = new_uniform_spherical_particle_distribution(1421, 1 | units.m, 1 | units.kg, type="glass", target_rms=0.3) self.assertEqual(len(particles), 1421) r_squared = particles.position.lengths_squared() self.assertAlmostEqual(r_squared.amax(), 1.0 | units.m**2, places=4) self.assertAlmostEqual(r_squared.amin(), 0.0 | units.m**2, places=1) - + def test11(self): print("Test new_uniform_spherical_particle_distribution, sobol sequence") particles = new_uniform_spherical_particle_distribution(14321, 1 | units.m, 1 | units.kg, type="sobol") @@ -132,10 +131,10 @@ def test11(self): select_half_radius = numpy.where(r_squared < (0.5 | units.m)**2) self.assertAlmostEqual(particles.mass[select_half_radius].sum(), 1.0/8.0 | units.kg, places=2) self.assertAlmostEqual(particles.center_of_mass(), [0.0, 0.0, 0.0] | units.m, places=2) - + def test12(self): print("Test new_uniform_spherical_particle_distribution, face-centered cubic") - particles = new_uniform_spherical_particle_distribution(14321, 1|units.m, 1|units.kg, type="fcc") + particles = new_uniform_spherical_particle_distribution(14321, 1 | units.m, 1 | units.kg, type="fcc") self.assertEqual(len(particles), 14321) r_squared = particles.position.lengths_squared() self.assertAlmostEqual(r_squared.amax(), 1.0 | units.m**2, places=4) @@ -144,18 +143,18 @@ def test12(self): select_half_radius = numpy.where(r_squared < (0.5 | units.m)**2) self.assertAlmostEqual(particles.mass[select_half_radius].sum(), 1.0/8.0 | units.kg, places=2) self.assertAlmostEqual(particles.center_of_mass(), [0.0, 0.0, 0.0] | units.m, places=2) - + def test13(self): print("Test new_spherical_particle_distribution, particle at the origin") - particles = new_spherical_particle_distribution(14321, radii = [2,4,3,1] | units.m, - densities = [80, 30, 50, 100] | (units.kg/units.m**3), - type="bcc", offset=[0,0,0]) + particles = new_spherical_particle_distribution(14321, radii=[2, 4, 3, 1] | units.m, + densities=[80, 30, 50, 100] | (units.kg/units.m**3), + type="bcc", offset=[0, 0, 0]) r_squared = particles.position.lengths_squared() self.assertAlmostEqual(r_squared.amax(), 16.0 | units.m**2, 2) self.assertEqual(r_squared.amin(), 0.0 | units.m**2) self.assertAlmostEqual(particles.center_of_mass(), [0.0, 0.0, 0.0] | units.m, places=2) self.assertEqual(particles[0].position, [0.0, 0.0, 0.0] | units.m) - + def test14(self): print("Test new_plummer_spatial_distribution") particles = new_plummer_spatial_distribution(1401, type="fcc") @@ -165,19 +164,19 @@ def test14(self): self.assertAlmostEqual(particles.total_mass(), 1 | nbody_system.mass) self.assertAlmostEqual(particles.virial_radius(), 1 | nbody_system.length, places=2) self.assertAlmostEqual(particles.center_of_mass(), [0.0, 0.0, 0.0] | nbody_system.length, places=1) - + def test15(self): print("Test new_plummer_spatial_distribution, SI units") - particles = new_plummer_spatial_distribution(1401, - virial_radius = 3 | units.m, - total_mass = 7 | units.kg, + particles = new_plummer_spatial_distribution(1401, + virial_radius=3 | units.m, + total_mass=7 | units.kg, type="fcc") self.assertEqual(len(particles), 1401) - r_halfmass_plummer = 3*numpy.pi/16.0*(0.5**(-2/3.)-1)**-0.5 * (3|units.m) + r_halfmass_plummer = 3*numpy.pi/16.0*(0.5**(-2/3.)-1)**-0.5 * (3 | units.m) self.assertAlmostEqual(particles[700].position.length(), r_halfmass_plummer, places=1) - self.assertAlmostEqual(particles.total_mass(), 7|units.kg) - self.assertAlmostEqual(particles.virial_radius(), 3|units.m, places=2) - + self.assertAlmostEqual(particles.total_mass(), 7 | units.kg) + self.assertAlmostEqual(particles.virial_radius(), 3 | units.m, places=2) + def test16(self): print("Test new_plummer_spatial_distribution, mass_cutoff") numpy.random.seed(12345) @@ -189,10 +188,10 @@ def test16(self): particles = new_plummer_spatial_distribution(1001, mass_cutoff=0.5, type="fcc") r_squared = particles.position.lengths_squared() self.assertAlmostEqual(r_squared.amax().sqrt(), r_halfmass_plummer, places=2) - + self.assertAlmostEqual(particles.total_mass(), 1 | nbody_system.mass) self.assertAlmostEqual(particles.center_of_mass(), [0.0, 0.0, 0.0] | nbody_system.length, places=1) - + def test17(self): print("Test new_gas_plummer_distribution") particles = new_gas_plummer_distribution(1401, type="fcc") @@ -204,22 +203,22 @@ def test17(self): self.assertAlmostEqual(particles.center_of_mass(), [0.0, 0.0, 0.0] | nbody_system.length, places=1) self.assertAlmostEqual(particles.kinetic_energy(), 0 | nbody_system.energy) self.assertAlmostEqual(particles.thermal_energy(), 0.25 | nbody_system.energy) - + def test18(self): print("Test new_gas_plummer_distribution, SI units") particles = new_gas_plummer_distribution(1801, - virial_radius = 0.36 | units.m, - total_mass = 6 | units.kg, + virial_radius=0.36 | units.m, + total_mass=6 | units.kg, type="sobol") self.assertEqual(len(particles), 1801) - r_halfmass_plummer = 3*numpy.pi/16.0*(0.5**(-2/3.)-1)**-0.5 * (0.36|units.m) + r_halfmass_plummer = 3*numpy.pi/16.0*(0.5**(-2/3.)-1)**-0.5 * (0.36 | units.m) self.assertAlmostEqual(particles[900].position.length(), r_halfmass_plummer, places=1) - self.assertAlmostEqual(particles.total_mass(), 6|units.kg) - self.assertAlmostEqual(particles.virial_radius(), 0.36|units.m, places=2) + self.assertAlmostEqual(particles.total_mass(), 6 | units.kg) + self.assertAlmostEqual(particles.virial_radius(), 0.36 | units.m, places=2) self.assertAlmostEqual(particles.center_of_mass(), [0.0, 0.0, 0.0] | units.m, places=1) self.assertAlmostEqual(particles.kinetic_energy(), 0 | units.J) self.assertAlmostEqual(particles.thermal_energy()/constants.G, 0.25 | (units.kg**2 / units.cm)) - + def test19(self): print("Test new_plummer_distribution") numpy.random.seed(12345) @@ -232,22 +231,22 @@ def test19(self): self.assertAlmostEqual(particles.center_of_mass(), [0.0, 0.0, 0.0] | nbody_system.length, places=1) self.assertAlmostEqual(particles.center_of_mass_velocity(), [0.0, 0.0, 0.0] | nbody_system.speed, places=1) self.assertAlmostEqual(particles.kinetic_energy(), 0.25 | nbody_system.energy) - + def test20(self): print("Test new_plummer_distribution, SI units") numpy.random.seed(12345) - particles = new_plummer_distribution(1401, - virial_radius = 0.025 | units.kpc, - total_mass = 5 | units.MSun, + particles = new_plummer_distribution(1401, + virial_radius=0.025 | units.kpc, + total_mass=5 | units.MSun, type="sobol") self.assertEqual(len(particles), 1401) - r_halfmass_plummer = 3*numpy.pi/16.0*(0.5**(-2/3.)-1)**-0.5 * (0.025|units.kpc) + r_halfmass_plummer = 3*numpy.pi/16.0*(0.5**(-2/3.)-1)**-0.5 * (0.025 | units.kpc) self.assertAlmostEqual(particles[700].position.length(), r_halfmass_plummer, places=1) - self.assertAlmostEqual(particles.total_mass(), 5|units.MSun) - self.assertAlmostEqual(particles.virial_radius(), (0.025|units.kpc), places=2) - self.assertAlmostEqual(particles.center_of_mass_velocity(), [0.0, 0.0, 0.0]|units.kms, places=2) + self.assertAlmostEqual(particles.total_mass(), 5 | units.MSun) + self.assertAlmostEqual(particles.virial_radius(), (0.025 | units.kpc), places=2) + self.assertAlmostEqual(particles.center_of_mass_velocity(), [0.0, 0.0, 0.0] | units.kms, places=2) self.assertAlmostEqual(particles.kinetic_energy()/constants.G, 0.25 | (units.MSun**2 / units.parsec)) - + def test21(self): print("Test docs") self.assertTrue("face_centered_cubic" in new_uniform_spherical_particle_distribution.__doc__) @@ -255,69 +254,61 @@ def test21(self): self.assertTrue("face_centered_cubic" in new_plummer_spatial_distribution.__doc__) self.assertTrue("face_centered_cubic" in new_gas_plummer_distribution.__doc__) self.assertTrue("face_centered_cubic" in new_plummer_distribution.__doc__) - + class TestEnclosedMassInterpolator(TestCase): - + def test1(self): instance = EnclosedMassInterpolator() self.assertFalse(instance.initialized) - instance.initialize([2,4,3,1] | units.m, [80, 30, 50, 100] | (units.kg/units.m**3)) + instance.initialize([2, 4, 3, 1] | units.m, [80, 30, 50, 100] | (units.kg/units.m**3)) self.assertTrue(instance.initialized) - self.assertEqual(instance.radii, [0,1,2,3,4] | units.m) - self.assertEqual(instance.densities, [100,80,50,30] | (units.kg/units.m**3)) + self.assertEqual(instance.radii, [0, 1, 2, 3, 4] | units.m) + self.assertEqual(instance.densities, [100, 80, 50, 30] | (units.kg/units.m**3)) self.assertEqual(instance.enclosed_mass[0], 0.0 | units.kg) - self.assertEqual(instance.enclosed_mass[1], + self.assertEqual(instance.enclosed_mass[1], numpy.pi * 4.0/3.0 * instance.densities[0] * instance.radii[1]**3) - self.assertEqual(instance.get_enclosed_mass(1.0 | units.m), + self.assertEqual(instance.get_enclosed_mass(1.0 | units.m), numpy.pi * 4.0/3.0 * instance.densities[0] * (1.0 | units.m)**3) - self.assertEqual(instance.get_enclosed_mass(0.5 | units.m), + self.assertEqual(instance.get_enclosed_mass(0.5 | units.m), numpy.pi * 4.0/3.0 * instance.densities[0] * (0.5 | units.m)**3) - self.assertEqual(instance.get_enclosed_mass(1.5 | units.m), + self.assertEqual(instance.get_enclosed_mass(1.5 | units.m), numpy.pi * 4.0/3.0 * (100*1.0**3 + 80*(1.5**3-1.0**3)) | units.kg) del instance - + def test2(self): interpolator = EnclosedMassInterpolator() - self.assertRaises(AmuseException, interpolator.get_enclosed_mass, 0.0 | units.m, - expected_message = "Can't calculate enclosed mass: interpolator is not initialized") - interpolator.initialize([2,4,3,1] | units.m, [80, 30, 50, 100] | (units.kg/units.m**3)) - self.assertEqual(numpy.pi * 4.0/3.0 * 100 * 0.3**3 | units.kg, + self.assertRaises(AmuseException, interpolator.get_enclosed_mass, 0.0 | units.m, + expected_message="Can't calculate enclosed mass: interpolator is not initialized") + interpolator.initialize([2, 4, 3, 1] | units.m, [80, 30, 50, 100] | (units.kg/units.m**3)) + self.assertEqual(numpy.pi * 4.0/3.0 * 100 * 0.3**3 | units.kg, interpolator.get_enclosed_mass(0.3 | units.m)) - self.assertEqual([0.0, numpy.pi * 4.0/3.0 * 100 * 0.3**3] | units.kg, + self.assertEqual([0.0, numpy.pi * 4.0/3.0 * 100 * 0.3**3] | units.kg, interpolator.get_enclosed_mass([0.0, 0.3] | units.m)) - self.assertEqual(numpy.pi * 4.0/3.0 * 100 * 1.0**3 | units.kg, + self.assertEqual(numpy.pi * 4.0/3.0 * 100 * 1.0**3 | units.kg, interpolator.get_enclosed_mass(1.0 | units.m)) - self.assertEqual(numpy.pi * 4.0/3.0 *(100 * 1.0**3 + 80*(1.5**3-1.0**3)) | units.kg, + self.assertEqual(numpy.pi * 4.0/3.0 * (100 * 1.0**3 + 80*(1.5**3-1.0**3)) | units.kg, interpolator.get_enclosed_mass(1.5 | units.m)) - self.assertRaises(AmuseException, interpolator.get_enclosed_mass, -0.5 | units.m, expected_message = - "Can't find a valid index. [-0.5] m is not in the range [0.0 m, 4.0 m].") - self.assertRaises(AmuseException, interpolator.get_enclosed_mass, 4.5 | units.m, expected_message = - "Can't find a valid index. [4.5] m is not in the range [0.0 m, 4.0 m].") - self.assertRaises(AmuseException, interpolator.get_enclosed_mass, [2.5, 3.5, 4.5] | units.m, expected_message = - "Can't find a valid index. [4.5] m is not in the range [0.0 m, 4.0 m].") - self.assertRaises(AmuseException, interpolator.get_enclosed_mass, [-0.5, 3.5, 4.5] | units.m, expected_message = - "Can't find a valid index. [-0.5, 4.5] m is not in the range [0.0 m, 4.0 m].") + self.assertRaises(AmuseException, interpolator.get_enclosed_mass, -0.5 | units.m, expected_message="Can't find a valid index. [-0.5] m is not in the range [0.0 m, 4.0 m].") + self.assertRaises(AmuseException, interpolator.get_enclosed_mass, 4.5 | units.m, expected_message="Can't find a valid index. [4.5] m is not in the range [0.0 m, 4.0 m].") + self.assertRaises(AmuseException, interpolator.get_enclosed_mass, [2.5, 3.5, 4.5] | units.m, expected_message="Can't find a valid index. [4.5] m is not in the range [0.0 m, 4.0 m].") + self.assertRaises(AmuseException, interpolator.get_enclosed_mass, [-0.5, 3.5, 4.5] | units.m, expected_message="Can't find a valid index. [-0.5, 4.5] m is not in the range [0.0 m, 4.0 m].") del interpolator - + def test3(self): interpolator = EnclosedMassInterpolator() - self.assertRaises(AmuseException, interpolator.get_radius_for_enclosed_mass, 0.0 | units.kg, - expected_message = "Can't calculate radius for enclosed mass: interpolator is not initialized") - interpolator.initialize([2,4,3,1] | units.m, [80, 30, 50, 100] | (units.kg/units.m**3)) - self.assertEqual(0.3 | units.m, + self.assertRaises(AmuseException, interpolator.get_radius_for_enclosed_mass, 0.0 | units.kg, + expected_message="Can't calculate radius for enclosed mass: interpolator is not initialized") + interpolator.initialize([2, 4, 3, 1] | units.m, [80, 30, 50, 100] | (units.kg/units.m**3)) + self.assertEqual(0.3 | units.m, interpolator.get_radius_for_enclosed_mass(numpy.pi * 4.0/3.0 * 100 * 0.3**3 | units.kg)) - self.assertEqual([0.0, 0.3] | units.m, + self.assertEqual([0.0, 0.3] | units.m, interpolator.get_radius_for_enclosed_mass([0.0, numpy.pi * 4.0/3.0 * 100 * 0.3**3] | units.kg)) - self.assertEqual(1.0 | units.m, + self.assertEqual(1.0 | units.m, interpolator.get_radius_for_enclosed_mass(numpy.pi * 4.0/3.0 * 100 * 1.0**3 | units.kg)) - self.assertEqual(1.5 | units.m, - interpolator.get_radius_for_enclosed_mass(numpy.pi * 4.0/3.0 *(100 * 1.0**3 + 80*(1.5**3-1.0**3)) | units.kg)) - self.assertRaises(AmuseException, interpolator.get_radius_for_enclosed_mass, -0.5 | units.kg, expected_message = - "Can't find a valid index. [-0.5] kg is not in the range [0.0 kg, 11393.509357 kg].") - self.assertRaises(AmuseException, interpolator.get_radius_for_enclosed_mass, 12000 | units.kg, expected_message = - "Can't find a valid index. [12000] kg is not in the range [0.0 kg, 11393.509357 kg].") - self.assertRaises(AmuseException, interpolator.get_radius_for_enclosed_mass, [-0.5, 1.0, 12000] | units.kg, expected_message = - "Can't find a valid index. [-0.5, 12000.0] kg is not in the range [0.0 kg, 11393.509357 kg].") + self.assertEqual(1.5 | units.m, + interpolator.get_radius_for_enclosed_mass(numpy.pi * 4.0/3.0 * (100 * 1.0**3 + 80*(1.5**3-1.0**3)) | units.kg)) + self.assertRaises(AmuseException, interpolator.get_radius_for_enclosed_mass, -0.5 | units.kg, expected_message="Can't find a valid index. [-0.5] kg is not in the range [0.0 kg, 11393.509357 kg].") + self.assertRaises(AmuseException, interpolator.get_radius_for_enclosed_mass, 12000 | units.kg, expected_message="Can't find a valid index. [12000] kg is not in the range [0.0 kg, 11393.509357 kg].") + self.assertRaises(AmuseException, interpolator.get_radius_for_enclosed_mass, [-0.5, 1.0, 12000] | units.kg, expected_message="Can't find a valid index. [-0.5, 12000.0] kg is not in the range [0.0 kg, 11393.509357 kg].") del interpolator - diff --git a/src/amuse/test/suite/ext_tests/test_star_to_sph.py b/src/amuse/test/suite/ext_tests/test_star_to_sph.py index 7affee161c..18f6424855 100644 --- a/src/amuse/test/suite/ext_tests/test_star_to_sph.py +++ b/src/amuse/test/suite/ext_tests/test_star_to_sph.py @@ -26,73 +26,74 @@ from amuse.datamodel import ParticlesSuperset from amuse.datamodel import Grid + class TestStellarModel2SPH(TestWithMPI): - + class StarParticleWithStructure(Particle): - - def __init__(self, number_of_species = 3, **keyword_arguments): + + def __init__(self, number_of_species=3, **keyword_arguments): Particle.__init__(self, **keyword_arguments) self.particles_set._private.number_of_species = number_of_species self.mass = 4.0/3.0 * numpy.pi * (9.0 / 8.0) | units.MSun self.radius = 1.0 | units.RSun - + def get_number_of_zones(self): return 4 - + def get_number_of_species(self): return self.particles_set._private.number_of_species - - def get_names_of_species(self, number_of_species = None): + + def get_names_of_species(self, number_of_species=None): return (['h1', 'he3', 'he4', 'c12'])[:int(self.particles_set._private.number_of_species)] - - def get_masses_of_species(self, number_of_species = None): + + def get_masses_of_species(self, number_of_species=None): return ([1.0078250, 3.0160293, 4.0026032, 12.0] | units.amu)[:int(self.particles_set._private.number_of_species)] - - def get_mass_profile(self, number_of_zones = None): + + def get_mass_profile(self, number_of_zones=None): return numpy.asarray([2.0, 14.0, 112.0, 448.0]) / sum([2.0, 14.0, 112.0, 448.0]) - - def get_density_profile(self, number_of_zones = None): + + def get_density_profile(self, number_of_zones=None): return [2.0, 2.0, 2.0, 1.0] | units.MSun/units.RSun**3 - - def get_radius_profile(self, number_of_zones = None): + + def get_radius_profile(self, number_of_zones=None): return ([1.0, 2.0, 4.0, 8.0] | units.RSun) / 8.0 - - def get_temperature_profile(self, number_of_zones = None): + + def get_temperature_profile(self, number_of_zones=None): return [1e7, 1e6, 1e5, 1e4] | units.K - - def get_luminosity_profile(self, number_of_zones = None): + + def get_luminosity_profile(self, number_of_zones=None): return [1.0, 1.0, 1.0, 1.0] | units.LSun - - def get_mu_profile(self, number_of_zones = None): + + def get_mu_profile(self, number_of_zones=None): return [0.8, 0.6, 0.6, 1.3] | units.amu - - def get_chemical_abundance_profiles(self, number_of_zones = None, number_of_species = None): - return numpy.asarray([[0.0, 0.7, 0.7, 0.7], [0.05, 0.01, 0.01, 0.01], [0.95, 0.29, 0.29, 0.29], - [0.0, 0.0, 0.0, 0.0]] )[:int(self.particles_set._private.number_of_species)] - + + def get_chemical_abundance_profiles(self, number_of_zones=None, number_of_species=None): + return numpy.asarray([[0.0, 0.7, 0.7, 0.7], [0.05, 0.01, 0.01, 0.01], [0.95, 0.29, 0.29, 0.29], + [0.0, 0.0, 0.0, 0.0]])[:int(self.particles_set._private.number_of_species)] + def test1(self): star = self.StarParticleWithStructure() number_of_zones = star.get_number_of_zones() - delta_mass = star.mass * star.get_mass_profile() + delta_mass = star.mass * star.get_mass_profile() outer_radius = star.get_radius_profile() inner_radius = [0.0] | units.RSun inner_radius.extend(outer_radius[:-1]) delta_radius_cubed = (outer_radius**3 - inner_radius**3) - self.assertAlmostEqual(star.get_density_profile() / (delta_mass/(4./3.*numpy.pi*delta_radius_cubed)), + self.assertAlmostEqual(star.get_density_profile() / (delta_mass/(4./3.*numpy.pi*delta_radius_cubed)), [1]*number_of_zones) - + def test2(self): star = self.StarParticleWithStructure() - number_of_sph_particles = 100 # only few particles for test speed-up + number_of_sph_particles = 100 # only few particles for test speed-up converter = StellarModel2SPH(star, number_of_sph_particles, seed=12345) converter.retrieve_stellar_structure() - self.assertAlmostEqual(converter.specific_internal_energy_profile, - [155896.35894, 20786.18119, 2078.61812, 95.93622] | (units.km/units.s)**2, places = 1) - + self.assertAlmostEqual(converter.specific_internal_energy_profile, + [155896.35894, 20786.18119, 2078.61812, 95.93622] | (units.km/units.s)**2, places=1) + def test3(self): print("Test interpolate_hydro_quantities") star = self.StarParticleWithStructure() - number_of_sph_particles = 100 # only few particles for test speed-up + number_of_sph_particles = 100 # only few particles for test speed-up converter = StellarModel2SPH(star, number_of_sph_particles, seed=12345) converter.retrieve_stellar_structure() outer_radii = star.get_radius_profile() @@ -102,54 +103,54 @@ def test3(self): self.assertEqual(inner_radii, [0.0, 0.125, 0.25, 0.5] | units.RSun) radial_positions = (outer_radii + inner_radii) / 2 int_specific_internal_energy, int_composition, int_mu = converter.interpolate_internal_energy(radial_positions) - self.assertEqual( converter.specific_internal_energy_profile, int_specific_internal_energy) - + self.assertEqual(converter.specific_internal_energy_profile, int_specific_internal_energy) + def test4(self): print("Test convert_stellar_model_to_SPH") star = self.StarParticleWithStructure() - number_of_sph_particles = 100 # only few particles for test speed-up + number_of_sph_particles = 100 # only few particles for test speed-up sph_particles = convert_stellar_model_to_SPH( - star, - number_of_sph_particles, - seed = 12345 + star, + number_of_sph_particles, + seed=12345 ).gas_particles self.assertEqual(len(sph_particles), number_of_sph_particles) self.assertAlmostEqual(sph_particles.mass.sum(), star.mass) - self.assertAlmostEqual(sph_particles.center_of_mass(), [0,0,0] | units.RSun, 1) + self.assertAlmostEqual(sph_particles.center_of_mass(), [0, 0, 0] | units.RSun, 1) self.assertIsOfOrder(max(sph_particles.x), star.radius) aa = sph_particles.composition.sum(axis=1) - numpy.asarray([1.0]*number_of_sph_particles) self.assertAlmostEqual(sph_particles.composition.sum(axis=1), 1.0) - self.assertTrue(numpy.all( sph_particles.h1 <= 0.7001 )) - self.assertTrue(numpy.all( sph_particles.he3 <= 0.0501 )) - self.assertTrue(numpy.all( sph_particles.he4 >= 0.2899 )) - self.assertTrue(numpy.all( sph_particles.h1[1:] - sph_particles.h1[:-1] >= -0.0001 )) - self.assertTrue(numpy.all( sph_particles.he3[1:] - sph_particles.he3[:-1] <= 0.0001 )) - self.assertTrue(numpy.all( sph_particles.he4[1:] - sph_particles.he4[:-1] <= 0.0001 )) - + self.assertTrue(numpy.all(sph_particles.h1 <= 0.7001)) + self.assertTrue(numpy.all(sph_particles.he3 <= 0.0501)) + self.assertTrue(numpy.all(sph_particles.he4 >= 0.2899)) + self.assertTrue(numpy.all(sph_particles.h1[1:] - sph_particles.h1[:-1] >= -0.0001)) + self.assertTrue(numpy.all(sph_particles.he3[1:] - sph_particles.he3[:-1] <= 0.0001)) + self.assertTrue(numpy.all(sph_particles.he4[1:] - sph_particles.he4[:-1] <= 0.0001)) + def test5(self): print("Test evolving created SPH particles in Gadget") stellar_evolution = self.new_instance_of_an_optional_code(MESA) if stellar_evolution is None: print("MESA was not built. Skipping test.") return - stars = Particles(1) + stars = Particles(1) stars.mass = 1.0 | units.MSun - stellar_evolution.initialize_code() + stellar_evolution.initialize_code() stellar_evolution.particles.add_particles(stars) stellar_evolution.commit_particles() - number_of_sph_particles = 200 # only few particles for test speed-up + number_of_sph_particles = 200 # only few particles for test speed-up sph_particles = convert_stellar_model_to_SPH( - stellar_evolution.particles[0], - number_of_sph_particles, + stellar_evolution.particles[0], + number_of_sph_particles, seed=12345 ).gas_particles self.assertEqual(len(sph_particles), number_of_sph_particles) self.assertAlmostEqual(sph_particles.mass.sum(), stars.mass) - self.assertAlmostEqual(sph_particles.center_of_mass(), [0,0,0] | units.RSun, 1) + self.assertAlmostEqual(sph_particles.center_of_mass(), [0, 0, 0] | units.RSun, 1) self.assertIsOfOrder(max(sph_particles.x), 1 | units.RSun) self.assertAlmostEqual(sph_particles.h1, 0.7, places=2) stellar_evolution.stop() - + time_end = 1.0 | units.s unit_converter = ConvertBetweenGenericAndSiUnits(1.0 | units.RSun, 1.0 | units.MSun, time_end*1000) hydrodynamics = Gadget2(unit_converter) @@ -157,46 +158,46 @@ def test5(self): hydrodynamics.gas_particles.add_particles(sph_particles) hydrodynamics.evolve_model(time_end) hydrodynamics.stop() - + def slowtest6(self): print("Compare composition profile of stellar model to SPH model") stellar_evolution = self.new_instance(MESA) if stellar_evolution is None: print("MESA was not built. Skipping test.") return - stars = Particles(1) + stars = Particles(1) stars.mass = 1.0 | units.MSun - stellar_evolution.initialize_code() + stellar_evolution.initialize_code() stellar_evolution.particles.add_particles(stars) stellar_evolution.commit_particles() stellar_evolution.evolve_model(5.0 | units.Gyr) - number_of_sph_particles = 1000 # only few particles for test speed-up + number_of_sph_particles = 1000 # only few particles for test speed-up composition = stellar_evolution.particles[0].get_chemical_abundance_profiles() outer_radii = stellar_evolution.particles[0].get_radius_profile() outer_radii.prepend(0.0 | units.m) midpoints = (outer_radii[:-1] + outer_radii[1:]) / 2 sph_particles = convert_stellar_model_to_SPH( - stellar_evolution.particles[0], - number_of_sph_particles, + stellar_evolution.particles[0], + number_of_sph_particles, seed=12345 ).gas_particles temperature = stellar_evolution.particles[0].get_temperature_profile() - mu = stellar_evolution.particles[0].get_mu_profile() + mu = stellar_evolution.particles[0].get_mu_profile() specific_internal_energy = (1.5 * constants.kB * temperature / mu).as_quantity_in(units.J/units.kg) stellar_evolution.stop() sph_midpoints = sph_particles.position.lengths() - + composition_comparison_plot( - midpoints, composition[0], - sph_midpoints, sph_particles.h1, + midpoints, composition[0], + sph_midpoints, sph_particles.h1, os.path.join(get_path_to_results(), "star2sph_test_6_composition_h1.png") ) composition_comparison_plot( - midpoints, composition[2], - sph_midpoints, sph_particles.he4, + midpoints, composition[2], + sph_midpoints, sph_particles.he4, os.path.join(get_path_to_results(), "star2sph_test_6_composition_he4.png") ) - + time_end = 4000.0 | units.s unit_converter = ConvertBetweenGenericAndSiUnits(1.0 | units.RSun, 1.0 | units.MSun, time_end) hydrodynamics = Gadget2(unit_converter) @@ -206,154 +207,154 @@ def slowtest6(self): sph_midpoints = hydrodynamics.gas_particles.position.lengths() hydrodynamics.stop() composition_comparison_plot( - midpoints, composition[0], - sph_midpoints, sph_particles.h1, + midpoints, composition[0], + sph_midpoints, sph_particles.h1, os.path.join(get_path_to_results(), "star2sph_test_6_relaxed_composition_h1.png") ) composition_comparison_plot( - midpoints, composition[2], - sph_midpoints, sph_particles.he4, + midpoints, composition[2], + sph_midpoints, sph_particles.he4, os.path.join(get_path_to_results(), "star2sph_test_6_relaxed_composition_he4.png") ) internal_energy_comparison_plot( - midpoints, specific_internal_energy, - sph_midpoints, sph_particles.u, + midpoints, specific_internal_energy, + sph_midpoints, sph_particles.u, os.path.join(get_path_to_results(), "star2sph_test_6_relaxed_composition_u.png") ) - + def slowtest7(self): print("Relaxation of stellar evolution model (Gadget2)") stellar_evolution = self.new_instance(MESA) if stellar_evolution is None: print("MESA was not built. Skipping test.") return - stars = Particles(1) + stars = Particles(1) stars.mass = 1.0 | units.MSun - stellar_evolution.initialize_code() + stellar_evolution.initialize_code() stellar_evolution.particles.add_particles(stars) stellar_evolution.commit_particles() stellar_evolution.evolve_model(10.0 | units.Gyr) - + composition = stellar_evolution.particles[0].get_chemical_abundance_profiles() outer_radii = stellar_evolution.particles[0].get_radius_profile() outer_radii.prepend(0.0 | units.m) midpoints = (outer_radii[:-1] + outer_radii[1:]) / 2 temperature = stellar_evolution.particles[0].get_temperature_profile() - mu = stellar_evolution.particles[0].get_mu_profile() - specific_internal_energy = (1.5 * constants.kB * temperature / mu).as_quantity_in(units.J/units.kg) # units.m**2/units.s**2) - + mu = stellar_evolution.particles[0].get_mu_profile() + specific_internal_energy = (1.5 * constants.kB * temperature / mu).as_quantity_in(units.J/units.kg) # units.m**2/units.s**2) + number_of_sph_particles = 10000 print("Creating initial conditions from a MESA stellar evolution model:") print(stars.mass[0], "star consisting of", number_of_sph_particles, "particles.") gas = convert_stellar_model_to_SPH( - stellar_evolution.particles[0], - number_of_sph_particles, + stellar_evolution.particles[0], + number_of_sph_particles, seed=12345 ).gas_particles stellar_evolution.stop() - + t_end = 1.0e4 | units.s print("Evolving to:", t_end) n_steps = 100 - + unit_converter = ConvertBetweenGenericAndSiUnits(1.0 | units.RSun, 1.0 | units.MSun, t_end) hydro_code = Gadget2(unit_converter) hydro_code.gas_particles.add_particles(gas) - + times = [] | units.Myr - kinetic_energies = [] | units.J + kinetic_energies = [] | units.J potential_energies = [] | units.J - thermal_energies = [] | units.J + thermal_energies = [] | units.J for time in [i*t_end/n_steps for i in range(1, n_steps+1)]: hydro_code.evolve_model(time) times.append(time) - kinetic_energies.append( hydro_code.kinetic_energy) - potential_energies.append( hydro_code.potential_energy) - thermal_energies.append( hydro_code.thermal_energy) - + kinetic_energies.append(hydro_code.kinetic_energy) + potential_energies.append(hydro_code.potential_energy) + thermal_energies.append(hydro_code.thermal_energy) + sph_midpoints = hydro_code.gas_particles.position.lengths() - energy_plot(times, kinetic_energies, potential_energies, thermal_energies, + energy_plot(times, kinetic_energies, potential_energies, thermal_energies, os.path.join(get_path_to_results(), "star2sph_test_7_after_t1e4_gadget_energy_evolution.png")) - thermal_energy_plot(times, thermal_energies, + thermal_energy_plot(times, thermal_energies, os.path.join(get_path_to_results(), "star2sph_test_7_after_t1e4_gadget_thermal_energy_evolution.png")) composition_comparison_plot( - midpoints, composition[0], - sph_midpoints, gas.h1, + midpoints, composition[0], + sph_midpoints, gas.h1, os.path.join(get_path_to_results(), "star2sph_test_7_after_t1e4_gadget_composition_h1.png") ) internal_energy_comparison_plot( - midpoints, specific_internal_energy, - sph_midpoints, gas.u, + midpoints, specific_internal_energy, + sph_midpoints, gas.u, os.path.join(get_path_to_results(), "star2sph_test_7_after_t1e4_gadget_original_u.png") ) internal_energy_comparison_plot( - midpoints, specific_internal_energy, - sph_midpoints, hydro_code.gas_particles.u, + midpoints, specific_internal_energy, + sph_midpoints, hydro_code.gas_particles.u, os.path.join(get_path_to_results(), "star2sph_test_7_after_t1e4_gadget_new_u.png") ) hydro_code.stop() print("All done!\n") - + def slowtest8(self): print("Isothermal relaxation of stellar evolution model (Fi)") stellar_evolution = self.new_instance(MESA) if stellar_evolution is None: print("MESA was not built. Skipping test.") return - stars = Particles(1) + stars = Particles(1) stars.mass = 1.0 | units.MSun - stellar_evolution.initialize_code() + stellar_evolution.initialize_code() stellar_evolution.particles.add_particles(stars) stellar_evolution.commit_particles() number_of_sph_particles = 10000 print("Creating initial conditions from a MESA stellar evolution model:") print(stars.mass[0], "star consisting of", number_of_sph_particles, "particles.") gas = convert_stellar_model_to_SPH( - stellar_evolution.particles[0], - number_of_sph_particles, + stellar_evolution.particles[0], + number_of_sph_particles, seed=12345 ).gas_particles stellar_evolution.stop() - + t_end = 1000.0 | units.s n_steps = 100 - + print("Evolving to:", t_end) - + gas.h_smooth = 0.01 | units.RSun - + unit_converter = nbody_system.nbody_to_si(1000.0 | units.s, 1.0 | units.RSun) hydro_code = Fi(unit_converter) hydro_code.parameters.timestep = t_end / n_steps hydro_code.parameters.isothermal_flag = True hydro_code.parameters.gamma = 1.0 hydro_code.gas_particles.add_particles(gas) - + times = [] | units.Myr - kinetic_energies = [] | units.J + kinetic_energies = [] | units.J potential_energies = [] | units.J - thermal_energies = [] | units.J + thermal_energies = [] | units.J for time in [i*t_end/n_steps for i in range(1, n_steps+1)]: hydro_code.evolve_model(time) print("Evolved model to:", time) times.append(time) - kinetic_energies.append( hydro_code.kinetic_energy) - potential_energies.append( hydro_code.potential_energy) - thermal_energies.append( hydro_code.thermal_energy) + kinetic_energies.append(hydro_code.kinetic_energy) + potential_energies.append(hydro_code.potential_energy) + thermal_energies.append(hydro_code.thermal_energy) hydro_code.stop() - energy_plot(times, kinetic_energies, potential_energies, thermal_energies, + energy_plot(times, kinetic_energies, potential_energies, thermal_energies, os.path.join(get_path_to_results(), "star2sph_test_8_fi_star2sph.png")) print("All done!\n") - + def slowtest9(self): print("Test convert_stellar_model_to_SPH and relaxation") stellar_evolution = self.new_instance(MESA) if stellar_evolution is None: print("MESA was not built. Skipping test.") return - stars = Particles(1) + stars = Particles(1) stars.mass = 1.0 | units.MSun - stellar_evolution.initialize_code() + stellar_evolution.initialize_code() stellar_evolution.particles.add_particles(stars) stellar_evolution.commit_particles() stellar_evolution.evolve_model(10.0 | units.Gyr) @@ -362,41 +363,41 @@ def slowtest9(self): outer_radii.prepend(0.0 | units.m) midpoints = (outer_radii[:-1] + outer_radii[1:]) / 2 temperature = stellar_evolution.particles[0].get_temperature_profile() - mu = stellar_evolution.particles[0].get_mu_profile() - specific_internal_energy = (1.5 * constants.kB * temperature / mu).as_quantity_in(units.J/units.kg) # units.m**2/units.s**2) - - number_of_sph_particles = 1000 # only few particles for test speed-up + mu = stellar_evolution.particles[0].get_mu_profile() + specific_internal_energy = (1.5 * constants.kB * temperature / mu).as_quantity_in(units.J/units.kg) # units.m**2/units.s**2) + + number_of_sph_particles = 1000 # only few particles for test speed-up print("Creating initial conditions from a MESA stellar evolution model:") print(stars.mass[0], "star consisting of", number_of_sph_particles, "particles, with relaxation turned ON.") sph_particles = convert_stellar_model_to_SPH( - stellar_evolution.particles[0], - number_of_sph_particles, - seed = 12345, - do_relax = True + stellar_evolution.particles[0], + number_of_sph_particles, + seed=12345, + do_relax=True ).gas_particles stellar_evolution.stop() sph_midpoints = sph_particles.position.lengths() - + composition_comparison_plot( - midpoints, composition[0], - sph_midpoints, sph_particles.h1, + midpoints, composition[0], + sph_midpoints, sph_particles.h1, os.path.join(get_path_to_results(), "star2sph_test_9_relax_h1.png") ) internal_energy_comparison_plot( - midpoints, specific_internal_energy, - sph_midpoints, sph_particles.u, + midpoints, specific_internal_energy, + sph_midpoints, sph_particles.u, os.path.join(get_path_to_results(), "star2sph_test_9_relax_u.png") ) - + def slowtest10(self): print("Test convert_stellar_model_to_SPH with relaxation, and subsequently relax with Gadget2") stellar_evolution = self.new_instance(MESA) if stellar_evolution is None: print("MESA was not built. Skipping test.") return - stars = Particles(1) + stars = Particles(1) stars.mass = 1.0 | units.MSun - stellar_evolution.initialize_code() + stellar_evolution.initialize_code() stellar_evolution.particles.add_particles(stars) stellar_evolution.commit_particles() stellar_evolution.evolve_model(10.0 | units.Gyr) @@ -405,184 +406,183 @@ def slowtest10(self): outer_radii.prepend(0.0 | units.m) midpoints = (outer_radii[:-1] + outer_radii[1:]) / 2 temperature = stellar_evolution.particles[0].get_temperature_profile() - mu = stellar_evolution.particles[0].get_mu_profile() - specific_internal_energy = (1.5 * constants.kB * temperature / mu).as_quantity_in(units.J/units.kg) # units.m**2/units.s**2) - - number_of_sph_particles = 10000 # only few particles for test speed-up + mu = stellar_evolution.particles[0].get_mu_profile() + specific_internal_energy = (1.5 * constants.kB * temperature / mu).as_quantity_in(units.J/units.kg) # units.m**2/units.s**2) + + number_of_sph_particles = 10000 # only few particles for test speed-up print("Creating initial conditions from a MESA stellar evolution model:") print(stars.mass[0], "star consisting of", number_of_sph_particles, "particles, with relaxation turned ON.") sph_particles = convert_stellar_model_to_SPH( - stellar_evolution.particles[0], - number_of_sph_particles, - seed = 12345, - do_relax = True + stellar_evolution.particles[0], + number_of_sph_particles, + seed=12345, + do_relax=True ).gas_particles stellar_evolution.stop() sph_midpoints = sph_particles.position.lengths() - + composition_comparison_plot( - midpoints, composition[0], - sph_midpoints, sph_particles.h1, + midpoints, composition[0], + sph_midpoints, sph_particles.h1, os.path.join(get_path_to_results(), "star2sph_test_10_before_h1_new.png") ) internal_energy_comparison_plot( - midpoints, specific_internal_energy, - sph_midpoints, sph_particles.u, + midpoints, specific_internal_energy, + sph_midpoints, sph_particles.u, os.path.join(get_path_to_results(), "star2sph_test_10_before_u_new.png") ) t_end = 1.0e4 | units.s print("Evolving to:", t_end) n_steps = 100 - + unit_converter = ConvertBetweenGenericAndSiUnits(1.0 | units.RSun, 1.0 | units.MSun, t_end) hydro_code = Gadget2(unit_converter) hydro_code.gas_particles.add_particles(sph_particles) - + times = [] | units.Myr - kinetic_energies = [] | units.J + kinetic_energies = [] | units.J potential_energies = [] | units.J - thermal_energies = [] | units.J + thermal_energies = [] | units.J for time in [i*t_end/n_steps for i in range(1, n_steps+1)]: hydro_code.evolve_model(time) times.append(time) - kinetic_energies.append( hydro_code.kinetic_energy) - potential_energies.append( hydro_code.potential_energy) - thermal_energies.append( hydro_code.thermal_energy) - + kinetic_energies.append(hydro_code.kinetic_energy) + potential_energies.append(hydro_code.potential_energy) + thermal_energies.append(hydro_code.thermal_energy) + sph_midpoints = hydro_code.gas_particles.position.lengths() - energy_plot(times, kinetic_energies, potential_energies, thermal_energies, + energy_plot(times, kinetic_energies, potential_energies, thermal_energies, os.path.join(get_path_to_results(), "star2sph_test_10_after_t1e4_gadget_energy_evolution.png")) - thermal_energy_plot(times, thermal_energies, + thermal_energy_plot(times, thermal_energies, os.path.join(get_path_to_results(), "star2sph_test_10_after_t1e4_gadget_thermal_energy_evolution.png")) composition_comparison_plot( - midpoints, composition[0], - sph_midpoints, sph_particles.h1, + midpoints, composition[0], + sph_midpoints, sph_particles.h1, os.path.join(get_path_to_results(), "star2sph_test_10_after_t1e4_gadget_h1.png") ) internal_energy_comparison_plot( - midpoints, specific_internal_energy, - sph_midpoints, sph_particles.u, + midpoints, specific_internal_energy, + sph_midpoints, sph_particles.u, os.path.join(get_path_to_results(), "star2sph_test_10_after_t1e4_gadget_original_u.png") ) internal_energy_comparison_plot( - midpoints, specific_internal_energy, - sph_midpoints, hydro_code.gas_particles.u, + midpoints, specific_internal_energy, + sph_midpoints, hydro_code.gas_particles.u, os.path.join(get_path_to_results(), "star2sph_test_10_after_t1e4_gadget_new_u.png") ) hydro_code.stop() print("All done!\n") - + def test11(self): print("Test convert_stellar_model_to_SPH with two stars") star = self.StarParticleWithStructure() - number_of_sph_particles = 100 # only few particles for test speed-up + number_of_sph_particles = 100 # only few particles for test speed-up some_sph_particles = convert_stellar_model_to_SPH( - star, - number_of_sph_particles, - seed = 12345 + star, + number_of_sph_particles, + seed=12345 ).gas_particles - - another_star = self.StarParticleWithStructure(number_of_species = 4) + + another_star = self.StarParticleWithStructure(number_of_species=4) more_sph_particles = convert_stellar_model_to_SPH( - another_star, - number_of_sph_particles, - seed = 12345 + another_star, + number_of_sph_particles, + seed=12345 ).gas_particles more_sph_particles.x += 100.0 | units.RSun - + sph_particles = ParticlesSuperset([some_sph_particles, more_sph_particles]) string_produced_by_print = sph_particles.__str__() self.assertTrue("he3" in string_produced_by_print) self.assertFalse("c12" in string_produced_by_print) - + self.assertEqual(len(sph_particles), 2 * number_of_sph_particles) self.assertAlmostEqual(sph_particles.mass.sum(), 2 * star.mass) self.assertIsOfOrder(max(sph_particles.x), (100.0 | units.RSun) + another_star.radius) self.assertIsOfOrder(min(sph_particles.x), -star.radius) - + self.assertEqual(len(some_sph_particles.composition), number_of_sph_particles) self.assertEqual(len(some_sph_particles[0].composition), 3) self.assertEqual(len(more_sph_particles[0].composition), 4) - self.assertRaises(AttributeError, getattr, sph_particles, "composition", - expected_message = "Subsets return incompatible quantities for attribute 'composition', attribute cannot be queried from the superset") - - + self.assertRaises(AttributeError, getattr, sph_particles, "composition", + expected_message="Subsets return incompatible quantities for attribute 'composition', attribute cannot be queried from the superset") + self.assertAlmostEqual(some_sph_particles.composition.sum(axis=1), [1.0]*number_of_sph_particles) self.assertAlmostEqual(more_sph_particles.composition.sum(axis=1), [1.0]*number_of_sph_particles) - self.assertTrue(numpy.all( sph_particles.h1 <= 0.7001 )) - self.assertTrue(numpy.all( sph_particles.he3 <= 0.0501 )) - self.assertTrue(numpy.all( sph_particles.he4 >= 0.2899 )) - + self.assertTrue(numpy.all(sph_particles.h1 <= 0.7001)) + self.assertTrue(numpy.all(sph_particles.he3 <= 0.0501)) + self.assertTrue(numpy.all(sph_particles.he4 >= 0.2899)) + def slowtest12(self): print("Test merge two stars") stellar_evolution = self.new_instance(MESA) if stellar_evolution is None: print("MESA was not built. Skipping test.") return - stars = Particles(2) + stars = Particles(2) stars.mass = [1.0, 1.0] | units.MSun - stellar_evolution.initialize_code() + stellar_evolution.initialize_code() stellar_evolution.particles.add_particles(stars) stellar_evolution.commit_particles() stellar_evolution.evolve_model(10.0 | units.Gyr) - + composition = stellar_evolution.particles[0].get_chemical_abundance_profiles() outer_radii = stellar_evolution.particles[0].get_radius_profile() outer_radii.prepend(0.0 | units.m) midpoints = (outer_radii[:-1] + outer_radii[1:]) / 2 temperature = stellar_evolution.particles[0].get_temperature_profile() - mu = stellar_evolution.particles[0].get_mu_profile() + mu = stellar_evolution.particles[0].get_mu_profile() specific_internal_energy = (1.5 * constants.kB * temperature / mu).as_quantity_in(units.J/units.kg) - + number_of_sph_particles = 4000 n_string = "n4e3" print("Creating initial conditions from a MESA stellar evolution model:") print(stars.mass[0], "star consisting of", number_of_sph_particles, "particles.") sph_particles_1 = convert_stellar_model_to_SPH( - stellar_evolution.particles[0], - number_of_sph_particles, + stellar_evolution.particles[0], + number_of_sph_particles, seed=12345 ).gas_particles print(stars.mass[1], "star consisting of", number_of_sph_particles, "particles.") sph_particles_2 = convert_stellar_model_to_SPH( - stellar_evolution.particles[1], - number_of_sph_particles, + stellar_evolution.particles[1], + number_of_sph_particles, seed=12345 ).gas_particles stellar_evolution.stop() initial_separation = 4.0 | units.RSun initial_speed = 100.0 | units.km / units.s - sph_particles_2.x += initial_separation + sph_particles_2.x += initial_separation sph_particles_1.vx += initial_speed all_sph_particles = ParticlesSuperset([sph_particles_1, sph_particles_2]) - + t_end = 4.0e4 | units.s t_end_string = "t4e4" print("Evolving to:", t_end) n_steps = 100 - + unit_converter = ConvertBetweenGenericAndSiUnits(1.0 | units.RSun, 1.0 | units.MSun, t_end) hydro_code = Gadget2(unit_converter) hydro_code.gas_particles.add_particles(all_sph_particles) - + times = [] | units.Myr - kinetic_energies = [] | units.J + kinetic_energies = [] | units.J potential_energies = [] | units.J - thermal_energies = [] | units.J + thermal_energies = [] | units.J for time in [i*t_end/n_steps for i in range(1, n_steps+1)]: hydro_code.evolve_model(time) times.append(time) - kinetic_energies.append( hydro_code.kinetic_energy) - potential_energies.append( hydro_code.potential_energy) - thermal_energies.append( hydro_code.thermal_energy) - - energy_plot(times, kinetic_energies, potential_energies, thermal_energies, + kinetic_energies.append(hydro_code.kinetic_energy) + potential_energies.append(hydro_code.potential_energy) + thermal_energies.append(hydro_code.thermal_energy) + + energy_plot(times, kinetic_energies, potential_energies, thermal_energies, os.path.join(get_path_to_results(), "star2sph_test_12_merger_"+n_string+"_"+t_end_string+"_energy_evolution.png")) - thermal_energy_plot(times, thermal_energies, + thermal_energy_plot(times, thermal_energies, os.path.join(get_path_to_results(), "star2sph_test_12_merger_"+n_string+"_"+t_end_string+"_thermal_energy_evolution.png")) - + channel = hydro_code.gas_particles.new_channel_to(all_sph_particles) - channel.copy_attributes(['mass', 'rho', 'x','y','z', 'vx','vy','vz', 'u']) + channel.copy_attributes(['mass', 'rho', 'x', 'y', 'z', 'vx', 'vy', 'vz', 'u']) center_of_mass = all_sph_particles.center_of_mass().as_quantity_in(units.RSun) center_of_mass_velocity = all_sph_particles.center_of_mass_velocity().as_quantity_in(units.km / units.s) print("center_of_mass:", center_of_mass) @@ -591,52 +591,52 @@ def slowtest12(self): self.assertIsOfOrder(center_of_mass_velocity[0], 0.5 * initial_speed) all_sph_particles.position -= center_of_mass sph_midpoints = all_sph_particles.position.lengths() - + composition_comparison_plot( - midpoints, composition[0], - sph_midpoints, all_sph_particles.h1, + midpoints, composition[0], + sph_midpoints, all_sph_particles.h1, os.path.join(get_path_to_results(), "star2sph_test_12_merger_"+n_string+"_"+t_end_string+"_composition_h1.png") ) internal_energy_comparison_plot( - midpoints, specific_internal_energy, - sph_midpoints, all_sph_particles.u, + midpoints, specific_internal_energy, + sph_midpoints, all_sph_particles.u, os.path.join(get_path_to_results(), "star2sph_test_12_merger_"+n_string+"_"+t_end_string+"_new_u.png") ) hydro_code.stop() print("All done!\n") - + def slowtest13(self): print("Super giant model in SPH") stellar_evolution = self.new_instance(MESA) if stellar_evolution is None: print("MESA was not built. Skipping test.") return - star = Particle() + star = Particle() star.mass = 10.0 | units.MSun - stellar_evolution.initialize_code() + stellar_evolution.initialize_code() se_star = stellar_evolution.particles.add_particle(star) stellar_evolution.commit_particles() original_outer_radii = se_star.get_radius_profile().as_quantity_in(units.RSun) - original_density = se_star.get_density_profile() + original_density = se_star.get_density_profile() try: while True: stellar_evolution.evolve_model() except AmuseException as ex: self.assertEqual(str(ex), "Error when calling 'evolve' of a 'MESA', errorcode is -14, error " "is 'Evolve terminated: Maximum number of backups reached.'") - + composition = se_star.get_chemical_abundance_profiles() - density = se_star.get_density_profile() + density = se_star.get_density_profile() outer_radii = se_star.get_radius_profile() outer_radii.prepend(0.0 | units.m) midpoints = (outer_radii[:-1] + outer_radii[1:]) / 2 temperature = se_star.get_temperature_profile() - mu = se_star.get_mu_profile() + mu = se_star.get_mu_profile() specific_internal_energy = (1.5 * constants.kB * temperature / mu).as_quantity_in(units.J/units.kg) - - pyplot.figure(figsize = (5, 5)) - loglog(original_outer_radii, original_density, label = "t = "+str(0|units.Myr)) - loglog(outer_radii[1:], density, label = "t = "+str(se_star.age.as_quantity_in(units.Myr))) + + pyplot.figure(figsize=(5, 5)) + loglog(original_outer_radii, original_density, label="t = "+str(0 | units.Myr)) + loglog(outer_radii[1:], density, label="t = "+str(se_star.age.as_quantity_in(units.Myr))) xlabel('radius') ylabel('density') pyplot.legend(loc=3) @@ -644,64 +644,64 @@ def slowtest13(self): pyplot.savefig(figname) print("\nPlot of density profile was saved to: ", figname) pyplot.close() - + number_of_sph_particles = 1000 print("Creating initial conditions from a MESA stellar evolution model:") print(star.mass[0], "star consisting of", number_of_sph_particles, "particles.") gas = convert_stellar_model_to_SPH( - se_star, + se_star, number_of_sph_particles ).gas_particles stellar_evolution.stop() - + t_end = 1.0e3 | units.s print("Evolving to:", t_end) n_steps = 100 - + unit_converter = ConvertBetweenGenericAndSiUnits(1.0 | units.RSun, 1.0 | units.MSun, t_end) hydro_code = Gadget2(unit_converter) hydro_code.gas_particles.add_particles(gas) - + times = [] | units.Myr - kinetic_energies = [] | units.J + kinetic_energies = [] | units.J potential_energies = [] | units.J - thermal_energies = [] | units.J + thermal_energies = [] | units.J for time in [i*t_end/n_steps for i in range(1, n_steps+1)]: hydro_code.evolve_model(time) times.append(time) - kinetic_energies.append( hydro_code.kinetic_energy) - potential_energies.append( hydro_code.potential_energy) - thermal_energies.append( hydro_code.thermal_energy) - + kinetic_energies.append(hydro_code.kinetic_energy) + potential_energies.append(hydro_code.potential_energy) + thermal_energies.append(hydro_code.thermal_energy) + sph_midpoints = hydro_code.gas_particles.position.lengths() - energy_plot(times, kinetic_energies, potential_energies, thermal_energies, + energy_plot(times, kinetic_energies, potential_energies, thermal_energies, os.path.join(get_path_to_results(), "star2sph_test_13_n1e3_after_t1e3_gadget_energy_evolution.png")) - thermal_energy_plot(times, thermal_energies, + thermal_energy_plot(times, thermal_energies, os.path.join(get_path_to_results(), "star2sph_test_13_n1e3_after_t1e3_gadget_thermal_energy_evolution.png")) composition_comparison_plot( - midpoints, composition[0], - sph_midpoints, gas.h1, + midpoints, composition[0], + sph_midpoints, gas.h1, os.path.join(get_path_to_results(), "star2sph_test_13_n1e3_after_t1e3_gadget_composition_h1.png") ) internal_energy_comparison_plot( - midpoints, specific_internal_energy, - sph_midpoints, gas.u, + midpoints, specific_internal_energy, + sph_midpoints, gas.u, os.path.join(get_path_to_results(), "star2sph_test_13_n1e3_after_t1e3_gadget_original_u.png") ) internal_energy_comparison_plot( - midpoints, specific_internal_energy, - sph_midpoints, hydro_code.gas_particles.u, + midpoints, specific_internal_energy, + sph_midpoints, hydro_code.gas_particles.u, os.path.join(get_path_to_results(), "star2sph_test_13_n1e3_after_t1e3_gadget_new_u.png") ) hydro_code.stop() print("All done!\n") - + def slowtest14(self): print("SPH model with core") # options: - with_core = True # set to False to do a comparison run without a core (True) - hydro_code = Gadget2 # Fi -or- Gadget2 - + with_core = True # set to False to do a comparison run without a core (True) + hydro_code = Gadget2 # Fi -or- Gadget2 + test_pickle_file = os.path.join(get_path_to_results(), "star2sph_test_14.pkl") if not os.path.exists(test_pickle_file): stellar_evolution = self.new_instance(MESA) @@ -711,24 +711,24 @@ def slowtest14(self): print(star.core_mass) pickle_stellar_model(star, test_pickle_file) stellar_evolution.stop() - + number_of_sph_particles = 10000 print("Creating initial conditions from a MESA stellar evolution model") - + converter = StellarModel2SPH( - None, - number_of_sph_particles, - seed = 12345, - pickle_file = test_pickle_file, - with_core_particle = with_core, - target_core_mass = 0.9 | units.MSun + None, + number_of_sph_particles, + seed=12345, + pickle_file=test_pickle_file, + with_core_particle=with_core, + target_core_mass=0.9 | units.MSun ) converter.unpickle_stellar_structure() original_mass = converter.mass stellar_model_in_SPH = converter.result - + if with_core: - print("Created", len(stellar_model_in_SPH.gas_particles), end=' ') + print("Created", len(stellar_model_in_SPH.gas_particles), end=' ') print("SPH particles and one 'core-particle':\n", stellar_model_in_SPH.core_particle) print(stellar_model_in_SPH.gas_particles.mass.sum()) core_radius = stellar_model_in_SPH.core_radius @@ -736,69 +736,70 @@ def slowtest14(self): print("Only SPH particles created.") core_radius = 1.0 | units.RSun print("Setting gravitational smoothing to:", core_radius.as_quantity_in(units.RSun)) - + t_end = 1.0e4 | units.s n_steps = 100 - + unit_converter = ConvertBetweenGenericAndSiUnits(1.0 | units.RSun, constants.G, t_end) hydro_code = hydro_code(unit_converter) try: hydro_code.parameters.timestep = t_end / n_steps except Exception as exc: - if not "parameter is read-only" in str(exc): raise + if not "parameter is read-only" in str(exc): + raise hydro_code.parameters.epsilon_squared = core_radius**2 hydro_code.gas_particles.add_particles(stellar_model_in_SPH.gas_particles) if with_core: hydro_code.dm_particles.add_particle(stellar_model_in_SPH.core_particle) - + self.assertAlmostRelativeEqual(original_mass, hydro_code.particles.total_mass(), places=7) - + sph_midpoints = hydro_code.gas_particles.position.lengths() radial_comparison_plot( - converter.midpoints_profile[1:-1], converter.specific_internal_energy_profile, - sph_midpoints, hydro_code.gas_particles.u, + converter.midpoints_profile[1:-1], converter.specific_internal_energy_profile, + sph_midpoints, hydro_code.gas_particles.u, os.path.join(get_path_to_results(), "star2sph_test_14_internal_energy.png"), - y_label = "internal energy" + y_label="internal energy" ) radial_comparison_plot( - converter.midpoints_profile[1:-1], converter.density_profile, - sph_midpoints, hydro_code.gas_particles.rho, - os.path.join(get_path_to_results(), "star2sph_test_14_density.png"), - y_label = "density" + converter.midpoints_profile[1:-1], converter.density_profile, + sph_midpoints, hydro_code.gas_particles.rho, + os.path.join(get_path_to_results(), "star2sph_test_14_density.png"), + y_label="density" ) radial_comparison_plot( - converter.midpoints_profile[1:-1], converter.specific_internal_energy_profile * converter.density_profile**(-2.0/3.0), - sph_midpoints, hydro_code.gas_particles.u * hydro_code.gas_particles.rho**(-2.0/3.0), - os.path.join(get_path_to_results(), "star2sph_test_14_entropy.png"), - y_label = "entropy" + converter.midpoints_profile[1:-1], converter.specific_internal_energy_profile * converter.density_profile**(-2.0/3.0), + sph_midpoints, hydro_code.gas_particles.u * hydro_code.gas_particles.rho**(-2.0/3.0), + os.path.join(get_path_to_results(), "star2sph_test_14_entropy.png"), + y_label="entropy" ) times = [] | units.s - kinetic_energies = [] | units.J + kinetic_energies = [] | units.J potential_energies = [] | units.J - thermal_energies = [] | units.J - + thermal_energies = [] | units.J + print("Evolving to:", t_end) for time in [i*t_end/n_steps for i in range(1, n_steps+1)]: hydro_code.evolve_model(time) times.append(time) - kinetic_energies.append( hydro_code.kinetic_energy) - potential_energies.append( hydro_code.potential_energy) - thermal_energies.append( hydro_code.thermal_energy) - + kinetic_energies.append(hydro_code.kinetic_energy) + potential_energies.append(hydro_code.potential_energy) + thermal_energies.append(hydro_code.thermal_energy) + sph_midpoints = hydro_code.gas_particles.position.lengths() - energy_plot(times, kinetic_energies, potential_energies, thermal_energies, + energy_plot(times, kinetic_energies, potential_energies, thermal_energies, os.path.join(get_path_to_results(), "star2sph_test_14_after_t1e2_gadget_energy_evolution.png")) - thermal_energy_plot(times, thermal_energies, + thermal_energy_plot(times, thermal_energies, os.path.join(get_path_to_results(), "star2sph_test_14_after_t1e2_gadget_thermal_energy_evolution.png")) radial_comparison_plot( - converter.midpoints_profile[1:-1], converter.specific_internal_energy_profile, - sph_midpoints, hydro_code.gas_particles.u, - os.path.join(get_path_to_results(), "star2sph_test_14_after_t1e2_gadget_internal_energy.png"), - y_label = "internal energy" + converter.midpoints_profile[1:-1], converter.specific_internal_energy_profile, + sph_midpoints, hydro_code.gas_particles.u, + os.path.join(get_path_to_results(), "star2sph_test_14_after_t1e2_gadget_internal_energy.png"), + y_label="internal energy" ) hydro_code.stop() print("All done!\n") - + def test15(self): print("Test pickling of stellar structure") star = self.StarParticleWithStructure() @@ -806,8 +807,8 @@ def test15(self): if os.path.exists(test_pickle_file): os.remove(test_pickle_file) pickle_stellar_model(star, test_pickle_file) - converter = StellarModel2SPH(None, 100, seed=12345, - pickle_file = test_pickle_file) + converter = StellarModel2SPH(None, 100, seed=12345, + pickle_file=test_pickle_file) converter.unpickle_stellar_structure() self.assertEqual(converter.mass, numpy.pi * 1.5 | units.MSun) self.assertEqual(converter.radius, 1.0 | units.RSun) @@ -816,21 +817,19 @@ def test15(self): self.assertEqual(converter.species_names, ['h1', 'he3', 'he4']) self.assertEqual(converter.density_profile, [2.0, 2.0, 2.0, 1.0] | units.MSun/units.RSun**3) self.assertEqual(converter.radius_profile, [1.0/8.0, 1.0/4.0, 1.0/2.0, 1.0] | units.RSun) -#~ self.assertEqual(converter.temperature_profile, [1e7, 1e6, 1e5, 1e4] | units.K) +# ~ self.assertEqual(converter.temperature_profile, [1e7, 1e6, 1e5, 1e4] | units.K) self.assertEqual(converter.mu_profile, [0.8, 0.6, 0.6, 1.3] | units.amu) - self.assertEqual(converter.composition_profile, [[0.0, 0.7, 0.7, 0.7], + self.assertEqual(converter.composition_profile, [[0.0, 0.7, 0.7, 0.7], [0.05, 0.01, 0.01, 0.01], [0.95, 0.29, 0.29, 0.29]]) - self.assertAlmostEqual(converter.specific_internal_energy_profile, - [155896.35894, 20786.18119, 2078.61812, 95.93622] | (units.km/units.s)**2, places = 1) - - self.assertRaises(AmuseWarning, pickle_stellar_model, star, test_pickle_file, expected_message = - "Incorrect file name '{0}'; directory must exist and file may not exist".format(test_pickle_file)) + self.assertAlmostEqual(converter.specific_internal_energy_profile, + [155896.35894, 20786.18119, 2078.61812, 95.93622] | (units.km/units.s)**2, places=1) + + self.assertRaises(AmuseWarning, pickle_stellar_model, star, test_pickle_file, expected_message="Incorrect file name '{0}'; directory must exist and file may not exist".format(test_pickle_file)) bogus_pickle_file = os.path.join(get_path_to_results(), "bogus.pkl") - converter = StellarModel2SPH(None, 100, seed=12345, - pickle_file = bogus_pickle_file) - self.assertRaises(AmuseException, converter.unpickle_stellar_structure, expected_message = - "Input pickle file '{0}' does not exist".format(bogus_pickle_file)) - + converter = StellarModel2SPH(None, 100, seed=12345, + pickle_file=bogus_pickle_file) + self.assertRaises(AmuseException, converter.unpickle_stellar_structure, expected_message="Input pickle file '{0}' does not exist".format(bogus_pickle_file)) + def test16(self): print("Test convert_stellar_model_to_SPH with pickled stellar structure") star = self.StarParticleWithStructure() @@ -838,48 +837,48 @@ def test16(self): if os.path.exists(test_pickle_file): os.remove(test_pickle_file) pickle_stellar_model(star, test_pickle_file) - - number_of_sph_particles = 100 # only few particles for test speed-up + + number_of_sph_particles = 100 # only few particles for test speed-up sph_particles = convert_stellar_model_to_SPH( - None, - number_of_sph_particles, - seed = 12345, - pickle_file = test_pickle_file + None, + number_of_sph_particles, + seed=12345, + pickle_file=test_pickle_file ).gas_particles self.assertEqual(len(sph_particles), number_of_sph_particles) self.assertAlmostEqual(sph_particles.mass.sum(), star.mass) - self.assertAlmostEqual(sph_particles.center_of_mass(), [0,0,0] | units.RSun, 1) + self.assertAlmostEqual(sph_particles.center_of_mass(), [0, 0, 0] | units.RSun, 1) self.assertIsOfOrder(max(sph_particles.x), star.radius) self.assertAlmostEqual(sph_particles.composition.sum(axis=1), [1.0]*number_of_sph_particles) - self.assertTrue(numpy.all( sph_particles.h1 <= 0.7001 )) - self.assertTrue(numpy.all( sph_particles.he3 <= 0.0501 )) - self.assertTrue(numpy.all( sph_particles.he4 >= 0.2899 )) - self.assertTrue(numpy.all( sph_particles.h1[1:] - sph_particles.h1[:-1] >= -0.0001 )) - self.assertTrue(numpy.all( sph_particles.he3[1:] - sph_particles.he3[:-1] <= 0.0001 )) - self.assertTrue(numpy.all( sph_particles.he4[1:] - sph_particles.he4[:-1] <= 0.0001 )) - + self.assertTrue(numpy.all(sph_particles.h1 <= 0.7001)) + self.assertTrue(numpy.all(sph_particles.he3 <= 0.0501)) + self.assertTrue(numpy.all(sph_particles.he4 >= 0.2899)) + self.assertTrue(numpy.all(sph_particles.h1[1:] - sph_particles.h1[:-1] >= -0.0001)) + self.assertTrue(numpy.all(sph_particles.he3[1:] - sph_particles.he3[:-1] <= 0.0001)) + self.assertTrue(numpy.all(sph_particles.he4[1:] - sph_particles.he4[:-1] <= 0.0001)) + def slowtest17(self): print("SPH red super giant model with core") # options: - with_core = True # set to False to do a comparison run without a core (True) - use_hydro_code = Gadget2 # Fi -or- Gadget2 - use_stellar_evolution_code = MESA # to be implemented as option... + with_core = True # set to False to do a comparison run without a core (True) + use_hydro_code = Gadget2 # Fi -or- Gadget2 + use_stellar_evolution_code = MESA # to be implemented as option... number_of_sph_particles = 3000 t_end = 3.0e6 | units.s - - # Convert some of the parameters to string, for use in output file names: + + # Convert some of the parameters to string, for use in output file names: hydro_code_string = "_" + str(use_hydro_code.__name__) - n_string = "_n" + ("%1.0e"%(number_of_sph_particles)).replace("+0","").replace("+","") - t_end_string = "_t" + ("%1.0e"%(t_end.value_in(units.s))).replace("+0","").replace("+","") + n_string = "_n" + ("%1.0e" % (number_of_sph_particles)).replace("+0", "").replace("+", "") + t_end_string = "_t" + ("%1.0e" % (t_end.value_in(units.s))).replace("+0", "").replace("+", "") base_plotfile_string = "star2sph_test_17" + n_string + hydro_code_string + t_end_string - - stellar_evolution = self.new_instance(MESA, redirection = "none") + + stellar_evolution = self.new_instance(MESA, redirection="none") if stellar_evolution is None: print("MESA was not built. Skipping test.") return - stars = Particles(1) + stars = Particles(1) stars.mass = 10.0 | units.MSun - stellar_evolution.initialize_code() + stellar_evolution.initialize_code() stellar_evolution.particles.add_particles(stars) stellar_evolution.commit_particles() @@ -893,195 +892,196 @@ def slowtest17(self): except AmuseException as ex: self.assertEqual(str(ex), "Error when calling 'evolve' of a 'MESA', errorcode is -14, error " "is 'Evolve terminated: Maximum number of backups reached.'") - - radius_evolution_plot(star_age, star_radius, + + radius_evolution_plot(star_age, star_radius, os.path.join(get_path_to_results(), base_plotfile_string + "_radius_evolution.png")) - self.assertIsOfOrder(stellar_evolution.particles[0].age, # MS lifetime: + self.assertIsOfOrder(stellar_evolution.particles[0].age, # MS lifetime: (1.0e10 | units.yr) * (stars.mass.value_in(units.MSun)) ** -2.5) - + outer_radii = stellar_evolution.particles[0].get_radius_profile() outer_radii.prepend(0.0 | units.m) midpoints = (outer_radii[:-1] + outer_radii[1:]) / 2 temperature = stellar_evolution.particles[0].get_temperature_profile() - mu = stellar_evolution.particles[0].get_mu_profile() - specific_internal_energy = (1.5 * constants.kB * temperature / mu).as_quantity_in(units.J/units.kg) # units.m**2/units.s**2) - + mu = stellar_evolution.particles[0].get_mu_profile() + specific_internal_energy = (1.5 * constants.kB * temperature / mu).as_quantity_in(units.J/units.kg) # units.m**2/units.s**2) + print("Creating initial conditions from a MESA stellar evolution model:") print(stars.mass[0], "star consisting of", number_of_sph_particles, "particles.") - + stellar_model_in_SPH = convert_stellar_model_to_SPH( - stellar_evolution.particles[0], - number_of_sph_particles, - seed = 12345, - base_grid_options = dict(type = "glass", target_rms = 0.04), - with_core_particle = with_core + stellar_evolution.particles[0], + number_of_sph_particles, + seed=12345, + base_grid_options=dict(type="glass", target_rms=0.04), + with_core_particle=with_core ) if len(stellar_model_in_SPH.core_particle): - print("Created", len(stellar_model_in_SPH.gas_particles), end=' ') + print("Created", len(stellar_model_in_SPH.gas_particles), end=' ') print("SPH particles and one 'core-particle':\n", stellar_model_in_SPH.core_particle) core_radius = stellar_model_in_SPH.core_radius else: print("Only SPH particles created.") core_radius = 1.0 | units.RSun print("Setting gravitational smoothing to:", core_radius) - + t_dyn = (stellar_evolution.particles[0].radius**3 / (2*constants.G*stars.mass[0])).sqrt() print("Dynamical timescale:", t_dyn.as_quantity_in(units.yr)) stellar_evolution.stop() - + print("Evolving to:", t_end, "("+str((t_end/t_dyn)), "dynamical timescales)") n_steps = 100 - + unit_converter = ConvertBetweenGenericAndSiUnits(1.0 | units.RSun, constants.G, t_end) - hydro_code = use_hydro_code(unit_converter, redirection = "none") - + hydro_code = use_hydro_code(unit_converter, redirection="none") + try: hydro_code.parameters.timestep = t_end / n_steps except Exception as exc: - if not "parameter is read-only" in str(exc): raise - + if not "parameter is read-only" in str(exc): + raise + hydro_code.parameters.epsilon_squared = core_radius**2 hydro_code.gas_particles.add_particles(stellar_model_in_SPH.gas_particles) if len(stellar_model_in_SPH.core_particle): hydro_code.dm_particles.add_particles(stellar_model_in_SPH.core_particle) - + self.assertAlmostRelativeEqual(stars.mass, hydro_code.particles.total_mass(), places=7) - + times = [] | units.s - kinetic_energies = [] | units.J + kinetic_energies = [] | units.J potential_energies = [] | units.J - thermal_energies = [] | units.J + thermal_energies = [] | units.J for time in [i*t_end/n_steps for i in range(1, n_steps+1)]: hydro_code.evolve_model(time) times.append(time) - kinetic_energies.append( hydro_code.kinetic_energy) - potential_energies.append( hydro_code.potential_energy) - thermal_energies.append( hydro_code.thermal_energy) - + kinetic_energies.append(hydro_code.kinetic_energy) + potential_energies.append(hydro_code.potential_energy) + thermal_energies.append(hydro_code.thermal_energy) + sph_midpoints = hydro_code.gas_particles.position.lengths() - energy_plot(times, kinetic_energies, potential_energies, thermal_energies, + energy_plot(times, kinetic_energies, potential_energies, thermal_energies, os.path.join(get_path_to_results(), base_plotfile_string + "_energy_evolution.png")) - thermal_energy_plot(times, thermal_energies, + thermal_energy_plot(times, thermal_energies, os.path.join(get_path_to_results(), base_plotfile_string + "_thermal_energy_evolution.png")) internal_energy_comparison_plot( - midpoints, specific_internal_energy, - sph_midpoints, hydro_code.gas_particles.u, + midpoints, specific_internal_energy, + sph_midpoints, hydro_code.gas_particles.u, os.path.join(get_path_to_results(), base_plotfile_string + "_internal_energy.png") ) hydro_code.stop() print("All done!\n") - + def slowtest18(self): print("SPH red super giant model with core (fixed core mass)") number_of_sph_particles = 300 - - stellar_evolution = self.new_instance(MESA, redirection = "none") + + stellar_evolution = self.new_instance(MESA, redirection="none") if stellar_evolution is None: print("MESA was not built. Skipping test.") return - stars = Particles(1) + stars = Particles(1) stars.mass = 50.0 | units.MSun - stellar_evolution.initialize_code() + stellar_evolution.initialize_code() stellar_evolution.particles.add_particles(stars) stellar_evolution.commit_particles() stellar_evolution.evolve_model(3.927 | units.Myr) - + expected_core_radii = [0.37648393, 0.58139942, 3.26189210, 31.89893263] | units.RSun for i, tgt_core_mass in enumerate([1.0, 5.0, 25.0, 49.0] | units.MSun): stellar_model_in_SPH = convert_stellar_model_to_SPH( - stellar_evolution.particles[0], - number_of_sph_particles, - seed = 12345, - with_core_particle = True, - target_core_mass = tgt_core_mass + stellar_evolution.particles[0], + number_of_sph_particles, + seed=12345, + with_core_particle=True, + target_core_mass=tgt_core_mass ) self.assertAlmostRelativeEqual(stellar_model_in_SPH.core_particle[0].mass, tgt_core_mass, 1) self.assertAlmostEqual(stellar_model_in_SPH.core_radius, expected_core_radii[i]) stellar_evolution.stop() - + def test19(self): print("Test convert_stellar_model_to_SPH with do_store_composition") - star = self.StarParticleWithStructure(number_of_species = 4) - number_of_sph_particles = 100 # only few particles for test speed-up - + star = self.StarParticleWithStructure(number_of_species=4) + number_of_sph_particles = 100 # only few particles for test speed-up + sph_particles = convert_stellar_model_to_SPH( - star, - number_of_sph_particles, - seed = 12345, - do_store_composition = False + star, + number_of_sph_particles, + seed=12345, + do_store_composition=False ).gas_particles self.assertEqual(len(sph_particles), number_of_sph_particles) self.assertTrue(set(sph_particles.get_attribute_names_defined_in_store()) == set(["mass", "x", "y", "z", "vx", "vy", "vz", "u", "h_smooth"])) self.assertTrue(set(sph_particles.get_attribute_names_defined_in_store()).isdisjoint( set(["h1", "he3", "he4", "c12"]))) - + sph_particles = convert_stellar_model_to_SPH( - star, - number_of_sph_particles, - seed = 12345, + star, + number_of_sph_particles, + seed=12345, ).gas_particles self.assertEqual(len(sph_particles), number_of_sph_particles) self.assertTrue(set(sph_particles.get_attribute_names_defined_in_store()) > set(["mass", "x", "y", "z", "vx", "vy", "vz", "u", "h_smooth"])) self.assertTrue(set(sph_particles.get_attribute_names_defined_in_store()) > set(["h1", "he3", "he4", "c12"])) - + def test20(self): print("Test convert_stellar_model_to_SPH with with_core_particle") - star = self.StarParticleWithStructure(number_of_species = 4) - number_of_sph_particles = 100 # only few particles for test speed-up - - self.assertRaises(AmuseException, convert_stellar_model_to_SPH, - star, - number_of_sph_particles, - seed = 12345, - with_core_particle = True, - expected_message = "Requested model has with_core_particle=True, but no target_core_mass specified." + star = self.StarParticleWithStructure(number_of_species=4) + number_of_sph_particles = 100 # only few particles for test speed-up + + self.assertRaises(AmuseException, convert_stellar_model_to_SPH, + star, + number_of_sph_particles, + seed=12345, + with_core_particle=True, + expected_message="Requested model has with_core_particle=True, but no target_core_mass specified." ) - + star.core_mass = 0.5 | units.MSun - self.assertRaises(AmuseException, convert_stellar_model_to_SPH, - star, - number_of_sph_particles, - seed = 12345, - with_core_particle = True, - expected_message = "Requested target_core_mass of 0.5 MSun is out of range." + self.assertRaises(AmuseException, convert_stellar_model_to_SPH, + star, + number_of_sph_particles, + seed=12345, + with_core_particle=True, + expected_message="Requested target_core_mass of 0.5 MSun is out of range." ) - + stellar_evolution = EVtwin() - star = stellar_evolution.particles.add_particle(Particle(mass=5|units.MSun)) + star = stellar_evolution.particles.add_particle(Particle(mass=5 | units.MSun)) model = convert_stellar_model_to_SPH( - star, - number_of_sph_particles, - seed = 12345, - with_core_particle = True, - target_core_mass = 0.5 | units.MSun + star, + number_of_sph_particles, + seed=12345, + with_core_particle=True, + target_core_mass=0.5 | units.MSun ) stellar_evolution.stop() core = model.core_particle sph_particles = model.gas_particles - + self.assertEqual(len(sph_particles), number_of_sph_particles) self.assertTrue(isinstance(core, Particle)) - + self.assertEqual(core.radius, model.core_radius) self.assertEqual(core.position, [0, 0, 0] | units.m) self.assertAlmostEqual(core.mass + sph_particles.total_mass(), 5.0 | units.MSun) self.assertIsOfOrder(core.mass, 0.5 | units.MSun) - - self.assertEqual(set(sph_particles.get_attribute_names_defined_in_store()), - set(["mass", "x", "y", "z", "vx", "vy", "vz", "u", "h_smooth", + + self.assertEqual(set(sph_particles.get_attribute_names_defined_in_store()), + set(["mass", "x", "y", "z", "vx", "vy", "vz", "u", "h_smooth", "h1", "he4", "c12", "n14", "o16", "ne20", "mg24", "si28", "fe56", "mu"])) - + def test21(self): print("Test convert_stellar_model_to_SPH and back") star = self.StarParticleWithStructure() - number_of_sph_particles = 50000 # only few particles for test speed-up + number_of_sph_particles = 50000 # only few particles for test speed-up sph_particles = convert_stellar_model_to_SPH( - star, - number_of_sph_particles, - base_grid_options = dict(type = "fcc") + star, + number_of_sph_particles, + base_grid_options=dict(type="fcc") ).gas_particles self.assertEqual(len(sph_particles), number_of_sph_particles) self.assertAlmostEqual(sph_particles.mass.sum(), star.mass) @@ -1096,7 +1096,7 @@ def test21(self): ) self.assertAlmostEqual(model.dmass.sum(), star.mass) self.assertAlmostEqual(model.radius[-1], star.radius, 1) - + # for a,b in model.iteritems(): # print a,b print(model.dmass[0].as_quantity_in(units.MSun)) @@ -1106,11 +1106,12 @@ def test21(self): print(model.X_H[0:10]) print(model.X_He[0:10]) + def composition_comparison_plot(radii_SE, comp_SE, radii_SPH, comp_SPH, figname): if not HAS_MATPLOTLIB: return - pyplot.figure(figsize = (7, 5)) - plot(radii_SE.as_quantity_in(units.RSun), comp_SE, + pyplot.figure(figsize=(7, 5)) + plot(radii_SE.as_quantity_in(units.RSun), comp_SE, label='stellar evolution model') plot(radii_SPH, comp_SPH, 'go', label='SPH model') xlabel('radius') @@ -1120,11 +1121,12 @@ def composition_comparison_plot(radii_SE, comp_SE, radii_SPH, comp_SPH, figname) print("\nPlot of composition profiles was saved to: ", figname) pyplot.close() + def radial_comparison_plot(radii_SE, u_SE, radii_SPH, u_SPH, figname, y_label="quantity"): if not HAS_MATPLOTLIB: return - pyplot.figure(figsize = (7, 5)) - semilogy(radii_SE.as_quantity_in(units.RSun), u_SE, + pyplot.figure(figsize=(7, 5)) + semilogy(radii_SE.as_quantity_in(units.RSun), u_SE, label='stellar evolution model') semilogy(radii_SPH, u_SPH, 'go', label='SPH model') xlabel('radius') @@ -1134,13 +1136,15 @@ def radial_comparison_plot(radii_SE, u_SE, radii_SPH, u_SPH, figname, y_label="q print("\nPlot of", y_label, "profiles was saved to: ", figname) pyplot.close() + def internal_energy_comparison_plot(radii_SE, u_SE, radii_SPH, u_SPH, figname): radial_comparison_plot(radii_SE, u_SE, radii_SPH, u_SPH, figname, y_label="internal energy") + def energy_plot(time, E_kin, E_pot, E_therm, figname): if not HAS_MATPLOTLIB: return - pyplot.figure(figsize = (5, 5)) + pyplot.figure(figsize=(5, 5)) plot(time, E_kin.as_quantity_in(units.erg), label='E_kin') plot(time, E_pot, label='E_pot') plot(time, E_therm, label='E_therm') @@ -1152,10 +1156,11 @@ def energy_plot(time, E_kin, E_pot, E_therm, figname): print("\nPlot of energy evolution was saved to: ", figname) pyplot.close() + def thermal_energy_plot(time, E_therm, figname): if not HAS_MATPLOTLIB: return - pyplot.figure(figsize = (5, 5)) + pyplot.figure(figsize=(5, 5)) plot(time, E_therm.as_quantity_in(units.erg), label='E_therm') xlabel('Time') ylabel('Energy') @@ -1163,11 +1168,12 @@ def thermal_energy_plot(time, E_therm, figname): pyplot.savefig(figname) print("\nPlot of thermal energy evolution was saved to: ", figname) pyplot.close() - + + def radius_evolution_plot(star_age, star_radius, figname): if not HAS_MATPLOTLIB: return - pyplot.figure(figsize = (5, 5)) + pyplot.figure(figsize=(5, 5)) plot(star_age, star_radius) xlabel('Time') ylabel('Radius') diff --git a/src/amuse/test/suite/ext_tests/test_static_potentials.py b/src/amuse/test/suite/ext_tests/test_static_potentials.py index a881a541b0..7d09cb3942 100644 --- a/src/amuse/test/suite/ext_tests/test_static_potentials.py +++ b/src/amuse/test/suite/ext_tests/test_static_potentials.py @@ -6,39 +6,39 @@ from amuse.support.console import set_printing_strategy + class TestGalacticCenterPotential(amusetest.TestCase): def setUp(self): - set_printing_strategy("custom", preferred_units = [units.MSun, units.parsec, units.Myr, units.kms, units.kms**2, units.m/units.s**2]) + set_printing_strategy("custom", preferred_units=[units.MSun, units.parsec, units.Myr, units.kms, units.kms**2, units.m/units.s**2]) def tearDown(self): set_printing_strategy("default") - + def test1(self): """ test enclosed mass profile of Kruijssen potential """ static_potential = static_potentials.Galactic_Center_Potential_Kruijssen() - m_zero = static_potential.enclosed_mass(0|units.parsec) - self.assertAlmostEqual(m_zero, 0|units.MSun) + m_zero = static_potential.enclosed_mass(0 | units.parsec) + self.assertAlmostEqual(m_zero, 0 | units.MSun) factor = 8.3/8.5 - m_on_bin = static_potential.enclosed_mass(7.489|units.parsec * factor) - self.assertAlmostEqual(m_on_bin, factor**2 * 17170000.|units.MSun) + m_on_bin = static_potential.enclosed_mass(7.489 | units.parsec * factor) + self.assertAlmostEqual(m_on_bin, factor**2 * 17170000. | units.MSun) - m_in_bin = static_potential.enclosed_mass(200|units.parsec) - self.assertAlmostEqual(m_in_bin, 1.644965507|1E9*units.MSun) + m_in_bin = static_potential.enclosed_mass(200 | units.parsec) + self.assertAlmostEqual(m_in_bin, 1.644965507 | 1E9*units.MSun) # test array r = numpy.logspace(1, 3, 500) | units.parsec m = static_potential.enclosed_mass(r) - self.assertAlmostEqual(m[10], 2.0680055041|1E7*units.MSun) - + self.assertAlmostEqual(m[10], 2.0680055041 | 1E7*units.MSun) # test 2D array x = numpy.logspace(1, 3, 500) | units.parsec matrix, m = quantities.meshgrid(x, x) mm = static_potential.enclosed_mass(matrix) - self.assertAlmostEqual(mm[20,20], 2.223803269|1E7*units.MSun) + self.assertAlmostEqual(mm[20, 20], 2.223803269 | 1E7*units.MSun) # quick plot for testing # from matplotlib import pyplot @@ -51,29 +51,29 @@ def test2(self): """ Test get_potential_at_point """ static_potential = static_potentials.Galactic_Center_Potential_Kruijssen() - points = [[1,0,0], - [0,10,0], - [1e3,0,1e2], + points = [[1, 0, 0], + [0, 10, 0], + [1e3, 0, 1e2], ] | units.parsec potentials = static_potential.get_potential_at_point(0, *points.transpose()) # print potentials.in_(units.kms**2) - self.assertAlmostEqual(potentials[0], -17280.958078|units.kms**2, 6) - self.assertAlmostEqual(potentials[1], -8296.5300805|units.kms**2, 6) - self.assertAlmostEqual(potentials[2], -14965.2205261|units.kms**2, 6) + self.assertAlmostEqual(potentials[0], -17280.958078 | units.kms**2, 6) + self.assertAlmostEqual(potentials[1], -8296.5300805 | units.kms**2, 6) + self.assertAlmostEqual(potentials[2], -14965.2205261 | units.kms**2, 6) def test3(self): """ Test get_gravity_at_point """ static_potential = static_potentials.Galactic_Center_Potential_Kruijssen() - points = [[1,0,0], - [0,10,0], - [1e3,0,1e2], + points = [[1, 0, 0], + [0, 10, 0], + [1e3, 0, 1e2], ] | units.parsec grav = static_potential.get_gravity_at_point(0, *points.transpose()).transpose() print(grav) - self.assertAlmostEqual(grav[0], [-5.6003771, 0, 0]|1e-7*units.m/units.s**2, 6) - self.assertAlmostEqual(grav[1], [0, -2.6887222, 0]|1e-8*units.m/units.s**2, 6) - self.assertAlmostEqual(grav[2], [-4.7661597, 0, -1.200846]|1e-10*units.m/units.s**2, 6) + self.assertAlmostEqual(grav[0], [-5.6003771, 0, 0] | 1e-7*units.m/units.s**2, 6) + self.assertAlmostEqual(grav[1], [0, -2.6887222, 0] | 1e-8*units.m/units.s**2, 6) + self.assertAlmostEqual(grav[2], [-4.7661597, 0, -1.200846] | 1e-10*units.m/units.s**2, 6) class TestGalacticPotential(amusetest.TestCase): @@ -81,13 +81,12 @@ def test1(self): """ Test the Galactic potential """ static_potential = static_potentials.Disc_Bulge_Halo_Potential() - points = [[1,0,0], - [10,0,0], - [1e3,0,1e4], + points = [[1, 0, 0], + [10, 0, 0], + [1e3, 0, 1e4], ] | units.kpc potentials = static_potential.get_potential_at_point(0, *points.transpose()).transpose() - self.assertAlmostEqual(potentials[0], -96648.29247|units.kms**2, 6) - self.assertAlmostEqual(potentials[1], 8827.40917774|units.kms**2, 6) - self.assertAlmostEqual(potentials[2], 266129.25389|units.kms**2, 6) - + self.assertAlmostEqual(potentials[0], -96648.29247 | units.kms**2, 6) + self.assertAlmostEqual(potentials[1], 8827.40917774 | units.kms**2, 6) + self.assertAlmostEqual(potentials[2], 266129.25389 | units.kms**2, 6) diff --git a/src/amuse/test/suite/ext_tests/test_stellar_wind.py b/src/amuse/test/suite/ext_tests/test_stellar_wind.py index c1f76e71a9..fd8440f1b6 100644 --- a/src/amuse/test/suite/ext_tests/test_stellar_wind.py +++ b/src/amuse/test/suite/ext_tests/test_stellar_wind.py @@ -60,7 +60,6 @@ def create_stars_without_wind_attributes(self): return stars - def tearDown(self): set_printing_strategy('default') @@ -841,7 +840,6 @@ def test_supernova(self): star_wind.particles, attributes=["age", "radius", "mass", "luminosity", "temperature", "stellar_type"]) - dt = 5 | units.Myr t = 0 | units.Myr t_end = 31 | units.Myr @@ -863,13 +861,11 @@ def test_supernova(self): t += dt - self.assertEqual(wind_N, [[0, 0], [32, 45], [57, 59], [114, 130], [302, 635], [1231, 5810], [2981, 285777]]) supernova = wind_2 sn_energy = (supernova.u * supernova.mass).sum() self.assertAlmostRelativeEqual(sn_energy, 1e49 | units.erg, 2) - def test_supernova_manual(self): stev, star_wind, stars = self.setup_supernova() stev.stopping_conditions.supernova_detection.enable() @@ -878,7 +874,6 @@ def test_supernova_manual(self): star_wind.particles, attributes=["age", "radius", "mass", "luminosity", "temperature"]) - dt = 5 | units.Myr t = 0 | units.Myr t_end = 31 | units.Myr @@ -910,4 +905,4 @@ def test_supernova_manual(self): print(wind_N) print(wind_E) self.assertEqual(wind_N[-2:], [606194, 0]) - self.assertAlmostRelativeEqual(wind_E[-2:], [1.e49, 0] | units.erg,7) + self.assertAlmostRelativeEqual(wind_E[-2:], [1.e49, 0] | units.erg, 7) diff --git a/src/amuse/test/suite/ext_tests/test_sticky_spheres.py b/src/amuse/test/suite/ext_tests/test_sticky_spheres.py index 788b0dcd78..1b031acf97 100644 --- a/src/amuse/test/suite/ext_tests/test_sticky_spheres.py +++ b/src/amuse/test/suite/ext_tests/test_sticky_spheres.py @@ -5,15 +5,16 @@ from amuse.ext.sticky_spheres import StickySpheres + class TestStickySpheres(TestCase): - + def test1(self): colliders = Particles(2) colliders.mass = [5, 2] | units.kg colliders.position = [[0.0, 0.0, 0.0], [0.7, 1.4, -0.35]] | units.m colliders.velocity = [[0.4, -0.6, 0.0], [0.0, 0.0, -3.0]] | units.m / units.s self.assertAlmostEqual(colliders.center_of_mass_velocity().length(), 1.0 | units.m / units.s) - + merged = StickySpheres().handle_collision(colliders[0], colliders[1]) self.assertTrue(isinstance(merged, Particles)) self.assertEqual(merged.mass, 7 | units.kg) @@ -23,13 +24,13 @@ def test1(self): copy = colliders.copy() copy.move_to_center() self.assertAlmostEqual(colliders.kinetic_energy(), merged.as_set().kinetic_energy() + copy.kinetic_energy()) - + def test2(self): colliders = Particles(2) colliders.mass = [5, 5] | units.kg colliders.position = [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]] | units.m colliders.velocity = [[0.0, 0.0, 0.0], [2.0, 2.0, 2.0]] | units.m / units.s - + merged = StickySpheres(mass_loss=0.2).handle_collision(colliders[0], colliders[1]) self.assertTrue(isinstance(merged, Particles)) self.assertEqual(merged.mass, 8 | units.kg) @@ -38,13 +39,11 @@ def test2(self): copy = colliders.copy() copy.move_to_center() self.assertAlmostEqual(colliders.kinetic_energy(), merged.as_set().kinetic_energy() / 0.8 + copy.kinetic_energy()) - + def test3(self): - self.assertRaises(AmuseException, StickySpheres, mass_loss=-0.1, expected_message= - "Mass-loss fraction must be in the range [0, 1)") - self.assertRaises(AmuseException, StickySpheres, mass_loss=1.0, expected_message= - "Mass-loss fraction must be in the range [0, 1)") - + self.assertRaises(AmuseException, StickySpheres, mass_loss=-0.1, expected_message="Mass-loss fraction must be in the range [0, 1)") + self.assertRaises(AmuseException, StickySpheres, mass_loss=1.0, expected_message="Mass-loss fraction must be in the range [0, 1)") + particles = Particles(6) particles.mass = range(1, 7) | units.kg particles.position = [[i, 1.0, 2.0] for i in range(1, 7)] | units.m @@ -53,18 +52,16 @@ def test3(self): [1.0, 0.0, 1.0], [0.0, -1.0, -1.0], [1.0, 0.0, 1.0], [0.0, -1.0, -1.0], ] | units.m / units.s - + for fraction in [0.01, 0.1, 0.5]: sticky_spheres = StickySpheres(mass_loss=fraction) for i in range(0, 6, 2): colliders = particles[i:i+2] merged = sticky_spheres.handle_collision(colliders[0], colliders[1]) self.assertTrue(isinstance(merged, Particles)) - self.assertAlmostEqual(merged.mass, - (2 * i +3.0) * (1 - fraction) | units.kg) - self.assertAlmostEqual(merged.position, + self.assertAlmostEqual(merged.mass, + (2 * i + 3.0) * (1 - fraction) | units.kg) + self.assertAlmostEqual(merged.position, [((i+1)**2 + (i+2)**2)/(2*i+3.0), 1.0, 2.0] | units.m) - self.assertAlmostEqual(merged.velocity, + self.assertAlmostEqual(merged.velocity, ([i+1, -(i+2), -1.0] | units.m / units.s) / (2*i+3.0)) - - diff --git a/src/amuse/test/suite/ticket_tests/test_github856.py b/src/amuse/test/suite/ticket_tests/test_github856.py new file mode 100644 index 0000000000..66c2ed3a5e --- /dev/null +++ b/src/amuse/test/suite/ticket_tests/test_github856.py @@ -0,0 +1,33 @@ +import os +from amuse.test import amusetest + +from amuse.datamodel import new_cartesian_grid, Particles + +from amuse.io import read_set_from_file, write_set_to_file + + +class test_github856(amusetest.TestCase): + def test1(self): + filename = os.path.join(self.get_path_to_results(), "github856.amuse") + + g1 = new_cartesian_grid((5, 5), 1) + write_set_to_file(g1, filename, "amuse") + del g1 + g2 = read_set_from_file(filename, "amuse") + self.assertEquals(g2.get_axes_names(), "xy") + + def test2(self): + g1 = Particles(lon=[1, 2], lat=[3, 4]) + g1.add_vector_attribute("lonlat", ["lon", "lat"]) + g2 = g1.copy() + self.assertEquals(g2.lonlat, [[1, 3], [2, 4]]) + + def test3(self): + filename = os.path.join(self.get_path_to_results(), "github856_2.amuse") + + g1 = Particles(lon=[1, 2], lat=[3, 4]) + g1.add_vector_attribute("lonlat", ["lon", "lat"]) + write_set_to_file(g1, filename, "amuse") + del g1 + g2 = read_set_from_file(filename, "amuse") + self.assertEquals(g2.lonlat, [[1, 3], [2, 4]]) diff --git a/src/amuse/test/suite/ticket_tests/test_issue123.py b/src/amuse/test/suite/ticket_tests/test_issue123.py index 8206a438c2..87acb1b753 100644 --- a/src/amuse/test/suite/ticket_tests/test_issue123.py +++ b/src/amuse/test/suite/ticket_tests/test_issue123.py @@ -3,10 +3,10 @@ from amuse.community.sse.interface import SSE from amuse.community.bhtree.interface import BHTree + class TestsForIssue123(amusetest.TestCase): - def test1(self): # doesn't trigger recursion error - self.assertRaises(Exception, BHTree, name_of_the_worker="bogus",expected_message= - "__init__() got multiple values for keyword argument 'name_of_the_worker'") - def test2(self): # does - self.assertRaises(Exception, SSE, name_of_the_worker="bogus",expected_message= - "__init__() got multiple values for keyword argument 'name_of_the_worker'") + def test1(self): # doesn't trigger recursion error + self.assertRaises(Exception, BHTree, name_of_the_worker="bogus", expected_message="__init__() got multiple values for keyword argument 'name_of_the_worker'") + + def test2(self): # does + self.assertRaises(Exception, SSE, name_of_the_worker="bogus", expected_message="__init__() got multiple values for keyword argument 'name_of_the_worker'") diff --git a/src/amuse/test/suite/ticket_tests/test_issue850.py b/src/amuse/test/suite/ticket_tests/test_issue850.py index 924b89a4ad..831cf4111f 100644 --- a/src/amuse/test/suite/ticket_tests/test_issue850.py +++ b/src/amuse/test/suite/ticket_tests/test_issue850.py @@ -7,10 +7,11 @@ from amuse.support.console import set_printing_strategy from amuse.units import units + class TestsForIssue850(amusetest.TestCase): def create_stars_and_binaries(self, binary_pair=[0, 1]): stars = Particles(3) - stars[0].initial_mass = 14 | units.MSun + stars[0].initial_mass = 14 | units.MSun stars[1].initial_mass = 10 | units.MSun stars[2].initial_mass = 9 | units.MSun stars.mass = stars.initial_mass @@ -45,7 +46,7 @@ def test_do_all_stars_evolve_no_binary(self, code=Seba): for i in range(len(stars)): self.assertNotEqual(stars[i].mass, stars[i].initial_mass) instance.stop() - + def _test_do_all_stars_evolve_no_binary_bse(self): self.test_do_all_stars_evolve_no_binary(code=Bse) @@ -132,7 +133,7 @@ def test_do_all_stars_evolve_alternative_binary(self): instance.evolve_model(end_time) channel_stars.copy() channel_binary.copy() - + # All stars need to have evolved print( f"t: {end_time}, m: {stars[0].mass} {stars[1].mass} {stars[2].mass} " @@ -163,7 +164,7 @@ def test_do_all_stars_evolve_alternative_binary_extra_stars(self): instance.evolve_model(end_time) channel_stars.copy() channel_binary.copy() - + # All stars need to have evolved print( f"t: {end_time}, m: {stars[0].mass} {stars[1].mass} {stars[2].mass} " diff --git a/src/amuse/test/suite/ticket_tests/test_ticket118.py b/src/amuse/test/suite/ticket_tests/test_ticket118.py index 75e3de8eb2..791fa2d4cc 100644 --- a/src/amuse/test/suite/ticket_tests/test_ticket118.py +++ b/src/amuse/test/suite/ticket_tests/test_ticket118.py @@ -4,21 +4,22 @@ from amuse import io from amuse.units import units + class TestsForTicket118(amusetest.TestCase): - + def test1(self): filename = os.path.join(os.path.dirname(__file__), 'FinalSnapshot.out') set = io.read_set_from_file(filename, 'dyn') - + self.assertEqual(len(set), 10) - + def test2(self): filename = os.path.join(os.path.dirname(__file__), 'FinalSnapshot.out') - + root = io.read_set_from_file(filename, 'dyn', return_children=False) - + self.assertFalse(root is None) - + def test3(self): filename = os.path.join(os.path.dirname(__file__), 'FinalSnapshot.out') set = io.read_set_from_file(filename, 'dyn') @@ -26,4 +27,4 @@ def test3(self): print("set[0].parent.mass", set[0].parent.mass) self.assertAlmostRelativeEquals(0.000227826766314251919 * 617.75586357299929284496, set[9].mass.value_in(units.MSun), 12) self.assertAlmostRelativeEquals(617.75586357299929284496 * 0.953575109205781479, set[0].parent.mass.value_in(units.MSun), 12) - #self.assertTrue(False) + # self.assertTrue(False) diff --git a/src/amuse/test/suite/ticket_tests/test_ticket208.py b/src/amuse/test/suite/ticket_tests/test_ticket208.py index 88cf82a255..b69bf0cedd 100644 --- a/src/amuse/test/suite/ticket_tests/test_ticket208.py +++ b/src/amuse/test/suite/ticket_tests/test_ticket208.py @@ -13,40 +13,42 @@ from amuse.units import nbody_system from amuse.units import units from amuse import datamodel + + class TestsForTicket208(amusetest.TestCase): - + def _run_addition_removal_test( self, - instance, - length_unit = nbody_system.length, - speed_unit = nbody_system.speed, - mass_unit = nbody_system.mass + instance, + length_unit=nbody_system.length, + speed_unit=nbody_system.speed, + mass_unit=nbody_system.mass ): - + instance.initialize_code() - + particles = datamodel.Particles(10) - particles.mass = numpy.arange(1,11) | mass_unit - particles.radius = numpy.arange(1,11) | length_unit - particles.x = numpy.arange(1,11) | length_unit - particles.y = numpy.arange(1,11) | length_unit - particles.z = numpy.arange(1,11) | length_unit - particles.vx = numpy.arange(1,11) | speed_unit - particles.vy = numpy.arange(1,11) | speed_unit - particles.vz = numpy.arange(1,11) | speed_unit - + particles.mass = numpy.arange(1, 11) | mass_unit + particles.radius = numpy.arange(1, 11) | length_unit + particles.x = numpy.arange(1, 11) | length_unit + particles.y = numpy.arange(1, 11) | length_unit + particles.z = numpy.arange(1, 11) | length_unit + particles.vx = numpy.arange(1, 11) | speed_unit + particles.vy = numpy.arange(1, 11) | speed_unit + particles.vz = numpy.arange(1, 11) | speed_unit + instance.particles.add_particles(particles) instance.commit_particles() - + self.assertEqual(len(instance.particles), 10) - self.assertAlmostRelativeEquals(instance.particles.mass.as_quantity_in(mass_unit), list(numpy.arange(1,11)) | mass_unit) - + self.assertAlmostRelativeEquals(instance.particles.mass.as_quantity_in(mass_unit), list(numpy.arange(1, 11)) | mass_unit) + instance.particles.remove_particle(particles[2]) instance.particles.remove_particle(particles[5]) - + self.assertEqual(len(instance.particles), 8) - self.assertAlmostRelativeEquals(instance.particles.mass.as_quantity_in(mass_unit), [1,2,4,5,7,8,9,10] | mass_unit) - + self.assertAlmostRelativeEquals(instance.particles.mass.as_quantity_in(mass_unit), [1, 2, 4, 5, 7, 8, 9, 10] | mass_unit) + particles_new = datamodel.Particles(1) particles_new.mass = 20 | mass_unit particles_new.radius = 21 | length_unit @@ -56,40 +58,40 @@ def _run_addition_removal_test( particles_new.vx = 25 | speed_unit particles_new.vy = 26 | speed_unit particles_new.vz = 27 | speed_unit - + instance.particles.add_particles(particles_new) self.assertEqual(len(instance.particles), 9) - - self.assertAlmostRelativeEquals(instance.particles.mass.as_quantity_in(mass_unit), [1,2,4,5,7,8,9,10,20] | mass_unit) - self.assertAlmostRelativeEquals(instance.particles.x.as_quantity_in(length_unit), [1,2,4,5,7,8,9,10,22] | length_unit) - + + self.assertAlmostRelativeEquals(instance.particles.mass.as_quantity_in(mass_unit), [1, 2, 4, 5, 7, 8, 9, 10, 20] | mass_unit) + self.assertAlmostRelativeEquals(instance.particles.x.as_quantity_in(length_unit), [1, 2, 4, 5, 7, 8, 9, 10, 22] | length_unit) + instance.cleanup_code() instance.stop() - + def test1(self): - + instance = Hermite() self._run_addition_removal_test(instance) - + def test2(self): - + instance = PhiGRAPE() self._run_addition_removal_test(instance) - + def test3(self): - + instance = BHTree() self._run_addition_removal_test(instance) - + def test4(self): - + instance = ph4() self._run_addition_removal_test(instance) - + def test5(self): instance = Fi() self._run_addition_removal_test(instance) - + def test6(self): length_unit = units.parsec speed_unit = units.parsec / units.Myr diff --git a/src/amuse/units/generic_unit_converter.py b/src/amuse/units/generic_unit_converter.py index 1f049a8a8f..1c99ea4c73 100644 --- a/src/amuse/units/generic_unit_converter.py +++ b/src/amuse/units/generic_unit_converter.py @@ -73,7 +73,7 @@ class ConvertBetweenGenericAndSiUnits(object): """ def __init__(self, *arguments_list): - + self.check_arguments(arguments_list) self.values = arguments_list @@ -81,22 +81,22 @@ def __init__(self, *arguments_list): self.units_of_values = [x.unit for x in self.values] self.system_rank = len(self.values) - self.new_base = numpy.mat(numpy.zeros((self.system_rank,self.system_rank))) - self.new_base_inv = numpy.mat(numpy.zeros((self.system_rank,self.system_rank))) + self.new_base = numpy.zeros((self.system_rank,self.system_rank)) + self.new_base_inv = numpy.zeros((self.system_rank,self.system_rank)) available_units = set() for unit in self.units_of_values: for factor, base_unit in unit.base: available_units.add(base_unit) - if not len(available_units) is self.system_rank: + if len(available_units) is not self.system_rank: raise UnitsNotOrtogonalException(self.system_rank, len(available_units)) - self.list_of_available_units = list(available_units) - + self.list_of_available_units = numpy.array(list(available_units)) + self.new_base = self.determine_new_base() rank_of_new_base = self.matrixrank(self.new_base) if rank_of_new_base < self.system_rank: raise UnitsNotOrtogonalException(self.system_rank, rank_of_new_base) - self.new_base_inv = self.new_base ** -1 + self.new_base_inv = numpy.linalg.matrix_power(self.new_base, -1) def check_arguments(self, arguments): @@ -107,25 +107,36 @@ def check_arguments(self, arguments): raise NotAQuantityException(index, x) if not x.is_scalar(): raise NotAScalarException(index, x) - + def matrixrank(self, A, tol=1e-8): - s = numpy.linalg.svd(A,compute_uv=0) - return numpy.sum(numpy.where( s>tol, 1, 0 ) ) + s = numpy.linalg.svd(A, compute_uv=0) + return numpy.sum(numpy.where(s > tol, 1, 0)) def determine_new_base(self): - matrix = numpy.asmatrix(numpy.zeros((self.system_rank,self.system_rank))) + matrix = numpy.zeros((self.system_rank, self.system_rank)) for row, value in enumerate(self.values): for n, unit in value.unit.base: - matrix[row, [i for i, j in enumerate(self.list_of_available_units) if j == unit]] = n + matrix[ + row, + [ + column for column, available_unit in enumerate( + self.list_of_available_units + ) if available_unit == unit + ] + ] = n return matrix @late def conversion_factors(self): - factors_of_the_bases = numpy.asmatrix(numpy.zeros((self.system_rank,1))) + factors_of_the_bases = numpy.zeros((self.system_rank,1)) for row, value in enumerate(self.values): factors_of_the_bases[row] = value.number * value.unit.factor log_factors_of_the_bases = numpy.log(numpy.abs(factors_of_the_bases)) - result = numpy.array(numpy.exp(self.new_base_inv*log_factors_of_the_bases))[:,0] + result = numpy.array( + numpy.exp( + numpy.matmul(self.new_base_inv, log_factors_of_the_bases) + ) + )[:,0] return result @late @@ -134,7 +145,7 @@ def units(self): result = [] generic_units = mass, length, time, temperature, current, luminous_intensity - for n, unit in enumerate(self.list_of_available_units): + for n, unit in enumerate(self.list_of_available_units): conversion_factor_for_this_base_unit = conversion_factors[n] for generic_unit in generic_units: if generic_unit.unit_in_si == unit: diff --git a/src/amuse/units/quantities.py b/src/amuse/units/quantities.py index 14a4a4a191..acb6650a02 100644 --- a/src/amuse/units/quantities.py +++ b/src/amuse/units/quantities.py @@ -636,7 +636,16 @@ def __setitem__(self, index, quantity): quantity = as_vector_quantity(quantity) if self.unit.is_zero(): self.unit = quantity.unit - self._number[index] = quantity.value_in(self.unit) + if ( + isinstance(quantity, VectorQuantity) + ): + if len(quantity) == 1: + self._number[index] = quantity[0].value_in(self.unit) + else: + self._number[index] = quantity[:].value_in(self.unit) + else: + self._number[index] = quantity.value_in(self.unit) + @property def number(self): diff --git a/support/setup_codes.py b/support/setup_codes.py index 08ce057b7a..b005fde2f5 100644 --- a/support/setup_codes.py +++ b/support/setup_codes.py @@ -1,46 +1,40 @@ - - -__revision__ = "$Id:$" - import warnings -import sys, os, re, subprocess +import sys +import os import os.path +import re import datetime -import stat from copy import deepcopy from os.path import abspath -from . import supportrc - try: import numpy except ImportError: - warnings.warn( "numpy etc needed during build; operation may fail" ) + warnings.warn("numpy needed during build; operation may fail") import configparser -from io import StringIO -from stat import ST_MODE -from distutils import sysconfig -from distutils.core import Command -from distutils.dep_util import newer +from subprocess import Popen, PIPE, STDOUT + +from glob import glob + from distutils.dir_util import create_tree -from distutils.util import convert_path from distutils import log from distutils import spawn from distutils import file_util from distutils.errors import DistutilsError from distutils.command.clean import clean -from distutils.command.install import install +from setuptools.command.install import install +from setuptools import Command from setuptools.command.build import build from setuptools.command.develop import develop from setuptools.command.editable_wheel import editable_wheel -from subprocess import call, Popen, PIPE, STDOUT +from . import supportrc if supportrc["framework_install"]: from .generate_main import generate_main - + try: from numpy.distutils import fcompiler except ImportError: @@ -48,8 +42,6 @@ # check if Python is called on the first line with this expression first_line_re = re.compile('^#!.*python[0-9.]*([ \t].*)?$') - -from glob import glob def pyfiles_in_build_dir(builddir): module_files = glob(os.path.join(builddir, "*.py")) @@ -72,30 +64,30 @@ class InstallLibraries(Command): ('root=', None, "install everything relative to this alternate root directory"), ] - negative_opt = {'no-inplace':'inplace'} - + negative_opt = {'no-inplace': 'inplace'} + boolean_options = ['inplace'] - def initialize_options (self): + def initialize_options(self): self.codes_dir = None self.lib_dir = None self.inplace = False self.build_lib = None self.build_temp = None self.install_data = None - self.root=None - - def finalize_options (self): + self.root = None + + def finalize_options(self): self.set_undefined_options( 'install', - ('build_lib', 'build_lib'), - ('root', 'root'), - ('install_data', 'install_data'), + ('build_lib', 'build_lib'), + ('root', 'root'), + ('install_data', 'install_data'), ) self.set_undefined_options( 'build', - ('build_temp', 'build_temp'), + ('build_temp', 'build_temp'), ) if self.lib_dir is None: @@ -107,41 +99,41 @@ def finalize_options (self): if self.inplace: pass else: - self.lib_dir=os.path.join(self.build_temp, 'lib') + self.lib_dir = os.path.join(self.build_temp, 'lib') def run(self): - data_dir = os.path.join(self.install_data,'share','amuse') # for the moment add to amuse.. + data_dir = os.path.join(self.install_data, 'share', 'amuse') # for the moment add to amuse.. data_dir = os.path.abspath(data_dir) # copy only: # '*.h', '*.a', '*.mod', '*.inc', '*.so', '*.dylib' - files=[os.path.join(dp, f) for dp, dn, fn in os.walk(self.lib_dir) for f in fn] - ext=['.h', '.a', '.mod', '.inc', '.so', '.dylib'] - files=[f for f in files if (os.path.splitext(f)[1] in ext)] - files=[os.path.relpath(f,self.lib_dir) for f in files] - create_tree(os.path.join(data_dir,'lib'), files) + files = [os.path.join(dp, f) for dp, dn, fn in os.walk(self.lib_dir) for f in fn] + ext = ['.h', '.a', '.mod', '.inc', '.so', '.dylib'] + files = [f for f in files if (os.path.splitext(f)[1] in ext)] + files = [os.path.relpath(f, self.lib_dir) for f in files] + create_tree(os.path.join(data_dir, 'lib'), files) for f in files: - src=os.path.join(self.lib_dir,f) - target=os.path.join(data_dir,'lib', f) - self.copy_file(src,target) + src = os.path.join(self.lib_dir, f) + target = os.path.join(data_dir, 'lib', f) + self.copy_file(src, target) class GenerateInstallIni(Command): - user_options = ( + user_options = ( ('build-dir=', 'd', "directory to install to"), ('install-data=', None, "installation directory for data files"), ('force', 'f', "force installation (overwrite existing files)"), ('root=', None, "install everything relative to this alternate root directory"), ) - + boolean_options = ['force'] - + def initialize_options(self): self.build_dir = None self.install_data = None self.force = False self.root = None - + def finalize_options(self): self.set_undefined_options( 'install', @@ -150,39 +142,36 @@ def finalize_options(self): ('root', 'root'), ('force', 'force'), ) - + def run(self): outfilename = os.path.join(self.build_dir, supportrc["package_name"], 'amuserc') - - + # this does not work for pip installs - #~ data_dir = os.path.join(self.install_data,'share','amuse') - #~ if not self.root is None: - #~ data_dir = os.path.relpath(data_dir,self.root) - #~ data_dir = os.path.join('/',data_dir) - #~ else: - #~ data_dir = os.path.abspath(data_dir) + # data_dir = os.path.join(self.install_data,'share','amuse') + # if not self.root is None: + # data_dir = os.path.relpath(data_dir,self.root) + # data_dir = os.path.join('/',data_dir) + # else: + # data_dir = os.path.abspath(data_dir) installinilines = [] installinilines.append('[channel]') installinilines.append('must_check_if_worker_is_up_to_date=0') installinilines.append('use_python_interpreter=1') - #installinilines.append('worker_code_directory={0}'.format(os.path.join(data_dir, 'bin'))) + # installinilines.append('worker_code_directory={0}'.format(os.path.join(data_dir, 'bin'))) if sys.platform == 'win32': installinilines.append('worker_code_suffix=".exe"') installinilines.append('[data]') - #~ installinilines.append('input_data_root_directory={0}'.format(os.path.join(data_dir, 'data'))) + # installinilines.append('input_data_root_directory={0}'.format(os.path.join(data_dir, 'data'))) installinilines.append('output_data_root_directory=_amuse_output_data') - #~ installinilines.append('amuse_root_dir={0}'.format(data_dir)) - + # installinilines.append('amuse_root_dir={0}'.format(data_dir)) + if 'BUILD_BINARY' in os.environ: installinilines.append('[test]') installinilines.append('can_run_tests_to_compile_modules=0') self.mkpath(os.path.join(self.build_dir, supportrc["package_name"])) file_util.write_file(outfilename, installinilines) - - class CodeCommand(Command): @@ -210,67 +199,65 @@ class CodeCommand(Command): ('lib-dir=', 'l', "directory containing libraries to build"), ] - negative_opt = {'no-inplace':'inplace'} - + negative_opt = {'no-inplace': 'inplace'} + boolean_options = ['force', 'inplace', 'debug', 'variant'] - def initialize_options (self): + def initialize_options(self): self.codes_dir = None self.lib_dir = None self.lib_src_dir = None - self.amuse_src_dir = os.path.join('src',supportrc["package_name"]) + self.amuse_src_dir = os.path.join('src', supportrc["package_name"]) self.environment = {} self.environment_notset = {} self.found_cuda = False self.found_sapporo = False self.variant = True self.inplace = False - + self.build_lib = None self.build_temp = None self.debug = None self.force = None - - - def finalize_options (self): + def finalize_options(self): self.set_undefined_options( 'build', - ('build_lib', 'build_lib'), - ('build_temp', 'build_temp'), - ('debug', 'debug'), - ('force', 'force'), + ('build_lib', 'build_lib'), + ('build_temp', 'build_temp'), + ('debug', 'debug'), + ('force', 'force'), ) - self.config=None + self.config = None if supportrc["framework_install"]: try: from . import config - self.config=config + self.config = config except ImportError: # continue pass else: from amuse import config - self.config=config + self.config = config if self.codes_dir is None: if self.inplace: self.codes_dir = os.path.join(self.amuse_src_dir,'community') self.codes_src_dir = self.codes_dir else: - #~ self.codes_dir = os.path.join(self.build_temp, 'src', 'amuse', 'community') + # self.codes_dir = os.path.join(self.build_temp, 'src', 'amuse', 'community') self.codes_dir = os.path.join(self.build_temp, 'codes') - self.codes_src_dir = os.path.join(self.amuse_src_dir,'community') + self.codes_src_dir = os.path.join(self.amuse_src_dir, 'community') else: if self.inplace: self.codes_src_dir = self.codes_dir else: self.codes_src_dir = self.codes_dir - #~ self.codes_dir=os.path.join(self.build_temp, 'src', 'amuse', 'community') - self.codes_dir=os.path.join(self.build_temp, 'codes') - + # self.codes_dir = os.path.join(self.build_temp, 'src', 'amuse', 'community') + self.codes_dir = os.path.join(self.build_temp, 'codes') + if self.lib_dir is None: if self.inplace: self.lib_dir = os.path.join('lib') @@ -289,14 +276,13 @@ def finalize_options (self): self.environment['PYTHON'] = self.config.interpreters.python else: self.environment['PYTHON'] = sys.executable - + self.set_cuda_variables() self.set_mpi_variables() self.set_compiler_variables() - - + self.set_fortran_variables() - + if 'FORTRAN' in self.environment: self.environment['F90'] = self.environment['FORTRAN'] self.environment['FC'] = self.environment['FORTRAN'] @@ -305,7 +291,7 @@ def finalize_options (self): self.set_libdir_variables() self.set_libs_variables() self.save_cfgfile_if_not_exists() - + if 'MSYSCON' in os.environ: pass else: @@ -317,74 +303,71 @@ def finalize_options (self): self.environment['AMUSE_DIR'] = get_amuse_root_dir() else: if self.inplace: - self.environment['AMUSE_DIR'] = os.path.abspath(os.getcwd()) + self.environment['AMUSE_DIR'] = os.path.abspath(os.getcwd()) else: - self.environment['AMUSE_DIR'] = os.path.abspath(self.build_temp) + self.environment['AMUSE_DIR'] = os.path.abspath(self.build_temp) if self.inplace: - self.environment['MUSE_PACKAGE_DIR'] = os.path.abspath(os.getcwd()) + self.environment['MUSE_PACKAGE_DIR'] = os.path.abspath(os.getcwd()) else: - self.environment['MUSE_PACKAGE_DIR'] = os.path.abspath(self.build_temp) + self.environment['MUSE_PACKAGE_DIR'] = os.path.abspath(self.build_temp) def set_fortran_variables(self): if 'FORTRAN' in self.environment: return - + if 'FORTRAN' in os.environ: self.environment['FORTRAN'] = os.environ['FORTRAN'] return - + if self.config: self.environment['FORTRAN'] = self.config.compilers.fc return - + if 'FC' in os.environ: self.environment['FORTRAN'] = os.environ['FC'] return - + if 'FORT' in os.environ: self.environment['FORTRAN'] = os.environ['FORT'] return - + if 'F90' in os.environ: self.environment['FORTRAN'] = os.environ['F90'] return - + mpif90 = os.environ['MPIF90'] if 'MPIF90' in os.environ else 'mpif90' - + try: - process = Popen([mpif90,'-show'], stdout = PIPE, stderr = PIPE) + process = Popen([mpif90, '-show'], stdout=PIPE, stderr=PIPE) stdoutstring, stderrstring = process.communicate() if process.returncode == 0: parts = stdoutstring.split() - self.environment['FORTRAN'] = parts[0] + self.environment['FORTRAN'] = parts[0] return - - process = Popen([mpif90,'--showme '], stdout = PIPE, stderr = PIPE) + + process = Popen([mpif90, '--showme '], stdout=PIPE, stderr=PIPE) stdoutstring, stderrstring = process.communicate() if process.returncode == 0: parts = stdoutstring.split() - self.environment['FORTRAN'] = parts[0] - return + self.environment['FORTRAN'] = parts[0] + return except: pass - - - if fcompiler: + + if fcompiler: compiler = fcompiler.new_fcompiler(requiref90=True) if compiler is not None: fortran_executable = compiler.executables['compiler_f90'][0] self.environment['FORTRAN'] = fortran_executable - - - + def is_mpi_enabled(self): if self.config and hasattr(self.config.mpi, 'is_enabled'): return self.config.mpi.is_enabled else: return True - + def set_cuda_variables(self): all_found = True if self.config and self.config.cuda.is_enabled: @@ -396,9 +379,9 @@ def set_cuda_variables(self): self.environment['CUDA_LIBS'] = self.config.cuda.cuda_libs else: raise DistutilsError("configuration is not up to date for cuda, please reconfigure amuse by running 'configure --enable-cuda'") - + return - + if self.config and not self.config.cuda.is_enabled: self.found_cuda = True self.environment['CUDA_LIBDIRS'] = '-L/NOCUDACONFIGURED/lib' + ' -LNOCUDACONFIGURED/lib64' @@ -412,20 +395,20 @@ def set_cuda_variables(self): if not x in self.environment: all_found = False break - + if all_found: cuda_dir = self.environment['CUDA_TK'] - self.environment['CUDA_LIBDIRS'] = '-L'+cuda_dir+'/lib' + ' -L'+cuda_dir+'/lib64' + self.environment['CUDA_LIBDIRS'] = '-L'+cuda_dir+'/lib' + ' -L'+cuda_dir+'/lib64' self.environment['CUDA_LIBS'] = '-lcudart' return - - dir = spawn.find_executable('nvcc') - if dir is None: + + directory = spawn.find_executable('nvcc') + if directory is None: self.found_cuda = False self.environment_notset['CUDA_SDK'] = '' self.environment_notset['CUDA_TK'] = '' return - cuda_dir = os.path.dirname(os.path.dirname(dir)) + cuda_dir = os.path.dirname(os.path.dirname(directory)) self.environment['CUDA_LIBDIRS'] = '-L'+cuda_dir+'/lib' + ' -L'+cuda_dir+'/lib64' self.environment['CUDA_LIBS'] = '-lcudart' self.environment['CUDA_TK'] = cuda_dir @@ -441,11 +424,10 @@ def set_mpi_variables(self): self.environment['MPIF90'] = self.config.mpi.mpif95 return - def set_compiler_variables(self): if self.config and not hasattr(self.config.compilers, 'found_fftw'): raise DistutilsError("configuration is not up to date, please reconfigure amuse by running 'configure'") - + if self.config: self.environment['CXX'] = self.config.compilers.cxx self.environment['CC'] = self.config.compilers.cc @@ -453,16 +435,15 @@ def set_compiler_variables(self): self.environment['CFLAGS'] = self.config.compilers.cc_flags self.environment['CXXFLAGS'] = self.config.compilers.cxx_flags self.environment['FFLAGS'] = self.config.compilers.fc_flags - + if self.config.compilers.found_fftw == 'yes': self.environment['FFTW_FLAGS'] = self.config.compilers.fftw_flags self.environment['FFTW_LIBS'] = self.config.compilers.fftw_libs - - + if self.config.compilers.found_gsl == 'yes': self.environment['GSL_FLAGS'] = self.config.compilers.gsl_flags self.environment['GSL_LIBS'] = self.config.compilers.gsl_libs - + return def set_java_variables(self): @@ -483,17 +464,17 @@ def set_openmp_flags(self): else: self.environment['OPENMP_FCFLAGS'] = '' self.environment['OPENMP_CFLAGS'] = '' - + def set_libdir_variables(self): for varname in ('SAPPORO_LIBDIRS', 'GRAPE6_LIBDIRS'): if varname in self.environment: continue - + if varname in os.environ: self.environment[varname] = os.environ[varname] else: - self.environment_notset[varname] ='-L' - + self.environment_notset[varname] = '-L' + if 'SAPPORO_LIBDIRS' in self.environment: self.environment['SAPPORO_LIBS'] = '-L{0} -lsapporo'.format( self.environment['SAPPORO_LIBDIRS'] @@ -514,105 +495,101 @@ def set_libdir_variables(self): os.path.abspath(os.getcwd()) ) self.environment['BOOSTLIBS'] = '' - + def set_libs_variables(self): for varname, libname in []: if varname in self.environment: continue - + if varname in os.environ: self.environment[varname] = os.environ[varname] else: self.environment_notset[varname] ='-L -l{0}'.format(libname) def copy_config_to_build_dir(self): - configpath=os.path.abspath(os.getcwd()) + configpath = os.path.abspath(os.getcwd()) if self.inplace: - topath=self.amuse_src_dir + topath = self.amuse_src_dir else: - topath=os.path.join(self.build_lib, "amuse") - self.copy_file(os.path.join(configpath,"config.mk"), topath) - + topath = os.path.join(self.build_lib, "amuse") + self.copy_file(os.path.join(configpath, "config.mk"), topath) + def copy_build_prereq_to_build_dir(self): if not os.path.exists(self.build_temp): self.mkpath(self.build_temp) if supportrc["framework_install"]: - configpath=os.path.abspath(os.getcwd()) - self.copy_file(os.path.join(configpath,"config.mk"), self.build_temp) - #~ self.copy_tree(os.path.join(configpath,"support"), os.path.join(self.build_temp,"support") ) - #~ self.copy_tree(os.path.join(configpath,"src"), os.path.join(self.build_temp,"src") ) - path=os.path.join(self.build_temp,"src") + configpath = os.path.abspath(os.getcwd()) + self.copy_file(os.path.join(configpath, "config.mk"), self.build_temp) + # self.copy_tree(os.path.join(configpath,"support"), os.path.join(self.build_temp,"support") ) + # self.copy_tree(os.path.join(configpath,"src"), os.path.join(self.build_temp,"src") ) + path = os.path.join(self.build_temp, "src") if not os.path.exists(path) and not os.path.islink(path): - os.symlink(os.path.relpath(self.build_lib,self.build_temp), path) - + os.symlink(os.path.relpath(self.build_lib, self.build_temp), path) + def copy_codes_to_build_dir(self): - for dir in self.makefile_paths(self.codes_src_dir): - reldir = os.path.relpath(dir, self.codes_src_dir) + for directory in self.makefile_paths(self.codes_src_dir): + reldir = os.path.relpath(directory, self.codes_src_dir) self.copy_tree( - dir, + directory, os.path.join(self.codes_dir, reldir) ) - + def copy_lib_to_build_dir(self): - for dir in self.makefile_paths(self.lib_src_dir): - reldir = os.path.relpath(dir, self.lib_src_dir) + for directory in self.makefile_paths(self.lib_src_dir): + reldir = os.path.relpath(directory, self.lib_src_dir) self.copy_tree( - dir, + directory, os.path.join(self.lib_dir, reldir) ) - def copy_worker_codes_to_build_dir(self): if sys.platform == 'win32': worker_code_re = re.compile(r'(([a-zA-Z0-9]+_)*)?worker(_[a-zA-Z0-9]+)?(.exe)?') else: worker_code_re = re.compile(r'(([a-zA-Z0-9]+_)*)?worker(_[a-zA-Z0-9]+)?') worker_so_re = re.compile(r'(([a-zA-Z0-9]+_)*)?cython(_[a-zA-Z0-9]+)?.so') - - + lib_binbuilddir = os.path.join(self.build_lib, supportrc["package_name"], '_workers') if not os.path.exists(lib_binbuilddir): self.mkpath(lib_binbuilddir) - + for srcdir in self.makefile_paths(self.codes_src_dir): reldir = os.path.relpath(srcdir, self.codes_src_dir) temp_builddir = os.path.join(self.codes_dir, reldir) - - self.announce("will copy worker: {0}".format(srcdir), level = log.INFO) + + self.announce("will copy worker: {0}".format(srcdir), level=log.INFO) lib_builddir = os.path.join(self.build_lib, os.path.relpath(srcdir, os.path.join(self.amuse_src_dir, '..'))) - - + shortname = reldir.lower() - self.announce(shortname, level = log.INFO) - + self.announce(shortname, level=log.INFO) + for name in os.listdir(temp_builddir): path = os.path.join(temp_builddir, name) stat = os.stat(path) - + if os.path.isfile(path): if worker_so_re.match(name): topath = os.path.join(lib_builddir, name) self.copy_file(path, topath) continue - - #self.announce("will copy worker: {0}".format(name), level = log.INFO) + # self.announce("will copy worker: {0}".format(name), level = log.INFO) if os.path.isfile(path) and os.access(path, os.X_OK): if worker_code_re.match(name): topath = os.path.join(lib_binbuilddir, name) self.copy_file(path, topath) elif not name.endswith('.py'): - self.announce("will not copy executable: {0}, it does not match the worker pattern".format(name), level = log.WARN) + self.announce("will not copy executable: {0}, it does not match the worker pattern".format(name), level=log.WARN) # also copy file or dir named data - path=os.path.join(temp_builddir,'data') + path = os.path.join(temp_builddir, 'data') topath = os.path.join(lib_builddir, 'data') if os.path.isfile(path): - self.copy_file(path, topath) + self.copy_file(path, topath) if os.path.isdir(path): - self.copy_tree(path, topath) + self.copy_tree(path, topath) def copy_worker_codes(self): if sys.platform == 'win32': @@ -620,21 +597,21 @@ def copy_worker_codes(self): else: worker_code_re = re.compile(r'(([a-zA-Z0-9]+_)*)?worker(_[a-zA-Z0-9]+)?') worker_so_re = re.compile(r'(([a-zA-Z0-9]+_)*)?cython(_[a-zA-Z0-9]+)?.so') - + for srcdir in self.makefile_paths(self.codes_src_dir): reldir = os.path.relpath(srcdir, self.codes_src_dir) temp_builddir = os.path.join(self.codes_dir, reldir) - - self.announce("will copy worker: {0}".format(srcdir), level = log.INFO) + + self.announce("will copy worker: {0}".format(srcdir), level=log.INFO) lib_builddir = os.path.join(self.build_lib, os.path.relpath(srcdir, os.path.join(self.amuse_src_dir, '..'))) shortname = reldir.lower() - self.announce(shortname, level = log.INFO) + self.announce(shortname, level=log.INFO) for name in os.listdir(temp_builddir): path = os.path.join(temp_builddir, name) stat = os.stat(path) - + if os.path.isfile(path): if worker_so_re.match(name): topath = os.path.join(lib_builddir, name) @@ -646,17 +623,17 @@ def copy_worker_codes(self): topath = os.path.join(lib_builddir, name) self.copy_file(path, topath) elif not name.endswith('.py'): - self.announce("will not copy executable: {0}, it does not match the worker pattern".format(name), level = log.WARN) + self.announce("will not copy executable: {0}, it does not match the worker pattern".format(name), level=log.WARN) # also copy file or dir named data - path=os.path.join(temp_builddir,'data') + path = os.path.join(temp_builddir, 'data') topath = os.path.join(lib_builddir, 'data') if os.path.isfile(path): - self.copy_file(path, topath) + self.copy_file(path, topath) if os.path.isdir(path): self.copy_tree(path, topath) - - def subdirs_in_path(self,path): + + def subdirs_in_path(self, path): if not os.path.exists(path): return @@ -664,12 +641,12 @@ def subdirs_in_path(self,path): for name in names: if name.startswith('.'): continue - + path_ = os.path.join(path, name) if os.path.isdir(path_): yield path_ - def makefile_paths(self,path): + def makefile_paths(self, path): for x in self.subdirs_in_path(path): for name in ('makefile', 'Makefile'): makefile_path = os.path.join(x, name) @@ -687,25 +664,22 @@ def update_environment_from_cfgfile(self): self.environment[varname] = value if varname in self.environment_notset: del self.environment_notset[varname] - + def save_cfgfile_if_not_exists(self): if not os.path.exists('amuse.cfg'): config = configparser.RawConfigParser() config.add_section('environment') for name, value in self.environment.items(): config.set('environment', name, value) - + for name, value in self.environment_notset.items(): config.set('environment', name, '') - + with open('amuse.cfg', 'w') as f: config.write(f) - - - def get_special_targets(self, name, directory, environment): - process = Popen(['make','-qp', '-C', directory], env = environment, stdout = PIPE, stderr = PIPE) + process = Popen(['make', '-qp', '-C', directory], env=environment, stdout=PIPE, stderr=PIPE) stdoutstring, stderrstring = process.communicate() stdoutstring = str(stdoutstring, 'utf-8') lines = stdoutstring.splitlines() @@ -719,130 +693,131 @@ def get_special_targets(self, name, directory, environment): index_of_the_colon = line.index(':') if(index_of_the_colon > 0): targetname = line[len('muse_worker_'):index_of_the_colon] - if '%' not in targetname: result.append((line[:index_of_the_colon], targetname,)) + if '%' not in targetname: + result.append((line[:index_of_the_colon], targetname,)) elif line.startswith('worker_code_'): index_of_the_colon = line.index(':') if(index_of_the_colon > 0): targetname = line[len('worker_code_'):index_of_the_colon] - if '%' not in targetname: result.append((line[:index_of_the_colon], targetname,)) + if '%' not in targetname: + result.append((line[:index_of_the_colon], targetname,)) elif line.startswith(name + '_worker_'): index_of_the_colon = line.index(':') if(index_of_the_colon > 0): targetname = line[len(name + '_worker_'):index_of_the_colon] - if '%' not in targetname: result.append((line[:index_of_the_colon], targetname,)) - - result=list(set(result)) - + if '%' not in targetname: + result.append((line[:index_of_the_colon], targetname,)) + + result = list(set(result)) + return result - - def call(self, arguments, buildlogfile = None, **keyword_arguments): + + def call(self, arguments, buildlogfile=None, **keyword_arguments): stringio = [] - + self.announce(' '.join(arguments), log.DEBUG) - + process = Popen( - arguments, - stdout = PIPE, - stderr = STDOUT, + arguments, + stdout=PIPE, + stderr=STDOUT, **keyword_arguments ) - + while True: line = process.stdout.readline() if len(line) == 0: break - - if not buildlogfile is None: + + if buildlogfile is not None: buildlogfile.write(line) self.announce(line[:-1].decode("utf-8"), log.DEBUG) stringio.append(str(line, 'utf-8')) - + result = process.wait() content = ''.join(stringio) - - if result!=0: + + if result != 0: self.announce("error in call, tail output:\n", log.INFO) self.announce(''.join(stringio[-100:]), log.INFO) self.announce("-"*80, log.INFO) return result, content - + def build_environment(self): - environment=self.environment.copy() + environment = self.environment.copy() environment.update(os.environ) - path=os.path.join(environment["MUSE_PACKAGE_DIR"],"src") - if environment["MUSE_PACKAGE_DIR"]!=environment["AMUSE_DIR"]: - path=path+":"+os.path.join(environment["AMUSE_DIR"],"src") - path=path+':'+environment.get("PYTHONPATH", "") - environment["PYTHONPATH"]=path + path = os.path.join(environment["MUSE_PACKAGE_DIR"], "src") + if environment["MUSE_PACKAGE_DIR"] != environment["AMUSE_DIR"]: + path = path+":"+os.path.join(environment["AMUSE_DIR"], "src") + path = path+':'+environment.get("PYTHONPATH", "") + environment["PYTHONPATH"] = path return environment - def do_clean(self): - environment = self.build_environment() + environment = self.build_environment() for x in self.makefile_paths(self.lib_dir): self.announce("cleaning libary " + x) - self.call(['make','-C', x, 'clean'], env=environment) - + self.call(['make', '-C', x, 'clean'], env=environment) + for x in self.makefile_paths(self.codes_dir): if os.path.exists(x): self.announce("cleaning " + x) - self.call(['make','-C', x, 'clean'], env=environment) + self.call(['make', '-C', x, 'clean'], env=environment) def do_distclean(self): - environment = self.build_environment() + environment = self.build_environment() for x in self.makefile_paths(self.lib_dir): self.announce("cleaning libary:" + x) - self.call(['make','-C', x, 'distclean'], env=environment) - + self.call(['make', '-C', x, 'distclean'], env=environment) + for x in self.makefile_paths(self.codes_dir): self.announce("cleaning community code:" + x) - self.call(['make','-C', x, 'distclean'], env=environment) + self.call(['make', '-C', x, 'distclean'], env=environment) - -class SplitOutput(object) : - def __init__(self, file1, file2) : +class SplitOutput(object): + def __init__(self, file1, file2): self.file1 = file1 self.file2 = file2 - def __del__(self) : + def __del__(self): self.close() def close(self): self.file1.close() self.file2.close() - def write(self, text) : + def write(self, text): self.file1.write(text) self.file2.write(text) - def flush(self) : + def flush(self): self.file1.flush() self.file2.flush() - - + + class BuildCodes(CodeCommand): description = "build interfaces to codes" user_options = list(CodeCommand.user_options) - user_options.append( ('clean=', 'c', "clean code",), ) + user_options.append(('clean=', 'c', "clean code",), ) def initialize_options(self): CodeCommand.initialize_options(self) self.clean = 'no' - - def finalize_options (self): + + def finalize_options(self): CodeCommand.finalize_options(self) self.must_clean = self.clean == 'yes' self.must_dist_clean = self.clean == 'dist' - + def run_make_on_directory(self, codename, directory, target, environment): buildlog = os.path.abspath("build.log") - + with open(buildlog, "a") as output: output.write('*'*100) output.write('\n') @@ -850,7 +825,7 @@ def run_make_on_directory(self, codename, directory, target, environment): output.write('*'*100) output.write('\n') output.flush() - + if environment.get('AMUSE_USE_CCACHE', 0) != "1" or "CCACHE_BASEDIR" in environment: build_environment = environment else: @@ -859,23 +834,23 @@ def run_make_on_directory(self, codename, directory, target, environment): with open(buildlog, "ab") as output: result, resultcontent = self.call( - ['make','-C', directory, target], + ['make', '-C', directory, target], output, - env = build_environment + env=build_environment ) - + with open(buildlog, "a") as output: output.write('*'*100) output.write('\n') - + return result, resultcontent - + def is_download_needed(self, string): for line in string.splitlines(): if 'DOWNLOAD_CODES' in line: return True return False - + def is_cuda_needed(self, string): for line in string.splitlines(): if 'CUDA_TK variable is not set' in line: @@ -883,14 +858,14 @@ def is_cuda_needed(self, string): if 'CUDA_SDK variable is not set' in line: return True return False - + def are_python_imports_needed(self, string): for line in string.splitlines(): if 'Python imports not available' in line: return True return False - - def run (self): + + def run(self): if self.must_clean: self.do_clean() if self.must_dist_clean: @@ -905,33 +880,33 @@ def run (self): lib_build = list() lib_not_build = list() environment = self.build_environment() - + buildlog = 'build.log' - - self.announce("building libraries and community codes", level = log.INFO) - self.announce("build, for logging, see '{0}'".format(buildlog), level = log.INFO) - + + self.announce("building libraries and community codes", level=log.INFO) + self.announce("build, for logging, see '{0}'".format(buildlog), level=log.INFO) + with open(buildlog, "w") as output: output.write('*'*100) output.write('\n') output.write('Building libraries and codes\n') output.write('*'*100) output.write('\n') - + if not self.lib_dir == self.lib_src_dir: self.copy_build_prereq_to_build_dir() self.copy_lib_to_build_dir() - + for x in self.makefile_paths(self.lib_dir): - + shortname = x[len(self.lib_dir) + 1:] + '-library' starttime = datetime.datetime.now() - self.announce("[{1:%H:%M:%S}] building {0}".format(shortname, starttime), level = log.INFO) + self.announce("[{1:%H:%M:%S}] building {0}".format(shortname, starttime), level=log.INFO) returncode, outputlog = self.run_make_on_directory(shortname, x, 'all', environment) - + endtime = datetime.datetime.now() if returncode == 2: - self.announce("[{2:%H:%M:%S}] building {0}, failed, see {1!r} for error log".format(shortname, buildlog, endtime), level = log.DEBUG) + self.announce("[{2:%H:%M:%S}] building {0}, failed, see {1!r} for error log".format(shortname, buildlog, endtime), level=log.DEBUG) if self.is_download_needed(outputlog): is_download_needed.append(x[len(self.lib_dir) + 1:]) elif self.is_cuda_needed(outputlog): @@ -939,36 +914,39 @@ def run (self): else: lib_not_build.append(shortname) else: - self.announce("[{1:%H:%M:%S}] building {0}, succeeded".format(shortname, endtime), level = log.DEBUG) + self.announce("[{1:%H:%M:%S}] building {0}, succeeded".format(shortname, endtime), level=log.DEBUG) lib_build.append(shortname) - + if not self.codes_dir == self.codes_src_dir: self.copy_codes_to_build_dir() - - #environment.update(self.environment) + + # environment.update(self.environment) makefile_paths = list(self.makefile_paths(self.codes_dir)) build_to_special_targets = {} - + for x in makefile_paths: shortname = x[len(self.codes_dir) + 1:].lower() starttime = datetime.datetime.now() # For binary builds we do not want # to distribute mesa, it will make the - # download size from about 100mb size + # download size from about 100mb size # to > 1Gb size. # # Could we remove some of the data files from mesa? # if not self.inplace and shortname == 'mesa': - self.announce("[{1:%H:%M:%S}] skipping {0}".format(shortname, starttime), level = log.INFO) - continue - - self.announce("[{1:%H:%M:%S}] building {0}".format(shortname, starttime), level = log.INFO) + self.announce("[{1:%H:%M:%S}] skipping {0}".format(shortname, starttime), level=log.INFO) + continue + + self.announce("[{1:%H:%M:%S}] building {0}".format(shortname, starttime), level=log.INFO) returncode, outputlog = self.run_make_on_directory(shortname, x, 'all', environment) endtime = datetime.datetime.now() if returncode > 0: - self.announce("[{2:%H:%M:%S}] building {0}, failed, see {1!r} for error log".format(shortname, buildlog, endtime), level = log.DEBUG) + self.announce( + "[{2:%H:%M:%S}] building {0}, failed, see {1!r} for error log".format(shortname, buildlog, endtime), + level=log.DEBUG + ) if self.is_download_needed(outputlog): is_download_needed.append(shortname) elif self.is_cuda_needed(outputlog): @@ -977,105 +955,126 @@ def run (self): are_python_imports_needed.append(shortname) else: not_build.append(shortname) - + if self.is_mpi_enabled(): continue else: build.append(shortname) is_built = True - self.announce("[{1:%H:%M:%S}] building {0}, succeeded".format(shortname, endtime), level = log.DEBUG) - + self.announce( + "[{1:%H:%M:%S}] building {0}, succeeded".format(shortname, endtime), + level=log.DEBUG + ) + if not self.variant: continue - + special_targets = self.get_special_targets(shortname, x, environment) - for target,target_name in special_targets: + for target, target_name in special_targets: starttime = datetime.datetime.now() - self.announce("[{2:%H:%M:%S}] building {0} - {1}".format(shortname, target_name, starttime), level = log.DEBUG) + self.announce( + "[{2:%H:%M:%S}] building {0} - {1}".format(shortname, target_name, starttime), + level=log.DEBUG + ) returncode, outputlog = self.run_make_on_directory(shortname, x, target, environment) endtime = datetime.datetime.now() if returncode > 0: specials_list = not_build_special.setdefault(shortname,[]) specials_list.append(target_name) - self.announce("[{3:%H:%M:%S}] building {0} - {1}, failed, see {2!r} for error log".format(shortname, target_name, buildlog,endtime), level = log.DEBUG) + self.announce( + "[{3:%H:%M:%S}] building {0} - {1}, failed, see {2!r} for error log".format(shortname, target_name, buildlog, endtime), + level=log.DEBUG + ) else: build_to_special_targets.setdefault(shortname, list()).append(target_name) - self.announce("[{2:%H:%M:%S}] building {0} - {1}, succeeded".format(shortname, target_name, endtime), level = log.DEBUG) - - #~ if supportrc["framework_install"]: - #~ self.copy_config_to_build_dir() - + self.announce( + "[{2:%H:%M:%S}] building {0} - {1}, succeeded".format(shortname, target_name, endtime), level=log.DEBUG + ) + + # if supportrc["framework_install"]: + # self.copy_config_to_build_dir() + if not self.codes_dir == self.codes_src_dir: - #~ self.copy_worker_codes_to_build_dir() + # self.copy_worker_codes_to_build_dir() self.copy_worker_codes() - + with open(buildlog, "a") as output: output.write('*'*80) output.write('\n') output.write('Building finished\n') output.write('*'*80) output.write('\n') - + self.announce("Environment variables") self.announce("="*80) sorted_keys = sorted(self.environment.keys()) for x in sorted_keys: - self.announce("%s\t%s" % (x , self.environment[x] )) - + self.announce("%s\t%s" % (x, self.environment[x])) + if not self.is_mpi_enabled(): all_build = set(build) not_build_copy = [] for x in not_build: if x in build_to_special_targets: - if not x in all_build: + if x not in all_build: build.append(x) all_build.add(x) else: not_build_copy.append(x) not_build = not_build_copy - - - if not_build or not_build_special or is_download_needed or is_cuda_needed or are_python_imports_needed: + + if ( + not_build + or not_build_special + or is_download_needed + or is_cuda_needed + or are_python_imports_needed + ): if not_build: level = log.WARN else: level = log.INFO if not_build: - self.announce("Community codes not built (because of errors/ missing libraries):", level = level) - self.announce("="*80, level = level) + self.announce( + "Community codes not built (because of errors/ missing libraries):", + level=level + ) + self.announce("="*80, level=level) for x in not_build: - self.announce(' * {0}'.format(x), level = level) + self.announce(' * {0}'.format(x), level=level) if not_build_special: - self.announce("Optional builds skipped, need special libraries:", level = level) + self.announce("Optional builds skipped, need special libraries:", level=level) for x in sorted(not_build_special.keys()): - self.announce(' * {0} - {1}'.format(x, ', '.join(not_build_special[x])), level = level) + self.announce(' * {0} - {1}'.format(x, ', '.join(not_build_special[x])), level=level) if is_cuda_needed: - self.announce("Optional builds skipped, need CUDA/GPU libraries:", level = level) + self.announce("Optional builds skipped, need CUDA/GPU libraries:", level=level) for x in is_cuda_needed: - self.announce(' * {0}'.format(x), level = level) + self.announce(' * {0}'.format(x), level=level) if are_python_imports_needed: - self.announce("Optional builds skipped, need additional python packages:", level = level) + self.announce("Optional builds skipped, need additional python packages:", level=level) for x in are_python_imports_needed: - self.announce(' * {0}'.format(x), level = level) + self.announce(' * {0}'.format(x), level=level) if is_download_needed: - self.announce("Optional builds skipped, need separate download", level = level) + self.announce("Optional builds skipped, need separate download", level=level) for x in is_download_needed: - self.announce(' * {0} , make {0}.code DOWNLOAD_CODES=1'.format(x), level = level) + self.announce( + f' * {x} , make {x}.code DOWNLOAD_CODES=1', level=level + ) + + self.announce("="*80, level=level) - self.announce("="*80, level = level) - if build: level = log.INFO - self.announce("Community codes built", level = level) - self.announce("="*80, level = level) + self.announce("Community codes built", level=level) + self.announce("="*80, level=level) for x in build: if x in build_to_special_targets: y = build_to_special_targets[x] - self.announce('* {0} ({1})'.format(x,','.join(y)), level = level) + self.announce('* {0} ({1})'.format(x, ','.join(y)), level=level) else: - self.announce('* {0}'.format(x), level = level) - self.announce("="*80, level = level) - + self.announce('* {0}'.format(x), level=level) + self.announce("="*80, level=level) + level = log.INFO self.announce( "{0} out of {1} codes built, {2} out of {3} libraries built".format( @@ -1084,14 +1083,14 @@ def run (self): len(lib_build), len(lib_build) + len(lib_not_build) ), - level = level + level=level ) self.announce("(not all codes and libraries need to be built)") if self.config and (not hasattr(self.config, 'java') or not hasattr(self.config.java, 'is_enabled')): self.announce( "Your configuration is out of date, please rerun configure", - level = level + level=level ) allow_build_failures=environment.get("AMUSE_ALLOW_BUILD_FAILURES", supportrc["allow_build_failures"]) @@ -1141,20 +1140,19 @@ class BuildCodes_inplace(BuildCodes): def initialize_options(self): BuildCodes.initialize_options(self) - self.inplace=True + self.inplace = True class ConfigureCodes(CodeCommand): description = "run configure for amuse" - def run (self): - + def run(self): if os.path.exists('config.mk') or self.config: - self.announce("Already configured, not running configure", level = 2) + self.announce("Already configured, not running configure", level=2) return environment = self.build_environment() - self.announce("Running configure for AMUSE", level = 2) + self.announce("Running configure for AMUSE", level=2) result,content=self.call(['./configure'], env=environment, shell=True) if not os.path.exists('config.mk'): self.announce("config.mk not generated; output of configure:", level=2) @@ -1167,37 +1165,36 @@ def run (self): self.announce(line[:-1], level=2) self.announce("="*80, level=2) - + class CleanCodes(CodeCommand): description = "clean build products in codes" - def run (self): - - self.announce("Cleaning libraries and community codes", level = 2) + def run(self): + self.announce("Cleaning libraries and community codes", level=2) self.do_clean() - - + + class DistCleanCodes(CodeCommand): description = "clean for distribution" - def run (self): - - self.announce("Cleaning for distribution, libraries and community codes", level = 2) + def run(self): + self.announce("Cleaning for distribution, libraries and community codes", level=2) self.do_distclean() - -class BuildOneCode(BuildCodes): + + +class BuildOneCode(BuildCodes): description = "build one code" user_options = list(BuildCodes.user_options) - user_options.append( ('code-name=', 'n', "name of the code",), ) + user_options.append(('code-name=', 'n', "name of the code",), ) def initialize_options(self): BuildCodes.initialize_options(self) self.code_name = None - - def finalize_options (self): + + def finalize_options(self): BuildCodes.finalize_options(self) if self.code_name is None: raise Exception("no code was specified") @@ -1205,7 +1202,7 @@ def finalize_options (self): def subdirs_in_path(self,path): if not os.path.exists(path): return - + names = os.listdir(path) for name in names: if name.startswith('.'): @@ -1219,20 +1216,20 @@ def subdirs_in_path(self,path): def run(self): if not self.inplace: self.run_command("build_py") - + BuildCodes.run(self) class Clean(clean): # make sure sub_commands are independent - sub_commands=list(clean.sub_commands) + sub_commands = list(clean.sub_commands) def run(self): for cmd_name in self.get_sub_commands(): self.run_command(cmd_name) class Install(install): - sub_commands=list(install.sub_commands) - + sub_commands = list(install.sub_commands) + def run(self): # this ensures sub commands are run first (only run once) for cmd_name in self.get_sub_commands(): @@ -1242,7 +1239,7 @@ def run(self): class Develop(develop): - sub_commands=list(develop.sub_commands) + sub_commands = list(develop.sub_commands) def run(self): # this ensures sub commands are run first (only run once) @@ -1253,12 +1250,12 @@ def run(self): class Editable_wheel(editable_wheel): - sub_commands=list(develop.sub_commands) + sub_commands = list(develop.sub_commands) def run(self): - build.sub_commands.remove( ('build_codes', None) ) - build.sub_commands.append( ('build_libraries_in_place', None) ) - + build.sub_commands.remove(('build_codes', None)) + build.sub_commands.append(('build_libraries_in_place', None)) + # this ensures sub commands are run first (only run once) for cmd_name in self.get_sub_commands(): self.run_command(cmd_name) @@ -1277,17 +1274,17 @@ def setup_commands(): 'build_libraries': BuildLibraries, 'build_libraries_in_place': BuildLibraries_inplace, 'install_libraries': InstallLibraries, - 'develop' : Develop, - 'develop_build' : BuildCodes_inplace, - 'editable_wheel' : Editable_wheel + 'develop': Develop, + 'develop_build': BuildCodes_inplace, + 'editable_wheel': Editable_wheel } - + build.sub_commands.append(('build_codes', None)) Clean.sub_commands.append(('clean_codes', None)) Clean.sub_commands.append(('clean_python', None)) Install.sub_commands.append(('install_libraries', None)) Develop.sub_commands.append(('build_libraries_in_place', None)) - + if supportrc["framework_install"]: mapping_from_command_name_to_command_class.update( { @@ -1300,6 +1297,4 @@ def setup_commands(): Install.sub_commands.insert(0, ('generate_install_ini', None)) Develop.sub_commands.insert(0, ('configure_codes', None)) - - return mapping_from_command_name_to_command_class