コード例 #1
0
ファイル: trajectory.py プロジェクト: clonker/readdy
 def __init__(self, filename, name=""):
     """
     attempts to open the given trajectory
     :param filename: the file name
     :param name: the trajectory name inside the file, as given in the simulation
     """
     assert _os.path.exists(
         filename), "The file '{}' did not exist!".format(filename)
     self._filename = filename
     self._name = name
     self._diffusion_constants = _io_utils.get_diffusion_constants(filename)
     self._particle_types = _io_utils.get_particle_types(filename)
     self._reactions = []
     self._inverse_types_map = {
         v: k
         for k, v in self.particle_types.items()
     }
     self._general = GeneralInformation(filename)
     for _, reaction in _io_utils.get_reactions(filename).items():
         info = ReactionInfo(reaction["name"], reaction["id"],
                             reaction["n_educts"], reaction["n_products"],
                             reaction["rate"], reaction["educt_distance"],
                             reaction["product_distance"],
                             reaction["educt_types"],
                             reaction["product_types"],
                             self._inverse_types_map)
         self._reactions.append(info)
コード例 #2
0
ファイル: test_watch.py プロジェクト: readdy/readdyviewer
def test_polymer_chain():
    fname = '/home/mho/Development/readdy/readdy/wrappers/python/src/python/readdy/examples/out.h5'
    config = rv.Configuration()
    p_types = ioutils.get_particle_types(fname)
    config.colors[p_types['Topology A']] = rv.Color(255. / 255., 153. / 255.,
                                                    0.)
    config.radii[p_types['Topology A']] = .5
    config.colors[p_types['B']] = rv.Color(51. / 255., 153. / 255.,
                                           255. / 255.)
    config.radii[p_types['B']] = .5
    config.stride = 1
    r = TrajectoryReader(fname)
    items = r[:]
    n_frames = len(items)
    print("n_frames = %s" % n_frames)
    n_particles_per_frame = np.zeros((n_frames))
    for idx, item in enumerate(items):
        n_particles_per_frame[idx] = len(item)
    max_n_particles = int(np.amax(n_particles_per_frame, 0))
    positions = np.zeros((n_frames, max_n_particles, 3), dtype=np.float64)
    types = np.zeros((n_frames, max_n_particles), dtype=np.uint)
    ids = np.zeros((n_frames, max_n_particles), dtype=np.ulonglong)
    chaintype = -1
    for t, frame in enumerate(items):
        for p, entry in enumerate(frame):
            positions[t, p, 0:3] = entry.position
            types[t, p] = entry.type_id
            ids[t, p] = entry.id
            chaintype = entry.type_id
    rv.watch_npy(positions, types, ids, n_particles_per_frame, config)
コード例 #3
0
    def test_reaction_info(self):
        p_types = ioutils.get_particle_types(self.fname)
        reactions = ioutils.get_reactions(self.fname)
        self.assertEqual(len(reactions), 3)

        self.assertTrue("mylabel" in reactions)
        mylabel = reactions["mylabel"]
        self.assertEqual(mylabel["n_educts"], 1)
        self.assertEqual(mylabel["n_products"], 1)
        self.assertAlmostEqual(mylabel["rate"], 0.00001)
        self.assertEqual(mylabel["educt_types"][0], p_types["A"])
        self.assertEqual(mylabel["product_types"][0], p_types["B"])

        self.assertTrue("A->B" in reactions)
        atob = reactions["A->B"]
        self.assertEqual(atob["n_educts"], 1)
        self.assertEqual(atob["n_products"], 1)
        self.assertEqual(atob["rate"], 1.)
        self.assertEqual(atob["educt_types"][0], p_types["A"])
        self.assertEqual(atob["product_types"][0], p_types["B"])

        self.assertTrue("B+C->A" in reactions)
        fusion = reactions["B+C->A"]
        self.assertEqual(fusion["n_educts"], 2)
        self.assertEqual(fusion["n_products"], 1)
        self.assertAlmostEqual(fusion["rate"], 0.4)
        self.assertAlmostEqual(fusion["educt_distance"], 0.2)
        correct_educts = (fusion["educt_types"][0] == p_types["B"]
                          and fusion["educt_types"][1] == p_types["C"])
        correct_educts = correct_educts or (
            fusion["educt_types"][1] == p_types["B"]
            and fusion["educt_types"][0] == p_types["C"])
        self.assertTrue(correct_educts)
        self.assertEqual(fusion["product_types"][0], p_types["A"])
