Esempio n. 1
0
def test_big_example():
    obj = object()
    structure = {'a': A(3.14, ()), 'x': {'foo': [('spam', obj), 123]}}
    tree = {
        '_class': 'dict',
        'a': {
            '_class': 'test_serializable_h5.A',
            'a': 3.14,
            'b': {
                '_class': 'tuple'
            }
        },
        'x': {
            '_class': 'dict',
            'foo': {
                '_class': 'list',
                '0': {
                    '_class': 'tuple',
                    '0': 'spam',
                    '1': obj
                },
                '1': 123
            }
        }
    }
    assert structure_to_tree(structure) == tree
    data = tree_to_structure(tree)
    assert type(data) == dict
    assert data.keys() == {'a', 'x'}
    assert data['x'] == structure['x']
    assert_dataclass_eq(data['a'], structure['a'])
Esempio n. 2
0
 def test_init(self):
     ir = InnerRegion('test', Box())
     assert ir.name == 'test'
     assert_dataclass_eq(ir.shape, Box())
     assert ir.total_absorbed_particles == 0
     assert ir.total_absorbed_charge == 0
     assert ir.inverted == False
Esempio n. 3
0
 def test_to_component(self):
     assert_dataclass_eq(
         TimeGrid(100, 1, 10).to_component(),
         time_grid.TimeGridConf(100, 10, 1))
     assert_dataclass_eq(
         TimeGrid(123, 3, 13).to_component(),
         time_grid.TimeGridConf(123, 12, 3))
Esempio n. 4
0
 def test_import_h5(self, tmpdir):
     bio = BytesIO()
     grid1 = TimeGrid(123, 3, 13, 111)
     with h5py.File(bio, mode="w") as h5file:
         grid1.export_h5(h5file.create_group("/gr"))
     with h5py.File(bio, mode="r") as h5file:
         grid2 = TimeGrid.import_h5(h5file["/gr"])
     assert_dataclass_eq(grid1, grid2)
Esempio n. 5
0
def test_conf_to_configparser_and_back(backend):
    confs = [C().to_conf() for C in comp_list]
    parser = ConfigParser()
    for c in confs:
        c.add_section_to_parser(parser)
    conf2 = ConfigSection.parser_to_confs(parser)
    for a, b in zip(conf2, confs):
        assert_dataclass_eq(a, b)
Esempio n. 6
0
 def test_export_h5(self):
     f = BytesIO()
     p1 = ParticleSource()
     with h5py.File(f, mode="w") as h5file:
         p1.export_h5(h5file.create_group(p1.name))
     with h5py.File(f, mode="r") as h5file:
         p2 = ParticleSource.import_h5(h5file[p1.name])
     assert_dataclass_eq(p1, p2)
Esempio n. 7
0
 def test_conf_repr(self):
     # noinspection PyUnresolvedReferences
     from numpy import array  # for use in eval
     conf = Config(sources=[ParticleSourceConf()],
                   inner_regions=(InnerRegionConf(), ))
     s = repr(conf)
     c1 = eval(s)
     assert_dataclass_eq(c1, conf)
Esempio n. 8
0
def test_single_particle_in_free_space(tmpdir):
    run_jupyter("examples/single_particle_in_free_space",
                "single_particle_in_free_space.ipynb", tmpdir.join('newdir'),
                True)
    assert_dataclass_eq(
        Config.from_fname(tmpdir.join('newdir').join('config.ini')),
        Config.from_fname(
            tmpdir.join('newdir').join('single_particle_in_free_space.conf')))
Esempio n. 9
0
 def test_generate_for_simulation(self):
     ps = ParticleSource('test', Box(6, 0), 17, 13, (4, 4, 4), 0, -2, 6)
     assert_dataclass_eq(
         ps.generate_initial_particles(),
         ParticleArray(range(17), -2, 6, np.full((17, 3), 6),
                       np.full((17, 3), 4), False))
     assert_dataclass_eq(
         ps.generate_each_step(),
         ParticleArray(range(13), -2, 6, np.full((13, 3), 6),
                       np.full((13, 3), 4), False))
