def test_initialization_with_cuds(self):
        # given
        points = [
            [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
        bonds = [[0, 1], [0, 3], [1, 3, 2]]
        point_temperature = [10., 20., 30., 40.]
        bond_temperature = [60., 80., 190., 5.]
        reference = Particles('test')

        # add particles
        particle_iter = (Particle(coordinates=point,
                                  data=DataContainer(TEMPERATURE=temp))
                         for temp, point in zip(point_temperature, points))
        point_uids = reference.add(particle_iter)

        # add bonds
        bond_iter = (Bond(particles=[point_uids[index] for index in indices],
                          data=DataContainer(TEMPERATURE=temp))
                     for temp, indices in zip(bond_temperature, bonds))
        bond_uids = reference.add(bond_iter)

        # when
        container = VTKParticles.from_particles(reference)

        # then
        number_of_particles = sum(1 for _ in container.iter(
            item_type=CUBA.PARTICLE))
        self.assertEqual(number_of_particles, len(point_uids))
        for expected in reference.iter(item_type=CUBA.PARTICLE):
            self.assertEqual(container.get(expected.uid), expected)
        number_of_bonds = sum(1 for _ in container.iter(item_type=CUBA.BOND))
        self.assertEqual(number_of_bonds, len(bond_uids))
        for expected in reference.iter(item_type=CUBA.BOND):
            self.assertEqual(container.get(expected.uid), expected)
示例#2
0
    def generate_cuds(self):
        pset1 = create_particles_with_id(restrict=[CUBA.VELOCITY])
        for p in pset1:
            p.data[CUBA.MATERIAL_TYPE] = 1

        pset2 = create_particles_with_id(restrict=[CUBA.VELOCITY])
        for p in pset2:
            p.data[CUBA.MATERIAL_TYPE] = 1

        ps1 = Particles('ps1')
        ps2 = Particles('ps2')

        ps1.add(pset1)
        ps2.add(pset2)

        c = CUDS()
        c.add([ps2])

        mat = api.Material()
        mat.data[CUBA.MASS] = 1.0
        c.add([mat])

        box = api.Box()
        c.add([box])

        return c
示例#3
0
    def test_add_named_dataset(self):
        ps = Particles('my particles')
        ps.add([Particle(), Particle()])
        c = CUDS()
        c.add([ps])

        self.assertEqual(c.get_by_name(ps.name), ps)
        self.assertRaises(ValueError, c.add, [ps])
示例#4
0
    def test_add_named_dataset(self):
        ps = Particles('my particles')
        ps.add([Particle(), Particle()])
        c = CUDS()
        c.add([ps])

        self.assertEqual(c.get_by_name(ps.name), ps)
        self.assertRaises(ValueError, c.add, [ps])
示例#5
0
    def test_remove_dataset(self):
        ps = Particles('my particles')
        ps.add([Particle(), Particle()])
        c = CUDS()
        c.add([ps])
        c.remove([ps.uid])

        self.assertRaises(KeyError, c.get, ps.uid)
示例#6
0
    def test_remove_dataset(self):
        ps = Particles('my particles')
        ps.add([Particle(), Particle()])
        c = CUDS()
        c.add([ps])
        c.remove([ps.uid])

        self.assertRaises(KeyError, c.get, ps.uid)
示例#7
0
    def test_iter_datasets_types(self):
        dataset = Particles('M1')
        dataset.add([Particle(), Particle()])
        c = CUDS()
        c.add([dataset])

        for ps in c.iter(item_type=CUBA.PARTICLES):
            self.assertIsInstance(ps, Particles)
            self.assertIn(ps, [dataset])
示例#8
0
    def test_iter_datasets_types(self):
        dataset = Particles('M1')
        dataset.add([Particle(),
                     Particle()])
        c = CUDS()
        c.add([dataset])

        for ps in c.iter(item_type=CUBA.PARTICLES):
            self.assertIsInstance(ps, Particles)
            self.assertIn(ps, [dataset])
def _create_pc(name):
    """ create particle container with a few particles """
    pc = Particles(name)

    data = DataContainer()
    data[CUBA.VELOCITY] = (0.0, 0.0, 0.0)

    pc.add([Particle(coordinates=(1.01, 1.01, 1.01), data=data),
            Particle(coordinates=(1.02, 1.02, 1.02), data=data)])

    return pc
示例#10
0
def generate_particles(smp_particles, smp_conditions, smp_materials, smp_pe):
    # Define the particle containers.
    particles = SParticles(name='particles')

    # Fill the data ( particle )
    data = DataContainer()
    data[CUBA.RADIUS] = 5e-5

    particles.add([
        SParticle(
            coordinates=(0.002, 0.004, 0.004),
            data=DataContainer(data),
        )
    ])

    material = api.Material(name='material_' + particles.name)
    materialData = material.data

    materialData[CUBA.DENSITY] = 950.0
    materialData[CUBA.YOUNG_MODULUS] = 35e9
    materialData[CUBA.POISSON_RATIO] = 0.20
    materialData[CUBA.FRICTION_COEFFICIENT] = 0.5773502691896257
    # materialData[CUBA.PARTICLE_COHESION] = 0.0
    materialData[CUBA.RESTITUTION_COEFFICIENT] = 0.02
    materialData[CUBA.ROLLING_FRICTION] = 0.01
    # materialData[CUBA.DEM_CONTINUUM_CONSTITUTIVE_LAW_NAME] = \
    # "DEM_KDEMFabric"
    # materialData[CUBA.DEM_DISCONTINUUM_CONSTITUTIVE_LAW_NAME] = \
    # "DEM_D_Hertz_viscous_Coulomb"
    # materialData[CUBA.CONTACT_TAU_ZERO] = 25
    # materialData[CUBA.CONTACT_SIGMA_MIN] = 5
    # materialData[CUBA.CONTACT_INTERNAL_FRICC] = 1

    material.data = materialData

    particlesData = particles.data
    particlesData[CUBA.MATERIAL] = material.name
    particles.data = particlesData

    # Pack the return objects
    smp_particles.append(particles)
    smp_materials.append(material)

    # Add the datasets that will be used by the wrapper
    smp_pe.data[CUBA.DATA_SET].append(particles.name)

    return {
        'datasets': smp_particles,
        'conditions': smp_conditions,
        'materials': smp_materials,
        'pe': smp_pe,
    }
示例#11
0
    def test_particles_snapshot(self):
        filename = self.filename
        coordinates = numpy.array([
            [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1],
            [2, 0, 0], [3, 0, 0], [3, 1, 0], [2, 1, 0],
            [2, 0, 1], [3, 0, 1], [3, 1, 1], [2, 1, 1]],
            'f')
        particles = Particles('test')
        particle_iter = (Particle(coordinates=point+3)
                         for point in coordinates)
        particles.add(particle_iter)

        snapshot(particles, filename)
        self.assertImageSavedWithContent(filename)
示例#12
0
    def test_iter_datasets_dimention(self):
        ps1 = Particles('M1')
        ps2 = Particles('M2')
        ps1.add([Particle(), Particle()])
        ps2.add([Particle(), Particle()])

        c = CUDS()
        c.add([ps1])
        c.add([ps2])

        cuds_list = []
        for component in c.iter(item_type=CUBA.PARTICLES):
            cuds_list.append(component)

        self.assertTrue(len(cuds_list), 2)
示例#13
0
    def test_iter_datasets_dimention(self):
        ps1 = Particles('M1')
        ps2 = Particles('M2')
        ps1.add([Particle(), Particle()])
        ps2.add([Particle(), Particle()])

        c = CUDS()
        c.add([ps1])
        c.add([ps2])

        cuds_list = []
        for component in c.iter(item_type=CUBA.PARTICLES):
            cuds_list.append(component)

        self.assertTrue(len(cuds_list), 2)
示例#14
0
    def test_particles_show(self):
        coordinates = numpy.array([
            [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1],
            [2, 0, 0], [3, 0, 0], [3, 1, 0], [2, 1, 0],
            [2, 0, 1], [3, 0, 1], [3, 1, 1], [2, 1, 1]],
            'f')
        particles = Particles('test')
        particle_iter = (Particle(coordinates=point+3)
                         for point in coordinates)
        particles.add(particle_iter)

        def function():
            show(particles)
            return True

        tester = ModalDialogTester(function)
        tester.open_and_run(when_opened=lambda x: x.close(accept=False))
        self.assertTrue(tester.result)
    def _handle_new_particles(self, uname, particles):
        """Add new particle container to this manager.


        Parameters
        ----------
        uname : string
            non-changing unique name of particles
        particles : ABCParticles
            particle container to be added

        """
        # create stand-alone particle container to use
        # as a cache of for input/output to LAMMPS
        pc = Particles(name="_")
        pc.data = DataContainer(particles.data)

        for p in particles.iter(item_type=CUBA.PARTICLE):
            pc.add([p])

        for b in particles.iter(item_type=CUBA.BOND):
            pc.add([b])

        self._pc_cache[uname] = pc
示例#16
0
    def test_compare_particles_datasets_equal(self):
        # given
        particles = Particles(name="test")
        reference = Particles(name="test")

        particle_list = create_particles_with_id()
        bond_list = create_bonds()
        data = DataContainer()

        particles.add(particle_list)
        reference.add(particle_list)

        particles.add(bond_list)
        reference.add(bond_list)

        particles.data = data
        reference.data = data

        # this should pass without problems
        compare_particles_datasets(particles, reference, testcase=self)
示例#17
0
    def test_compare_particles_datasets_equal(self):
        # given
        particles = Particles(name="test")
        reference = Particles(name="test")

        particle_list = create_particles_with_id()
        bond_list = create_bonds()
        data = DataContainer()

        particles.add(particle_list)
        reference.add(particle_list)

        particles.add(bond_list)
        reference.add(bond_list)

        particles.data = data
        reference.data = data

        # this should pass without problems
        compare_particles_datasets(particles, reference, testcase=self)
示例#18
0
def read_data_file(filename, atom_style=None, name=None):
    """ Reads LAMMPS data file and create CUDS objects

    Reads LAMMPS data file and create a Particles and CUDS. The CUDS
    will contain a material for each atom type (e.g. CUBA.MATERIAL_TYPE).

    The attributes for each particle are based upon what atom-style
    the file contains (i.e. "sphere" means that particles in addition to having
    CUBA.VELOCITY will also have a CUBA.RADIUS and CUBA.MASS). See
    'atom_style' for more details.

    Parameters
    ----------
    filename : str
        filename of lammps data file
    atom_style : AtomStyle, optional
        type of atoms in the file.  If None, then an attempt of
        interpreting the atom-style in the file is performed.
    name : str, optional
        name to be given to returned Particles.  If None, then filename is
        used.

    Returns
    -------
    particles : Particles
        particles
    SD : CUDS
        SD containing materials

    """
    handler = LammpsSimpleDataHandler()
    parser = LammpsDataFileParser(handler=handler)

    parser.parse(filename)

    if atom_style is None:
        atom_style = (
            get_atom_style(handler.get_atom_type())
            if handler.get_atom_type()
            else AtomStyle.ATOMIC)

    types = (atom_t for atom_t in
             range(1, handler.get_number_atom_types() + 1))
    atoms = handler.get_atoms()
    velocities = handler.get_velocities()
    masses = handler.get_masses()

    box_origin = handler.get_box_origin()
    box_vectors = handler.get_box_vectors()

    type_to_material_map = {}

    statedata = CUDS()

    # set up a Material for each different type
    for atom_type in types:
        material = Material()
        description = "Material for lammps atom type (originally '{}')".format(
            atom_type
        )
        material.description = description
        type_to_material_map[atom_type] = material.uid
        statedata.add([material])

    # add masses to materials
    for atom_type, mass in masses.iteritems():
        material = statedata.get(type_to_material_map[atom_type])
        material.data[CUBA.MASS] = mass
        statedata.update([material])

    def convert_atom_type_to_material(atom_type):
        return type_to_material_map[atom_type]

    interpreter = LammpsDataLineInterpreter(atom_style,
                                            convert_atom_type_to_material)

    # create particles
    particles = Particles(name=name if name else filename)
    data = particles.data
    data.update({CUBA.ORIGIN: box_origin,
                 CUBA.VECTOR: box_vectors})
    particles.data = data

    # add each particle
    for lammps_id, values in atoms.iteritems():
        coordinates, data = interpreter.convert_atom_values(values)
        data.update(interpreter.convert_velocity_values(velocities[lammps_id]))

        p = Particle(coordinates=coordinates, data=data)
        particles.add([p])

    return particles, statedata
示例#19
0
    def test_compare_particles_datasets_not_equal(self):
        # given
        particles = Particles(name="test")
        reference = Particles(name="test_ref")

        particle_list = create_particles_with_id()
        bond_list = create_bonds()
        data = create_data_container()

        particles.add(particle_list)
        reference.add(particle_list)

        particles.add(bond_list)
        reference.add(bond_list)

        particles.data = data
        reference.data = data

        # when/then
        with self.assertRaises(AssertionError):
            compare_particles_datasets(particles, reference, testcase=self)

        # given
        test_particles = create_particles_with_id()

        particles = Particles(name=reference.name)
        particles.add(test_particles)
        particles.add(bond_list)
        particles.data = data

        # when/then
        with self.assertRaises(AssertionError):
            compare_particles_datasets(particles, reference, testcase=self)

        # given
        test_bonds = create_bonds()

        particles = Particles(name=reference.name)
        particles.add(particle_list)
        particles.add(test_bonds)
        particles.data = data

        # when/then
        with self.assertRaises(AssertionError):
            compare_particles_datasets(particles, reference, testcase=self)

        # given
        test_data = DataContainer()

        particles = Particles(name=reference.name)
        particles.add(particle_list)
        particles.add(bond_list)
        particles.data = test_data

        # when/then
        with self.assertRaises(AssertionError):
            compare_particles_datasets(particles, reference, testcase=self)
from numpy import array

from simphony.cuds.particles import Particles, Particle, Bond
from simphony.core.data_container import DataContainer

points = array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], 'f')
bonds = array([[0, 1], [0, 3], [1, 3, 2]])
temperature = array([10., 20., 30., 40.])

