repo
stringlengths 2
99
| file
stringlengths 13
225
| code
stringlengths 0
18.3M
| file_length
int64 0
18.3M
| avg_line_length
float64 0
1.36M
| max_line_length
int64 0
4.26M
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
amuse
|
amuse-main/src/amuse/test/suite/codes_tests/test_stellar_evolution.py
|
from amuse.test.amusetest import TestWithMPI
from amuse.community.sse.interface import SSE
from amuse.community.mesa.interface import MESA
from amuse.community.evtwin.interface import EVtwin
from amuse.community.seba.interface import SeBa
from amuse.community.bse.interface import BSE
import numpy
import time
from amuse.units import units
from amuse import datamodel
class _TestStellarEvolutionCodes(TestWithMPI):
def code_factory(self):
self.skip("abstract test")
def test1(self):
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"))
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")
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))
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))
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)
def test7(self):
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)
def test8(self):
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)
"""
the following two tests will not work - this is to be fixed.
def test6(self):
instance=self.code_factory()()
p1=datamodel.Particle(mass=1. | units.MSun)
p2=datamodel.Particle(mass=1. | units.MSun,age=1.| units.Gyr)
p1=instance.particles.add_particle(p1)
p2=instance.particles.add_particle(p2)
self.assertAlmostEqual(p1.age, (0. | units.Gyr) )
self.assertAlmostEqual(p2.age, (1. | units.Gyr) )
def test7(self):
p1=datamodel.Particle(mass=8. | units.MSun)
p2=datamodel.Particle(mass=8. | units.MSun,age=42. | units.Myr)
instance1=self.code_factory()()
p1=instance1.particles.add_particle(p1)
instance2=self.code_factory()()
p2=instance2.particles.add_particle(p2)
instance1.evolve_model(44. | units.Myr)
instance1.evolve_model(2. | units.Myr)
self.assertalmostEqual( p1.mass,p2.mass)
"""
class TestSSECode(_TestStellarEvolutionCodes):
def code_factory(self):
return SSE
# class xTestBSECode(_TestStellarEvolutionCodes):
# def code_factory(self):
# return BSE
class TestMESACode(_TestStellarEvolutionCodes):
def code_factory(self):
try:
MESA()
except Exception as message:
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
| 5,971
| 34.760479
| 140
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/codes_tests/test_mesa_2208.py
|
from amuse.test.amusetest import TestWithMPI, get_path_to_results
import sys
import os.path
from subprocess import PIPE, Popen
import numpy
from math import ceil
from amuse.community.mesa_r2208.interface import MESA, MESAInterface
from amuse.support.exceptions import AmuseException
from amuse.units import units
from amuse.datamodel import Particles
from amuse.datamodel import Particle
from amuse.rfi import channel
from amuse.ext.spherical_model import EnclosedMassInterpolator
class TestMESAInterface(TestWithMPI):
def test1(self):
print("Testing initialization of the interface...")
instance = self.new_instance_of_an_optional_code(MESAInterface)
if instance is None:
print("MESA was not built. Skipping test.")
return
inlist_path = instance.default_path_to_inlist
# print "Path to inlist: ", inlist_path
MESA_data_path = instance.default_path_to_MESA_data
# print "Path to MESA data directory: ", MESA_data_path
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)
instance.stop()
def slowtest2(self):
print("Testing get/set of metallicity (tests new ZAMS model implicitly)...")
print("The first time this test will take quite some time"
" to generate new starting models.")
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.default_path_to_MESA_data, instance.get_output_directory())
status = instance.initialize_code()
self.assertEqual(status, 0)
(metallicity, error) = instance.get_metallicity()
self.assertEqual(0, error)
self.assertEqual(0.02, metallicity)
for x in [0.04, 0.02, 0.01, 0.00]:
error = instance.set_metallicity(x)
self.assertEqual(0, error)
(metallicity, error) = instance.get_metallicity()
self.assertEqual(0, error)
self.assertEqual(x, metallicity)
instance.stop()
def test3(self):
print("Testing basic operations: new_particle...")
instance = self.new_instance_of_an_optional_code(MESAInterface)
if instance is None:
print("MESA was not built. Skipping test.")
return
(maximum_number_of_stars, error) = instance.get_maximum_number_of_stars()
self.assertEqual(0, error)
self.assertEqual(maximum_number_of_stars, 1000)
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)
number_of_stars = 1
for i in range(number_of_stars):
# print i
(index_of_the_star, error) = instance.new_particle(0.5+i*1.0/number_of_stars)
self.assertEqual(0, error)
self.assertEqual(index_of_the_star, i+1)
# import time # To check the amount of memory is used ...
# time.sleep(10) # when a large number of stars is created.
instance.stop()
def test4(self):
print("Testing basic operations: evolve...")
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.default_path_to_MESA_data, instance.get_output_directory())
status = instance.initialize_code()
(index_of_the_star, error) = instance.new_particle(1.0)
self.assertEqual(0, error)
self.assertEqual(index_of_the_star, 1)
self.assertEqual(0, instance.commit_particles())
initial_dt = 1.0e5
dt_factor = 1.2
self.assertEqual([initial_dt, 0], list(instance.get_time_step(index_of_the_star).values()))
self.assertEqual(0, instance.evolve_one_step(index_of_the_star))
self.assertEqual([initial_dt, 0], list(instance.get_age(index_of_the_star).values()))
target_end_time = 3.0e5 # (years)
self.assertEqual(0, instance.evolve_for(index_of_the_star, target_end_time-initial_dt))
self.assertEqual([initial_dt*(1 + dt_factor + dt_factor**2), 0], list(instance.get_age(index_of_the_star).values()))
self.assertEqual([round(initial_dt*dt_factor**3), 0], list(instance.get_time_step(index_of_the_star).values()))
self.assertTrue(instance.get_age(index_of_the_star)['age'] >= 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)
(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)
(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)
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 "
"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.default_path_to_MESA_data, instance.get_output_directory())
status = instance.initialize_code()
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)):
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)
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)
instance.stop()
def test6(self):
print("Testing MESA stop conditions...")
instance = self.new_instance_of_an_optional_code(MESAInterface)
if instance is None:
print("MESA was not built. Skipping test.")
return
(value, error) = instance.get_max_age_stop_condition()
self.assertEqual(0, error)
self.assertEqual(1.0e36, value)
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()
self.assertEqual(0, error)
self.assertEqual(10 ** x, value)
(value, error) = instance.get_min_timestep_stop_condition()
self.assertEqual(0, error)
self.assertEqual(1.0e-6, value)
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)
if instance is None:
print("MESA was not built. Skipping test.")
return
(value, error) = instance.get_mixing_length_ratio()
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)
self.assertEqual(0, error)
(value, error) = instance.get_mixing_length_ratio()
self.assertEqual(0, error)
self.assertEqual(x, value)
(value, error) = instance.get_semi_convection_efficiency()
self.assertEqual(0, error)
self.assertEqual(0.0, value)
for x in [0.1, 0.04, 0.001]:
error = instance.set_semi_convection_efficiency(x)
self.assertEqual(0, error)
(value, error) = instance.get_semi_convection_efficiency()
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)
if instance is None:
print("MESA was not built. Skipping test.")
return
(value, error) = instance.get_RGB_wind_scheme()
self.assertEqual(0, error)
self.assertEqual(1, value)
for x in range(6):
error = instance.set_RGB_wind_scheme(x)
self.assertEqual(0, error)
(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(1, value)
for x in range(6):
error = instance.set_AGB_wind_scheme(x)
self.assertEqual(0, error)
(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)
for x in [0.0, 0.1, 0.5, 1.0]:
error = instance.set_reimers_wind_efficiency(x)
self.assertEqual(0, error)
(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)
for x in [0.0, 0.1, 0.5, 1.0]:
error = instance.set_blocker_wind_efficiency(x)
self.assertEqual(0, error)
(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)
for x in [0.0, 0.1, 0.5, 1.0]:
error = instance.set_de_jager_wind_efficiency(x)
self.assertEqual(0, error)
(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)
for x in [0.0, 0.1, 0.5, 1.0]:
error = instance.set_dutch_wind_efficiency(x)
self.assertEqual(0, error)
(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.default_path_to_MESA_data, instance.get_output_directory())
instance.initialize_code()
self.assertEqual(0.02 | units.no_unit, instance.parameters.metallicity)
self.assertEqual(1.0e36 | units.yr, instance.parameters.max_age_stop_condition)
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()
index_of_the_star = instance.new_particle(1.0 | units.MSun)
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)
self.assertAlmostEqual(time_step, initial_dt)
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)
M_of_the_star = instance.get_mass(index_of_the_star)
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)
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()
stars = Particles(1)
mass = 10. | units.MSun
stars.mass = mass
instance.particles.add_particles(stars)
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:
self.assertEqual(stars[0].mass, mass)
self.assertAlmostRelativeEqual(stars[0].luminosity, 5841. | units.LSun, 1)
instance.evolve_model()
from_code_to_model.copy()
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)
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))
results.append((star.age, star.mass, star.stellar_type))
previous_type = star.stellar_type
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,
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,
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)
stars.mass = masses
instance.initialize_code()
self.assertEqual(instance.parameters.max_age_stop_condition, 1e30 | units.Myr)
instance.parameters.max_age_stop_condition = max_age
self.assertEqual(instance.parameters.max_age_stop_condition, max_age)
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)
from_code_to_model.copy()
# 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', "
"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)
stars.mass = [1.0, 10.0] | units.MSun
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.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.")
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)
self.assertIsOfOrder(instance.particles[0].get_temperature_profile()[0], 1.0e7 | units.K)
self.assertIsOfOrder(instance.particles[0].get_luminosity_profile()[-1], 1.0 | units.LSun)
self.assertIsOfOrder(instance.particles[0].get_pressure_profile()[0], 1.0e17 | units.barye)
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)
delta_radius_cubed = (radius1**3 - radius2**3)
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)
stars.mass = 1.0 | units.MSun
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.particles.add_particles(stars)
instance.commit_particles()
instance.evolve_model()
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()
self.assertEqual(number_of_zones, 575)
self.assertEqual(number_of_species, 8)
self.assertEqual(len(species_names), number_of_species)
self.assertEqual(len(composition), number_of_species)
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,
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.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)
stars.mass = 1.0 | units.MSun
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.parameters.metallicity = 0.0
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_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()
self.assertEqual(number_of_zones, 578)
self.assertEqual(number_of_species, 8)
self.assertEqual(len(species_names), number_of_species)
self.assertEqual(len(composition), number_of_species)
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.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)
instance.stop()
def test9(self):
print("Test for changing the stellar structure model")
star = Particles(1)
star.mass = 1.0 | units.MSun
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.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 "
"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)
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)
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')
if instance is None:
print("MESA was not built. Skipping test.")
return
instance.initialize_code()
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)
self.assertAlmostEqual(composition[1:3, k_surface].sum(), (0.3) - 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
he4_profile = composition[2] * 1
composition[0] = alpha * he4_profile + (1-alpha) * h1_profile
composition[2] = (1-alpha) * he4_profile + alpha * h1_profile
instance.particles[0].set_chemical_abundance_profiles(composition)
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:3, k_surface].sum(), 0.7)
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 "
"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)
stars.mass = [1.0, 2.0, 3.0] | units.MSun
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.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)
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!
instance.stop()
def test12(self):
print("Test for importing new stellar models")
star = Particles(1)
star.mass = 1.0 | units.MSun
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.parameters.stabilize_new_stellar_model_flag = False
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)
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)
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(),
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(),
instance.native_stars[0].get_radius_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)
print(instance.particles)
instance.stop()
def slowtest13(self):
print("Testing MESA wind parameters...")
stars = Particles(9)
stars.mass = 10.0 | units.MSun
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.parameters.reimers_wind_efficiency = 0.5
instance.parameters.blocker_wind_efficiency = 0.1
instance.parameters.de_jager_wind_efficiency = 0.8
instance.parameters.dutch_wind_efficiency = 0.8
instance.commit_parameters()
for wind_scheme in [0, 1, 2, 3, 4]:
instance.parameters.RGB_wind_scheme = wind_scheme
instance.recommit_parameters()
instance.particles.add_particle(stars[wind_scheme])
instance.parameters.reimers_wind_efficiency *= 2.0
instance.parameters.blocker_wind_efficiency *= 2.0
instance.parameters.de_jager_wind_efficiency *= 2.0
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.particles.add_particle(stars[wind_scheme+4])
instance.commit_particles()
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)
instance.stop()
def test14(self):
print("Testing MESA wind parameters... (short version of slowtest13)")
stars = Particles(3)
stars.mass = 10.0 | units.MSun
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.parameters.RGB_wind_scheme = 0
instance.commit_parameters()
instance.particles.add_particle(stars[0])
instance.parameters.RGB_wind_scheme = 1
for i, wind_efficiency in enumerate([0.5, 1.0]):
instance.parameters.reimers_wind_efficiency = wind_efficiency
instance.recommit_parameters()
instance.particles.add_particle(stars[i+1])
instance.commit_particles()
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)
instance.stop()
def test15(self):
print("Testing MESA states")
stars = Particles(2)
stars.mass = 1.0 | units.MSun
instance = self.new_instance_of_an_optional_code(MESA)
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()
self.assertEqual(instance.get_name_of_current_state(), 'INITIALIZED')
instance.commit_parameters()
self.assertEqual(instance.get_name_of_current_state(), 'EDIT')
instance.particles.add_particle(stars[0])
instance.commit_particles()
self.assertEqual(instance.get_name_of_current_state(), 'RUN')
instance.cleanup_code()
self.assertEqual(instance.get_name_of_current_state(), 'END')
instance.stop()
print("ok")
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')
instance.parameters.RGB_wind_scheme = 1
instance.parameters.reimers_wind_efficiency = 0.5
self.assertEqual(instance.get_name_of_current_state(), 'INITIALIZED')
instance.particles.add_particle(stars[0])
self.assertEqual(instance.get_name_of_current_state(), 'EDIT')
mass = instance.particles[0].mass
self.assertEqual(instance.get_name_of_current_state(), 'RUN')
instance.particles.add_particle(stars[1])
self.assertEqual(instance.get_name_of_current_state(), 'UPDATE')
mass = instance.particles[0].mass
self.assertEqual(instance.get_name_of_current_state(), 'RUN')
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')
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
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)
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')
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():
if ("max_model_number" in one_line):
test_inlist.write(" max_model_number = "+str(number_of_steps+1)+"\n")
elif ("mesa_data_dir" in one_line):
test_inlist.write(" mesa_data_dir = '"+os.path.join(mesa_src_path, 'data')+"'\n")
elif ("zams_filename" in one_line):
test_inlist.write(" zams_filename = '"+os.path.join(instance.get_output_directory(), "star_data", "starting_models", "zams_z20m3.data")+"'\n")
else:
test_inlist.write(one_line)
instance.stop()
(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
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
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.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.evolve_for(330 | units.Myr)
for i in range(10):
star.evolve_for(10 | units.Myr)
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)
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.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))
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")
self.assertTrue(star.age > 1.0 | units.yr)
self.assertTrue(star.temperature < 4500 | units.K)
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)
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"])
c12_core_mass = star.calculate_core_mass(species=["c12"])
n14_core_mass = star.calculate_core_mass(species=["n14"])
o16_core_mass = star.calculate_core_mass(species=["o16"])
ne20_core_mass = star.calculate_core_mass(species=["ne20"])
mg24_core_mass = star.calculate_core_mass(species=["mg24"])
metal_core_mass = star.calculate_core_mass(species=["c12", "n14", "o16", "ne20", "mg24"])
print(h1_core_mass, he3_core_mass, he4_core_mass, c12_core_mass, n14_core_mass, o16_core_mass)
print(ne20_core_mass, mg24_core_mass, metal_core_mass)
self.assertAlmostRelativeEqual(star.core_mass, total_core_mass, 2)
instance.stop()
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,
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
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.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)
c12_core_mass = star.calculate_core_mass(species=["c12"], core_H_abundance_limit=limit)
n14_core_mass = star.calculate_core_mass(species=["n14"], core_H_abundance_limit=limit)
o16_core_mass = star.calculate_core_mass(species=["o16"], core_H_abundance_limit=limit)
ne20_core_mass = star.calculate_core_mass(species=["ne20"], core_H_abundance_limit=limit)
mg24_core_mass = star.calculate_core_mass(species=["mg24"], core_H_abundance_limit=limit)
metal_core_mass = star.calculate_core_mass(species=["c12", "n14", "o16", "ne20", "mg24"], core_H_abundance_limit=limit)
instance.stop()
self.assertAlmostRelativeEqual(h1_core_mass, expected_core_mass*0.68, 2)
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,
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))
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))
composition = star.get_chemical_abundance_profiles()
# Mimic hydrogen exhausted core:
composition[2, :100] = composition[2, :100] + composition[0, :100]
composition[0, :100] = 0
# Mimic helium exhausted core:
carbon_oxygen = composition[:6, :50].sum(axis=0)
composition[3, :50] = carbon_oxygen * 0.6
composition[5, :50] = carbon_oxygen * 0.4
composition[1:3, :50] = 0
composition[4, :50] = 0
star.set_chemical_abundance_profiles(composition)
self.assertAlmostRelativeEqual(star.calculate_core_mass(),
star.mass * star.get_cumulative_mass_profile()[100], 1)
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())
self.assertEqual(core_mass_by_species[0:3].sum(), 0 | units.MSun)
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))
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)
print("Accreting 75% deuterium", end=' ')
composition_light = [0, 0.75, 0, 0]
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(*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)
composition = star.get_chemical_abundance_profiles()
species = star.get_names_of_species()
print("Both deuterium and iron are not in the current net,")
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()
| 55,049
| 49.504587
| 171
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/codes_tests/test_hermite.py
|
from amuse.test.amusetest import TestWithMPI
import os
import sys
import numpy
import math
from amuse.community.hermite.interface import HermiteInterface, Hermite
from amuse.units import nbody_system
from amuse.units import units
from amuse import datamodel
from amuse.ic import plummer
from amuse.ic.plummer import new_plummer_model
from amuse.test.suite.codes_tests.gd_tests import (
_TestGravitationalDynamicsInterface,
)
try:
from matplotlib import pyplot
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
class TestHermiteInterface(_TestGravitationalDynamicsInterface, TestWithMPI):
def gravity_code_interface(self):
return HermiteInterface
def reference_includes(self):
return "Hut"
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])
retrieved_state = hermite.get_state(0)
retr = hermite.get_potential_at_point(0.01, 0, 0, 0)
self.assertEqual(retr['phi'], -20.0)
hermite.cleanup_code()
hermite.stop()
def test7(self):
instance = HermiteInterface()
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)
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 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)
instance.commit_particles()
potential, errorcode = instance.get_potential(id1)
self.assertEqual(errorcode, 0)
self.assertAlmostRelativeEquals(potential, -1.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):
print("Test HermiteInterface evolve_model")
instance = HermiteInterface()
self.assertEqual(0, instance.initialize_code())
self.assertEqual(0, instance.set_dt_param(0.001))
self.assertEqual(0, instance.set_end_time_accuracy_factor(0.0))
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(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.cleanup_code()
instance.stop()
class TestHermite(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.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
def test1(self):
convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km)
hermite = Hermite(convert_nbody)
hermite.initialize_code()
hermite.parameters.epsilon_squared = 0.0 | units.AU**2
hermite.parameters.end_time_accuracy_factor = 0.0
hermite.dt_dia = 5000
stars = self.new_system_of_sun_and_earth()
earth = stars[1]
hermite.particles.add_particles(stars)
hermite.evolve_model(365.0 | units.day)
hermite.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)
hermite.evolve_model(365.0 + (365.0 / 2) | units.day)
hermite.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)
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]
self.assertAlmostRelativeEqual(-position_at_start, position_after_half_a_rotation, 3)
hermite.cleanup_code()
hermite.stop()
def test2(self):
convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km)
instance = Hermite(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)
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.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()
def test3(self):
convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km)
instance = Hermite(convert_nbody)
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.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.radius = units.RSun(100.0)
instance.particles.add_particles(stars)
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()
def test4(self):
convert_nbody = nbody_system.nbody_to_si(5.0 | units.kg, 10.0 | units.m)
instance = Hermite(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.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.stop()
def test5(self):
convert_nbody = nbody_system.nbody_to_si(5.0 | units.kg, 10.0 | units.m)
instance = Hermite(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.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):
self.assertAlmostRelativeEquals(expected, actual)
instance.stop()
self.assertEqual(curr_state[0], 16 | units.kg, 8)
def test6(self):
print("Test6: Testing Hermite parameters")
convert_nbody = nbody_system.nbody_to_si(1.0 | units.yr, 1.0 | units.AU)
instance = Hermite(convert_nbody)
value = instance.get_eps2()
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)
for x in [0.001, 0.01, 0.1]:
instance.parameters.dt_param = x
self.assertAlmostEqual(x, instance.parameters.dt_param)
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_begin_time()
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 test7(self):
print("Test7: Testing effect of Hermite 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
sun.position = [0.0, 0.0, 0.0] | units.AU
sun.velocity = [0.0, 0.0, 0.0] | units.AU / units.yr
sun.radius = 1.0 | units.RSun
earth = particles[1]
earth.mass = 5.9736e24 | units.kg
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):
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] /
instance.particles[1].velocity[1])))
instance.stop()
# Small values of epsilon_squared should result in normal earth-sun dynamics: rotation of 90 degrees
self.assertAlmostEqual(abs(final_direction[0]), abs(initial_direction+math.pi/2.0), 2)
# Large values of epsilon_squared should result in ~ no interaction
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))
def test8(self):
print("Testing Hermite collision_detection")
particles = datamodel.Particles(7)
particles.mass = 0.001 | nbody_system.mass
particles.radius = 0.01 | nbody_system.length
particles.x = [-101.0, -100.0, -0.5, 0.5, 100.0, 101.0, 104.0] | nbody_system.length
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 = Hermite()
instance.initialize_code()
instance.parameters.set_defaults()
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) <=
(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)
print(instance.particles)
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) <=
(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)
instance = Hermite(convert_nbody)
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)
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.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.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.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.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
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.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)
instance.stop()
def test13(self):
particles = plummer.new_plummer_model(31)
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)
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]:
instance = Hermite(number_of_workers=n)
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]):
self.assertAlmostEqual(expected_positions, positions_per_workers[index], 15)
def test14(self):
instance = Hermite()
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.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)
self.assertAlmostEqual(fy, 0.0 | nbody_system.acceleration, 6)
self.assertAlmostEqual(fz, 0.0 | nbody_system.acceleration, 6)
for x in (0.25, 0.5, 0.75):
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, 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()
def test15(self):
particles = datamodel.Particles(2)
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.mass = 1.0 | nbody_system.mass
instance = Hermite()
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,
)
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()
instance = Hermite()
instance.initialize_code()
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
zero = numpy.zeros(len(x)) | nbody_system.length
potential0 = instance.get_potential_at_point(zero, x, zero, zero)
instance.stop()
for n in (2, 3, 4):
instance = Hermite(number_of_workers=n)
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)
self.assertAlmostRelativeEquals(potential0, potential, 8)
instance.stop()
def test17(self):
particles = new_plummer_model(50)
particles.scale_to_standard()
instance = Hermite()
instance.parameters.epsilon_squared = 0.22000 | nbody_system.length**2
instance.particles.add_particles(particles)
self.assertEqual(len(instance.particles), 50)
instance.reset()
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.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.mass = 1.0 | nbody_system.mass
instance = Hermite()
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)
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)
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)
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)
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)
instance.stop()
def test19(self):
particles = datamodel.Particles(2)
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.mass = 1.0 | nbody_system.mass
instance = Hermite()
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)
instance.stop()
def test20(self):
convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 149.5e6 | units.km)
hermite = Hermite(convert_nbody)
hermite.initialize_code()
hermite.parameters.epsilon_squared = 0.0 | units.AU**2
hermite.parameters.end_time_accuracy_factor = 0.0
hermite.parameters.is_time_reversed_allowed = True
stars = self.new_system_of_sun_and_earth()
earth = stars[1]
hermite.particles.add_particles(stars)
hermite.evolve_model(365.0 | units.day)
hermite.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)
hermite.evolve_model(365.0 - (365.0 / 2) | units.day)
hermite.particles.copy_values_of_all_attributes_to(stars)
position_after_half_a_rotation_backward = earth.position.value_in(units.AU)[0]
self.assertAlmostRelativeEqual(-position_at_start, position_after_half_a_rotation_backward, 4)
hermite.evolve_model(365.0 | units.day)
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)
hermite.cleanup_code()
hermite.stop()
def test21(self):
import pickle
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)
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
hermite.particles.add_particles(particles)
hermite.stopping_conditions.out_of_box_detection.enable()
hermite.parameters.stopping_conditions_out_of_box_size = 2 | nbody_system.length
hermite.parameters.stopping_conditions_out_of_box_use_center_of_mass = False
hermite.evolve_model(1 | nbody_system.time)
print(hermite.particles.x)
print(hermite.particles.key, particles[1].key)
print(hermite.stopping_conditions.out_of_box_detection.particles(0))
self.assertTrue(hermite.stopping_conditions.out_of_box_detection.is_set())
self.assertEqual(len(hermite.stopping_conditions.out_of_box_detection.particles(0)), 1)
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
hermite.particles.add_particles(particles)
hermite.evolve_model(1 | nbody_system.time)
print(hermite.particles.x)
self.assertAlmostRelativeEquals(hermite.model_time, 1 | nbody_system.time)
self.assertAlmostRelativeEquals(hermite.particles[0].x, 1 | nbody_system.length)
hermite.evolve_model(1.5 | nbody_system.time)
print(hermite.particles.x)
self.assertAlmostRelativeEquals(hermite.model_time, 1.5 | nbody_system.time)
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
hermite.stop()
hermite = Hermite(reuse_worker=True)
channel2 = hermite.legacy_interface.channel
hermite.stop()
self.assertEqual(id(channel1), id(channel2))
def test25(self):
hermite = Hermite()
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
hermite.particles.add_particles(particles)
request = hermite.particles.get_values_in_store_async(None, ["x"])
request.wait()
print(request.result())
self.assertEqual(request.result()[0], particles.x)
request = hermite.particles.get_values_in_store_async(None, ["x", "vx"])
request.wait()
print(request.result())
self.assertEqual(request.result()[0], particles.x)
self.assertEqual(request.result()[1], particles.vx)
p = particles.copy()
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.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.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.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.wait()
self.assertEqual(p.x, particles.x)
self.assertEqual(p.vx, particles.vx)
| 35,945
| 42.943765
| 126
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/codes_tests/test_bse.py
|
from amuse.community.bse.interface import BSE, BSEInterface
from amuse.test.amusetest import TestWithMPI
from amuse.units import units
from amuse.units import constants
from amuse.datamodel import Particles
import numpy
class TestBSEInterface(TestWithMPI):
class state(object):
def __init__(self):
self.type1 = 0.0
self.type2 = 0.0
self.initial_mass1 = 0.0
self.initial_mass2 = 0.0
self.mass1 = 0.0
self.mass2 = 0.0
self.radius1 = 0.0
self.radius2 = 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
self.core_radius2 = 0.0
self.envelope_mass1 = 0.0
self.envelope_mass2 = 0.0
self.envelope_radius1 = 0.0
self.envelope_radius2 = 0.0
self.spin1 = 0.0
self.spin2 = 0.0
self.epoch1 = 0.0
self.epoch2 = 0.0
self.t_ms1 = 0.0
self.t_ms2 = 0.0
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
alpha1 = 1.0
CElambda = 0.5
ceflag = 0
tflag = 1
ifflag = 0
wdflag = 1
bhflag = 0
nsflag = 1
mxns = 3.0
idum = 29769
pts1 = 0.05
pts2 = 0.01
pts3 = 0.02
sigma = 190.0
beta = 1.0/8.0
xi = 1.0
acc2 = 3.0/2.0
epsnov = 0.001
eddfac = 1.0
gamma = -1.0
status = instance.initialize(metallicity,
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)
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,
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
new_state.initial_mass1 = 3.0
new_state.initial_mass2 = 1.0
new_state.type1 = 1.0
new_state.type2 = 1.0
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.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.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_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
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',
}
for x in expected:
# 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,
updated_state.mass2, updated_state.t_ms1, updated_state.t_ms2,
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,
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]
init_mass1 = masses1
init_mass2 = masses2
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,
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,
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,
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)]
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,
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()
instance.initialize_code()
instance.parameters.metallicity = 0.001
instance.parameters.common_envelope_efficiency = 3.0
instance.parameters.Eddington_mass_transfer_limit_factor = 10.0
instance.commit_parameters()
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)
instance.particles.add_particles(stars)
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.
current_time = current_time + max(5.0*instance.binaries[0].time_step, 0.3 | 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_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",
"Core Helium Burning",
"First Asymptotic Giant Branch",
"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,
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,
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()
instance.parameters.metallicity = 0.001
instance.parameters.common_envelope_efficiency = 3.0
instance.parameters.Eddington_mass_transfer_limit_factor = 10.0
instance.commit_parameters()
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)
instance.particles.add_particles(stars)
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.
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_type:
results.append((binary.age, binary.child1.mass, binary.child1.stellar_type))
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,
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,
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",
"Core Helium Burning",
"First Asymptotic Giant Branch",
"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[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)
instance.particles.add_particles(stars)
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):
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,
43.8025 | units.Myr,
43.9923 | units.Myr,
44.0686 | units.Myr,
141.7077 | units.Myr,
142.3448 | units.Myr,
142.7827 | units.Myr,
166.1043 | units.Myr,
166.5795 | units.Myr,
166.9627 | units.Myr,
166.9863 | units.Myr
)
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",
"Core Helium Burning and Main Sequence star",
"First Asymptotic Giant Branch and Main Sequence star",
"Second Asymptotic Giant Branch and Main Sequence star",
"Oxygen/Neon White Dwarf and Main Sequence star",
"Oxygen/Neon White Dwarf and Hertzsprung Gap",
"Oxygen/Neon White Dwarf and First Giant Branch",
"Oxygen/Neon White Dwarf and Core Helium Burning",
"Oxygen/Neon White Dwarf and First Asymptotic Giant Branch",
"Oxygen/Neon White Dwarf and Hertzsprung Gap Naked Helium star",
"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[0].mass = 7.816 | units.MSun
stars[1].mass = 4.387 | units.MSun
instance.particles.add_particles(stars)
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)
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()
self.assertAlmostEqual(binary.child1.mass.value_in(units.MSun), 1.304, 3)
self.assertAlmostEqual(binary.child2.mass.value_in(units.MSun), 0.800, 3)
self.assertEqual(str(binary.child1.stellar_type), "Neutron Star")
self.assertEqual(str(binary.child2.stellar_type), "Carbon/Oxygen White Dwarf")
instance.stop()
def test5(self):
print("Testing stellar collision...")
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[0].mass = 3.0 | units.MSun
stars[1].mass = 0.3 | units.MSun
instance.particles.add_particles(stars)
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)
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)
self.assertAlmostEqual(binary.child1.mass.value_in(units.MSun), 3.300, 3)
self.assertAlmostEqual(binary.child2.mass.value_in(units.MSun), 0.000, 3)
self.assertEqual(str(binary.child1.stellar_type), "Main Sequence star")
self.assertEqual(str(binary.child2.stellar_type), "Massless Supernova")
instance.stop()
def test6(self):
print("Testing additional parameters for initialization...")
instance = BSE()
instance.initialize_code()
self.assertEqual(instance.parameters.reimers_mass_loss_coefficient, 0.5)
myvalue = 0.7
instance.parameters.reimers_mass_loss_coefficient = myvalue
self.assertEqual(instance.parameters.reimers_mass_loss_coefficient, myvalue)
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
instance.parameters.reimers_mass_loss_coefficient = myvalue
instance.parameters.set_defaults()
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)
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
semi_major_axis = instance.orbital_period_to_semi_major_axis(
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)
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!
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)
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
semi_major_axis = instance.orbital_period_to_semi_major_axis(
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
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.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.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.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)
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()
self.assertEqual(instance.get_name_of_current_state(), 'INITIALIZED')
instance.commit_parameters()
self.assertEqual(instance.get_name_of_current_state(), 'RUN')
instance.cleanup_code()
self.assertEqual(instance.get_name_of_current_state(), 'END')
instance.stop()
print("ok")
print("initialize_code(), commit_parameters(), "
"and cleanup_code() should be called automatically:", end=' ')
instance = BSE()
self.assertEqual(instance.get_name_of_current_state(), 'UNINITIALIZED')
instance.parameters.reimers_mass_loss_coefficient = 0.5
self.assertEqual(instance.get_name_of_current_state(), 'INITIALIZED')
instance.particles.add_particles(stars)
instance.binaries.add_particles(binaries)
self.assertEqual(instance.get_name_of_current_state(), 'RUN')
instance.stop()
self.assertEqual(instance.get_name_of_current_state(), 'STOPPED')
print("ok")
| 29,416
| 39.970752
| 120
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/codes_tests/test_twobody.py
|
import numpy
from amuse.community.twobody import interface
from amuse.test.amusetest import TestWithMPI
from amuse.units import units
from amuse.units import nbody_system
from amuse.units.quantities import zero
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)
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)
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.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)
instance.stop()
class TwoBodyTests(TestWithMPI):
def test1(self):
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)
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
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)
instance.stop()
def test3(self):
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
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)
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)
instance.stop()
def test4(self):
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
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
instance.evolve_model(4000.0 | units.s)
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
instance = interface.TwoBody()
p = datamodel.Particle()
p.mass = 1.0 | nbody_system.mass
p.radius = 0.001 | nbody_system.length
p.position = [1.0, 0.1, -0.1] | nbody_system.length
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.stop()
def test6(self):
# from: Fundamentals of Celestial Mechanics, J.M.A. Danby 2nd edition
instance = interface.TwoBody()
p = datamodel.Particles(2)
p.mass = [1, 0.0] | nbody_system.mass
p.radius = 0.001 | nbody_system.length
p.x = [1.0, 0.0] | nbody_system.length
p.y = [0.1, 0.0] | nbody_system.length
p.z = [-0.1, 0.0] | nbody_system.length
p.vx = [-0.1, 0.0] | nbody_system.speed
p.vy = [2.0, 0.0] | nbody_system.speed
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.stop()
def test7(self):
print("Test 7: get_gravity_at_point")
instance = interface.TwoBody()
p = datamodel.Particles(2)
p.mass = 0.5 | nbody_system.mass
p.radius = 0 | nbody_system.length
p.position = [[1.0, 0, 0], [-1.0, 0, 0]] | nbody_system.length
p.velocity = [[0]*3]*2 | nbody_system.speed
instance.particles.add_particles(p)
zero = [0.0] | nbody_system.length
ax, ay, az = instance.get_gravity_at_point(zero, 0.5 | nbody_system.length, zero, zero)
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)
self.assertAlmostEqual(ax, -0.12453271 | nbody_system.acceleration)
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()
p = datamodel.Particles(2)
p.mass = 0.5 | nbody_system.mass
p.radius = 0 | nbody_system.length
p.position = [[1.0, 0, 0], [-1.0, 0, 0]] | nbody_system.length
p.velocity = [[0]*3]*2 | nbody_system.speed
instance.particles.add_particles(p)
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, "
"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.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)
p.mass = [1, 0.0] | nbody_system.mass
p.radius = 0.001 | nbody_system.length
p.x = [1.0, 0.0] | nbody_system.length
p.y = [0.1, 0.0] | nbody_system.length
p.z = [-0.1, 0.0] | nbody_system.length
p.vx = [-0.1, 0.0] | nbody_system.speed
p.vy = [2.0, 0.0] | nbody_system.speed
p.vz = [-0.2, 0.0] | nbody_system.speed
instance.particles.add_particles(p)
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.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.stop()
| 12,116
| 40.639175
| 127
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/compile_tests/test_java_implementation.py
|
from amuse.support.interface import InCodeComponentImplementation
from amuse.test.amusetest import TestWithMPI
from amuse.test import compile_tools
from amuse.support import exceptions
import subprocess
import os
import time
import shutil
from amuse.units import nbody_system
from amuse.units import units
from amuse import datamodel
from amuse import config
from amuse.rfi.tools import create_java
from amuse.rfi import channel
from amuse.rfi.core import *
codestring = """
public class Code implements CodeInterface {
public Code(String codeDir, String amuseRootDir) {
}
public void end() {
//IGNORE
}
// parameter "int_in" is an input parameter
// parameter "int_out" is an output parameter
// parameter "len" is a length parameter
public int echo_array_with_result(int[] int_in, int[] int_out, int len) {
for(int i = 0; i < len; i++) {
int_out[i] = int_in[i];
}
return -1;
}
// parameter "string_in" is an input parameter
public int print_error_string(String[] string_in) {
for(int i = 0; i < string_in.length; i++) {
System.err.println(string_in[i]);
}
return 0;
}
// parameter "string_inout1" is an inout parameter
// parameter "string_inout2" is an inout parameter
public int echo_strings(String[] string_inout1, String[] string_inout2) {
for(int i = 0; i < string_inout1.length; i++) {
String tmp = string_inout1[i];
string_inout1[i] = string_inout2[i];
string_inout2[i] = tmp;
}
return 0;
}
// parameter "double_in" is an input parameter
// parameter "double_out" is an output parameter
public int echo_double(double[] double_in, double[] double_out) {
for(int i = 0; i < double_in.length; i++) {
double_out[i] = double_in[i];
}
return 0;
}
// parameter "float_in" is an input parameter
// parameter "float_out" is an output parameter
public int echo_float(float[] float_in, float[] float_out) {
for(int i = 0; i < float_in.length; i++) {
float_out[i] = float_in[i];
}
return 0;
}
// parameter "int_in" is an input parameter
// parameter "int_out" is an output parameter
public int echo_int(int int_in, int[] int_out) {
int_out[0] = int_in;
if (int_in < 0) {
return -1;
} else {
return 0;
}
}
// parameter "int_in" is an input parameter
// parameter "int_out" is an output parameter
public int echo_int_array(int[] int_in, int[] int_out) {
for(int i = 0; i < int_in.length; i++) {
int_out[i] = int_in[i];
}
return 0;
}
// parameter "in_out" is an inout parameter
// parameter "len" is a length parameter
public int echo_inout_array_with_result(int[] in_out, int len) {
for(int i = 0; i < len; i++) {
in_out[i] = in_out[i] + 10;
}
return 11;
}
// parameter "int_in" is an input parameter
// parameter "int_out" is an output parameter
// parameter "len" is a length parameter
public void echo_array(int[] int_in, int[] int_out, int len) {
for(int i = 0; i < len; i++) {
int_out[i] = int_in[i];
}
}
// parameter "in" is an input parameter
// parameter "out" is an output parameter
public int echo_long_long_int(long[] in, long[] out) {
for(int i = 0; i < in.length; i++) {
out[i] = in[i];
}
if (in[0] < 0) {
return -1;
} else {
return 0;
}
}
// parameter "string_in" is an input parameter
// parameter "string_out" is an output parameter
public int echo_string(String[] string_in, String[] string_out) {
for(int i = 0; i < string_in.length; i++) {
string_out[i] = string_in[i];
}
return 0;
}
// parameter "input" is an input parameter
// parameter "output" is an output parameter
public int echo_logical(boolean[] input, boolean[] output) {
for(int i = 0; i < input.length; i++) {
output[i] = input[i];
}
return 0;
}
// parameter "string_in" is an input parameter
public int print_string(String[] string_in) {
for(int i = 0; i < string_in.length; i++) {
System.out.println(string_in[i]);
}
return 0;
}
// parameter "int_in1" is an input parameter
// parameter "int_in2" is an input parameter
// parameter "int_out1" is an output parameter
// parameter "int_out2" is an output parameter
// parameter "len" is a length parameter
public int echo_2_int(int[] int_in1, int[] int_in2, int[] int_out1, int[] int_out2, int len) {
for(int i = 0; i < len; i++) {
int_out1[i] = int_in1[i];
int_out2[i] = int_in2[i];
}
return len;
}
}
"""
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",))
def channel_type(self):
return 'sockets'
@legacy_function
def echo_int():
function = LegacyFunctionSpecification()
function.addParameter('int_in', dtype='int32', direction=function.IN)
function.addParameter('int_out', dtype='int32', direction=function.OUT)
function.result_type = 'int32'
return function
@legacy_function
def echo_int_array():
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
@legacy_function
def echo_long_long_int():
function = LegacyFunctionSpecification()
function.addParameter('in', dtype='int64', direction=function.IN)
function.addParameter('out', dtype='int64', direction=function.OUT)
function.result_type = 'int32'
function.can_handle_array = True
return function
@legacy_function
def echo_double():
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
@legacy_function
def echo_float():
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
@legacy_function
def echo_string():
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
@legacy_function
def echo_strings():
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
@legacy_function
def echo_array():
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.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 return_string():
function = LegacyFunctionSpecification()
function.addParameter('string_in', dtype='string', direction=function.IN)
function.result_type = 'string'
function.can_handle_array = True
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_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
@legacy_function
def echo_inout_array_with_result():
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
@legacy_function
def echo_logical():
function = LegacyFunctionSpecification()
function.addParameter('input', dtype='bool', direction=function.IN)
function.addParameter('output', dtype='bool', direction=function.OUT)
function.result_type = 'int32'
function.can_handle_array = True
return function
@legacy_function
def print_string():
function = LegacyFunctionSpecification()
function.addParameter('string_in', dtype='string', direction=function.IN)
function.result_type = 'int32'
function.can_handle_array = True
return function
@legacy_function
def print_error_string():
function = LegacyFunctionSpecification()
function.addParameter('string_in', dtype='string', direction=function.IN)
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(
'echo_int',
(units.m,),
(
units.m,
object.ERROR_CODE,
)
)
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
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")
@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)
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]
output, errors = instance.echo_int_array(input)
instance.stop()
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]
output, errors = instance.echo_double(input)
instance.stop()
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()
self.assertEqual(error, 0)
self.assertEqual(out, "abc")
def test7(self):
instance = ForTestingInterface(self.exefile)
out, error = instance.echo_string(["abc", "def"])
instance.stop()
self.assertEqual(error[0], 0)
self.assertEqual(error[1], 0)
self.assertEqual(out[0], "abc")
self.assertEqual(out[1], "def")
def test8(self):
instance = ForTestingInterface(self.exefile)
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'.
Also note: to test this, you best set the ulimit
to a low number (but not too low), for example
ulimit -n 400
"""
for x in range(400):
instance = ForTestingInterface(self.exefile)
out, error = instance.echo_float(4.0)
instance.stop()
def test11(self):
instance = ForTestingInterface(self.exefile)
(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])
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")
instance.stop()
def test14(self):
instance = ForTesting(self.exefile)
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))
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_ints7, output_ints8 = instance.echo_2_int([5])
instance.stop()
self.assertEqual(output_ints1[1], 2)
self.assertEqual(output_ints2[0], 3)
self.assertEqual(output_ints2[1], 4)
for i in range(3):
self.assertEqual(output_ints3[i], i + 1)
self.assertEqual(output_ints4[i], 1)
self.assertEqual(output_ints5[0], 5)
self.assertEqual(output_ints6[0], 0)
self.assertEqual(output_ints7[0], 5)
self.assertEqual(output_ints8[0], 1)
def test16(self):
instance = ForTesting(self.exefile)
# 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])
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 test18(self):
instance = ForTestingInterface(self.exefile)
out, error = instance.echo_logical([True, False, True])
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")
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.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:
content = f.read()
self.assertTrue("test_string_123" in content.strip())
self.assertTrue(os.path.exists(error))
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")
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.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:
content = f.read()
# some times java generates "Picked up _JAVA_OPTIONS" message, so only test:
self.assertTrue("abcdef" in content)
self.assertTrue("&Hfecd" in content)
| 20,606
| 32.237097
| 121
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/compile_tests/test_python_implementation.py
|
from amuse.support.interface import InCodeComponentImplementation
from amuse.test.amusetest import TestWithMPI
from amuse.test.amusetest import TestCase
import numpy
import sys
import os
import time
import pickle
from amuse.units import nbody_system
from amuse.units import units
from amuse import datamodel
from amuse.rfi import python_code
from amuse.rfi.core import (
PythonCodeInterface,
LegacyFunctionSpecification,
legacy_function,
)
from amuse.rfi.async_request import AsyncRequestsPool
from amuse.rfi.async_request import ASyncRequestSequence
from amuse.rfi.tools.create_python_worker import CreateAPythonWorker
from amuse.support import exceptions
class ForTestingInterface(PythonCodeInterface):
def __init__(self, **options):
PythonCodeInterface.__init__(self, implementation_factory=ForTestingImplementation, **options)
@legacy_function
def get_mass():
function = LegacyFunctionSpecification()
function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN)
function.addParameter('mass', dtype='float64', direction=function.OUT)
function.result_type = 'int32'
function.can_handle_array = True
function.id = 10
return function
@legacy_function
def set_mass():
function = LegacyFunctionSpecification()
function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN)
function.addParameter('mass', dtype='float64', direction=function.IN, description="The new mass of the particle")
function.result_type = 'int32'
function.can_handle_array = True
function.id = 11
return function
@legacy_function
def new_particle():
function = LegacyFunctionSpecification()
function.addParameter('mass', dtype='float64', direction=function.IN, description="The new mass of the particle")
function.addParameter('other', dtype='int32', direction=function.IN)
function.addParameter('index_of_the_particle', dtype='int32', direction=function.OUT)
function.result_type = 'int32'
function.can_handle_array = True
return function
@legacy_function
def delete_particle():
function = LegacyFunctionSpecification()
function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN)
function.result_type = 'int32'
function.can_handle_array = True
return function
@legacy_function
def echo_int():
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
function.id = 12
return function
@legacy_function
def echo_double():
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
function.id = 13
return function
@legacy_function
def echo_string():
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
function.id = 14
return function
@legacy_function
def echo_strings():
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
function.id = 15
return function
@legacy_function
def echo_bool():
function = LegacyFunctionSpecification()
function.addParameter('string_in', dtype='bool', direction=function.IN)
function.addParameter('string_out', dtype='bool', direction=function.OUT)
function.result_type = 'int32'
function.can_handle_array = True
function.id = 16
return function
@legacy_function
def sleep():
function = LegacyFunctionSpecification()
function.addParameter('number_of_seconds', dtype='float64', direction=function.IN)
function.result_type = 'int32'
function.can_handle_array = False
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_out', dtype='float64', direction=function.OUT)
function.result_type = 'int32'
function.can_handle_array = True
return function
@legacy_function
def multiply_ints():
function = LegacyFunctionSpecification()
function.addParameter('int_in1', dtype='int32', direction=function.IN)
function.addParameter('int_in2', 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
@legacy_function
def print_string():
function = LegacyFunctionSpecification()
function.addParameter('string_in', dtype='string', direction=function.IN)
function.result_type = 'int32'
function.can_handle_array = True
return function
@legacy_function
def print_error_string():
function = LegacyFunctionSpecification()
function.addParameter('string_in', dtype='string', direction=function.IN)
function.result_type = 'int32'
function.can_handle_array = True
return function
@legacy_function
def get_position():
function = LegacyFunctionSpecification()
function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN)
function.addParameter('x', dtype='float64', direction=function.OUT)
function.addParameter('y', dtype='float64', direction=function.OUT)
function.addParameter('z', dtype='float64', direction=function.OUT)
function.addParameter('length', 'int32', function.LENGTH)
function.result_type = 'int32'
function.must_handle_array = True
return function
@legacy_function
def set_position():
function = LegacyFunctionSpecification()
function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN)
function.addParameter('x', dtype='float64', direction=function.IN)
function.addParameter('y', dtype='float64', direction=function.IN)
function.addParameter('z', dtype='float64', direction=function.IN)
function.addParameter('length', 'int32', function.LENGTH)
function.result_type = 'int32'
function.must_handle_array = True
return function
@legacy_function
def copy_over_interface():
function = LegacyFunctionSpecification()
function.addParameter('comm_identifier', dtype='int32', direction=function.IN)
function.addParameter('encoded_interface', dtype='string', direction=function.IN)
function.result_type = 'int32'
function.can_handle_array = False
return function
@legacy_function
def deep_echo_string():
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
@legacy_function
def return_control():
function = LegacyFunctionSpecification()
function.result_type = 'int32'
function.can_handle_array = False
return function
@legacy_function
def echo_quantity():
function = LegacyFunctionSpecification()
function.addParameter('quantity_in', dtype='float64', direction=function.IN)
function.addParameter('quantity_out', dtype='float64', direction=function.OUT)
function.result_type = 'int32'
function.can_handle_array = True
function.has_units = True
function.id = 23
return function
@legacy_function
def echo_quantities():
function = LegacyFunctionSpecification()
function.addParameter('quantity_in', dtype='float64', direction=function.IN)
function.addParameter('quantity_out', dtype='float64', direction=function.OUT)
function.result_type = 'int32'
function.must_handle_array = True
function.has_units = True
function.id = 23
return function
@legacy_function
def echo_quantities_error():
function = LegacyFunctionSpecification()
function.addParameter('quantity_in', dtype='float64', direction=function.IN)
function.addParameter('quantity_out', dtype='float64', direction=function.OUT)
function.result_type = 'int32'
function.must_handle_array = True
function.has_units = True
function.id = 25
return function
basic_python_exe = """#!{executable}
import sys
import os
from subprocess import call
if __name__ == '__main__':
command = sys.argv[1:]
dirname=os.path.dirname(__file__)
dirname=os.path.abspath(dirname)
logfile=os.path.join(dirname, 'pythonexe.log')
with open(logfile, 'a') as stream:
stream.write('start {{0}}\\n'.format(command[0]))
stream.flush()
command.insert(0, sys.executable)
returncode = call(command, close_fds=False)
with open(logfile, 'a') as stream:
stream.write('end {{0}} {{1}}\\n'.format(command[0], returncode))
stream.flush()
sys.exit(returncode)
"""
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
def new_particle(self, mass, other, index_of_the_particle):
try:
self.masses[self.maxindex] = mass
index_of_the_particle.value = self.maxindex
self.maxindex += 1
return 0
except:
return -1
def get_mass(self, index_of_the_particle, mass):
try:
mass.value = self.masses[index_of_the_particle]
return 0
except:
return -1
def set_mass(self, index_of_the_particle, mass):
try:
self.masses[index_of_the_particle] = mass
return 0
except:
return -1
def echo_int(self, int_in, int_out):
int_out.value = int_in
return 0
def echo_double(self, double_in, double_out):
double_out.value = double_in
return 0
def echo_string(self, string_in, string_out):
string_out.value = string_in
return 0
def echo_bool(self, in_, out_):
out_.value = in_
return 0
def print_string(self, string_in):
print(string_in)
return 0
def print_error_string(self, string_in):
print(string_in, file=sys.stderr)
return 0
def echo_strings(self, string_inout1, string_inout2):
string_inout1.value = string_inout1.value[::-1]
string_inout2.value = string_inout2.value[::-1]
return 0
def sleep(self, number_of_seconds):
import time
time.sleep(number_of_seconds)
return 0
def sum_doubles(self, double_in1, double_in2, double_out):
double_out.value = double_in1 + double_in2
return 0
def multiply_ints(self, int_in1, int_in2, int_out):
int_out.value = int_in1 * int_in2
return 0
def get_position(self, index_of_the_particle, x, y, z, length):
try:
x.value = self._particle_data[index_of_the_particle, 0]
y.value = self._particle_data[index_of_the_particle, 1]
z.value = self._particle_data[index_of_the_particle, 2]
return 0
except:
return -1
def set_position(self, index_of_the_particle, x, y, z, length):
try:
self._particle_data[index_of_the_particle, 0] = x
self._particle_data[index_of_the_particle, 1] = y
self._particle_data[index_of_the_particle, 2] = z
return 0
except:
return -1
def copy_over_interface(self, comm_identifier, encoded_interface):
self._other = pickle.loads(encoded_interface.encode("latin-1"))
self._other.channel.intercomm = self._interface.communicators[comm_identifier]
return 0
def deep_echo_string(self, string_in, string_out):
result, errorcode = self._other.echo_string(string_in)
string_out.value = result[::-1]
return errorcode
def return_control(self):
self._other.internal__activate_communicator(0)
return 0
def echo_quantity(self, quantity_in, quantity_out):
quantity_out.value = quantity_in * (10 | (1.0/units.s))
return 0
def echo_quantities(self, quantity_in, quantity_out):
quantity_out.value = quantity_in * (10 | (1.0/units.s))
return 0
def echo_quantities_error(self, quantity_in, quantity_out):
raise Exception("an unexpected event")
return 0
class ForTesting(InCodeComponentImplementation):
def __init__(self, **options):
InCodeComponentImplementation.__init__(self, ForTestingInterface(**options), **options)
def define_methods(self, object):
object.add_method("sleep", (units.s,), (object.ERROR_CODE,))
object.add_method("new_particle", (units.kg, object.LINK("particles")), (object.INDEX, object.ERROR_CODE,))
def define_particle_sets(self, object):
object.define_set('particles', 'index_of_the_particle')
object.set_new('particles', 'new_particle')
object.set_delete('particles', 'delete_particle')
object.add_setter('particles', 'set_mass')
object.add_getter('particles', 'get_mass')
class TestCreatePythonWorker(TestCase):
def test1(self):
x = CreateAPythonWorker()
x.implementation_factory = ForTestingImplementation
x.channel_type = 'mpi'
x.interface_class = ForTestingInterface
script_string = x.new_executable_script_string()
self.assertTrue(script_string.find('syspath = (') > 0)
self.assertTrue(script_string.find('ForTestingInterface') > 0)
self.assertTrue(script_string.find('ForTestingImplementation') > 0)
self.assertTrue(script_string.find('test_python_implementation') > 0)
self.assertTrue(script_string.find('PythonImplementation(instance, ForTestingInterface)') > 0)
try:
st = compile(script_string, 'test.py', 'exec')
except SyntaxError as ex:
self.fail("Compilation error {0}".format(ex))
def test2(self):
x = CreateAPythonWorker()
x.implementation_factory = ForTestingImplementation
x.channel_type = 'sockets'
x.interface_class = ForTestingInterface
script_string = x.new_executable_script_string()
self.assertTrue(script_string.find('syspath = (') > 0)
self.assertTrue(script_string.find('ForTestingInterface') > 0)
self.assertTrue(script_string.find('ForTestingImplementation') > 0)
self.assertTrue(script_string.find('test_python_implementation') > 0)
self.assertTrue(script_string.find('PythonImplementation(instance, ForTestingInterface)') > 0)
self.assertTrue(script_string.find('start_socket') > 0)
try:
st = compile(script_string, 'test.py', 'exec')
except SyntaxError as ex:
self.fail("Compilation error {0}".format(ex))
class TestInterface(TestWithMPI):
def ForTesting(self, **options):
options["worker_dir"] = self.get_path_to_results()
return ForTesting(**options)
def ForTestingInterface(self, **options):
options["worker_dir"] = self.get_path_to_results()
return ForTestingInterface(**options)
def test02(self):
implementation = ForTestingImplementation()
x = python_code.PythonImplementation(implementation, ForTestingInterface)
input_message = python_code.ClientSideMPIMessage(0, 10, 1)
input_message.ints = [1]
output_message = python_code.ClientSideMPIMessage(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 test03(self):
implementation = ForTestingImplementation()
x = python_code.PythonImplementation(implementation, ForTestingInterface)
input_message = python_code.ClientSideMPIMessage(0, 11, 1)
input_message.ints = [1]
input_message.doubles = [12.0]
output_message = python_code.ClientSideMPIMessage(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 test04(self):
implementation = ForTestingImplementation()
x = python_code.PythonImplementation(implementation, ForTestingInterface)
input_message = python_code.ClientSideMPIMessage(0, 11, 4)
input_message.ints = [1, 2, 3, 4]
input_message.doubles = [12.0, 13.0, 14.0, 15.0]
output_message = python_code.ClientSideMPIMessage(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)
self.assertEqual(output_message.ints[3], 0)
self.assertEqual(implementation.masses[1], 12.0)
self.assertEqual(implementation.masses[2], 13.0)
self.assertEqual(implementation.masses[3], 14.0)
self.assertEqual(implementation.masses[4], 15.0)
def test05(self):
x = self.ForTestingInterface()
error = x.set_mass(1, 10.0)
self.assertEqual(error, 0)
answer, error = x.get_mass(1)
self.assertEqual(error, 0)
self.assertEqual(answer, 10.0)
x.stop()
def test06(self):
x = self.ForTestingInterface()
errors = x.set_mass([1, 2], [10.0, 11.0])
self.assertEqual(errors[0], 0)
self.assertEqual(errors[1], 0)
answer, errors = x.get_mass([1, 2])
self.assertEqual(errors[0], 0)
self.assertEqual(answer[0], 10.0)
self.assertEqual(answer[1], 11.0)
x.stop()
x.stop()
def test07(self):
x = self.ForTestingInterface()
int_out, error = x.echo_int(20)
self.assertEqual(error, 0)
self.assertEqual(int_out, 20)
x.stop()
x.stop()
def test08(self):
implementation = ForTestingImplementation()
x = python_code.PythonImplementation(implementation, ForTestingInterface)
input_message = python_code.ClientSideMPIMessage(0, 12, 1)
input_message.ints = [20]
output_message = python_code.ClientSideMPIMessage(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 test09(self):
x = self.ForTestingInterface()
string_out, error = x.echo_string("1234567")
self.assertEqual(error, 0)
self.assertEqual(string_out, "1234567")
x.stop()
def test10(self):
x = self.ForTestingInterface()
string_out, error = x.echo_string(["aaaaa", "bbbb"])
self.assertEqual(error[0], 0)
self.assertEqual(len(string_out), 2)
self.assertEqual(string_out[0], "aaaaa")
self.assertEqual(string_out[1], "bbbb")
x.stop()
def test11(self):
x = self.ForTestingInterface()
string_out, error = x.echo_string(["", "bbbb"])
self.assertEqual(error[0], 0)
self.assertEqual(len(string_out), 2)
self.assertEqual(string_out[0], "")
self.assertEqual(string_out[1], "bbbb")
x.stop()
def test12(self):
x = self.ForTestingInterface()
str1_out, str2_out, error = x.echo_strings("abc", "def")
self.assertEqual(error, 0)
self.assertEqual(str1_out, "cba")
self.assertEqual(str2_out, "fed")
x.stop()
def test13(self):
x = self.ForTestingInterface()
str1_out, str2_out, error = x.echo_strings(["abc", "def"], ["ghi", "jkl"])
self.assertEqual(error[0], 0)
self.assertEqual(error[1], 0)
self.assertEqual(str1_out[0], "cba")
self.assertEqual(str1_out[1], "fed")
self.assertEqual(str2_out[0], "ihg")
self.assertEqual(str2_out[1], "lkj")
x.stop()
def test14(self):
x = self.ForTestingInterface()
result = x.sleep(2)
self.assertEqual(result, 0)
request = x.sleep.asynchronous(0.01)
request.wait()
result = request.result()
self.assertEqual(result, 0)
x.stop()
def test15(self):
x = self.ForTestingInterface()
y = self.ForTestingInterface()
request1 = x.sleep.asynchronous(0.5)
self.assertFalse(request1.is_result_available())
request2 = y.sleep.asynchronous(1.5)
self.assertFalse(request2.is_result_available())
request2.wait()
self.assertTrue(request1.is_result_available())
self.assertTrue(request2.is_result_available())
self.assertEqual(request1.result(), 0)
self.assertEqual(request2.result(), 0)
y.stop()
x.stop()
def test16(self):
x = self.ForTestingInterface()
request1 = x.sleep.asynchronous(0.4)
x.sleep(0.01)
self.assertTrue(request1.is_result_available(), True)
request1.wait()
self.assertTrue(request1.is_result_available())
x.sleep(0.01)
self.assertTrue(request1.is_result_available())
x.stop()
def test17(self):
x = self.ForTesting()
self.assertTrue(x.sleep.is_async_supported)
request = x.sleep.asynchronous(0.2 | units.s)
request.wait()
result = request.result()
self.assertEqual(result, [])
x.stop()
def test18(self):
print("Testing the splitting of very long MPI messages into blocks")
x = self.ForTesting(max_message_length=10)
N = 100
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([1.0*i for i in range(N)], [1.0*i for i in range(N)])
self.assertTrue(list(sums) == [2.0*i for i in range(N)])
products = x.multiply_ints(range(N), range(N))
self.assertTrue(list(products) == [i*i for i in range(N)])
N = 101
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([1.0*i for i in range(N)], [1.0*i for i in range(N)])
self.assertTrue(list(sums) == [2.0*i for i in range(N)])
products = x.multiply_ints(range(N), range(N))
self.assertTrue(list(products) == [i*i for i in range(N)])
x.stop()
def test19(self):
print("Testing the splitting of very long MPI messages into blocks II: strings")
x = self.ForTesting(max_message_length=10)
N = 100
strings1, strings2 = x.echo_strings(['REDRUM' for i in range(N)], ['stressed' for i in range(N)])
self.assertTrue(list(strings1) == ['MURDER' for i in range(N)])
self.assertTrue(list(strings2) == ['desserts' for i in range(N)])
N = 101
strings1, strings2 = x.echo_strings(['REDRUM' for i in range(N)], ['stressed' for i in range(N)])
self.assertTrue(list(strings1) == ['MURDER' for i in range(N)])
self.assertTrue(list(strings2) == ['desserts' for i in range(N)])
x.stop()
def xtest20(self):
#
# TURNED OFF support for redirection,
# by default output is redirected to /dev/null
# if you need file, use the support from your mpi implementation
#
if os.path.exists("pout.000"):
os.remove("pout.000")
if os.path.exists("perr.000"):
os.remove("perr.000")
x = self.ForTesting(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:
content = f.read()
self.assertEqual(content.strip(), "abc")
self.assertTrue(os.path.exists("perr.000"))
with open("perr.000", "r") as f:
content = f.read()
self.assertEqual(content.strip(), "exex")
x = self.ForTesting(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:
content = f.read()
self.assertEqual(content.strip(), "abc\ndef\nexex")
def test21(self):
print("Testing must_handle_array for Python codes")
instance = self.ForTestingInterface()
x, y, z, err = instance.get_position(range(100))
self.assertEqual(err, 0)
self.assertEqual(x, numpy.arange(0.0, 300.0, 3.0))
self.assertEqual(y, numpy.arange(1.0, 300.0, 3.0))
self.assertEqual(z, numpy.arange(2.0, 300.0, 3.0))
x, y, z, err = instance.get_position(range(101))
self.assertEqual(err, -1)
self.assertEqual(list(instance.get_position(1).values()), [3.0, 4.0, 5.0, 0])
err = instance.set_position(range(100), numpy.arange(100.0), numpy.arange(100.0, 200.0), numpy.arange(200.0, 300.0))
self.assertEqual(err, 0)
err = instance.set_position(range(101), numpy.arange(101.0), numpy.arange(101.0, 202.0), numpy.arange(202.0, 303.0))
self.assertEqual(err, -1)
err = instance.set_position(0, -1.0, -2.0, -3.0)
x, y, z, err = instance.get_position(range(100))
self.assertEqual(err, 0)
self.assertEqual(x, numpy.concatenate(([-1.0], numpy.arange(1.0, 100.0))))
self.assertEqual(y, numpy.concatenate(([-2.0], numpy.arange(101.0, 200.0))))
self.assertEqual(z, numpy.concatenate(([-3.0], numpy.arange(201.0, 300.0))))
instance.stop()
def test22(self):
pool = AsyncRequestsPool()
x = self.ForTestingInterface()
y = self.ForTestingInterface()
request1 = x.sleep.asynchronous(0.5)
request2 = y.sleep.asynchronous(1.5)
finished_requests = []
def handle_result(request, index):
self.assertTrue(request.is_result_available())
finished_requests.append(index)
pool.add_request(request1, handle_result, [1])
pool.add_request(request2, handle_result, [2])
pool.wait()
self.assertEqual(len(finished_requests), 1)
self.assertEqual(len(pool), 1)
pool.wait()
self.assertEqual(len(finished_requests), 2)
self.assertEqual(len(pool), 0)
self.assertTrue(request1.is_result_available())
self.assertTrue(request2.is_result_available())
self.assertEqual(request1.result(), 0)
self.assertEqual(request2.result(), 0)
y.stop()
x.stop()
def test22b(self):
pool = AsyncRequestsPool()
x = self.ForTestingInterface()
y = self.ForTestingInterface()
request1 = x.sleep.asynchronous(0.2)
request2 = y.sleep.asynchronous(0.2)
finished_requests = []
def handle_result(request, index):
self.assertTrue(request.is_result_available())
finished_requests.append(index)
pool.add_request(request1, handle_result, [1])
pool.add_request(request2, handle_result, [2])
time.sleep(1.0)
pool.wait()
pool.wait()
self.assertEqual(len(finished_requests), 2)
self.assertEqual(len(pool), 0)
self.assertTrue(request1.is_result_available())
self.assertTrue(request2.is_result_available())
self.assertEqual(request1.result(), 0)
self.assertEqual(request2.result(), 0)
pool.wait()
self.assertEqual(len(pool), 0)
y.stop()
x.stop()
def test23(self):
path = self.get_path_to_results()
exe = os.path.join(path, "pythonexe")
log = os.path.join(path, "pythonexe.log")
if os.path.exists(exe):
os.remove(exe)
if os.path.exists(log):
os.remove(log)
string = basic_python_exe.format(executable=sys.executable)
with open(exe, 'w') as f:
f.write(string)
os.chmod(exe, 0o777)
instance = self.ForTestingInterface(
use_python_interpreter=True,
python_interpreter=exe
)
x, y, z, err = instance.get_position(range(100))
self.assertEqual(err, 0)
self.assertEqual(x, numpy.arange(0.0, 300.0, 3.0))
self.assertEqual(y, numpy.arange(1.0, 300.0, 3.0))
self.assertEqual(z, numpy.arange(2.0, 300.0, 3.0))
instance.stop()
# this is quite long, but apparently necessary
time.sleep(2.)
self.assertTrue(os.path.exists(log))
with open(log, 'r') as f:
loglines = f.read().splitlines()
print(loglines)
self.assertEqual(len(loglines), 2)
self.assertTrue(loglines[0].startswith('start '))
self.assertTrue(loglines[1].startswith('end '))
def test24(self):
# same as test23 but now with redirection is none
path = self.get_path_to_results()
exe = os.path.join(path, "pythonexe")
log = os.path.join(path, "pythonexe.log")
if os.path.exists(exe):
os.remove(exe)
if os.path.exists(log):
os.remove(log)
string = basic_python_exe.format(executable=sys.executable)
with open(exe, 'w') as f:
f.write(string)
os.chmod(exe, 0o777)
instance = self.ForTestingInterface(
use_python_interpreter=True,
python_interpreter=exe,
redirection="none"
)
x, y, z, err = instance.get_position(range(100))
self.assertEqual(err, 0)
self.assertEqual(x, numpy.arange(0.0, 300.0, 3.0))
self.assertEqual(y, numpy.arange(1.0, 300.0, 3.0))
self.assertEqual(z, numpy.arange(2.0, 300.0, 3.0))
instance.stop()
time.sleep(2.)
self.assertTrue(os.path.exists(log))
with open(log, 'r') as f:
loglines = f.read().splitlines()
self.assertEqual(len(loglines), 2)
self.assertTrue(loglines[0].startswith('start '))
self.assertTrue(loglines[1].startswith('end '))
def test25(self):
self.check_for_mpi()
instance = self.ForTestingInterface(polling_interval_in_milliseconds=100)
(output1, error1) = instance.internal__get_message_polling_interval()
instance.stop()
self.assertEqual(error1, 0)
self.assertEqual(output1, 100000)
def test25(self):
instance = self.ForTestingInterface(polling_interval_in_milliseconds=100)
if instance.channel.is_polling_supported():
(output1, error1) = instance.internal__get_message_polling_interval()
self.assertEqual(error1, 0)
self.assertEqual(output1, 100000)
instance.stop()
# these test might need special configuration, e.g. for openmpi:
# run "ompi-server --no-daemonize -r -"
# and set OMPI_MCA_pmix_server_uri="<uri>" with <uri> the reported uri
def test26(self):
self.check_for_mpi()
instance1 = self.ForTestingInterface()
instance2 = self.ForTestingInterface()
portname, error = instance1.internal__open_port()
self.assertTrue(len(portname) > 0)
self.assertEqual(error, 0)
request1 = instance1.internal__accept_on_port.asynchronous(portname)
request2 = instance2.internal__connect_to_port.asynchronous(portname)
request1.wait()
request2.wait()
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)
# this test requires that instance1 and instance2 use MPIchannel
# note shutdown of remote process triggers (ignored) invalid communicator error
def test27(self):
self.check_for_mpi()
instance1 = self.ForTestingInterface(redirection="none")
instance2 = self.ForTestingInterface(redirection="none")
encoded_interface = pickle.dumps(instance1, 0)
decoded_interface = pickle.loads(encoded_interface)
# 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)
request1.wait()
request2.wait()
port_id1, error1 = request1.result()
port_id2, error2 = request2.result()
instance2.copy_over_interface(port_id2, pickle.dumps(instance1, 0).decode('latin-1'))
instance1.internal__activate_communicator(port_id1)
result, errorcode = instance2.deep_echo_string("hello")
self.assertEqual(errorcode, 0)
self.assertEqual(result, "olleh")
result, errorcode = instance2.deep_echo_string("world")
self.assertEqual(errorcode, 0)
self.assertEqual(result, "dlrow")
instance2.return_control()
result, errorcode = instance1.echo_string("world")
self.assertEqual(errorcode, 0)
self.assertEqual(result, "world")
instance1.stop()
instance2.stop()
def test28(self):
x = self.ForTestingInterface()
def next_request(index):
if index < 3:
return x.sleep.asynchronous(0.1)
else:
return None
sequence = ASyncRequestSequence(next_request)
self.assertFalse(sequence.is_finished)
sequence.wait()
self.assertTrue(sequence.is_finished)
result = sequence.result()
self.assertEqual(len(result), 3)
x.stop()
def test29(self):
pool = AsyncRequestsPool()
x = self.ForTestingInterface()
y = self.ForTestingInterface()
sequenced_requests_indices = []
def next_request(index):
if index < 4:
sequenced_requests_indices.append(index)
return x.sleep.asynchronous(0.5)
else:
return None
request1 = ASyncRequestSequence(next_request)
request2 = y.sleep.asynchronous(1.0)
finished_requests = []
def handle_result(request, index):
self.assertTrue(request.is_result_available())
self.assertTrue(request.is_finished)
finished_requests.append(index)
pool.add_request(request1, handle_result, [1])
pool.add_request(request2, handle_result, [2])
pool.wait()
self.assertEqual(len(finished_requests), 1)
self.assertEqual(len(pool), 1)
self.assertEqual(finished_requests, [2])
self.assertTrue(len(sequenced_requests_indices) > 0)
pool.wait()
self.assertEqual(len(finished_requests), 2)
self.assertEqual(len(pool), 0)
x.sleep(0.1)
self.assertEqual(sequenced_requests_indices, [0, 1, 2, 3])
self.assertTrue(request1.is_result_available())
self.assertTrue(request2.is_result_available())
self.assertEqual(request1.result(), [0, 0, 0, 0])
self.assertEqual(request2.result(), 0)
y.stop()
x.stop()
def test30(self):
instance = self.ForTesting()
input = [1.0, 2.0, 3.0]
output = instance.sum_doubles(input, 5)
self.assertAlmostRelativeEquals(output, [6.0, 7.0, 8.0])
output = instance.sum_doubles(5, input)
self.assertAlmostRelativeEquals(output, [6.0, 7.0, 8.0])
def test31(self):
x = self.ForTesting()
p = datamodel.Particles(5)
p.mass = [1, 2, 3, 4, 5] | units.kg
p.other = None
for pi in p:
x.particles.add_particle(pi)
self.assertAlmostRelativeEquals(x.particles.mass, [1, 2, 3, 4, 5])
x.stop()
def test32(self):
x = self.ForTestingInterface()
quantity_out, error = x.echo_quantity(20.0 | units.m)
self.assertEqual(error, 0)
self.assertEqual(quantity_out, 200 | (units.m/units.s))
quantity_out, error = x.echo_quantity(30)
self.assertEqual(error, 0)
self.assertEqual(quantity_out, 300 | (1.0/units.s))
x.stop()
def test33(self):
x = self.ForTestingInterface()
quantity_out, error = x.echo_quantity([20, 30, 40] | units.m)
self.assertEqual(error, 0)
self.assertEqual(quantity_out, [200, 300, 400] | (units.m/units.s))
x.stop()
def test34(self):
x = self.ForTestingInterface()
# 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))
x.stop()
def test35(self):
x = self.ForTesting(max_message_length=10)
N = 10
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)])
N = 11
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)])
x.stop()
def test36(self):
x = self.ForTestingInterface()
self.assertRaises(exceptions.CodeException, x.echo_quantities_error, ([20, 30, 40] | units.m), expected_message="Exception when calling function 'echo_quantities_error', of code 'ForTestingInterface', exception was 'Error in code: an unexpected event'")
x.stop()
def test37(self):
x = self.ForTestingInterface()
request = x.echo_quantity.asynchronous([20, 30, 40] | units.m)
quantity_out, error = request.result()
self.assertEqual(error, 0)
self.assertEqual(quantity_out, [200, 300, 400] | (units.m/units.s))
x.stop()
def test40(self):
x = self.ForTesting()
out = x.echo_bool([True, False, True])
self.assertEqual(out, [True, False, True])
x.stop()
| 40,169
| 34.738434
| 261
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/compile_tests/test_async.py
|
from amuse.support.interface import InCodeComponentImplementation
from amuse.test.amusetest import TestWithMPI
from amuse.support import exceptions
from amuse.support import options
import os
import time
from amuse.units import nbody_system
from amuse.units import units
from amuse import datamodel
from amuse.rfi.tools import create_c
from amuse.rfi import async_request
from amuse.rfi.core import *
from . import test_c_implementation
from amuse.test import compile_tools
from amuse.community.distributed.interface import DistributedAmuse, Pilot
codestring = test_c_implementation.codestring+"""
#include <unistd.h>
float _x[10] = { 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.};
int do_sleep(int in) {
sleep(in);
return 0;
}
int return_error(int * out) {
*out=123;
return -1;
}
int get_x(int in, float *x){
*x=_x[in];
return 0;
}
int set_x(int in, float x){
_x[in]=x;
return 0;
}
int dummy(){
return 0;
}
"""
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
@legacy_function
def return_error():
function = LegacyFunctionSpecification()
function.addParameter('out', dtype='int32', direction=function.OUT)
function.result_type = 'int32'
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_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)
function.result_type = 'int32'
function.must_handle_array = True
return function
@legacy_function
def get_x():
function = LegacyFunctionSpecification()
function.addParameter('index', dtype='int32', direction=function.IN)
function.addParameter('x', dtype='float32', direction=function.OUT, unit=units.m)
function.result_type = 'int32'
function.can_handle_array = True
return function
@legacy_function
def set_x():
function = LegacyFunctionSpecification()
function.addParameter('index', dtype='int32', direction=function.IN)
function.addParameter('x', dtype='float32', direction=function.IN, unit=units.m)
function.result_type = 'int32'
function.can_handle_array = True
return function
@legacy_function
def dummy():
function = LegacyFunctionSpecification()
function.result_type = 'int32'
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)
def define_grids(self, handler):
handler.define_grid('grid')
handler.set_grid_range('grid', 'get_grid_range')
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")
handler.add_transition("1", "2", "dummy")
handler.add_method("2", "get_x")
handler.add_method("2", "set_x")
class TestASync(TestWithMPI):
@classmethod
def setup_class(cls):
print("building...")
cls.check_can_compile_modules()
try:
cls.exefile = compile_tools.build_worker(codestring, cls.get_path_to_results(), ForTestingInterface)
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)
request = instance.echo_int.asynchronous(10)
self.assertEqual(request, instance.async_request)
request.wait()
int_out, error = request.result()
self.assertEqual(int_out, 10)
self.assertEqual(error, 0)
instance.stop()
def test3(self):
instance = ForTestingInterface(self.exefile)
request1 = instance.do_sleep.asynchronous(1)
request2 = instance.echo_int.asynchronous(10)
self.assertEqual(request2, instance.async_request)
request2.wait()
int_out, error = request2.result()
self.assertEqual(int_out, 10)
self.assertEqual(error, 0)
instance.stop()
def test4(self):
instance = ForTesting(self.exefile)
request1 = instance.do_sleep(1, return_request=True)
request2 = instance.echo_int(10, return_request=True)
self.assertEqual(request2, instance.async_request)
instance.async_request.wait()
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 = []
for x in range(10):
requests.append(instance.echo_int(x, return_request=True))
instance.async_request.wait()
for i, x in enumerate(requests):
self.assertEqual(x.result(), i)
instance.stop()
def test6(self):
instance = ForTesting(self.exefile)
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):
self.assertEqual(x.result(), i)
instance.stop()
def test7(self):
instance1 = ForTesting(self.exefile)
instance2 = ForTesting(self.exefile)
t1 = time.time()
requests = []
for x in range(10):
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])
instance1.do_sleep(1, return_request=True)
instance2.do_sleep(1, return_request=True)
pool = instance1.async_request.join(instance2.async_request)
pool.waitall()
t2 = time.time()
for x in requests:
self.assertEqual(x[0].result(), x[1])
instance1.stop()
instance2.stop()
self.assertTrue(t2-t1 < 2.)
def test8(self):
from threading import Thread
instance1 = ForTesting(self.exefile)
instance2 = ForTesting(self.exefile)
t1 = time.time()
requests = []
for x in range(10):
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])
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)
thread.start()
time.sleep(1)
thread.join()
self.assertTrue(pool)
t2 = time.time()
for x in requests:
self.assertEqual(x[0].result(), x[1])
instance1.stop()
instance2.stop()
self.assertTrue(t2-t1 < 2.)
def test9(self):
instance = ForTesting(self.exefile)
for x in range(10):
instance.echo_int(x, return_request=True)
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)
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())
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)
def fac():
return instance2.echo_int(20, return_request=True)
# ~ request2=instance2.echo_int(20, async_dependency=request1)
request2 = async_request.DependentASyncRequest(request1, fac)
request2.wait()
self.assertEqual(request2.result(), 20)
instance1.stop()
instance2.stop()
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)
request2.wait()
self.assertTrue(request1.is_result_available())
self.assertEqual(request2.result(), 20)
instance1.stop()
instance2.stop()
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()
def safe_result(arg, index):
result = arg()
results[index] = result
return result
request1.add_result_handler(safe_result, (1,))
def fac():
return instance2.echo_int(results[1], return_request=True)
# ~ request2=instance2.echo_int(??, async_factory=fac)
request2 = async_request.DependentASyncRequest(request1, fac)
request2.wait()
self.assertEqual(request2.result(), 10)
instance1.stop()
instance2.stop()
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)
request2 = instance2.echo_int(request1, return_request=True)
request2.wait()
self.assertEqual(request2.result(), 10)
instance1.stop()
instance2.stop()
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)
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)
instance1.stop()
instance2.stop()
def test12c(self):
""" cross dependency with input-output dependency """
instance1 = ForTesting(self.exefile)
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)
instance4.do_sleep(1, return_request=True)
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)
instance1.stop()
instance2.stop()
instance3.stop()
instance4.stop()
def test13(self):
instance = ForTesting(self.exefile)
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)
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.assertFalse(r.is_result_available())
self.assertTrue(r.is_finished)
instance.stop()
def test14(self):
instance = ForTesting(self.exefile, channel_type="sockets")
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)
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.assertFalse(r.is_result_available())
self.assertTrue(r.is_finished)
instance.stop()
def test15(self):
instance = ForTesting(self.exefile)
instance.do_sleep(1, 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)
instance.stop()
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)
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])
r1 = request["int_out1"]
r2 = request["int_out2"]
self.assertEqual(r1.result(), [11, 12, 13])
self.assertEqual(r2.result(), [3, 2, 1])
instance.stop()
def test18(self):
""" test pool as depedency 1 """
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)
request3.wait()
self.assertTrue(request1.is_result_available())
self.assertTrue(request2.is_result_available())
self.assertEqual(request3.result(), 11)
instance1.stop()
instance2.stop()
instance3.stop()
def test18b(self):
""" test pool as depedency 2 """
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)
request3.wait()
self.assertTrue(request1.is_result_available())
self.assertTrue(request2.is_result_available())
self.assertEqual(request3.result(), 11)
instance1.stop()
instance2.stop()
instance3.stop()
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)
instance1.stop()
instance2.stop()
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)
instance1.stop()
instance2.stop()
def test20(self):
""" some more tests of request expressions """
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)
request3a.wait()
request3b.wait()
self.assertEqual(request3a.result(), 0)
self.assertEqual(request3b.result(), 0)
instance1.stop()
instance2.stop()
instance3.stop()
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)
instance1.stop()
instance2.stop()
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
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)))
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)))
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())
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)
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()
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.wait()
r2.wait()
p1.add_request(r1)
p1.add_request(r2)
# ~ p1=r1.join(r2)
p1.waitall()
self.assertEqual(r2.result(), 2)
instance1.stop()
def test26(self):
""" test a lot of calls"""
instances = []
for i in range(20):
instances.append(ForTesting(self.exefile, channel_type="sockets"))
import time
print("ready")
time.sleep(1)
print("start")
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(t2-t1)
for i in instances:
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)
instance1.do_sleep(1, return_request=True)
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.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)
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()
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.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)
t1 = time.time()
instance1.do_sleep(1, return_request=True)
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()
self.assertGreater(t2-t1, 1.)
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)
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()
self.assertLess(t2-t1, 0.5)
instance1.async_request.wait()
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)
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)
def test35(self):
""" test a grid attribute request setter with state"""
instance1 = ForTestingWithState(self.exefile, redirection="none")
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
self.assertEqual(instance1.get_name_of_current_state(), '2')
t2 = time.time()
self.assertGreater(t2-t1, 1.) # first time, state calls dummy (blocking) -> wait
t1 = time.time()
instance1.do_sleep(1, return_request=True)
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()
self.assertGreater(t2-t1, 1.)
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):
""" more state tests"""
instance1 = ForTestingWithState(self.exefile, redirection="none")
self.assertEqual(instance1.get_name_of_current_state(), '1')
# this documents current behaviour:
instance1.dummy(return_request=True)
self.assertEqual(instance1.get_name_of_current_state(), '1')
instance1.async_request.wait()
self.assertEqual(instance1.get_name_of_current_state(), '2')
# ie state changes upon completion of call at wait. This is
# sort of ok, alternatively state could be changed immediately...
class TestASyncDistributed(TestASync):
@classmethod
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.parameters.debug = False
# ~ 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'
cls.distinstance.pilots.add_pilot(pilot)
# ~ print "Pilots:"
# ~ print cls.distinstance.pilots
# ~ print "Waiting for pilots"
cls.distinstance.wait_for_pilots()
cls.distinstance.use_for_all_workers()
@classmethod
def tearDown(cls):
# ~ print "Stopping distributed code"
cls.distinstance.stop()
@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
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__":
TestASync.setup_class()
t = TestASync()
t.test26()
| 29,773
| 32.082222
| 135
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/compile_tests/test_fortran_implementation.py
|
import unittest
from amuse.support.interface import InCodeComponentImplementation
from amuse.test.amusetest import TestWithMPI
from amuse.test import compile_tools
import os
import time
import shlex
from amuse.units import nbody_system
from amuse.units import units
from amuse import datamodel
from amuse.rfi import channel
from amuse.rfi.core import *
codestring = """
function echo_int(int_in, int_out)
implicit none
integer :: int_in, int_out
integer :: echo_int
int_out = int_in
echo_int = 0
end function
function echo_double(double_in, double_out)
implicit none
DOUBLE PRECISION :: double_in, double_out
integer :: echo_double
double_out = double_in
echo_double = 0
end function
function echo_float(float_in, float_out)
implicit none
REAL(kind=4) :: float_in, float_out
integer :: echo_float
float_out = float_in
echo_float = 0
end function
function echo_string(string_in, string_out)
implicit none
character(len=*) :: string_in, string_out
integer :: echo_string
string_out = string_in
echo_string = 0
end function
function echo_strings(string_inout1, string_inout2)
implicit none
character(len=*) :: string_inout1, string_inout2
integer :: echo_strings
string_inout1(1:1) = 'A'
string_inout2(1:1) = 'B'
echo_strings = 0
end function
function return_string(string_in)
implicit none
character(len=*) :: string_in, return_string
return_string = string_in
end function
function hello_string(string_out)
implicit none
character(len=*) :: string_out
integer :: hello_string
string_out = 'hello'
hello_string = 0
end function
function print_string(string_in)
implicit none
character(len=*) :: string_in
integer :: print_string
write (*,*) string_in
print_string = 0
end function
function print_error_string(string_in)
implicit none
character(len=*) :: string_in
integer :: print_error_string
write (0,*) string_in
print_error_string = 0
end function
function echo_string_fixed_len(string_in, string_out)
implicit none
character(len=30) :: string_in, string_out
integer :: echo_string_fixed_len
string_out = string_in
echo_string_fixed_len = 0
end function
function echo_array_with_result(int_in, int_out, N)
implicit none
integer, intent(in) :: N
integer :: int_in(N), int_out(N)
integer :: echo_array_with_result, i
do i = 1, N
int_out(i) = int_in(i)
end do
echo_array_with_result = -1
end function
function echo_inout_array_with_result(inout, N)
implicit none
integer, intent(in) :: N
integer :: inout(N)
integer :: echo_inout_array_with_result, i
do i = 1, N
inout(i) = inout(i) + 10
end do
echo_inout_array_with_result = 11;
end function
function echo_logical(input, output)
implicit none
logical :: input, output
integer :: echo_logical
output = input
print *, "INPUT=", input
echo_logical = 0
end function
function echo_logical2(input, output, n)
implicit none
logical :: input(n), output(n)
integer :: echo_logical2, n,i
output(1:n)=.FALSE.
do i=1,n
if(input(i)) then
output(i) = .TRUE.
endif
enddo
echo_logical2 = 0
end function
function get_element_status(ind,x) result(ret)
integer :: ind,ret
character(len=*) :: x
x="dry"
ret=0
end function
"""
class ForTestingInterface(CodeInterface):
def __init__(self, exefile, **options):
CodeInterface.__init__(self, exefile, **options)
# use_modules=['code']
@legacy_function
def echo_int():
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
@legacy_function
def echo_double():
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
@legacy_function
def echo_float():
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
@legacy_function
def echo_string():
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
@legacy_function
def echo_strings():
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
@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
@legacy_function
def hello_string():
function = LegacyFunctionSpecification()
function.addParameter('string_out', dtype='string', direction=function.OUT)
function.result_type = 'int32'
function.can_handle_array = True
return function
@legacy_function
def echo_string_fixed_len():
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
@legacy_function
def echo_array_with_result():
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.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
@legacy_function
def echo_logical():
function = LegacyFunctionSpecification()
function.addParameter('input', dtype='bool', direction=function.IN)
function.addParameter('output', dtype='bool', direction=function.OUT)
function.result_type = 'int32'
function.can_handle_array = True
return function
@legacy_function
def echo_logical2():
function = LegacyFunctionSpecification()
function.addParameter('input', dtype='bool', direction=function.IN)
function.addParameter('output', dtype='bool', direction=function.OUT)
function.addParameter('n', dtype='int32', direction=function.LENGTH)
function.result_type = 'int32'
function.must_handle_array = True
return function
@legacy_function
def print_string():
function = LegacyFunctionSpecification()
function.addParameter('string_in', dtype='string', direction=function.IN)
function.result_type = 'int32'
function.can_handle_array = True
return function
@legacy_function
def print_error_string():
function = LegacyFunctionSpecification()
function.addParameter('string_in', dtype='string', direction=function.IN)
function.result_type = 'int32'
function.can_handle_array = True
return function
@legacy_function
def get_element_status():
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(
'echo_int',
(units.m,)
,
(
units.m,
object.ERROR_CODE,
)
)
"""
class TestInterface(TestWithMPI):
@classmethod
def skip_if_fortran_does_not_support_mpi(cls):
try:
from amuse import config
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)
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]
output, errors = instance.echo_int(input)
del instance
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]
output, errors = instance.echo_double(input)
del instance
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
self.assertEqual(error, 0)
self.assertEqual(out, "abc")
def test7(self):
instance = ForTestingInterface(self.exefile)
out, error = instance.echo_string(["abc", "def"])
del instance
self.assertEqual(error[0], 0)
self.assertEqual(error[1], 0)
self.assertEqual(out[0], "abc")
self.assertEqual(out[1], "def")
def test8(self):
instance = ForTestingInterface(self.exefile)
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])
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])
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)
(output2, error2) = instance.echo_logical(False)
instance.stop()
self.assertEqual(error1, 0)
self.assertEqual(error2, 0)
self.assertTrue(output1)
self.assertFalse(output2)
def test16b(self):
instance = ForTesting(self.exefile)
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)
self.assertEqual(output, [True, True, False, True, False]*1024)
def xtest20(self):
#
# TURNED OFF support for redirection,
# by default output is redirected to /dev/null
# if you need file, use the support from your mpi implementation
#
if os.path.exists("pout.000"):
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.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:
content = f.read()
self.assertEqual(content.strip(), "abc")
self.assertTrue(os.path.exists("perr.000"))
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.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:
content = f.read()
self.assertEqual(content.strip(), "abc\n def")
self.assertTrue(os.path.exists("perr.000"))
with open("perr.000", "r") as f:
content = f.read()
self.assertEqual(content.strip(), "exex\n exex")
def test17(self):
self.check_for_mpi()
instance = ForTestingInterface(self.exefile)
(output1, error1) = instance.internal__get_message_polling_interval()
error2 = instance.internal__set_message_polling_interval(1234)
(output2, error3) = instance.internal__get_message_polling_interval()
instance.stop()
self.assertEqual(error1, 0)
self.assertEqual(output1, 0)
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()
t1 = time.time()
error2 = instance.internal__set_message_polling_interval(500 * 1000)
t2 = time.time()
(output2, error3) = instance.internal__get_message_polling_interval()
time.sleep(0.1)
(output2, error3) = instance.internal__get_message_polling_interval()
t3 = time.time()
instance.stop()
self.assertEqual(error1, 0)
self.assertEqual(output1, 0)
self.assertEqual(error2, 0)
self.assertEqual(error3, 0)
self.assertEqual(output2, 500 * 1000)
# ~ print t1 - t0, t3 - t2
# ~ self.assertTrue((t3 - t2) > 0.25)
def test19(self):
self.check_for_mpi()
instance1 = ForTestingInterface(self.exefile)
instance2 = ForTestingInterface(self.exefile)
portname, error = instance1.internal__open_port()
self.assertTrue(len(portname) > 0)
request1 = instance1.internal__accept_on_port.asynchronous(portname)
request2 = instance2.internal__connect_to_port.asynchronous(portname)
request1.wait()
request2.wait()
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()
for i in range(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()
for i in range(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)
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)
N = 255
out, error = instance.echo_string("a"*N)
del instance
self.assertEqual(error, 0)
self.assertEqual(out, "a"*N)
| 20,814
| 29.610294
| 123
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/compile_tests/test_c_sockets_implementation.py
|
from amuse.support.interface import InCodeComponentImplementation
from amuse.test.amusetest import TestWithMPI
from amuse.support import exceptions
from amuse.support import options
import os
import time
from amuse.units import nbody_system
from amuse.units import units
from amuse import datamodel
from amuse.rfi.tools import create_c
from amuse.rfi import channel
from amuse.rfi.core import *
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
options.GlobalOptions.instance().override_value_for_option("channel_type", "sockets")
@classmethod
def teardown_class(cls):
del options.GlobalOptions.instance().overriden_options["channel_type"]
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
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!
if 'HYDRA_CONTROL_FD' in os.environ or 'PMI_FD' in os.environ:
cls.skip('cannot run the socket tests under mpi process manager')
| 1,694
| 32.235294
| 94
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/compile_tests/test_fortran_sockets_implementation.py
|
from amuse.support.interface import InCodeComponentImplementation
from amuse.test.amusetest import TestWithMPI
from amuse.test import compile_tools
import os
import time
import shlex
from amuse.units import nbody_system
from amuse.units import units
from amuse import datamodel
from amuse.rfi import channel
from amuse.rfi.core import *
from .test_fortran_implementation import codestring, ForTestingInterface
class ForTesting(InCodeComponentImplementation):
def __init__(self, exefile, **options):
InCodeComponentImplementation.__init__(self, ForTestingInterface(exefile, **options), **options)
class TestInterface(TestWithMPI):
@classmethod
def setup_class(cls):
print("building")
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)
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
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]
output, errors = instance.echo_int(input)
del instance
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]
output, errors = instance.echo_double(input)
del instance
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
self.assertEqual(error, 0)
self.assertEqual(out, "abc")
def test7(self):
instance = ForTestingInterface(self.exefile, channel_type="sockets")
out, error = instance.echo_string(["abc", "def"])
del instance
self.assertEqual(error[0], 0)
self.assertEqual(error[1], 0)
self.assertEqual(out[0], "abc")
self.assertEqual(out[1], "def")
def test8(self):
instance = ForTestingInterface(self.exefile, channel_type="sockets")
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])
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])
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)
(output2, error2) = instance.echo_logical(False)
instance.stop()
self.assertEqual(error1, 0)
self.assertEqual(error2, 0)
self.assertTrue(output1)
self.assertFalse(output2)
def test16b(self):
instance = ForTesting(self.exefile, channel_type="sockets")
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)
self.assertEqual(output, [True, True, False, True, False]*1024)
def xtest20(self):
#
# TURNED OFF support for redirection,
# by default output is redirected to /dev/null
# if you need file, use the support from your mpi implementation
#
if os.path.exists("pout.000"):
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.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:
content = f.read()
self.assertEqual(content.strip(), "abc")
self.assertTrue(os.path.exists("perr.000"))
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.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:
content = f.read()
self.assertEqual(content.strip(), "abc\n def")
self.assertTrue(os.path.exists("perr.000"))
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)
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
out, error = instance.echo_string("a"*N)
del instance
self.assertEqual(error, 0)
self.assertEqual(out, "a"*N)
| 9,363
| 33.300366
| 147
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/compile_tests/test_python_sockets_implementation.py
|
from amuse.support.interface import InCodeComponentImplementation
from amuse.test.amusetest import TestWithMPI, TestCase
import numpy
import sys
import os
import time
from amuse.units import nbody_system
from amuse.units import units
from amuse import datamodel
from amuse.rfi import python_code
from amuse.rfi.core import *
from amuse.rfi.async_request import AsyncRequestsPool
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)
def ForTestingInterface(self, **options):
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]
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)
self.assertEqual(output_message.ints[3], 0)
self.assertEqual(implementation.masses[1], 12.0)
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
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)
def ForTestingInterface(self, **options):
options["worker_dir"] = self.get_path_to_results()
options["channel_type"] = "sockets"
return test_python_implementation_mpi.ForTestingInterface(**options)
| 5,536
| 37.451389
| 108
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/compile_tests/test_c_distributed_implementation.py
|
from amuse.support.interface import InCodeComponentImplementation
from amuse.community.distributed.interface import DistributedAmuse, Pilot
from amuse.test.amusetest import TestWithMPI
from amuse.support import exceptions
import os
import time
from amuse.units import nbody_system
from amuse.units import units
from amuse import datamodel
from amuse.rfi.tools import create_c
from amuse.rfi import channel
from amuse.rfi.core import *
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')
cls.distinstance.parameters.debug = False
# ~ 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'
cls.distinstance.pilots.add_pilot(pilot)
# ~ print "Pilots:"
# ~ print cls.distinstance.pilots
# ~ print "Waiting for pilots"
cls.distinstance.wait_for_pilots()
cls.distinstance.use_for_all_workers()
@classmethod
def tearDown(cls):
# ~ print "Stopping distributed code"
cls.distinstance.stop()
@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
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 test22(self):
self.skip("this test uses mpi internals, skip here")
| 2,224
| 31.246377
| 106
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/compile_tests/test_python_implementation_mpi.py
|
from amuse.support.interface import InCodeComponentImplementation
from amuse.test.amusetest import TestWithMPI
from amuse import datamodel
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)
@legacy_function
def get_range():
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.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
@legacy_function
def get_dens():
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
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
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.dens = x**2
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)
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)
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)
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)
def ForTestingInterface(self, **options):
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.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)
interface.stop()
| 3,914
| 32.461538
| 102
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/compile_tests/__init__.py
| 0
| 0
| 0
|
py
|
|
amuse
|
amuse-main/src/amuse/test/suite/compile_tests/test_grid_implementation.py
|
from amuse.support.interface import InCodeComponentImplementation
from amuse.test.amusetest import TestWithMPI
from amuse.test import compile_tools
from amuse.support import exceptions
import subprocess
import os
import time
from amuse.units import nbody_system
from amuse.units import units
from amuse import datamodel
from amuse.rfi.tools import create_c
from amuse.rfi import channel
from amuse.rfi.core import *
codestring = """
#include <stdio.h>
#include <stdlib.h>
double grid0;
double grid1[10];
double grid2[10][10];
int set0(double in) {
grid0=in;
return 0;
}
int get0(double *out) {
*out=grid0;
return 0;
}
int get_grid0_range() {
return 0;
}
"""
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()
@remote_function
def get0():
returns(a=0. | units.m)
@remote_function
def get_grid0_range():
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")
object.set_grid_range('grid0', 'get_grid0_range')
object.add_getter('grid0', 'get0', names=['a'])
object.add_setter('grid0', 'set0', names=['a'])
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")
compile_tools.c_compile(codefile, codestring)
uc = create_c.GenerateACHeaderStringFromASpecificationClass()
uc.specification_class = ForTestingInterface
uc.needs_mpi = False
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
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()
print("building...", end=' ')
self.check_can_compile_modules()
try:
self.build_worker()
except Exception as ex:
print(ex)
raise
print("done")
def test1(self):
instance = ForTestingInterface(self.exefile)
error = instance.set0(1)
a_out, error = instance.get0()
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.stop()
def test3(self):
instance1 = ForTesting(self.exefile)
instance2 = ForTesting(self.exefile)
instance1.grid0.a = 12. | units.m
instance1.grid0.new_channel_to(instance2.grid0).copy_all_attributes()
self.assertEqual(instance2.grid0.a, 12. | units.m)
instance1.stop()
instance2.stop()
| 3,694
| 26.992424
| 112
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/compile_tests/test_c_implementation.py
|
from amuse.support.interface import InCodeComponentImplementation
from amuse.test.amusetest import TestWithMPI
from amuse.test import compile_tools
from amuse.support import exceptions
import os
import time
from amuse.units import nbody_system
from amuse.units import units
from amuse import datamodel
from amuse.rfi import channel
from amuse.rfi.core import *
codestring = """
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int echo_int(int int_in, int * int_out) {
*int_out = int_in;
if(int_in < 0) {
return -1;
} else {
return 0;
}
}
int echo_long_long_int(long long int int_in, long long int * int_out) {
*int_out = int_in;
if(int_in < 0) {
return -1;
} else {
return 0;
}
}
int echo_double(double in, double * out) {
*out = in;
return 0;
}
int echo_float(float in, float * out) {
*out = in;
return 0;
}
int echo_string(char * in, char ** out) {
*out = in;
return 0;
}
int echo_string_int(int inint, char * in, char ** out) {
*out = in;
return 0;
}
int echo_string_two(char * in1, char * in2, char ** out1, char ** out2) {
*out1 = in1;
*out2 = in2;
return 0;
}
int print_string(char * in) {
fprintf(stdout, "%s\\n", in);
return 0;
}
int print_error_string(char * in) {
fprintf(stderr, "%s\\n", in);
return 0;
}
int echo_strings(char ** inout1, char ** inout2) {
char * tmp;
tmp = *inout1;
*inout1 = *inout2;
*inout2 = tmp;
return 0;
}
void echo_array(int * in, int * out, int len) {
int i = 0;
for(i = 0; i < len; i++) {
out[i] = in[i];
}
}
int echo_array_with_result(int * in, int *out, int len) {
int i = 0;
for(i = 0; i < len; i++) {
out[i] = in[i];
}
return -1;
}
int echo_2_int(int * int_in1, int * int_in2, int * int_out1, int * int_out2, int len) {
int i = 0;
for(i = 0; i < len; i++) {
int_out1[i] = int_in1[i];
int_out2[i] = int_in2[i];
}
return len;
}
int echo_3_int(int * i, int * j, int * k, int * l, int * m, int * int_out, int len) {
int x = 0;
for(x = 0; x < len; x++) {
int_out[x] = i;
}
return len;
}
int dummy_3_int(int i, int j, int k) {
return 0;
}
int echo_inout_array_with_result(int * inout, int len) {
int i = 0;
for(i = 0; i < len; i++) {
inout[i] = inout[i] + 10;
}
return 11;
}
int echo_logical(bool in, bool * out) {
*out = in;
return 0;
}
/*
int echo_string_array(char ** in, char ** out, int len) {
int x = 0;
for(x = 0; x < len; x++) {
out[x] = in[x];
}
return len;
}
*/
int sum_doubles(double in1, double in2, double * out) {
*out = in1 + in2;
return 0;
}
"""
class ForTestingInterface(CodeInterface):
include_headers = ['worker_code.h']
def __init__(self, exefile, **options):
CodeInterface.__init__(self, exefile, **options)
@legacy_function
def echo_int():
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
@legacy_function
def echo_long_long_int():
function = LegacyFunctionSpecification()
function.addParameter('in', dtype='int64', direction=function.IN)
function.addParameter('out', dtype='int64', direction=function.OUT)
function.result_type = 'int32'
function.can_handle_array = True
return function
@legacy_function
def echo_double():
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
@legacy_function
def echo_float():
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
@legacy_function
def echo_string():
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
@legacy_function
def echo_strings():
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
@legacy_function
def echo_string_int():
function = LegacyFunctionSpecification()
function.addParameter('inint', dtype='int32', direction=function.IN)
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
@legacy_function
def echo_string_two():
function = LegacyFunctionSpecification()
function.addParameter('in1', dtype='string', direction=function.IN)
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
@legacy_function
def echo_array():
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.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 return_string():
function = LegacyFunctionSpecification()
function.addParameter('string_in', dtype='string', direction=function.IN)
function.result_type = 'string'
function.can_handle_array = True
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_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
@legacy_function
def echo_3_int():
function = LegacyFunctionSpecification()
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('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.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
@legacy_function
def echo_logical():
function = LegacyFunctionSpecification()
function.addParameter('input', dtype='bool', direction=function.IN)
function.addParameter('output', dtype='bool', direction=function.OUT)
function.result_type = 'int32'
function.can_handle_array = True
return function
@legacy_function
def print_string():
function = LegacyFunctionSpecification()
function.addParameter('string_in', dtype='string', direction=function.IN)
function.result_type = 'int32'
function.can_handle_array = True
return function
@legacy_function
def dummy_3_int():
function = LegacyFunctionSpecification()
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.result_type = 'int32'
return function
@legacy_function
def print_error_string():
function = LegacyFunctionSpecification()
function.addParameter('string_in', dtype='string', direction=function.IN)
function.result_type = 'int32'
function.can_handle_array = True
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_out', dtype='float64', 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(
'echo_int',
(units.m,),
(
units.m,
object.ERROR_CODE,
)
)
class TestCImplementationInterface(TestWithMPI):
@classmethod
def setup_class(cls):
print("building...")
cls.check_can_compile_modules()
try:
cls.exefile = compile_tools.build_worker(codestring, cls.get_path_to_results(), ForTestingInterface)
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]
output, errors = instance.echo_int(input)
instance.stop()
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]
output, errors = instance.echo_double(input)
instance.stop()
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()
self.assertEqual(error, 0)
self.assertEqual(out, "abc")
def test7(self):
instance = ForTestingInterface(self.exefile)
out, error = instance.echo_string(["abc", "def"])
instance.stop()
self.assertEqual(error[0], 0)
self.assertEqual(error[1], 0)
self.assertEqual(out[0], "abc")
self.assertEqual(out[1], "def")
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))
instance.stop()
def test7c(self):
instance = ForTestingInterface(self.exefile)
out, error = instance.echo_string(["abc"]*10)
self.assertEqual(error, [0]*10)
self.assertEqual(out, ["abc"]*10)
instance.stop()
def test7d(self):
instance = ForTestingInterface(self.exefile)
out, error = instance.echo_string(["abc"]*100000)
self.assertEqual(error, [0]*100000)
self.assertEqual(out, ["abc"]*100000)
instance.stop()
def test8(self):
instance = ForTestingInterface(self.exefile)
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'.
Also note: to test this, you best set the ulimit
to a low number (but not too low), for example
ulimit -n 400
"""
for x in range(400):
instance = ForTestingInterface(self.exefile)
out, error = instance.echo_float(4.0)
if x % 100 == 0:
print("x:", x)
instance.stop()
def test11(self):
instance = ForTestingInterface(self.exefile)
(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])
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 '<class 'amuse.test.suite.compile_tests.test_c_implementation.ForTesting'>', errorcode is -1")
instance.stop()
def test14(self):
instance = ForTesting(self.exefile)
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))
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_ints7, output_ints8 = instance.echo_2_int([5])
instance.stop()
self.assertEqual(output_ints1[1], 2)
self.assertEqual(output_ints2[0], 3)
self.assertEqual(output_ints2[1], 4)
for i in range(3):
self.assertEqual(output_ints3[i], i + 1)
self.assertEqual(output_ints4[i], 1)
self.assertEqual(output_ints5[0], 5)
self.assertEqual(output_ints6[0], 0)
self.assertEqual(output_ints7[0], 5)
self.assertEqual(output_ints8[0], 1)
def test16(self):
instance = ForTesting(self.exefile)
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])
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 test18(self):
instance = ForTestingInterface(self.exefile)
out, error = instance.echo_logical([True, False, True])
instance.stop()
self.assertEqual(out, [True, False, True])
self.assertEqual(error, 0)
def test19(self):
instance = ForTestingInterface(self.exefile)
print(3935559000370003845)
int_out, error = instance.echo_long_long_int(3935559000370003845)
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
# if you need file, use the support from your mpi implementation
#
if os.path.exists("pout.000"):
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.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:
content = f.read()
self.assertEqual(content.strip(), "abc")
self.assertTrue(os.path.exists("perr.000"))
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.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:
content = f.read()
self.assertEqual(content.strip(), "abc\ndef\nexex")
def test21(self):
instance = ForTestingInterface(self.exefile)
(output1, error1) = instance.internal__get_message_polling_interval()
error2 = instance.internal__set_message_polling_interval(1234)
(output2, error3) = instance.internal__get_message_polling_interval()
instance.internal__set_message_polling_interval(0)
instance.stop()
self.assertEqual(error1, 0)
self.assertEqual(output1, 0)
self.assertEqual(error2, 0)
self.assertEqual(error3, 0)
self.assertEqual(output2, 1234)
def test22(self):
self.check_for_mpi()
instance = ForTestingInterface(self.exefile)
t0 = time.time()
(output1, error1) = instance.internal__get_message_polling_interval()
t1 = time.time()
error2 = instance.internal__set_message_polling_interval(500 * 1000)
t2 = time.time()
(output2, error3) = instance.internal__get_message_polling_interval()
t3 = time.time()
instance.stop()
self.assertEqual(error1, 0)
self.assertEqual(output1, 0)
self.assertEqual(error2, 0)
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)
def test23(self):
instance = ForTestingInterface(self.exefile)
out, error = instance.echo_string_int(1)
instance.stop()
self.assertEqual(error, 0)
self.assertEqual(out, "echo")
def test24(self):
instance = ForTestingInterface(self.exefile)
out, error = instance.echo_string_int(1, "abc")
instance.stop()
self.assertEqual(error, 0)
self.assertEqual(out, "abc")
def test25(self):
instance = ForTestingInterface(self.exefile)
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"])
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")
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")
instance.stop()
self.assertEqual(error, 0)
self.assertEqual(out1[0], "one")
self.assertEqual(out1[1], "two")
self.assertEqual(out2[0], "three")
self.assertEqual(out2[1], "three")
def test29(self):
self.check_for_mpi()
instance1 = ForTestingInterface(self.exefile)
instance2 = ForTestingInterface(self.exefile)
portname, error = instance1.internal__open_port()
self.assertTrue(len(portname) > 0)
request1 = instance1.internal__accept_on_port.asynchronous(portname)
request2 = instance2.internal__connect_to_port.asynchronous(portname)
request1.wait()
request2.wait()
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")
instance.stop()
def test31(self):
x = ForTesting(self.exefile, max_message_length=10)
N = 100
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)])
print(sums)
self.assertTrue(list(sums) == [3.0*i + 1 for i in range(N)])
N = 101
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)])
x.stop()
def test32(self):
for i in range(5):
instance = ForTestingInterface(self.exefile)
instance.stop()
| 25,225
| 32.679573
| 164
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/compile_tests/test_c_implementation_simplified.py
|
import unittest
import numpy
from amuse.support.interface import InCodeComponentImplementation
from amuse.test.amusetest import TestWithMPI
from amuse.test import compile_tools
from amuse.support import exceptions
import os
import time
from amuse.units import nbody_system
from amuse.units import units
from amuse import datamodel
from amuse.rfi.tools import create_c
from amuse.rfi import channel
from amuse.rfi.core import *
codestring = """
#include <stdio.h>
#include <stdlib.h>
int echo_int(int int_in, int * int_out) {
*int_out = int_in;
if(int_in < 0) {
return -1;
} else {
return 0;
}
}
int echo_long_long_int(long long int int_in, long long int * int_out) {
*int_out = int_in;
if(int_in < 0) {
return -1;
} else {
return 0;
}
}
int echo_double(double in, double * out) {
*out = in;
return 0;
}
int echo_float(float in, float * out) {
*out = in;
return 0;
}
int echo_string(char * in, char ** out) {
*out = in;
return 0;
}
int echo_string_int(int inint, char * in, char ** out) {
*out = in;
return 0;
}
int echo_string_two(char * in1, char * in2, char ** out1, char ** out2) {
*out1 = in1;
*out2 = in2;
return 0;
}
int print_string(char * in) {
fprintf(stdout, "%s\\n", in);
return 0;
}
int print_error_string(char * in) {
fprintf(stderr, "%s\\n", in);
return 0;
}
int echo_strings(char ** inout1, char ** inout2) {
char * tmp;
tmp = *inout1;
*inout1 = *inout2;
*inout2 = tmp;
return 0;
}
void echo_array(int * in, int * out, int len) {
int i = 0;
for(i = 0; i < len; i++) {
out[i] = in[i];
}
}
int echo_array_with_result(int * in, int *out, int len) {
int i = 0;
for(i = 0; i < len; i++) {
out[i] = in[i];
}
return -1;
}
int echo_2_int(int * int_in1, int * int_in2, int * int_out1, int * int_out2, int len) {
int i = 0;
for(i = 0; i < len; i++) {
int_out1[i] = int_in1[i];
int_out2[i] = int_in2[i];
}
return len;
}
int echo_3_int(int * i, int * j, int * k, int * l, int * m, int * int_out, int len) {
int x = 0;
for(x = 0; x < len; x++) {
int_out[x] = i;
}
return len;
}
int dummy_3_int(int i, int j, int k) {
return 0;
}
int echo_inout_array_with_result(int * inout, int len) {
int i = 0;
for(i = 0; i < len; i++) {
inout[i] = inout[i] + 10;
}
return 11;
}
int echo_logical(int in, int * out) {
*out = in;
return 0;
}
/*
int echo_string_array(char ** in, char ** out, int len) {
int x = 0;
for(x = 0; x < len; x++) {
out[x] = in[x];
}
return len;
}
*/
"""
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')
@remote_function(can_handle_array=True)
def echo_long_long_int(int_in='int64'):
returns(int_out='int64')
@remote_function(can_handle_array=True)
def echo_double(double_in='float64'):
returns(double_out='float64')
@remote_function(can_handle_array=True)
def echo_float(float_in='float32'):
returns(float_out='float32')
@remote_function(can_handle_array=True)
def echo_string(string_in='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')
@remote_function(can_handle_array=True)
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')
@remote_function(must_handle_array=True)
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
@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')
@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')
@remote_function(must_handle_array=True)
def echo_inout_array_with_result(in_out='int32'):
returns(in_out='int32')
@remote_function(can_handle_array=True)
def echo_logical(input='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'):
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,
object.ERROR_CODE,
)
)
class TestCImplementationInterface(TestWithMPI):
@classmethod
def setup_class(cls):
print("building...")
cls.check_can_compile_modules()
try:
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]
output, errors = instance.echo_int(input)
instance.stop()
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]
output, errors = instance.echo_double(input)
instance.stop()
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()
self.assertEqual(error, 0)
self.assertEqual(out, "abc")
def test7(self):
instance = ForTestingInterface(self.exefile)
out, error = instance.echo_string(["abc", "def"])
instance.stop()
self.assertEqual(error[0], 0)
self.assertEqual(error[1], 0)
self.assertEqual(out[0], "abc")
self.assertEqual(out[1], "def")
def test8(self):
instance = ForTestingInterface(self.exefile)
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'.
Also note: to test this, you best set the ulimit
to a low number (but not too low), for example
ulimit -n 400
"""
for x in range(400):
instance = ForTestingInterface(self.exefile)
out, error = instance.echo_float(4.0)
if x % 100 == 0:
print("x:", x)
instance.stop()
def test11(self):
instance = ForTestingInterface(self.exefile)
(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])
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")
instance.stop()
def test14(self):
instance = ForTesting(self.exefile)
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))
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_ints7, output_ints8 = instance.echo_2_int([5])
instance.stop()
self.assertEqual(output_ints1[1], 2)
self.assertEqual(output_ints2[0], 3)
self.assertEqual(output_ints2[1], 4)
for i in range(3):
self.assertEqual(output_ints3[i], i + 1)
self.assertEqual(output_ints4[i], 1)
self.assertEqual(output_ints5[0], 5)
self.assertEqual(output_ints6[0], 0)
self.assertEqual(output_ints7[0], 5)
self.assertEqual(output_ints8[0], 1)
def test16(self):
instance = ForTesting(self.exefile)
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])
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 test18(self):
instance = ForTestingInterface(self.exefile)
out, error = instance.echo_logical([True, False, True])
instance.stop()
self.assertEqual(out, [True, False, True])
self.assertEqual(error, 0)
def test19(self):
instance = ForTestingInterface(self.exefile)
print(3935559000370003845)
int_out, error = instance.echo_long_long_int(3935559000370003845)
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
# if you need file, use the support from your mpi implementation
#
if os.path.exists("pout.000"):
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.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:
content = f.read()
self.assertEqual(content.strip(), "abc")
self.assertTrue(os.path.exists("perr.000"))
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.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:
content = f.read()
self.assertEqual(content.strip(), "abc\ndef\nexex")
def test21(self):
instance = ForTestingInterface(self.exefile)
(output1, error1) = instance.internal__get_message_polling_interval()
error2 = instance.internal__set_message_polling_interval(1234)
(output2, error3) = instance.internal__get_message_polling_interval()
instance.internal__set_message_polling_interval(0)
instance.stop()
self.assertEqual(error1, 0)
self.assertEqual(output1, 0)
self.assertEqual(error2, 0)
self.assertEqual(error3, 0)
self.assertEqual(output2, 1234)
def test22(self):
self.check_for_mpi()
instance = ForTestingInterface(self.exefile)
t0 = time.time()
(output1, error1) = instance.internal__get_message_polling_interval()
t1 = time.time()
error2 = instance.internal__set_message_polling_interval(500 * 1000)
t2 = time.time()
(output2, error3) = instance.internal__get_message_polling_interval()
t3 = time.time()
instance.stop()
self.assertEqual(error1, 0)
self.assertEqual(output1, 0)
self.assertEqual(error2, 0)
self.assertEqual(error3, 0)
self.assertEqual(output2, 500 * 1000)
# ~ 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()
self.assertEqual(error, 0)
self.assertEqual(out, "echo")
def test24(self):
instance = ForTestingInterface(self.exefile)
out, error = instance.echo_string_int(1, "abc")
instance.stop()
self.assertEqual(error, 0)
self.assertEqual(out, "abc")
def test25(self):
instance = ForTestingInterface(self.exefile)
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"])
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")
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")
instance.stop()
self.assertEqual(error, 0)
self.assertEqual(out1[0], "one")
self.assertEqual(out1[1], "two")
self.assertEqual(out2[0], "three")
self.assertEqual(out2[1], "three")
def test29(self):
self.check_for_mpi()
instance1 = ForTestingInterface(self.exefile)
instance2 = ForTestingInterface(self.exefile)
portname, error = instance1.internal__open_port()
self.assertTrue(len(portname) > 0)
request1 = instance1.internal__accept_on_port.asynchronous(portname)
request2 = instance2.internal__connect_to_port.asynchronous(portname)
request1.wait()
request2.wait()
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")
instance.stop()
@unittest.skip
def test31(self):
import time
instance = ForTestingInterface(self.exefile)
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)
instance.stop()
instance = ForTesting(self.exefile)
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)
instance.stop()
| 18,747
| 29.784893
| 164
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/compile_tests/test_stopping_conditions.py
|
from amuse.test.amusetest import TestWithMPI
from amuse.test import compile_tools
from amuse.test.amusetest import get_amuse_root_dir
# cello
from amuse.community.interface import stopping_conditions
from amuse.support.interface import InCodeComponentImplementation
import os
import shlex
from amuse.units import nbody_system
from amuse.units import units
from amuse import datamodel
from amuse.support.exceptions import AmuseException
from amuse.rfi.tools import create_c
from amuse.rfi.tools import create_fortran
from amuse.rfi import channel
from amuse.rfi.core import *
from amuse.community import NO_UNIT
codestring = """
#ifndef NOMPI
#include <mpi.h>
#endif
#include <stopcond.h>
#ifdef __cplusplus
extern "C" {
#endif
int initialize_code()
{
// AMUSE STOPPING CONDITIONS SUPPORT
supported_conditions = COLLISION_DETECTION_BITMAP | PAIR_DETECTION_BITMAP | TIMEOUT_DETECTION_BITMAP | OUT_OF_BOX_DETECTION_BITMAP;
// -----------------------
return 0;
}
int fire_condition(int condition_to_set, int particle_index1, int particle_index2, int rank) {
int my_rank;
int error, stopping_index;
#ifndef NOMPI
error = MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
#else
error = 0;
my_rank = rank;
#endif
if (rank >= 0 && rank != my_rank) { return 0; }
stopping_index = next_index_for_stopping_condition();
error = set_stopping_condition_info(stopping_index, condition_to_set);
if(particle_index1 > 0) {
error = set_stopping_condition_particle_index(stopping_index, 0, particle_index1);
}
if(particle_index2 > 0) {
error = set_stopping_condition_particle_index(stopping_index, 1, particle_index2);
}
return 0;
}
#ifdef __cplusplus
}
#endif
"""
codestringF = """
FUNCTION initialize_code()
IMPLICIT NONE
include "stopcond.inc"
INTEGER :: initialize_code
INTEGER :: set_support_for_condition
INTEGER :: return
initialize_code = 0
return = set_support_for_condition(COLLISION_DETECTION)
return = set_support_for_condition(PAIR_DETECTION)
RETURN
END FUNCTION
"""
codestringFModule = """
MODULE AmuseInterface
CONTAINS
FUNCTION initialize_code()
use StoppingConditions
IMPLICIT NONE
INTEGER :: initialize_code
INTEGER :: return
initialize_code = 0
return = set_support_for_condition(COLLISION_DETECTION)
return = set_support_for_condition(PAIR_DETECTION)
END FUNCTION
FUNCTION fire_condition(condition_to_set, particle_index1, particle_index2, rank)
use StoppingConditions
IMPLICIT NONE
include "mpif.h"
INTEGER :: fire_condition
INTEGER :: my_rank
INTEGER :: error, stopping_index
INTEGER, intent(in) :: condition_to_set, particle_index1, particle_index2, rank
fire_condition = 0
call mpi_comm_rank(MPI_COMM_WORLD, my_rank, error)
if (rank.GE.0 .AND. rank.NE.my_rank) then
return
end if
stopping_index = next_index_for_stopping_condition()
error = set_stopping_condition_info(stopping_index, condition_to_set)
if(particle_index1 .GT. 0) then
error = set_stopping_condition_particle_index(stopping_index, 0, particle_index1)
end if
if(particle_index2 .GT. 0) then
error = set_stopping_condition_particle_index(stopping_index, 1, particle_index2)
end if
END FUNCTION
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.result_type = 'int32'
function.can_handle_array = False
return function
@legacy_function
def reset_stopping_conditions():
function = LegacyFunctionSpecification()
function.result_type = 'int32'
function.can_handle_array = False
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
@legacy_function
def set_stopping_condition_info():
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
@legacy_function
def set_stopping_condition_particle_index():
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
@legacy_function
def mpi_setup_stopping_conditions():
function = LegacyFunctionSpecification()
function.result_type = 'int32'
function.can_handle_array = False
return function
@legacy_function
def mpi_collect_stopping_conditions():
function = LegacyFunctionSpecification()
function.result_type = 'int32'
function.can_handle_array = False
return function
@legacy_function
def mpi_distribute_stopping_conditions():
function = LegacyFunctionSpecification()
function.result_type = 'int32'
function.can_handle_array = False
return function
class ForTestingInterfaceFortranModule(ForTestingInterface):
use_modules = ['StoppingConditions', 'AmuseInterface']
@legacy_function
def fire_condition():
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.result_type = 'int32'
function.can_handle_array = True
return function
class ForTesting(InCodeComponentImplementation):
def __init__(self, exefile, **options):
if 'community_interface' in options:
interface = options['community_interface']
else:
interface = ForTestingInterface
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')
object.set_delete('particles', 'delete_particle')
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,
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
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.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.initialize_code()
self.assertFalse(instance.stopping_conditions.pair_detection.is_enabled())
instance.stopping_conditions.pair_detection.enable()
self.assertTrue(instance.stopping_conditions.pair_detection.is_enabled())
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)
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_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)
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)
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_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))
self.assertEqual(12, instance.get_stopping_condition_particle_index(next, 1))
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_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))
self.assertEqual(index2, instance.get_stopping_condition_particle_index(next, 1))
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,
[first + 1 for first, second in pairs] | units.kg)
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.")
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
self.assertEqual(next, i)
instance.stop()
class TestInterfaceMP(_AbstractTestInterface):
@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.reset_stopping_conditions()
instance.mpi_setup_stopping_conditions()
instance.enable_stopping_condition(1)
nmax = 50
for i in range(nmax):
next = instance.next_index_for_stopping_condition()
self.assertEqual(next, i)
i, error = instance.get_number_of_stopping_conditions_set()
self.assertEqual(error, 0)
self.assertEqual(i, nmax)
instance.mpi_collect_stopping_conditions()
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()
)
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
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)
instance.stop()
def test5(self):
instance = ForTesting(
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
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)
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()
)
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
)
instance.fire_condition(
pair_detection.type,
3, 4, 1
)
instance.fire_condition(
pair_detection.type,
5, 6, 2
)
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)
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()
)
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)
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
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()])
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.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, 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())
self.assertFalse(instance.stopping_conditions.escaper_detection.is_supported())
instance.stop()
def test3(self):
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()
self.assertTrue(instance.stopping_conditions.pair_detection.is_enabled())
instance.stopping_conditions.pair_detection.disable()
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.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)
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.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_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())
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_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))
self.assertEqual(12, instance.get_stopping_condition_particle_index(next, 1))
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_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))
self.assertEqual(index2, instance.get_stopping_condition_particle_index(next, 1))
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,
[first + 1 for first, second in pairs] | units.kg)
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.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.")
instance.stop()
def test9(self):
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
self.assertEqual(next, i)
instance.stop()
class TestInterfaceFortran(_TestInterfaceFortranSingleProcess):
@classmethod
def get_libname(cls):
return 'stopcond'
@classmethod
def get_codestring(cls):
return codestringF
@classmethod
def get_interface_class(cls):
return ForTestingInterface
class TestInterfaceFortranModule(_TestInterfaceFortranSingleProcess):
@classmethod
def get_libname(cls):
return 'stopcond'
@classmethod
def get_codestring(cls):
return codestringFModule
@classmethod
def get_interface_class(cls):
return ForTestingInterfaceFortranModule
class TestInterfaceFortranModuleMultiprocess(TestWithMPI, _AbstractTestInterfaceFortran):
@classmethod
def get_libname(cls):
return 'stopcondmpi'
@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()
)
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
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)
instance.stop()
def test2(self):
instance = ForTesting(
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
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)
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()
)
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
)
instance.fire_condition(
pair_detection.type,
3, 4, 1
)
instance.fire_condition(
pair_detection.type,
5, 6, 2
)
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)
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()
)
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)
instance.stop()
def test5(self):
number_of_workers = 4
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)
nmax = 50
for i in range(nmax):
next = instance.next_index_for_stopping_condition()
self.assertEqual(next, i)
i, error = instance.get_number_of_stopping_conditions_set()
self.assertEqual(error, 0)
self.assertEqual(i, nmax)
instance.mpi_collect_stopping_conditions()
i, error = instance.get_number_of_stopping_conditions_set()
self.assertEqual(error, 0)
self.assertEqual(i, number_of_workers * nmax)
instance.stop()
| 36,066
| 38.07584
| 221
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_generic_units.py
|
from amuse.test import amusetest
from amuse.units import constants
from amuse.units.generic_unit_converter import *
class TestGenericUnits(amusetest.TestCase):
def test1(self):
L = 1 | length
T = 1 | time
V = 1 | speed
self.assertTrue(L/T == V)
def test2(self):
# 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)
def test3(self):
# 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
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(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
UnitMass_in_g = 1.989e43 | units.g # 1.0e10 solar masses
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(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 "
"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, )
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)
| 4,313
| 44.893617
| 119
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_io.py
|
from amuse.test import amusetest
from amuse.support.exceptions import AmuseException
import os
import tempfile
from amuse import io
from amuse.io import base
from amuse.units import nbody_system
from amuse.units import units
from amuse import datamodel
class ForTestFileFormatProcessor(base.FileFormatProcessor):
"""
Save files in a test format
long description
"""
provided_formats = ['test', '123']
instance = None
def __init__(self, filename=None, set=None, format=None):
base.FileFormatProcessor.__init__(self, filename, set, format)
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"""
return False
def store(self):
self.stored = True
def load(self):
return 10
class FrameworkTests(amusetest.TestCase):
def test1(self):
options = ForTestFileFormatProcessor.get_options()
self.assertTrue('add_comma' in options)
self.assertTrue('save_fast' in options)
ForTestFileFormatProcessor.register()
base.write_set_to_file(None, "test.txt", format="123")
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):
ForTestFileFormatProcessor.register()
base.write_set_to_file(None, "test.txt", format="123", add_comma=False)
self.assertFalse(ForTestFileFormatProcessor.instance.add_comma)
def test3(self):
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])
name, description, default = options[0]
self.assertEqual(name, 'add_comma')
self.assertEqual(description, 'if True will add a comma between each value')
self.assertEqual(default, True)
name, description, default = options[2]
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.")
processor = base.FileFormatProcessor(format="test")
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"
" 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")
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)
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")
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 "
"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)
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 "
"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)
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 "
"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"):
os.remove("test_unit.hdf5")
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")
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)
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")
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")
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"
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")
self.assertAlmostEqual(x.mass, y.mass, 8)
self.assertEqual(y.previous_state().previous_state(), None)
os.remove("test_unit.hdf5")
def test6b(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")
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")
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"
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")
self.assertAlmostEqual(x.mass, y.mass, 8)
self.assertEqual(y.previous_state().previous_state(), None)
os.remove("test_unit.hdf5")
def test6c(self):
print("Testing HDF5 io, with options, version=2.0")
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="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")
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)
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)
self.assertAlmostEqual(x.mass, y.mass, 8)
self.assertEqual(y.previous_state(), None)
os.remove("test_unit.hdf5")
def test6d(self):
print("Testing HDF5 io, with options, version=2.0")
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="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")
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"
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)
self.assertAlmostEqual(x.mass, y.mass, 8)
self.assertEqual(y.previous_state(), None)
os.remove("test_unit.hdf5")
def test7(self):
print("Testing HDF5 io with a ParticlesSuperset")
if os.path.exists("test_unit.hdf5"):
os.remove("test_unit.hdf5")
set1 = datamodel.Particles(2)
set2 = datamodel.Particles(2)
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")
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)
os.remove("test_unit.hdf5")
def test8(self):
options = base.get_options_for_format('tsf')
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])
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])
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'"
", 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
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)
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)
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
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")
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)
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
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)
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)
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
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")
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)
os.remove("time_test_unit.tsf")
def test12(self):
all_formats = sorted(base.registered_fileformat_processors.keys())
for x in all_formats:
options = base.get_options_for_format('txt')
self.assertTrue(len(options) >= 0)
def test_hdf5_compressed(self):
options = {
"version": "2.0",
"compression": "gzip",
"compression_opts": 5,
}
with tempfile.NamedTemporaryFile() as tmp:
filename = tmp.name
x = datamodel.Particles(2)
x.mass = [1.0, 2.0] | units.kg
io.write_set_to_file(x, filename, "hdf5", **options, overwrite_file=True)
x.mass = [10.0, 20.0] | units.kg
io.write_set_to_file(x, filename, "hdf5", append_to_file=True, **options)
x.mass = [100.0, 200.0] | units.kg
io.write_set_to_file(x, filename, "hdf5", append_to_file=True, **options)
y = io.read_set_from_file(filename, "hdf5", copy_history=False, close_file=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, 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)
self.assertEqual(y.previous_state().previous_state(), None)
| 20,139
| 46.056075
| 115
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_amuse_import.py
|
import amuse
import sys
print(sys.path)
def test():
amuse.config.compilers.fc_iso_c_bindings
if __name__ == "__main__":
test()
| 141
| 9.142857
| 44
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_trees.py
|
from amuse.test import amusetest
from amuse.support.exceptions import AmuseException
from amuse.units import units
from amuse.units import constants
from amuse.units import nbody_system
from amuse.support.interface import InCodeComponentImplementation
import numpy
import time
import sys
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',])
self.assertEqual(len(binaries), 1)
def test3(self):
n = 10
particles = Particles(n)
particles.mass = range(n) | units.kg
particles[0].child1 = particles[1]
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",])
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_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
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)
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)
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 = 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,
[
('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', 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,
[
(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 = ''
for level, particle in binary.iter_levels():
output += '..' * level
output += str(particle.mass.value_in(units.kg))
output += '\n'
self.assertEqual(output, """0.0
..1.0
....3.0
....4.0
..2.0
""")
def test8(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")
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)
self.assertEqual(len(list(tree.iter_branches())), 1)
self.assertEqual(len(list(tree.iter_leafs())), 7)
branches = list(tree.iter_branches())
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)
self.assertEqual(len(list(tree.iter_descendant_branches())), 1)
branches = list(tree.iter_branches())
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
particles[0].child1 = particles[1]
particles[0].child2 = particles[2]
particles[1].child1 = particles[3]
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)
self.assertEqual(len(list(tree.iter_branches())), 1)
self.assertEqual(len(list(tree.iter_leafs())), 3)
self.assertEqual(len(list(tree.iter_descendant_leafs())), 7)
self.assertEqual(len(list(tree.iter_descendant_branches())), 3)
branches = list(tree.iter_branches())
self.assertEqual(len(list(branches[0].iter_children())), 2)
self.assertEqual(len(list(branches[0].iter_branches())), 2)
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
particles[0].child1 = particles[2]
particles[0].child2 = particles[1]
particles[1].child1 = particles[4]
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()))
while stack:
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)
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 = ''
for level, node in binary.iter_levels():
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
""")
| 10,550
| 34.40604
| 115
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_constants.py
|
from amuse.test import amusetest
from amuse.units import units
from amuse.units.constants import *
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)
def test2(self):
self.assertAlmostEqual(h, 6.6e-34 | units.J*units.s, 35)
self.assertAlmostEqual(c, 299792458.0 | units.m/units.s, 7)
def test3(self):
self.assertAlmostRelativeEquals(
Planck_length**2,
hbar * G / c**3, 5)
self.assertAlmostRelativeEquals(
Planck_mass**2,
hbar * c / G, 5)
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,
fine_hyphen_structure_constant**2 * electron_mass * c, 7)
self.assertAlmostRelativeEquals(fine_hyphen_structure_constant,
elementary_charge**2 / (2 * h * c * electric_constant), 7)
| 1,182
| 34.848485
| 88
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_literature.py
|
import unittest
import docutils.core
from amuse.support import literature
class TestLiteratureRefs(unittest.TestCase):
def setUp(self):
literature.LiteratureReferencesMixIn.literature_list = []
def test1(self):
class ClassLitrefs(literature.LiteratureReferencesMixIn):
""" some comments with added lit refs, i.e. [#]_ and [3]_ etc...
.. [#] Gratia, Exempli, *Journal of I.M.*, **1**, 1--100 (2009).
.. [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)
classnames = literature.LiteratureReferencesMixIn.names_of_classes_with_references()
for classname in classnames:
self.assertFalse("ClassLitrefs" in classname)
instance = ClassLitrefs()
classnames = literature.LiteratureReferencesMixIn.names_of_classes_with_references()
for classname in classnames:
self.assertTrue("ClassLitrefs" in classname)
def test2(self):
class ClassLitrefs(literature.LiteratureReferencesMixIn):
""" some comments with added lit refs, i.e. [#]_ and [3]_ etc...
.. [#] Gratia, Exempli, *Journal of I.M.*, **1**, 1--100 (2009).
.. [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)
self.assertFalse(".. [3] Dude" in string)
self.assertFalse(".. [4] Hat" in string)
self.assertTrue("Gratia, Exem" in string)
self.assertTrue("Dude" in string)
self.assertTrue("Hat" in string)
self.assertTrue("ClassLitrefs" in string)
| 2,545
| 39.412698
| 97
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_pickle.py
|
from amuse.test import amusetest
import pickle
from amuse.support.exceptions import AmuseException
from amuse.units import core
from amuse.units import si
from amuse.units import nbody_system
from amuse.units import generic_unit_system
from amuse.units.quantities import zero
from amuse.units.units import *
from amuse.units.constants import *
from amuse.datamodel import Particles, parameters
import subprocess
import pickle
import sys
import os
class TestPicklingOfUnitsAndQuantities(amusetest.TestCase):
def test1(self):
km = 1000 * m
self.assertEqual(1000, km.value_in(m))
pickled_km = pickle.dumps(km)
unpickled_km = pickle.loads(pickled_km)
self.assertEqual(1000, unpickled_km.value_in(m))
def test2(self):
km = 1000 * m
quantity = 12.0 | km
self.assertEqual(12000, quantity.value_in(m))
pickled_quantity = pickle.dumps(quantity)
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
pickled_quantity = pickle.dumps(quantity)
unpickled_quantity = pickle.loads(pickled_quantity)
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
pickled_quantity = pickle.dumps(quantity)
unpickled_quantity = pickle.loads(pickled_quantity)
self.assertEqual(quantity, unpickled_quantity)
self.assertEqual(str(quantity), str(unpickled_quantity))
def test7(self):
quantity = zero
pickled_quantity = pickle.dumps(quantity)
unpickled_quantity = pickle.loads(pickled_quantity)
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)
unpickled_quantity = pickle.loads(pickled_quantity)
self.assertEqual(quantity, unpickled_quantity)
self.assertEqual(str(quantity), str(unpickled_quantity))
def test9(self):
quantity = 1.3 | nbody_system.time
path = os.path.abspath(os.path.join(self.get_path_to_results(), "test9.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
)
unpickled_quantity_string, error_string = process.communicate()
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:
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
)
unpickled_quantity_string, error_string = process.communicate()
self.assertEqual(process.returncode, 0)
self.assertEqual(str(quantity), unpickled_quantity_string.strip().decode('utf-8'))
def test11(self):
value = 1 | stellar_type
self.assertEqual(1 | stellar_type, value)
pickled = pickle.dumps(value)
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
pickled_particles = pickle.dumps(particles)
unpickled_particles = pickle.loads(pickled_particles)
self.assertAlmostRelativeEquals(unpickled_particles.mass, [1, 2, 3, 4] | km)
def test2(self):
particles = Particles(4)
particles.mass = [1, 2, 3, 6] | kg
particles.position = [[0, 0, 0], [3, 0, 0], [0, 4, 0], [3, 4, 0]] | m
self.assertEqual(particles.center_of_mass(), [2, 3, 0] | m)
pickled_particles = pickle.dumps(particles)
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)
particles.mass = [1, 2, 3, 6] | kg
particles.position = [[0, 0, 0], [3, 0, 0], [0, 4, 0], [3, 4, 0]] | m
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!
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 test4(self):
particles = Particles(4)
particles.mass = [1, 2, 3, 6] | kg
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)
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",
"set_test",
"test_name",
"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)
memento = set.copy()
self.assertEqual(memento.test_name, 10 | m)
pickled_memento = pickle.dumps(memento)
unpickled_memento = pickle.loads(pickled_memento)
self.assertEqual(memento.test_name, unpickled_memento.test_name)
| 8,040
| 35.885321
| 118
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_store.py
|
from amuse.test import amusetest
import os
import numpy
import time
from amuse import io
from amuse.io import store
from amuse.io import store_v1
from amuse.io import store_v2
from amuse.units import units
from amuse.units import nbody_system
from amuse.datamodel import Particles
from amuse.datamodel import ParticlesOverlay
from amuse.datamodel import Grid
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
def test1(self):
test_results_path = self.get_path_to_results()
output_file = os.path.join(test_results_path, "test1."+self.store_version()+".hdf5")
if os.path.exists(output_file):
os.remove(output_file)
instance = self.store_factory()(output_file)
number_of_particles = 10
p = Particles(number_of_particles)
p.mass = [x * 2.0 for x in range(number_of_particles)] | units.kg
p.model_time = 2.0 | units.s
instance.store(p)
loaded_particles = instance.load()
loaded_mass_in_kg = loaded_particles.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 test2(self):
test_results_path = self.get_path_to_results()
output_file = os.path.join(test_results_path, "test2."+self.store_version()+".hdf5")
if os.path.exists(output_file):
os.remove(output_file)
instance = self.store_factory()(output_file)
number_of_particles = 10
p = Particles(number_of_particles)
p.mass = [x * 2.0 for x in range(number_of_particles)] | units.kg
instance.store(p.savepoint(1 | units.Myr))
p.mass = [x * 4.0 for x in range(number_of_particles)] | units.kg
instance.store(p.savepoint(2 | units.Myr))
instance.close()
instance = self.store_factory()(output_file)
loaded_particles = instance.load()
self.assertAlmostRelativeEquals(self.get_version_in_store(loaded_particles).get_timestamp(), 2 | units.Myr)
self.assertAlmostRelativeEquals(self.get_version_in_store(loaded_particles).previous_state().get_timestamp(), 1 | units.Myr)
masses = loaded_particles[1].get_timeline_of_attribute("mass")
self.assertEqual(len(masses), 2)
instance.close()
def test3(self):
test_results_path = self.get_path_to_results()
output_file = os.path.join(test_results_path, "test3"+self.store_version()+".hdf5")
if os.path.exists(output_file):
os.remove(output_file)
instance = self.store_factory()(output_file)
number_of_particles = 10
p = Particles(number_of_particles)
p.mass = [x * 2.0 for x in range(number_of_particles)] | nbody_system.mass
instance.store(p.savepoint(1 | nbody_system.time))
instance.close()
instance = self.store_factory()(output_file)
loaded_particles = instance.load()
self.assertAlmostRelativeEquals(p.mass[1], 2.0 | nbody_system.mass)
instance.close()
def test4(self):
test_results_path = self.get_path_to_results()
output_file = os.path.join(test_results_path, "test4"+self.store_version()+".hdf5")
if os.path.exists(output_file):
os.remove(output_file)
particles = Particles(10)
particles.mass = 1.0 | units.kg
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())
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)
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)
p.model_time = 2.0 | units.s
instance.store_grid(p)
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))
loaded_grid = self.get_version_in_store(instance.load_grid())
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)
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")
if os.path.exists(output_file):
os.remove(output_file)
instance = self.store_factory()(output_file)
number_of_particles = 10
p = Particles(number_of_particles)
p.mass = [x * 2.0 for x in range(number_of_particles)] | units.kg
p.model_time = 2.0 | units.s
instance.store(p)
instance.close()
instance = self.store_factory()(output_file)
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)
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")
if os.path.exists(output_file):
os.remove(output_file)
instance = self.store_factory()(output_file)
number_of_particles = 10
p = Particles(number_of_particles)
p.mass = numpy.asarray([x * 2.0 for x in range(number_of_particles)])
instance.store(p.savepoint(1 | nbody_system.time))
instance.close()
instance = self.store_factory()(output_file)
loaded_particles = instance.load()
self.assertAlmostRelativeEquals(p.mass[1], 2.0)
instance.close()
def test9(self):
test_results_path = self.get_path_to_results()
output_file = os.path.join(test_results_path, "test9"+self.store_version()+".hdf5")
if os.path.exists(output_file):
os.remove(output_file)
number_of_particles = 10
p = Particles(number_of_particles)
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,
output_file,
"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,
"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 test10(self):
test_results_path = self.get_path_to_results()
output_file = os.path.join(test_results_path, "test10"+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, 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)
self.assertAlmostRelativeEquals(a.scale, 1 | units.kg)
def test11(self):
test_results_path = self.get_path_to_results()
output_file = os.path.join(test_results_path, "test11"+self.store_version()+".hdf5")
if os.path.exists(output_file):
os.remove(output_file)
number_of_particles = 10
p = Particles(number_of_particles)
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())
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())
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")
if os.path.exists(output_file):
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)
def test14(self):
test_results_path = self.get_path_to_results()
output_file = os.path.join(test_results_path, "test14"+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", 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]]]
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]])
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]])
def test16(self):
import h5py
test_results_path = self.get_path_to_results()
output_file = os.path.join(test_results_path, "test16"+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].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)
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)
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
binaries = Particles(2)
binaries[0].y = 1.0 | units.km
binaries[1].y = 2.0 | units.km
binaries[0].child1 = stars[0]
binaries[0].child2 = stars[1]
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)
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
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, 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")
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
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])
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())
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]])
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
overlay = ParticlesOverlay(stars)
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())
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")
if os.path.exists(output_file):
os.remove(output_file)
particles = Particles()
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())
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")
if os.path.exists(output_file):
os.remove(output_file)
particles = Particles(20)
# ~ 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())
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")
if os.path.exists(output_file):
os.remove(output_file)
particles = Particles(20)
# ~ 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)
history = list(particles_from_file.history)
self.assertEqual(len(history), 10)
self.assertFalse("HDF" in str(type(history[1]._private.attribute_storage)))
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())
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")
if os.path.exists(output_file):
os.remove(output_file)
p = Grid(20)
io.write_set_to_file(p, output_file, format='amuse', version=self.store_version())
os.remove(output_file)
def test27(self):
test_results_path = self.get_path_to_results()
output_file = os.path.join(test_results_path, "test27"+self.store_version()+".hdf5")
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)
p.model_time = 2.0 | units.s
instance.store_grid(p)
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
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, 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()
output_file = os.path.join(test_results_path, "test29"+self.store_version()+".hdf5")
if os.path.exists(output_file):
os.remove(output_file)
particles = Grid(10)
particles.attribute1 = "normal"
particles.attribute2 = "unicode"
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")
if os.path.exists(output_file):
os.remove(output_file)
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
self.assertEqual(output.new_attribute, 2 * output.mass)
output = next(output.iter_history())
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)
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")
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
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)
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")
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
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)
self.assertEqual(loaded_stars[1].gas, None)
def test54(self):
test_results_path = self.get_path_to_results()
output_file = os.path.join(test_results_path, "test23"+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
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)
def test54b(self):
test_results_path = self.get_path_to_results()
output_file = os.path.join(test_results_path, "test24"+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
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())
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")
if os.path.exists(output_file):
os.remove(output_file)
particles1 = Particles(2)
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
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)
def test56(self):
test_results_path = self.get_path_to_results()
output_file = os.path.join(test_results_path, "test26"+self.store_version()+".hdf5")
if os.path.exists(output_file):
os.remove(output_file)
number_of_particles = 10
p = Particles(number_of_particles)
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
io.write_set_to_file(
p,
output_file,
"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,
"hdf5",
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)
self.assertEquals(id(attributes.particles), id(loaded_particles))
self.assertAlmostRelativeEquals(attributes.gridpoint.y, 1.0 | units.km)
self.assertAlmostRelativeEquals(attributes.grid[0][0].y, 1.0 | units.km)
def test57(self):
test_results_path = self.get_path_to_results()
output_file = os.path.join(test_results_path, "test26"+self.store_version()+".hdf5")
if os.path.exists(output_file):
os.remove(output_file)
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")
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)
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.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")
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(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)
os.remove(output_file)
def test59(self):
test_results_path = self.get_path_to_results()
output_file = os.path.join(test_results_path, "test59"+self.store_version()+".h5")
if os.path.exists(output_file):
os.remove(output_file)
g = Grid(10, 10)
p = Particles(2)
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")
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")
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")
self.assertEqual(x[0].y[0].id, 5)
self.assertEqual(z[0].y[0].id, 5)
os.remove(output_file)
| 40,936
| 38.062023
| 146
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_interface.py
|
from amuse.support import interface
from amuse.support.exceptions import AmuseException
from amuse.datamodel.binding import *
from amuse.datamodel.parameters import *
from amuse.support.core import OrderedDictionary
from amuse.support import exceptions
from amuse.test import amusetest
import numpy
import pickle
from amuse.units import units
from amuse.units import nbody_system
from amuse import datamodel
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)
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)
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)
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')
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),
expected_message="Error when calling 'return_an_errorcode' of a '<class 'amuse.support.interface.InCodeComponentImplementation'>', errorcode is -1"
)
class CodeInterfaceWithUnitsOnLegacyFunctionTests(amusetest.TestCase):
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):
class TestImplementation(object):
def echo_one(self, input):
return input, 0
class TestInterface(object):
@legacy_function
def echo_one():
function = LegacyFunctionSpecification()
function.addParameter('input', dtype='d', direction=function.IN, unit=units.kg)
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):
class TestImplementation(object):
def return_error(self):
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 '<class 'amuse.support.interface.InCodeComponentImplementation'>', errorcode is -1")
def test4(self):
class TestImplementation(object):
def echo_one(self, input):
return input, 0
class TestInterface(object):
@legacy_function
def echo_one():
function = LegacyFunctionSpecification()
function.addParameter('input', dtype='d', direction=function.IN, unit=units.deg)
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!!
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))
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')
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))
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')
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 '<class 'amuse.support.interface.InCodeComponentImplementation'>', 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.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.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.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.get_name_of_current_state(), 'THREE')
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 <class 'amuse.support.interface.InCodeComponentImplementation'>: 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')
instance.move_to_state_2()
self.assertEqual(instance.get_name_of_current_state(), 'TWO')
instance.move_to_state_1()
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)
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()
self.assertEqual(instance.get_name_of_current_state(), 'ONE')
instance.state_machine.disable()
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)
handler = instance.get_handler('STATE')
handler.add_transition('ZERO', 'ONE', 'move_to_state_1')
handler.add_transition('ONE', 'THREE', 'move_to_state_3')
handler.add_transition('THREE', 'FOUR', 'move_to_state_4')
handler.add_transition('!ZERO!ONE!THREE', '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)
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)
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')
handler.add_transition('TWO', 'THREE', 'move_to_state_3')
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)
self.assertEqual(instance.number_of_times_move_to_state_3_called, 0)
self.assertEqual(instance.number_of_times_move_to_state_4_called, 0)
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.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.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.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
# 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.assertRaises(Exception, instance.returns_2, expected_message="While calling returns_2 of <class 'amuse.support.interface.InCodeComponentImplementation'>: 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 = 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 = 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)
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 '<class 'amuse.support.interface.InCodeComponentImplementation'>', 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 '<class 'amuse.support.interface.InCodeComponentImplementation'>', 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)
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 = []
for x in id:
masses.append(self.masses[x])
errors.append(0)
result = OrderedDictionary()
result["mass"] = masses
result["__result"] = errors
return result
def set_mass(self, id, mass):
for i, m in zip(id, mass):
self.masses[i] = m
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
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)
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
return [0]
for i in id:
self.masses[i] += 1.0
return [0 for x in id]
def get_heaviest_particle(self):
max = -1
id = -1
for index, mass in self.masses.items():
if mass > max:
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])
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
if abs(m - mass) < 1.0:
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):
mass = self.masses[index]
count = 0
for otherindex, m in self.masses.items():
if otherindex == index:
continue
if abs(m - mass) < 1.0:
count += 1
if count == (index_in_list + 1):
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 = 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',))
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 = 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')
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 = 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',))
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 = 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_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 = 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 = 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 = 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 = 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 = 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 = 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))
pickled_handler = pickle.dumps(handler)
unpickled_handler = pickle.loads(pickled_handler)
method1 = handler.get_attribute('get_mass', original.get_mass)
method2 = unpickled_handler.get_attribute('get_mass', unpickled_handler.interface.legacy_interface.get_mass)
self.assertTrue(method1 is not None)
self.assertTrue(method2 is not None)
self.assertAlmostRelativeEquals(method1([1])[0], 10 | units.kg)
self.assertAlmostRelativeEquals(method2([1])[0], 10 | units.kg)
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 = 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',))
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)
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)
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 set_a(self, i_s, j_s, k_s, values):
index = 0
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 = instance.get_handler('PARTICLES')
handler.define_grid('grid',)
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))
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 = instance.get_handler('PARTICLES')
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)
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 = instance.get_handler('PARTICLES')
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 = 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',))
grid = instance.grid
self.assertEqual(grid.__class__.__name__, "CartesianGrid")
class TestGridWithBinding2(amusetest.TestCase):
class TestInterface(object):
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)
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 set_a(self, i_s, j_s, values):
index = 0
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 = instance.get_handler('PARTICLES')
handler.define_grid('grid',)
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(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)
class TestGridWithBinding3(amusetest.TestCase):
class TestInterface(object):
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)
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)]),]
def set_a(self, 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 = 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',))
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)
self.assertEqual(grid[1].mass, original.storage[1] | units.kg)
class TestGridWithBinding4(amusetest.TestCase):
class TestInterface(object):
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)]),]
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
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 = 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',))
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(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)
self.assertEqual(grid[1].mass, original.storage[1] | units.kg)
class TestGridWithBinding5(amusetest.TestCase):
class TestInterface(object):
shape = (3, 4, 5, 6)
def __init__(self):
self.storage = numpy.arange(
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 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 = 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',))
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(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)
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)
def __init__(self):
self.storage = numpy.arange(
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 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 = 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',))
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(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.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 = instance.get_handler('PARTICLES')
handler.define_grid('grid',)
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 = instance.get_handler('PARTICLES')
handler.define_grid('grid',)
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)
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 = 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'))
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 = 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'))
grid = instance.grid
grid1 = grid.copy()
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(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()
function.addParameter('input1', dtype='d', direction=function.OUT)
function.addParameter('input2', dtype='d', direction=function.OUT)
function.addParameter('output1', dtype='d', direction=function.IN)
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', "
"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', "
"the number of outputs do not match, expected 3, actual 4.")
def test2(self):
class TestClass(object):
@legacy_function
def echo_inputs():
function = LegacyFunctionSpecification()
function.addParameter('input1', dtype='d', direction=function.OUT)
function.addParameter('input2', dtype='d', direction=function.OUT)
function.addParameter('output1', dtype='d', direction=function.IN)
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', "
"the number of inputs do not match, expected 2, actual 1.")
def test3(self):
class TestClass(object):
async_request = None
@legacy_function
def echo_inputs():
function = LegacyFunctionSpecification()
function.addParameter('input1', dtype='d', direction=function.OUT)
function.addParameter('input2', dtype='d', direction=function.OUT)
function.addParameter('output1', dtype='d', direction=function.IN)
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''")
| 69,011
| 38.211364
| 238
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_imf.py
|
import numpy.random
from amuse.test import amusetest
from amuse.units import units
from amuse.ic.brokenimf import new_kroupa_mass_distribution
class TestMassFunctions(amusetest.TestCase):
def test_kroupa_default_masslimits(self):
"""
Test the default mass limits of a Kroupa mass distribution
"""
numpy.random.seed(124)
mass_min = 0.01 | units.MSun
mass_max = 125 | units.MSun
mass = new_kroupa_mass_distribution(10000)
self.assertTrue(mass.max() <= mass_max)
self.assertTrue(mass.min() >= mass_min)
def test_kroupa_lower_masslimit(self):
"""
Test the lower mass limits of a Kroupa mass distribution
"""
numpy.random.seed(124)
mass_min = 1.0 | units.MSun
mass = new_kroupa_mass_distribution(
10000, mass_min=mass_min)
self.assertTrue(mass.min() >= mass_min)
def test_kroupa_upper_masslimit(self):
"""
Test the upper mass limits of a Kroupa mass distribution
"""
numpy.random.seed(124)
mass_max = 1.0 | units.MSun
mass = new_kroupa_mass_distribution(
10000, mass_max=mass_max)
self.assertTrue(mass.max() <= mass_max)
def test_kroupa_masslimits(self):
"""
Test both mass limits of a Kroupa mass distribution
"""
numpy.random.seed(124)
mass_max = 1.0 | units.MSun
mass_min = 1.0 | units.MSun
mass = new_kroupa_mass_distribution(
10000, mass_min=mass_min, mass_max=mass_max)
self.assertEqual(mass.max(), mass.min())
| 1,622
| 29.055556
| 66
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_phigrape.py
|
from amuse.test import amusetest
import os.path
import numpy
from amuse.io import phigrape
from amuse.units import units
from amuse.units import constants
from amuse.units import nbody_system
from amuse.units import quantities
from amuse import datamodel
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)
control_instance = phigrape.Inp2Particles()
control_instance.convert_to_particles(os.path.join(directory, output))
self.assertAlmostEqual(control_instance.Particles.mass, instance.Particles.mass, 16)
self.assertAlmostEqual(control_instance.Particles[1].position, instance.Particles[1].position, 16)
self.assertAlmostEqual(control_instance.Particles[1].velocity, instance.Particles[1].velocity, 16)
| 1,116
| 38.892857
| 106
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_optparse.py
|
from amuse.test import amusetest
import numpy
import sys
from amuse.support.exceptions import AmuseException
from amuse.units.quantities import *
from amuse.units import si
from amuse.units import units
from amuse.units import nbody_system
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)
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)
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)
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)
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)
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)
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)
helpstr = x.format_help()
print(helpstr)
self.assertTrue('unit: MSun)' in helpstr)
self.assertTrue('(default: 1' in helpstr)
| 2,383
| 33.550725
| 124
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_console.py
|
from amuse.test import amusetest
from amuse.support.exceptions import AmuseException
from amuse.units import units
from amuse.units import nbody_system
from amuse.units import constants
from amuse.support import console
from amuse.support.console import set_printing_strategy
from amuse.support.console import get_current_printing_strategy
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)
set_printing_strategy("no_unit")
self.assertEqual(get_current_printing_strategy(), console.NoUnitsPrintingStrategy)
set_printing_strategy("default")
self.assertEqual(get_current_printing_strategy(), console.DefaultPrintingStrategy)
set_printing_strategy("no_units")
self.assertEqual(get_current_printing_strategy(), console.NoUnitsPrintingStrategy)
set_printing_strategy("with_units")
self.assertEqual(get_current_printing_strategy(), console.DefaultPrintingStrategy)
set_printing_strategy("formal")
self.assertEqual(get_current_printing_strategy(), console.FormalPrintingStrategy)
set_printing_strategy("nbody")
self.assertEqual(get_current_printing_strategy(), console.NBodyPrintingStrategy)
set_printing_strategy(console.NoUnitsPrintingStrategy)
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
position = [1, 2.0, 3] | units.m
mass_in_g = mass.as_quantity_in(units.g)
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")
self.assertEqual(str(acc), "9.8")
self.assertEqual(str(position), "[1.0, 2.0, 3.0]")
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
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
position = [1, 2.0, 3] | nbody_system.length
mass_in_g = mass.as_quantity_in(units.g) * 1.0
pi = 3.14 | units.none
set_printing_strategy("formal")
self.assertEqual(str(mass), "<quantity 1.0 | kg>")
self.assertEqual(str(acc), "<quantity 9.8 | m / (s**2)>")
self.assertEqual(str(position), "<quantity [1.0, 2.0, 3.0] | length>")
self.assertEqual(str(mass_in_g), "<quantity 1000.0 | 0.001 * kg>") # <quantity 1000.0 | g>")
self.assertEqual(str(pi), "<quantity 3.14 | none>")
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
position = [1, 2, 3] | units.m
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.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)
self.assertEqual(str(mass), "1.0")
self.assertEqual(str(acc * constants.G.number), "9.8")
if sys.hexversion > 0x03000000:
self.assertEqual(str(position), "[1.0, 2.0, 3.0]")
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)
position = [0.1, 0.2, 0.3] | nbody_system.length
energy = 1e8 | units.erg
temperature = 5000 | units.K
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)
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.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)
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)
position = [0.1, 0.2, 0.3] | nbody_system.length
energy = 1e8 | units.erg
temperature = 5000 | units.K
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)
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("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
position = [0.1, 0.2, 0.3] | nbody_system.length
energy = 1e8 | units.erg
temperature = 5000 | units.milli(units.K)
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)
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")
self.assertEqual(str(energy), "10.0 kg * m**2 * s**-2")
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)
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]")
self.assertEqual(str(energy), "10.0")
self.assertEqual(str(constants.G), "6.67428e-11")
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)
position = [0.1, 0.2, 0.3] | nbody_system.length
power = 10 | units.W
temperature = 5000 | units.K
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=" <)")
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 <)")
self.assertEqual(str(power), "(> 6.00e+09 <|> erg / min <)")
self.assertEqual(str(constants.G), "(> 1.19e-67 <|> AU**3 * amu**-1 * min**-2 <)")
self.assertEqual(str(constants.kB), "(> 1.38e-19 <|> erg * mK**-1 <)")
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
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)
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 +
"], ["+tmp+", "+tmp+"]] AU")
self.assertEqual(str(pi), "3.14 none")
set_printing_strategy("default")
| 11,944
| 47.755102
| 165
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_links.py
|
from amuse.test import amusetest
from amuse.support.exceptions import AmuseException
from amuse import datamodel
from amuse.units import units
from amuse.units import nbody_system
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
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
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)
particles = datamodel.ParticlesWithUnitsConverted(
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
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
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
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
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)
def test6(self):
binaries = datamodel.Particles(2)
binaries.mass = [4, 6] | units.kg
stars = datamodel.Particles(4)
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)
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
stars = datamodel.Particles(4)
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]
stars[0].binary = binaries[0]
stars[1].binary = binaries[0]
stars[2].binary = binaries[1]
stars[3].binary = binaries[1]
other = binaries.copy()
stars.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)
self.assertAlmostRelativeEqual(other[1].child1.mass, 2 | units.kg)
self.assertAlmostRelativeEqual(other[1].child2.mass, 4 | units.kg)
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
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[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
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[1].particles2 = particles2
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[1].particles2 = particles2
self.assertEqual(len(particles1.particles2), 4)
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[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[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_copy = particles1.copy()
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[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.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.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[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])
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])
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[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)
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[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)
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_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)
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[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)
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[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)
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)
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_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)
channel = particles.new_channel_to(particles_copy)
channel.copy()
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
particles = datamodel.Particles(3)
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
particles = datamodel.Particles(3)
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
particles = datamodel.Particles(3)
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
particles = datamodel.Particles(3)
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
particles = datamodel.Particles(3)
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
particles = datamodel.Particles(3)
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[0][0].neighbour = grid[0][1]
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[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.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_copy[0][1].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_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.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_copy[0][1].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[0][0].container = grid
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[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.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_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)
def test3(self):
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.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_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)
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
self.assertEqual(id(grid[0][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.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)
| 23,975
| 34.00146
| 103
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_bridge.py
|
import numpy
from amuse.units import units, constants, nbody_system
from amuse.units.quantities import zero, AdaptingVectorQuantity, VectorQuantity
from amuse.support.exceptions import AmuseException
from amuse.datamodel import Particles
from amuse.datamodel import parameters
from amuse.ic.plummer import new_plummer_model
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.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)
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])
self.assertAlmostEqual(fx, [0.0] | nbody_system.acceleration, 6)
self.assertAlmostEqual(fy, [0.0] | nbody_system.acceleration, 6)
self.assertAlmostEqual(fz, [0.0] | nbody_system.acceleration, 6)
for x in (0.25, 0.5, 0.75):
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.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)
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.particles.add_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),
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),
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.particles.add_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),
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),
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),
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),
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)
class ExampleGravityCodeInterface(object):
def __init__(self, softening_mode="shared"):
self.particles = Particles()
if softening_mode == "individual":
self.softening_mode = "individual"
self._softening_lengths_squared = self._softening_lengths_squared_individual
self._softening_lengths = self._softening_lengths_individual
else:
self.softening_mode = "shared"
self._softening_lengths_squared = self._softening_lengths_squared_shared
self._softening_lengths = self._softening_lengths_shared
epsilon_squared_parameter = parameters.ModuleMethodParameterDefinition(
"get_epsilon_squared",
"set_epsilon_squared",
"epsilon_squared",
"gravitational softening length squared",
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):
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 +
(self.particles.y - y)**2 + (self.particles.z - z)**2).sqrt()).sum()
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**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 /
(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":
if len(self.particles) < 2:
return zero * constants.G
eps_vector = self.particles.radius**2
sum_of_energies = zero
for i in range(len(self.particles) - 1):
dx = self.particles[i].x - self.particles[i+1:].x
dy = self.particles[i].y - self.particles[i+1:].y
dz = self.particles[i].z - self.particles[i+1:].z
dr = ((dx * dx) + (dy * dy) + (dz * dz) + eps_vector[i] + eps_vector[i+1:]).sqrt()
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(),
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.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
self.particles.position += self.particles.velocity * dt + 0.5 * self.particles.acceleration * dt**2
old_acceleration = self.particles.acceleration
self.set_accelerations()
self.particles.velocity += 0.5 * (old_acceleration + self.particles.acceleration) * dt
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.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
numpy.random.seed(12345)
stars = new_plummer_model(100, convert_nbody=convert)
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'])
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,))
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
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.particles.add_particles(stars)
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.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
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.particles.add_particles(stars)
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,), 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
numpy.random.seed(12345)
stars = new_plummer_model(100, convert_nbody=convert)
cluster = test_class()
cluster.initialize_code()
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'])
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,))
self.assertAlmostRelativeEqual(
cluster1.particles.get_intersecting_subset_in(cluster.particles).position,
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()
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)
| 18,356
| 46.069231
| 132
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_incode_particle_sets.py
|
from amuse.test import amusetest
from amuse.units import units
from amuse.units import quantities
from amuse.support import interface
from amuse.support import exceptions
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_setter('particles', 'set_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')
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):
"""Returns an array of the positions for the indices in index_of_the_particle
"""
if not hasattr(index_in_the_list, '__iter__'):
index_in_the_list = [index_in_the_list,]
if not hasattr(index_of_the_particle, '__iter__'):
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]
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):
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})
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
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
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)
self.assertEqual(list[0].value2, 0 | units.none)
self.assertEqual(list[1].value1, 0 | units.none)
self.assertEqual(list[1].value2, 1 | units.none)
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
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)
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)
def log(self, message, *arguments):
print("IN TEST >>", message.format(*arguments))
| 15,803
| 37.359223
| 153
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_particles_properties.py
|
import numpy
import time
import sys
import pickle
from amuse.test import amusetest
from amuse.units import units
from amuse.units import constants
from amuse.units import nbody_system
from amuse.support.exceptions import AmuseException
from amuse.support.interface import InCodeComponentImplementation
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
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
pickled_string = pickle.dumps(particles1)
particles2 = pickle.loads(pickled_string)
self.assertEqual(particles2.collection_attributes.timestamp, 1 | units.yr)
self.assertEqual(particles2.collection_attributes.a, 2)
| 2,056
| 32.721311
| 88
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_plot.py
|
import numpy
from amuse.test import amusetest
from amuse.units import units, quantities
from amuse.support.console import set_printing_strategy
import amuse.plot as aplot
try:
from matplotlib import pyplot
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
class TestPlot(amusetest.TestCase):
def test1(self):
""" Test a basic plot with units and labels"""
if not HAS_MATPLOTLIB:
return self.skip()
pyplot.clf()
x = numpy.linspace(0, 100, 100) | units.yr
y = numpy.linspace(0, 200, 100) | units.RSun
aplot.plot(x, y)
self.assertEqual("[yr]", self.xaxis().get_label_text())
self.assertEqual("[RSun]", self.yaxis().get_label_text())
aplot.xlabel("time")
aplot.ylabel("radius")
self.assertEqual("time [yr]", self.xaxis().get_label_text())
self.assertEqual("radius [RSun]", self.yaxis().get_label_text())
def test2(self):
""" Test a basic plot with and without units and labels"""
if not HAS_MATPLOTLIB:
return self.skip()
pyplot.clf()
x = numpy.linspace(0, 100, 100) | units.yr
y = numpy.linspace(0, 200, 100)
aplot.plot(x, y)
self.assertEqual("[yr]", self.xaxis().get_label_text())
self.assertEqual("", self.yaxis().get_label_text())
aplot.xlabel("time")
aplot.ylabel("radius")
self.assertEqual("time [yr]", self.xaxis().get_label_text())
self.assertEqual("radius ", self.yaxis().get_label_text())
def test3(self):
""" Test a plot with preferred units """
if not HAS_MATPLOTLIB:
return self.skip()
pyplot.clf()
x = numpy.linspace(0, 100, 100) | units.yr
y = numpy.linspace(0, 200, 100) | units.RSun
set_printing_strategy('custom', preferred_units=[units.Myr, units.AU])
aplot.plot(x, y)
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.0001, pyplot.xlim()[1], 1)
def test4(self):
""" Test text in a plot """
if not HAS_MATPLOTLIB:
return self.skip()
pyplot.clf()
set_printing_strategy('default')
x = numpy.linspace(0, 100, 100) | units.yr
y = numpy.linspace(0, 200, 100) | units.RSun
aplot.plot(x, y)
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])
def test5(self):
""" Test errorbar plot """
if not HAS_MATPLOTLIB:
return self.skip()
pyplot.clf()
set_printing_strategy('default')
x = numpy.linspace(0, 100, 100) | units.yr
y = numpy.linspace(0, 200, 100) | units.RSun
yerr = [2e5]*len(y) | units.km
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]
self.assertAlmostEqual(0.575125808, error_height)
def test6(self):
""" Test setting the x limits on a plot """
if not HAS_MATPLOTLIB:
return self.skip()
pyplot.clf()
set_printing_strategy('default')
x = numpy.linspace(0, 100, 100) | units.yr
y = numpy.linspace(0, 200, 100) | units.RSun
line = aplot.plot(x, y)
aplot.xlim(0 | units.yr, 2e9 | units.s)
self.assertAlmostEqual(0, pyplot.xlim()[0])
self.assertAlmostEqual(63.37752924, pyplot.xlim()[1])
def test7(self):
""" Test setting the x and y limits in various ways"""
if not HAS_MATPLOTLIB:
return self.skip()
pyplot.clf()
set_printing_strategy('default')
x = numpy.linspace(0, 100, 100)
y = numpy.linspace(0, 200, 100) | units.RSun
line = aplot.plot(x, y)
aplot.xlim(-10, 80)
self.assertEqual(-10, pyplot.xlim()[0])
self.assertEqual(80, pyplot.xlim()[1])
print(pyplot.xlim())
aplot.xlim(xmax=90)
print(pyplot.xlim())
self.assertEqual(-10, pyplot.xlim()[0])
self.assertEqual(90, pyplot.xlim()[1])
aplot.ylim([-12, 110] | units.RSun)
self.assertEqual(-12, pyplot.ylim()[0])
self.assertEqual(110, pyplot.ylim()[1])
aplot.ylim(ymin=1e6 | units.km)
self.assertAlmostEqual(1.43781452, pyplot.ylim()[0])
self.assertEqual(110, pyplot.ylim()[1])
def test8(self):
""" Test the imshow color plot """
if not HAS_MATPLOTLIB:
return self.skip()
pyplot.clf()
x = numpy.linspace(0, 100, 100) | units.m
y = numpy.linspace(0, 200, 100) | units.m
X, Y = quantities.meshgrid(x, y)
Z = X**2 + Y**2
figure, bar = aplot.imshow_color_plot(X, Y, Z, add_colorbar=True)
self.assertEqual("[m]", self.xaxis().get_label_text())
self.assertEqual("[m]", self.yaxis().get_label_text())
# Removed 2021-04-14, no longer supported by matplotlib
# self.assertEqual("[m**2]", bar._label)
def test9(self):
""" Test the contour plot """
if not HAS_MATPLOTLIB:
return self.skip()
pyplot.clf()
x = numpy.linspace(0, 100, 100) | units.m
y = numpy.linspace(0, 200, 100) | units.m
X, Y = quantities.meshgrid(x, y)
Z = X**2 + Y**2
aplot.contour(X, Y, Z)
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)
self.assertEqual([50, 100], con.get_array())
con = aplot.contour(X, Y, Z, [0.0002, 0.0003] | units.km**2)
self.assertEqual([200, 300], con.get_array())
def xaxis(self):
return pyplot.gca().get_xaxis()
def yaxis(self):
return pyplot.gca().get_yaxis()
def skip(self, reason="Matplotlib not installed. Skipping test."):
amusetest.TestCase.skip(reason)
def tearDown(self):
set_printing_strategy('default')
| 6,361
| 29.7343
| 78
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_indexing.py
|
from amuse.test import amusetest
from amuse.support.interface import InCodeComponentImplementation
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, :, :]))
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)
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]))
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_[:]))]
self.assertEqual(indirect.shape, direct.shape)
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_[:]))]
self.assertEqual(indirect.shape, direct.shape)
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:]))]
self.assertEqual(indirect.shape, direct.shape)
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:]))]
self.assertEqual(indirect.shape, direct.shape)
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])]
self.assertEqual(indirect.shape, direct.shape)
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]))]
self.assertEqual(indirect.shape, direct.shape)
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)]
self.assertEqual(indirect, direct)
def test11(self):
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))
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, :]))
def xtest13(self):
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]))
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]))
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:, ..., ...]))
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])
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]))
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:]))
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)
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)
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))
def test21(self):
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))
# 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)),
]
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])
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])
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])
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))
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))
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)))
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)))
class TestSplitOverDimensions(amusetest.TestCase):
def test1(self):
dimension_values = [
[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(split_dimension_values[0], 3)
self.assertEqual(split_dimension_values[1], ['a', 'b', 'c'])
def test2(self):
dimension_values = [
[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)
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']
]
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)
self.assertEqual(split_dimension_values[0], [1, 3, 5])
def test5(self):
dimension_values = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
]
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)
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]
]
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)
self.assertEqual(split_dimension_values[0], [1])
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])
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])
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])
self.assertEqual(split_dimension_values[1], 0)
self.assertEqual(split_dimension_values[2], [0])
| 19,635
| 43.325056
| 124
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_parameters.py
|
import warnings
from amuse.test import amusetest
from amuse.support.exceptions import AmuseException, AmuseWarning
from amuse.units import nbody_system, generic_unit_system, generic_unit_converter
from amuse.units import units
from amuse.datamodel import parameters
from amuse.support.interface import HandleParameters
from amuse.support.interface import InCodeComponentImplementation
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",
"set_test",
"test_name",
"a test parameter",
0.1 | units.m)], o)
x = set.get_parameter("test_name")
value = x.get_value()
self.assertTrue(value.unit.has_same_base_as(units.m))
self.assertEqual(value.value_in(units.m), 123)
def test2(self):
definition = parameters.ModuleMethodParameterDefinition(
"get_test",
"set_test",
"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)
value = x.get_value()
self.assertEqual(value, 10 | units.m)
def test3(self):
definition = parameters.ModuleMethodParameterDefinition(
"get_test",
"set_test",
"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)
value = x.get_value()
self.assertEqual(value, 10)
def test4(self):
parameter_definition = parameters.ModuleMethodParameterDefinition(
"get_test",
"set_test",
"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
class TestModuleBinding(object):
parameter_definitions = [parameter_definition]
def __init__(self):
self.parameters = parameters.Parameters(self.parameter_definitions, self)
class TestInterface(TestModule, TestModuleBinding):
def __init__(self):
TestModuleBinding.__init__(self)
instance = TestInterface()
self.assertTrue('test_name' in list(instance.parameters.names()))
instance.parameters.test_name = 1 | units.km
self.assertEqual(1 | units.km, instance.parameters.test_name)
self.assertEqual(1000 | units.m, instance.x)
def test5(self):
parameter_definition = parameters.ModuleMethodParameterDefinition(
None,
"set_test",
"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
class TestModuleBinding(object):
parameter_definitions = [parameter_definition]
def __init__(self):
self.parameters = parameters.Parameters(self.parameter_definitions, self)
class TestInterface(TestModule, TestModuleBinding):
def __init__(self):
TestModuleBinding.__init__(self)
instance = TestInterface()
self.assertTrue('test_name' in list(instance.parameters.names()))
instance.parameters.test_name = 1 | units.km
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",
"set_test",
"test_name",
"a test parameter",
"bla"
)
class TestModule(BaseTestModule):
def get_test(self):
return self.x
def set_test(self, value):
self.x = value
class TestModuleBinding(object):
parameter_definitions = [parameter_definition]
def __init__(self):
self.parameters = parameters.Parameters(self.parameter_definitions, self)
class TestInterface(TestModule, TestModuleBinding):
def __init__(self):
TestModuleBinding.__init__(self)
instance = TestInterface()
instance.parameters.test_name = "bla"
self.assertEqual("bla", instance.x)
instance.parameters.test_name = "bla"
self.assertEqual("bla", instance.x)
def test8(self):
parameter_definition = parameters.ModuleMethodParameterDefinition(
"get_test",
"set_test",
"test_name",
"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)
p.set_defaults()
self.assertEqual(11.0 | units.m, instance.x)
def test9(self):
parameter_definition = parameters.ModuleMethodParameterDefinition(
"get_test",
"set_test",
"test_name",
"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)
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")
def test10(self):
parameter_definition = parameters.ModuleMethodParameterDefinition(
"get_test",
None,
"test_name",
"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")
def test11(self):
parameter_definition1 = parameters.ModuleMethodParameterDefinition(
"get_test",
"set_test",
"test_name",
"a test parameter",
11.0 | units.m
)
parameter_definition2 = parameters.ModuleMethodParameterDefinition(
"get_test1",
"set_test1",
"test_name2",
"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",
"set_test",
"test_name",
"a test parameter",
[0.1, 0.2, 0.3] | units.km,
True
)
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
self.z = z
class TestModuleBinding(object):
parameter_definitions = [parameter_definition]
def __init__(self):
self.parameters = parameters.Parameters(self.parameter_definitions, self)
class TestInterface(TestModule, TestModuleBinding):
def __init__(self):
TestModuleBinding.__init__(self)
instance = TestInterface()
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",
"a test parameter",
0.1 | units.m)], o)
x = set.get_parameter("test_name")
value = x.get_value()
self.assertTrue(value.unit.has_same_base_as(units.m))
self.assertEqual(value.value_in(units.m), 0.1)
def test2(self):
definition = parameters.InterfaceParameterDefinition(
"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)
value = x.get_value()
self.assertEqual(value, 10 | units.m)
def test4(self):
parameter_definition = parameters.InterfaceParameterDefinition(
"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
class TestModuleBinding(object):
parameter_definitions = [parameter_definition]
def __init__(self):
self.parameters = parameters.Parameters(self.parameter_definitions, self)
class TestInterface(TestModule, TestModuleBinding):
def __init__(self):
TestModuleBinding.__init__(self)
instance = TestInterface()
self.assertTrue('test_name' in list(instance.parameters.names()))
instance.parameters.test_name = 1 | units.km
self.assertEqual(1 | units.km, instance.parameters.test_name)
def test5(self):
parameter_definition = parameters.InterfaceParameterDefinition(
"test_name",
"a test parameter",
0.1 | units.m,
"before_"
)
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
pass
class TestModuleBinding(object):
parameter_definitions = [parameter_definition]
def __init__(self):
self.parameters = parameters.Parameters(self.parameter_definitions, self)
class TestInterface(TestModule, TestModuleBinding):
def __init__(self):
TestModuleBinding.__init__(self)
instance = TestInterface()
self.assertTrue('test_name' in list(instance.parameters.names()))
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)
class TestParameters(amusetest.TestCase):
def test1(self):
parameter_definition = parameters.ModuleMethodParameterDefinition(
"get_test",
"set_test",
"test_name",
"a test parameter",
11.0 | units.m
)
class TestModule(BaseTestModule):
x = 123 | units.m
def get_test(self):
return self.x
def set_test(self, value):
self.x = value
o = TestModule()
x = parameters.Parameters([parameter_definition], o)
value = x.test_name
self.assertTrue(value.unit.has_same_base_as(units.m))
self.assertEqual(value.value_in(units.m), 123)
def test2(self):
parameter_definition = parameters.ModuleMethodParameterDefinition(
"get_test",
"set_test",
"test_name",
"a test parameter",
11.0 | nbody_system.length
)
class TestModule(BaseTestModule):
x = 123 | nbody_system.length
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)
y = parameters.ParametersWithUnitsConverted(
x,
convert_nbody.as_converter_from_si_to_generic()
)
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",
None,
"test_name",
"a test parameter",
11.0 | nbody_system.length
)
class TestModule(BaseTestModule):
x = 123 | units.m
def get_test(self):
return self.x
def set_test(self, value):
self.x = value
o = TestModule()
x = parameters.new_parameters_instance_with_docs([parameter_definition], o)
self.assertTrue("test_name" in x.__doc__)
self.assertTrue("a test parameter" in x.__doc__)
self.assertTrue("default" in x.__doc__)
self.assertTrue("11.0 length" in x.__doc__)
convert_nbody = nbody_system.nbody_to_si(2.0 | units.m, 4.0 | units.kg)
y = parameters.new_parameters_with_units_converted_instance_with_docs(
x,
convert_nbody.as_converter_from_si_to_generic()
)
self.assertTrue("test_name" in y.__doc__)
self.assertTrue("a test parameter" in y.__doc__)
self.assertTrue("default" in y.__doc__)
self.assertTrue("22.0 m" in y.__doc__)
def test3b(self):
# Same test as test3, but testing on the class, not instance
# This makes sure the python 'help' functionality works on parameters
parameter_definition = parameters.ModuleMethodParameterDefinition(
"get_test",
None,
"test_name",
"a test parameter",
11.0 | nbody_system.length
)
class TestModule(BaseTestModule):
x = 123 | units.m
def get_test(self):
return self.x
def set_test(self, value):
self.x = value
o = TestModule()
x = parameters.new_parameters_instance_with_docs([parameter_definition], o)
self.assertTrue("test_name" in x.__class__.__doc__)
self.assertTrue("a test parameter" in x.__class__.__doc__)
self.assertTrue("default" in x.__class__.__doc__)
self.assertTrue("11.0 length" in x.__class__.__doc__)
convert_nbody = nbody_system.nbody_to_si(2.0 | units.m, 4.0 | units.kg)
y = parameters.new_parameters_with_units_converted_instance_with_docs(
x,
convert_nbody.as_converter_from_si_to_generic()
)
self.assertTrue("test_name" in y.__class__.__doc__)
self.assertTrue("a test parameter" in y.__class__.__doc__)
self.assertTrue("default" in y.__class__.__doc__)
self.assertTrue("22.0 m" in y.__class__.__doc__)
def test4(self):
parameter_definition = parameters.ModuleMethodParameterDefinition(
"get_test",
None,
"test_name",
"a test parameter",
11.0 | nbody_system.length
)
class TestModule(BaseTestModule):
x = 123.0 | nbody_system.length
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))
convert_nbody = nbody_system.nbody_to_si(2.0 | units.m, 4.0 | units.kg)
y = parameters.ParametersWithUnitsConverted(
x,
convert_nbody.as_converter_from_si_to_generic()
)
self.assertTrue("test_name" in str(y))
self.assertTrue("246.0 m" in str(y))
def test5(self):
print("Test 5: testing mixed nbody and physical units")
phys_parameter_definition = parameters.ModuleMethodParameterDefinition(
"get_test",
"set_test",
"phys_test_name",
"a test parameter with physical units",
11.0 | units.m
)
nbody_parameter_definition = parameters.ModuleMethodParameterDefinition(
"get_test1",
"set_test1",
"nbody_test_name",
"a test parameter with nbody units",
11.0 | nbody_system.length
)
class TestModule(BaseTestModule):
x = 123.0 | units.m
y = 123.0 | nbody_system.length
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
o = TestModule()
x = parameters.Parameters([phys_parameter_definition, nbody_parameter_definition], o)
self.assertTrue("nbody_test_name" in str(x))
self.assertTrue("123.0 length" in str(x))
self.assertTrue("phys_test_name" in str(x))
self.assertTrue("123.0 m" in str(x))
convert_nbody = nbody_system.nbody_to_si(2.0 | units.m, 4.0 | units.kg)
y = parameters.ParametersWithUnitsConverted(
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)
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
self.assertAlmostEqual(y.nbody_test_name, 24690.0 | units.m)
y.nbody_test_name = 12345.0 | units.m
self.assertEqual(y.nbody_test_name, 12345.0 | units.m)
def test6(self):
print("Test 5: testing mixed nbody and string units")
nbody_parameter_definition = parameters.ModuleMethodParameterDefinition(
"get_nbody",
None,
"nbody_par_name",
"a test parameter with nbody units",
11.0 | nbody_system.length
)
string_parameter_definition = parameters.ModuleMethodParameterDefinition(
"get_string",
None,
"string_par_name",
"a test parameter with string units",
"test string"
)
class TestModule(BaseTestModule):
x = 123.0 | nbody_system.length
def get_nbody(self):
return self.x
def get_string(self):
return str(10 * self.x.number)
o = TestModule()
x = parameters.Parameters([string_parameter_definition, nbody_parameter_definition], o)
self.assertTrue("nbody_par_name" in str(x))
self.assertTrue("123.0 length" in str(x))
self.assertTrue("string_par_name" in str(x))
self.assertTrue("1230.0" in str(x))
convert_nbody = nbody_system.nbody_to_si(2.0 | units.m, 4.0 | units.kg)
y = parameters.ParametersWithUnitsConverted(
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)
def test7(self):
parameter_definition1 = parameters.ModuleCachingParameterDefinition(
"initialize_vars",
"arg1",
"test_par1",
"a test parameter (1)",
11.0 | units.m
)
parameter_definition2 = parameters.ModuleCachingParameterDefinition(
"initialize_vars",
"arg2",
"test_par2",
"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
print(x.test_par1)
self.assertEqual(x.test_par1, 20 | units.m)
self.assertEqual(x.test_par2, 12 | units.m)
self.assertEqual(o.x, 123 | units.m)
self.assertEqual(o.y, 456 | units.m)
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(
"initialize_vars",
"arg1",
"test_par1",
"a test parameter (1)",
11.0 | units.m
)
parameter_definition2 = parameters.ModuleCachingParameterDefinition(
"initialize_vars",
"arg2",
"test_par2",
"a test parameter (2)",
12.0 | units.m
)
parameter_definition3 = parameters.ModuleCachingParameterDefinition(
"initialize_vars2",
"arg1",
"test_par3",
"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(
"get_test",
"set_test",
"test_name",
"a test parameter",
11.0 | units.m
)
parameter_definition2 = parameters.ModuleMethodParameterDefinition(
"get_test1",
"set_test1",
"test_name2",
"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(instance.x, 3 | units.m)
self.assertEqual(instance.y, 4 | units.m)
def test10(self):
print("Testing ParametersWithUnitsConverted on vector parameters")
definitions = []
for par_name in ["length_x", "length_y", "length_z"]:
definitions.append(parameters.ModuleMethodParameterDefinition(
"get_"+par_name,
"set_"+par_name,
par_name,
"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,
converter.as_converter_from_si_to_generic()
)
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(
"mesh_length",
"length of the model in the x, y and z directions",
("length_x", "length_y", "length_z")
)
for par_name in ["length_x", "length_y", "length_z"]:
parameters_handler.add_method_parameter(
"get_"+par_name,
"set_"+par_name,
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,
converter.as_converter_from_si_to_generic()
)
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",
"set_test",
"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)
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)
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)
def test13(self):
definition = parameters.ModuleMethodParameterDefinition(
"get_test",
None,
"test_name",
"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)
memento = set.copy()
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)
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)
def test14(self):
definition = parameters.InterfaceParameterDefinition(
"test_name",
"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)
memento = set.copy()
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)
def test15(self):
definition = parameters.InterfaceParameterDefinition(
"test_name",
"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)
def test16(self):
print("Testing add_interface_parameter")
class TestModule(BaseTestModule):
pass
o = TestModule()
parameters_handler = HandleParameters(o)
parameters_handler.add_vector_parameter(
"mesh_length",
"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"]):
parameters_handler.add_interface_parameter(
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,
converter.as_converter_from_si_to_generic()
)
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):
return self.x[i]
def set_length(self, i, value):
self.x[i] = value
def range(self):
return 0, len(self.x)-1
o = TestModule()
parameters_handler = HandleParameters(o)
parameters_handler.add_array_parameter(
"get_length",
"set_length",
"range",
"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))
def test18(self):
print("Testing array parameters")
definitions = []
definitions.append(parameters.ModuleArrayParameterDefinition(
"get",
"set",
"range",
"param",
"a test parameter"
))
class TestModule(BaseTestModule):
x = [1., 2., 3.] | generic_unit_system.length
def get(self, i):
return self.x[i]
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)
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,
"set_"+par_name,
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"]):
x = parameters_handler.get_attribute(par_name+"_set", None)
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
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.)
def test21(self):
print("Test change in parameter sets")
class TestInterface(BaseTestModule):
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.
)
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.)
| 41,812
| 30.50942
| 126
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_amusetest.py
|
from amuse.test.amusetest import TestCase
from amuse.support.exceptions import AmuseException
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.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")
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")
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"
"@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")
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")
# 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"
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)
# the ultimate test... lol
if sys.hexversion > 0x03000000:
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)
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.")
| 4,652
| 54.392857
| 145
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_binaryio.py
|
from amuse.test import amusetest
from io import BytesIO
from collections import namedtuple
import os.path
import math
from amuse import io
from amuse.io import gadget
from amuse.io import nemobin
from amuse.units import nbody_system
from amuse.datamodel import Particles
class GadgetFileFormatProcessorTests(amusetest.TestCase):
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',
b'\xed\xb5\xa0\xf7\xc6\x90>\x00\x00\x00\x00\x00\x00\x00\x00',
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 N\x00\x00 ',
b'\xa1\x07\x00 N\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
b'\x00\x00\x00\x00\x00\x00\x01\x00\x00',
)
def test1(self):
header = b''.join(self.header_parts)
x = gadget.GadgetFileFormatProcessor()
file = BytesIO(header)
x.load_header(file)
print(x.header_struct)
self.assertEqual(x.header_struct.Npart[0], 20000)
self.assertEqual(x.header_struct.Npart[1], 500000)
self.assertEqual(x.header_struct.Npart[2], 20000)
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')
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')
x = gadget.GadgetFileFormatProcessor()
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')
x = gadget.GadgetFileFormatProcessor()
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
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')
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)
def test7(self):
"""test returned ids from gadget file
for ticket #245.
All the 'uneven' particles have key "1", and identical velocities/positions. This is incorrect
upon further inspection, the test file is incorrect
"""
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(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)
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)
def test8(self):
"""test returned ids from gadget file
for ticket #245.
added option to not use the ids as a key, should fix the problem
for incorrect id's
"""
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)
self.assertEqual(len(gas), 0)
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)
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
file = BytesIO()
x.store_header(file)
print(x.header_struct)
self.assertEqual(x.header_struct.Npart[0], 20000)
self.assertEqual(x.header_struct.Npart[1], 500000)
self.assertEqual(x.header_struct.Npart[2], 20000)
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)
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])
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])
ids = x.read_fortran_block_ulongs(input)
self.assertEqual(ids[0], p[0].key)
self.assertEqual(ids[1], p[1].key)
masses = x.read_fortran_block_floats(input)
self.assertEqual(masses[0], 5)
self.assertEqual(masses[1], 6)
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)
outputfilename = 'gadgettest.output'
try:
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)
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)
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.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)
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],
[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)
self.assertEqual(data_converted.halo[0].key, 32**3 + 1)
self.assertEqual(data_converted.Npart, (32, 32, 0, 0, 0, 0))
self.assertEqual(data_converted.Time, 1/11.0)
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')
file = open(filename, 'rb')
nemofile = nemobin.NemoBinaryFile(file)
tagcharacter, tagstring, dim, mustswap = nemofile.get_item_header()
self.assertEqual(tagcharacter, 'c')
self.assertEqual(tagstring, 'Headline')
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')
file = open(filename, 'rb')
nemofile = nemobin.NemoBinaryFile(file)
data = nemofile.read()
file.close()
self.assertEqual(len(data), 3)
tags = list(data.keys())
self.assertEqual(tags[0], 'Headline')
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')
file = open(filename, 'rb')
x = nemobin.NemoBinaryFileFormatProcessor()
set = x.load_file(file).previous_state()
file.close()
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)
def test5(self):
directory_name = os.path.dirname(__file__)
filename = os.path.join(directory_name, 'plummer128.nemo')
file = open(filename, 'rb')
nemofile = nemobin.NemoBinaryFile(file)
data = nemofile.read()
file.close()
outputfile = BytesIO()
nemooutputfile = nemobin.NemoBinaryFile(outputfile)
nemooutputfile.write(data)
string = outputfile.getvalue()
outputfile.close()
inputfile = BytesIO(string)
nemoinputfile = nemobin.NemoBinaryFile(inputfile)
tagcharacter, tagstring, dim, mustswap = nemoinputfile.get_item_header()
self.assertEqual(tagcharacter, 'c')
self.assertEqual(tagstring, 'Headline')
self.assertEqual(len(dim), 1)
self.assertEqual(dim[0], 28)
inputfile.close()
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')
file = open(filename, 'rb')
nemofile = nemobin.NemoBinaryFile(file)
data = nemofile.read()
file.close()
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')
file = open(filename, 'rb')
x = nemobin.NemoBinaryFileFormatProcessor()
set = x.load_file(file)
file.close()
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)
def test9(self):
filename = os.path.join(os.path.dirname(__file__), 'plummer128.nemo')
particles = io.read_set_from_file(filename, format="nemobin")
self.assertEqual(len(particles), 128)
self.assertAlmostEqual(particles.total_mass(), 1.0 | nbody_system.mass)
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)
| 20,014
| 45.224018
| 193
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_rotation.py
|
from amuse.test import amusetest
import os.path
import numpy
from amuse.units import units
from amuse.units import constants
from amuse.units import nbody_system
from amuse.units import quantities
from amuse.ic.plummer import new_plummer_model
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(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)))
x = rotation.new_rotation_matrix(0, 0, numpy.pi)
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)
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)
print(x)
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)
print(x)
self.assertAlmostRelativeEquals(x, ((0, 1, 0), (0, 0, -1), (-1, 0, 0)))
def test03(self):
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)
rotated = rotation.rotated(positions, numpy.pi, 0.0, 0.0)
print(rotated)
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
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)
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)
def test05(self):
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)
def test06(self):
particles = new_plummer_model(100)
kinetic_energy0 = particles.kinetic_energy()
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)
self.assertAlmostRelativeEquals(potential_energy1, potential_energy0)
def test07(self):
particles = new_plummer_model(100)
kinetic_energy0 = particles.kinetic_energy()
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(),
[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()
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()
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)))
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))
| 8,040
| 42.464865
| 141
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_particle_attributes.py
|
import random
import numpy.random
import sys
from amuse.test import amusetest
from amuse.units import units
from amuse.units import constants
from amuse.units import nbody_system
from amuse.support.interface import ConvertArgumentsException
from amuse.ic.plummer import new_plummer_sphere
from amuse.ic.salpeter import new_salpeter_mass_distribution_nbody
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.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)
self.assertAlmostRelativeEquals(particles.potential_energy(G=nbody_system.G), -0.08 | nbody_system.energy)
self.assertAlmostRelativeEquals(particles.virial_radius(), 4.0 | nbody_system.length)
particles.scale_to_standard()
self.assertAlmostRelativeEquals(particles.total_mass(), 1.0 | nbody_system.mass)
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
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
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
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.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
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
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
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)
random.seed(456)
number_of_particles = 10000
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))
if sys.hexversion > 0x03000000:
self.assertAlmostEqual(result.mass_segregation_ratio, 0.7160, 3)
self.assertAlmostEqual(result.uncertainty, 0.2321, 3)
else:
self.assertAlmostEqual(result.mass_segregation_ratio, 0.8877, 3)
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,
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,
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)
self.assertTrue("Returns the total kinetic energy of the\n particles in the particles set." in particles.kinetic_energy.__doc__)
self.assertEqual(particles.kinetic_energy.__class__.__name__, "BoundParticlesFunctionAttribute")
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.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
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
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
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)
particles.x = numpy.logspace(0.0, 2.0, 21) | units.m
particles.y = 0.0 | units.m
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
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
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
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
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]
x_one_third = x_values[:-1] + dx / 3.0
y_one_third = y_values[:-1] + dy / 3.0
x_two_third = x_one_third + dx / 3.0
y_two_third = y_one_third + dy / 3.0
x_new_point = x_values[:-1] + 0.5*dx - height * dy
y_new_point = y_values[:-1] + 0.5*dy + height * dx
new_x = numpy.append(numpy.dstack((x_values[:-1], x_one_third, x_new_point, x_two_third)), [x_values[-1]])
new_y = numpy.append(numpy.dstack((y_values[:-1], y_one_third, y_new_point, y_two_third)), [y_values[-1]])
return new_x, new_y
x, y = numpy.array([0.0, 0.5, 1.0, 0.0]), numpy.array([0.0, 3*height, 0.0, 0.0])
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
particles = Particles(729)
particles.position = numpy.mgrid[0:9.0, 0:9.0, 0:9.0].reshape(3, -1).transpose() | units.m
dimension = particles.correlation_dimension()
self.assertAlmostRelativeEquals(dimension, 3.0, 1)
# 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)
sel = numpy.random.randint(len(x), size=729)
particles.position = numpy.hstack((x[sel], y[sel], numpy.zeros(729))) | units.m
dimension = particles.correlation_dimension()
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
particles = Particles(4096)
particles.position = numpy.mgrid[0:16.0, 0:16.0, 0:16.0].reshape(3, -1).transpose() | units.m
dimension = particles.box_counting_dimension()
self.assertAlmostRelativeEquals(dimension, 3.0, 1)
# 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)
sel = numpy.random.randint(len(x), size=4096)
particles.position = numpy.hstack((x[sel], y[sel], numpy.zeros(4096))) | units.m
dimension = particles.box_counting_dimension()
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)
random.seed(4567)
number_of_particles = 1000
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)
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,
also_compute_uncertainty=True)
self.assertTrue(MSR > 5.0)
if sys.hexversion > 0x03000000:
self.assertAlmostEqual(sigma, 0.3, 1)
else:
self.assertAlmostEqual(sigma, 0.4, 1)
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)
for n in range(3162, 3165, 1):
stars = new_plummer_sphere(
n,
convert_nbody=converter,
)
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())
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)
for n in range(0, 50):
stars = new_plummer_sphere(
50,
convert_nbody=converter,
)
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())
class TestParticlesDomainAttributes(amusetest.TestCase):
def test1(self):
particles = Particles(2)
particles.add_attribute_domain('a')
particles.add_attribute_domain('b')
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')
particles.add_attribute_domain('b')
particles.a.foo = 1 | units.m
particles.b.bar = 2 | units.kg
particles.foo = 3 | units.s
self.assertEqual(
sorted(particles.a.get_attribute_names_defined_in_store()),
['foo']
)
self.assertEqual(
sorted(particles.b.get_attribute_names_defined_in_store()),
['bar']
)
def test3(self):
particles = Particles(2)
particles.add_attribute_domain('a')
particles.add_attribute_domain('b')
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)
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)
def test5(self):
particles = Particles(2)
particles.add_attribute_domain('a')
particles.add_attribute_domain('b')
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)
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)
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)
| 23,384
| 52.147727
| 170
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_grids.py
|
from amuse.test import amusetest
from amuse.support.interface import InCodeComponentImplementation
from amuse.datamodel.indexing import *
from amuse.datamodel.grids import *
import numpy
import inspect
import collections
from amuse.units import units
from amuse.units import constants
from amuse.units import nbody_system
from amuse import datamodel
class TestGrids(amusetest.TestCase):
def test1(self):
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))
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))
def test3(self):
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.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.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.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))
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)
y = x + 100.0
z = x + 200.0
grid.x = units.m.new_quantity(x)
grid.y = units.m.new_quantity(y)
grid.z = units.m.new_quantity(z)
gridpoint = grid[1][2][1]
self.assertEqual(gridpoint.position[0], 19 | units.m)
self.assertEqual(gridpoint.position[1], 119 | units.m)
self.assertEqual(gridpoint.position[2], 219 | units.m)
subgrid = grid[1][2]
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)
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)
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)
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)
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()
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()
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()
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()
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()
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])
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))
self.assertEqual(grid[0][0].shape, (2,))
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)
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, :])
def test15(self):
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:
nj += 1
for plane3 in plane2:
ni += 1
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)
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)
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, ...])
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])
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])
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))
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, :, :]
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])
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, ...]
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])
def test24(self):
particle = datamodel.Particle()
particle.mass = 10 | units.kg
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)
def test25(self):
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]
xv = xv.flatten()
yv = yv.flatten()
zv = zv.flatten()
i = 0
for cell in grid.iter_cells():
expected_position = grid[xv[i], yv[i], zv[i]].position
self.assertEqual(cell.position, expected_position)
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)
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))
def test29(self):
grid = datamodel.Grid(200)
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,))
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)
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])
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])
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))
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)
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))
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)))
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))
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, 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])
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.m1 = 1
grid1.m2 = 2
channel = grid1.new_channel_to(grid2)
channel.transform(["m3"], lambda x, y: (x,), ["m1", "m2"])
self.assertEqual(grid2.m3, 1)
channel.transform(["m3"], lambda x, y: (y,), ["m1", "m2"])
self.assertEqual(grid2.m3, 2)
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"])
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])
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])
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])
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])
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])
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])
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((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])
def test47(self):
grid = datamodel.Grid()
grid.mass = 12.
self.assertEqual(grid[...].mass, 12.)
self.assertEqual(grid.mass, 12.)
def test48(self):
p = datamodel.Grid(3)
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])
def test50(self):
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][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)
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")
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][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)
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))
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)
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")
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)
self.assertEqual(dens[2], 2 | units.kg/units.m**3)
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 test53(self):
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))
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)
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 test54(self):
"""
illustrates getting subgrid/gridpoint with history from subgrid with history
"""
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")
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)
self.assertEqual(dens[2], 2 | units.kg/units.m**3)
self.assertEqual(time[0], 1.0 | units.s)
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)
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.])
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)
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))
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))
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)))
def test3(self):
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))
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])
connectivity = grid.connectivity()
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])
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])
connectivity = grid.connectivity()
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])
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])
connectivity = grid.connectivity()
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])
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)
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))
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))
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())
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)
self.assertTrue(grid1.overlaps(grid2))
self.assertTrue(grid1.overlaps(grid3))
self.assertFalse(grid2.overlaps(grid3))
self.assertTrue(grid2.overlaps(grid1))
self.assertTrue(grid3.overlaps(grid1))
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)
self.assertTrue(grid1.overlaps(grid2))
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)
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)
class TestGridSampling(amusetest.TestCase):
def test1(self):
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])
def test2(self):
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])
def test3(self):
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],
])
def test4(self):
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)
def test5(self):
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")
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)
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)
def test6(self):
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))
def test7(self):
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.assertTrue(sample.isvalid)
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")
self.assertFalse(sample.isvalid)
def test8(self):
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)
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)
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.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)
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)
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.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")
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)
def test2(self):
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")
self.assertEqual(len(samples), 2)
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.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.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)
self.assertEqual(len(samples), 3)
self.assertEqual(samples.mass, [3.0, 4.0, 13.0] | units.kg)
| 48,010
| 44.899618
| 139
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_staggeredgrid.py
|
from amuse.test import amusetest
from amuse.units import units
import numpy
from amuse.datamodel.grids import *
from amuse.datamodel.staggeredgrid import StaggeredGrid
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
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)
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)
lons = lons/ind.shape[1] * 2.0*numpy.pi
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:]])
nodes = StructuredGrid(*ind[0].shape)
nodes.lat = (lats | units.rad)
nodes.lon = (lons | units.rad)
grid = StaggeredGrid(elements, nodes)
values = numpy.random.random(shape)
elements.values = values
nodes.values = grid.map_elements_to_nodes(values)
remapped_values = grid.map_nodes_to_elements(nodes.values)
before_sum = values.sum()
after_sum = remapped_values.sum()
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
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)
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)
lons = lons/ind.shape[1] * 2.0*numpy.pi
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:]])
nodes = StructuredGrid(*shape)
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]))
values = numpy.random.random(shape)
elements.values = values
nodes.values = grid.map_elements_to_nodes(values)
remapped_values = grid.map_nodes_to_elements(nodes.values)
before_sum = values.sum()
after_sum = remapped_values.sum()
self.assertEqual(after_sum, before_sum, msg="Sum of values before and after remapping should be the same")
# 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
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],
[-0.090, 0.904], [-0.069, 0.907], [-0.069, 0.921], [-0.080, 0.919],
[-0.073, 0.928], [-0.052, 0.930], [-0.048, 0.942], [-0.062, 0.949],
[-0.054, 0.958], [-0.069, 0.954], [-0.087, 0.952], [-0.087, 0.959],
[-0.080, 0.966], [-0.085, 0.973], [-0.087, 0.965], [-0.097, 0.965],
[-0.097, 0.975], [-0.092, 0.984], [-0.101, 0.980], [-0.108, 0.980],
[-0.104, 0.987], [-0.102, 0.993], [-0.115, 1.001], [-0.099, 0.996],
[-0.101, 1.007], [-0.090, 1.010], [-0.087, 1.021], [-0.069, 1.021],
[-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.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],
[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],
[49, 48, 71], [14, 16, 15], [14, 71, 48], [17, 19, 18], [17, 20, 19],
[48, 16, 14], [48, 47, 16], [47, 46, 16], [16, 46, 45], [23, 22, 24],
[21, 24, 22], [17, 16, 45], [20, 17, 45], [21, 25, 24], [27, 26, 28],
[20, 72, 21], [25, 21, 72], [45, 72, 20], [25, 28, 26], [44, 73, 45],
[72, 45, 73], [28, 25, 29], [29, 25, 31], [43, 73, 44], [73, 43, 40],
[72, 73, 39], [72, 31, 25], [42, 40, 43], [31, 30, 29], [39, 73, 40],
[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
nodes = UnstructuredGrid(len(xy))
nodes.lon = (xy[:, 0] | units.rad)
nodes.lat = (xy[:, 1] | units.rad)
grid = StaggeredGrid(elements, nodes)
values = numpy.random.random(num_elems)
elements.values = values
nodes.values = grid.map_elements_to_nodes(values)
remapped_values = grid.map_nodes_to_elements(nodes.values)
before_sum = values.sum()
after_sum = remapped_values.sum()
self.assertAlmostEqual(after_sum, before_sum, msg="Sum of values before and after remapping should be the same")
| 6,998
| 43.297468
| 120
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_nbody_units.py
|
from amuse.test import amusetest
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)
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)
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)
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')
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')
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)
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)
y = 5 | units.m / units.s
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)
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)
y = 1 | time
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)
y = 1.0 | units.none
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])
| 3,140
| 40.88
| 107
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_nemo.py
|
from amuse.test import amusetest
import os.path
import numpy
from amuse.io import nemotsf
from amuse.units import units
from amuse.units import constants
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)
def test2(self):
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)
def test3(self):
instance = nemotsf.Tsf2Particles()
particles = instance.convert_to_particles(self.p10_string)
self.assertAlmostEqual(particles.mass[0], 0.1 | nbody_system.mass, constants.precision)
def test4(self):
reader = nemotsf.Tsf2Particles()
particles = reader.convert_to_particles(self.p10_string)
writer = nemotsf.Particles2Tsf()
string = writer.convert_to_string(particles)
print(string)
print(self.p10_string)
self.assertTrue("double PhaseSpace[10][2][3]" in string)
self.assertTrue("double Mass[10]" in string)
| 1,676
| 34.680851
| 109
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_starlab.py
|
import os.path
import io
import numpy
from amuse import io
from amuse.io import starlab
from amuse.units import units
from amuse.units import nbody_system
from amuse.test import amusetest
from amuse import datamodel
plummer_scaled_content = """(Particle
N = 5
(Log
===> Wed Mar 23 10:36:19 2011
Starlab 4.4.4 (user vanelteren) : makeplummer -n 5
random number generator seed = 1300872979
initial_mass = 1.93791189968789
===> Wed Mar 23 10:36:19 2011
Starlab 4.4.4 (user vanelteren) : makemass -l 0.2 -u 20 -x -2.35
random number generator seed = 1300872979
Power_Law mass function, total mass = 1.94 Solar
)Log
(Dynamics
system_time = 0
m = 1.93791189968789257
r = 0 0 0
v = 0 0 0
com_time = 0
com_pos = 0 0 0
com_vel = 0 0 0
total_energy = -0.25
)Dynamics
(Hydro
)Hydro
(Star
mass_scale = 0.516019329960796136
size_scale = -2.25500000000000001e-08
time_scale = -1
)Star
(Particle
N = 1
(Log
)Log
(Dynamics
m = 0.266730587350341442
r = -0.934040458729136547 -0.695803261872860679 0.564081767628105579
v = 0.293044501505944688 0.0259404966497079996 0.196831834670057881
)Dynamics
(Hydro
)Hydro
(Star
)Star
)Particle
(Particle
N = 1
(Log
)Log
(Dynamics
m = 0.32415747586178062
r = -0.177487175943360831 0.205223807753114523 -0.191956558941283828
v = -0.178395285089674116 -0.0357730795197053753 0.376231470164175796
)Dynamics
(Hydro
)Hydro
(Star
)Star
)Particle
(Particle
N = 1
(Log
)Log
(Dynamics
m = 0.567097501003086424
r = 0.607757256863783235 0.120278701131815768 0.338645014325028748
v = -0.26638454687085783 0.291986511517820568 0.672417896548585303
)Dynamics
(Hydro
)Hydro
(Star
)Star
)Particle
(Particle
N = 1
(Log
)Log
(Dynamics
m = 0.379463033750591316
r = 0.247202300114546969 0.086741731241469916 -0.164892802949227257
v = -0.0888917818811222754 0.286288450446576914 -1.03818564484543829
)Dynamics
(Hydro
)Hydro
(Star
)Star
)Particle
(Particle
N = 1
(Log
)Log
(Dynamics
m = 0.400463301722092879
r = 0.256568077694167229 0.283559021746460527 -0.545877420062623298
v = 0.240627112335709492 -0.568442379094400096 -0.207295556537380576
)Dynamics
(Hydro
)Hydro
(Star
)Star
)Particle
)Particle
"""
with_stellar_structure = """(Particle
N = 2
(Log
===> Wed Mar 23 12:28:21 2011
Starlab 4.4.4 (user vanelteren) : makeplummer -n 2
random number generator seed = 1300879701
initial_mass = 1
===> Wed Mar 23 12:28:21 2011
Starlab 4.4.4 (user vanelteren) : makemass -f 1 -x -2.0 -l 0.1 -u 20
random number generator seed = 1300879701
Power_Law mass function, total mass = 0.22 Solar
===> Wed Mar 23 12:28:21 2011
Starlab 4.4.4 (user vanelteren) : add_star -Q 0.5 -R 5
===> Wed Mar 23 12:28:21 2011
Starlab 4.4.4 (user vanelteren) : scale -s
initial_total_energy = -0.25
initial_rvirial = 1
)Log
(Dynamics
system_time = 0
m = 1.000000000000002
r = 0 0 0
v = 0 0 0
com_time = 0
com_pos = 0 0 0
com_vel = 0 0 0
total_energy = -0.25
)Dynamics
(Hydro
)Hydro
(Star
mass_scale = 4.62223018200823255
size_scale = 4.51000000000000035e-09
time_scale = 0.0028016566610805007
)Star
(Particle
N = 1
(Log
)Log
(Dynamics
m = 0.483839787917132669
r = -0.209118735762131774 -0.0880146969484976449 0.122429686361064466
v = 0.435701422371714053 -0.0578440884891995299 0.583282312300410277
)Dynamics
(Hydro
)Hydro
(Star
Type = main_sequence
T_cur = 0
M_rel = 0.104676696933106134
M_env = 0.0946766969331061387
M_core = 0.0100000000000000002
T_eff = 3011.01000587455155
L_eff = 0.00122847524117014736
)Star
)Particle
(Particle
N = 1
(Log
)Log
(Dynamics
m = 0.516160212082869219
r = 0.196024339714903045 0.0825034772310478115 -0.114763501907016688
v = -0.408419089384746692 0.0542220629403740648 -0.546758900962974193
)Dynamics
(Hydro
)Hydro
(Star
Type = main_sequence
T_cur = 0
M_rel = 0.111669084350665276
M_env = 0.101669084350665281
M_core = 0.0100000000000000002
T_eff = 3051.91244441666595
L_eff = 0.00147739782384390963
)Star
)Particle
)Particle
"""
class Test(amusetest.TestCase):
def test1(self):
"""test_starlab.test1
+---------------------------------------------------------------------+
| Particle tree of test_subub.dyn |
| |
| 0 16kg x=0 |
| ,- . |
| ,-' `._ |
| _,' `. |
| ,' `-. |
| 1 8kg, x=-10 3 8kg, x=10 |
| ,-' - ._ |
| ,' ,' `. |
| ,' ,' `._ |
| ,' ,' `. |
| 2 4kg, x=-15 4 4kg, x=5 5 4kg, x=15 |
| . |
| `._ |
| `. |
| ` |
| 6 2kg, x=17 |
| |
+---------------------------------------------------------------------+
"""
directory = os.path.dirname(__file__)
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(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)
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(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):
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)
self.assertAlmostRelativeEquals(set[0].envelope_mass, 0.0946766969331061387 | units.MSun)
self.assertAlmostRelativeEquals(set[0].core_mass, 0.0100000000000000002 | units.MSun)
self.assertAlmostRelativeEquals(set[0].relative_mass, set[0].mass, 10)
self.assertAlmostRelativeEquals(set[0].effective_temperature, 3011.01000587455155 | units.K)
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[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"])
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"])
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)
self.assertEqual(len(set), 20)
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)
| 11,103
| 35.406557
| 158
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_incode_storage.py
|
from amuse.test import amusetest
from amuse.datamodel.incode_storage import *
import numpy
import time
from amuse.units import units
from amuse.units import constants
from amuse.units import nbody_system
class TestParticles(amusetest.TestCase):
def test1(self):
class Code(object):
def __init__(self):
# x,y,z,mass
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):
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)
return [units.m(x) for x in data_to_return]
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]
return [i for i in range(len(x))]
code = Code()
storage = InCodeAttributeStorage(
code,
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"
)
self.assertEqual(len(storage), 0)
self.assertEqual(storage.get_defined_attribute_names(), ["x", "y", "z"])
self.assertFalse(code.get_position_called)
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"],
[
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):
# x,y,z,mass
self.data = []
self.get_position_called = False
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):
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)
return [units.m(x) for x in data_to_return]
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):
self.set_position_called = True
pass
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]
return [i for i in range(len(x))]
code = Code()
storage = InCodeAttributeStorage(
code,
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",)),
],
name_of_the_index="index"
)
storage.add_particles_to_store(
[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]),
]
)
self.assertEqual(len(storage), 4)
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"])
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):
def __init__(self):
# mass
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):
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):
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",)),
None,
code.get_number_of_particles,
[],
[
ParticleGetAttributesMethod(code.get_mass, ("mass",)),
],
name_of_the_index="index"
)
storage.add_particles_to_store(
[1, 2, 3, 4],
["mass"],
[
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"])
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):
# mass
self.data = []
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):
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):
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",)),
None,
code.get_number_of_particles,
[],
[
ParticleGetAttributesMethod(code.get_mass, ("mass",)),
],
name_of_the_index="index"
)
storage.add_particles_to_store(
numpy.asarray([1, 2, 3, 4], dtype='uint64'),
["mass"],
[
units.kg([1, 2, 3, 4]),
]
)
self.assertEqual(len(storage), 4)
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"])
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])
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"])
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"])
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):
data_to_return = [self.data[i][0] for i in index]
return units.kg(data_to_return)
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.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'])
storage = InCodeAttributeStorage(
code,
NewParticleMethod(code.new_particle, ("mass",)),
None,
code.get_number_of_particles,
[],
[
ParticleGetAttributesMethod(code.get_mass, ("mass",)),
children_getter
],
name_of_the_index="index"
)
storage.add_particles_to_store(
numpy.asarray([100, 200, 300, 400], dtype='uint64'),
["mass"],
[
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]
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'])
self.assertEqual(child1[0].number, 200)
self.assertEqual(child2[0].number, 300)
def test7(self):
class Code(object):
def __init__(self):
# x,y,z,mass
self.data = []
self.get_position_called = False
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):
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)
return [units.m(x) for x in data_to_return]
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):
self.set_position_called = True
pass
def set_mass(self, index, mass):
self.set_mass_called = True
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]
return [i for i in range(len(x))]
code = Code()
storage = InCodeAttributeStorage(
code,
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",)),
],
[
ParticleGetAttributesMethod(code.get_position, ("x", "y", "z")),
ParticleGetAttributesMethod(code.get_mass, ("mass",)),
],
name_of_the_index="index"
)
storage.add_particles_to_store(
[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]),
]
)
self.assertEqual(len(storage), 4)
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"])
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)
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 units.m(i), units.m(j), units.m(k)
code = Code()
storage = InCodeGridAttributeStorage(
code,
code.get_range,
[],
[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(len(values), 1)
self.assertEqual(values[0], 1 | units.m)
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 units.m(i), units.m(j), units.m(k)
code = Code()
storage = InCodeGridAttributeStorage(
code,
code.get_range,
[],
[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][0][0][0], 1 | units.m)
self.assertEqual(values[0][1][0][0], 2 | units.m)
def test3(self):
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)]))
def set_a(self, i_s, j_s, k_s, 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):
self.storage[i][j][k] = values[index].value_in(units.m)
index += 1
# ~ print index
code = Code()
storage = InCodeGridAttributeStorage(
code,
code.get_range,
[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.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",))
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,])
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 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},
)
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(len(values), 1)
self.assertEqual(values[0], 1 | units.m)
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 units.m(i), units.m(j), units.m(k)
code = Code()
storage = InCodeGridAttributeStorage(
code,
code.get_range,
[],
[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(None, ("i",))
self.assertEqual(len(values), 1)
self.assertEqual(values[0].number.ndim, 3)
def test6(self):
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)])
def set_a(self, i_s, j_s, k_s, 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):
self.storage[i][j][k] = values[index]
index += 1
# ~ print index
code = Code()
storage = InCodeGridAttributeStorage(
code,
code.get_range,
[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",))
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",))
self.assertEqual(values[0], 11.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],])
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)
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)])
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):
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",)),],
)
values = storage.get_values_in_store((), ())
self.assertTrue(values == [])
values = storage.get_values_in_store((0, 0, 1,), ("a",))
self.assertTrue(values[0] == 1)
def test8(self):
class Code(object):
def __init__(self):
self.storage = 1. | units.m
def get_range(self):
return ()
def get_a(self):
return self.storage
def set_a(self, value):
self.storage = value
code = Code()
storage = InCodeGridAttributeStorage(
code,
code.get_range,
[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, "<")
self.assertEqual(values[0], 1 | units.m)
| 24,474
| 33.278711
| 145
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_scaling_converter.py
|
from amuse.units import scaling_converter
from amuse.units import nbody_system
from amuse.test import amusetest
class TestScalingConverter(amusetest.TestCase):
def test1(self):
converter = scaling_converter.ScalingConverter(
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,
)
input = 1 | nbody_system.length ** 2
output = converter.convert(input)
self.assertAlmostRelativeEquals(output, 0.2 * 0.2 | nbody_system.length ** 2)
| 757
| 28.153846
| 85
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_quantities.py
|
from amuse.test import amusetest
import numpy
import sys
from amuse.support.exceptions import AmuseException
from amuse.units.quantities import *
from amuse.units import si
from amuse.units import units
from amuse.units import trigo
from amuse.units import nbody_system
from amuse.units import quantities
from amuse.units import core
from amuse import datamodel
class TestQuantities(amusetest.TestCase):
def test1(self):
x = 1.0 | si.kg
self.assertTrue(isinstance(x, ScalarQuantity))
x = [1.0, 2.0, 3.0] | si.kg
self.assertTrue(isinstance(x, VectorQuantity))
def test2(self):
x = [1.0, 2.0, 3.0] | si.kg
y = [2.0, 3.0, 4.0] | si.kg
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
self.assertEqual(str(x), "[1.0, 2.0, 3.0] kg")
x[0] = 3000.0 | g
self.assertEqual(str(x), "[3.0, 2.0, 3.0] kg")
def test5(self):
number_of_stars = 10
stars = datamodel.Particles(number_of_stars)
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:
for i in range(3):
if star.position[i] < minpos[i]:
minpos[i] = star.position[i]
if star.position[i] > maxpos[i]:
maxpos[i] = star.position[i]
self.assertEqual(str(minpos), "[1000.0, 2000.0, -10000.0] m")
self.assertEqual(str(maxpos), "[10000.0, 20000.0, -1000.0] m")
def test6(self):
x = [1.0, 2.0, 3.0] | si.kg
y = x.copy()
y[0] = 3.0 | si.kg
self.assertEqual(x[0].value_in(si.kg), 1.0)
self.assertEqual(y[0].value_in(si.kg), 3.0)
def test7(self):
x = 2.0 | si.kg
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))
def test9(self):
converter = nbody_system.nbody_to_si(1 | si.kg, 2 | si.s)
self.assertEqual(0.0 | nbody_system.mass, converter.to_nbody(zero))
self.assertEqual(converter.to_nbody(zero), 0.0 | nbody_system.mass)
def test10(self):
self.assertEqual(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.assertFalse(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.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.assertFalse([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.assertFalse([1] | units.m >= [2] | 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)
def test12(self):
self.assertEqual(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.assertFalse(zero != zero)
self.assertTrue(zero >= zero)
self.assertFalse(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)
def test13(self):
self.assertEqual('a', 'a')
self.assertTrue('a' == 'a')
self.assertFalse('a' == 'ab')
self.assertTrue('a' != 'A')
self.assertFalse('a' != 'a')
self.assertTrue('b' >= 'a')
self.assertFalse('B' >= 'a')
self.assertTrue('a' <= 'ab')
self.assertFalse('a' <= 'A')
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"))
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)))
masses = [1, 2, 3] | units.kg
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))
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)
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.assertRaises(AmuseException, quantity.__radd__, number)
self.assertTrue(number.__radd__(quantity) is NotImplemented)
self.assertRaises(AmuseException, quantity.__add__, number)
self.assertTrue(number.__sub__(quantity) is NotImplemented)
self.assertRaises(AmuseException, quantity.__rsub__, number)
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")
self.assertRaises(AmuseException, lambda: quantity + number,
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")
self.assertRaises(AmuseException, lambda: quantity - number,
expected_message="Cannot express none in m, the units do not have the same bases")
def test18(self):
quantity = 'string'
self.assertEqual(quantity, 'string')
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())
def test20(self):
lengths = [] | units.m
lengths.append(1 | units.m)
self.assertEqual(lengths, [1] | units.m)
lengths.append(2 | units.m)
self.assertEqual(lengths, [1, 2] | units.m)
positions = [] | units.m
positions.append([1, 2, 3] | units.m)
self.assertEqual(positions, [[1, 2, 3]] | units.m)
positions.append([4, 5, 6] | units.m)
self.assertEqual(positions, [[1, 2, 3], [4, 5, 6]] | units.m)
two_positions = [] | units.m
two_positions.append([[1, 2, 3], [-1, -2, -3]] | units.m)
self.assertEqual(two_positions, [[[1, 2, 3], [-1, -2, -3]]] | units.m)
two_positions.append([[4, 5, 6], [7, 8, 9]] | units.m)
self.assertEqual(two_positions, [[[1, 2, 3], [-1, -2, -3]], [[4, 5, 6], [7, 8, 9]]] | units.m)
# Appending quantities with incompatible shapes:
two_positions.append(99 | units.m)
self.assertEqual(two_positions, [1, 2, 3, -1, -2, -3, 4, 5, 6, 7, 8, 9, 99] | units.m)
def test21(self):
zero_vector = zero.as_vector_with_length(3)
self.assertEqual(str(zero_vector), "[0.0, 0.0, 0.0] zero")
self.assertEqual(zero_vector + (1 | units.m), [1, 1, 1] | units.m)
self.assertEqual(zero_vector - (1 | units.m), [-1, -1, -1] | units.m)
self.assertEqual((1 | units.m) + zero_vector, [1, 1, 1] | units.m)
self.assertEqual((1 | units.m) - zero_vector, [1, 1, 1] | units.m)
self.assertEqual(zero_vector + ([1, 1, 1] | units.m), [1, 1, 1] | units.m)
self.assertEqual(zero_vector - ([1, 1, 1] | units.m), [-1, -1, -1] | units.m)
self.assertEqual(([1, 1, 1] | units.m) + zero_vector, [1, 1, 1] | units.m)
self.assertEqual(([1, 1, 1] | units.m) - zero_vector, [1, 1, 1] | units.m)
for one_zero in zero_vector:
self.assertEqual(one_zero, zero)
self.assertEqual(zero_vector[0:2], zero.as_vector_with_length(2))
def test22(self):
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.assertTrue(is_quantity(x * y))
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)
def xtest24(self):
rhs = 2 | units.MSun / units.AU
lhs = 3 | units.AU
product = rhs * lhs
product_unit = product.unit
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)
def xtest26(self):
rhs = 2.0 | units.AU / (2 * units.MSun)**2
lhs = 3.0 | units.MSun
product = rhs * lhs
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)
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)
def test28(self):
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")
except:
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)
def test31(self):
"""
test trigonometric unit stuff
"""
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
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
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
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 = 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 = 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.]])
self.assertEqual(list(a.flatten()), list(a.flat))
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)
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
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))
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.m)
x[0] = -1
self.assertEqual(a, [1, 2, 3, 4, 5] | units.m)
class TestAdaptingVectorQuantities(amusetest.TestCase):
def test1(self):
x = AdaptingVectorQuantity()
self.assertEqual(x.append.__name__, "append_start")
x.append(1 | units.kg)
self.assertEqual(x.unit, units.kg)
self.assertEqual(len(x), 1)
self.assertEqual(x.append.__name__, "append_normal")
self.assertTrue(isinstance(x._number_list, list))
self.assertFalse(isinstance(x._number_list, numpy.ndarray))
self.assertTrue(isinstance(x.number, numpy.ndarray))
self.assertFalse(isinstance(x.number, list))
self.assertEqual(x._number_list, [1])
self.assertEqual(x.number, numpy.array([1]))
def test2(self):
x = AdaptingVectorQuantity()
self.assertEqual(len(x), 0)
self.assertEqual(len(x.number), 0)
self.assertEqual(str(x), '[]')
x.append(1 | units.kg)
self.assertEqual(x.unit, units.kg)
self.assertEqual(len(x), 1)
self.assertEqual(str(x), '[1] kg')
x.append(2 | units.kg)
self.assertEqual(x.unit, units.kg)
self.assertEqual(len(x), 2)
self.assertEqual(str(x), '[1, 2] kg')
def test3(self):
x = AdaptingVectorQuantity()
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]))
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)
def test4(self):
x = AdaptingVectorQuantity()
x.prepend(1 | units.kg)
self.assertEqual(x.unit, units.kg)
self.assertEqual(len(x), 1)
self.assertEqual(str(x), '[1] kg')
x.prepend(2 | units.kg)
self.assertEqual(x.unit, units.kg)
self.assertEqual(len(x), 2)
self.assertEqual(str(x), '[2, 1] kg')
def test5(self):
# Everything mixed...
x = AdaptingVectorQuantity()
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.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)
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)
class TestNumpyFunctionWithUnits(amusetest.TestCase):
def test1(self):
array = quantities.arange(0 | units.kg, 10 | units.kg, 1 | units.kg)
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)
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)
fit = quantities.polyfit(x, y, 2)
self.assertEqual(len(fit), 3)
self.assertEqual(fit[0].unit, units.km/units.yr**2)
fit_values = quantities.polyval(fit, x)
self.assertEqual(fit_values.shape, x.shape)
self.assertEqual(y.unit, fit_values.unit)
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)
| 20,747
| 37.708955
| 102
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_vtkio.py
|
from amuse.test import amusetest
from io import StringIO
import textwrap
import os
import numpy
from amuse import io
from amuse.io import vtk
from amuse.units import units
from amuse.units import generic_unit_system
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.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('<DataArray type="Float64" NumberOfComponents="3">') > 0)
self.assertTrue(contents.find('<DataArray type="Float64" NumberOfComponents="1" Name="rho">') > 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))
data_file = StringIO()
instance = vtk.VtkStructuredGrid("test.vts", data_file, grid)
instance.store()
contents = data_file.getvalue()
self.assertTrue(contents.find('<Piece Extent="0 4 0 5 0 6">') > 0)
self.assertTrue(contents.find('<CellData>') > 0)
self.assertTrue(contents.find('<PointData>') > 0)
self.assertTrue(contents.find('<DataArray type="Float64" NumberOfComponents="3">') > 0)
self.assertTrue(contents.find('<DataArray type="Float64" NumberOfComponents="1" Name="mass">') > 0)
class VtkUnstructuredGridTests(amusetest.TestCase):
def test1(self):
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('<Piece NumberOfPoints="60" NumberOfCells="24"') > 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.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('<Piece NumberOfPoints="27" NumberOfCells="8"') > 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('<DataArray type="Float64" NumberOfComponents="1" Name="rho">') > 0)
def test3(self):
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.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()
contents = data_file.getvalue()
index_of_piece_1 = contents.find('<Piece NumberOfPoints="27" NumberOfCells="8"')
index_of_piece_2 = contents.find('<Piece NumberOfPoints="27" NumberOfCells="8"', index_of_piece_1 + 1)
self.assertTrue(index_of_piece_1 > 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('<DataArray type="Float64" NumberOfComponents="1" Name="rho">') > 0)
| 5,220
| 51.737374
| 112
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_textio.py
|
from amuse.test import amusetest
from io import StringIO
import textwrap
import os
import numpy
import tempfile
from amuse import io
from amuse.io import text
from amuse.units import units
from amuse.units import quantities, core
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()
self.assertEqual("2", instance.line())
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())
instance.forward()
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
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)
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
stream = StringIO()
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):
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])
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):
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)
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
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.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
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
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.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")
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)
self.assertEqual(read.age, daltons.age)
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
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)
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"
data_stream = StringIO(contents)
instance = text.CsvFileText(None, data_stream)
instance.attribute_names = ['a', 'b', 'c']
instance.attribute_types = [units.none, units.m, units.m/units.s]
particles = instance.load()
self.assertEqual(len(particles), 3)
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'),"
"(system.get('S.I.').base('length') / system.get('S.I.').base('time'))\n"
"#none, m, m/s\n1,2,3\n4,5,6\n7,8,9\n")
data_stream = StringIO(contents)
instance = text.CsvFileText(None, data_stream)
particles = instance.load()
self.assertEqual(len(particles), 3)
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"
"#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'))\n"
"#mass,length,length**2 * time**-2 * mass\n1.0,2.0,3.0\n4.0,5.0,6.0\n")
data_stream = StringIO(contents)
instance = text.CsvFileText(None, data_stream)
particles = instance.load()
self.assertEqual(len(particles), 2)
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)
particles.a = [1, 4] | generic_unit_system.mass
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]
instance.store()
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")
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,
"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"
)
self.assertEqual(len(read_particles), 2)
self.assertEqual(read_particles.a, [1, 4])
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")
class Athena3DTextTests(amusetest.TestCase):
def test1(self):
contents = """\
# Nx1 = 128
# x1-size = 1
# Time = 0.103125
#
# [1]=i-zone [2]=x1 [3]=d [4]=M1 [5]=M2 [6]=M3 [7]=P [8]=E [9]=B1c [10]=B2c [11]=B3c [12]=B1i [13]=B1i [14]=B1i
#
4 3.90625e-03 1.00000e+00 -8.66511e-07 4.08477e-07 1.44419e-07 6.00000e-01 2.52500e+00 1.00000e+00 1.41421e+00 5.00000e-01 1.00000e+00 1.41421e+00 5.00000e-01
"""
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)
| 21,551
| 37.832432
| 180
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/__init__.py
| 0
| 0
| 0
|
py
|
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_inmemorystorage.py
|
import numpy
import time
from amuse.test import amusetest
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.set_values_in_store(
(i, j, k),
['a', 'b'],
[2.0 | units.kg, 1.0 | units.m]
)
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.set_values_in_store(
(i, j, k),
['a', 'b'],
[2.0, 1.0]
)
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)
(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(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)
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.set_values_in_store(
(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'])
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'])
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]))
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)
attribute.increase_to_length(5)
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]))
attribute = InMemoryVectorQuantityAttribute('test', quantity.shape, quantity.unit)
attribute.set_values(None, quantity)
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)
def test3(self):
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))
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)
| 4,893
| 35.251852
| 132
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_options.py
|
from amuse.support import options
from amuse.test import amusetest
import io
import textwrap
import os
class OptionsTestsClass(options.OptionalAttributes):
option_sections = ('amuse',)
def string_option(self):
return "default string"
def boolean_option(self):
return False
def int_option(self):
return 2
def float_option(self):
return 2.5
class OptionsTests(amusetest.TestCase):
ini_contents = textwrap.dedent("""
[amuse]
string_option=a string
boolean_option=1
int_option=1
float_option=1.5
[bhtree]
mode=gpu
int_option=3
""")
def test1(self):
global_options = options.GlobalOptions()
global_options.config.read_file(io.StringIO(self.ini_contents))
instance = OptionsTestsClass()
option = options.option(OptionsTestsClass.string_option, global_options=global_options)
self.assertEqual(option.__get__(instance, type(instance)), "a string")
def test2(self):
global_options = options.GlobalOptions()
global_options.config.read_file(io.StringIO(self.ini_contents))
instance = OptionsTestsClass()
option = options.option(OptionsTestsClass.int_option, type="int", global_options=global_options)
self.assertEqual(option.__get__(instance, type(instance)), 1)
option = options.option(OptionsTestsClass.boolean_option, type="boolean", global_options=global_options)
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)
def test3(self):
global_options = options.GlobalOptions()
global_options.config.read_file(io.StringIO(self.ini_contents))
instance = OptionsTestsClass()
instance.option_sections = ('unknown')
option = options.option(OptionsTestsClass.string_option, global_options=global_options)
self.assertEqual(option.__get__(instance, type(instance)), "default string")
option = options.option(OptionsTestsClass.int_option, type="int", global_options=global_options)
self.assertEqual(option.__get__(instance, type(instance)), 2)
option = options.option(OptionsTestsClass.boolean_option, type="boolean", global_options=global_options)
self.assertEqual(option.__get__(instance, type(instance)), False)
option = options.option(OptionsTestsClass.float_option, type="float", global_options=global_options)
self.assertEqual(option.__get__(instance, type(instance)), 2.5)
def test4(self):
global_options = options.GlobalOptions()
global_options.config.read_file(io.StringIO(self.ini_contents))
instance = OptionsTestsClass()
option = options.option(OptionsTestsClass.int_option, type="int", sections=("bhtree",), global_options=global_options)
self.assertEqual(option.__get__(instance, type(instance)), 1)
instance.option_sections = ('unknown')
self.assertEqual(option.__get__(instance, type(instance)), 3)
def test5(self):
global_options = options.GlobalOptions()
global_options.config.read_file(io.StringIO(self.ini_contents))
instance = OptionsTestsClass()
instance.option_sections = ('unknown')
option = options.option(type="int", global_options=global_options)
option = option(OptionsTestsClass.int_option)
self.assertEqual(option.__get__(instance, type(instance)), 2)
def test6(self):
global_options = options.GlobalOptions()
global_options.config.read_file(io.StringIO(self.ini_contents))
class DecoratedMethods(options.OptionalAttributes):
option_sections = ('unknown')
@options.option(type="int", global_options=global_options)
def int_option(self):
return self.i
instance = DecoratedMethods()
instance.i = 10
self.assertEqual(instance.int_option, 10)
def test7(self):
global_options = options.GlobalOptions()
global_options.config.read_file(io.StringIO(self.ini_contents))
class DecoratedMethods(options.OptionalAttributes):
option_sections = ('unknown')
i = 8
def __init__(self, **optional_arguments):
options.OptionalAttributes.__init__(self, **optional_arguments)
@options.option(type="int", global_options=global_options)
def int_option(self):
return self.i
instance = DecoratedMethods()
instance.i = 10
instance.int_option = 12
self.assertEqual(instance.int_option, 12)
instance = DecoratedMethods(int_option=14)
self.assertEqual(instance.int_option, 14)
def test8(self):
global_options = options.GlobalOptions()
global_options.config.read_file(io.StringIO(self.ini_contents))
class A(options.OptionalAttributes):
option_sections = ('amuse')
def __init__(self, **optional_arguments):
options.OptionalAttributes.__init__(self, **optional_arguments)
@options.option(type="int", global_options=global_options)
def int_option_a(self):
return self.i
class B(options.OptionalAttributes):
option_sections = ('amuse')
def __init__(self, **optional_arguments):
options.OptionalAttributes.__init__(self, **optional_arguments)
@options.option(type="int", global_options=global_options)
def int_option_b(self):
return 10
class C(A, B):
def __init__(self, **optional_arguments):
A.__init__(self, **optional_arguments)
B.__init__(self, **optional_arguments)
instance = C(int_option_a=14)
self.assertEqual(instance.int_option_a, 14)
self.assertEqual(instance.int_option_b, 10)
def test9(self):
global_options = options.GlobalOptions()
global_options.config.read_file(io.StringIO(self.ini_contents))
class A(options.OptionalAttributes):
option_sections = ('amuse')
def __init__(self, **optional_arguments):
options.OptionalAttributes.__init__(self, **optional_arguments)
@options.option(type="int", global_options=global_options)
def int_option_a(self):
return self.i
class B(options.OptionalAttributes):
option_sections = ('amuse')
def __init__(self, **optional_arguments):
options.OptionalAttributes.__init__(self, **optional_arguments)
@options.option(type="int", global_options=global_options)
def int_option_b(self):
return 10
class C(A, B):
def __init__(self, **optional_arguments):
A.__init__(self, **optional_arguments)
B.__init__(self, **optional_arguments)
instance = C(int_option_a=14)
self.assertEqual(instance.int_option_a, 14)
self.assertEqual(instance.int_option_b, 10)
def test10(self):
global_options = options.GlobalOptions()
self.assertEqual(global_options.rcfilename, 'amuserc')
global_options.rcfilename = 'test_for_amuserc'
with open(global_options.rcfilename, "w") as f:
f.write(self.ini_contents)
self.assertTrue(global_options.rcfilepath.endswith('test_for_amuserc'))
global_options.load()
instance = OptionsTestsClass()
option = options.option(OptionsTestsClass.int_option, type="int", global_options=global_options)
self.assertEqual(option.__get__(instance, type(instance)), 1)
os.remove(global_options.rcfilepath)
def test11(self):
global_options = options.GlobalOptions()
global_options.config.read_file(io.StringIO(self.ini_contents))
class DecoratedMethods(options.OptionalAttributes):
option_sections = ('amuse',)
def __init__(self, **optional_arguments):
options.OptionalAttributes.__init__(self, **optional_arguments)
@options.option(choices=("1", "2"), global_options=global_options)
def int_option(self):
return 2
instance = DecoratedMethods()
self.assertEqual(instance.int_option, "1")
all_options = list(instance.iter_options())
self.assertEqual(len(all_options), 1)
self.assertEqual(all_options[0].name, "int_option")
def test12(self):
global_options = options.GlobalOptions()
global_options.read_from_ini_string(self.ini_contents)
print(global_options.to_ini_string())
ini_string = global_options.to_ini_string()
self.assertTrue(ini_string.find("= a string") > 0)
| 8,972
| 35.327935
| 126
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_particles.py
|
from amuse.test import amusetest
from amuse.support.exceptions import AmuseException, MissingAttributesAmuseException
from amuse.support.interface import InCodeComponentImplementation
from amuse.support.interface import LinkMethodArgumentOrResultType
from amuse.support.core import compare_version_strings
import numpy
import time
import pickle
import textwrap
import random
from amuse.units import units
from amuse.units import quantities
from amuse.units import constants
from amuse.units import nbody_system
from amuse.units.core import unit_with_specific_dtype
from amuse import datamodel
from amuse.datamodel import incode_storage
from amuse.datamodel import memory_storage
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)
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.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])
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.add_particles(particles2)
particles.remove_particles(particles2)
self.assertEqual(len(particles), 2)
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])
def test5(self):
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)
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)
def test7(self):
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)
def test8(self):
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)
def test9(self):
particles = datamodel.Particles(keys=[10, 11])
particles.mass = [1, 2] | units.kg
outputstring = str(particles)
self.assertEqual(outputstring.strip(), textwrap.dedent("""
key mass
- kg
==================== ===========
10 1.000e+00
11 2.000e+00
==================== ===========""").strip())
def test10(self):
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")
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.synchronize_to(particles2)
self.assertEqual(len(particles2), 4)
self.assertTrue(particles2.has_key_in_store(10))
self.assertTrue(particles2.has_key_in_store(11))
self.assertTrue(particles2.has_key_in_store(12))
self.assertTrue(particles2.has_key_in_store(13))
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
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)
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
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)
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')
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
particles2 = particles.copy_to_new_particles()
self.assertAlmostRelativeEquals(particles2.mass, [1, 2] | units.kg)
self.assertAlmostRelativeEquals(particles2[1].mass, 2 | units.kg)
self.assertNotEqual(particles[1].key, particles2[1].key)
def test16(self):
random.seed(12345)
particles = datamodel.Particles(10000)
subset = particles.random_sample(2500)
self.assertEqual(len(subset), 2500)
self.assertEqual(len(particles.difference(subset)), 7500)
subset2 = particles.random_sample(4000)
self.assertEqual(len(subset2), 4000)
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 < 1025)
def test17(self):
names = ('123', '1234', '12345')
particles = datamodel.Particles(3)
particles.name = names
for i in range(3):
self.assertEqual(particles[i].name, names[i])
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)
del particles.radius
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[0].child = particles2[0]
particles[1].child = particles2[1]
outputstring = str(particles)
self.assertEqual(outputstring.strip(), textwrap.dedent("""
key child mass
- none kg
==================== =========== ===========
10 12 1.000e+00
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[0].child = particles2[0]
particles[1].child = particles2[1]
outputstring = str(particles[0])
print(outputstring)
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
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
particle = particles[1]
self.assertAlmostRelativeEquals(particle.mass, 2 | units.kg)
particles.remove_particle(particles[0])
self.assertAlmostRelativeEquals(particle.mass, 2 | units.kg)
self.assertAlmostRelativeEquals(particles[0].mass, 2 | units.kg)
def test3(self):
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
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
self.assertAlmostRelativeEquals(particles[0].xy, 8 | units.m*units.m)
def test6(self):
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
particle = particles[0]
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)
def test7(self):
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
particle = particles[0]
attributes = set(dir(particle))
self.assertTrue('x' in attributes)
self.assertTrue('y' in attributes)
self.assertTrue('position2d' in attributes)
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
particle1 = particles1[0]
particle2 = particles2[0]
self.assertEqual(particle1, particle2)
self.assertNotEqual(particle1, particles2[1])
particle12 = particle1.as_particle_in_set(particles2)
self.assertEqual(particle12, particle2)
self.assertEqual(particle12, particle1)
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
i = 1
for particle in particles:
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.add_function_attribute(
"xy",
lambda allparticles, a: (allparticles.x * allparticles.y) + a,
lambda allparticles, one, a: (one.x * one.y) + (2*a)
)
print(particles.xy)
self.assertAlmostRelativeEquals(
particles.xy(2.0 | units.m*units.m),
[5, 10] | units.m*units.m
)
self.assertAlmostRelativeEquals(
particles[0].xy(2.0 | units.m*units.m),
7 | units.m*units.m
)
def test11(self):
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])
particles.remove_particle(particles[1])
self.assertAlmostRelativeEquals(particle.mass, 2 | units.kg)
self.assertAlmostRelativeEquals(particles[0].mass, 2 | units.kg)
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
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
self.assertAlmostRelativeEquals(particles[0].mass, 1 | units.kg)
copy = particles[0].empty_copy()
self.assertFalse(hasattr(copy, 'mass'))
self.assertTrue(hasattr(particles[0], 'mass'))
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)
self.assertEqual(len(particles[0:2]), 2)
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
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)
def test3(self):
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)
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
subset = particles[0:2]
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)
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)
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.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)
def test7(self):
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)
union = subset1.union(subset2)
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
subset = particles[0:2]
particle = subset[0]
self.assertAlmostRelativeEquals(particle.mass, 1 | 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(particle.mass, 3 | units.kg)
def test9(self):
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))
self.assertAlmostRelativeEquals(particle.mass, 1 | 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(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
subset = particles[0:]
i = 1
for particle in subset:
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
subset = particles[0:]
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
subset = particles[0:]
subset.add_calculated_attribute("xy", lambda x, y: x * y)
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)
def test13(self):
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
subset = particles[0:2]
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)
def test14(self):
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)
def test16(self):
set1 = datamodel.Particles(3)
set1.x = [1.0, 2.0, 3.0] | units.kg
subset1 = set1[0:2]
subset2 = set1[1:3]
self.assertAlmostRelativeEquals(subset1.x, [1.0, 2.0] | units.kg)
self.assertAlmostRelativeEquals(subset2.x, [2.0, 3.0] | units.kg)
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.x = [1.0, 2.0, 3.0] | units.kg
subset1 = set1[0:2]
subset2 = set1[1:3]
self.assertAlmostRelativeEquals(subset1.x, [1.0, 2.0] | units.kg)
self.assertAlmostRelativeEquals(subset2.x, [2.0, 3.0] | units.kg)
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.x = [1.0, 2.0, 3.0] | units.kg
subset1 = set1[0:2]
subset2 = set1[1:3]
self.assertAlmostRelativeEquals(subset1.x, [1.0, 2.0] | units.kg)
self.assertAlmostRelativeEquals(subset2.x, [2.0, 3.0] | units.kg)
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.add_caching_function_attribute(
"xy",
lambda allparticles: (allparticles.x * allparticles.y),
lambda allparticles, one: (one.x * one.y)
)
self.assertAlmostRelativeEquals(
particles.xy(),
[3, 8] | units.m*units.m
)
self.assertAlmostRelativeEquals(
particles[0].xy(),
3 | units.m*units.m
)
particles.x = [5, 6] | units.m
self.assertAlmostRelativeEquals(
particles.xy(),
[3, 8] | units.m*units.m
)
self.assertAlmostRelativeEquals(
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
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)
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)
def test2(self):
particles1 = datamodel.Particles(keys=[10, 11])
particles1.mass = [1, 2] | 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)
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)
def test3(self):
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
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)
channel.copy_attribute("mass")
self.assertAlmostRelativeEquals(particles2.mass, [2, 1] | units.kg)
def test4(self):
particles1 = datamodel.Particles(2)
particles1.mass = 1 | units.kg
particles2 = particles1.copy()
particles2.stellar_mass = range(2) | units.kg
particles2.mass = 0 | units.kg
self.assertFalse(hasattr(particles1, 'stellar_mass'))
channel = particles2.new_channel_to(particles1)
channel.copy_overlapping_attributes()
self.assertFalse(hasattr(particles1, 'stellar_mass'))
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)
def test5(self):
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
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)
def test6(self):
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
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)
def test7(self):
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
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
channel.copy()
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
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)
channel = particles2.new_channel_to(particles1)
channel.copy()
particles2.remove_particle(particles2[1])
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)
def test9(self):
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
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
channel.copy()
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
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)
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)
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)
def test11(self):
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
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)
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)
def test12(self):
""" Test Channels add channel"""
channel1, channel2, p1, p2 = self.setup_test_channels()
channels = datamodel.Channels()
channels.add_channel(channel1)
channels.add_channel(channel2)
channels.copy()
self.assertAlmostRelativeEquals(p2.mass, [1, 2] | units.kg)
self.assertAlmostRelativeEquals(p1.x, [11, 13] | units.m)
def test13(self):
""" Test Channels add channels"""
channel1, channel2, p1, p2 = self.setup_test_channels()
channels = datamodel.Channels()
channels.add_channels([channel1, channel2])
channels.copy()
self.assertAlmostRelativeEquals(p2.mass, [1, 2] | units.kg)
self.assertAlmostRelativeEquals(p1.x, [11, 13] | units.m)
def test14(self):
""" Test Channels add channels"""
channel1, channel2, p1, p2 = self.setup_test_channels()
channels = datamodel.Channels([channel1, channel2])
channels.copy()
self.assertAlmostRelativeEquals(p2.mass, [1, 2] | units.kg)
self.assertAlmostRelativeEquals(p1.x, [11, 13] | units.m)
def test15(self):
""" Test Channels add channels"""
channel1, channel2, p1, p2 = self.setup_test_channels()
channels = datamodel.Channels()
channels.add_channel(channel1)
channels2 = datamodel.Channels()
channels2.add_channel(channel2)
channels2.add_channels(channels)
channels2.copy()
self.assertAlmostRelativeEquals(p2.mass, [1, 2] | units.kg)
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
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'])
return channel1, channel2, particles1, particles2
def test16(self):
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])
channel = particles1.new_channel_to(particles2)
channel.transform(["momentum"], lambda x, y: (x*y,), ["mass", "vx"])
self.assertEqual(particles2.momentum, [2*12, 1*10] | units.kg*units.m/units.s)
channel.transform(["vx_by_another_name"], None, ["vx"])
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
self.assertEqual(len(superset), 6)
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
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)
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
i = 1
for particle in superset:
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)
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.add_vector_attribute('position2d', ['x', 'y'])
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
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.add_vector_attribute('position2d', ['x', 'y'])
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)
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)
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
superset.add_particles(particles3)
self.assertEqual(len(superset), 9)
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)
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)
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)
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_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
particle_in_copy = particles1_copy[1]
particle_in_superset = superset[1]
self.assertAlmostRelativeEquals(particle_in_copy.mass, 6 | units.kg)
self.assertAlmostRelativeEquals(particle_in_superset.mass, 2 | units.kg)
particles_in_original = particle_in_copy.as_particle_in_set(superset)
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
particles2 = datamodel.Particles()
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
self.assertEqual(superset.get_attribute_names_defined_in_store(), ["mass"])
def test14(self):
particles1 = datamodel.Particles(3)
particles1.name = '123'
particles2 = datamodel.Particles(3)
particles2.name = '1234'
superset = particles1 | particles2
for i in range(3):
self.assertEqual(superset[i].name, '123')
self.assertEqual(superset.name[i], '123')
self.assertEqual(superset[i+3].name, '1234')
self.assertEqual(superset.name[i+3], '1234')
superset[2:4].name = '12345'
self.assertEqual(superset[1].name, '123')
self.assertEqual(superset.name[1], '123')
self.assertEqual(superset[2].name, '12345')
self.assertEqual(superset.name[2], '12345')
self.assertEqual(superset[3].name, '12345')
self.assertEqual(superset.name[3], '12345')
self.assertEqual(superset[4].name, '1234')
self.assertEqual(superset.name[4], '1234')
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
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"])
self.assertEqual(particles.get_attribute_names_defined_in_store(), ["mass", "radius"])
self.assertEqual(particles.get_settable_attribute_names_defined_in_store(), ["mass", "radius"])
self.assertTrue(particles.can_extend_attributes())
self.assertFalse(particles1.can_extend_attributes())
def test2(self):
particles = datamodel.Particles(3)
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
print(particles1)
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
particles1 = datamodel.ParticlesWithFilteredAttributes(particles, ["mass"])
def set_mass():
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
superset = datamodel.ParticlesSuperset(
[particles1, particles2],
names=['one', 'two']
)
self.assertEqual(len(superset), 6)
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)
particles_2 = superset.get_subset('two')
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
superset = datamodel.ParticlesSuperset(
[particles1, particles2],
names=['one', 'two']
)
self.assertEqual(len(superset), 6)
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)
particles_2 = superset['two']
self.assertAlmostRelativeEquals(particles_2.mass, [20, 21] | units.kg)
class TestParticlesExtra(amusetest.TestCase):
def test1(self):
particles = datamodel.Particles(2)
for i in range(3):
particles.mass = (i * 1.0) | units.kg
particles.savepoint((i + 1) * 1.0 | units.s)
masses = particles[0].get_timeline_of_attribute("mass")
self.assertEqual(len(masses), 3)
self.assertEqual(masses[0][0], 1.0 | units.s)
self.assertEqual(masses[1][0], 2.0 | units.s)
self.assertEqual(masses[2][0], 3.0 | units.s)
def test2(self):
particles = datamodel.Particles(2)
particles.mass = [1, 1] | units.kg
heavy = particles.select(lambda m: m > 1 | units.kg, ["mass"])
self.assertTrue(heavy.is_empty())
def test3(self):
particles = datamodel.Particles(2)
for i in range(3):
particles.mass = (i * 2.0) | units.kg
particles.savepoint((i + 1) * 1.0 | units.s)
state0 = particles.get_state_at_timestamp(2.0 | units.s)
self.assertEqual(state0[0].mass, 2.0 | units.kg)
state0 = particles.get_state_at_timestamp(2.4 | units.s)
self.assertEqual(state0[0].mass, 2.0 | units.kg)
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)
particles.mass = 1.0 | units.kg
particles.vy = 1.0 | units.m / units.s
particles.vx = 0.0 | units.m / units.s
particles.vz = 0.0 | units.m / units.s
particles.x = [0.0, 1.0] | units.m
particles.y = 0.0 | units.m
particles.z = 0.0 | units.m
self.assertEqual(particles.kinetic_energy(), 1.0 | units.J)
self.assertEqual(particles.potential_energy(), -1.0 * constants.G * (1.0 | units.kg ** 2 / units.m))
self.assertEqual(particles.center_of_mass().x, 0.5 | units.m)
self.assertEqual(particles.center_of_mass().y, 0.0 | units.m)
self.assertEqual(particles.center_of_mass().z, 0.0 | units.m)
self.assertEqual(particles.center_of_mass_velocity().x, 0.0 | units.m / units.s)
self.assertEqual(particles.center_of_mass_velocity().y, 1.0 | units.m / units.s)
self.assertEqual(particles.center_of_mass_velocity().z, 0.0 | units.m / units.s)
def test5(self):
particles = datamodel.Particles(4)
particles.mass = 1.0 | units.kg
particles[2].mass = 2.0 | units.kg
subset = particles.select_array(lambda mass: mass > 1.0 | units.kg, ["mass"])
self.assertEqual(len(subset), 1)
copyof_subset = subset.copy()
self.assertEqual(len(copyof_subset), 1)
def test6(self):
particles = datamodel.Particles(2)
particles.mass = 1.0 | units.kg
particles.vy = 1.0 | units.m / units.s
particles.vx = 0.0 | units.m / units.s
particles.vz = 0.0 | units.m / units.s
particles.x = [0.0, 1.0] | units.m
particles.y = 0.0 | units.m
particles.z = 0.0 | 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
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)
for i in range(10):
particles[i].mass = (i * 1.0) | units.kg
def test8(self):
particles = datamodel.Particles(4)
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
for x in particles:
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.assertAlmostRelativeEquals(0.5*(particles.mass*particles.potential()).sum(), Ep)
def test10(self):
particles = datamodel.Particles(4)
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)
subset.set_values_in_store(None, ['mass'], [6.0 | 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.nounit = range(3)
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[0].child = particles[1]
particles[1].child = particles[2]
print(particles[0].child)
print(particles[1].child)
print(particles[2].child)
self.assertEqual(particles[0].child, particles[1])
self.assertEqual(particles[1].child, particles[2])
self.assertEqual(particles[2].child, None)
def test15(self):
particles = datamodel.Particles(10)
# List of scalar quantities:
masses = [i | nbody_system.mass for i in range(10)]
particles.mass = masses
print(particles.mass)
self.assertEqual(particles.mass, range(10) | nbody_system.mass)
# List of vector quantities:
positions = [(i, 2*i, 3*i) | units.m for i in range(10)]
particles.position = positions
self.assertEqual(particles.position, [(i, 2*i, 3*i) for i in range(10)] | units.m)
# Even lists of tuples of quantities work:
positions = [(i | units.m, i | units.cm, i | units.km) for i in range(10)]
particles.position = positions
self.assertEqual(particles.position, [(i, 0.01*i, 1000*i) for i in range(10)] | units.m)
def test16(self):
particles = datamodel.Particles(2)
particles.add_vector_attribute('unitless', ['u1', 'u2', 'u3'])
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].u1, 7)
self.assertEqual(particles.unitless, [[7, 8, 9], [4, 5, 6]])
def test17(self):
particles = datamodel.Particles(2)
particles.a = [1.0, 2.0]
self.assertEqual(particles[0].a, 1.0)
particles.b = 3.0
self.assertEqual(particles[0].b, 3.0)
self.assertEqual(particles[1].b, 3.0)
self.assertAlmostRelativeEquals(particles.b, [3.0, 3.0])
particles[0].b = 4.0
self.assertAlmostRelativeEquals(particles.b, [4.0, 3.0])
particles[1].a = 5.0
self.assertAlmostRelativeEquals(particles.a, [1.0, 5.0])
def test18(self):
particles = datamodel.Particles(3)
particles.mass = [1.0, 2.0, 3.0] | units.kg
self.assertTrue(particles[1] in particles)
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)
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.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.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.assertEqual(len(particles), 3)
self.assertAlmostRelativeEquals(particles.a, [2, 2, 2])
self.assertAlmostRelativeEquals(particles.b, [1.0, 1.0, 1.0])
def test20(self):
particles = datamodel.Particles(3)
particles.a = numpy.array([1.0, 2.0, 3.0])
self.assertEqual(particles[0].a, 1.0)
# should be able to set the attribute with a unitless array
# this code will be obsoleted when units.none is completely gone
particles.a = [4.0, 5.0, 6.0] | units.none
self.assertEqual(particles[0].a, 4.0)
particles.b = [1, 2, 3] | units.none
self.assertEqual(particles[0].b, 1 | units.none)
particles.b = [4, 5, 6]
self.assertEqual(particles[0].b, 4 | units.none)
def test21(self):
particles = datamodel.Particles(3)
particles.z = quantities.zero
print(particles.z, particles[0].z)
self.assertEqual(particles[0].z, quantities.zero)
particles.z += 1 | units.kg
self.assertEqual(particles[0].z, 1 | units.kg)
print(particles[0].z)
self.assertEqual(particles.z.unit, units.kg)
def test22(self):
particles = datamodel.Particles(3)
particles.z = quantities.zero
particles.z = 1 | units.kg
self.assertEqual(particles[0].z, 1 | units.kg)
self.assertEqual(particles.z.unit, units.kg)
def test23(self):
p = datamodel.Particles(3)
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])
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[1].mass = 10 | units.g
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[1].mass = 10 | units.g
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[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]))
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].y = 2000.0 | units.m
stars[0].z = 3500.0 | units.m
self.assertEqual(stars.position[0], [1000.0, 2000.0, 3500.0] | units.m)
def test5(self):
stars = datamodel.Particles(2)
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.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])
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)
def test6(self):
stars = datamodel.Particles(2)
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)
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)
class TestParticlesWithBinding(amusetest.TestCase):
class TestLegacyCode(object):
def __init__(self):
self.masses = {}
self.links = {}
self.grids = {}
def get_mass(self, id):
masses = []
errors = []
for x in id:
masses.append(self.masses[x])
errors.append(0)
return (masses, errors, )
def set_mass(self, id, mass):
for i, m in zip(id, mass):
self.masses[i] = m
return ([0] * len(id),)
def get_radius(self, id):
masses = []
errors = []
for x in id:
masses.append(1)
errors.append(0)
return (masses, errors, )
def get_link(self, id):
result = []
errors = []
for x in id:
result.append(self.links[x])
errors.append(0)
return (result, errors, )
def set_link(self, id, link):
for i, l in zip(id, link):
self.links[i] = l
return ([0] * len(id),)
def get_grid(self, id, index1, index2):
result = []
errors = []
for x, i1, i2 in zip(id, index1, index2):
result.append(self.grids[x][i1][i2])
errors.append(0)
return (result, errors, )
def set_grid(self, id, index1, index2, value):
errors = []
for x, i1, i2, v in zip(id, index1, index2, value):
self.grids[x][i1][i2] = v
errors.append(0)
return (0, )
def get_grid_range(self):
return (0, 3, 0, 2)
def new_particle(self, mass):
ids = []
errors = []
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)
ids.append(index)
errors.append(0)
return (ids, errors)
def delete_particle(self, ids):
errors = []
for x in ids:
del self.masses[x]
del self.links[x]
errors.append(0)
return errors
def get_number_of_particles(self):
return (len(self.masses), 0)
set_state = set_mass
get_state = get_mass
class TestInterface(InCodeComponentImplementation):
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,))
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_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',))
class TestInterfaceSuperset(InCodeComponentImplementation):
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,))
def define_particle_sets(self, handler):
handler.define_super_set(
'particles',
['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_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.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_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',))
def test1(self):
interface = self.TestInterface()
interface.particles.add_particles_to_store(
[1, 2],
["mass"],
[[3.0, 4.0] | units.kg]
)
remote_particles = interface.particles
local_particles = remote_particles.copy()
channel = remote_particles.new_channel_to(local_particles)
self.assertEqual(interface.masses[0], 3000)
interface.masses[0] = 3500
self.assertEqual(remote_particles[0].mass.value_in(units.kg), 3.5)
self.assertEqual(local_particles[0].mass.value_in(units.kg), 3.0)
channel.copy_attributes(["mass"])
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(
[1, 2],
["mass"],
[[3.0, 4.0] | units.kg]
)
remote_particles = interface.particles
self.assertEqual(len(remote_particles), 2)
interface.particles.add_particles_to_store(
[3, 4],
["mass"],
[[5.0, 6.0] | units.kg]
)
self.assertEqual(len(remote_particles), 4)
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)
interface.particles.remove_particle(remote_particles[0])
interface.particles.remove_particle(remote_particles[1])
self.assertEqual(len(remote_particles), 2)
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)
self.assertEqual(len(remote_particles), 2)
local_particles2 = datamodel.Particles(2)
local_particles2.mass = units.kg.new_quantity([5.0, 6.0])
remote_particles.add_particles(local_particles2)
self.assertEqual(len(remote_particles), 4)
self.assertEqual(remote_particles[0].mass.value_in(units.kg), 3)
self.assertEqual(remote_particles[2].mass.value_in(units.kg), 5)
set = datamodel.Particles()
set.add_particle(remote_particles[0])
set.add_particle(remote_particles[2])
interface.particles.remove_particles(set)
self.assertEqual(len(remote_particles), 2)
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)
self.assertEqual(len(remote_particles), 2)
particle = datamodel.Particle()
particle.mass = units.g.new_quantity(10.0)
local_particles.add_particle(particle)
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)
local_particles2 = datamodel.Particles(3)
local_particles2.mass = units.kg.new_quantity([5.0, 6.0, 7.0])
local_particles1.add_particles(local_particles2)
self.assertEqual(len(local_particles1), 5)
self.assertEqual(len(local_particles2), 3)
local_particles1.synchronize_to(remote_particles)
local_particles1.remove_particle(local_particles1[0])
local_particles1.synchronize_to(remote_particles)
self.assertEqual(len(remote_particles), 4)
def test6(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)
local_particle = datamodel.Particle()
local_particle.mass = units.kg.new_quantity(5.0)
local_particles1.add_particle(local_particle)
self.assertEqual(len(local_particles1), 3)
self.assertEqual(len(remote_particles), 2)
local_particles1.synchronize_to(remote_particles)
self.assertEqual(len(remote_particles), 3)
remote_particles.remove_particle(local_particle)
self.assertEqual(len(remote_particles), 2)
def test7(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)
local_particles.unknown_attribute = [3.0, 4.0] | units.m
local_particles.mass = [1, 3] | units.kg
channel = local_particles.new_channel_to(remote_particles)
self.assertRaises(Exception, channel.copy_all_attributes)
channel.copy()
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)
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)
self.assertEqual(remote_particles.link[1], None)
remote_particles[0].link = remote_particles[1]
self.assertEqual(remote_particles.link[0], remote_particles[1])
self.assertEqual(remote_particles.link[0], local_particles1[1])
self.assertEqual(remote_particles.link[1], None)
channel = remote_particles.new_channel_to(local_particles1)
channel.copy_all_attributes()
self.assertEqual(local_particles1.link[0], remote_particles[1])
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)
self.assertEqual(remote_particles.grid[0][1][2], 5 | units.g)
def test11(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)
channel = remote_particles.new_channel_to(local_particles)
channel.copy()
self.assertEqual(local_particles[0].grid[1][2], 5 | units.g)
self.assertEqual(local_particles.grid[0][1][2], 5 | units.g)
channel = local_particles.new_channel_to(remote_particles)
channel.copy()
def test12(self):
interface = self.TestInterface()
local_particles = datamodel.Particles(4)
local_particles.mass = units.kg.new_quantity([3.0, 4.0, 5.0, 6.0])
remote_particles = interface.particles
remote_particles.add_particles(local_particles)
query = incode_storage.ParticleQueryMethod(
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)
def test13(self):
interface = self.TestInterfaceSuperset()
local_particles1 = datamodel.Particles(2)
local_particles1.mass = units.kg.new_quantity([3.0, 4.0])
local_particles2 = datamodel.Particles(2)
local_particles2.mass = units.kg.new_quantity([5.0, 6.0])
interface.particles1.add_particles(local_particles1)
interface.particles2.add_particles(local_particles2)
query = incode_storage.ParticleQueryMethod(
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)
def test14(self):
interface = self.TestInterfaceSuperset()
local_particles1 = datamodel.Particles(2)
local_particles1.mass = units.kg.new_quantity([3.0, 4.0])
local_particles2 = datamodel.Particles(2)
local_particles2.mass = units.kg.new_quantity([5.0, 6.0])
interface.particles1.add_particles(local_particles1)
interface.particles2.add_particles(local_particles2)
query = incode_storage.ParticleQueryMethod(
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)
def test15(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)
local_particles.mass = 10 | 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)
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)
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)
def test16(self):
local_particles = datamodel.Particles(2)
interface = self.TestInterface()
self.assertRaises(MissingAttributesAmuseException, interface.particles.add_particles, local_particles,
expected_message="To add particles to this code you need to specify the 'mass' attribute")
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)
class TestInterface2(InCodeComponentImplementation):
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,))
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',))
def test17(self):
interface = self.TestInterface2()
interface.particles.add_particles_to_store(
[1, 2],
["mass"],
[[3.0, 4.0] | units.kg]
)
remote_particles = interface.particles
local_particles = remote_particles.copy()
channel = remote_particles.new_channel_to(local_particles)
self.assertEqual(local_particles[0].radius.value_in(units.m), 1)
channel = local_particles.new_channel_to(remote_particles)
local_particles.radius = 10 | units.m
local_particles.mass = 3.5 | units.kg
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
subset1 = set1[0:2]
subset2 = set1[1:3]
self.assertAlmostRelativeEquals(subset1.mass, [1.0, 2.0] | units.kg)
self.assertAlmostRelativeEquals(subset2.mass, [2.0, 3.0] | units.kg)
subset1.remove_particle(subset1[1])
self.assertAlmostRelativeEquals(subset1.mass, [1.0] | units.kg)
self.assertAlmostRelativeEquals(subset2.mass, [3.0] | units.kg)
class TestParticlesWithUnitsConverted(amusetest.TestCase):
def test1(self):
stars = datamodel.Particles(2)
stars[0].mass = 10 | units.g
stars[1].mass = 20 | units.g
class LengthMassConverter(object):
"source == length, m"
"target == mass, g"
source_unit = units.m
target_unit = units.g
def from_source_to_target(self, quantity):
value = quantity.value_in(self.source_unit)
return self.target_unit.new_quantity(value)
def from_target_to_source(self, quantity):
value = quantity.value_in(self.target_unit)
return self.source_unit.new_quantity(value)
converted_stars = datamodel.ParticlesWithUnitsConverted(stars, LengthMassConverter())
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)
stars = datamodel.Particles(1)
stars[0].mass = 10 | nbody_system.mass
stars[0].x = 10.0 | nbody_system.length
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())
self.assertEqual(stars[0].mass, 10 | nbody_system.mass)
self.assertAlmostEqual(converted_stars[0].mass, 100.0 | units.kg, 5)
converted_star = converted_stars[0]
expected = units.m.new_quantity([50.0, 100.0, 150.0])
for i in range(3):
self.assertAlmostEqual(converted_star.position[i], expected[i], 6)
converted_star.position = [100.0, 200.0, 300.0] | units.m
star = stars[0]
expected = nbody_system.length([20.0, 40.0, 60.0])
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)
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)
i = 1
for particle in particles:
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)
stars = datamodel.Particles(1)
converted_stars = datamodel.ParticlesWithUnitsConverted(
stars,
convert_nbody.as_converter_from_si_to_generic()
)
stars.stellar_type = units.stellar_type("Main Sequence star")
print(stars.stellar_type)
print(converted_stars.stellar_type)
self.assertEqual(stars[0].stellar_type, units.stellar_type("Main Sequence star"))
self.assertEqual(converted_stars[0].stellar_type, units.stellar_type("Main Sequence star"))
class TestParticlesWithTransformedAttributes(amusetest.TestCase):
def test1(self):
stars = datamodel.Particles(2)
stars[0].mass = 10 | units.g
stars[1].mass = 20 | units.g
def get_function(attribute, quantity):
return quantity * 2
def set_function(attribute, quantity):
return quantity / 2
converted_stars = datamodel.ParticlesWithAttributesTransformed(
stars,
get_function,
set_function
)
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)
converted_stars[0].mass = 40 | units.g
self.assertEqual(stars[0].mass, 20 | units.g)
def test2(self):
stars = datamodel.Particles(2)
stars[0].mass = 10 | units.g
stars[1].mass = 20 | units.g
def get_function(attribute, quantity):
return quantity * 2
def set_function(attribute, quantity):
return quantity / 2
converted_stars = datamodel.ParticlesWithAttributesTransformed(
stars,
get_function,
set_function
)
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)
stars.add_particle(p)
self.assertEqual(stars[3].mass, 100. | units.g)
self.assertEqual(converted_stars[3].mass, 200 | units.g)
def test3(self):
stars = datamodel.Particles(3)
stars[0].mass = 10 | units.g
stars[1].mass = 20 | units.g
stars[2].mass = 30 | units.g
def get_function(attribute, quantity):
return quantity * 2
def set_function(attribute, quantity):
return quantity / 2
converted_stars = datamodel.ParticlesWithAttributesTransformed(
stars,
get_function,
set_function
)
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
self.assertEqual(converted_stars[0].mass, 2 | units.g)
self.assertEqual(sub[0].mass, 2 | 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[1].mass = 1 | units.MSun
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()
converted_stars = datamodel.ParticlesWithAttributesTransformed.translate(
stars,
-com,
-cov
)
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)
class TestTransformedParticles(amusetest.TestCase):
def test1(self):
stars = datamodel.Particles(2)
stars[0].mass = 10 | units.g
stars[1].mass = 20 | units.g
def forward_transformation(mass):
return [2*mass]
def backward_transformation(mass):
return [mass/2]
converted_stars = datamodel.TransformedParticles(
stars,
["mass"],
forward_transformation,
["mass"],
backward_transformation
)
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)
converted_stars[0].mass = 40 | units.g
self.assertEqual(stars[0].mass, 20 | units.g)
self.assertEqual(converted_stars[0].mass, 40 | units.g)
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
def forward_transformation(x, y):
return (x+y, x-y)
def backward_transformation(x, y):
return [(x+y)/2, (x-y)/2]
converted_stars = datamodel.TransformedParticles(
stars,
["x", "y"],
forward_transformation,
["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)
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)
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(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
def forward_transformation(x, y):
return (x+y, x-y)
def backward_transformation(x, y):
return [(x+y)/2, (x-y)/2]
converted_stars = datamodel.TransformedParticles(
stars,
["x", "y"],
forward_transformation,
["x", "y"],
backward_transformation
)
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)
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)
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[1].mass = 1 | units.MSun
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()
converted_stars = datamodel.TransformedParticles.translate(
stars,
-com,
-cov
)
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)
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[1].mass = 1 | units.MSun
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
converted_stars = datamodel.TransformedParticles.rotate_z(
stars,
angle,
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)
angle = numpy.pi/2
omega = 2 * numpy.pi | units.rad/units.yr
converted_stars = datamodel.TransformedParticles.rotate_z(
stars,
angle,
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)
class TestParticlesWithChildren(amusetest.TestCase):
def test1(self):
particles = datamodel.Particles(3)
parent = particles[0]
child1 = particles[1]
child2 = particles[2]
parent.add_child(child1)
parent.add_child(child2)
self.assertEqual(child1.parent.key, parent.key)
self.assertEqual(child2.parent.key, parent.key)
children = parent.children()
self.assertEqual(len(children), 2)
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:
# x.grid = numpy.arange(12).reshape(4,3)
parent = particles[0]
child1 = particles[1]
child2 = particles[2]
parent.add_child(child1)
parent.add_child(child2)
outputstr = str(particles)
print(outputstr)
self.assertTrue(" 4.000e+00 --" in outputstr)
code1.particles.add_particles(parent.as_set())
code2.particles.add_particles(parent.children())
self.assertEqual(len(parent.children()), 2)
self.assertEqual(len(code1.particles), 1)
self.assertEqual(len(code2.particles), 2)
code1.legacy_interface.set_mass([0], [10000.0])
code2.legacy_interface.set_mass([0], [9000.0])
self.assertEqual(parent.mass, 4.0 | units.kg)
self.assertEqual(child1.mass, 3.0 | units.kg)
code1.particles.new_channel_to(particles).copy_attribute("mass")
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]
child1 = particles[1]
child2 = particles[2]
parent.add_child(child1)
parent.add_child(child2)
self.assertEqual(parent.parent, None)
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())
self.assertEqual(len(code1.particles), 3)
self.assertEqual(len(code2.particles), 2)
def test4(self):
particles = datamodel.Particles(5)
particles.mass = [1.0, 2.0, 3.0, 4.0, 5.0] | units.kg
parent = particles[0]
child1 = particles[1]
child2 = particles[2]
child3 = particles[3]
child4 = particles[4]
parent.add_child(child1)
child1.add_child(child2)
child2.add_child(child3)
child3.add_child(child4)
self.assertEqual(len(parent.children()), 1)
self.assertEqual(len(parent.descendents()), 4)
self.assertEqual(len(child1.descendents()), 3)
self.assertEqual(len(child2.descendents()), 2)
self.assertEqual(len(child3.descendents()), 1)
def test5(self):
particles = datamodel.Particles(5)
particles.mass = [1.0, 2.0, 3.0, 4.0, 5.0] | units.kg
parent = particles[0]
child1 = particles[1]
child2 = particles[2]
child3 = particles[3]
child4 = particles[4]
parent.add_child(child1)
child1.add_child(child2)
child2.add_child(child3)
child3.add_child(child4)
copy = particles.copy()
self.assertEqual(copy[0].parent, None)
self.assertEqual(copy[1].parent, copy[0])
self.assertEqual(copy[2].parent, copy[1])
self.assertEqual(copy[3].parent, copy[2])
self.assertEqual(copy[4].parent, copy[3])
self.assertEqual(copy[1].parent, parent)
self.assertEqual(len(copy[0].descendents()), 4)
def test6(self):
class Dummy(object):
@property
def definition(self):
return self
@property
def handler(self):
return self
@property
def interface(self):
return self._interface
class Code(object):
def __init__(self):
self.data = []
self.number_of_particles = 0
self.link_type = LinkMethodArgumentOrResultType("particles")
self.definition = Dummy()
self.definition.wrapped_object = self
self.definition._interface = self
def get_number_of_particles(self):
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):
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):
return self.link_type.convert_result_value(None, self.definition, number)
def new_particle(self, mass):
mass = mass.value_in(units.kg)
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 = incode_storage.ParticleGetAttributesMethod(
code.get_children,
('child1', 'child2',)
)
storage = incode_storage.InCodeAttributeStorage(
code,
incode_storage.NewParticleMethod(code.new_particle, ("mass",)),
None,
code.get_number_of_particles,
[],
[
incode_storage.ParticleGetAttributesMethod(code.get_mass, ("mass",)),
children_getter
],
name_of_the_index="index"
)
storage.add_particles_to_store(
numpy.asarray([100, 200, 300, 400], dtype='uint64'),
["mass"],
[
units.kg([1, 2, 3, 4]),
]
)
code.data[0][1] = 1
code.data[0][2] = 2
code.particles = datamodel.Particles(storage=storage)
x = code.particles
print(code.get_children([0]))
print(x[0].child1)
self.assertEqual(x[0].mass, 1.0 | units.kg)
self.assertEqual(x[0].child1.mass, 2.0 | units.kg)
self.assertEqual(x[0].child2.mass, 3.0 | units.kg)
self.assertEqual(x[1].child1, None)
self.assertEqual(x[1].child2, None)
code.data[1][1] = 3
code.data[1][2] = 2
self.assertEqual(x[0].child1, x[1])
self.assertEqual(x[0].child1.child1.mass, 4.0 | units.kg)
self.assertEqual(x[0].child1.child2.mass, 3.0 | units.kg)
def test7(self):
class Dummy(object):
@property
def definition(self):
return self
@property
def handler(self):
return self
@property
def interface(self):
return self._interface
class Code(object):
def __init__(self):
self.data = []
self.number_of_particles = 0
self.link_type = LinkMethodArgumentOrResultType("particles")
self.definition = Dummy()
self.definition._interface = self
self.definition.wrapped_object = self
def get_number_of_particles(self):
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):
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):
return self.link_type.convert_result_value(None, self.definition, number)
def new_particle(self, mass):
mass = mass.value_in(units.kg)
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 = incode_storage.ParticleGetAttributesMethod(
code.get_children,
('child1', 'child2',)
)
storage = incode_storage.InCodeAttributeStorage(
code,
incode_storage.NewParticleMethod(code.new_particle, ("mass",)),
None,
code.get_number_of_particles,
[],
[
incode_storage.ParticleGetAttributesMethod(code.get_mass, ("mass",)),
children_getter
],
name_of_the_index="index"
)
code_particles = datamodel.Particles(storage=storage)
code.particles = code_particles
memory_particles = datamodel.Particles(keys=100 * (1 + numpy.arange(10)))
memory_particles.mass = range(10) | units.kg
code_particles.add_particles(memory_particles)
self.assertEqual(len(code_particles), 10)
code.data[0][1] = 1
code.data[0][2] = 2
code.data[1][1] = 3
code.data[1][2] = 4
self.assertEqual(code_particles[0].child1, code_particles[1])
self.assertEqual(code_particles[0].child1.mass, 1.0 | units.kg)
self.assertEqual(code_particles[0].child2.mass, 2.0 | units.kg)
self.assertEqual(code_particles[0].child1.key, 200)
self.assertEqual(code_particles[0].child2.key, 300)
self.assertEqual(code_particles[0].child1.child1.mass, 3.0 | units.kg)
self.assertEqual(code_particles[0].child1.child2.mass, 4.0 | units.kg)
channel = code_particles.new_channel_to(memory_particles)
channel.copy()
self.assertEqual(memory_particles[0].child1, memory_particles[1])
self.assertEqual(memory_particles[0].child1.mass, 1.0 | units.kg)
self.assertEqual(memory_particles[0].child2.mass, 2.0 | units.kg)
self.assertEqual(memory_particles[0].child1.child1.mass, 3.0 | units.kg)
self.assertEqual(memory_particles[0].child1.child2.mass, 4.0 | units.kg)
def test8(self):
particles = datamodel.Particles(keys=(1,))
children = datamodel.Particles(keys=(10, 11))
parent = particles[0]
child1 = children[0]
child2 = children[1]
child1.mass = 1 | units.kg
child2.mass = 2 | units.kg
parent.child1 = child1
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)
def test9(self):
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
parent.child1 = child1
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)
class TestParticlesSupersetComplex(amusetest.TestCase):
def test1(self):
print("Test1: getting attributes of a particle superset.")
superset = datamodel.Particles(2)
superset.x = [1.0, 2.0] | units.m
set2 = datamodel.Particles(2)
set2.x = [4.0, 5.0] | units.m
particle1 = datamodel.Particle()
particle1.x = 3.0 | units.m
particle2 = datamodel.Particle()
particle2.x = 6.0 | units.m
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)
# 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')]
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)
def test2(self):
print("Test2: setting attributes of a particle superset.")
firstset = datamodel.Particles(2)
superset = firstset
set2 = datamodel.Particles(2)
particle1 = datamodel.Particle()
particle2 = datamodel.Particle()
for x in [particle1, set2, particle2]:
superset = datamodel.ParticlesSuperset([superset, x.as_set()])
self.assertTrue(isinstance(superset, datamodel.ParticlesSuperset))
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))
superset.y = 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))
# 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)
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)
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.xtimesy, ([3.0, 8.0, 5.0, 12.0, 21.0] | units.m ** 2))
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)
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.xtimesypluso(0.0 | units.m ** 2), ([3.0, 8.0, 5.0, 12.0, 21.0] | units.m ** 2))
self.assertEqual(superset.xtimesypluso(2.0 | units.m ** 2), ([1.0, 6.0, 7.0, 14.0, 23.0] | units.m ** 2))
self.assertEqual(superset[0].xtimesypluso(0.0 | units.m ** 2), 3.0 | units.m ** 2)
self.assertEqual(superset[3].xtimesypluso(0.0 | units.m ** 2), 12.0 | units.m ** 2)
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
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)
superset = datamodel.ParticlesSuperset([set2, set1])
self.assertEqual(len(superset), 2)
self.assertEqual(superset.x, ([1.0, 2.0] | units.m))
self.assertEqual(superset.xtimesypluso(0.0 | units.m ** 2), ([3.0, 8.0] | units.m ** 2))
self.assertEqual(superset.xtimesypluso(2.0 | units.m ** 2), ([1.0, 6.0] | units.m ** 2))
superset = datamodel.ParticlesSuperset([set1, set2])
self.assertEqual(len(superset), 2)
self.assertEqual(superset.x, ([1.0, 2.0] | units.m))
self.assertEqual(superset.xtimesypluso(0.0 | units.m ** 2), ([3.0, 8.0] | units.m ** 2))
self.assertEqual(superset.xtimesypluso(2.0 | units.m ** 2), ([1.0, 6.0] | units.m ** 2))
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
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)
superset = datamodel.ParticlesSuperset([set1, set2])
self.assertEqual(len(superset), 2)
self.assertEqual(superset.x, ([1.0, 2.0] | units.m))
self.assertEqual(superset.xtimesy, ([3.0, 8.0] | units.m ** 2))
superset = datamodel.ParticlesSuperset([set2, set1])
self.assertEqual(len(superset), 2)
self.assertEqual(superset.x, ([1.0, 2.0] | units.m))
self.assertEqual(superset.xtimesy, ([3.0, 8.0] | units.m ** 2))
def test7(self):
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
set2.x = [] | units.m
set2.y = [] | units.m
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)
self.assertEqual(superset.x, ([1.0, 2.0] | units.m))
self.assertEqual(superset.xtimesy(), ([3.0, 8.0] | units.m ** 2))
superset = datamodel.ParticlesSuperset([set2, set1])
self.assertEqual(len(superset), 2)
self.assertEqual(superset.x, ([1.0, 2.0] | units.m))
self.assertEqual(superset.xtimesy(), ([3.0, 8.0] | units.m ** 2))
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)
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)
particles1.mass = 10 | units.kg
particles2 = datamodel.Particles(2)
particles2.mass = 20 | units.kg
superset = datamodel.ParticlesSuperset([particles1, particles2])
self.assertTrue(hasattr(superset, 'mass'))
self.assertFalse(hasattr(superset, 'radius'))
particles1.radius = 10 | units.m
self.assertFalse(hasattr(superset, 'radius'))
particles2.radius = 20 | units.m
self.assertTrue(hasattr(superset, 'radius'))
def test10(self):
particles1 = datamodel.Particles(2)
particles1.u1 = 10
particles2 = datamodel.Particles(2)
particles2.u1 = 20
superset = datamodel.ParticlesSuperset([particles1, particles2])
self.assertTrue(hasattr(superset, 'u1'))
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])
superset.u2 = 15
self.assertEqual(superset.u2, [15, 15, 15, 15])
def test11(self):
print("ParticlesSuperset from one set, of one particle")
particles1 = datamodel.Particles(1)
particles1.u = 10
superset = datamodel.ParticlesSuperset([particles1])
self.assertTrue(hasattr(superset, 'u'))
self.assertEqual(superset.u, [10])
self.assertEqual(len(superset.u), 1)
self.assertEqual(len(superset), 1)
particles1.y = 3 | units.m
self.assertTrue(hasattr(superset, 'y'))
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)
superset = datamodel.ParticlesSuperset([particles1])
self.assertEqual(len(superset), 1)
self.assertEqual(superset.x, [1.0] | units.m)
self.assertEqual(superset.xtimesypluso(0.0 | units.m**2), [3.0] | units.m**2)
self.assertEqual(superset.xtimesypluso(2.0 | units.m**2), [5.0] | units.m**2)
self.assertEqual(superset[0].xtimesypluso(0.0 | units.m**2), 3.0 | units.m**2)
self.assertEqual(superset[0].xtimesypluso(2.0 | units.m**2), 5.0 | units.m**2)
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)
superset = datamodel.ParticlesSuperset([set1])
self.assertEqual(len(set1.greater_than(-2.0 | units.m)), 4)
self.assertTrue(isinstance(set1.greater_than(-2.0 | units.m), datamodel.ParticlesSubset))
self.assertEqual(len(set1.greater_than(0.0 | units.m)), 3)
self.assertTrue(isinstance(set1.greater_than(0.0 | units.m), datamodel.ParticlesSubset))
self.assertTrue(numpy.all(set1.greater_than(0.0 | units.m).x > 0.0 | units.m))
self.assertEqual(len(set1.greater_than(3.0 | units.m)), 0)
self.assertTrue(isinstance(set1.greater_than(3.0 | units.m), datamodel.ParticlesSubset))
self.assertEqual(len(superset.greater_than(-2.0 | units.m)), 4)
self.assertTrue(isinstance(superset.greater_than(-2.0 | units.m), datamodel.ParticlesSuperset))
self.assertEqual(len(superset.greater_than(0.0 | units.m)), 3)
self.assertTrue(isinstance(superset.greater_than(0.0 | units.m), datamodel.ParticlesSuperset))
self.assertTrue(numpy.all(superset.greater_than(0.0 | units.m).x > 0.0 | units.m))
self.assertEqual(len(superset.greater_than(3.0 | units.m)), 0)
self.assertTrue(isinstance(superset.greater_than(3.0 | units.m), datamodel.ParticlesSuperset))
self.assertEqual(superset[0].greater_than(-2.0 | units.m), superset[0])
self.assertTrue(isinstance(superset[0].greater_than(-2.0 | units.m), datamodel.Particle))
self.assertEqual(superset[0].greater_than(0.0 | units.m), None)
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)
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))
self.assertEqual(len(superset.greater_than(3.0 | units.m)), 1)
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)
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
set2 = datamodel.Particles(2)
set2.x = [[5.0, 6.0], [7.0, 8.0]] | units.m
superset = datamodel.ParticlesSuperset([set1, set2])
print(superset.x)
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)
class TestSliceParticles(amusetest.TestCase):
def test1(self):
print("Test: slice a particle set.")
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)
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
all = original_set[:] # contains all particles
one = original_set[3] # contains one particle (Particle)
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))
self.assertTrue(isinstance(subset2, datamodel.ParticlesSubset))
self.assertTrue(isinstance(odd, datamodel.ParticlesSubset))
self.assertTrue(isinstance(even, datamodel.ParticlesSubset))
self.assertTrue(isinstance(reverse, datamodel.ParticlesSubset))
self.assertTrue(isinstance(all, datamodel.ParticlesSubset))
self.assertTrue(isinstance(one, datamodel.Particle))
self.assertTrue(isinstance(another, datamodel.ParticlesSubset))
self.assertTrue(isinstance(empty, datamodel.ParticlesSubset))
print("ok!")
print("Checking their length... ", end=' ')
self.assertEqual(len(subset1), 2)
self.assertEqual(len(subset2), number_of_particles-2)
self.assertEqual(len(odd), int((number_of_particles/2.0)))
self.assertEqual(len(even), int((0.5+number_of_particles/2.0)))
self.assertEqual(len(reverse), number_of_particles)
self.assertEqual(len(all), number_of_particles)
self.assertEqual(len([one]), 1)
self.assertEqual(len(another), 1)
self.assertEqual(len(empty), 0)
print("ok!")
class TestAddParticles(amusetest.TestCase):
def test1(self):
print("Test1: create a particle subset by adding a particle to a set.")
original_set = datamodel.Particles(4)
original_set.x = [1.0, 2.0, -789.0, 3.0] | units.m
particleset = original_set[:2]
particle = original_set[3]
self.assertTrue(isinstance(particleset, datamodel.ParticlesSubset))
self.assertTrue(isinstance(particle, datamodel.Particle))
new_set = particleset + particle
self.assertTrue(isinstance(new_set, datamodel.ParticlesSubset))
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))
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))
def test2(self):
print("Test2: create a particle subset by adding a set to a set.")
original_set = datamodel.Particles(5)
original_set.x = [1.0, 2.0, -789.0, 3.0, 4.0] | units.m
set1 = original_set[:2]
set2 = original_set[3:]
self.assertTrue(isinstance(set1, datamodel.ParticlesSubset))
self.assertTrue(isinstance(set2, datamodel.ParticlesSubset))
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))
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))
def test3(self):
print("Test3: create a particle superset by adding a particle to a set.")
particleset = datamodel.Particles(2)
particleset.x = [1.0, 2.0] | units.m
particle = datamodel.Particle()
particle.x = 3.0 | units.m
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))
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))
def test4(self):
print("Test4: check if the particle is already part of the set.")
particleset = datamodel.Particles(2)
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)
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.")
def test5(self):
print("Test5: recursive addition, create a new superset from supersets.")
particle = datamodel.Particle()
set1 = datamodel.Particles(2)
set2 = datamodel.Particles(2)
set3 = datamodel.Particles(2)
set4 = datamodel.Particles(2)
superset1 = datamodel.ParticlesSuperset([set1, set2])
superset2 = datamodel.ParticlesSuperset([set3, set4])
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()))
supersuperset.mass = 1 | units.kg
self.assertEqual(x.mass, 1 | units.kg)
def test6(self):
print("Test6: check if the particle belongs to the same particle set as self.")
set1 = datamodel.Particles(2)
set2 = datamodel.Particles(2)
particle = set2[0]
self.assertRaises(AmuseException, lambda: set1 + set2,
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 "
"separate particle sets. Try creating a superset instead.")
def test7(self):
print("Test7: add a particle (set) to a particle.")
original_set = datamodel.Particles(4)
particle1 = original_set[0]
particle2 = original_set[1]
particleset = original_set[2:]
self.assertTrue(isinstance(particle1, datamodel.Particle))
self.assertTrue(isinstance(particle2, datamodel.Particle))
self.assertTrue(isinstance(particleset, datamodel.ParticlesSubset))
new_particleset = particle1 + particle2
self.assertTrue(isinstance(new_particleset, datamodel.ParticlesSubset))
self.assertEqual(len(new_particleset), 2)
new_particleset = particle1 + particleset
self.assertTrue(isinstance(new_particleset, datamodel.ParticlesSubset))
self.assertEqual(len(new_particleset), 3)
class TestSubtractParticles(amusetest.TestCase):
def test1(self):
print("Test1: create a particle subset by removing a particle from a set.")
particleset = datamodel.Particles(4)
particleset.x = [1.0, 2.0, -789.0, 3.0] | units.m
particle = particleset[2]
self.assertTrue(isinstance(particle, datamodel.Particle))
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))
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))
def test2(self):
print("Test2: create a particle subset by removing a set from a set.")
set1 = datamodel.Particles(5)
set1.x = [1.0, 2.0, -789.0, 3.0, 4.0] | units.m
set2 = set1[2::3]
self.assertTrue(isinstance(set1, datamodel.Particles))
self.assertTrue(isinstance(set2, datamodel.ParticlesSubset))
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))
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))
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.")
def test4(self):
print("Test4: recursive subtraction, remove particles until the set is empty.")
particleset = datamodel.Particles(10)
self.assertEqual(len(particleset), 10)
while len(particleset):
particleset -= particleset[0]
self.assertEqual(len(particleset), 0)
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.")
particle2 = datamodel.Particle()
self.assertRaises(AmuseException, lambda: particle - particle2,
expected_message="Cannot subtract particle(s) from a particle.")
class TestIterateOverParticles(amusetest.TestCase):
def iterate_over_array(self, particles):
for x in particles:
x.radius
def iterate_over_particles(self, particles):
for x in particles:
x.key
def test1(self):
self.total_number_of_points = 10000
class Test(object):
def __init__(self):
self.radius = 1.0
particles = [Test() for x in range(self.total_number_of_points)]
particles = datamodel.Particles(self.total_number_of_points)
particles.radius = 2.0 | nbody_system.length
t0 = time.time()
self.iterate_over_particles1(particles)
t1 = time.time()
dt0 = t1 - t0
particles = datamodel.Particles(self.total_number_of_points)
particles.radius = 2.0 | nbody_system.length
t0 = time.time()
self.iterate_over_particles2(particles)
t1 = time.time()
dt1 = t1 - t0
print(dt0, dt1, dt1 / dt0)
self.assertTrue((dt1 / dt0) < 20)
def iterate_over_particles1(self, particles):
for x in particles:
x.key
def iterate_over_particles2(self, particles):
for x in particles:
x.radius
def test2(self):
self.total_number_of_points = 10000
class Test(object):
def __init__(self):
self.radius = 1.0
particles = [Test() for x in range(self.total_number_of_points)]
particles = datamodel.Particles(self.total_number_of_points)
particles.radius = 2.0 | nbody_system.length
t0 = time.time()
# self.iterate_over_array(particles)
for key in particles.get_all_keys_in_store():
key
t1 = time.time()
dt0 = t1 - t0
particles = datamodel.Particles(self.total_number_of_points)
particles.radius = 2.0 | nbody_system.length
t0 = time.time()
self.iterate_over_particles2(particles)
t1 = time.time()
dt1 = t1 - t0
print(dt0, dt1, dt1 / dt0)
self.assertTrue((dt1 / dt0) < 1000)
class TestParticlesIndexing(amusetest.TestCase):
def test1(self):
particles = datamodel.Particles(10)
particles.mass = 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)
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)
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[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)
def test4(self):
converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m)
particles = datamodel.Particles(10)
particles.mass = numpy.arange(10) | units.kg
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 | 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)
particles = datamodel.Particles(10)
particles.mass = numpy.arange(10) | units.kg
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)
def test6(self):
converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m)
particles = datamodel.Particles(10)
particles.mass = numpy.arange(10) | units.kg
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[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)
def test7(self):
set1 = datamodel.Particles(5)
set1.mass = numpy.arange(5) | units.kg
set2 = datamodel.Particles(5)
set2.mass = 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)
def test8(self):
set1 = datamodel.Particles(5)
set1.mass = numpy.arange(5) | units.kg
set2 = datamodel.Particles(5)
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)
def test9(self):
set1 = datamodel.Particles(5)
set1.mass = numpy.arange(5) | units.kg
set2 = datamodel.Particles(5)
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[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)
def test10(self):
converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m)
set1 = datamodel.Particles(5)
set1.mass = numpy.arange(5) | units.kg
set2 = datamodel.Particles(5)
set2.mass = numpy.arange(5) + 5 | units.kg
particles = datamodel.ParticlesSuperset([set1, set2])
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 | 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)
set1 = datamodel.Particles(5)
set1.mass = numpy.arange(5) | units.kg
set2 = datamodel.Particles(5)
set2.mass = numpy.arange(5) + 5 | units.kg
particles = datamodel.ParticlesSuperset([set1, set2])
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[1:3][:1].mass, 0.1 | 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)
particles = datamodel.Particles(10)
particles.mass = numpy.arange(10) | units.kg
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[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)
class TestParticlesIndexingWithBinding(amusetest.TestCase):
class TestLegacyCode(object):
def __init__(self, offset=2):
self.masses = {}
self.offset = offset
def get_mass(self, id):
masses = []
errors = []
for x in id:
masses.append(self.masses[x-self.offset])
errors.append(0)
return (masses, errors, )
def set_mass(self, id, mass):
for i, m in zip(id, mass):
self.masses[i-self.offset] = m
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
ids.append(id + self.offset)
errors.append(0)
return (ids, errors)
def delete_particle(self, ids):
errors = []
for x in ids:
del self.masses[x]
errors.append(0)
return errors
def get_number_of_particles(self):
return (len(self.masses), 0)
set_state = set_mass
get_state = get_mass
class TestInterface(InCodeComponentImplementation):
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,))
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',))
def test1(self):
particles = self.TestInterface().particles
particles.add_particles_to_store(
numpy.arange(10),
["mass"],
[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)
def test2(self):
particles = self.TestInterface().particles
particles.add_particles_to_store(
numpy.arange(10),
["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)
def test3(self):
particles = self.TestInterface().particles
particles.add_particles_to_store(
numpy.arange(10),
["mass"],
[numpy.arange(10) | 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)
def test4(self):
particles = self.TestInterface().particles
particles.add_particles_to_store(
numpy.arange(10),
["mass"],
[numpy.arange(10) | units.kg]
)
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 | 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):
particles = self.TestInterface().particles
particles.add_particles_to_store(
numpy.arange(10),
["mass"],
[numpy.arange(10) | units.kg]
)
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)
def test6(self):
particles = self.TestInterface().particles
particles.add_particles_to_store(
numpy.arange(10),
["mass"],
[numpy.arange(10) | units.kg]
)
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[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)
def test7(self):
set1 = self.TestInterface().particles
set1.add_particles_to_store(
numpy.arange(5),
["mass"],
[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]
)
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)
def test8(self):
set1 = self.TestInterface().particles
set1.add_particles_to_store(
numpy.arange(5),
["mass"],
[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]
)
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)
def test9(self):
set1 = self.TestInterface().particles
set1.add_particles_to_store(
numpy.arange(5),
["mass"],
[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]
)
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[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)
def test10(self):
set1 = self.TestInterface().particles
set1.add_particles_to_store(
numpy.arange(5),
["mass"],
[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]
)
particles = datamodel.ParticlesSuperset([set1, set2])
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 | 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]
)
set2 = self.TestInterface().particles
set2.add_particles_to_store(
numpy.arange(5)+5,
["mass"],
[numpy.arange(5) + 5 | units.kg]
)
particles = datamodel.ParticlesSuperset([set1, set2])
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[1:3][:1].mass, 0.1 | 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]
)
set2 = self.TestInterface().particles
set2.add_particles_to_store(
numpy.arange(5)+5,
["mass"],
[numpy.arange(5) + 5 | units.kg]
)
particles = datamodel.ParticlesSuperset([set1, set2])
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[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)
def test13(self):
set1 = self.TestInterface().particles
set2 = self.TestInterface().particles
self.assertEqual(set1.mass, [])
particles = datamodel.ParticlesSuperset([set1, set2])
self.assertEqual(particles.mass, [])
class TestParticlesIndexingWithSet(amusetest.TestCase):
#
# normal set
#
def test1(self):
particles = datamodel.Particles(10)
particles.mass = numpy.arange(10) | units.kg
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))
particles[5].mass = 15 | 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]])
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.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)
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.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.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)
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.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.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.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)
#
# Converted unit sets
#
def test4(self):
converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m)
particles = datamodel.Particles(10)
particles.mass = numpy.arange(10) | units.kg
converted = datamodel.ParticlesWithUnitsConverted(
particles,
converter.as_converter_from_generic_to_si()
)
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)
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)
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)
def test5(self):
converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m)
particles = datamodel.Particles(10)
particles.mass = numpy.arange(10) | units.kg
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)
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)
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)
def test6(self):
converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m)
particles = datamodel.Particles(10)
particles.mass = numpy.arange(10) | units.kg
converted = datamodel.ParticlesWithUnitsConverted(
particles,
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)
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)
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)
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)
#
# Particles super sets
#
def test7(self):
set1 = datamodel.Particles(5)
set1.mass = numpy.arange(5) | units.kg
set2 = datamodel.Particles(5)
set2.mass = 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)
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.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)
def test8(self):
set1 = datamodel.Particles(5)
set1.mass = numpy.arange(5) | units.kg
set2 = datamodel.Particles(5)
set2.mass = 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.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.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)
def test9(self):
set1 = datamodel.Particles(5)
set1.mass = numpy.arange(5) | units.kg
set2 = datamodel.Particles(5)
set2.mass = 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)
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.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.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.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)
def test10(self):
converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m)
set1 = datamodel.Particles(5)
set1.mass = numpy.arange(5) | units.kg
set2 = datamodel.Particles(5)
set2.mass = numpy.arange(5) + 5 | units.kg
particles = datamodel.ParticlesSuperset([set1, set2])
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 | 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)
set1 = datamodel.Particles(5)
set1.mass = numpy.arange(5) | units.kg
set2 = datamodel.Particles(5)
set2.mass = numpy.arange(5) + 5 | units.kg
particles = datamodel.ParticlesSuperset([set1, set2])
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)
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)
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)
def test12(self):
converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m)
particles = datamodel.Particles(10)
particles.mass = numpy.arange(10) | units.kg
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)
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)
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)
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)
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)
class TestParticlesIndexingWithBindingAndSet(amusetest.TestCase):
class TestLegacyCode(object):
def __init__(self, offset=2):
self.masses = {}
self.offset = offset
def get_mass(self, id):
masses = []
errors = []
for x in id:
masses.append(self.masses[x-self.offset])
errors.append(0)
return (masses, errors, )
def set_mass(self, id, mass):
try:
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),)
def new_particle(self, mass):
ids = []
errors = []
for x in mass:
id = len(self.masses)
self.masses[len(self.masses)] = x
ids.append(id + self.offset)
errors.append(0)
return (ids, errors)
def delete_particle(self, ids):
errors = []
for x in ids:
del self.masses[x]
errors.append(0)
return errors
def get_number_of_particles(self):
return (len(self.masses), 0)
set_state = set_mass
get_state = get_mass
class TestInterface(InCodeComponentImplementation):
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,))
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',))
#
# normal set
#
def test1(self):
particles = self.TestInterface().particles
particles.add_particles_to_store(
numpy.arange(10),
["mass"],
[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)
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.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)
def test2(self):
particles = self.TestInterface().particles
particles.add_particles_to_store(
numpy.arange(10),
["mass"],
[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.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.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)
def test3(self):
particles = self.TestInterface().particles
particles.add_particles_to_store(
numpy.arange(10),
["mass"],
[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.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.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.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)
#
# units converted
#
def test4(self):
particles = self.TestInterface().particles
particles.add_particles_to_store(
numpy.arange(10),
["mass"],
[numpy.arange(10) | units.kg]
)
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(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)
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)
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)
def test5(self):
particles = self.TestInterface().particles
particles.add_particles_to_store(
numpy.arange(10),
["mass"],
[numpy.arange(10) | units.kg]
)
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)
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)
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)
def test6(self):
particles = self.TestInterface().particles
particles.add_particles_to_store(
numpy.arange(10),
["mass"],
[numpy.arange(10) | units.kg]
)
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)
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)
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)
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)
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)
#
# supersets
#
def test7(self):
set1 = self.TestInterface().particles
set1.add_particles_to_store(
numpy.arange(5),
["mass"],
[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]
)
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)
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.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)
def test8(self):
set1 = self.TestInterface().particles
set1.add_particles_to_store(
numpy.arange(5),
["mass"],
[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]
)
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.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.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)
def test9(self):
set1 = self.TestInterface().particles
set1.add_particles_to_store(
numpy.arange(5),
["mass"],
[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]
)
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)
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.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.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.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)
#
# superset and unit conversion
#
def test10(self):
set1 = self.TestInterface().particles
set1.add_particles_to_store(
numpy.arange(5),
["mass"],
[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]
)
particles = datamodel.ParticlesSuperset([set1, set2])
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(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)
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)
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)
def test11(self):
set1 = self.TestInterface().particles
set1.add_particles_to_store(
numpy.arange(5),
["mass"],
[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]
)
particles = datamodel.ParticlesSuperset([set1, set2])
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)
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)
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)
def test12(self):
set1 = self.TestInterface().particles
set1.add_particles_to_store(
numpy.arange(5),
["mass"],
[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]
)
particles = datamodel.ParticlesSuperset([set1, set2])
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)
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)
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)
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)
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)
class TestParticlesIndexingAfterPickle(amusetest.TestCase):
def copy_with_pickle(self, set):
return pickle.loads(pickle.dumps(set))
def test1(self):
particles = datamodel.Particles(10)
particles.mass = numpy.arange(10) | units.kg
particles = self.copy_with_pickle(particles)
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)
def test2(self):
particles = datamodel.Particles(10)
particles.mass = numpy.arange(10) | units.kg
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)
def test3(self):
particles = datamodel.Particles(10)
particles.mass = numpy.arange(10) | units.kg
particles = self.copy_with_pickle(particles)
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)
def test4(self):
converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m)
particles = datamodel.Particles(10)
particles.mass = numpy.arange(10) | units.kg
converted = datamodel.ParticlesWithUnitsConverted(
particles,
converter.as_converter_from_generic_to_si()
)
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 | 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)
particles = datamodel.Particles(10)
particles.mass = numpy.arange(10) | units.kg
converted = datamodel.ParticlesWithUnitsConverted(
particles,
converter.as_converter_from_generic_to_si()
)
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)
def test6(self):
converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m)
particles = datamodel.Particles(10)
particles.mass = numpy.arange(10) | units.kg
converted = datamodel.ParticlesWithUnitsConverted(
particles,
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[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)
def test7(self):
set1 = datamodel.Particles(5)
set1.mass = numpy.arange(5) | units.kg
set2 = datamodel.Particles(5)
set2.mass = numpy.arange(5) + 5 | units.kg
particles = datamodel.ParticlesSuperset([set1, set2])
particles = self.copy_with_pickle(particles)
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)
def test8(self):
set1 = datamodel.Particles(5)
set1.mass = numpy.arange(5) | units.kg
set2 = datamodel.Particles(5)
set2.mass = numpy.arange(5) + 5 | units.kg
particles = datamodel.ParticlesSuperset([set1, set2])
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)
def test9(self):
set1 = datamodel.Particles(5)
set1.mass = numpy.arange(5) | units.kg
set2 = datamodel.Particles(5)
set2.mass = numpy.arange(5) + 5 | units.kg
particles = datamodel.ParticlesSuperset([set1, set2])
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[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)
def test10(self):
converter = nbody_system.nbody_to_si(10 | units.kg, 5 | units.m)
set1 = datamodel.Particles(5)
set1.mass = numpy.arange(5) | units.kg
set2 = datamodel.Particles(5)
set2.mass = numpy.arange(5) + 5 | units.kg
particles = datamodel.ParticlesSuperset([set1, set2])
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 | 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)
set1 = datamodel.Particles(5)
set1.mass = numpy.arange(5) | units.kg
set2 = datamodel.Particles(5)
set2.mass = numpy.arange(5) + 5 | units.kg
particles = datamodel.ParticlesSuperset([set1, set2])
converted = datamodel.ParticlesWithUnitsConverted(
particles,
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[1:3][:1].mass, 0.1 | 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)
particles = datamodel.Particles(10)
particles.mass = numpy.arange(10) | units.kg
converted = datamodel.ParticlesWithUnitsConverted(
particles,
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[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)
class TestParticlesOverlay(amusetest.TestCase):
def test1(self):
set1 = datamodel.Particles(2)
set1.x = [1.0, 2.0] | units.kg
set2 = datamodel.ParticlesOverlay(set1)
set2.y = [4.0, 5.0] | units.m
self.assertAlmostRelativeEquals(set2.x, [1.0, 2.0] | units.kg)
self.assertAlmostRelativeEquals(set2.y, [4.0, 5.0] | units.m)
self.assertTrue('x' in dir(set1))
self.assertFalse('y' in dir(set1))
def test2(self):
set1 = datamodel.Particles(2)
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))
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)
def test3(self):
set1 = datamodel.Particles(2)
set1.x = [1.0, 2.0] | units.kg
set2 = datamodel.ParticlesOverlay(set1)
set2.y = [4.0, 5.0] | units.m
particle = set2[0]
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
set2 = datamodel.ParticlesOverlay(set1)
set2.y = [4.0, 5.0] | units.m
set2.remove_particle(set2[1])
self.assertEqual(len(set2), 1)
self.assertAlmostRelativeEquals(set2.x, [1.0] | units.kg)
self.assertAlmostRelativeEquals(set2.y, [4.0] | units.m)
self.assertAlmostRelativeEquals(set1.x, [1.0] | units.kg)
def test5(self):
set1 = datamodel.Particles(3)
set1.x = [1.0, 2.0, 3.0] | units.kg
set2 = datamodel.ParticlesOverlay(set1)
set2.y = [4.0, 5.0, 6.0] | units.m
subset = set2[1:]
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'])
self.assertAlmostRelativeEquals(xy[0], [2.0, 3.0] | units.kg)
self.assertAlmostRelativeEquals(xy[1], [5.0, 6.0] | units.m)
def test6(self):
set1 = datamodel.Particles(3)
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)
def test7(self):
set1 = datamodel.Particles(2)
set1.x = [1.0, 2.0] | units.kg
set2 = datamodel.ParticlesOverlay(set1)
set2.y = [4.0, 5.0] | units.m
set1.remove_particle(set1[0])
self.assertAlmostRelativeEquals(set2.y, [5.0] | units.m)
def test8(self):
set1 = datamodel.Particles(10)
set1.x = range(10) | units.kg
set2 = datamodel.ParticlesOverlay(set1)
set2.y = (range(10) | units.m) * 2
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.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)
set = datamodel.Particles(3)
set.x = [1.3, 2.7, numpy.pi] | units.m
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()
self.assertEqual(set.x.unit.dtype, None)
self.assertEqual(set.y.unit.dtype, numpy.float32)
self.assertEqual(set.z.unit.dtype, numpy.int32)
self.assertEqual(set.x.number.dtype, numpy.float64)
self.assertEqual(set.y.number.dtype, numpy.float32)
self.assertEqual(set.z.number.dtype, numpy.int32)
self.assertTrue((set.x.number == [1.3, 2.7, numpy.pi]).all())
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")
print("Stored unit with dtype remains, only number can be changed")
set = self.new_set_with_specific_dtype()
temp_x = set.x.copy()
set.x = set.z
set.y = set.z
set.z = 2 * temp_x
self.assertEqual(set.x.unit.dtype, None)
self.assertEqual(set.y.unit.dtype, numpy.float32)
self.assertEqual(set.z.unit.dtype, numpy.int32)
self.assertEqual(set.x.number.dtype, numpy.float64)
self.assertEqual(set.y.number.dtype, numpy.float32)
self.assertEqual(set.z.number.dtype, numpy.int32)
self.assertTrue((set.x.number == [1, 2, 3]).all())
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()
set2 = datamodel.Particles(3)
set2.position = [[1.3]*3, [2.7]*3, [numpy.pi]*3] | units.m
set.add_particles(set2)
self.assertEqual(set.x.unit.dtype, None)
self.assertEqual(set.y.unit.dtype, numpy.float32)
self.assertEqual(set.z.unit.dtype, numpy.int32)
self.assertEqual(set.x.number.dtype, numpy.float64)
self.assertEqual(set.y.number.dtype, numpy.float32)
self.assertEqual(set.z.number.dtype, numpy.int32)
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])
| 207,219
| 41.203666
| 176
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_attribute_error.py
|
import numpy
import math
import os
from amuse.test import amusetest
from amuse.io import store
from amuse.units import units
from amuse.units import nbody_system
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):
# mass
self.data = []
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):
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):
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",)),
None,
code.get_number_of_particles,
[],
[
incode_storage.ParticleGetAttributesMethod(code.get_mass, ("mass",)),
],
name_of_the_index="index"
)
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()])
instances = [particles, particle, subset, superset]
classes = [Particles, Particle, ParticlesSubset, ParticlesSuperset]
lengths = [4, 1, 2, 5]
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.")
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()])
superset.mass = 1.0 | units.MSun
superset.radius = 1.0 | units.RSun
for i, x in enumerate(superset):
x.mass = 2.0 | units.kg
instances = [particles, particle.as_set(), subset, superset]
convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU)
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.")
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()])
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]
for i, x in enumerate(instances):
self.assertTrue(isinstance(x, classes[i]))
self.assertEqual(len(x.as_set()), lengths[i])
if os.path.exists(output_file):
os.remove(output_file)
HDFstorage = store.StoreHDF(output_file)
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.")
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()])
instances = [particles, particle, subset, superset]
classes = [Particles, Particle, ParticlesSubset, ParticlesSuperset]
lengths = [4, 1, 2, 5]
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.")
def xtest5(self):
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()])
superset.mass = 1.0 | units.MSun
for i, x in enumerate(superset):
x.mass = 2.0 | units.kg
instances = [particles, particle.as_set(), subset, superset]
classes = [Particles, Particle, ParticlesSubset, ParticlesSuperset]
convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU)
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 =
# "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()])
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]
for i, x in enumerate(instances):
self.assertTrue(isinstance(x, classes[i]))
self.assertEqual(len(x.as_set()), lengths[i])
if os.path.exists(output_file):
os.remove(output_file)
HDFstorage = store.StoreHDF(output_file)
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.")
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.remove_particle(p[0])
self.assertRaises(exceptions.KeysNotInStorageException, lambda: q.position)
| 8,040
| 42.231183
| 183
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_grid_attributes.py
|
from amuse.test import amusetest
from amuse.datamodel.grids import *
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.])
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)))
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))
self.assertFalse(grid.overlaps(grid3))
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.])
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)
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))
self.assertFalse(grid.overlaps(grid3))
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))
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])
def xtest5(self):
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]])
| 3,481
| 41.463415
| 115
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_stopping_conditions.py
|
from amuse.test import amusetest
from amuse.support.exceptions import AmuseException
from amuse.community.interface.stopping_conditions import StoppingConditions
from amuse import datamodel
from amuse.units import units
from amuse.support import interface
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())
self.assertTrue(instance.escaper_detection.is_supported())
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())
self.assertFalse(instance.escaper_detection.is_supported())
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())
instance.collision_detection.enable()
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]
instance = StoppingConditions(Collision())
instance.code.particles = datamodel.Particles(3)
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]
)
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)
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]
instance = StoppingConditions(Collision())
instance.code.particles = datamodel.Particles(3)
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]
)
self.assertTrue(instance.collision_detection.is_set())
particles = instance.collision_detection.particles(0)
self.assertEqual(len(particles), 1)
particles = instance.collision_detection.particles(1)
self.assertEqual(len(particles), 1)
particles = instance.collision_detection.particles(2)
self.assertEqual(len(particles), 1)
particles = instance.collision_detection.particles(3)
self.assertEqual(len(particles), 0)
| 6,632
| 36.264045
| 77
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_attribute_storage.py
|
import numpy
import time
from amuse.test import amusetest
from amuse.datamodel.memory_storage import InMemoryAttributeStorageUseDictionaryForKeySet
from amuse.datamodel.memory_storage import InMemoryAttributeStorageUseSortedKeys
from amuse.datamodel.memory_storage import get_in_memory_attribute_storage_factory
from amuse.datamodel.memory_storage import InMemoryVectorQuantityAttribute
from amuse.datamodel.incode_storage import *
class _AbstractTestInMemoryAttributeStorage:
def new_inmemory_storage(self, is_with_units=True):
raise NotImplementedError()
def test1(self):
keys = 4, 5, 6
attributes = "a", "b"
values = [
units.m.new_quantity([1.0, 2.0, 3.0]),
units.g.new_quantity([4.0, 5.0, 6.0])
]
instance = self.new_inmemory_storage()
indices = instance.add_particles_to_store(keys, attributes, values)
self.assertEqual(len(indices), len(keys))
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
attributes = "a", "b"
values = [
units.m.new_quantity(numpy.array([1.0, 2.0, 3.0])),
units.g.new_quantity(numpy.array([4.0, 5.0, 6.0]))
]
instance = self.new_inmemory_storage()
indices_stored = instance.add_particles_to_store(keys, attributes, values)
indices = instance.get_indices_of([
keys[2],
keys[1],
keys[0]
])
for index, wanted in zip(indices, [indices_stored[2], indices_stored[1], indices_stored[0]]):
self.assertEqual(index, wanted)
def ntest2b(self):
keys = 4, 5, 6
attributes = "a", "b"
values = [
units.m.new_quantity(numpy.array([1.0, 2.0, 3.0])),
units.g.new_quantity(numpy.array([4.0, 5.0, 6.0]))
]
instance = self.new_inmemory_storage()
print(instance.add_particles_to_store(keys, attributes, values))
indices = instance.get_indices_of([
keys[2],
keys[0]
])
all_values = instance.get_values_in_store(
indices,
["b", "a"]
)
self.assertEqual(all_values[0][0], 6.0 | units.g)
self.assertEqual(all_values[0][1], 4.0 | units.g)
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
attributes = "a", "b"
values = [
units.m.new_quantity(numpy.array([1.0, 2.0, 3.0])),
units.g.new_quantity(numpy.array([4.0, 5.0, 6.0]))
]
instance = self.new_inmemory_storage()
instance.add_particles_to_store(keys, attributes, values)
self.assertEqual(values[0][0], 1.0 | units.m)
indices = instance.get_indices_of([
keys[0],
keys[2]
])
instance.set_values_in_store(
indices,
["b", "a"],
[
units.kg.new_quantity(numpy.array([9.0, 11.0])),
units.km.new_quantity(numpy.array([1.0, 2.0]))
]
)
values = instance.get_values_in_store(None, ["a", "b"])
self.assertEqual(values[0][0], 1000.0 | units.m)
self.assertEqual(values[0][2], 2000.0 | units.m)
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.g.new_quantity(numpy.array([4.0, 5.0, 6.0, 7.0]))
]
instance = self.new_inmemory_storage()
instance.add_particles_to_store(keys, attributes, values)
indices = instance.get_indices_of([
keys[2],
keys[0]
])
print(indices)
instance.remove_particles_from_store(indices)
self.assertEqual(len(instance), 2)
indices = instance.get_indices_of([
keys[1],
keys[3]
])
all_values = instance.get_values_in_store(
indices,
["a", "b"]
)
self.assertEqual(all_values[0][0], 0.002 | units.km)
self.assertEqual(all_values[0][1], 0.004 | units.km)
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.g.new_quantity(numpy.array([4.0, 5.0, 6.0, 7.0]))
]
instance = self.new_inmemory_storage()
indices1 = instance.add_particles_to_store(keys, attributes, values)
self.assertEqual(len(instance), 4)
keys = 20, 21, 22, 23
indices2 = instance.add_particles_to_store(keys, attributes, values)
self.assertEqual(len(instance), 8)
indices = instance.get_indices_of([5, 21])
all_values = instance.get_values_in_store(indices, ["a"])
self.assertEqual(all_values[0][0], 2.0 | units.m)
self.assertEqual(all_values[0][1], 2.0 | units.m)
indices = instance.get_indices_of([10, 20])
instance.remove_particles_from_store(indices)
self.assertEqual(len(instance), 6)
indices = instance.get_indices_of([5, 21])
all_values = instance.get_values_in_store(indices, ["a"])
self.assertEqual(all_values[0][0], 2.0 | units.m)
self.assertEqual(all_values[0][1], 2.0 | units.m)
def test6(self):
keys = 10, 5, 6, 7
attributes = "a", "b"
values = [
numpy.array([1.0, 2.0, 3.0, 4.0]),
numpy.array([4.0, 5.0, 6.0, 7.0])
]
instance = self.new_inmemory_storage(False)
instance.add_particles_to_store(keys, attributes, values)
self.assertEqual(len(instance), 4)
particles = [4, 5, 6, 7]
keys = 20, 21, 22, 23
instance.add_particles_to_store(keys, attributes, values)
self.assertEqual(len(instance), 8)
indices = instance.get_indices_of([5, 21])
all_values = instance.get_values_in_store(indices, ["a"])
self.assertEqual(all_values[0][0], 2.0)
self.assertEqual(all_values[0][1], 2.0)
indices = instance.get_indices_of([10, 20])
instance.remove_particles_from_store(indices)
self.assertEqual(len(instance), 6)
indices = instance.get_indices_of([5, 21])
all_values = instance.get_values_in_store(indices, ["a"])
self.assertEqual(all_values[0][0], 2.0)
self.assertEqual(all_values[0][1], 2.0)
instance.set_values_in_store(indices, ["a", "b"], [[4.0, 5.0], [77, 88]])
all_values = instance.get_values_in_store(indices, ["a"])[0]
self.assertEqual(all_values[0], 4.0)
self.assertEqual(all_values[1], 5.0)
if hasattr(instance, "copy"):
instance2 = instance.copy()
indices = instance2.get_indices_of([5, 21])
instance2.set_values_in_store(indices, ["a"], [[3.0, 1.0]])
all_values = instance2.get_values_in_store(indices, ["a"])[0]
self.assertEqual(all_values[0], 3.0)
self.assertEqual(all_values[1], 1.0)
all_values = instance.get_values_in_store(indices, ["a"])[0]
self.assertEqual(all_values[0], 4.0)
self.assertEqual(all_values[1], 5.0)
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.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.assertTrue(instance.has_key_in_store(5))
self.assertFalse(instance.has_key_in_store(1))
self.assertFalse(instance.has_key_in_store(8))
self.assertFalse(instance.has_key_in_store(11))
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.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.assertEqual(instance.get_all_indices_in_store(), 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.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")
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.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")
def test11(self):
keys = 10, 5
attributes = "a", "b"
values = [
units.m.new_quantity(numpy.array([1.0, 2.0])),
units.g.new_quantity(numpy.array([4.0, 5.0]))
]
instance = self.new_inmemory_storage()
instance.add_particles_to_store(keys, attributes, values)
self.assertEqual(len(instance), 2)
keys = 7, 6
instance.add_particles_to_store(keys, attributes, values)
self.assertEqual(len(instance), 4)
indices = instance.get_all_indices_in_store()[0]
instance.remove_particles_from_store([indices])
self.assertEqual(len(instance), 3)
self.assertEqual(instance.get_all_keys_in_store(), [5, 7, 6])
indices = instance.get_all_indices_in_store()[1]
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):
return InMemoryAttributeStorageUseSortedKeys()
class TestDictionaryKeysInMemoryAttributeStorage(amusetest.TestCase, _AbstractTestInMemoryAttributeStorage):
def new_inmemory_storage(self, is_with_units=True):
return InMemoryAttributeStorageUseDictionaryForKeySet()
class _Code(object):
def __init__(self, is_with_units):
self.data = {}
self.index = 100
self.is_with_units = is_with_units
def get_number_of_particles(self):
return len(self.data)
def get_ab(self, index):
a = [(self.data[i]['a']) for i in index]
b = [(self.data[i]['b']) for i in index]
if self.is_with_units:
return [units.m(a), units.g(b)]
else:
return [numpy.asarray(a), numpy.asarray(b)]
def set_ab(self, index, a, b):
if self.is_with_units:
a = a.value_in(units.m)
b = b.value_in(units.g)
for j, i in enumerate(index):
self.data[i]['a'] = a[j]
self.data[i]['b'] = b[j]
def new_particle(self, a, b):
if self.is_with_units:
a = a.value_in(units.m)
b = b.value_in(units.g)
result = []
for i in range(len(a)):
self.data[self.index] = {}
self.data[self.index]['a'] = a[i]
self.data[self.index]['b'] = b[i]
result.append(self.index)
self.index += 1
return result
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):
code = _Code(is_with_units)
return InCodeAttributeStorage(
code,
NewParticleMethod(code.new_particle, ("a", "b")),
code.delete_particle,
code.get_number_of_particles,
[ParticleSetAttributesMethod(code.set_ab, ("a", "b")), ],
[ParticleGetAttributesMethod(code.get_ab, ("a", "b")), ],
name_of_the_index="index"
)
| 13,947
| 34.948454
| 150
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_generate_fortran.py
|
from amuse.test import amusetest
import numpy
import inspect
import collections
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.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
@legacy_function
def echo_double():
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
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
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
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
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
self.assertContainsString(outputstring, "integer :: echo_int_")
self.assertContainsString(outputstring, "integer :: echo_double_")
self.assertContainsString(outputstring, "echo_int_(")
self.assertContainsString(outputstring, "echo_double_(")
| 3,643
| 36.958333
| 86
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/core_tests/test_unit_conversion.py
|
from amuse.test import amusetest
import numpy
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)
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)
kmh = km/h
ms = m/s
val = 10 | m/s
self.assertEqual(36, val.value_in(kmh))
def test5(self):
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))
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
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)
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)
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
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")
def test12(self):
self.assertEqual((1234 | g).as_string_in(g), '1234 g')
self.assertEqual((1234 | g).as_string_in(kg), '1.234 kg')
self.assertEqual((1.234 | kg).as_string_in(g), '1234.0 g')
self.assertEqual((1.0 | km * s**-1).as_string_in(m / s), '1000.0 m / s')
self.assertEqual((1.0 | km * s**-1).as_string_in(s**-1 * m), '1000.0 s**-1 * m')
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)
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])
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")
def test2(self):
x = "test" | string
self.assertEqual("test", x.value_in(string))
def test3(self):
test_unit = core.enumeration_unit(
"test",
"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<test>")
def test4(self):
self.assertRaises(Exception, lambda: 1 | string,
expected_message="<1> is not a valid value for unit<string>")
def test5(self):
test_unit = core.enumeration_unit(
"test",
"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(str(x), y)
def test6(self):
test_unit = core.enumeration_unit(
"test",
"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(str(x), y)
def test7(self):
test_unit = core.enumeration_unit(
"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.assertFalse(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.assertFalse(1 | test_unit >= 2 | 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)
| 6,262
| 34.994253
| 109
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_galactic_potentials.py
|
from amuse.test import amusetest
from amuse.units import units, nbody_system, constants
from amuse.ext.galactic_potentials import NFW_profile, MiyamotoNagai_profile, Plummer_profile, \
PowerLawCutoff_profile, MWpotentialBovy2015, scipy_imported
import numpy
class TestNFWProfile(amusetest.TestCase):
def test1(self):
"""
See the textbook by L.Aguilar, chapter 3:
ftp://ftp.crya.unam.mx/pub/luisfr/laguilar/GH05_Aguilar.pdf
"""
rho0 = 1.e3 | units.MSun/units.parsec**3
rs = 6.6 | units.kpc
nfw_profile = NFW_profile(rho0, rs)
m0 = 4.*numpy.pi*rho0*rs**3
phi0 = -4.*numpy.pi*constants.G*rho0*rs**2
ar0 = -phi0/rs
# relative mass enclosed at rs: m_at_rs / m0 ~ 0.193147
m_at_rs = nfw_profile.enclosed_mass(rs)
self.assertAlmostEqual(m_at_rs/m0, 0.193147, 5)
# relative mass enclosed at 5.3054*rs ~ m0
m_eq_one = nfw_profile.enclosed_mass(5.3054*rs,)
self.assertAlmostEqual(m_eq_one/m0, 1.0, 5)
# relative mass density, rho(rs) ~ rho0/4
rho_rs = nfw_profile.mass_density(rs)
self.assertAlmostEqual(rho0/rho_rs, 4.0, 5)
# relative gravitational potential at (r/rs)->0 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)
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)
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)
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)
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)
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)
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)
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)
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)
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)
rho_p = plummer_profile.mass_density(b*6.6)
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
alpha = 1.6
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)
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)
def test2(self):
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)
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
# 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)
# 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)
# mass enclosed in 60kpc
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)
# 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)
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")
| 9,463
| 43.018605
| 120
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_halogen_model.py
|
from amuse.test.amusetest import TestWithMPI
from amuse.support.exceptions import AmuseException
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)
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 "
"'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
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(),
2.27538127277e+43 | units.J, 10)
| 1,935
| 46.219512
| 182
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_sticky_spheres.py
|
from amuse.units import units
from amuse.datamodel import Particles
from amuse.support.exceptions import AmuseException
from amuse.test.amusetest import TestCase
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)
self.assertAlmostEqual(merged.position, [0.2, 0.4, -0.1] | units.m)
self.assertAlmostEqual(merged.velocity, ([2.0, -3.0, -6.0] | units.m / units.s) / 7.0)
self.assertAlmostEqual(merged.velocity.length(), 1.0 | units.m / units.s)
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)
self.assertAlmostEqual(merged.position, [0.5, 0.5, 0.5] | units.m)
self.assertAlmostEqual(merged.velocity, [1.0, 1.0, 1.0] | units.m / units.s)
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)")
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
particles.velocity = [
[1.0, 0.0, 1.0], [0.0, -1.0, -1.0],
[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,
[((i+1)**2 + (i+2)**2)/(2*i+3.0), 1.0, 2.0] | units.m)
self.assertAlmostEqual(merged.velocity,
([i+1, -(i+2), -1.0] | units.m / units.s) / (2*i+3.0))
| 3,428
| 49.426471
| 139
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_fractalcluster.py
|
from amuse.test import amusetest
from amuse.units import units, nbody_system, constants
from amuse.ic.fractalcluster import new_fractal_cluster_model
class TestFractalCluster(amusetest.TestCase):
def test1(self):
print("First test: making a fractal cluster.")
target_number_of_particles = 100
parts = new_fractal_cluster_model(N=target_number_of_particles)
self.assertEqual(len(parts), 100)
def test2(self):
print("test 2: test energy.")
target_number_of_particles = 100
parts = new_fractal_cluster_model(N=target_number_of_particles)
ek = parts.kinetic_energy()
ep = parts.potential_energy(G=nbody_system.G)
self.assertAlmostEqual(ek/abs(ep), 0.5, 12)
self.assertAlmostRelativeEqual(ep, -0.5 | nbody_system.energy, 12)
def test3(self):
print("test 3: test energy physical units.")
target_number_of_particles = 100
convert_nbody = nbody_system.nbody_to_si(1000 | units.MSun, 1 | units.parsec)
parts = new_fractal_cluster_model(N=target_number_of_particles, convert_nbody=convert_nbody)
ek = parts.kinetic_energy()
ep = parts.potential_energy()
self.assertAlmostEqual(ek/abs(ep), 0.5, 12)
self.assertAlmostRelativeEqual(ep, -0.5 * constants.G * (1000 | units.MSun)**2 / (1.0 | units.parsec), 12)
def test4(self):
print("Test with masses")
target_number_of_particles = 100
masses = (range(1, 11) | units.MSun) * 1.0
convert_nbody = nbody_system.nbody_to_si(1000 | units.MSun, 1 | units.parsec)
particles = new_fractal_cluster_model(masses=masses, convert_nbody=convert_nbody, do_scale=True)
ek = particles.kinetic_energy()
ep = particles.potential_energy()
self.assertEqual(len(particles), 10)
self.assertAlmostEqual(particles.total_mass(), 1000 | units.MSun) # Note: total_mass == converter's mass unit!
self.assertAlmostEqual(masses.sum(), 55 | units.MSun) # Note: total_mass != masses.sum()
self.assertAlmostEqual(particles.center_of_mass(), [0, 0, 0] | units.parsec)
self.assertAlmostEqual(particles.center_of_mass_velocity(), [0, 0, 0] | units.km / units.s)
self.assertAlmostEqual(ek/ep, -0.5, 12)
self.assertAlmostRelativeEqual(ek, (0.25 * constants.G * (1000 | units.MSun)**2 / (1.0 | units.parsec)).as_quantity_in(ek.unit), 12)
def test5(self):
print("Test with masses, with correct mass unit in converter")
target_number_of_particles = 100
masses = (range(1, 11) | units.MSun) * 1.0
convert_nbody = nbody_system.nbody_to_si(masses.sum(), 1 | units.parsec)
particles = new_fractal_cluster_model(masses=masses, convert_nbody=convert_nbody, do_scale=True)
ek = particles.kinetic_energy()
ep = particles.potential_energy()
self.assertEqual(len(particles), 10)
self.assertAlmostEqual(particles.total_mass(), 55 | units.MSun) # Note: total_mass == converter's mass unit!
self.assertAlmostEqual(particles.center_of_mass(), [0, 0, 0] | units.parsec)
self.assertAlmostEqual(particles.center_of_mass_velocity(), [0, 0, 0] | units.km / units.s)
self.assertAlmostEqual(ek/ep, -0.5, 12)
self.assertAlmostRelativeEqual(ek, (0.25 * constants.G * (55 | units.MSun)**2 / (1.0 | units.parsec)).as_quantity_in(ek.unit), 12)
def test6(self):
print("Test fractal dimension.")
number_of_particles = 1000
for target_fractal_dimension in [1.6, 2.0, 2.5, 3.0]:
particles = new_fractal_cluster_model(
N=number_of_particles,
fractal_dimension=target_fractal_dimension,
do_scale=False, random_seed=1234321)
self.assertAlmostRelativeEquals(particles.box_counting_dimension(),
target_fractal_dimension, 1)
self.assertAlmostRelativeEquals(particles.correlation_dimension(),
target_fractal_dimension, 1)
| 4,025
| 49.962025
| 140
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_grid_remappers.py
|
from amuse.units import units
from amuse.datamodel import new_cartesian_grid
from amuse.support.exceptions import AmuseException
from amuse.test.amusetest import TestCase
try:
from omuse.ext import grid_remappers
except:
from amuse.ext import grid_remappers
import numpy
from amuse.datamodel.grids import *
from amuse.datamodel.staggeredgrid import StaggeredGrid
class TestGridRemappers(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.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)
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)
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)
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)
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))
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))
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)
class TestConservativeSphericalRemapper(TestCase):
def setUp(self):
try:
from omuse.community.cdo.interface import CDORemapper
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
# 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],
[-0.090, 0.904], [-0.069, 0.907], [-0.069, 0.921], [-0.080, 0.919],
[-0.073, 0.928], [-0.052, 0.930], [-0.048, 0.942], [-0.062, 0.949],
[-0.054, 0.958], [-0.069, 0.954], [-0.087, 0.952], [-0.087, 0.959],
[-0.080, 0.966], [-0.085, 0.973], [-0.087, 0.965], [-0.097, 0.965],
[-0.097, 0.975], [-0.092, 0.984], [-0.101, 0.980], [-0.108, 0.980],
[-0.104, 0.987], [-0.102, 0.993], [-0.115, 1.001], [-0.099, 0.996],
[-0.101, 1.007], [-0.090, 1.010], [-0.087, 1.021], [-0.069, 1.021],
[-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.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],
[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],
[49, 48, 71], [14, 16, 15], [14, 71, 48], [17, 19, 18], [17, 20, 19],
[48, 16, 14], [48, 47, 16], [47, 46, 16], [16, 46, 45], [23, 22, 24],
[21, 24, 22], [17, 16, 45], [20, 17, 45], [21, 25, 24], [27, 26, 28],
[20, 72, 21], [25, 21, 72], [45, 72, 20], [25, 28, 26], [44, 73, 45],
[72, 45, 73], [28, 25, 29], [29, 25, 31], [43, 73, 44], [73, 43, 40],
[72, 73, 39], [72, 31, 25], [42, 40, 43], [31, 30, 29], [39, 73, 40],
[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
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
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)
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)
lats = lat_min + lats/shape[1] * lat_range
lons = numpy.array(ind[0], dtype=numpy.float)
lons = lon_min + lons/shape[0] * lon_range
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
nodes = StructuredGrid(*ind[0].shape)
nodes.lat = (corners[1] | units.rad)
nodes.lon = (corners[0] | units.rad)
self.structured2 = StaggeredGrid(elements, nodes)
def test1(self):
target = self.unstructured
source = self.structured
# 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
constant_field = numpy.zeros(source.elements.shape, dtype=numpy.double)
constant_field += 1.0
source.elements.const2 = constant_field
# create remapper
remapper = grid_remappers.conservative_spherical_remapper(source, target)
# 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")
self.assertTrue(numpy.all(target.elements.const2 >= 0.0), msg="Expecting all remapped values values to be larger than zero")
def test2(self):
target = self.structured2
source = self.structured
# 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
constant_field = numpy.zeros(source.elements.shape, dtype=numpy.double)
constant_field += 1.0
source.elements.const2 = constant_field
# create remapper
remapper = grid_remappers.conservative_spherical_remapper(source, target)
# 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")
self.assertTrue(numpy.all(target.elements.const2 >= 0.0), msg="Expecting all remapped values values to be larger than zero")
def test3(self):
target = self.unstructured
source = self.structured
# 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
constant_field = numpy.zeros(source.elements.shape, dtype=numpy.double)
constant_field += 1.0
source.elements.const2 = constant_field
# use a remapping channel
channel = source.new_remapping_channel_to(target, remapper=grid_remappers.conservative_spherical_remapper)
# 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)
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)
| 13,425
| 40.95625
| 132
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_gasplummer.py
|
import numpy
from amuse.test import amusetest
from amuse.units import nbody_system
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()
self.assertEqual(mass[0], 0.5)
self.assertEqual(mass[1], 0.5)
self.assertAlmostEqual(x, [-0.02295788, 0.12829775])
self.assertAlmostEqual(y, [-0.41054985, 0.14190860])
self.assertAlmostEqual(z, [-0.50723639, 0.08937734])
self.assertAlmostEqual(vx, [0.0, 0.0])
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)
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)
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.assertAlmostEqual(gas.thermal_energy(), 0.238075609078 | 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.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)
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.total_mass(), 1.00 | nbody_system.mass)
self.assertAlmostEqual(gas.virial_radius(), 1.00 | nbody_system.length)
| 3,532
| 50.202899
| 109
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_concurrent.py
|
import os
from amuse.test.amusetest import TestWithMPI
from amuse.ext import concurrent
from amuse.rfi.core import *
from amuse.ic.plummer import new_plummer_sphere
from amuse.units import nbody_system
import numpy
class ConcurrentTestingInterface(PythonCodeInterface):
def __init__(self, implementation_factory, **options):
PythonCodeInterface.__init__(self, implementation_factory=implementation_factory, **options)
@legacy_function
def do_concurrent_run():
function = LegacyFunctionSpecification()
function.addParameter('output', dtype='string', direction=function.OUT)
function.result_type = 'int32'
function.can_handle_array = True
function.id = 10
return function
class Test1Implementation(object):
def create_particles(self):
self.particles = new_plummer_sphere(100)
def do_concurrent_run(self, output):
processes = concurrent.MPIConcurrentProcesses()
processes.init()
try:
self.particles = None
processes.on_root(self.create_particles)
shared_particles = processes.share(self.particles)
shared_particles.distribute()
assert len(shared_particles) == 100, '{0} != 100'.format(len(shared_particles))
output.value = str('success')
result = 0
except Exception as ex:
output.value = str(ex)
result = -1
return self.reduce_result(processes, result)
def reduce_result(self, processes, result):
mpi_comm = processes.mpi_comm
from mpi4py import MPI
input = numpy.zeros(1, dtype='int64')
output = numpy.zeros(1, dtype='int64')
input[0] = result
if mpi_comm.rank == 0:
mpi_comm.Reduce(
[input, MPI.INTEGER8],
[output, MPI.INTEGER8],
op=MPI.SUM,
root=0
)
else:
mpi_comm.Reduce(
[input, MPI.INTEGER8],
[output, MPI.INTEGER8],
op=MPI.SUM,
root=0
)
return output[0]
class Test3Implementation(Test1Implementation):
def do_concurrent_run(self, output):
processes = concurrent.MPIConcurrentProcesses()
processes.init()
test = TestMPIConcurrentProcesses('test1')
try:
self.particles = None
processes.on_root(self.create_particles)
shared_particles = processes.share(self.particles)
shared_particles.distribute()
test.assertEqual(len(shared_particles), 100)
test.assertAlmostRelativeEquals(shared_particles.mass.sum(), 1.0 | nbody_system.mass)
output.value = str('success')
result = 0
except Exception as ex:
print(ex)
output.value = str(ex)
result = -1
return self.reduce_result(processes, result)
class Test4Implementation(Test1Implementation):
def root_potential_energy(self):
self.potential_energy = self.particles.potential_energy(G=nbody_system.G)
def distributed_potential_energy_on_root(self):
test = TestMPIConcurrentProcesses('test1')
self.distributed_potential_energy = self.shared_particles.potential_energy(G=nbody_system.G)
test.assertAlmostRelativeEquals(self.distributed_potential_energy, self.potential_energy)
def distributed_potential_energy_not_on_root(self):
self.distributed_potential_energy = self.shared_particles.potential_energy(G=nbody_system.G)
def do_concurrent_run(self, output):
processes = concurrent.MPIConcurrentProcesses()
processes.init()
test = TestMPIConcurrentProcesses('test1')
self.particles = None
self.potential_energy = 0
try:
processes.on_root(self.create_particles)
processes.on_root(self.root_potential_energy)
self.shared_particles = processes.share(self.particles)
self.shared_particles.distribute()
processes.call(
self.distributed_potential_energy_on_root,
self.distributed_potential_energy_not_on_root,
)
output.value = str('success')
result = 0
except Exception as ex:
print(ex)
output.value = str(ex)
result = -1
return self.reduce_result(processes, result)
class TestMPIConcurrentProcesses(TestWithMPI):
def setUp(self):
pass
def tearDown(self):
os.remove("test_concurrent")
def test1(self):
x = ConcurrentTestingInterface(implementation_factory=Test1Implementation)
output, error = x.do_concurrent_run()
self.assertEqual(error, 0, msg=output)
def test2(self):
x = ConcurrentTestingInterface(
implementation_factory=Test1Implementation,
number_of_workers=4
)
output, error = x.do_concurrent_run()
self.assertEqual(error, 0, msg=output)
def test3(self):
x = ConcurrentTestingInterface(
implementation_factory=Test3Implementation,
number_of_workers=4
)
output, error = x.do_concurrent_run()
self.assertEqual(error, 0, msg=output)
def test4(self):
x = ConcurrentTestingInterface(
implementation_factory=Test4Implementation,
number_of_workers=4
)
output, error = x.do_concurrent_run()
self.assertEqual(error, 0, msg=output)
| 5,575
| 31.231214
| 100
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_particles_with_color.py
|
import numpy
from amuse.test.amusetest import TestCase
from amuse.units import units
from amuse.datamodel import Particles
from amuse.ext.particles_with_color import *
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])
)
self.assertEqual(with_color.red, [1, 1, 1, 0])
self.assertEqual(with_color.green, [0, 1, 1, 0])
self.assertEqual(with_color.blue, [0, 0, 1, 1])
self.assertEqual(with_color.color, [[1, 0, 0], [1, 1, 0], [1, 1, 1], [0, 0, 1]])
with_color.mass = [3, 2, 1, 0.1] | units.MSun
self.assertEqual(with_color.red, [0, 1, 1, 1])
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)
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))
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))
| 2,457
| 53.622222
| 114
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_molecular_cloud.py
|
import sys
import os
import numpy.random
from amuse.test import amusetest
from amuse.units import units, nbody_system
from amuse.ext.molecular_cloud import molecular_cloud, ism_cube
from amuse.ext.evrard_test import sobol_unit_cube
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)
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)
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)
| 1,443
| 35.1
| 94
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_flatimf.py
|
import numpy
from amuse.test import amusetest
from amuse.units import units, nbody_system
from amuse.ic.flatimf import FlatIMF
from amuse.ic.flatimf import new_flat_mass_distribution, new_flat_mass_distribution_nbody
class FlatIMFTests(amusetest.TestCase):
def test1(self):
instance = FlatIMF(0.1 | units.MSun, 100.0 | units.MSun)
self.assertAlmostEqual(instance.mass_mean(), 99.9/numpy.log(1e3) | units.MSun)
instance = FlatIMF(42.0 | units.MSun, 42.00001 | units.MSun)
self.assertAlmostEqual(instance.mass_mean(), 42.000 | units.MSun, 3)
def test2(self):
instance = FlatIMF(0.1 | units.MSun, 1000.0 | units.MSun)
self.assertAlmostEqual(instance.mass(1.0), 1000.0 | units.MSun)
self.assertAlmostEqual(instance.mass(0.75), 100.0 | units.MSun)
self.assertAlmostEqual(instance.mass(0.5), 10.0 | units.MSun)
self.assertAlmostEqual(instance.mass(0.25), 1.0 | units.MSun)
self.assertAlmostEqual(instance.mass(0.0), 0.1 | units.MSun)
def test3(self):
numpy.random.seed(345672)
instance = FlatIMF(0.1 | units.MSun, 100 | units.MSun)
n = 10000
total_mass, set_of_masses = instance.next_set(n)
mean_mass = 99.9/numpy.log(1e3) | units.MSun
self.assertAlmostEqual(instance.mass_mean(), mean_mass)
self.assertAlmostRelativeEqual(total_mass / n, mean_mass, 3)
self.assertAlmostEqual(total_mass / n, 14.4615334306 | units.MSun)
self.assertAlmostEqual(instance.mass(0.5), set_of_masses.median(), 1)
def test4(self):
print("Test 4: testing user interface (SI units)")
numpy.random.seed(345672)
masses = new_flat_mass_distribution(10000)
self.assertEqual(len(masses), 10000)
self.assertAlmostRelativeEqual(masses.mean(), FlatIMF().mass_mean(), 3)
self.assertAlmostEqual(masses.mean(), 17.5145247111 | units.MSun)
self.assertAlmostEqual(masses.amin(), 0.100145673289 | units.MSun)
self.assertAlmostEqual(masses.amax(), 124.94980234 | units.MSun)
def test5(self):
print("Test 5: testing user interface (SI units), optional args")
numpy.random.seed(345672)
masses = new_flat_mass_distribution(10000,
mass_min=10.0 | units.MSun, mass_max=100.0 | units.MSun)
self.assertEqual(len(masses), 10000)
self.assertAlmostRelativeEqual(masses.mean(),
FlatIMF(mass_min=10.0 | units.MSun, mass_max=100.0 | units.MSun).mass_mean(), 2)
self.assertAlmostEqual(masses.mean(), 39.1111546565 | units.MSun)
self.assertAlmostEqual(masses.amin(), 10.0047015091 | units.MSun)
self.assertAlmostEqual(masses.amax(), 99.9870310764 | units.MSun)
def test6(self):
print("Test 6: testing user interface (nbody units)")
numpy.random.seed(345672)
n = 10000
masses = new_flat_mass_distribution_nbody(n)
self.assertEqual(len(masses), n)
self.assertAlmostEqual(masses.sum(), 1.0 | nbody_system.mass)
self.assertAlmostEqual(masses.mean(), 1.0 / n | nbody_system.mass)
self.assertAlmostEqual(masses.amin(), 0.100145673289 / 17.5145247111 / n | nbody_system.mass)
self.assertAlmostEqual(masses.amax(), 124.94980234 / 17.5145247111 / n | nbody_system.mass)
def test7(self):
print("Test 7: testing user interface (nbody units), optional args")
numpy.random.seed(345672)
n = 10000
masses = new_flat_mass_distribution_nbody(n,
mass_min=10.0 | nbody_system.mass, mass_max=100.0 | nbody_system.mass)
self.assertEqual(len(masses), n)
self.assertAlmostEqual(masses.sum(), 1.0 | nbody_system.mass)
self.assertAlmostEqual(masses.mean(), 1.0 / n | nbody_system.mass)
self.assertAlmostEqual(masses.amin(), 10.0047015091 / 39.1111546565 / n | nbody_system.mass)
self.assertAlmostEqual(masses.amax(), 99.9870310764 / 39.1111546565 / n | nbody_system.mass)
| 4,008
| 45.616279
| 101
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_brokenimf.py
|
import numpy
from amuse.test import amusetest
from amuse.units import units, nbody_system
from amuse.ic.brokenimf import *
# 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)
self.assertEqual(instance.mass_boundaries, [0.1, 100.0] | units.MSun)
self.assertEqual(instance.alphas, [-2.35])
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)
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)
self.assertTrue((masses >= 0.1 | units.MSun).all())
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,
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)
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,
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)
self.assertTrue((masses >= 0.1 | units.MSun).all())
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,
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)
self.assertTrue((masses >= 0.1 | units.MSun).all())
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,
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)
self.assertTrue((masses >= 0.01 | units.MSun).all())
roundoff = 1.0 + 1.0e-12
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,
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)
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,
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)
| 6,819
| 51.061069
| 115
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_distributed_particles.py
|
from amuse.datamodel import AbstractSet
from amuse.test.amusetest import TestWithMPI
from amuse.ext import concurrent
from amuse import datamodel
from amuse.rfi.core import *
from amuse.ic.plummer import new_plummer_sphere
from amuse.units import nbody_system
from amuse.units import units
from amuse.community import *
from amuse.support.interface import InCodeComponentImplementation
from amuse.io import read_set_from_file, write_set_to_file
from collections import namedtuple
import numpy
import pickle
try:
from mpi4py import MPI
except ImportError:
MPI = None
import base64
def dump_and_encode(x):
return base64.b64encode(pickle.dumps(x)).decode()
def decode_and_load(x):
return pickle.loads(base64.b64decode(x.encode()))
class DistributedParticlesInterface(PythonCodeInterface):
def __init__(self, implementation_factory, **options):
PythonCodeInterface.__init__(self, implementation_factory=implementation_factory, **options)
@legacy_function
def get_length():
function = LegacyFunctionSpecification()
function.addParameter('reference', dtype='int64', direction=function.IN)
function.addParameter('len_out', dtype='int64', direction=function.OUT)
function.result_type = 'int32'
return function
@legacy_function
def do_init():
function = LegacyFunctionSpecification()
function.addParameter('size', dtype='int64', direction=function.IN)
function.addParameter('reference_out', dtype='int64', direction=function.OUT)
function.result_type = 'int32'
return function
@legacy_function
def do_set_attribute():
function = LegacyFunctionSpecification()
function.addParameter('reference', dtype='int64', direction=function.IN)
function.addParameter('name_of_the_attribute', dtype='string', direction=function.IN)
function.addParameter('pickled_value', dtype='string', direction=function.IN)
function.result_type = 'int32'
return function
@legacy_function
def do_get_attribute():
function = LegacyFunctionSpecification()
function.addParameter('reference', dtype='int64', direction=function.IN)
function.addParameter('name_of_the_attribute', dtype='string', direction=function.IN)
function.addParameter('output', dtype='string', direction=function.OUT)
function.result_type = 'int32'
return function
@legacy_function
def do_getitem():
function = LegacyFunctionSpecification()
function.addParameter('reference_in', dtype='int64', direction=function.IN)
function.addParameter('pickled_index', dtype='string', direction=function.IN)
function.addParameter('is_particle_out', dtype='bool', direction=function.OUT)
function.addParameter('reference_out', dtype='int64', direction=function.OUT)
function.result_type = 'int32'
return function
@legacy_function
def set_from_generator():
function = LegacyFunctionSpecification()
function.addParameter('reference_in', dtype='int64', direction=function.IN)
function.addParameter('pickled_generator', dtype='string', direction=function.IN)
function.addParameter('pickled_args', dtype='string', direction=function.IN)
function.addParameter('pickled_kwargs', dtype='string', direction=function.IN)
function.result_type = 'int32'
return function
@legacy_function
def select_array():
function = LegacyFunctionSpecification()
function.addParameter('reference_in', dtype='int64', direction=function.IN)
function.addParameter('pickled_function', dtype='string', direction=function.IN)
function.addParameter('pickled_attributes', dtype='string', direction=function.IN)
function.addParameter('reference_out', dtype='int64', direction=function.OUT)
function.result_type = 'int32'
return function
@legacy_function
def write_set_to_file():
function = LegacyFunctionSpecification()
function.addParameter('reference_in', dtype='int64', direction=function.IN)
function.addParameter('filebase', dtype='string', direction=function.IN)
function.addParameter('fileformat', dtype='string', direction=function.IN)
function.addParameter('pickled_filenames', dtype='string', direction=function.OUT)
function.result_type = 'int32'
return function
@legacy_function
def read_set_from_file():
function = LegacyFunctionSpecification()
function.addParameter('reference_in', dtype='int64', direction=function.IN)
function.addParameter('pickled_filenames', dtype='string', direction=function.IN)
function.addParameter('fileformat', dtype='string', direction=function.IN)
function.result_type = 'int32'
return function
class DistributedParticlesCode(InCodeComponentImplementation):
def __init__(self, **options):
interface = DistributedParticlesInterface(
implementation_factory=DistributedParticlesImplementation,
**options
)
InCodeComponentImplementation.__init__(
self,
interface,
**options
)
class DistributedParticles(object):
def __init__(self, size=0, reference=0, code=None, **options):
if code is None:
code = DistributedParticlesCode(**options)
code.do_init(size)
reference = 0
object.__setattr__(self, "code", code)
object.__setattr__(self, "reference", reference)
def __len__(self):
return self.code.get_length(self.reference)
def __setattr__(self, name_of_the_attribute, value):
self.code.do_set_attribute(
self.reference,
name_of_the_attribute,
dump_and_encode(value)
)
def __getattr__(self, name_of_the_attribute):
result = self.code.do_get_attribute(self.reference, name_of_the_attribute)
return decode_and_load(result)
def __getitem__(self, index):
is_particle, reference = self.code.do_getitem(
self.reference,
dump_and_encode(index)
)
if is_particle:
return DistributedParticle(
code=self.code,
reference=reference
)
else:
return DistributedParticles(
code=self.code,
reference=reference
)
def set_from_generator(self, func, args=(), kwargs={}):
self.code.set_from_generator(self.reference, dump_and_encode(func),
dump_and_encode(args), dump_and_encode(kwargs))
def select_array(self, function, attributes):
reference = self.code.select_array(self.reference,
dump_and_encode(function),
dump_and_encode(attributes)
)
return DistributedParticles(
code=self.code,
reference=reference
)
def write_set_to_file(self, filebase, fileformat):
filenames = self.code.write_set_to_file(self.reference, filebase, fileformat)
return decode_and_load(filenames)
def read_set_from_file(self, filenames, fileformat):
if self.reference != 0:
raise Exception("read only allowed to root set")
self.code.read_set_from_file(self.reference,
dump_and_encode(filenames),
fileformat)
class DistributedParticle(object):
def __init__(self, reference, code, **options):
object.__setattr__(self, "code", code)
object.__setattr__(self, "reference", reference)
def __setattr__(self, name_of_the_attribute, value):
self.code.do_set_attribute(
self.reference,
name_of_the_attribute,
dump_and_encode(value)
)
def __getattr__(self, name_of_the_attribute):
return decode_and_load(self.code.do_get_attribute(self.reference, name_of_the_attribute))
ReferencedParticles = namedtuple('ReferencedParticles', ['particles', 'local_offset', 'local_size', 'global_size'])
class DistributedParticlesImplementation(object):
EmptyReference = ReferencedParticles(
None,
0,
0,
0
)
def do_init(self, size, reference_out):
self.mpi_comm = MPI.COMM_WORLD
self.rank = MPI.COMM_WORLD.Get_rank()
self.number_of_processes = MPI.COMM_WORLD.Get_size()
local_size = size // self.number_of_processes
left_over = size - (local_size * self.number_of_processes)
if self.rank == 0:
local_size += left_over
local_offset = 0
else:
local_offset = (local_size * self.rank) + left_over
self.reference_counter = 0
self.references_to_particles = {}
real_particles = datamodel.Particles(local_size)
self.references_to_particles[self.reference_counter] = ReferencedParticles(
real_particles,
local_offset,
local_size,
size
)
reference_out.value = self.reference_counter
self.reference_counter += 1
return 0
def get_length(self, reference, len_out):
particles_len = self.references_to_particles[reference].local_size
input = numpy.zeros(1, dtype='int64')
output = numpy.zeros(1, dtype='int64')
input[0] = particles_len
self.mpi_comm.Reduce(
[input, MPI.INTEGER],
[output, MPI.INTEGER],
op=MPI.SUM,
root=0
)
len_out.value = output[0]
return 0
def do_set_attribute(self, reference, name_of_the_attribute, pickled_value):
real_particles, local_offset, local_size, global_size = self.references_to_particles[reference]
value = decode_and_load(pickled_value)
if not real_particles is None:
if (is_quantity(value) and not value.is_scalar()) or hasattr(value, '__iter__'):
setattr(real_particles, name_of_the_attribute, value[local_offset:local_offset + local_size])
else:
setattr(real_particles, name_of_the_attribute, value)
return 0
def _merge_results(self, quantities):
values = []
value = None
quantities = [x for x in quantities if x[-1] is not None]
if len(quantities) == 0:
return None
if len(quantities) == 1:
local_size, local_offset, quantity = quantities[0]
if local_size == 0:
return quantity
total_size = 0
for local_size, local_offset, quantity in quantities:
total_size += local_size
first_quantity = quantities[0][-1]
result = numpy.zeros(total_size, dtype=first_quantity.dtype)
if is_quantity(first_quantity):
result = result | first_quantity.unit
for local_size, local_offset, quantity in quantities:
result[local_offset:local_offset+local_size] = quantity
return result
def do_get_attribute(self, reference, name_of_the_attribute, output):
real_particles, local_offset, local_size, global_size = self.references_to_particles[reference]
try:
quantity = [local_size, local_offset, getattr(real_particles, name_of_the_attribute)]
except:
quantity = [0, 0, None]
quantities = self.mpi_comm.gather(quantity, root=0)
if self.rank == 0:
value = self._merge_results(quantities)
else:
value = None
output.value = dump_and_encode(value)
return 0
def do_getitem(self, reference_in, pickled_index, is_particle_out, reference_out):
real_particles, local_offset, local_size, global_size = self.references_to_particles[reference_in]
index = decode_and_load(pickled_index)
self.references_to_particles[self.reference_counter] = self.EmptyReference
if isinstance(index, int):
if index >= local_offset and index < local_offset + local_size:
output_particles = real_particles[index - local_offset]
self.references_to_particles[self.reference_counter] = ReferencedParticles(
output_particles,
0,
0,
0
)
is_particle_out.value = True
elif isinstance(index, slice):
start, stop, step = index.indices(global_size)
start -= local_offset
stop -= local_offset
start = min(max(0, start), local_size)
stop = min(max(0, stop), local_size)
output_particles = real_particles[start:stop]
input = numpy.zeros(1, dtype='int64')
output = numpy.zeros(self.number_of_processes, dtype='int64')
input[0] = len(output_particles)
self.mpi_comm.Allgather(
[input, MPI.INTEGER],
[output, MPI.INTEGER]
)
total_size = 0
local_offset = 0
for i, current_size in enumerate(output):
if i < self.rank:
local_offset += current_size
total_size += current_size
referenced_particles = ReferencedParticles(
output_particles,
local_offset,
len(output_particles),
total_size
)
self.references_to_particles[self.reference_counter] = referenced_particles
is_particle_out.value = False # check, a slice could still result in 1 particle!!!
else:
raise Exception("need to parse index and do smart things here!!")
reference_out.value = self.reference_counter
self.reference_counter += 1
return 0
def set_from_generator(self, reference, pickled_generator, pickled_args=None, pickled_kwargs=None):
generator = decode_and_load(pickled_generator)
args = ()
if pickled_args is not None:
args = decode_and_load(pickled_args)
kwargs = {}
if pickled_kwargs is not None:
kwargs = decode_and_load(pickled_kwargs)
real_particles, local_offset, local_size, global_size = self.references_to_particles[reference]
particles = generator(local_offset, local_offset+local_size, *args, **kwargs)
keys = real_particles.get_all_keys_in_store()
real_particles.remove_particles(real_particles[:])
attributes = particles.get_attribute_names_defined_in_store()
indices = particles.get_all_indices_in_store()
values = particles.get_values_in_store(indices, attributes)
result = datamodel.Particles()
result.add_particles_to_store(keys, attributes, values)
real_particles.add_particles(result)
return 0
def select_array(self, reference_in, pickled_function, pickled_attributes, reference_out):
real_particles, local_offset, local_size, global_size = self.references_to_particles[reference_in]
function = decode_and_load(pickled_function)
attributes = decode_and_load(pickled_attributes)
output_particles = real_particles.select_array(function, attributes)
input = numpy.zeros(1, dtype='int64')
output = numpy.zeros(self.number_of_processes, dtype='int64')
input[0] = len(output_particles)
self.mpi_comm.Allgather(
[input, MPI.INTEGER],
[output, MPI.INTEGER]
)
total_size = 0
local_offset = 0
for i, current_size in enumerate(output):
if i < self.rank:
local_offset += current_size
total_size += current_size
referenced_particles = ReferencedParticles(
output_particles,
local_offset,
len(output_particles),
total_size
)
self.references_to_particles[self.reference_counter] = referenced_particles
reference_out.value = self.reference_counter
self.reference_counter += 1
return 0
def write_set_to_file(self, reference_in, filebase, fileformat, filenames_out):
real_particles, local_offset, local_size, global_size = self.references_to_particles[reference_in]
filename = filebase+"_%6.6i" % self.rank
write_set_to_file(real_particles, filename, fileformat,
local_offset=local_offset, local_size=local_size, global_size=global_size, overwrite_file=True)
filenames = self.mpi_comm.gather(filename, root=0)
if self.rank == 0:
value = filenames
else:
value = None
filenames_out.value = dump_and_encode(value)
return 0
def read_set_from_file(self, reference_in, filenames_in, fileformat):
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],
[output, MPI.INTEGER]
)
total_size = 0
local_offset = 0
for i, current_size in enumerate(output):
if i < self.rank:
local_offset += current_size
total_size += current_size
referenced_particles = ReferencedParticles(
real_particles,
local_offset,
len(real_particles),
total_size
)
self.references_to_particles[reference_in] = referenced_particles
return 0
def generate_set_example_function(start, end, *args, **kwargs):
from amuse.datamodel import Particles
p = Particles(end-start)
p.index = range(start, end)
return p
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]
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
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
)
self.assertEqual(len(x), 3)
x.mass = 10 | units.MSun
self.assertEqual(x.mass, [10, 10, 10] | units.MSun)
def test2(self):
x = DistributedParticles(
size=3,
number_of_workers=1
)
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)
def test3(self):
x = DistributedParticles(
size=3,
number_of_workers=1
)
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)
def test4(self):
x = DistributedParticles(
size=3,
number_of_workers=1
)
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)
def test5(self):
x = DistributedParticles(
size=8,
number_of_workers=2
)
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)
def test6(self):
x = DistributedParticles(
size=9,
number_of_workers=2
)
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)
def test7(self):
x = DistributedParticles(
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[3:7]), 4)
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])
def test8(self):
x = DistributedParticles(
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[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)
def test9(self):
x = DistributedParticles(
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[3:7]), 4)
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
)
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)))
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)
x = DistributedParticles(
size=10,
number_of_workers=2
)
x.set_from_generator(generate_set_example_function)
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)
x = DistributedParticles(
size=10,
number_of_workers=2
)
x.set_from_generator(generate_set_example_function)
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)
def test13(self):
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",))
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)
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)
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)
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])
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)
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")
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)
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)
x = DistributedParticles(
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")
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)
# 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)
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")
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)
def test19(self):
from .test_distributed_particles import distributed_king_generator
from amuse.ic.kingmodel import MakeKingModel
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)
| 29,847
| 34.533333
| 115
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_limepy.py
|
import numpy
from amuse.test import amusetest
from amuse.units import nbody_system
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
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)
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)
self.assertAlmostEqual(cluster.total_mass(), 200. | units.MSun)
self.assertEqual(len(cluster), 100)
def setUp(self):
if not limepy.scipy_imported:
self.skip("scipy not installed")
| 941
| 28.4375
| 72
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_stellar_wind.py
|
import numpy
from amuse.test import amusetest
from amuse.units import units, quantities
from amuse.datamodel.particles import Particles, Particle
# from amuse.community.sse.interface import SSE
from amuse.community.seba.interface import SeBa
from amuse.ext import stellar_wind
from amuse.support.console import set_preferred_units
from amuse.support.console import set_printing_strategy
class TestStellarWind(amusetest.TestCase):
def setUp(self):
set_preferred_units(units.MSun, units.RSun, units.yr, units.kms,
units.kms**2, units.m/units.s**2, units.W, units.erg)
def skip_no_scipy(self):
try:
import scipy
except ImportError:
self.skip("Failed to import scipy")
def assertAllAlmostEqual(self, values, expected, *args, **kwargs):
for value in values:
self.assertAlmostEqual(value, expected, *args, **kwargs)
def assertDecreasing(self, array):
delta = array[1:] - array[:-1]
for d in delta:
self.assertLess(d, quantities.zero)
def create_star(self, N=1):
star = Particles(N)
star.mass = 2 | units.MSun
star.radius = 2 | units.RSun
star.temperature = 5000 | units.K
star.position = [1, 1, 1] | units.parsec
star.velocity = [-1000, 0, 1000] | units.ms
star.wind_mass_loss_rate = 1e-6 | units.MSun / units.yr
star.initial_wind_velocity = 50 | units.ms
star.terminal_wind_velocity = 500 | units.ms
return star
def create_stars_without_wind_attributes(self):
stars = Particles(2)
stars.mass = 2 | units.MSun
stars.radius = 2 | units.RSun
stars.temperature = 5000 | units.K
stars.luminosity = 2 | units.LSun
stars.age = 0 | units.Myr
stars[0].position = [1, 1, 1] | units.parsec
stars[1].position = [-1, -1, -1] | units.parsec
stars[0].velocity = [-1000, 0, 1000] | units.ms
stars[1].velocity = [0, 0, 0] | units.ms
return stars
def tearDown(self):
set_printing_strategy('default')
class TestStarsWithMassLoss(TestStellarWind):
def test_add_particles(self):
star_particles = self.create_star(2)
print("created parts")
stars = stellar_wind.StarsWithMassLoss()
print("created stars")
stars.add_particles(star_particles)
print("added", stars)
self.assertEqual(stars.lost_mass, [0, 0] | units.MSun)
self.assertEqual(stars.wind_release_time, [0, 0] | units.yr)
self.assertAlmostEqual(stars.mu[0], 1.145934546 | units.amu)
def test_add_particle(self):
star_particles = self.create_star(1)
stars = stellar_wind.StarsWithMassLoss()
star = stars.add_particle(star_particles[0])
self.assertEqual(star.lost_mass, 0 | units.MSun)
self.assertEqual(star.wind_release_time, 0 | units.yr)
self.assertAlmostEqual(star.mu, 1.145934546 | units.amu)
attrs = stars.get_attribute_names_defined_in_store()
self.assertFalse("mechanical_energy" in attrs)
self.assertFalse("previous_mechanical_luminosity" in attrs)
def test_default_lmech(self):
star_particles = self.create_star(1)
stars = stellar_wind.StarsWithMassLoss()
stars.track_mechanical_energy()
star = stars.add_particle(star_particles[0])
self.assertEqual(star.mechanical_energy, 0 | units.J)
def test_add_particle_later(self):
star_particles = self.create_star(2)
stars = stellar_wind.StarsWithMassLoss()
stars.add_particle(star_particles[0])
stars.evolve_mass_loss(1 | units.yr)
new_star = stars.add_particle(star_particles[1])
self.assertAlmostEqual(new_star.wind_release_time, 1 | units.yr)
def test_superfluous_attributes(self):
star_particles = self.create_star(2)
star_particles.other_attr = 10 | units.yr
stars = stellar_wind.StarsWithMassLoss()
stars.add_particles(star_particles)
self.assertRaises(AttributeError, stars.__getattr__, "other_attr")
def test_add_wrong_attribute(self):
star_particles = self.create_star(2)
star_particles
stars = stellar_wind.StarsWithMassLoss()
stars.add_particles(star_particles)
self.assertRaises(AttributeError, stars.__setattr__, "other_attr", 10)
class FakeStevCode(object):
def __init__(self, *args, **kwargs):
self.particles = Particles()
self.model_time = 0 | units.Myr
self.mass_loss_rate = 1e-11 | units.MSun/units.yr
def evolve_model(self, time):
dt = time - self.model_time
self.model_time = time
self.particles.mass -= self.mass_loss_rate * dt
self.particles.age = time
class TestPositionGenerator(TestStellarWind):
def test_random_cube(self):
numpy.random.seed(1232367)
gen = stellar_wind.PositionGenerator('random')
cube = gen.cube_generator(1000)
self.assertEqual(cube.shape, (1000, 3))
self.assertAlmostEqual(cube.min(), -0.99970440813)
self.assertAlmostEqual(cube.max(), 0.997978975085)
def test_regular_cube(self):
numpy.random.seed(1232367)
gen = stellar_wind.PositionGenerator(grid_type="regular")
cube = gen.cube_generator(25)
print(cube)
self.assertEqual(cube.shape, (25, 3))
self.assertAlmostEqual(cube.min(), -2./3.)
self.assertAlmostEqual(cube.max(), 2./3.)
def test_cutout_sphere(self):
points = [[0., 0., 0.],
[1., 1., 1.],
[-1., -1., -1.],
[-0., 0., -.99],
[0., .5, 0.],
]
points = numpy.array(points)
gen = stellar_wind.PositionGenerator()
remaining = gen.cutout_sphere(points, 0.1)
self.assertEqual(len(remaining), 2)
self.assertEqual(remaining, points[-2:])
def test_uniform_hollow_sphere(self):
numpy.random.seed(1232367)
gen = stellar_wind.PositionGenerator()
points = gen.uniform_hollow_sphere(2, 0.6)
self.assertEqual(len(points), 2)
points = gen.uniform_hollow_sphere(1000, 0.1)
self.assertEqual(len(points), 1000)
def test_regular_hollow_sphere(self):
numpy.random.seed(1232367)
gen = stellar_wind.PositionGenerator(grid_type="regular")
points = gen.uniform_hollow_sphere(2, 0.6)
self.assertEqual(len(points), 2)
points = gen.uniform_hollow_sphere(1000, 0.1)
self.assertEqual(len(points), 1000)
def test_density_distribution(self):
numpy.random.seed(1234567)
N = 100000
rmin = 1 | units.RSun
rmax = 10 | units.RSun
gen = stellar_wind.PositionGenerator()
p, _ = gen.generate_positions(N, rmin, rmax)
r = p.lengths()
print('rmin', r.min())
print('rmax', r.max())
print(r.mean())
self.assertEqual(len(r), N)
self.assertGreaterEqual(r.min(), rmin)
self.assertLessEqual(r.max(), rmax)
self.assertAlmostEqual(r.mean(), 5.49955427602 | units.RSun)
return
r = r.value_in(units.RSun)
n_bins = 50
n, bins = numpy.histogram(r, n_bins, range=(1, 10))
bin_volume = 4./3. * numpy.pi * (bins[1:]**3 - bins[:-1]**3)
dens = n / bin_volume
bin_means = (bins[1:] + bins[:-1])/2.
s = p[abs(p[:, 2]) < (0.1 | units.RSun)]
from matplotlib import pyplot
from amuse import plot as aplot
aplot.plot(s[:, 0], s[:, 1], '.')
pyplot.axis('equal')
pyplot.savefig("scatter.pdf")
pyplot.clf()
x = numpy.linspace(1, 10, num=200)
y = 300. / x**2
# y = 0. * x + dens.mean()
from matplotlib import pyplot
# pyplot.plot(x, y)
pyplot.loglog(x, y)
pyplot.plot(bin_means, dens, '*')
pyplot.savefig("dens.pdf")
def test_alternate_radius_function(self):
numpy.random.seed(123)
gen = stellar_wind.PositionGenerator()
# func = stellar_wind.LogisticVelocityAcceleration().radius_from_number
func = stellar_wind.ConstantVelocityAcceleration().radius_from_number
N = 100000
rmin = 2 | units.RSun
rmax = 6 | units.RSun
star = Particle()
star.radius = rmin
star.acc_cutoff = 10 | units.RSun
star.initial_wind_velocity = 4 | units.kms
star.terminal_wind_velocity = 12 | units.kms
p, _ = gen.generate_positions(N, rmin, rmax, func, star)
r = p.lengths()
self.assertEqual(len(r), N)
self.assertGreaterEqual(r.min(), rmin)
self.assertLessEqual(r.max(), rmax)
print(r.mean())
self.assertAlmostEqual(r.mean(), 4.00196447056 | units.RSun)
return
r = r.value_in(units.RSun)
n_bins = 50
n, bins = numpy.histogram(r, n_bins)
bin_volume = 4./3. * numpy.pi * (bins[1:]**3 - bins[:-1]**3)
dens = n / bin_volume
bin_means = (bins[1:] + bins[:-1])/2.
from matplotlib import pyplot
pyplot.plot(bin_means, dens, '*')
pyplot.savefig("dens.pdf")
def test_random_rotation(self):
numpy.random.seed(1232367)
gen = stellar_wind.PositionGenerator()
axis, angle = gen.random_rotation()
print(axis)
print(angle)
self.assertEqual(len(axis), 3)
self.assertAlmostEqual((axis**2).sum(), 1.)
self.assertGreaterEqual(angle, 0.)
self.assertLessEqual(angle, 2. * numpy.pi)
def test_rotation_matrix(self):
gen = stellar_wind.PositionGenerator()
axis = [0, 0, 1]
angle = numpy.pi
matrix = gen.rotation_matrix(axis, angle)
print(numpy.rint(matrix))
expected = [[-1, 0, 0], [0, -1, 0], [0, 0, 1]]
self.assertAlmostEqual(matrix, expected)
def test_rotate_positions(self):
gen = stellar_wind.PositionGenerator()
axis = [0, 1, 0]
angle = numpy.pi
positions = [[0.5, 0.5, 0.5], [0.2, -0.5, 1.3]]
rotated = gen.rotate_positions(positions, axis, angle)
print(rotated)
expected = [[-0.5, 0.5, -0.5], [-0.2, -0.5, -1.3]]
self.assertAlmostEqual(rotated, expected)
class TestSimpleWind(TestStellarWind):
def test_wind_particles(self):
star = self.create_star()
star_wind = stellar_wind.new_stellar_wind(1e-8 | units.MSun)
star_wind.particles.add_particles(star)
star_wind.evolve_model(1 | units.yr)
wind = star_wind.create_wind_particles()
self.assertEqual(len(wind), 100)
min_dist = (wind.position - star.position).lengths().min()
max_dist = (wind.position - star.position).lengths().max()
self.assertGreaterEqual(min_dist, 2 | units.RSun)
self.assertLessEqual(max_dist, 24.7 | units.RSun)
plus_x_wind = wind[wind.x > star.x]
minus_x_wind = wind[wind.x < star.x]
plus_y_wind = wind[wind.y > star.y]
minus_y_wind = wind[wind.y < star.y]
plus_z_wind = wind[wind.z > star.z]
minus_z_wind = wind[wind.z < star.z]
self.assertGreaterEqual(minus_x_wind.vx.min(), -1500 | units.ms)
self.assertLessEqual(minus_x_wind.vx.max(), -1000 | units.ms)
self.assertGreaterEqual(plus_x_wind.vx.min(), -1000 | units.ms)
self.assertLessEqual(plus_x_wind.vx.max(), -500 | units.ms)
self.assertGreaterEqual(minus_y_wind.vy.min(), -500 | units.ms)
self.assertLessEqual(minus_y_wind.vy.max(), 0 | units.ms)
self.assertGreaterEqual(plus_y_wind.vy.min(), 0 | units.ms)
self.assertLessEqual(plus_y_wind.vy.max(), 500 | units.ms)
self.assertGreaterEqual(minus_z_wind.vz.min(), 500 | units.ms)
self.assertLessEqual(minus_z_wind.vz.max(), 1000 | units.ms)
self.assertGreaterEqual(plus_z_wind.vz.min(), 1000 | units.ms)
self.assertLessEqual(plus_z_wind.vz.max(), 1500 | units.ms)
def test_create_wind_short_time(self):
numpy.random.seed(123457)
star = self.create_star()
star_wind = stellar_wind.new_stellar_wind(
1e-9 | units.MSun)
star_wind.particles.add_particles(star)
star_wind.evolve_model(0.01 | units.yr)
wind = star_wind.create_wind_particles()
self.assertEqual(len(wind), 10)
radii = (wind.position - star.position).lengths()
self.assertGreaterEqual(radii.min(), star.radius)
def test_target_gas(self):
star = self.create_star()
gas = Particles()
star_wind = stellar_wind.new_stellar_wind(
1e-8 | units.MSun, target_gas=gas, timestep=1 | units.day)
star_wind.particles.add_particles(star)
star_wind.evolve_model(1 | units.yr)
self.assertEqual(len(gas), 99)
star_wind.evolve_model(1.5 | units.yr)
self.assertEqual(len(gas), 149)
def test_compensate_gravity(self):
numpy.random.seed(123457)
star = self.create_star()
star_wind = stellar_wind.new_stellar_wind(
1e-8 | units.MSun, compensate_gravity=True,
grid_type="random", rotate=False)
star_wind.particles.add_particles(star)
star_wind.evolve_model(1 | units.yr)
wind = star_wind.create_wind_particles()
self.assertEqual(len(wind), 100)
radii = (wind.position - star.position).lengths()
wind_velocities = (wind.velocity - star.velocity).lengths()
r_sort = radii.argsort()
v_sorted = wind_velocities[r_sort]
print(v_sorted)
self.assertDecreasing(v_sorted)
self.assertAlmostEqual(v_sorted[0], 615.945250201 | units.kms)
self.assertAlmostEqual(v_sorted[-1], 176.050310315 | units.kms)
return
from matplotlib import pyplot
from amuse import plot as aplot
aplot.plot(radii[r_sort], v_sorted)
pyplot.show()
def test_later_star_add(self):
star1 = self.create_star()
gas = Particles()
star_wind = stellar_wind.new_stellar_wind(
1e-8 | units.MSun, target_gas=gas, timestep=1 | units.day)
star_wind.particles.add_particles(star1)
star_wind.evolve_model(1 | units.yr)
self.assertEqual(len(gas), 99)
star2 = self.create_star()[0]
star2.x = 50 | units.parsec
star_wind.particles.add_particle(star2)
star_wind.evolve_model(1.5 | units.yr)
self.assertEqual(len(gas), 198)
star1_gas = gas[gas.x < 25 | units.parsec]
star2_gas = gas - star1_gas
self.assertEqual(len(star1_gas), 149)
self.assertEqual(len(star2_gas), 49)
def test_derive_from_evolution(self):
stars = self.create_stars_without_wind_attributes()
stars[1].temperature = 16000 | units.K
stars[1].luminosity = 20 | units.LSun
star_wind = stellar_wind.new_stellar_wind(
1e-8 | units.MSun, derive_from_evolution=True, tag_gas_source=True)
stars = star_wind.particles.add_particles(stars)
stev = FakeStevCode()
stev.mass_loss_rate = [1e-7, 2e-7] | units.MSun/units.yr
stev.particles.add_particles(stars)
chan = stev.particles.new_channel_to(
star_wind.particles,
attributes=["age", "radius", "mass", "luminosity", "temperature"])
time = 0 | units.yr
while time < 2.1 | units.yr:
stev.evolve_model(time)
chan.copy()
star_wind.evolve_model(time)
time += 0.5 | units.yr
self.assertTrue(star_wind.has_new_wind_particles(),
"No new wind particles")
wind = star_wind.create_wind_particles()
self.assertEqual(len(wind), 59)
wind_0 = wind[wind.source == stars[0].key]
wind_1 = wind[wind.source == stars[1].key]
self.assertEqual(len(wind_0), 19)
self.assertEqual(len(wind_1), 40)
vel_0 = (wind_0.velocity - stars[0].velocity).lengths()
vel_1 = (wind_1.velocity - stars[1].velocity).lengths()
self.assertAllAlmostEqual(vel_0, 617.83472287 | units.kms)
self.assertAllAlmostEqual(vel_1, 864.87956297 | units.kms)
def test_static_wind_from_evolution(self):
stars = self.create_stars_without_wind_attributes()
star_wind = stellar_wind.new_stellar_wind(
1e-8 | units.MSun, derive_from_evolution=True)
stev = FakeStevCode()
stev.mass_loss_rate = [1e-11, 2e-11] | units.MSun/units.yr
stev.particles.add_particles(stars)
stellar_wind.static_wind_from_stellar_evolution(
star_wind, stev, 1.49 | units.Gyr, 1.495 | units.Gyr)
self.assertAlmostRelativeEquals(
star_wind.particles.wind_mass_loss_rate,
[1e-11, 2e-11] | units.MSun/units.yr,
places=5
)
self.assertAlmostRelativeEquals(
star_wind.particles.terminal_wind_velocity,
[615.521, 613.198] | units.kms, places=5)
class ConstantSubclass(stellar_wind.AccelerationFunction):
def acceleration_from_radius(self, radius, star):
return numpy.zeros_like(radius, dtype=float) | units.m/units.s**2
class RSquaredSubclass(stellar_wind.AccelerationFunction):
def scaling(self, star):
return 0.5 * ((star.terminal_wind_velocity**2
- star.initial_wind_velocity**2)
/ (1./star.radius - 1./star.acc_cutoff))
def acceleration_from_radius(self, r, star):
return self.scaling(star)/r**2
class TestAccelerationFunctions(TestStellarWind):
def create_star(self):
star = Particle()
star.radius = 2 | units.RSun
star.acc_cutoff = 10 | units.RSun
star.initial_wind_velocity = 4 | units.kms
star.terminal_wind_velocity = 12 | units.kms
return star
def test_default_acceleration_1(self):
self.skip_no_scipy()
func = ConstantSubclass()
self.constant_asserts(func)
def slowtest_default_acceleration_2(self):
self.skip_no_scipy()
func = RSquaredSubclass()
self.r_squared_asserts(func)
def test_constant_velocity(self):
func = stellar_wind.ConstantVelocityAcceleration()
self.constant_asserts(func)
def test_r_squared_velocity(self):
self.skip_no_scipy()
func = stellar_wind.RSquaredAcceleration()
self.r_squared_asserts(func)
def constant_asserts(self, func):
star = self.create_star()
star.initial_wind_velocity = star.terminal_wind_velocity
radii = [2., 4.] | units.RSun
accelerations = func.acceleration_from_radius(radii, star)
self.assertAlmostEqual(accelerations, [0., 0.] | units.m/units.s**2)
velocities = func.velocity_from_radius(radii, star)
self.assertAlmostEqual(velocities, [12., 12.] | units.kms)
times = (numpy.array([0, 1, 2, 3]) * star.radius
/ star.terminal_wind_velocity)
new_radii = func.radius_from_time(times, star)
self.assertAlmostEqual(new_radii, [2., 4., 6., 8.] | units.RSun)
random_numbers = numpy.linspace(0., 1., 4)
radii = func.radius_from_number(random_numbers, 5 | units.RSun, star)
self.assertAlmostEqual(radii, [2, 3., 4., 5] | units.RSun)
def r_squared_asserts(self, func):
star = self.create_star()
radii = [2., 4., 8., 10.] | units.RSun
accelerations = func.acceleration_from_radius(radii, star)
expected = (numpy.array([40., 10., 2.5, 1.6]) * 0.0014378145
| units.m/units.s**2)
self.assertAlmostEqual(accelerations, expected)
velocities = func.velocity_from_radius(radii, star)
expected = [4., 9.79795897113, 11.6619037897, 12.] | units.kms
self.assertAlmostEqual(velocities, expected)
times = (numpy.array([0., 1., 2., 3.]) * star.radius
/ star.initial_wind_velocity)
new_radii = func.radius_from_time(times, star)
exp = [2.0, 6.50863038599, 12.4140692531, 18.4140691706] | units.RSun
self.assertAlmostEqual(new_radii, exp)
x = numpy.linspace(0., 1., 4)
new_radii = func.radius_from_number(x, 5 | units.RSun, star)
expected = [2, 2.72665604616, 3.7783430146, 5] | units.RSun
self.assertAlmostEqual(new_radii, expected)
def test_radius_from_time(self):
self.skip_no_scipy()
func = stellar_wind.RSquaredAcceleration()
star = Particle()
star.radius = 312. | units.RSun
star.acc_cutoff = 312*5. | units.RSun
star.initial_wind_velocity = 2 | units.kms
star.terminal_wind_velocity = 20 | units.kms
times = [0., 25., 100.] | units.yr
print("times", times)
radii = func.radius_from_time(times, star)
print("radii", radii)
self.assertAlmostEqual(radii[0], 312. | units.RSun)
self.assertAlmostEqual(radii[1], 22644.6086263 | units.RSun)
self.assertAlmostEqual(radii[2], 90704.1183516 | units.RSun)
return
times = numpy.linspace(0., 1, 100) | units.yr
radii = func.radius_from_time(times, star)
print(radii)
from matplotlib import pyplot
from amuse import plot as aplot
aplot.plot(times, radii/star.radius)
pyplot.show()
def test_radius_from_number(self):
self.skip_no_scipy()
star = Particle(
initial_wind_velocity=200. | units.kms, mass=20. | units.MSun,
radius=10. | units.RSun, terminal_wind_velocity=1000. | units.kms)
star.acc_cutoff = 5. * star.radius
r_max = 24.2642526438 | units.RSun
x = 0.1
func = stellar_wind.RSquaredAcceleration()
radius = func.radius_from_number(x, r_max, star)
self.assertAlmostEqual(radius, 10.6029030808 | units.RSun)
class TestAcceleratingWind(TestStellarWind):
def test_wind_creation_constant(self):
numpy.random.seed(123457)
star = self.create_star()
star.initial_wind_velocity = star.terminal_wind_velocity
star_wind = stellar_wind.new_stellar_wind(
3e-11 | units.MSun,
mode="accelerate",
acceleration_function="constant_velocity",
)
star_wind.particles.add_particles(star)
star_wind.evolve_model(10 | units.day)
wind = star_wind.create_wind_particles()
self.assertEqual(len(wind), 912)
radii = (wind.position - star.position).lengths()
velocities = (wind.velocity - star.velocity).lengths()
self.assertGreaterEqual(radii.min(), star.radius)
self.assertLessEqual(radii.max(), 8.212 | units.RSun)
self.assertAlmostEqual(radii.mean(), 2.32897955194 | units.RSun)
self.assertAlmostEqual(velocities.min(), star.initial_wind_velocity)
self.assertAlmostEqual(velocities.max(), star.initial_wind_velocity)
return
from matplotlib import pyplot
from amuse import plot as aplot
import pylab
n, bins, patches = pylab.hist(radii.value_in(units.RSun), 10)
pylab.show()
pyplot.clf()
aplot.scatter(radii, velocities)
pyplot.show()
def test_wind_creation_rsquared(self):
self.skip_no_scipy()
numpy.random.seed(123457)
star = self.create_star()
star_wind = stellar_wind.new_stellar_wind(
3e-9 | units.MSun,
mode="accelerate",
acceleration_function="rsquared",
)
star_wind.particles.add_particles(star)
star_wind.evolve_model(10 | units.day)
wind = star_wind.create_wind_particles()
self.assertEqual(len(wind), 9)
radii = (wind.position - star.position).lengths()
velocities = (wind.velocity - star.velocity).lengths()
self.assertGreaterEqual(radii.min(), star.radius)
self.assertLessEqual(radii.max(), 12.023 | units.RSun)
self.assertAlmostEqual(radii.mean(), 2.06872960025 | units.RSun)
self.assertGreaterEqual(velocities.min(), star.initial_wind_velocity)
self.assertLessEqual(velocities.max(), star.terminal_wind_velocity)
self.assertAlmostEqual(velocities.mean(), 0.103550548126 | units.kms)
def test_acceleration(self):
star = self.create_star()
star.position = [1, 1, 1] | units.RSun
star_wind = stellar_wind.new_stellar_wind(
3e-11 | units.MSun,
mode="accelerate",
acceleration_function="rsquared",
compensate_gravity=False,
r_out_ratio=5,
)
star = star_wind.particles.add_particles(star)
distances = [2, 4, 5, 10] | units.RSun
accelerations = star_wind.acceleration(star, distances)
expected = ([0.00011120596693, 2.78014917326e-5, 1.77929547088e-5, 0.]
| units.m/units.s**2)
self.assertAlmostEqual(accelerations, expected)
def test_gravity_compensation(self):
star = self.create_star()
star.position = [1, 1, 1] | units.RSun
star_wind = stellar_wind.new_stellar_wind(
3e-11 | units.MSun,
mode="accelerate",
acceleration_function="constant_velocity",
compensate_gravity=True,
)
star = star_wind.particles.add_particles(star)
distances = [2, 4, 5, 10, 20] | units.RSun
accelerations = star_wind.acceleration(star, distances)
expected = ([137.213699216, 34.3034248039, 21.9541918745,
5.48854796862, 1.37213699216] | units.m/units.s**2)
self.assertAlmostEqual(accelerations, expected)
def test_pressure_compensation(self):
star = self.create_star()
star.position = [1, 1, 1] | units.RSun
star_wind = stellar_wind.new_stellar_wind(
3e-11 | units.MSun,
mode="accelerate",
acceleration_function="constant_velocity",
compensate_gravity=False,
compensate_pressure=True
)
star = star_wind.particles.add_particles(star)
distances = [2, 4, 5, 10] | units.RSun
accelerations = star_wind.acceleration(star, distances)
print(accelerations)
expected = ([-0.0187296577097, -0.00371643479392, -0.00220802076676,
-0.000438126811] | units.m/units.s**2)
self.assertAlmostEqual(accelerations, expected)
def test_get_gravity_at_point(self):
star = self.create_star()
star.position = [1, 1, 1] | units.RSun
star_wind = stellar_wind.new_stellar_wind(
3e-11 | units.MSun,
mode="accelerate",
acceleration_function="rsquared",
compensate_gravity=False,
compensate_pressure=False,
r_out_ratio=5,
)
star_wind.particles.add_particles(star)
# unaffected points
points = [[1, 1, -10], [1, 12, 0], [1, -10, 1],
[12, 0, 1]] | units.RSun
x, y, z = points.transpose()
ax, ay, az = star_wind.get_gravity_at_point(1, x, y, z)
zeros = [0, 0, 0, 0] | units.m/units.s**2
self.assertEqual(ax, zeros)
self.assertEqual(ay, zeros)
self.assertEqual(az, zeros)
# affected points
points = [[5.1, 1, 1], [1, 1, 5.1], [1, 7, 1], [1, 7, 8],
[-8, 1, 1]] | units.RSun
x, y, z = points.transpose()
ax, ay, az = star_wind.get_gravity_at_point(1, x, y, z)
result = quantities.as_vector_quantity([ax, ay, az]).transpose()
expected = [[2.64618600667e-05, 0.0, 0.0],
[0.0, 0.0, 2.64618600667e-05],
[0.0, 1.23562185478e-05, 0.0],
[0.0, 3.40573571553e-06, 3.97335833479e-06],
[-5.49165268791e-06, 0.0, 0.0]] | units.m / units.s**2
self.assertAlmostEqual(result, expected)
class TestHeatingWind(TestStellarWind):
def test_wind_creation(self):
numpy.random.seed(123456789)
star = self.create_star()
feedback_efficiency = 0.01
r_max = 10 | units.RSun
star_wind = stellar_wind.new_stellar_wind(
3e-10 | units.MSun,
mode="heating",
r_max=r_max,
feedback_efficiency=feedback_efficiency,
)
star_wind.particles.add_particles(star)
evolve_time = 1 | units.day
expected_u = 0.5*feedback_efficiency*star.terminal_wind_velocity**2
star_wind.evolve_model(evolve_time)
wind = star_wind.create_wind_particles()
self.assertEqual(len(wind), 9)
max_dist = (wind.position - star.position).lengths().max()
self.assertLessEqual(max_dist, r_max + star.radius)
self.assertAlmostEqual(max_dist, 8.69397162579 | units.RSun)
self.assertAllAlmostEqual(wind.u, expected_u)
for t in numpy.arange(2, 10) * evolve_time:
star_wind.evolve_model(t)
wind = star_wind.create_wind_particles()
self.assertEqual(len(wind), 73)
max_dist = (wind.position - star.position).lengths().max()
self.assertLessEqual(max_dist, r_max + star.radius)
self.assertAllAlmostEqual(wind.u, expected_u)
def setup_supernova(self):
numpy.random.seed(123456789)
stars = Particles(2)
stars.mass = [9, 10] | units.MSun
stars[0].position = [1, 1, 1] | units.parsec
stars[1].position = [-1, -1, -1] | units.parsec
stars[0].velocity = [-1000, 0, 1000] | units.ms
stars[1].velocity = [0, 0, 0] | units.ms
stev = SeBa()
stars = stev.particles.add_particles(stars)
r_max = .1 | units.parsec
star_wind = stellar_wind.new_stellar_wind(
3e-5 | units.MSun,
mode="heating",
r_max=r_max,
derive_from_evolution=True,
tag_gas_source=True
)
star_wind.particles.add_particles(stars)
return stev, star_wind, stars
def test_supernova(self):
stev, star_wind, stars = self.setup_supernova()
chan = stev.particles.new_channel_to(
star_wind.particles,
attributes=["age", "radius", "mass", "luminosity", "temperature", "stellar_type"])
dt = 5 | units.Myr
t = 0 | units.Myr
t_end = 31 | units.Myr
wind_N = []
while t < t_end:
stev.evolve_model(t)
chan.copy()
star_wind.evolve_model(t)
if star_wind.has_new_wind_particles():
wind = star_wind.create_wind_particles()
wind_1 = wind[wind.source == stars[0].key]
wind_2 = wind - wind_1
wind_N.append([len(wind_1), len(wind_2)])
if len(wind_2) > 0:
print("time", t, "wind energy", (wind_2.u * wind_2.mass).sum())
else:
wind_N.append([0, 0])
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()
chan = stev.particles.new_channel_to(
star_wind.particles,
attributes=["age", "radius", "mass", "luminosity", "temperature"])
dt = 5 | units.Myr
t = 0 | units.Myr
t_end = 31 | units.Myr
wind_N = []
wind_E = [] | units.erg
while stev.model_time < t_end:
stev.evolve_model(t)
chan.copy()
if stev.stopping_conditions.supernova_detection.is_set():
key = stev.stopping_conditions.supernova_detection.particles(0)[0].key
star = star_wind.particles._get_particle(key)
star.mass_loss_type = "supernova"
print("supernova detected at time", t, stev.model_time)
star_wind.evolve_model(t)
if star_wind.has_new_wind_particles():
wind = star_wind.create_wind_particles()
wind_2 = wind[wind.source == stars[1].key]
wind_N.append(len(wind_2))
wind_E.append((wind_2.u * wind_2.mass).sum())
print(len(wind), len(wind_2))
if not stev.stopping_conditions.supernova_detection.is_set():
t += dt
print(wind_N)
print(wind_E)
self.assertEqual(wind_N[-2:], [606194, 0])
self.assertAlmostRelativeEqual(wind_E[-2:], [1.e49, 0] | units.erg, 7)
| 32,915
| 35.211221
| 116
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_jobserver.py
|
from amuse.test import amusetest
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
class TestRemoteCode(amusetest.TestCase):
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)
def test2(self):
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)
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)
class TestJobServer(amusetest.TestCase):
def test1(self):
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))
def test3(self):
result = example_parallel_jobs2(10, 4)
for arg, res in result.items():
self.assertEqual(arg, len(res))
| 2,878
| 24.034783
| 78
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_star_to_sph.py
|
import os.path
import numpy
from amuse.test.amusetest import get_path_to_results, TestWithMPI
try:
from matplotlib import pyplot
HAS_MATPLOTLIB = True
from amuse.plot import plot, semilogy, xlabel, ylabel, loglog
except ImportError:
HAS_MATPLOTLIB = False
from amuse.support.exceptions import AmuseException, AmuseWarning
from amuse.community.mesa.interface import MESA
from amuse.community.evtwin.interface import EVtwin
from amuse.community.gadget2.interface import Gadget2
from amuse.community.fi.interface import Fi
from amuse.ext.star_to_sph import *
from amuse.ext.sph_to_star import convert_SPH_to_stellar_model
from amuse.units import units
from amuse.units import generic_unit_system
from amuse.units import nbody_system
from amuse.units import constants
from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits
from amuse.datamodel import Particles
from amuse.datamodel import Particle
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):
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):
return (['h1', 'he3', 'he4', 'c12'])[:int(self.particles_set._private.number_of_species)]
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):
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):
return [2.0, 2.0, 2.0, 1.0] | units.MSun/units.RSun**3
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):
return [1e7, 1e6, 1e5, 1e4] | units.K
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):
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 test1(self):
star = self.StarParticleWithStructure()
number_of_zones = star.get_number_of_zones()
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)),
[1]*number_of_zones)
def test2(self):
star = self.StarParticleWithStructure()
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)
def test3(self):
print("Test interpolate_hydro_quantities")
star = self.StarParticleWithStructure()
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()
inner_radii = [0.0] | units.RSun
inner_radii.extend(outer_radii[:-1])
self.assertEqual(outer_radii, [0.125, 0.25, 0.5, 1.0] | units.RSun)
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)
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
sph_particles = convert_stellar_model_to_SPH(
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.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))
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.mass = 1.0 | units.MSun
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
sph_particles = convert_stellar_model_to_SPH(
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.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)
hydrodynamics.initialize_code()
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.mass = 1.0 | units.MSun
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
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,
seed=12345
).gas_particles
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)
stellar_evolution.stop()
sph_midpoints = sph_particles.position.lengths()
composition_comparison_plot(
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,
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)
hydrodynamics.initialize_code()
hydrodynamics.gas_particles.add_particles(sph_particles)
hydrodynamics.evolve_model(time_end)
sph_midpoints = hydrodynamics.gas_particles.position.lengths()
hydrodynamics.stop()
composition_comparison_plot(
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,
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,
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.mass = 1.0 | units.MSun
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)
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,
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
potential_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)
sph_midpoints = hydro_code.gas_particles.position.lengths()
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,
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,
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,
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,
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.mass = 1.0 | units.MSun
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,
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
potential_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)
hydro_code.stop()
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.mass = 1.0 | units.MSun
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)
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
).gas_particles
stellar_evolution.stop()
sph_midpoints = sph_particles.position.lengths()
composition_comparison_plot(
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,
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.mass = 1.0 | units.MSun
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)
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
).gas_particles
stellar_evolution.stop()
sph_midpoints = sph_particles.position.lengths()
composition_comparison_plot(
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,
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
potential_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)
sph_midpoints = hydro_code.gas_particles.position.lengths()
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,
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,
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,
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,
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
some_sph_particles = convert_stellar_model_to_SPH(
star,
number_of_sph_particles,
seed=12345
).gas_particles
another_star = self.StarParticleWithStructure(number_of_species=4)
more_sph_particles = convert_stellar_model_to_SPH(
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.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))
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.mass = [1.0, 1.0] | units.MSun
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)
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,
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,
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_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
potential_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,
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,
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'])
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)
print("center_of_mass_velocity:", center_of_mass_velocity)
self.assertIsOfOrder(center_of_mass[0], 0.5 * (initial_separation + t_end * initial_speed))
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,
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,
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.mass = 10.0 | units.MSun
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()
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()
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()
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)))
xlabel('radius')
ylabel('density')
pyplot.legend(loc=3)
figname = os.path.join(get_path_to_results(), "star2sph_test_13_density.png")
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,
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
potential_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)
sph_midpoints = hydro_code.gas_particles.position.lengths()
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,
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,
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,
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,
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
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)
star = stellar_evolution.particles.add_particle(Particle(mass=5.0 | units.MSun))
while star.radius < (200 | units.RSun):
star.evolve_for(10 * star.time_step)
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
)
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("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
else:
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
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,
os.path.join(get_path_to_results(), "star2sph_test_14_internal_energy.png"),
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"
)
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"
)
times = [] | units.s
kinetic_energies = [] | units.J
potential_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)
sph_midpoints = hydro_code.gas_particles.position.lengths()
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,
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"
)
hydro_code.stop()
print("All done!\n")
def test15(self):
print("Test pickling of stellar structure")
star = self.StarParticleWithStructure()
test_pickle_file = os.path.join(get_path_to_results(), "test_star_structure.pkl")
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.unpickle_stellar_structure()
self.assertEqual(converter.mass, numpy.pi * 1.5 | units.MSun)
self.assertEqual(converter.radius, 1.0 | units.RSun)
self.assertEqual(converter.number_of_zones, 4)
self.assertEqual(converter.number_of_species, 3)
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.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],
[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))
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))
def test16(self):
print("Test convert_stellar_model_to_SPH with pickled stellar structure")
star = self.StarParticleWithStructure()
test_pickle_file = os.path.join(get_path_to_results(), "test_star_structure.pkl")
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
sph_particles = convert_stellar_model_to_SPH(
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.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))
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...
number_of_sph_particles = 3000
t_end = 3.0e6 | units.s
# 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("+", "")
base_plotfile_string = "star2sph_test_17" + n_string + hydro_code_string + t_end_string
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.mass = 10.0 | units.MSun
stellar_evolution.initialize_code()
stellar_evolution.particles.add_particles(stars)
stellar_evolution.commit_particles()
star_age = [] | units.yr
star_radius = [] | units.RSun
try:
while True:
stellar_evolution.evolve_model()
star_age.append(stellar_evolution.particles[0].age)
star_radius.append(stellar_evolution.particles[0].radius)
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,
os.path.join(get_path_to_results(), base_plotfile_string + "_radius_evolution.png"))
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)
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
)
if len(stellar_model_in_SPH.core_particle):
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")
try:
hydro_code.parameters.timestep = t_end / n_steps
except Exception as exc:
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
potential_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)
sph_midpoints = hydro_code.gas_particles.position.lengths()
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,
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,
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")
if stellar_evolution is None:
print("MESA was not built. Skipping test.")
return
stars = Particles(1)
stars.mass = 50.0 | units.MSun
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
)
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
sph_particles = convert_stellar_model_to_SPH(
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,
).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.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."
)
stellar_evolution = EVtwin()
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
)
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",
"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
sph_particles = convert_stellar_model_to_SPH(
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)
unit_converter = ConvertBetweenGenericAndSiUnits(1.0 | units.RSun, 1.0 | units.MSun, 1.0 | units.s)
hydrodynamics = Gadget2(unit_converter)
in_hydro = hydrodynamics.gas_particles.add_particles(sph_particles)
sph_particles.pressure = in_hydro.pressure
sph_particles.density = in_hydro.density
model = convert_SPH_to_stellar_model(
sph_particles, particles_per_zone=100
# particles_per_zone=number_of_sph_particles/4
)
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))
print(model.rho[0:10].as_quantity_in(units.MSun/units.RSun**3))
print(model.rho[-10:].as_quantity_in(units.MSun/units.RSun**3))
print(model.radius[0:10].as_quantity_in(units.RSun))
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,
label='stellar evolution model')
plot(radii_SPH, comp_SPH, 'go', label='SPH model')
xlabel('radius')
ylabel('mass fraction')
pyplot.legend()
pyplot.savefig(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,
label='stellar evolution model')
semilogy(radii_SPH, u_SPH, 'go', label='SPH model')
xlabel('radius')
ylabel(y_label)
pyplot.legend(loc="lower center")
pyplot.savefig(figname)
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))
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')
plot(time, E_kin+E_pot+E_therm, label='E_total')
xlabel('Time')
ylabel('Energy')
pyplot.legend(loc=3)
pyplot.savefig(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))
plot(time, E_therm.as_quantity_in(units.erg), label='E_therm')
xlabel('Time')
ylabel('Energy')
pyplot.legend(loc=3)
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))
plot(star_age, star_radius)
xlabel('Time')
ylabel('Radius')
pyplot.savefig(figname)
print("\nPlot of radius evolution was saved to: ", figname)
pyplot.close()
| 56,008
| 46.344886
| 201
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_boss_bodenheimer.py
|
import sys
import os
import numpy.random
from amuse.test import amusetest
from amuse.units import units, nbody_system
from amuse.ext.boss_bodenheimer import bb79_cloud
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()
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()
self.assertAlmostEqual(eth/ep, -0.25, 2)
self.assertAlmostEqual(ek/ep, -0.2, 2)
| 1,038
| 30.484848
| 78
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_isotropic_cloud.py
|
from amuse.test import amusetest
from amuse.units import units, nbody_system, constants
from amuse.ic.isotropic_cloud import new_isotropic_cloud
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)
| 1,582
| 41.783784
| 112
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_mameclot.py
|
import numpy
from amuse.test import amusetest
from amuse.units import nbody_system
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)
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)
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)
| 840
| 28
| 77
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_plummer.py
|
import numpy
from amuse.test import amusetest
from amuse.units import nbody_system
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()
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)
def test2(self):
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)
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)
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.mass.sum(), 1.00 | nbody_system.mass)
self.assertAlmostEqual(stars.virial_radius(), 1.00 | nbody_system.length)
| 1,875
| 40.688889
| 101
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_static_potentials.py
|
import numpy
from amuse.test import amusetest
from amuse.units import units, quantities
from amuse.ext import static_potentials
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])
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)
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_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)
# 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)
# quick plot for testing
# from matplotlib import pyplot
# from amuse import plot as aplot
# aplot.loglog(r, m, marker="*")
# aplot.scatter(static_potential.radius, static_potential.enclosed_mass_profile)
# pyplot.show()
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],
] | 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)
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],
] | 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)
class TestGalacticPotential(amusetest.TestCase):
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],
] | 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)
| 3,751
| 39.344086
| 139
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_spherical_model.py
|
import numpy
from amuse.test.amusetest import TestCase
from amuse.support.exceptions import AmuseWarning, AmuseException
from amuse.ext.spherical_model import *
from amuse.units import units
class TestUniformSphericalDistribution(TestCase):
def test1(self):
instance = UniformSphericalDistribution(4200)
x, y, z = instance.result
self.assertEqual(len(x), 4200)
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]:
for type_i in ["cubic", "bcc", "body_centered_cubic", "random"]:
for offset_i in [(0.406645, 0.879611, 0.573737), (0.939868, 0.796048, 0.236403)]:
instance = UniformSphericalDistribution(n_i, type=type_i, offset=offset_i)
x, y, z = instance.result
self.assertEqual(len(x), n_i)
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
grid_spacing_x = min(x[numpy.where(x > min(x))]) - min(x)
grid_spacing_y = min(y[numpy.where(y > min(y))]) - min(y)
grid_spacing_z = min(z[numpy.where(z > min(z))]) - min(z)
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])
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
grid_spacing_x = min(x[numpy.where(x > min(x))]) - min(x)
grid_spacing_y = min(y[numpy.where(y > min(y))]) - min(y)
grid_spacing_z = min(z[numpy.where(z > min(z))]) - min(z)
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 = min(
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")
self.assertEqual(len(particles), 14321)
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, 2)
self.assertAlmostEqual(particles.total_mass(), 1 | units.kg)
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)
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.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.")
def test9(self):
print("Test new_spherical_particle_distribution without total_mass")
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)
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)
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.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.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,
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")
self.assertEqual(len(particles), 14321)
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, 2)
self.assertAlmostEqual(particles.total_mass(), 1 | units.kg)
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")
self.assertEqual(len(particles), 14321)
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, 2)
self.assertAlmostEqual(particles.total_mass(), 1 | units.kg)
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])
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")
self.assertEqual(len(particles), 1401)
r_halfmass_plummer = 3*numpy.pi/16.0*(0.5**(-2/3.)-1)**-0.5 | nbody_system.length
self.assertAlmostEqual(particles[700].position.length(), r_halfmass_plummer, places=1)
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,
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)
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)
def test16(self):
print("Test new_plummer_spatial_distribution, mass_cutoff")
numpy.random.seed(12345)
particles = new_plummer_spatial_distribution(1001, mass_cutoff=0.5, type="random")
r_squared = particles.position.lengths_squared()
r_halfmass_plummer = 3*numpy.pi/16.0*(0.5**(-2/3.)-1)**-0.5 | nbody_system.length
# With mass_cutoff=0.5, the outermost particle should be close to the (uncut) half-mass radius:
self.assertAlmostEqual(r_squared.amax().sqrt(), r_halfmass_plummer, places=2)
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")
self.assertEqual(len(particles), 1401)
r_halfmass_plummer = 3*numpy.pi/16.0*(0.5**(-2/3.)-1)**-0.5 | nbody_system.length
self.assertAlmostEqual(particles[700].position.length(), r_halfmass_plummer, places=1)
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)
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,
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)
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.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)
particles = new_plummer_distribution(1401, type="fcc")
self.assertEqual(len(particles), 1401)
r_halfmass_plummer = 3*numpy.pi/16.0*(0.5**(-2/3.)-1)**-0.5 | nbody_system.length
self.assertAlmostEqual(particles[700].position.length(), r_halfmass_plummer, places=1)
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)
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,
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)
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.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__)
self.assertTrue("face_centered_cubic" in new_spherical_particle_distribution.__doc__)
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))
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.enclosed_mass[0], 0.0 | units.kg)
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),
numpy.pi * 4.0/3.0 * instance.densities[0] * (1.0 | units.m)**3)
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),
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,
interpolator.get_enclosed_mass(0.3 | units.m))
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,
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,
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].")
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,
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,
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,
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].")
del interpolator
| 19,501
| 60.911111
| 227
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_hydro_collision.py
|
import numpy
from amuse.units import units, nbody_system
from amuse.units.quantities import zero
from amuse.datamodel import Particles, Particle
from amuse.support.exceptions import AmuseException
from amuse.test.amusetest import TestWithMPI
from amuse.plot import pynbody_column_density_plot, HAS_PYNBODY
from amuse.community.bhtree.interface import BHTree
from amuse.community.gadget2.interface import Gadget2
from amuse.community.seba.interface import SeBa
from amuse.community.evtwin.interface import EVtwin
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
colliders.position = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]] | units.RSun
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.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 -
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)
collision.dynamical_timescale = zero
collision.start_kepler(7 | units.MSun, 10 | units.RSun)
# at periastron, close enough:
colliders = self.new_colliders()
colliders.radius = 1 | units.RSun
self.assertTrue(collision.binary_will_collide(colliders[0], colliders[1]))
# at periastron, distance too large:
colliders.radius = 0.4 | units.RSun
self.assertFalse(collision.binary_will_collide(colliders[0], colliders[1]))
# at apastron, will collide at periastron:
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]))
# hyperbolic orbits, moving away from each other:
colliders.position = [[0.0, 0.0, 0.0], [1.0, 100.0, 0.0]] | units.RSun
self.assertFalse(collision.binary_will_collide(colliders[0], colliders[1]))
# hyperbolic orbits, moving towards each other:
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()
colliders.position = [[0.0, 0.0, 0.0], [1.1, 0.0, 0.0]] | units.RSun
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,
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)
self.assertTrue(1800 < len(groups[1]) < 2000)
self.assertEqual(len(gas_particles - groups[0] - groups[1]), 346)
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 += 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
result = collision.handle_collision(colliders[0], colliders[1], gravity_code=gravity, stellar_evolution_code=stellar)
stellar.stop()
print(result)
self.assertTrue(isinstance(result, Particles))
self.assertEqual(len(result), 2)
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
velocity_offset = [10000.0, 20000.0, 30000.0] | units.km / units.s
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),
verbose=True,
debug=False
)
result = collision.handle_collision(colliders[0], colliders[1], gravity_code=gravity, stellar_evolution_code=stellar)
stellar.stop()
print(result)
self.assertTrue(isinstance(result, Particles))
self.assertEqual(len(result), 2)
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)
| 10,524
| 46.197309
| 135
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_parallel_stellar_evolution.py
|
import os
import os.path
import numpy
from amuse.units import units
from amuse.datamodel import Particles
from amuse.support.exceptions import AmuseException
from amuse.test.amusetest import TestCase, get_path_to_results
from amuse.community.mesa.interface import MESA
from amuse.community.evtwin.interface import EVtwin
from amuse.community.sse.interface import SSE
from amuse.couple.parallel_stellar_evolution import ParallelStellarEvolution
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)
instance.commit_particles()
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)
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)
parallel.evolve_model(0.2 | units.Myr)
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)
parallel.parameters.metallicity = 0.01
self.assertEqual(parallel.parameters.metallicity, 0.01)
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,
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
if self.code_factory == MESA:
expected_message = ("Error when calling 'evolve_for' of a 'MESA', errorcode is -12, error is 'Evolve terminated: Maximum age reached.'")
elif self.code_factory == EVtwin:
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)
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()
| 5,345
| 44.305085
| 148
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_orbital_elements.py
|
import numpy
from amuse.test import amusetest
from amuse.ext.orbital_elements import (
generate_binaries,
get_orbital_elements_from_binaries,
new_binary_from_orbital_elements,
# get_orbital_elements_from_binary,
orbital_elements_for_rel_posvel_arrays,
orbital_elements,
rel_posvel_arrays_from_orbital_elements,
)
from amuse.units import units
from amuse.units import constants
from amuse.units import nbody_system
from amuse import datamodel
from numpy import random
class KeplerTests(amusetest.TestCase):
def test1(self):
mass1 = 1 | nbody_system.mass
mass2 = 1 | nbody_system.mass
binary = new_binary_from_orbital_elements(
mass1,
mass2,
1 | nbody_system.length
)
self.assertEqual(len(binary), 2)
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,
[1, 0, 0] | nbody_system.length)
self.assertAlmostRelativeEquals(
binary[0].velocity,
[0, 0, 0] | nbody_system.speed)
self.assertAlmostRelativeEquals(
binary[1].velocity,
[0, numpy.sqrt(2), 0] | nbody_system.speed)
def test2(self):
# test going around in a circular orbit
mass1 = 1 | nbody_system.mass
mass2 = 1 | nbody_system.mass
binary = new_binary_from_orbital_elements(
mass1,
mass2,
1 | nbody_system.length,
eccentricity=0,
true_anomaly=90,
)
self.assertEqual(len(binary), 2)
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)
binary = new_binary_from_orbital_elements(
mass1,
mass2,
1 | nbody_system.length,
eccentricity=0,
true_anomaly=180,
)
self.assertEqual(len(binary), 2)
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, [-1, 0, 0] | nbody_system.length)
self.assertAlmostRelativeEquals(
binary[0].velocity, [0, 0, 0] | nbody_system.speed)
self.assertAlmostRelativeEquals(
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,
)
self.assertEqual(len(binary), 2)
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)
binary = new_binary_from_orbital_elements(
mass1,
mass2,
1 | nbody_system.length,
eccentricity=0,
true_anomaly=45,
)
self.assertEqual(len(binary), 2)
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
mass2 = 1. | nbody_system.mass
binary = new_binary_from_orbital_elements(
mass1,
mass2,
1. | nbody_system.length,
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)
def test4(self):
numpy.random.seed(3456789)
N = 100
mass1 = random.random(N) | nbody_system.mass
mass2 = random.random(N) | nbody_system.mass
semi_major_axis = (-numpy.log(random.random(N))) | nbody_system.length
eccentricity = random.random(N)
true_anomaly = (360.*random.random(N)-180.) | units.deg
inclination = (180*random.random(N)) | units.deg
longitude_of_the_ascending_node = (
360*random.random(N)-180) | units.deg
argument_of_periapsis = (360*random.random(N)-180) | units.deg
for arg in zip(
mass1, mass2, semi_major_axis, eccentricity, true_anomaly,
inclination, longitude_of_the_ascending_node,
argument_of_periapsis):
arg_ = orbital_elements(
new_binary_from_orbital_elements(*arg))
for i, (copy, org) in enumerate(zip(arg_, arg)):
self.assertAlmostEqual(copy, org)
def test5(self):
numpy.random.seed(4567893)
N = 100
mass1 = random.random(N) | units.MSun
mass2 = random.random(N) | units.MSun
semi_major_axis = (-numpy.log(random.random(N))) | units.AU
eccentricity = random.random(N)
true_anomaly = (360.*random.random(N)-180.) | units.deg
inclination = (180*random.random(N)) | units.deg
longitude_of_the_ascending_node = (
360*random.random(N)-180
) | units.deg
argument_of_periapsis = (360*random.random(N)-180) | units.deg
for arg in zip(
mass1, mass2, semi_major_axis, eccentricity, true_anomaly,
inclination, longitude_of_the_ascending_node,
argument_of_periapsis):
arg_ = orbital_elements(
new_binary_from_orbital_elements(*arg, G=constants.G),
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
with random orbital elements
"""
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
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
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)
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)
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
ecc = 0.05
inc = 20.
lon = 10.
arg = 0.4
ta = 360.*random.random()-180.
binary = new_binary_from_orbital_elements(mass1,
mass2,
sem,
ecc,
ta,
inc,
lon,
arg,
G=constants.G)
rel_pos = binary[1].position - binary[0].position
rel_vel = binary[1].velocity - binary[0].velocity
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)
def test8(self):
"""
testing orbital_elements_for_rel_posvel_arrays for extreme cases
"""
N = 3
mass1 = (1.2*numpy.ones(N)) | units.MSun
mass2 = (0.1, 0.05, 0.003) | units.MSun
semi_major_axis = (1., 2., 3.) | units.AU
eccentricity = (0., 0.5, 0.6)
true_anomaly = (0., 0., 66.)
inclination = (12., 0., 180.)
longitude_of_the_ascending_node = (0., 0., 0.,)
argument_of_periapsis = (0., 23., 90.)
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)
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)
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):
"""
testing orbital_elements_for_rel_posvel_arrays for N particles
with random orbital elements, nbody_system
"""
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
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
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)
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)
def xtest10(self):
"""
testing orbital_elements_for_rel_posvel_arrays for N particles
with random orbital elements, unitless
"""
numpy.random.seed(666)
N = 100
mass_sun = 1.
mass1 = numpy.ones(N) * mass_sun
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
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)
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=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)
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
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
# 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)
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)):
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)
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]
r[1] = r_vec[1]
r[2] = r_vec[2]
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)
def test12(self):
"""
tests generating cartesian coordinates from orbital elements
"""
numpy.random.seed(1701)
mass1 = 1.0 | units.MSun
mass2 = 0.1 | units.MEarth
sem = 2. | units.AU
ecc = 0.15
inc = 11. | units.deg
lon = 30. | units.deg
arg = 0.3 | units.deg
ta = (360.*random.random()-180.) | units.deg
rel_pos, rel_vel = rel_posvel_arrays_from_orbital_elements(
mass1,
mass2,
sem,
ecc,
ta,
inc,
lon,
arg,
G=constants.G)
mass_12 = mass1 + mass2
sem_ext, ecc_ext, ta_ext, inc_ext, lon_ext, arg_ext = \
orbital_elements(
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)
def test13(self):
"""
tests generating cartesian coordinates from orbital elements
"""
numpy.random.seed(17014)
N = 5
mass1 = 1.0 | units.MSun
mass2 = numpy.ones(N) * 0.01 | units.MEarth
sem = 2. | units.AU
ecc = 0.15
inc = 11. | units.deg
lon = 30. | units.deg
arg = 0.3 | units.deg
ta = (360.*random.random()-180.) | units.deg
rel_pos, rel_vel = rel_posvel_arrays_from_orbital_elements(
mass1,
mass2,
sem,
ecc,
ta,
inc,
lon,
arg,
G=constants.G)
mass_12 = mass1 + mass2
sem_ext, ecc_ext, ta_ext, inc_ext, lon_ext, arg_ext = \
orbital_elements(
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)
def test14(self):
"""
tests generating cartesian coordinates from orbital elements
"""
numpy.random.seed(17018)
N = 5
mass1 = numpy.ones(N) * 1.0 | units.MSun
mass2 = random.random(N) | units.MEarth
sem = numpy.array([2., 1.0, 1.1, 1.2, 4.0]) | units.AU
ecc = numpy.array([0.15, 0.01, 0.5, 0.9, 0.99])
inc = numpy.array([11., 0.1, 20, 90, 180.]) | units.deg
lon = numpy.array([31., 32., 33., 45., 30.]) | units.deg
arg = numpy.array([0.3, 11., 15., 30., 95.]) | units.deg
ta = (360.*random.random(N)-180.) | units.deg
rel_pos, rel_vel = rel_posvel_arrays_from_orbital_elements(
mass1,
mass2,
sem,
ecc,
ta,
inc,
lon,
arg,
G=constants.G)
mass_12 = mass1 + mass2
sem_ext, ecc_ext, ta_ext, inc_ext, lon_ext, arg_ext = \
orbital_elements(
rel_pos, rel_vel, mass_12, G=constants.G)
self.assertAlmostEqual(
sem.value_in(units.AU), sem_ext.value_in(units.AU))
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)
def test15(self):
"""
testing orbital_elements_for_rel_posvel_arrays for N particles
with random orbital elements
"""
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
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
comets = datamodel.Particles(N)
suns = 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)
comets[i].mass = sun_and_comet[1].mass
comets[i].position = sun_and_comet[1].position
comets[i].velocity = sun_and_comet[1].velocity
suns.mass = mass1
suns.position = 0*comets.position
suns.velocity = 0*comets.velocity
mass1_ext, mass2_ext, semi_major_axis_ext, eccentricity_ext, ta_ext,\
inclination_ext, longitude_of_the_ascending_node_ext,\
argument_of_periapsis_ext = orbital_elements(
suns, comets, G=constants.G)
rad_to_deg = 180./numpy.pi
for i in range(N):
self.assertAlmostEqual(
semi_major_axis[i].value_in(units.AU),
semi_major_axis_ext[i].value_in(units.AU))
self.assertAlmostEqual(eccentricity[i], eccentricity_ext[i])
self.assertAlmostEqual(
inclination[i], rad_to_deg*inclination_ext[i])
self.assertAlmostEqual(
longitude_of_the_ascending_node[i],
rad_to_deg*longitude_of_the_ascending_node_ext[i])
self.assertAlmostEqual(
argument_of_periapsis[i],
rad_to_deg*argument_of_periapsis_ext[i])
self.assertAlmostEqual(true_anomaly[i], rad_to_deg*ta_ext[i])
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_)
| 27,092
| 39.925982
| 128
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_galactics_model.py
|
import os.path
from amuse.test.amusetest import TestWithMPI, get_path_to_results
from amuse.support.exceptions import AmuseException
from amuse.ext.galactics_model import new_galactics_model, new_galactics_gas_model
from amuse.units import nbody_system, generic_unit_converter, constants, units
from amuse.io import write_set_to_file
# 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)
self.assertEqual(len(particles), halo_number_of_particles)
self.assertAlmostEqual(particles.total_mass(), 1.0 | nbody_system.mass)
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,
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,
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)
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)
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)
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)
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)
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.assertAlmostEquals(particles.kinetic_energy(),
# ~ 0.25 | nbody_system.energy)
| 7,813
| 52.156463
| 133
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_composition_methods.py
|
from amuse.test import amusetest
import numpy
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_time < tend-dt/2:
h.evolve_step(dt)
data['x'].append(h.x)
data['time'].append(h.model_time)
E = h.total_energy()
data['de'].append(abs(E0-E)/E0)
return data
class TestSymplecticCompositions(amusetest.TestCase):
def test1(self):
from amuse.ext.composition_methods import LEAPFROG
dt1 = .1
data = run_harmonic_oscillator(dt1, method=LEAPFROG)
de1 = max(data['de'])
dt2 = 0.01
data = run_harmonic_oscillator(dt2, method=LEAPFROG)
de2 = max(data['de'])
order = int(numpy.log(de2/de1)/numpy.log(dt2/dt1)+0.5)
self.assertEqual(order, 2)
def test2(self):
from amuse.ext.composition_methods import SPLIT_4TH_S_M6
dt1 = .5
data = run_harmonic_oscillator(dt1, method=SPLIT_4TH_S_M6)
de1 = max(data['de'])
dt2 = 0.05
data = run_harmonic_oscillator(dt2, method=SPLIT_4TH_S_M6)
de2 = max(data['de'])
order = int(numpy.log(de2/de1)/numpy.log(dt2/dt1)+0.5)
self.assertEqual(order, 4)
def test3(self):
from amuse.ext.composition_methods import SPLIT_4TH_S_M5
dt1 = .5
data = run_harmonic_oscillator(dt1, method=SPLIT_4TH_S_M5)
de1 = max(data['de'])
dt2 = 0.05
data = run_harmonic_oscillator(dt2, method=SPLIT_4TH_S_M5)
de2 = max(data['de'])
order = int(numpy.log(de2/de1)/numpy.log(dt2/dt1)+0.5)
self.assertEqual(order, 4)
def test4(self):
from amuse.ext.composition_methods import SPLIT_4TH_S_M4
dt1 = .5
data = run_harmonic_oscillator(dt1, method=SPLIT_4TH_S_M4)
de1 = max(data['de'])
dt2 = 0.05
data = run_harmonic_oscillator(dt2, method=SPLIT_4TH_S_M4)
de2 = max(data['de'])
order = int(numpy.log(de2/de1)/numpy.log(dt2/dt1)+0.5)
self.assertEqual(order, 4)
def test5(self):
from amuse.ext.composition_methods import SPLIT_6TH_SS_M11
dt1 = .5
data = run_harmonic_oscillator(dt1, method=SPLIT_6TH_SS_M11)
de1 = max(data['de'])
dt2 = 0.05
data = run_harmonic_oscillator(dt2, method=SPLIT_6TH_SS_M11)
de2 = max(data['de'])
order = int(numpy.log(de2/de1)/numpy.log(dt2/dt1)+0.5)
self.assertEqual(order, 6)
def test6(self):
from amuse.ext.composition_methods import SPLIT_6TH_SS_M13
dt1 = .5
data = run_harmonic_oscillator(dt1, method=SPLIT_6TH_SS_M13)
de1 = max(data['de'])
dt2 = 0.05
data = run_harmonic_oscillator(dt2, method=SPLIT_6TH_SS_M13)
de2 = max(data['de'])
order = int(numpy.log(de2/de1)/numpy.log(dt2/dt1)+0.5)
self.assertEqual(order, 6)
def test7(self):
from amuse.ext.composition_methods import SPLIT_8TH_SS_M21
dt1 = 1.
data = run_harmonic_oscillator(dt1, method=SPLIT_8TH_SS_M21)
de1 = max(data['de'])
dt2 = 0.25
data = run_harmonic_oscillator(dt2, method=SPLIT_8TH_SS_M21)
de2 = max(data['de'])
order = int(numpy.log(de2/de1)/numpy.log(dt2/dt1)+0.5)
self.assertEqual(order, 8)
def test8(self):
from amuse.ext.composition_methods import SPLIT_10TH_SS_M35
dt1 = 1.
data = run_harmonic_oscillator(dt1, method=SPLIT_10TH_SS_M35)
de1 = max(data['de'])
dt2 = 0.5
data = run_harmonic_oscillator(dt2, method=SPLIT_10TH_SS_M35)
de2 = max(data['de'])
order = int(numpy.log(de2/de1)/numpy.log(dt2/dt1)+0.5)
self.assertEqual(order, 10)
| 4,336
| 31.609023
| 69
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_roche_radius.py
|
import numpy
from amuse.test import amusetest
from amuse.units import units
from amuse.ext.roche_radius import Roche_Orbit, sepinsky_formula
class TestRocheRadius(amusetest.TestCase):
def test1(self):
""" Test that the basic numbers from Sepinsky are not unreasonable. """
self.assertAlmostEqual(sepinsky_formula(), 1.0, places=1)
q_values = 10.0**numpy.arange(-8, 9)
answers = [1.0] * len(q_values)
self.assertAlmostEqual(sepinsky_formula(q=q_values), answers, places=1)
a_values = 10.0**numpy.arange(-4, 2)
answers = [1.0]*len(a_values)
self.assertIsOfOrder(sepinsky_formula(q=1.0, A=a_values), answers)
self.assertIsOfOrder(sepinsky_formula(q=1e-4, A=a_values), answers)
self.assertIsOfOrder(sepinsky_formula(q=1e4, A=a_values), answers)
def test2(self):
""" Test the Roche_Orbit class """
roche_orbit = Roche_Orbit()
roche_orbit.semimajor_axis = 1 | units.AU
print(roche_orbit.eggleton_roche_radius().as_quantity_in(units.RSun))
self.assertAlmostEqual(roche_orbit.eggleton_roche_radius(), 81.5 | units.RSun, places=2)
self.assertAlmostEqual(roche_orbit.sepinsky_roche_radius(), 81.32 | units.RSun, places=2)
roche_orbit.eccentricity = 0.5
self.assertAlmostEqual(roche_orbit.eggleton_roche_radius(), 40.75 | units.RSun, places=2)
self.assertAlmostEqual(roche_orbit.sepinsky_roche_radius(), 39.62 | units.RSun, places=2)
roche_orbit.semimajor_axis = 20.0 | units.AU
roche_orbit.mass_2 = 10000.0 | units.MSun
roche_orbit.eccentricity = 0.95
roche_orbit.angular_velocity_ratio = 0.1
self.assertAlmostEqual(roche_orbit.eggleton_roche_radius(), 4.87 | units.RSun, places=2)
self.assertAlmostEqual(roche_orbit.sepinsky_roche_radius(), 5.39 | units.RSun, places=2)
roche_orbit.eccentricity = numpy.array([0.0, 0.5, 0.95])
self.assertAlmostEqual(roche_orbit.sepinsky_roche_radius(), [107.92, 53.93, 5.39] | units.RSun, places=2)
| 2,065
| 38.730769
| 113
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_sph_to_grid.py
|
import numpy
from amuse.test.amusetest import TestWithMPI
from amuse.support.exceptions import AmuseException
from amuse.ext.sph_to_grid import convert_SPH_to_grid
from amuse.units import units, generic_unit_system, constants
from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits
from amuse.datamodel import Particles
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.parameters.periodic_box_size = 10.0 | units.parsec
gas = Particles(number_of_particles)
gas.mass = (rho * L**3) / number_of_particles
numpy.random.seed(12345)
gas.x = L * numpy.random.uniform(0.0, 1.0, number_of_particles)
gas.y = L * numpy.random.uniform(0.0, 1.0, number_of_particles)
gas.z = L * numpy.random.uniform(0.0, 1.0, number_of_particles)
gas.vx = numpy.zeros(number_of_particles) | units.cm / units.s
gas.vy = numpy.zeros(number_of_particles) | units.cm / units.s
gas.vz = numpy.zeros(number_of_particles) | units.cm / units.s
gas.u = u
if isinstance(sph_code, Fi):
sph_code.parameters.self_gravity_flag = False
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)
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))
sph_code.stop()
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.assertEqual(
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))
sph_code.stop()
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.assertEqual(
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)
sph_code.stop()
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.assertEqual(
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)
sph_code.stop()
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.assertEqual(
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"):
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 "
"box runs from 0 to L or from -0.5 L to 0.5 L.")
| 7,450
| 46.158228
| 109
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_fallback_stellar_evolution.py
|
import os
import os.path
import numpy
from amuse.units import units
from amuse.datamodel import Particles, Particle
from amuse.support.exceptions import AmuseException
from amuse.test.amusetest import TestCase, get_path_to_results
from amuse.community.mesa.interface import MESA
from amuse.community.evtwin.interface import EVtwin
from amuse.community.sse.interface import SSE
from amuse.couple.fallback_stellar_evolution import FallbackStellarEvolution
class TestFallbackStellarEvolution(TestCase):
def test1(self):
print("Testing FallbackStellarEvolution")
instance = FallbackStellarEvolution()
instance.stop()
def xtest2(self):
print("Testing FallbackStellarEvolution: evolve tests")
# 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,
sse_mass=9.99289747724 | units.MSun,
sse_rad=4.24764389443 | units.RSun,
sse_L=5993.72678228 | 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.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_mass=37.0862227121 | units.MSun,
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
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()
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)
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)
print("%s\t%s\t%s\t%s\t%s" % (star.age, star.mass, star.radius,
star.luminosity, star.stellar_type))
instance.stop()
def slowtest3(self):
print("Testing FallbackStellarEvolution: evolve 3 stars at the same time")
# 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,
sse_mass=9.99289747724 | units.MSun,
sse_rad=4.35949272485 | units.RSun,
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,
evtwin_mass=37.0862227121 | units.MSun,
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
stars = Particles(3, mass=[10., 20., 40.] | units.MSun)
stars = instance.particles.add_particles(stars)
stars.initial_mass = stars.mass
instance.commit_particles()
while instance.model_time < .05 | units.Myr:
instance.evolve_model()
for star in stars:
self.assertEqual(instance.ActiveModel[star].__class__.__name__, "EVtwin")
while instance.model_time <= 3. | units.Myr:
instance.evolve_model()
for star in stars:
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)
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()
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
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()
for star in stars:
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
self.assertEqual(age1, age2)
self.assertEqual(age2, age3)
instance.stop()
def slowtest5(self):
print("Testing FallbackStellarEvolution: evolve with end time")
instance = FallbackStellarEvolution()
instance._main_se.parameters.max_age_stop_condition = 0.1 | units.Myr
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.assertTrue(.101 | units.Myr < instance.model_time)
instance.stop()
def test6(self):
print("Testing FallbackStellarEvolution: enforce monotonic mass evolution")
instance = FallbackStellarEvolution(enforce_monotonic_mass_evolution=True)
instance._main_se.parameters.max_age_stop_condition = 3. | units.Myr
stars = Particles(1, mass=[40.] | units.MSun)
stars = instance.particles.add_particles(stars)
instance.commit_particles()
while instance.ActiveModel[stars[0]].__class__.__name__ == "EVtwin":
emass = stars[0].mass
instance.evolve_model()
self.assertTrue(stars[0].mass <= emass)
instance.stop()
def slowtest7(self):
print("Testing FallbackStellarEvolution: test mesa")
instance = FallbackStellarEvolution(MESA)
instance._main_se.parameters.max_age_stop_condition = 3. | units.Myr
stars = Particles(3, mass=[40., 40., 40.] | units.MSun)
stars = instance.particles.add_particles(stars)
instance.commit_particles()
instance.evolve_model(3.01 | units.Myr)
for star in stars:
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
self.assertEqual(age1, age2)
self.assertEqual(age2, age3)
instance.stop()
| 10,863
| 44.647059
| 131
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_sph_to_star.py
|
import os.path
import numpy
from time import sleep
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 pynbody_column_density_plot, HAS_PYNBODY
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
from amuse.support.exceptions import AmuseException
from amuse.io import write_set_to_file, read_set_from_file
from amuse.community.evtwin.interface import EVtwin
from amuse.community.mesa.interface import MESA
from amuse.community.gadget2.interface import Gadget2
from amuse.community.fi.interface import Fi
from amuse.units import units, generic_unit_system, nbody_system, constants
from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits
from amuse.datamodel import Particle, Particles, ParticlesSuperset
from amuse.ext.evrard_test import new_evrard_gas_sphere
from amuse.ext.star_to_sph import convert_stellar_model_to_SPH
from amuse.ext.sph_to_star import SPH2StellarModel, convert_SPH_to_stellar_model
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)
particles = convert_stellar_model_to_SPH(
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.gas_particles.add_particles(particles)
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',
'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
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',
'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.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(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)
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)
print(stellar_evolution.particles)
self.assertAlmostEqual(stellar_evolution.particles.age, [204.59, 103.02] | units.Myr, 1)
self.assertAlmostRelativeEqual(stellar_evolution.particles[0].temperature,
stellar_evolution.particles[1].temperature, 2)
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)
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)
print(stellar_evolution.particles)
self.assertAlmostEqual(stellar_evolution.particles.age, [200.0, 100.0] | units.Myr, 1)
self.assertAlmostRelativeEqual(stellar_evolution.particles[0].temperature,
stellar_evolution.particles[1].temperature, 2)
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.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,
seed=12345
).gas_particles
sph_particles_2 = convert_stellar_model_to_SPH(
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_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)
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()
| 8,914
| 47.451087
| 117
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_collision_handler.py
|
from amuse.units import units
from amuse.datamodel import Particles, Particle
from amuse.support.exceptions import AmuseException
from amuse.test.amusetest import TestCase
from amuse.ext.sticky_spheres import StickySpheres
from amuse.couple.collision_handler import CollisionHandler
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):
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
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"
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"
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),
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_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,
[[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,
[[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: "
"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)
collision_code = CollisionCodeForTesting()
collision_code.stellar_evolution_code_required = True
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)
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: "
"CollisionHandler(..., stellar_evolution_code=x)")
handler = CollisionHandler(
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,
[[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,
[[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,
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,
[[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,
[[0.5, 0.5, 0.5], [2.5, 6.5, 17.5], [4.5, 20.5, 94.5]] | units.km / units.s)
| 11,690
| 44.313953
| 154
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/__init__.py
| 0
| 0
| 0
|
py
|
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_cloud.py
|
import sys
import os
import numpy
from amuse.test import amusetest
from amuse.ext import cloud
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.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"])
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)
)
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):
# 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)
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"])
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,
)
self.assertAlmostRelativeEquals(grid.rho[5][4][4], 0.5921875 | generic_unit_system.mass / generic_unit_system.length**3)
| 2,499
| 35.764706
| 128
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_sink.py
|
import numpy
from amuse.test.amusetest import TestCase
from amuse.support.exceptions import AmuseWarning, AmuseException
from amuse.units import units, nbody_system, generic_unit_system, quantities
from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits
from amuse.units.quantities import zero, VectorQuantity
from amuse.datamodel import Particle, Particles, ParticlesSuperset
from amuse.community.interface.gd import GravitationalDynamics
from amuse.community.interface.stopping_conditions import StoppingConditions
from amuse.ext.sink import SinkParticles, new_sink_particles
from amuse.ext import sink
from amuse.community.gadget2.interface import Gadget2
from amuse.ext.evrard_test import new_evrard_gas_sphere
from amuse.ic.plummer import new_plummer_model
class TestSinkParticles(TestCase):
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)
self.assertEqual(sinks.sink_radius, [42.0, 43.0] | units.RSun)
self.assertEqual(sinks.mass, 0.0 | units.MSun)
self.assertEqual(sinks.position, [0.0, 0.0, 0.0] | units.parsec)
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)
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)
self.assertEqual(sinks.velocity, [4.0, 5.0, 6.0] | nbody_system.length/nbody_system.time)
self.assertEqual(sinks.angular_momentum, [9.0, 8.0, 7.0] | nbody_system.mass*nbody_system.length**2/nbody_system.time)
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.")
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.")
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.")
particles.radius = 42.0 | units.RSun
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]])
self.assertEqual(sinks.mass, 5.0 | units.MSun)
self.assertEqual(sinks.sink_radius, 42.0 | units.RSun)
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)
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']),
set(str(sinks).split("\n")[0].split()))
self.assertEqual(set(['key', 'mass', 'radius', 'x', 'y', 'z']),
set(str(particles).split("\n")[0].split()))
def test4(self):
print("Testing SinkParticles accrete")
particles = Particles(10)
particles.radius = 42.0 | units.RSun
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)
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(particles), 6)
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
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(particles), 4)
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
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.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)
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(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
class TestSinkParticlesLoopingOverSources(TestSinkParticles):
looping_over = "sources"
class TestNewSinkParticles(TestCase):
looping_over = "sinks"
def test1(self):
print("Test the documentation for new_sink_particles")
print(new_sink_particles.__doc__)
def test2(self):
print("Demonstrate new_sink_particles usage")
cloud = Particles(100)
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)
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)
density_limit_detection = sph_code.stopping_conditions.density_limit_detection
density_limit_detection.enable()
sph_code.evolve_model(1 | units.Myr)
self.assertTrue(density_limit_detection.is_set())
self.assertEqual(len(density_limit_detection.particles()), 3)
self.assertEqual(density_limit_detection.particles().position,
[[100, 100, 100], [200, 200, 200], [300, 300, 300]] | units.parsec)
print(density_limit_detection.particles())
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)
self.assertEqual(sinks.sink_radius, 1.0 | units.parsec)
self.assertEqual(sinks.mass, 1.0 | units.MSun)
self.assertEqual(sinks.position,
[[100, 100, 100], [200, 200, 200], [300, 300, 300]] | units.parsec)
self.assertEqual(len(sph_code.gas_particles), 97)
self.assertAlmostRelativeEqual(sph_code.gas_particles.total_mass() + clumps.total_mass(), 100 | units.MSun, 10)
self.assertAlmostRelativeEqual(sph_code.gas_particles.total_mass(), 97 | units.MSun, 10)
sinks.accrete(sph_code.gas_particles)
self.assertAlmostRelativeEqual(sinks.mass, [25, 25, 25] | units.MSun, 10)
self.assertEqual(len(sph_code.gas_particles), 25)
self.assertAlmostRelativeEqual(sph_code.gas_particles.total_mass() + clumps.total_mass(), 100 | units.MSun, 10)
self.assertAlmostRelativeEqual(sph_code.gas_particles.total_mass(), 25 | units.MSun, 10)
def test3(self):
print("Demonstrate new_sink_particles usage (using Gadget2)")
UnitLength = 1.0 | units.kpc
UnitMass = 1.0e10 | units.MSun
UnitVelocity = 1.0 | units.km / units.s
convert_nbody = nbody_system.nbody_to_si(UnitLength, UnitMass)
converter = ConvertBetweenGenericAndSiUnits(UnitLength, UnitMass, UnitVelocity)
number_gas_particles = 1000
gas = new_evrard_gas_sphere(number_gas_particles, convert_nbody, do_scale=True, seed=12345)
sph_code = Gadget2(converter)
sph_code.initialize_code()
sph_code.parameters.stopping_condition_maximum_density = 10 * UnitMass / UnitLength**3
sph_code.gas_particles.add_particles(gas)
self.assertIsOfOrder(max(sph_code.gas_particles.density), UnitMass / UnitLength**3)
density_limit_detection = sph_code.stopping_conditions.density_limit_detection
density_limit_detection.enable()
sph_code.evolve_model(10.0 | units.Myr)
self.assertTrue(density_limit_detection.is_set())
self.assertTrue(sph_code.model_time < 10.0 | units.Myr)
print("density_limit exceeded at t =", sph_code.model_time.as_quantity_in(units.Myr))
self.assertEqual(len(density_limit_detection.particles()), 1)
self.assertTrue(density_limit_detection.particles().density >
10 * UnitMass / UnitLength**3)
clumps = density_limit_detection.particles().copy()
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)
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"]),
set(sph_code.particles.get_attribute_names_defined_in_store()))
sinks.accrete(sph_code.gas_particles)
self.assertAlmostRelativeEqual(sinks.mass, 3 * UnitMass / number_gas_particles, 10)
self.assertEqual(len(sph_code.gas_particles), number_gas_particles - 3)
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
self.assertAlmostRelativeEqual(sinks.mass, 3 * UnitMass / number_gas_particles, 10)
self.assertAlmostRelativeEqual(sph_code.particles.total_mass(), UnitMass, 10)
steps = 0
while True:
sph_code.evolve_model(sph_code.model_time + (0.1 | units.Myr))
sinks.sink_radius = 4 * clumps_in_code.radius
sinks.accrete(sph_code.gas_particles)
steps += 1
if density_limit_detection.is_set():
break
self.assertEqual(len(sph_code.gas_particles), number_gas_particles - 7)
self.assertAlmostRelativeEqual(sinks.mass, 7 * UnitMass / number_gas_particles, 10)
self.assertAlmostRelativeEqual(sph_code.particles.total_mass(), UnitMass, 10)
self.assertAlmostRelativeEqual(sph_code.gas_particles.total_mass(), UnitMass - sinks.total_mass(), 10)
self.assertTrue(density_limit_detection.is_set())
self.assertEqual(steps, 5)
self.assertTrue(sph_code.model_time < 10.0 | units.Myr)
print("density_limit exceeded at t =", sph_code.model_time.as_quantity_in(units.Myr))
self.assertEqual(len(density_limit_detection.particles()), 5)
self.assertTrue((density_limit_detection.particles().density >
10 * UnitMass / UnitLength**3).all())
clumps = density_limit_detection.particles().copy()
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)
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)
self.assertAlmostRelativeEqual(sinks.position[1:], clumps.position, 10)
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.gas_particles)
self.assertEqual(len(sph_code.gas_particles), number_gas_particles - 66)
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"
class TestNonSphericalSinkParticles(TestCase):
def test1(self):
""" Test creating shapes and combining them """
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)
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)
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)
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)
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)
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)
def create_particle_grid(self):
particles = Particles(2000)
particles.radius = 1. | units.RSun
particles.mass = 1. | units.MSun
particles.velocity = [1, 0, -1] | units.km/units.s
i = 0
for x in range(-5, 5):
for y in range(-5, 5):
for z in numpy.arange(-5, 5, 0.5):
particles[i].position = [x, y, z] | units.RSun
i += 1
return particles
def assertIsSubvector(self, subvector, vectorlist):
self._check_comparable(subvector, vectorlist)
if not (subvector == vectorlist).all(axis=1).any():
raise self.failureException("{} is not a subvector of given vectorlist".format(subvector))
class StubInterface(object):
def __init__(self, **options):
self.maximum_density = 1 | units.kg / units.m**3
self._gas_particles = Particles()
self._dm_particles = Particles()
self._all_particles = ParticlesSuperset([self._gas_particles, self._dm_particles])
def before_get_parameter(self):
pass
def before_set_parameter(self):
pass
def initialize_code(self):
return 0
synchronize_model = commit_particles = recommit_particles = commit_parameters = initialize_code
def new_particle(self, mass, x, y, z, vx, vy, vz, *args):
next_id = len(self._dm_particles)
temp = Particles(len(mass))
temp.mass = mass
temp.x = x
temp.y = y
temp.z = z
temp.vx = vx
temp.vy = vy
temp.vz = vz
temp.id = range(next_id, next_id + len(mass))
self._dm_particles.add_particles(temp)
return [temp.id, temp.id]
def new_gas_particle(self, mass, x, y, z, vx, vy, vz, *args):
next_id = len(self._gas_particles) + 1000000
temp = Particles(len(mass))
temp.mass = mass
temp.x = x
temp.y = y
temp.z = z
temp.vx = vx
temp.vy = vy
temp.vz = vz
temp.id = range(next_id, next_id + len(mass))
self._gas_particles.add_particles(temp)
return [temp.id, temp.id]
def delete_particle(self, indices):
for index in indices:
for id, particle in zip(self._all_particles.id, self._all_particles):
if id == index:
self._all_particles.remove_particle(particle)
return 0
def get_mass(self, indices):
return [[mass for index in indices for id, mass in zip(self._all_particles.id,
self._all_particles.mass) if index == id], [0]*len(indices)]
def set_mass(self, indices, masses):
for index, mass in zip(indices, masses):
for id, particle in zip(self._all_particles.id, self._all_particles):
if id == index:
particle.mass = mass
break
return 0
def get_position(self, indices):
return [[x for index in indices for id, x in zip(self._all_particles.id, self._all_particles.x) if index == id],
[y for index in indices for id, y in zip(self._all_particles.id, self._all_particles.y) if index == id],
[z for index in indices for id, z in zip(self._all_particles.id, self._all_particles.z) if index == id],
[0]*len(indices)]
def get_velocity(self, indices):
return [[vx for index in indices for id, vx in zip(self._all_particles.id, self._all_particles.vx) if index == id],
[vy for index in indices for id, vy in zip(self._all_particles.id, self._all_particles.vy) if index == id],
[vz for index in indices for id, vz in zip(self._all_particles.id, self._all_particles.vz) if index == id],
[0]*len(indices)]
def has_stopping_condition(self, type):
return 1 if type == 6 else 0
def get_stopping_condition_maximum_density_parameter(self):
return self.maximum_density
def set_stopping_condition_maximum_density_parameter(self, value):
self.maximum_density = value
is_stopping_condition_set = is_stopping_condition_enabled = has_stopping_condition
def get_number_of_stopping_conditions_set(self):
return 3
def get_stopping_condition_info(self, sc_indices):
return [6]*len(sc_indices), [1]*len(sc_indices)
def get_stopping_condition_particle_index(self, sc_index, sc_sub_index):
return list(range(len(self._gas_particles) + 1000000 - len(sc_index), len(self._gas_particles) + 1000000))
def enable_stopping_condition(self, type):
pass
def evolve_model(self, time):
return 0
class Stub(GravitationalDynamics):
def __init__(self, unit_converter=None, **options):
self.stopping_conditions = StoppingConditions(self)
GravitationalDynamics.__init__(
self,
StubInterface(**options),
unit_converter,
**options
)
def define_parameters(self, object):
object.add_method_parameter(
"get_stopping_condition_maximum_density_parameter",
"set_stopping_condition_maximum_density_parameter",
"stopping_condition_maximum_density",
"maximum density of a gas particle",
default_value=-1.0 | generic_unit_system.density
)
def define_methods(self, object):
GravitationalDynamics.define_methods(self, object)
object.add_method("new_gas_particle",
(nbody_system.mass, nbody_system.length, nbody_system.length, nbody_system.length,
nbody_system.speed, nbody_system.speed, nbody_system.speed),
(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_set('dm_particles', 'index_of_the_particle')
object.set_new('dm_particles', 'new_particle')
object.set_delete('dm_particles', 'delete_particle')
object.add_getter('dm_particles', 'get_mass', names=("mass",))
object.add_setter('dm_particles', 'set_mass', names=("mass",))
object.add_getter('dm_particles', 'get_position', names=("x", "y", "z"))
object.add_getter('dm_particles', 'get_velocity', names=("vx", "vy", "vz"))
object.define_set('gas_particles', 'index_of_the_particle')
object.set_new('gas_particles', 'new_gas_particle')
object.set_delete('gas_particles', 'delete_particle')
object.add_getter('gas_particles', 'get_mass', names=("mass",))
object.add_getter('gas_particles', 'get_position', names=("x", "y", "z"))
object.add_getter('gas_particles', 'get_velocity', names=("vx", "vy", "vz"))
object.add_query('particles', 'get_stopping_condition_particle_index')
| 26,222
| 49.72147
| 182
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_salpeter.py
|
import sys
import os
import numpy.random
from amuse.test import amusetest
from amuse.units import units, nbody_system
from amuse.ic.salpeter import SalpeterIMF
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)
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)
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)
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)
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)
| 2,590
| 42.915254
| 104
|
py
|
amuse
|
amuse-main/src/amuse/test/suite/ext_tests/test_solarsystem.py
|
import numpy
from amuse.test.amusetest import TestCase
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)
# 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)
| 2,365
| 50.434783
| 134
|
py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.