Esempio n. 10
0
 def test_init(self):
     p = ParticleSource()
     assert p.name == "particle_source"
     assert_dataclass_eq(p.shape, Box())
     assert p.initial_number_of_particles == 0
     assert p.particles_to_generate_each_step == 0
     assert_array_equal(p.mean_momentum, np.zeros(3))
     assert p.temperature == 0
     assert p.charge == 0
     assert p.mass == 1
Esempio n. 11
0
 def test_write_python(self, monkeypatch, tmpdir, sim_full):
     monkeypatch.chdir(tmpdir)
     sim = sim_full
     writer = OutputWriterPython('test_', '.ext')
     writer.write(sim, 'asdf')
     assert tmpdir.join('test_asdf.ext').exists()
     writer.write(sim)
     assert tmpdir.join('test_0000000.ext').exists()
     with h5py.File('test_0000000.ext') as h5file:
         assert Reader().guess_h5_format(h5file) == 'python'
         assert_dataclass_eq(Reader().read_simulation(h5file), sim)
Esempio n. 12
0
 def test_assert_eq(self):
     AB = self.AB
     ab = AB(1, 2)
     assert_dataclass_eq(ab, ab)
     assert_dataclass_eq(ab, AB(1, 2))
     with raises(AssertionError, match='a'):
         assert_dataclass_eq(ab, AB(2, 2))
     with raises(AssertionError, match=''):
         assert_dataclass_eq(ab, (1, 2))
     with raises(AssertionError, match='xyz'):
         assert_dataclass_eq(ab, self.AB2(1, 2), 'xyz')
Esempio n. 13
0
 def test_write_history(self, monkeypatch, tmpdir, sim_full):
     monkeypatch.chdir(tmpdir)
     sim = sim_full
     assert tmpdir.listdir() == []
     writer = OutputWriterHistory('test_', '.ext')
     assert tmpdir.join('test_history.ext').exists()
     assert writer.h5file.keys() == set()
     writer.write(sim, 'asdf')
     assert writer.h5file.keys() == set()
     writer.write(sim)
     assert writer.h5file.keys() == {'history', 'simulation'}
     with h5py.File('test_history.ext') as h5file:
         assert Reader().guess_h5_format(h5file) == 'history'
         assert_dataclass_eq(Reader().read_simulation(h5file), sim)
Esempio n. 14
0
def test_minimal_example():
    parser = ConfigParser()
    parser.read("examples/minimal_working_example/minimal_conf.conf")
    components = [
        conf.make() for conf in ConfigSection.parser_to_confs(parser)
    ]
    for a, b in zip(components, [
            TimeGridConf(1e-7, 1e-9, 1e-9),
            SpatialMeshConf((5, 5, 15), (0.5, 0.5, 1.5)),
            ParticleInteractionModelConf('noninteracting'),
            BoundaryConditionsConf(0),
            ExternalMagneticFieldUniformConf('mgn_uni'),
            ExternalElectricFieldUniformConf('el_uni'),
            OutputFileConf('example_', '.h5')
    ]):
        assert_dataclass_eq(a, b)
Esempio n. 15
0
 def test_init(self):
     assert_dataclass_eq(TimeGrid(100.0, 1.0, 10.0), TimeGrid(100, 1, 10))
     t = TimeGrid(123, 3, 13)
     assert t.total_time == 123
     assert t.total_nodes == 42
     assert t.time_step_size == 3
     assert t.time_save_step == 12
     assert t.node_to_save == 4
     assert t.current_time == 0
     assert t.current_node == 0
     t = TimeGrid(123, 4, 13, 1000)
     assert t.total_time == 123
     assert t.total_nodes == 32
     assert t.time_step_size == 123 / 31
     assert t.time_save_step == 123 / 31 * 3
     assert t.node_to_save == 3
     assert t.current_time == pytest.approx(123000 / 31)
     assert t.current_node == 1000