particles = Particles('test')

# add particles
particle_iter = (Particle(coordinates=point,
                          data=DataContainer(TEMPERATURE=temperature[index]))
                 for index, point in enumerate(points))
uids = particles.add(particle_iter)

# add bonds
bond_iter = (Bond(particles=[uids[index] for index in indices])
             for indices in bonds)
particles.add(bond_iter)

if __name__ == '__main__':
    from simphony.visualisation import mayavi_tools

    # Visualise the Particles object
    mayavi_tools.show(particles)
class TestCUBADataExtractor(UnittestTools, unittest.TestCase):

    def setUp(self):
        self.points = [
            [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
        self.temperature = numpy.arange(4)
        self.velocity = [
            (0.5, 0.5, 0.5), (1.0, 0.0, 1.0), (1.0, 1.0, 0.0), (1.0, 1.0, 1.0)]
        self.bonds = [[0, 1], [0, 3], [1, 3, 2]]
        self.container = Particles('test')

        # add particles
        particle_list = []
        for index, point in enumerate(self.points):
            data = DataContainer(
                TEMPERATURE=self.temperature[index],
                VELOCITY=self.velocity[index])
            particle_list.append(Particle(coordinates=point, data=data))
        self.point_uids = self.container.add(particle_list)

        # add bonds
        bond_iter = (Bond(particles=[self.point_uids[index]
                                     for index in indices],
                          data=DataContainer(NAME=str(len(indices))))
                     for indices in self.bonds)
        self.bond_uids = self.container.add(bond_iter)

    def test_initialization(self):
        container = self.container
        extractor = CUBADataExtractor(function=functools.partial(
            container.iter, item_type=CUBA.PARTICLE))
        self.assertEqual(
            extractor.available, set((CUBA.TEMPERATURE, CUBA.VELOCITY)))
        self.assertEqual(extractor.data, {})

    def test_selectinng_available(self):
        container = self.container
        extractor = CUBADataExtractor(function=functools.partial(
            container.iter, item_type=CUBA.PARTICLE))

        with self.assertTraitChanges(extractor, 'data', count=1):
            extractor.selected = CUBA.TEMPERATURE

        self.assertEqual(len(extractor.data), 4)
        for uid, data in extractor.data.iteritems():
            particle = container.get(uid)
            self.assertEqual(particle.data[CUBA.TEMPERATURE], data)

    def test_selecting_none(self):
        extractor = CUBADataExtractor(
            function=functools.partial(
                self.container.iter, item_type=CUBA.PARTICLE))

        with self.assertTraitChanges(extractor, 'data', count=2):
            extractor.selected = CUBA.TEMPERATURE
            extractor.selected = None

        self.assertEqual(extractor.data, {})

    def test_selecting_unavailable(self):
        container = self.container
        extractor = CUBADataExtractor(
            function=functools.partial(container.iter,
                                       item_type=CUBA.PARTICLE))

        with self.assertTraitChanges(extractor, 'data', count=1):
            extractor.selected = CUBA.NAME

        self.assertEqual(len(extractor.data), 4)
        for uid, data in extractor.data.iteritems():
            self.assertTrue(container.has(uid))
            self.assertEqual(data, None)

    def test_function_change(self):
        container = self.container
        extractor = CUBADataExtractor(
            function=functools.partial(container.iter,
                                       item_type=CUBA.PARTICLE))
        extractor.selected = CUBA.TEMPERATURE

        with self.assertRaises(TraitError):
            extractor.function = functools.partial(container.iter,
                                                   item_type=CUBA.BOND)

    def test_keys_filtering(self):
        container = self.container
        extractor = CUBADataExtractor(
            function=functools.partial(
                container.iter,
                item_type=CUBA.PARTICLE),
            keys=set(self.point_uids[:1]))
        extractor.selected = CUBA.TEMPERATURE

        particle = container.get(self.point_uids[0])
        self.assertEqual(
            extractor.data,
            {self.point_uids[0]: particle.data[CUBA.TEMPERATURE]})

    def test_keys_filtering_change(self):
        container = self.container
        extractor = CUBADataExtractor(
            function=functools.partial(
                container.iter,
                item_type=CUBA.PARTICLE), keys=set(self.point_uids[:1]))
        extractor.selected = CUBA.TEMPERATURE

        with self.assertTraitChanges(extractor, 'data', count=1):
            extractor.keys = set(self.point_uids)

        self.assertEqual(len(extractor.data), 4)
        for uid, data in extractor.data.iteritems():
            particle = container.get(uid)
            self.assertEqual(particle.data[CUBA.TEMPERATURE], data)
from mayavi.scripts import mayavi2

from simphony.cuds.particles import Particles, Particle, Bond
from simphony.core.data_container import DataContainer

points = array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], 'f')
bonds = array([[0, 1], [0, 3], [1, 3, 2]])
temperature = array([10., 20., 30., 40.])