コード例 #4
0
ファイル: test_io_utils.py プロジェクト: chrisfroe/readdy
    def test_reaction_info(self):
        p_types = ioutils.get_particle_types(self.fname)
        reactions = ioutils.get_reactions(self.fname)
        self.assertEqual(len(reactions), 3)

        self.assertTrue("mylabel" in reactions)
        mylabel = reactions["mylabel"]
        self.assertEqual(mylabel["n_educts"], 1)
        self.assertEqual(mylabel["n_products"], 1)
        self.assertAlmostEqual(mylabel["rate"], 0.00001)
        self.assertEqual(mylabel["educt_types"][0], p_types["A"])
        self.assertEqual(mylabel["product_types"][0], p_types["B"])

        self.assertTrue("A->B" in reactions)
        atob = reactions["A->B"]
        self.assertEqual(atob["n_educts"], 1)
        self.assertEqual(atob["n_products"], 1)
        self.assertEqual(atob["rate"], 1.)
        self.assertEqual(atob["educt_types"][0], p_types["A"])
        self.assertEqual(atob["product_types"][0], p_types["B"])

        self.assertTrue("B+C->A" in reactions)
        fusion = reactions["B+C->A"]
        self.assertEqual(fusion["n_educts"], 2)
        self.assertEqual(fusion["n_products"], 1)
        self.assertAlmostEqual(fusion["rate"], 0.4)
        self.assertAlmostEqual(fusion["educt_distance"], 0.2)
        correct_educts = (fusion["educt_types"][0] == p_types["B"] and fusion["educt_types"][1] == p_types["C"])
        correct_educts = correct_educts or (fusion["educt_types"][1] == p_types["B"] and fusion["educt_types"][0] == p_types["C"])
        self.assertTrue(correct_educts)
        self.assertEqual(fusion["product_types"][0], p_types["A"])
コード例 #5
0
    def load_particles_from_checkpoint(self, file_name, n=None):
        """
        Adds particles to the simulation as contained in the n-th checkpoint of a trajectory file.
        :param file_name: the trajectory file
        :param n: if n is None, retrieve configuration from latest checkpoint, otherwise use 'n-th' checkpoint, n >= 0
        """
        import numpy as _np
        from readdy import Trajectory
        from readdy.api.trajectory import _CKPT
        from readdy.util.io_utils import get_particle_types
        checkpoints = self.list_checkpoints(file_name)
        if n is None:
            n = len(checkpoints) - 1
        else:
            assert n < len(
                checkpoints
            ), f"n={n} is out of bounds, only have {len(checkpoints)} checkpoints"
        assert n >= 0, f"n must be positive but was {n}"

        # group particle types by flavor (NORMAL, TOPOLOGY)
        ptypes = get_particle_types(filename=file_name)
        normal_types = []
        topology_types = []
        for t in ptypes.values():
            if t['flavor'] == 'TOPOLOGY':
                topology_types.append(t['type_id'])
            if t['flavor'] == 'NORMAL':
                normal_types.append(t['type_id'])

        # load frame into memory
        traj = Trajectory(file_name)
        n_particles_per_frame, positions, types, ids = traj.to_numpy(
            start=n, stop=n + 1, name=_CKPT.POSITIONS_CKPT)

        # add particles with flavor NORMAL
        for normal_type in normal_types:
            tixs = _np.argwhere(types[0] == normal_type)
            pos = positions[0][tixs].squeeze()
            if len(pos) > 0:
                self.add_particles(traj.species_name(normal_type),
                                   _np.atleast_2d(pos))

        # add topologies
        time, topology_records = traj.read_observable_topologies(
            start=n, stop=n + 1, data_set_name=_CKPT.TOPOLOGY_CKPT)
        assert len(topology_records) == 1
        for topology in topology_records[0]:
            particle_types = [
                traj.species_name(types[0, i]) for i in topology.particles
            ]
            pos = _np.atleast_2d(
                _np.array([positions[0, i] for i in topology.particles]))
            top = self.add_topology(traj.topology_type_name(topology.type),
                                    particle_types, pos)
            for e in topology.edges:
                top.graph.add_edge(e[0], e[1])