Esempio n. 16
0
def test_read_conf():
    p = ConfigParser()
    c = Config(output_file=OutputFileConf("conf-prefix", "conf-suffix"))
    p.read_string(c.export_to_string())
    assert_dataclass_eq(read_conf(p, None, None, 'cpp'), c)
    assert_dataclass_eq(read_conf(p, 'prefix2', None, 'cpp'),
                        Config(output_file=OutputFileConf("prefix2", "conf-suffix")))
    assert_dataclass_eq(read_conf(p, 'prefix3', 'suffix3', 'cpp'),
                        Config(output_file=OutputFileConf("prefix3", "suffix3")))
    assert_dataclass_eq(read_conf(p, None, 'suffix4', 'cpp'),
                        Config(output_file=OutputFileConf("conf-prefix", "suffix4")))
Esempio n. 17
0
 def test_absorb_charge_inverted(self):
     particles = ParticleArray([1], -2.0, 1.0, (0, 0, 0), np.zeros(3))
     ir = InnerRegion('test', Box(), inverted=True)
     assert ir.total_absorbed_particles == 0
     assert ir.total_absorbed_charge == 0
     ir.collide_with_particles(particles)
     assert ir.total_absorbed_particles == 0
     assert ir.total_absorbed_charge == 0
     assert_dataclass_eq(
         particles,
         ParticleArray([1], -2.0, 1.0, np.zeros((1, 3)), np.zeros((1, 3))))
     particles = ParticleArray([1], -2.0, 1.0, (10, 10, 10), np.zeros(3))
     ir = InnerRegion('test', Box(), inverted=True)
     assert ir.total_absorbed_particles == 0
     assert ir.total_absorbed_charge == 0
     ir.collide_with_particles(particles)
     assert ir.total_absorbed_particles == 1
     assert ir.total_absorbed_charge == -2
     assert_dataclass_eq(
         particles,
         ParticleArray([], -2.0, 1.0, np.zeros((0, 3)), np.zeros((0, 3))))
     particles = ParticleArray([1, 2], -2.0, 1.0, [(0, 0, 0), (10, 10, 10)],
                               np.zeros((2, 3)))
     ir = InnerRegion('test', Box(), inverted=True)
     assert ir.total_absorbed_particles == 0
     assert ir.total_absorbed_charge == 0
     ir.collide_with_particles(particles)
     assert ir.total_absorbed_particles == 1
     assert ir.total_absorbed_charge == -2
     assert_dataclass_eq(
         particles,
         ParticleArray([1], -2.0, 1.0, [(0, 0, 0)], np.zeros((1, 3))))
Esempio n. 18
0
def test_tree_to_structure():
    assert_dataclass_eq(
        tree_to_structure({
            '_class': 'test_serializable_h5.A',
            'a': 1,
            'b': 'a'
        }), A(1, 'a'))
    assert tree_to_structure({
        '_class': 'dict',
        'a': 1,
        'b': 'a'
    }) == {
        'a': 1,
        'b': 'a'
    }
    assert tree_to_structure({
        '_class': 'list',
        '0': 13,
        '1': 14,
        '2': 15
    }) == [13, 14, 15]
    assert tree_to_structure({
        '_class': 'tuple',
        '0': 13,
        '1': 14,
        '2': 15
    }) == (13, 14, 15)
    a = np.full(10, 3.14)
    t = tree_to_structure({'_class': 'tuple', '0': a})
    assert type(t) is tuple and len(t) == 1 and t[0] is a
    with raises(KeyError):
        tree_to_structure({})
    with raises(KeyError):
        tree_to_structure({'class_': 'nonexistant'})
    with raises(KeyError):
        tree_to_structure({'_class': 'list', 'a': 1, 'b': 'a'})
    with raises(TypeError):
        tree_to_structure({'_class': 'test_serializable_h5.A', 'a': 1})