container = Particles('test')

# add particles
particle_iter = (Particle(coordinates=point,
                          data=DataContainer(TEMPERATURE=temperature[index]))
                 for index, point in enumerate(points))
uids = container.add(particle_iter)

# add bonds
bond_iter = (Bond(particles=[uids[index] for index in indices])
             for indices in bonds)
container.add(bond_iter)


# Now view the data.
@mayavi2.standalone
def view():
    from mayavi.modules.surface import Surface
    from mayavi.modules.glyph import Glyph
    from simphony_mayavi.sources.api import CUDSSource

    mayavi.new_scene()  # noqa
class TestParticlesSource(unittest.TestCase):
    tested_class = CUDSSource

    def setUp(self):
        self.points = [
            [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
        self.bonds = [[0, 1], [0, 3], [1, 3, 2]]
        self.point_temperature = [10., 20., 30., 40.]
        self.bond_temperature = [60., 80., 190., 5.]

        self.container = Particles('test')

        # add particles
        def particle_iter():
            for temp, point in zip(self.point_temperature, self.points):
                yield Particle(coordinates=point,
                               data=DataContainer(TEMPERATURE=temp))

        self.point_uids = self.container.add(particle_iter())

        # add bonds
        def bond_iter():
            for temp, indices in zip(self.bond_temperature, self.bonds):
                yield Bond(particles=[self.point_uids[index]
                                      for index in indices],
                           data=DataContainer(TEMPERATURE=temp))

        self.bond_uids = self.container.add(bond_iter())

        # for testing save/load visualization
        self.temp_dir = tempfile.mkdtemp()

    def tearDown(self):
        shutil.rmtree(self.temp_dir)

    def test_source_from_vtk_particles(self):
        # given
        container = VTKParticles('test')
        container.add(self.container.iter(item_type=CUBA.PARTICLE))
        container.add(self.container.iter(item_type=CUBA.BOND))

        # when
        source = self.tested_class(cuds=container)

        # then
        self.assertIs(source.data, container.data_set)
        self.assertIs(source.cuds, container)

    def test_particles(self):
        # given
        container = self.container

        # when
        source = self.tested_class(cuds=container)

        # then
        points = source.data.points.to_array()
        dataset = source.data
        vtk_cuds = source._vtk_cuds

        number_of_particles = len(self.points)
        self.assertEqual(len(points), number_of_particles)
        self.assertEqual(len(vtk_cuds.particle2index), number_of_particles)
        self.assertEqual(dataset.point_data.number_of_arrays, 1)
        temperature = dataset.point_data.get_array('TEMPERATURE')
        for key, index in vtk_cuds.particle2index.iteritems():
            point = container.get(key)
            assert_array_equal(points[index], point.coordinates)
            self.assertEqual(temperature[index], point.data[CUBA.TEMPERATURE])

    def test_bonds(self):
        # given
        container = self.container

        # when
        source = self.tested_class(cuds=container)

        # then
        dataset = source.data
        vtk_cuds = source._vtk_cuds
        bonds = [
            bond for bond in cell_array_slicer(dataset.lines.to_array())]
        number_of_bonds = len(self.bonds)
        self.assertEqual(len(bonds), number_of_bonds)
        self.assertEqual(len(vtk_cuds.bond2index), number_of_bonds)
        self.assertEqual(dataset.cell_data.number_of_arrays, 1)
        temperature = dataset.cell_data.get_array('TEMPERATURE')
        for key, index in vtk_cuds.bond2index.iteritems():
            bond = container.get(key)
            particles = [
                vtk_cuds.particle2index[uid] for uid in bond.particles]
            self.assertEqual(bonds[index], particles)
            self.assertEqual(temperature[index], bond.data[CUBA.TEMPERATURE])

    def test_particles_source_name(self):
        # given
        particles = Particles(name='my_particles')

        # when
        source = self.tested_class(cuds=particles)

        # then
        self.assertEqual(source.name, 'my_particles (CUDS Particles)')

    def check_save_load_visualization(self, engine):
        # set up the visualization
        container = self.container
        source = self.tested_class(cuds=container)
        engine.add_source(source)

        # save the visualization
        saved_viz_file = os.path.join(self.temp_dir, 'test_saved_viz.mv2')
        engine.save_visualization(saved_viz_file)
        engine.close_scene(engine.current_scene)

        # restore the visualization
        engine.load_visualization(saved_viz_file)

        # then
        source_in_scene = engine.current_scene.children[0]
        points = source_in_scene.data.points.to_array()
        dataset = source_in_scene.data
        number_of_particles = len(self.points)

        # data is restored
        self.assertEqual(len(points), number_of_particles)
        self.assertEqual(dataset.point_data.number_of_arrays, 1)

        # But cuds and vtk_cuds are not available
        self.assertIsNone(source_in_scene._vtk_cuds)
        self.assertIsNone(source_in_scene._cuds)

    @unittest.skipIf(is_mayavi_older("4.4.4"),
                     "Mayavi < 4.4.4 has problem with load_visualization")
    def test_save_load_visualization_with_mlab(self):
        # test mlab.get_engine
        engine = mlab.get_engine()

        try:
            self.check_save_load_visualization(engine)
        finally:
            mlab.clf()
            mlab.close(all=True)

    def test_save_load_visualization_with_null_engine(self):
        self.check_save_load_visualization(NullEngine())
示例#24
0
    def test_add_nameless_dataset(self):
        ps = Particles(None)
        ps.add([Particle(), Particle()])
        c = CUDS()

        self.assertRaises(TypeError, c.add, [ps])
示例#25
0
    def test_add_nameless_dataset(self):
        ps = Particles(None)
        ps.add([Particle(), Particle()])
        c = CUDS()

        self.assertRaises(TypeError, c.add, [ps])
class TestParticlesSlimSource(TestParticlesSource):
    tested_class = SlimCUDSSource

    def setUp(self):
        self.points = [
            [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
        self.bonds = [[0, 1], [0, 3], [1, 3, 2]]
        self.point_temperature = [10., 20., 30., 40.]
        self.point_radius = [1., 2., 3., 4.]
        self.point_mass = [4., 8., 16., 32.]
        self.bond_temperature = [60., 80., 190., 5.]

        self.container = Particles('test')

        # add particles
        def particle_iter():
            for temp, radius, mass, point in zip(
                    self.point_temperature,
                    self.point_radius,
                    self.point_mass,
                    self.points):
                yield Particle(coordinates=point,
                               data=DataContainer(
                                   TEMPERATURE=temp,
                                   RADIUS=radius,
                                   MASS=mass))

        self.point_uids = self.container.add(particle_iter())

        # add bonds
        def bond_iter():
            for temp, indices in zip(self.bond_temperature, self.bonds):
                yield Bond(particles=[self.point_uids[index]
                                      for index in indices],
                           data=DataContainer(
                               TEMPERATURE=temp,
                               ))

        self.bond_uids = self.container.add(bond_iter())

        # for testing save/load visualization
        self.temp_dir = tempfile.mkdtemp()

    def test_particles(self):
        cuds = self.container

        source = SlimCUDSSource(cuds=cuds)

        self.assertEqual(len(source._point_scalars_list), 4)
        for entry in ['', 'MASS', 'RADIUS', 'TEMPERATURE']:
            self.assertIn(entry, source._point_scalars_list)

        dataset = source.data
        self.assertEqual(dataset.point_data.number_of_arrays, 1)
        self.assertEqual(source.point_scalars_name, 'MASS')

        source.point_scalars_name = "TEMPERATURE"
        dataset = source.data
        points = dataset.points.to_array()
        vtk_cuds = source._vtk_cuds

        self.assertEqual(dataset.point_data.number_of_arrays, 1)
        temperature = dataset.point_data.get_array('TEMPERATURE')
        for key, index in vtk_cuds.particle2index.iteritems():
            point = self.container.get(key)
            assert_array_equal(points[index], point.coordinates)
            self.assertEqual(temperature[index], point.data[CUBA.TEMPERATURE])

        source.point_scalars_name = "MASS"
        self.assertEqual(dataset.point_data.number_of_arrays, 1)
        dataset = source.data
        mass = dataset.point_data.get_array('MASS')
        for key, index in vtk_cuds.particle2index.iteritems():
            point = self.container.get(key)
            assert_array_equal(points[index], point.coordinates)
            self.assertEqual(mass[index], point.data[CUBA.MASS])

        source.point_scalars_name = ""
        dataset = source.data
        self.assertEqual(dataset.point_data.number_of_arrays, 0)

    def test_available_keys(self):
        available_keys = _available_keys(self.container)

        self.assertEqual(available_keys["point_scalars"],
                         {CUBA.TEMPERATURE,
                          CUBA.RADIUS,
                          CUBA.MASS})

        self.assertEqual(available_keys["point_vectors"], set())
        self.assertEqual(available_keys["cell_scalars"], {CUBA.TEMPERATURE})
        self.assertEqual(available_keys["cell_vectors"], set())

    def test_bonds(self):
        source = SlimCUDSSource(cuds=self.container)

        # We should have two entries in the available cuba data, one for
        # temperature and one for blank
        self.assertEqual(len(source._cell_scalars_list), 2)
        for entry in ['', 'TEMPERATURE']:
            self.assertIn(entry, source._cell_scalars_list)

        dataset = source.data
        # The actual array set in the cell data should be empty if selection
        # is blank
        self.assertEqual(dataset.cell_data.number_of_arrays, 1)
        self.assertEqual(source.cell_scalars_name, 'TEMPERATURE')

        # Clearing should empty the data again
        source.cell_scalars_name = ""
        dataset = source.data
        self.assertEqual(dataset.cell_data.number_of_arrays, 0)

        # Selecting temperature triggers the transfer from cuds to vtk cuds
        # of only the selected array
        source.cell_scalars_name = "TEMPERATURE"
        dataset = source.data
        vtk_cuds = source._vtk_cuds
        bonds = [
            bond for bond in cell_array_slicer(dataset.lines.to_array())]
        number_of_bonds = len(self.bonds)
        self.assertEqual(len(bonds), number_of_bonds)
        self.assertEqual(len(vtk_cuds.bond2index), number_of_bonds)
        self.assertEqual(dataset.cell_data.number_of_arrays, 1)

        temperature = dataset.cell_data.get_array('TEMPERATURE')
        for key, index in vtk_cuds.bond2index.iteritems():
            bond = self.container.get(key)
            particles = [
                vtk_cuds.particle2index[uid] for uid in bond.particles]
            self.assertEqual(bonds[index], particles)
            self.assertEqual(temperature[index], bond.data[CUBA.TEMPERATURE])

    @unittest.skip("Cannot perform save/load with SlimCUDSSource")
    def test_save_load_visualization_with_mlab(self):
        pass

    @unittest.skip("Cannot perform save/load with SlimCUDSSource")
    def test_save_load_visualization_with_null_engine(self):
        pass

    def test_start_setup(self):
        source = SlimCUDSSource(cuds=self.container)

        self.assertEqual(source.point_scalars_name, "MASS")
        self.assertEqual(source.point_vectors_name, "")
        self.assertEqual(source.cell_scalars_name, "TEMPERATURE")
        self.assertEqual(source.cell_vectors_name, "")

        self.assertEqual(len(source._point_scalars_list), 4)
        self.assertEqual(len(source._point_vectors_list), 1)
        self.assertEqual(len(source._cell_scalars_list), 2)
        self.assertEqual(len(source._cell_vectors_list), 1)

        source = SlimCUDSSource(cuds=self.container,
                                point_scalars="TEMPERATURE")

        self.assertEqual(source.point_scalars_name, "TEMPERATURE")
        self.assertEqual(source.point_vectors_name, "")
        self.assertEqual(source.cell_scalars_name, "TEMPERATURE")
        self.assertEqual(source.cell_vectors_name, "")

        self.assertEqual(len(source._point_scalars_list), 4)
        self.assertEqual(len(source._point_vectors_list), 1)
        self.assertEqual(len(source._cell_scalars_list), 2)
        self.assertEqual(len(source._cell_vectors_list), 1)

    def test_changing_names(self):
        source = SlimCUDSSource(cuds=self.container,
                                point_scalars="TEMPERATURE")

        point_attrs, cell_attrs = get_all_attributes(source.data)
        self.assertEqual(len(point_attrs["scalars"]), 1)
        self.assertEqual(point_attrs["scalars"][0], "TEMPERATURE")

        source.point_scalars_name = ""
        point_attrs, cell_attrs = get_all_attributes(source.data)
        self.assertEqual(len(point_attrs["scalars"]), 0)

    def test_unexistent_choice(self):
        # This should work and trigger no error
        source = SlimCUDSSource(point_scalars="TEMPERATURE")
        self.assertEqual(source.point_scalars_name, '')

    def test_changing_cuds(self):
        source = SlimCUDSSource()

        source.cuds = self.container
        source.point_scalars_name = "TEMPERATURE"
        point_attrs, cell_attrs = get_all_attributes(source.data)
        self.assertEqual(len(point_attrs["scalars"]), 1)
        self.assertEqual(point_attrs["scalars"][0], "TEMPERATURE")

        source.point_scalars_name = ""
        point_attrs, cell_attrs = get_all_attributes(source.data)
        self.assertEqual(len(point_attrs["scalars"]), 0)

    def test_combo_selection_preserved(self):
        dummy_engine = DummyEngine()
        source = SlimCUDSSource(cuds=dummy_engine.get_dataset("particles"),
                                point_scalars="MASS", point_vectors="")

        self.assertEqual(source.point_scalars_name, "MASS")
        self.assertEqual(source.point_vectors_name, "")

        source.start()

        self.assertEqual(source.point_scalars_name, "MASS")
        self.assertEqual(source.point_vectors_name, "")
示例#27
0
    def test_compare_particles_datasets_not_equal(self):
        # given
        particles = Particles(name="test")
        reference = Particles(name="test_ref")

        particle_list = create_particles_with_id()
        bond_list = create_bonds()
        data = create_data_container()

        particles.add(particle_list)
        reference.add(particle_list)

        particles.add(bond_list)
        reference.add(bond_list)

        particles.data = data
        reference.data = data

        # when/then
        with self.assertRaises(AssertionError):
            compare_particles_datasets(particles, reference, testcase=self)

        # given
        test_particles = create_particles_with_id()

        particles = Particles(name=reference.name)
        particles.add(test_particles)
        particles.add(bond_list)
        particles.data = data

        # when/then
        with self.assertRaises(AssertionError):
            compare_particles_datasets(particles, reference, testcase=self)

        # given
        test_bonds = create_bonds()

        particles = Particles(name=reference.name)
        particles.add(particle_list)
        particles.add(test_bonds)
        particles.data = data

        # when/then
        with self.assertRaises(AssertionError):
            compare_particles_datasets(particles, reference, testcase=self)

        # given
        test_data = DataContainer()

        particles = Particles(name=reference.name)
        particles.add(particle_list)
        particles.add(bond_list)
        particles.data = test_data

        # when/then
        with self.assertRaises(AssertionError):
            compare_particles_datasets(particles, reference, testcase=self)
示例#28
0
def generate_fibers(smp_particles, smp_conditions, smp_materials, smp_pe):
    # Define the particle containers.
    fibers = SParticles(name='fibers')

    # Fill the data ( fiber )
    data = DataContainer()
    data[CUBA.RADIUS] = 1e-5

    fiberCoords = [
        (0.1166666666666666685, 0.5083333333333333037, 0.5166666666666666075),
        (0.1499999999999999944, 0.5250000000000000222, 0.5500000000000000444),
        (0.1833333333333333481, 0.5416666666666667407, 0.5833333333333332593),
        (0.2166666666666666741, 0.5583333333333333481, 0.6166666666666666963),
        (0.2500000000000000000, 0.5749999999999999556, 0.6499999999999999112),
        (0.2833333333333333259, 0.5916666666666665630, 0.6833333333333333481)
    ]

    fibers.add([
        SParticle(
            coordinates=fiberCoords[0],
            data=DataContainer(data),
        ),
        SParticle(
            coordinates=fiberCoords[1],
            data=DataContainer(data),
        ),
        SParticle(
            coordinates=fiberCoords[2],
            data=DataContainer(data),
        ),
        SParticle(
            coordinates=fiberCoords[3],
            data=DataContainer(data),
        ),
        SParticle(
            coordinates=fiberCoords[4],
            data=DataContainer(data),
        ),
        SParticle(
            coordinates=fiberCoords[5],
            data=DataContainer(data),
        )
    ])

    material = api.Material(name='material_' + fibers.name)
    materialData = material.data

    materialData[CUBA.DENSITY] = 1050.0
    materialData[CUBA.YOUNG_MODULUS] = 1.0e9
    materialData[CUBA.POISSON_RATIO] = 0.20
    materialData[CUBA.FRICTION_COEFFICIENT] = 0.9999999999999999
    # materialData[CUBA.PARTICLE_COHESION] = 0.0
    materialData[CUBA.RESTITUTION_COEFFICIENT] = 0.02
    materialData[CUBA.ROLLING_FRICTION] = 0.01
    # materialData[CUBA.FABRIC_COEFFICIENT] = 0.1
    # materialData[CUBA.DEM_CONTINUUM_CONSTITUTIVE_LAW_NAME] = \
    # "DEM_KDEMFabric"
    # materialData[CUBA.DEM_DISCONTINUUM_CONSTITUTIVE_LAW_NAME] = \
    # "DEM_D_Hertz_viscous_Coulomb"
    # materialData[CUBA.CONTACT_TAU_ZERO] = 25
    # materialData[CUBA.CONTACT_SIGMA_MIN] = 5
    # materialData[CUBA.CONTACT_INTERNAL_FRICC] = 1

    material.data = materialData

    fibersData = fibers.data
    fibersData[CUBA.MATERIAL] = material.name
    fibers.data = fibersData

    # Pack the return objects
    smp_particles.append(fibers)
    smp_materials.append(material)

    # Add the datasets that will be used by the wrapper
    smp_pe.data[CUBA.DATA_SET].append(fibers.name)

    return {
        'datasets': smp_particles,
        'conditions': smp_conditions,
        'materials': smp_materials,
        'pe': smp_pe,
    }
示例#29
0
input_particles = []

for pos in atoms1:
    pos2 = [pos[0] * a_latt, pos[1] * a_latt, pos[2] * a_latt]
    p = Particle(coordinates=pos2)
    # p = api.Particle(position=pos2)
    # Usually, user asks the MD program to initialize the velocities
    # according to a Maxwell-Boltzmann distribution. In this example
    # we define a uniform random distribution, the MD algorithm will
    # in any case result in a MB one quickly.
    p.data[CUBA.VELOCITY] = [
        numpy.random.uniform(-0.5, 0.5),
        numpy.random.uniform(-0.5, 0.5),
        numpy.random.uniform(-0.5, 0.5)
    ]
    pc.add([p])
    input_particles.append(p)


# Calculate the velocity of center of mass and reset it to zero to
# avoid drift of the whole system.
v_cm = [0, 0, 0]
for p in pc.iter(item_type=CUBA.PARTICLE):
    v_cm[0] += p.data[CUBA.VELOCITY][0]
    v_cm[1] += p.data[CUBA.VELOCITY][1]
    v_cm[2] += p.data[CUBA.VELOCITY][2]

number_of_points = pc.count_of(CUBA.PARTICLE)

v_cm[0] /= number_of_points
v_cm[1] /= number_of_points