コード例 #6
0
ファイル: test_io_utils.py プロジェクト: chrisfroe/readdy
    def test_particle_types_info(self):
        p_types = ioutils.get_particle_types(self.fname)
        # assuming that type ids are in accordance to order of registration
        np.testing.assert_equal(p_types["A"], 0)
        np.testing.assert_equal(p_types["B"], 1)
        np.testing.assert_equal(p_types["C"], 2)

        diff_constants = ioutils.get_diffusion_constants(self.fname)
        np.testing.assert_equal(diff_constants["A"], 1.)
        np.testing.assert_equal(diff_constants["B"], 2.)
        np.testing.assert_equal(diff_constants["C"], 3.)
コード例 #7
0
    def test_particle_types_info(self):
        p_types = ioutils.get_particle_types(self.fname)
        # assuming that type ids are in accordance to order of registration
        np.testing.assert_equal(p_types["A"], 0)
        np.testing.assert_equal(p_types["B"], 1)
        np.testing.assert_equal(p_types["C"], 2)

        diff_constants = ioutils.get_diffusion_constants(self.fname)
        np.testing.assert_equal(diff_constants["A"], 1.)
        np.testing.assert_equal(diff_constants["B"], 2.)
        np.testing.assert_equal(diff_constants["C"], 3.)
コード例 #8
0
ファイル: test_io_utils.py プロジェクト: marscher/readdy
 def test_reaction_info_order2(self):
     p_types = ioutils.get_particle_types(self.fname)
     reactions_o2 = ioutils.get_reactions_order2(self.fname)
     fusion = get_item("B+C->A", reactions_o2)
     np.testing.assert_equal(fusion["n_educts"], 2)
     np.testing.assert_equal(fusion["n_products"], 1)
     np.testing.assert_equal(fusion["rate"], 0.4)
     np.testing.assert_equal(fusion["educt_distance"], 0.2)
     correct_educts = (fusion["educt_types"][0] == p_types["B"] and fusion["educt_types"][1] == p_types["C"])
     correct_educts = correct_educts or (fusion["educt_types"][1] == p_types["B"] and fusion["educt_types"][0] == p_types["C"])
     np.testing.assert_(correct_educts)
     np.testing.assert_equal(fusion["product_types"][0], p_types["A"])
