def test_binary_field(self): d = Config().make() d.particle_arrays = [ParticleArray(1, -1, 1, [(1, 2, 3)], [(-2, 2, 0)], False)] assert_array_almost_equal(d.binary_electric_field_at_positions((1, 2, 3)), (0, 0, 0)) assert_array_almost_equal(d.binary_electric_field_at_positions((1, 2, 4)), (0, 0, -1)) assert_array_almost_equal(d.binary_electric_field_at_positions((0, 2, 3)), (1, 0, 0)) assert_array_almost_equal(d.binary_electric_field_at_positions((0, 1, 2)), (1 / sqrt(27), 1 / sqrt(27), 1 / sqrt(27)))
def test_all_config(self): efconf = Config(TimeGridConf(200, 20, 2), SpatialMeshConf((5, 5, 5), (.1, .1, .1)), sources=[ParticleSourceConf('a', Box()), ParticleSourceConf('c', Cylinder()), ParticleSourceConf('d', Tube())], 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=[ExternalFieldUniformConf('x', 'electric', (-2, -2, 1)), ExternalFieldExpressionConf('y', 'magnetic', ('0', '0', '3*x + sqrt(y) - z**2'))]) parser = ConfigParser() parser.read_string(efconf.export_to_string()) sim = Config.from_configparser(parser).make() assert sim.time_grid == TimeGrid(200, 2, 20) assert sim.spat_mesh == SpatialMesh.do_init((5, 5, 5), (.1, .1, .1), BoundaryConditionsConf(-2.7)) assert sim.inner_regions == [InnerRegion('1', Box(), 1), InnerRegion('2', Sphere(), -2), InnerRegion('3', Cylinder(), 0), InnerRegion('4', Tube(), 4)] assert type(sim._field_solver) == FieldSolver assert sim.particle_sources == [ParticleSourceConf('a', Box()).make(), ParticleSourceConf('c', Cylinder()).make(), ParticleSourceConf('d', Tube()).make()] assert sim.electric_fields == [ExternalFieldUniform('x', 'electric', np.array((-2, -2, 1)))] assert sim.magnetic_fields == [ExternalFieldExpression('y', 'magnetic', '0', '0', '3*x + sqrt(y) - z**2')] assert sim.particle_interaction_model == ParticleInteractionModel("binary") assert sim._output_filename_prefix == "out_" assert sim._output_filename_suffix == ".h5"
def test_particle_generation(self, monkeypatch, tmpdir, backend_and_solver): monkeypatch.chdir(tmpdir) conf = Config( TimeGridConf(2, 1, 1), SpatialMeshConf((5, 5, 5), (.1, .1, .1)), sources=[ ParticleSourceConf('a', Box((2, 2, 2), (0, 0, 0)), 2, 1, (0, 0, 0), 0, charge=0), ParticleSourceConf('b', Box((1, 1, 1), (0, 0, 0)), 7, 5, (0, 0, 0), 0, charge=0) ], inner_regions=[InnerRegionConf('1', Box((.5, .5, .5), (1, 1, 1)))], output_file=OutputFileConf(), boundary_conditions=BoundaryConditionsConf(), particle_interaction_model=ParticleInteractionModelConf( 'noninteracting'), external_fields=[]) sim = conf.make() Runner(sim).start() assert [len(a.ids) for a in sim.particle_arrays] == [4]
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')))
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
def test_large_grid(solver_, backend_): try: configure_application(solver_, backend_) c = Config(TimeGridConf(1, 1, 1), SpatialMeshConf(100, 1), inner_regions=[InnerRegionConf('tube', Tube((50, 50, 10), (50, 50, 12), 10, 90), 10)]) r = Runner(c.make()) r.eval_and_write_fields_without_particles() assert r.simulation.potential.data.mean() >= 0 assert r.simulation.potential.data.mean() <= 10 assert abs(r.simulation.potential.data.max() - 10) < 0.01 assert abs(r.simulation.potential.data.min()) < 0.01 finally: inject.clear()
def test_init_from_config(self): efconf = Config() parser = ConfigParser() parser.read_string(efconf.export_to_string()) sim = Config.from_configparser(parser).make() assert sim.time_grid == TimeGrid(100, 1, 10) assert sim.spat_mesh == SpatialMesh.do_init((10, 10, 10), (1, 1, 1), BoundaryConditionsConf(0)) assert sim.inner_regions == [] assert type(sim._field_solver) == FieldSolver assert sim.particle_sources == [] assert sim.electric_fields == [] assert sim.magnetic_fields == [] assert sim.particle_interaction_model == ParticleInteractionModel("PIC") assert sim._output_filename_prefix == "out_" assert sim._output_filename_suffix == ".h5"
def test_cube_of_gas_with_hole(self, model, monkeypatch, tmpdir): monkeypatch.chdir(tmpdir) Config(TimeGridConf(1.0, save_step=.5, step=.1), SpatialMeshConf((10, 10, 10), (1, 1, 1)), [ParticleSourceConf('gas', Box(size=(10, 10, 10)), 50, 0, np.zeros(3), 300)], [InnerRegionConf('hole', Box(origin=(4, 4, 4), size=(2, 2, 2)))], particle_interaction_model=ParticleInteractionModelConf(model) ).make().start_pic_simulation()
def test_id_generation(self, monkeypatch, tmpdir): monkeypatch.chdir(tmpdir) conf = Config(TimeGridConf(0.001, save_step=.0005, step=0.0001), SpatialMeshConf((10, 10, 10), (1, 1, 1)), sources=[ParticleSourceConf('gas', Box((4, 4, 4), size=(1, 1, 1)), 50, 0, np.zeros(3), 0.00), ParticleSourceConf('gas2', Box((5, 5, 5), size=(1, 1, 1)), 50, 0, np.zeros(3), 0.00)], particle_interaction_model=ParticleInteractionModelConf('noninteracting') ) assert len(conf.sources) == 2 sim = conf.make() assert len(sim.particle_sources) == 2 assert len(sim.particle_arrays) == 0 sim.start_pic_simulation() assert len(sim.particle_sources) == 2 assert len(sim.particle_arrays) == 2 assert_array_equal(sim.particle_arrays[0].ids, range(50)) assert_array_equal(sim.particle_arrays[1].ids, range(50, 100))
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)
def test_main(mocker, capsys, tmpdir, monkeypatch): monkeypatch.chdir(tmpdir) config = tmpdir.join("test_main.conf") Config(time_grid=TimeGridConf(10, 5, 1)).export_to_fname("test_main.conf") mocker.patch("sys.argv", ["main.py", str(config)]) main() out, err = capsys.readouterr() assert err == "" assert out == f"""Config file is: {config}
def test_cube_of_gas(self, model, backend_and_solver): sim = Config(TimeGridConf(1.0, save_step=.5, step=.1), SpatialMeshConf((10, 10, 10), (1, 1, 1)), [ ParticleSourceConf('gas', Box(size=(10, 10, 10)), 50, 0, np.zeros(3), 300) ], particle_interaction_model=ParticleInteractionModelConf( model)).make() Runner(sim).start()
def read_conf(parser, prefix, suffix, format_): conf = Config.from_configparser(parser) if prefix: conf.output_file.prefix = prefix if suffix: conf.output_file.suffix = suffix conf.output_file.format_ = format_ print(conf) return conf
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
def test_id_generation(self, backend_and_solver): conf = Config(TimeGridConf(0.001, save_step=.0005, step=0.0001), SpatialMeshConf((10, 10, 10), (1, 1, 1)), sources=[ ParticleSourceConf('gas', Box((4, 4, 4), size=(1, 1, 1)), 50, 0, np.zeros(3), 0.00), ParticleSourceConf('gas2', Box((5, 5, 5), size=(1, 1, 1)), 50, 0, np.zeros(3), 0.00) ], particle_interaction_model=ParticleInteractionModelConf( 'noninteracting')) assert len(conf.sources) == 2 sim = conf.make() assert len(sim.particle_sources) == 2 assert len(sim.particle_arrays) == 0 Runner(sim).start() assert len(sim.particle_sources) == 2 assert len(sim.particle_arrays) == 1 sim.particle_arrays[0].xp.testing.assert_array_equal( sim.particle_arrays[0].ids, range(100))
def test_numbered(self, capsys, mocker): mocker.patch('h5py.File') sim = Config().make() writer = OutputWriterNumberedH5('a_', '.b') mocker.patch.object(writer, 'do_write') assert writer.format_filename('test') == 'a_test.b' assert writer.get_filename(sim) == '0000000' writer.write(sim) h5py.File.assert_called_once_with('a_0000000.b', 'w') writer.do_write.assert_called_once() out, err = capsys.readouterr() assert err == "" assert out == "Writing to file a_0000000.b\n"
def test_guess(tmpdir): h5 = tmpdir.join("test.h5") h5py.File(h5, 'w') assert guess_input_type(h5) == (False, h5) conf = tmpdir.join("test.conf") Config().export_to_fname(conf) p = ConfigParser() p.read_string(Config().export_to_string()) assert guess_input_type(conf) == (True, p) with raises(ArgumentTypeError): guess_input_type(tmpdir.join('missing.txt')) text = tmpdir.join('some.txt') text.write('eowjfm ievmiefraivuenwaeofiunapewovjfiajief asdwouhd \n adfaef afef') with raises(ArgumentTypeError): guess_input_type(text) data = tmpdir.join('some.bin') data.write(bytes(range(255)), 'wb') with raises(ArgumentTypeError): guess_input_type(data)
def test_main(mocker, capsys, tmpdir, monkeypatch, solver_, backend_): inject.clear() monkeypatch.chdir(tmpdir) config = tmpdir.join("test_main.conf") Config(time_grid=TimeGridConf(10, 5, 1)).export_to_fname("test_main.conf") argv = ["main.py", str(config)] if solver_ != ' ': argv += ["--solver", solver_] if backend_ != ' ': argv += ["--backend", backend_] mocker.patch("sys.argv", argv) main() inject.clear() out, err = capsys.readouterr() assert err == "" assert out == f"""Trying to guess input file type: {config} ### Config: time_grid = TimeGridConf(total=10.0, save_step=5.0, step=1.0) spatial_mesh = SpatialMeshConf(size=array([10., 10., 10.]), step=array([1., 1., 1.])) sources = [] inner_regions = [] output_file = OutputFileConf(prefix='out_', suffix='.h5', format_='cpp') boundary_conditions = BoundaryConditionsConf(right=0.0, left=0.0, bottom=0.0, top=0.0, near=0.0, far=0.0) particle_interaction_model = ParticleInteractionModelConf(model='PIC') external_fields = [] Writing initial fields to file Writing to file out_fieldsWithoutParticles.h5 Writing step 0 to file Writing to file out_0000000.h5 \rTime step from 0 to 1 of 10\rTime step from 1 to 2 of 10\rTime step from 2 to 3 of 10\rTime step from 3 to 4 of 10\rTime step from 4 to 5 of 10 Writing step 5 to file Writing to file out_0000005.h5 \rTime step from 5 to 6 of 10\rTime step from 6 to 7 of 10\rTime step from 7 to 8 of 10\rTime step from 8 to 9 of 10\rTime step from 9 to 10 of 10 Writing step 10 to file Writing to file out_0000010.h5 """ argv = ["main.py", "out_0000005.h5"] if solver_ != ' ': argv += ["--solver", solver_] if backend_ != ' ': argv += ["--backend", backend_] mocker.patch("sys.argv", argv) main() inject.clear() out, err = capsys.readouterr() assert err == "" assert out == f"""Trying to guess input file type: out_0000005.h5
def construct_domain(config_or_h5_file): extension = config_or_h5_file[config_or_h5_file.rfind(".") + 1:] if extension == "h5": with h5py.File(config_or_h5_file, 'r') as h5file: filename_prefix, filename_suffix = \ extract_filename_prefix_and_suffix_from_h5filename(config_or_h5_file) dom = Simulation.init_from_h5(h5file, filename_prefix, filename_suffix) continue_from_h5 = True else: conf = configparser.ConfigParser() conf.read(config_or_h5_file) echo_config(config_or_h5_file, conf) dom = Config.from_configparser(conf).make() continue_from_h5 = False return dom, continue_from_h5
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")))
def test_is_trivial(backend): assert BoundaryConditionsConf().is_the_same_on_all_boundaries assert BoundaryConditionsConf(3.14).is_the_same_on_all_boundaries assert not BoundaryConditionsConf(*range(6)).is_the_same_on_all_boundaries assert not BoundaryConditionsConf(-1, 1, 1, 1, 1, 1).is_the_same_on_all_boundaries assert Config().is_trivial() assert Config(boundary_conditions=BoundaryConditionsConf(1)).is_trivial() assert not Config(boundary_conditions=BoundaryConditionsConf( 1, 1, 1, 2, 1, 1)).is_trivial() assert Config( inner_regions=[InnerRegionConf(), InnerRegionConf()]).is_trivial() assert Config(inner_regions=[ InnerRegionConf(potential=-2), InnerRegionConf(potential=-2) ], boundary_conditions=BoundaryConditionsConf(-2)).is_trivial() assert not Config(inner_regions=[InnerRegionConf( potential=1)]).is_trivial() assert not Config(inner_regions=[ InnerRegionConf(potential=1), InnerRegionConf(potential=0) ]).is_trivial()
def test_guess_stdin(tmpdir, monkeypatch): monkeypatch.setattr('sys.stdin', StringIO(Config().export_to_string())) p = ConfigParser() p.read_string(Config().export_to_string()) assert guess_input_type('-') == (True, p)
def test_potentials(): assert Config().get_potentials() == [0., 0., 0., 0., 0., 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)
def test_example_conf(fname, tmpdir, monkeypatch, backend_and_solver): sim = Config.from_fname(fname).make() monkeypatch.chdir(tmpdir) Runner(sim).start()