Esempio n. 19
0
 def test_gradient(self):
     m = MeshGrid((1.5, 2, 1), (4, 3, 2))
     potential = self.Array(m)
     potential._data = self.xp.stack([
         self.xp.array([[0., 0, 0], [1, 2, 3], [4, 3, 2], [4, 4, 4]]),
         self.xp.zeros((4, 3))
     ], -1)
     expected = self.Array(
         m, 3, [[[[-2, 0, 0], [0, 0, 0]], [[-4, 0, 0], [0, 0, 0]],
                 [[-6, 0, 0], [0, 0, 0]]],
                [[[-4, -1, 1], [0, 0, 1]], [[-3, -1, 2], [0, 0, 2]],
                 [[-2, -1, 3], [0, 0, 3]]],
                [[[-3, 1, 4], [0, 0, 4]], [[-2, 1, 3], [0, 0, 3]],
                 [[-1, 1, 2], [0, 0, 2]]],
                [[[0, 0, 4], [0, 0, 4]], [[-2, 0, 4], [0, 0, 4]],
                 [[-4, 0, 4], [0, 0, 4]]]])
     field = potential.gradient()
     assert_dataclass_eq(field, expected)
     with raises(
             ValueError,
             match=
             "Trying got compute gradient for a non-scalar field: ambiguous"
     ):
         field.gradient()
Esempio n. 20
0
 def test_generate_particles(self):
     ps = ParticleSource('test', Box((1., 2., 3.), 0), 17, 13, (-2, 3, 1),
                         0, -2, 6)
     assert_dataclass_eq(
         ps.generate_num_of_particles(3),
         ParticleArray(range(3), -2, 6, [(1, 2, 3)] * 3, [(-2, 3, 1)] * 3,
                       False))
     assert_dataclass_eq(
         ps.generate_num_of_particles(1),
         ParticleArray([0], -2, 6, [(1, 2, 3)], [(-2, 3, 1)], False))
     assert_dataclass_eq(
         ps.generate_num_of_particles(0),
         ParticleArray([], -2, 6, np.empty((0, 3)), np.empty((0, 3)),
                       False))
Esempio n. 21
0
 def test_init_from_config(self, backend):
     efconf = Config()
     parser = ConfigParser()
     parser.read_string(efconf.export_to_string())
     sim = Config.from_configparser(parser).make()
     assert_dataclass_eq(sim.time_grid, TimeGrid(100, 1, 10))
     g = MeshGrid(10, 11)
     assert_dataclass_eq(sim.mesh, g)
     assert_dataclass_eq(sim.potential, self.Array(g))
     assert_dataclass_eq(sim.charge_density, self.Array(g))
     assert_dataclass_eq(
         sim.electric_field,
         FieldOnGrid('spatial_mesh', 'electric', self.Array(g, 3)))
     assert sim.inner_regions == []
     assert sim.particle_sources == []
     assert_dataclass_eq(sim.electric_fields,
                         FieldZero('ZeroSum', 'electric'))
     assert_dataclass_eq(sim.magnetic_fields,
                         FieldZero('ZeroSum', 'magnetic'))
     assert sim.particle_interaction_model == Model.PIC
Esempio n. 22
0
 def test_dict_init(self):
     ab = self.AB(1, 'ham')
     assert_dataclass_eq(self.AB(**ab.dict_init), ab)
Esempio n. 23
0
 def test_repr_init(self):
     AB = self.AB
     ab = AB(2, 'spam')
     assert_dataclass_eq(eval(repr(ab)), ab)