コード例 #9
0
    def test_particles_observable(self):
        fname = os.path.join(self.dir, "test_observables_particles.h5")
        context = Context()
        context.box_size = [13., 13., 13.]
        context.particle_types.add("A", .1)
        context.particle_types.add("B", .1)
        sim = Simulation("SingleCPU", context)
        sim.add_particle("A", common.Vec(0, 0, 0))
        sim.add_particle("B", common.Vec(0, 0, 0))
        # every time step, add one particle
        sim.register_observable_n_particles(
            1, ["A"],
            lambda n: sim.add_particle("A", common.Vec(1.5, 2.5, 3.5)))
        handle = sim.register_observable_particles(1)
        n_timesteps = 19
        with closing(io.File.create(fname)) as f:
            handle.enable_write_to_file(f, u"particles", int(3))
            loop = sim.create_loop(0)
            loop.write_config_to_file(f)
            loop.run(n_timesteps)
            handle.flush()

        from readdy.util.io_utils import get_particle_types

        particle_types = get_particle_types(fname)

        with h5py.File(fname, "r") as f2:

            types = f2["readdy/observables/particles/types"][:]
            ids = f2["readdy/observables/particles/ids"][:]
            positions = f2["readdy/observables/particles/positions"][:]
            for t in range(n_timesteps):
                np.testing.assert_equal(len(types[t]), t + 3)
                np.testing.assert_equal(len(ids[t]), t + 3)
                np.testing.assert_equal(len(positions[t]), t + 3)
                np.testing.assert_equal(types[t][0],
                                        particle_types["A"]["type_id"])
                np.testing.assert_equal(positions[t][0][0], 0)
                np.testing.assert_equal(positions[t][0][1], 0)
                np.testing.assert_equal(positions[t][0][2], 0)
                np.testing.assert_equal(positions[t][1][0], 0)
                np.testing.assert_equal(positions[t][1][1], 0)
                np.testing.assert_equal(positions[t][1][2], 0)
                np.testing.assert_equal(types[t][1],
                                        particle_types["B"]["type_id"])
                for others in range(2, len(types[t])):
                    np.testing.assert_equal(types[t][others],
                                            particle_types["A"]["type_id"])
                    np.testing.assert_equal(positions[t][others][0], 1.5)
                    np.testing.assert_equal(positions[t][others][1], 2.5)
                    np.testing.assert_equal(positions[t][others][2], 3.5)
コード例 #10
0
ファイル: test_io_utils.py プロジェクト: marscher/readdy
 def test_reaction_info_order1(self):
     p_types = ioutils.get_particle_types(self.fname)
     reactions_o1 = ioutils.get_reactions_order1(self.fname)
     mylabel = get_item("mylabel", reactions_o1)
     np.testing.assert_equal(mylabel["n_educts"], 1)
     np.testing.assert_equal(mylabel["n_products"], 1)
     np.testing.assert_equal(mylabel["rate"], 0.00001)
     np.testing.assert_equal(mylabel["educt_types"][0], p_types["A"])
     np.testing.assert_equal(mylabel["product_types"][0], p_types["B"])
     atob = get_item("A->B", reactions_o1)
     np.testing.assert_equal(atob["n_educts"], 1)
     np.testing.assert_equal(atob["n_products"], 1)
     np.testing.assert_equal(atob["rate"], 1.)
     np.testing.assert_equal(atob["educt_types"][0], p_types["A"])
     np.testing.assert_equal(atob["product_types"][0], p_types["B"])
コード例 #11
0
ファイル: simulation.py プロジェクト: readdy/readdy
    def load_particles_from_checkpoint(self, file_name, n=None):
        """
        Adds particles to the simulation as contained in the n-th checkpoint of a trajectory file.
        :param file_name: the trajectory file
        :param n: if n is None, retrieve configuration from latest checkpoint, otherwise use 'n-th' checkpoint, n >= 0
        """
        import numpy as _np
        from readdy import Trajectory
        from readdy.api.trajectory import _CKPT
        from readdy.util.io_utils import get_particle_types
        checkpoints = self.list_checkpoints(file_name)
        if n is None:
            n = len(checkpoints)-1
        else:
            assert n < len(checkpoints), f"n={n} is out of bounds, only have {len(checkpoints)} checkpoints"
        assert n >= 0, f"n must be positive but was {n}"

        # group particle types by flavor (NORMAL, TOPOLOGY)
        ptypes = get_particle_types(filename=file_name)
        normal_types = []
        topology_types = []
        for t in ptypes.values():
            if t['flavor'] == 'TOPOLOGY':
                topology_types.append(t['type_id'])
            if t['flavor'] == 'NORMAL':
                normal_types.append(t['type_id'])

        # load frame into memory
        traj = Trajectory(file_name)
        n_particles_per_frame, positions, types, ids = traj.to_numpy(start=n, stop=n+1, name=_CKPT.POSITIONS_CKPT)

        # add particles with flavor NORMAL
        for normal_type in normal_types:
            tixs = _np.argwhere(types[0] == normal_type)
            pos = positions[0][tixs].squeeze()
            if len(pos) > 0:
                self.add_particles(traj.species_name(normal_type), _np.atleast_2d(pos))

        # add topologies
        time, topology_records = traj.read_observable_topologies(start=n, stop=n+1, data_set_name=_CKPT.TOPOLOGY_CKPT)
        assert len(topology_records) == 1
        for topology in topology_records[0]:
            particle_types = [traj.species_name(types[0, i]) for i in topology.particles]
            pos = _np.atleast_2d(_np.array([positions[0, i] for i in topology.particles]))
            top = self.add_topology(traj.topology_type_name(topology.type), particle_types, pos)
            for e in topology.edges:
                top.graph.add_edge(e[0], e[1])
コード例 #12
0
ファイル: test_observables_io.py プロジェクト: readdy/readdy
    def test_particles_observable(self):
        fname = os.path.join(self.dir, "test_observables_particles.h5")
        sim = Simulation("SingleCPU")
        sim.context.box_size = [13.,13.,13.]
        sim.context.particle_types.add("A", .1)
        sim.context.particle_types.add("B", .1)
        sim.add_particle("A", common.Vec(0, 0, 0))
        sim.add_particle("B", common.Vec(0, 0, 0))
        # every time step, add one particle
        sim.register_observable_n_particles(1, ["A"], lambda n: sim.add_particle("A", common.Vec(1.5, 2.5, 3.5)))
        handle = sim.register_observable_particles(1)
        n_timesteps = 19
        with closing(io.File.create(fname)) as f:
            handle.enable_write_to_file(f, u"particles", int(3))
            loop = sim.create_loop(0)
            loop.write_config_to_file(f)
            loop.run(n_timesteps)
            handle.flush()

        from readdy.util.io_utils import get_particle_types

        particle_types = get_particle_types(fname)

        with h5py.File(fname, "r") as f2:

            types = f2["readdy/observables/particles/types"][:]
            ids = f2["readdy/observables/particles/ids"][:]
            positions = f2["readdy/observables/particles/positions"][:]
            for t in range(n_timesteps):
                np.testing.assert_equal(len(types[t]), t + 3)
                np.testing.assert_equal(len(ids[t]), t + 3)
                np.testing.assert_equal(len(positions[t]), t + 3)
                np.testing.assert_equal(types[t][0], particle_types["A"]["type_id"])
                np.testing.assert_equal(positions[t][0][0], 0)
                np.testing.assert_equal(positions[t][0][1], 0)
                np.testing.assert_equal(positions[t][0][2], 0)
                np.testing.assert_equal(positions[t][1][0], 0)
                np.testing.assert_equal(positions[t][1][1], 0)
                np.testing.assert_equal(positions[t][1][2], 0)
                np.testing.assert_equal(types[t][1], particle_types["B"]["type_id"])
                for others in range(2, len(types[t])):
                    np.testing.assert_equal(types[t][others], particle_types["A"]["type_id"])
                    np.testing.assert_equal(positions[t][others][0], 1.5)
                    np.testing.assert_equal(positions[t][others][1], 2.5)
                    np.testing.assert_equal(positions[t][others][2], 3.5)
コード例 #13
0
ファイル: test.py プロジェクト: readdy/readdyviewer
def get_config_brighter(outfile):
    import readdy.util.io_utils as ioutils
    config = readdyviewer.Configuration()
    p_types = ioutils.get_particle_types(outfile)
    config.colors[p_types['ReaDDy_inactive']] = readdyviewer.Color(
        0. / 255., 0. / 255., 0. / 255.)
    config.radii[p_types['ReaDDy_inactive']] = 1.
    config.colors[p_types['ReaDDy_active']] = readdyviewer.Color(
        255. / 255., 50. / 255., 0. / 255.)
    config.radii[p_types['ReaDDy_active']] = 1.2
    config.colors[p_types['Activator']] = readdyviewer.Color(
        200. / 255., 200. / 255., 255. / 255.)
    config.radii[p_types['Activator']] = .9
    config.colors[p_types['Activator_predator']] = readdyviewer.Color(
        130. / 255., 170. / 255., 155. / 255.)
    config.radii[p_types['Activator_predator']] = .4
    config.stride = 1
    config.clearcolor = readdyviewer.Color(15. / 255., 15. / 255., 15. / 255.)
    return config