Esempio n. 24
0
 def test_from_step(self):
     assert_dataclass_eq(MeshGrid.from_step(10, 1, 7), MeshGrid(10, 11, 7))
     assert_dataclass_eq(MeshGrid.from_step([10, 20, 5], [1, 4, 1]),
                         MeshGrid([10, 20, 5], [11, 6, 6]))
     assert_dataclass_eq(MeshGrid.from_step(10, [1, 2, 4]),
                         MeshGrid(10, [11, 6, 4]))
Esempio n. 25
0
 def test_conf_export(self):
     conf = Config(sources=[ParticleSourceConf()],
                   inner_regions=(InnerRegionConf(), ))
     s = conf.export_to_string()
     c1 = Config.from_string(s)
     assert_dataclass_eq(c1, conf)
Esempio n. 26
0
 def test_config_make(self):
     assert_dataclass_eq(time_grid.TimeGridConf().make(),
                         TimeGrid(100.0, 1.0, 10.0))
     assert_dataclass_eq(
         time_grid.TimeGridConf(123, 13, 3).make(), TimeGrid(123, 3, 13))
Esempio n. 27
0
def test_components_to_conf_and_back(backend):
    for Component in comp_list:
        x = Component()
        y = x.to_conf().make()
        assert_dataclass_eq(x, y)
Esempio n. 28
0
    def test_all_config(self, backend):
        efconf = Config(
            TimeGridConf(200, 20, 2),
            SpatialMeshConf((5, 5, 5), (.1, .1, .1)),
            sources=[
                ParticleSourceConf('a', Box()),
                ParticleSourceConf('c', Cylinder()),
                ParticleSourceConf('d', Tube(start=(0, 0, 0), end=(0, 0, 1)))
            ],
            inner_regions=[
                InnerRegionConf('1', Box(), 1),
                InnerRegionConf('2', Sphere(), -2),
                InnerRegionConf('3', Cylinder(), 0),
                InnerRegionConf('4', Tube(), 4)
            ],
            output_file=OutputFileConf(),
            boundary_conditions=BoundaryConditionsConf(-2.7),
            particle_interaction_model=ParticleInteractionModelConf('binary'),
            external_fields=[
                ExternalElectricFieldUniformConf('x', (-2, -2, 1)),
                ExternalMagneticFieldExpressionConf(
                    'y', ('0', '0', '3*x + sqrt(y) - z**2'))
            ])

        parser = ConfigParser()
        parser.read_string(efconf.export_to_string())
        conf = Config.from_configparser(parser)
        sim = conf.make()
        assert_dataclass_eq(sim.time_grid, TimeGrid(200, 2, 20))
        assert_dataclass_eq(sim.mesh, MeshGrid(5, 51))
        assert_dataclass_eq(
            sim.electric_field,
            FieldOnGrid('spatial_mesh', 'electric', self.Array(sim.mesh, 3)))
        assert_dataclass_eq(sim.charge_density, self.Array(sim.mesh))
        expected = np.full((51, 51, 51), -2.7)
        expected[1:-1, 1:-1, 1:-1] = 0
        assert_dataclass_eq(sim.potential, self.Array(sim.mesh, (), expected))
        _assert_value_eq(sim.inner_regions, [
            InnerRegion('1', Box(), 1),
            InnerRegion('2', Sphere(), -2),
            InnerRegion('3', Cylinder(), 0),
            InnerRegion('4', Tube(), 4)
        ])
        _assert_value_eq(sim.particle_sources, [
            ParticleSourceConf('a', Box()).make(),
            ParticleSourceConf('c', Cylinder()).make(),
            ParticleSourceConf('d', Tube(start=(0, 0, 0),
                                         end=(0, 0, 1))).make()
        ])
        assert_dataclass_eq(
            sim.electric_fields,
            FieldUniform('x', 'electric', np.array((-2, -2, 1))))
        assert_dataclass_eq(
            sim.magnetic_fields,
            FieldExpression('y', 'magnetic', '0', '0', '3*x + sqrt(y) - z**2'))
        assert sim.particle_interaction_model == Model.binary