コード例 #14
0
ファイル: trajectory.py プロジェクト: chrisfroe/readdy
 def __init__(self, filename, name=""):
     """
     attempts to open the given trajectory
     :param filename: the file name
     :param name: the trajectory name inside the file, as given in the simulation
     """
     assert _os.path.exists(filename), "The file '{}' did not exist!".format(filename)
     self._filename = filename
     self._name = name
     self._diffusion_constants = _io_utils.get_diffusion_constants(filename)
     self._particle_types = _io_utils.get_particle_types(filename)
     self._reactions = []
     self._inverse_types_map = {v: k for k, v in self.particle_types.items()}
     self._general = GeneralInformation(filename)
     for _, reaction in _io_utils.get_reactions(filename).items():
         info = ReactionInfo(reaction["name"], reaction["id"], reaction["n_educts"],
                             reaction["n_products"], reaction["rate"], reaction["educt_distance"],
                             reaction["product_distance"], reaction["educt_types"], reaction["product_types"],
                             self._inverse_types_map)
         self._reactions.append(info)
コード例 #15
0
ファイル: test.py プロジェクト: readdy/readdyviewer
def get_config_rgb_light_gray(outfile):
    import readdy.util.io_utils as ioutils
    config = readdyviewer.Configuration()
    p_types = ioutils.get_particle_types(outfile)
    config.colors[p_types['ReaDDy_inactive']] = readdyviewer.Color(
        128. / 255., 0. / 255., 0. / 255.)
    config.radii[p_types['ReaDDy_inactive']] = 1.
    config.colors[p_types['ReaDDy_active']] = readdyviewer.Color(
        230. / 255., 9. / 255., 9. / 255.)
    config.radii[p_types['ReaDDy_active']] = 1.2
    config.colors[p_types['Activator']] = readdyviewer.Color(
        9. / 255., 230. / 255., 230. / 255.)
    config.radii[p_types['Activator']] = .9
    config.colors[p_types['Activator_predator']] = readdyviewer.Color(
        120. / 255., 230. / 255., 9. / 255.)
    config.radii[p_types['Activator_predator']] = .4
    config.stride = 1
    config.clearcolor = readdyviewer.Color(
        240. / 255., 240. / 255., 240. /
        255.)  # readdyviewer.Color(253. / 255., 246. / 255., 227. / 255.)
    return config
コード例 #16
0
ファイル: test.py プロジェクト: readdy/readdyviewer
def get_config_solarized_light(outfile):
    import readdy.util.io_utils as ioutils
    config = readdyviewer.Configuration()
    p_types = ioutils.get_particle_types(outfile)
    config.colors[p_types['ReaDDy_inactive']] = readdyviewer.Color(
        128. / 255., 0. / 255., 0. / 255.)
    config.radii[p_types['ReaDDy_inactive']] = 1.
    config.colors[p_types['ReaDDy_active']] = readdyviewer.Color(
        255. / 255., 50. / 255., 47. / 255.)
    config.radii[p_types['ReaDDy_active']] = 1.2
    config.colors[p_types['Activator']] = readdyviewer.Color(
        139. / 255., 210. / 255., 255. / 255.)
    config.radii[p_types['Activator']] = .9
    config.colors[p_types['Activator_predator']] = readdyviewer.Color(
        181. / 255., 137. / 255., 137. / 255.)
    config.radii[p_types['Activator_predator']] = .4
    config.stride = 1
    config.clearcolor = readdyviewer.Color(
        227. / 255., 227. / 255., 227. /
        255.)  # readdyviewer.Color(253. / 255., 246. / 255., 227. / 255.)
    return config
コード例 #17
0
    def test_reactions_observable(self):
        fname = os.path.join(self.dir, "test_observables_particle_reactions.h5")
        sim = Simulation("CPU")
        sim.context.box_size = [10.,10.,10.]
        sim.context.particle_types.add("A", .0)
        sim.context.particle_types.add("B", .0)
        sim.context.particle_types.add("C", .0)
        sim.context.reactions.add_conversion("mylabel", "A", "B", .00001)
        sim.context.reactions.add_conversion("A->B", "A", "B", 1.)
        sim.context.reactions.add_fusion("B+C->A", "B", "C", "A", 1.0, 1.0, .5, .5)
        sim.add_particle("A", common.Vec(0, 0, 0))
        sim.add_particle("B", common.Vec(1.0, 1.0, 1.0))
        sim.add_particle("C", common.Vec(1.1, 1.0, 1.0))

        n_timesteps = 1

        handle = sim.register_observable_reactions(1)
        with closing(io.File.create(fname)) as f:
            handle.enable_write_to_file(f, u"reactions", int(3))
            loop = sim.create_loop(1)
            loop.write_config_to_file(f)
            loop.run(n_timesteps)

        type_str_to_id = {k: x["type_id"] for k, x in ioutils.get_particle_types(fname).items()}

        with h5py.File(fname, "r") as f2:
            data = f2["readdy/observables/reactions"]
            time_series = f2["readdy/observables/reactions/time"]
            np.testing.assert_equal(time_series, np.array(range(0, n_timesteps+1)))

            def get_item(name, collection):
                return next(x for x in collection if x["name"] == name)

            import readdy.util.io_utils as io_utils
            reactions = io_utils.get_reactions(fname)

            mylabel_reaction = get_item("mylabel", reactions.values())
            np.testing.assert_allclose(mylabel_reaction["rate"], .00001)
            np.testing.assert_equal(mylabel_reaction["n_educts"], 1)
            np.testing.assert_equal(mylabel_reaction["n_products"], 1)
            np.testing.assert_equal(mylabel_reaction["educt_types"], [type_str_to_id["A"], 0])
            np.testing.assert_equal(mylabel_reaction["product_types"], [type_str_to_id["B"], 0])
            atob_reaction = get_item("A->B", reactions.values())
            np.testing.assert_equal(atob_reaction["rate"], 1.)
            np.testing.assert_equal(atob_reaction["n_educts"], 1)
            np.testing.assert_equal(atob_reaction["n_products"], 1)
            np.testing.assert_equal(mylabel_reaction["educt_types"], [type_str_to_id["A"], 0])
            np.testing.assert_equal(mylabel_reaction["product_types"], [type_str_to_id["B"], 0])

            fusion_reaction = get_item("B+C->A", reactions.values())
            np.testing.assert_equal(fusion_reaction["rate"], 1.)
            np.testing.assert_equal(fusion_reaction["educt_distance"], 1.)
            np.testing.assert_equal(fusion_reaction["n_educts"], 2)
            np.testing.assert_equal(fusion_reaction["n_products"], 1)
            np.testing.assert_equal(fusion_reaction["educt_types"], [type_str_to_id["B"], type_str_to_id["C"]])
            np.testing.assert_equal(fusion_reaction["product_types"], [type_str_to_id["A"], 0])

            records = data["records"][:]
            np.testing.assert_equal(len(records), 2)
            # records of 1st time step
            for record in records[1]:
                np.testing.assert_equal(record["reaction_type"] == 0 or record["reaction_type"] == 1, True)
                if record["reaction_type"] == 0:
                    np.testing.assert_equal(record["position"], np.array([.0, .0, .0]))
                    np.testing.assert_equal(record["reaction_id"], atob_reaction["id"])
                elif record["reaction_type"] == 1:
                    # fusion
                    np.testing.assert_allclose(record["position"], np.array([1.05, 1.0, 1.0]))
                    np.testing.assert_equal(record["reaction_id"], fusion_reaction["id"])
コード例 #18
0
    def test_reactions_observable(self):
        common.set_logging_level("warn")
        fname = os.path.join(self.dir,
                             "test_observables_particle_reactions.h5")
        sim = Simulation()
        sim.set_kernel("CPU")
        sim.box_size = common.Vec(10, 10, 10)
        sim.register_particle_type("A", .0, 5.0)
        sim.register_particle_type("B", .0, 6.0)
        sim.register_particle_type("C", .0, 6.0)
        sim.register_reaction_conversion("mylabel", "A", "B", .00001)
        sim.register_reaction_conversion("A->B", "A", "B", 1.)
        sim.register_reaction_fusion("B+C->A", "B", "C", "A", 1.0, 1.0, .5, .5)
        sim.add_particle("A", common.Vec(0, 0, 0))
        sim.add_particle("B", common.Vec(1.0, 1.0, 1.0))
        sim.add_particle("C", common.Vec(1.1, 1.0, 1.0))

        n_timesteps = 1

        handle = sim.register_observable_reactions(1)
        with closing(
                io.File(fname, io.FileAction.CREATE,
                        io.FileFlag.OVERWRITE)) as f:
            handle.enable_write_to_file(f, u"reactions", int(3))
            sim.run_scheme_readdy(True).write_config_to_file(
                f).configure_and_run(n_timesteps, 1)

        type_str_to_id = ioutils.get_particle_types(fname)

        with h5py.File(fname, "r") as f2:
            data = f2["readdy/observables/reactions"]
            time_series = f2["readdy/observables/reactions/time"]
            np.testing.assert_equal(time_series,
                                    np.array(range(0, n_timesteps + 1)))

            def get_item(name, collection):
                return next(x for x in collection if x["name"] == name)

            order_1_reactions = data["registered_reactions/order1_reactions"]

            mylabel_reaction = get_item("mylabel", order_1_reactions)
            np.testing.assert_equal(mylabel_reaction["rate"], .00001)
            np.testing.assert_equal(mylabel_reaction["n_educts"], 1)
            np.testing.assert_equal(mylabel_reaction["n_products"], 1)
            np.testing.assert_equal(mylabel_reaction["educt_types"],
                                    [type_str_to_id["A"], 0])
            np.testing.assert_equal(mylabel_reaction["product_types"],
                                    [type_str_to_id["B"], 0])
            atob_reaction = get_item("A->B", order_1_reactions)
            np.testing.assert_equal(atob_reaction["rate"], 1.)
            np.testing.assert_equal(atob_reaction["n_educts"], 1)
            np.testing.assert_equal(atob_reaction["n_products"], 1)
            np.testing.assert_equal(mylabel_reaction["educt_types"],
                                    [type_str_to_id["A"], 0])
            np.testing.assert_equal(mylabel_reaction["product_types"],
                                    [type_str_to_id["B"], 0])

            order_2_reactions = data["registered_reactions/order2_reactions"]

            fusion_reaction = get_item("B+C->A", order_2_reactions)
            np.testing.assert_equal(fusion_reaction["rate"], 1.)
            np.testing.assert_equal(fusion_reaction["educt_distance"], 1.)
            np.testing.assert_equal(fusion_reaction["n_educts"], 2)
            np.testing.assert_equal(fusion_reaction["n_products"], 1)
            np.testing.assert_equal(fusion_reaction["educt_types"],
                                    [type_str_to_id["B"], type_str_to_id["C"]])
            np.testing.assert_equal(fusion_reaction["product_types"],
                                    [type_str_to_id["A"], 0])

            records = data["records"][:]
            np.testing.assert_equal(len(records), 2)
            # records of 1st time step
            for record in records[1]:
                np.testing.assert_equal(
                    record["reaction_type"] == 0
                    or record["reaction_type"] == 1, True)
                if record["reaction_type"] == 0:
                    np.testing.assert_equal(record["position"],
                                            np.array([.0, .0, .0]))
                    np.testing.assert_equal(record["reaction_index"], 1)
                elif record["reaction_type"] == 1:
                    # fusion
                    np.testing.assert_equal(record["position"],
                                            np.array([1.05, 1.0, 1.0]))
                    np.testing.assert_equal(record["reaction_index"], 0)

        common.set_logging_level("warn")