Example #1
0
    def load_chk(self, fn):
        """
        Load the atom types, atom type ids and structure by reading a .chk file.

        **Arguments**

        fn      the path to the chk file
        """

        system = System.from_file(fn)
        system.set_standard_masses()
        if len(system.pos.shape) != 2:
            raise IOError(
                "Something went wrong, positions in CHK file %s should have Nx3 dimensions"
                % fn)
        if system.cell.rvecs is not None and len(system.cell.rvecs) > 0:
            self.structure = Atoms(
                positions=system.pos.copy() / angstrom,
                numbers=system.numbers,
                masses=system.masses,
                cell=system.cell.rvecs / angstrom,
                pbc=True,
            )
        else:
            self.structure = Atoms(
                positions=system.pos.copy() / angstrom,
                numbers=system.numbers,
                masses=system.masses,
            )
        if system.ffatypes is not None:
            self.ffatypes = system.ffatypes
        if system.ffatype_ids is not None:
            self.ffatype_ids = system.ffatype_ids
Example #2
0
    def test_get_parent_basis(self):
        periodic_table = PeriodicTable()
        periodic_table.add_element(parent_element="O", new_element="O_up")
        O_up = periodic_table.element("O_up")

        O_basis = Atoms([O_up],
                        cell=10.0 * np.eye(3),
                        scaled_positions=[[0.5, 0.5, 0.5]])
        O_simple = Atoms(["O"],
                         cell=10.0 * np.eye(3),
                         scaled_positions=[[0.5, 0.5, 0.5]])
        O_parent = O_basis.get_parent_basis()
        self.assertNotEqual(O_basis, O_parent)
        self.assertEqual(O_simple, O_parent)
        self.assertEqual(O_parent[0].symbol, "O")
        periodic_table.add_element(parent_element="O", new_element="O_down")
        O_down = periodic_table.element("O_down")
        O_basis = Atoms([O_up, O_down],
                        cell=10.0 * np.eye(3),
                        scaled_positions=[[0.5, 0.5, 0.5], [0, 0, 0]])
        O_simple = Atoms(["O", "O"],
                         cell=10.0 * np.eye(3),
                         scaled_positions=[[0.5, 0.5, 0.5]])
        O_parent = O_basis.get_parent_basis()
        self.assertNotEqual(O_basis, O_parent)
        self.assertEqual(O_simple, O_parent)
        self.assertEqual(O_parent.get_chemical_formula(), "O2")
        self.assertEqual(len(O_basis.species), 2)
        self.assertEqual(len(O_simple.species), 1)
        self.assertEqual(len(O_parent.species), 1)
Example #3
0
 def setUp(self):
     pass
     self.CO2 = Atoms("CO2",
                      positions=[[0, 0, 0], [0, 0, 1.5], [0, 1.5, 0]])
     C = Atom('C').element
     self.C3 = Atoms([C, C, C], positions=[[0, 0, 0], [0, 0, 2], [0, 2, 0]])
     self.C2 = Atoms(2 * [Atom('C')])
Example #4
0
 def setUpClass(cls):
     cls.file_location = os.path.dirname(os.path.abspath(__file__))
     cls.project = Project(os.path.join(cls.file_location, "../static/sphinx"))
     pt = PeriodicTable()
     pt.add_element(parent_element="Fe", new_element="Fe_up", spin="0.5")
     Fe_up = pt.element("Fe_up")
     cls.basis = Atoms(
         elements=[Fe_up, Fe_up],
         scaled_positions=[[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]],
         cell=2.6 * np.eye(3),
     )
     cls.sphinx = cls.project.create_job("Sphinx", "job_sphinx")
     cls.sphinx_2_3 = cls.project.create_job("Sphinx", "sphinx_test_2_3")
     cls.sphinx_2_5 = cls.project.create_job("Sphinx", "sphinx_test_2_5")
     cls.sphinx.structure = cls.basis
     cls.sphinx_2_3.structure = Atoms(
         elements=["Fe", "Fe"],
         scaled_positions=[[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]],
         cell=2.6 * np.eye(3),
     )
     cls.sphinx_2_5.structure = Atoms(
         elements=["Fe", "Ni"],
         scaled_positions=[[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]],
         cell=2.83 * np.eye(3),
     )
     cls.current_dir = os.path.abspath(os.getcwd())
     cls.sphinx._create_working_directory()
     cls.sphinx_2_3._create_working_directory()
     cls.sphinx.write_input()
     cls.sphinx.version = "2.6"
     cls.sphinx_2_3.to_hdf()
     cls.sphinx_2_3.decompress()
     cls.sphinx_2_5.decompress()
Example #5
0
    def get_initial_structure(self):
        """
        Gets the initial structure from the simulation

        Returns:
            pyiron.atomistics.structure.atoms.Atoms: The initial structure

        """
        try:
            el_list = self.vasprun_dict["atominfo"]["species_list"]
            cell = self.vasprun_dict["init_structure"]["cell"]
            positions = self.vasprun_dict["init_structure"]["positions"]
            if len(positions[positions > 1.01]) > 0:
                basis = Atoms(el_list, positions=positions, cell=cell)
            else:
                basis = Atoms(el_list, scaled_positions=positions, cell=cell)
            if "selective_dynamics" in self.vasprun_dict[
                    "init_structure"].keys():
                basis.add_tag(selective_dynamics=[True, True, True])
                for i, val in enumerate(self.vasprun_dict["init_structure"]
                                        ["selective_dynamics"]):
                    basis[i].selective_dynamics = val
            return basis
        except KeyError:
            s = Settings()
            s.logger.warning(
                "The initial structure could not be extracted from vasprun properly"
            )
            return
Example #6
0
    def from_hdf(self, hdf = None, group_name = None):
        # keep hdf structure for version peeking in separate variable, so that
        # the inherited from_hdf() can properly deal with it
        h5 = hdf or self.project_hdf5
        if group_name:
            h5 = h5[group_name]
        if "HDF_VERSION" in h5.list_nodes():
            hdf_version = h5["HDF_VERSION"]
        else:
            # old versions didn't use to set a HDF version
            hdf_version = "0.1.0"
        if hdf_version == "0.1.0":
            super().from_hdf(hdf=hdf, group_name=group_name)
            with self.project_hdf5.open("input") as hdf5_input:
                self.structure = Atoms().from_hdf(hdf5_input)
        else:
            GenericJob.from_hdf(self, hdf = hdf, group_name = group_name)

            self.structure_lst.clear()

            hdf = self.project_hdf5["structures"]
            for group in sorted(hdf.list_groups()):
                structure = Atoms()
                structure.from_hdf(hdf, group_name = group)
                self.structure_lst.append(structure)
Example #7
0
 def test_get_space_group(self):
     cell = 2.2 * np.identity(3)
     Al_sc = Atoms('AlAl',
                   scaled_positions=[(0, 0, 0), (0.5, 0.5, 0.5)],
                   cell=cell)
     self.assertEqual(Al_sc.get_spacegroup()['InternationalTableSymbol'],
                      'Im-3m')
     self.assertEqual(Al_sc.get_spacegroup()['Number'], 229)
     cell = 4.2 * (0.5 * np.ones((3, 3)) - 0.5 * np.eye(3))
     Al_fcc = Atoms('Al', scaled_positions=[(0, 0, 0)], cell=cell)
     self.assertEqual(Al_fcc.get_spacegroup()['InternationalTableSymbol'],
                      'Fm-3m')
     self.assertEqual(Al_fcc.get_spacegroup()['Number'], 225)
     a = 3.18
     c = 1.623 * a
     cell = np.eye(3)
     cell[0, 0] = a
     cell[2, 2] = c
     cell[1, 0] = -a / 2.
     cell[1, 1] = np.sqrt(3) * a / 2.
     pos = np.array([[0., 0., 0.], [1. / 3., 2. / 3., 1. / 2.]])
     Mg_hcp = Atoms('Mg2', scaled_positions=pos, cell=cell)
     self.assertEqual(Mg_hcp.get_spacegroup()['Number'], 194)
     cell = np.eye(3)
     cell[0, 0] = a
     cell[2, 2] = c
     cell[1, 1] = np.sqrt(3) * a
     pos = np.array([[0., 0., 0.], [0.5, 0.5, 0.], [0.5, 0.16666667, 0.5],
                     [0., 0.66666667, 0.5]])
     Mg_hcp = Atoms('Mg4', scaled_positions=pos, cell=cell)
     self.assertEqual(Mg_hcp.get_spacegroup()['Number'], 194)
Example #8
0
 def setUpClass(cls):
     cls.file_location = os.path.dirname(os.path.abspath(__file__))
     cls.project = Project(
         os.path.join(cls.file_location, "../static/sphinx"))
     pt = PeriodicTable()
     pt.add_element(parent_element="Fe", new_element="Fe_up", spin="0.5")
     Fe_up = pt.element("Fe_up")
     cls.basis = Atoms(
         elements=[Fe_up, Fe_up],
         scaled_positions=[[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]],
         cell=2.6 * np.eye(3),
     )
     cls.sphinx = cls.project.create_job("Sphinx", "job_sphinx")
     cls.sphinx_band_structure = cls.project.create_job(
         "Sphinx", "sphinx_test_bs")
     cls.sphinx_2_3 = cls.project.create_job("Sphinx", "sphinx_test_2_3")
     cls.sphinx_2_5 = cls.project.create_job("Sphinx", "sphinx_test_2_5")
     cls.sphinx_aborted = cls.project.create_job("Sphinx",
                                                 "sphinx_test_aborted")
     cls.sphinx.structure = cls.basis
     cls.sphinx.fix_spin_constraint = True
     cls.sphinx_band_structure.structure = cls.project.create_structure(
         "Fe", "bcc", 2.81)
     cls.sphinx_band_structure.structure = cls.sphinx_band_structure.structure.create_line_mode_structure(
     )
     cls.sphinx_2_3.structure = Atoms(
         elements=["Fe", "Fe"],
         scaled_positions=[[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]],
         cell=2.6 * np.eye(3),
     )
     cls.sphinx_2_5.structure = Atoms(
         elements=["Fe", "Ni"],
         scaled_positions=[[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]],
         cell=2.83 * np.eye(3),
     )
     cls.sphinx_aborted.structure = Atoms(
         elements=32 * ["Fe"],
         scaled_positions=np.arange(32 * 3).reshape(-1, 3) / (32 * 3),
         cell=3.5 * np.eye(3),
     )
     cls.sphinx_aborted.status.aborted = True
     cls.current_dir = os.path.abspath(os.getcwd())
     cls.sphinx._create_working_directory()
     cls.sphinx_2_3._create_working_directory()
     cls.sphinx.input["VaspPot"] = False
     cls.sphinx.structure.add_tag(selective_dynamics=(True, True, True))
     cls.sphinx.structure.selective_dynamics[1] = (False, False, False)
     cls.sphinx.load_default_groups()
     cls.sphinx.fix_symmetry = False
     cls.sphinx.write_input()
     try:
         cls.sphinx.version = "2.6"
     except ValueError:
         cls.sphinx.version = "2.6.2_default"
     cls.sphinx_2_3.to_hdf()
     cls.sphinx_2_3.decompress()
     cls.sphinx_2_5.decompress()
Example #9
0
def _dict_to_atoms(atoms_dict, species_list=None, read_from_first_line=False):
    """
    Function to convert a generated dict into an structure object

    Args:
        atoms_dict (dict): Dictionary with the details (from string_to_atom)
        species_list (list/numpy.ndarray): List of species
        read_from_first_line (bool): True if we are to read the species information from the first line in the file

    Returns:
        pyiron.atomistics.structure.atoms.Atoms: The required structure object
    """
    is_absolute = not (atoms_dict["relative"])
    positions = atoms_dict["positions"]
    cell = atoms_dict["cell"]
    symbol = str()
    elements = list()
    el_list = list()
    for i, sp_key in enumerate(atoms_dict["species_dict"].keys()):
        if species_list is not None:
            try:
                el_list = np.array([species_list[i]])
                el_list = np.tile(el_list, atoms_dict["species_dict"][sp_key]["count"])
                if isinstance(species_list[i], str):
                    symbol += species_list[i] + str(atoms_dict["species_dict"][sp_key]["count"])
                else: 
                    symbol += species_list[i].Abbreviation + str(atoms_dict["species_dict"][sp_key]["count"])
            except IndexError:
                raise ValueError("Number of species in the specified species list does not match that in the file")
        elif "species" in atoms_dict["species_dict"][sp_key].keys():
            el_list = np.array([atoms_dict["species_dict"][sp_key]["species"]])
            el_list = np.tile(el_list, atoms_dict["species_dict"][sp_key]["count"])
            symbol += atoms_dict["species_dict"][sp_key]["species"]
            symbol += str(atoms_dict["species_dict"][sp_key]["count"])
        elif read_from_first_line:
            if not (len(atoms_dict["first_line"].split()) == len(atoms_dict["species_dict"].keys())):
                raise AssertionError()
            el_list = np.array(atoms_dict["first_line"].split()[i])
            el_list = np.tile(el_list, atoms_dict["species_dict"][sp_key]["count"])
            symbol += atoms_dict["first_line"].split()[i]
            symbol += str(atoms_dict["species_dict"][sp_key]["count"])
        elif species_list is None:
            raise ValueError("Species list should be provided since pyiron can't detect species information")
        elements.append(el_list)
    elements_new = list()
    for ele in elements:
        for e in ele:
            elements_new.append(e)
    elements = elements_new
    if is_absolute:
        atoms = Atoms(elements, positions=positions, cell=cell)
    else:
        atoms = Atoms(elements, scaled_positions=positions, cell=cell)
    return atoms
Example #10
0
 def get_equivalent_voronoi_vertices(self):
     cell = 2.2 * np.identity(3)
     Al = Atoms('AlAl', positions=[(0, 0, 0), (0.5, 0.5, 0.5)],
                cell=cell).repeat(2)
     pos, box = Al._get_voronoi_vertices()
     self.assertEqual(len(Al), 69)
     self.assertEqual(len(len(Al.get_species_symbols())), 2)
     Al = Atoms('AlAl',
                scaled_positions=[(0, 0, 0), (0.5, 0.5, 0.5)],
                cell=cell).repeat(2)
     pos = Al.get_equivalent_voronoi_vertices()
     self.assertEqual(len(pos), 1)
Example #11
0
    def test__delitem__(self):
        cell = np.eye(3) * 10.0
        basis_0 = Atoms(["O"], scaled_positions=[[0.5, 0.5, 0.5]], cell=cell)
        basis_1 = Atoms(["H"],
                        scaled_positions=[[0.75, 0.75, 0.75]],
                        cell=cell)
        basis_2 = Atoms(["H"],
                        scaled_positions=[[0.25, 0.25, 0.25]],
                        cell=cell)
        basis_3 = Atoms(["H", "O", "N"],
                        scaled_positions=[[0.35, 0.35, 0.35], [0., 0., 0.],
                                          [0., 0., 0.1]],
                        cell=cell)

        pse = PeriodicTable()
        pse.add_element("O", "O_up", spin="up")
        o_up = pse.element("O_up")
        basis_4 = Atoms([o_up],
                        scaled_positions=[[0.27, 0.27, 0.27]],
                        cell=cell)
        b = basis_0 + basis_1 + basis_2 + basis_3 + basis_4
        O_indices = b.select_index("O")
        self.assertEqual(len(b), 7)
        self.assertEqual(len(b.indices), 7)
        self.assertEqual(len(b.species), 4)
        b.__delitem__(O_indices[0])
        self.assertEqual(b.get_chemical_formula(), "H3NOO_up")
        self.assertEqual(len(b), 6)
        self.assertEqual(len(b.indices), 6)
        self.assertEqual(len(b._tag_list), 6)
        self.assertEqual(len(b.species), 4)
        O_indices = b.select_index("O")
        b.__delitem__(O_indices)
        self.assertEqual(b.get_chemical_formula(), "H3NO_up")
        self.assertEqual(len(b), 5)
        self.assertEqual(len(b.indices), 5)
        self.assertEqual(len(b.species), 3)
        self.assertEqual(np.max(b.indices), 2)
        N_indices = b.select_index("N")
        b.__delitem__(N_indices)
        self.assertEqual(b.get_chemical_formula(), "H3O_up")
        self.assertEqual(len(b), 4)
        self.assertEqual(len(b.indices), 4)
        self.assertEqual(len(b.species), 2)
        self.assertEqual(np.max(b.indices), 1)
        O_indices = b.select_index(o_up)
        b.__delitem__(O_indices)
        self.assertEqual(b.get_chemical_formula(), "H3")
        self.assertEqual(len(b), 3)
        self.assertEqual(len(b.indices), 3)
        self.assertEqual(len(b.species), 1)
        self.assertEqual(np.max(b.indices), 0)
Example #12
0
 def test_from_hdf(self):
     if sys.version_info[0] >= 3:
         filename = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                 "../../static/atomistics/test_hdf")
         abs_filename = os.path.abspath(filename)
         hdf_obj = FileHDFio(abs_filename)
         pos, cell = generate_fcc_lattice()
         basis_store = Atoms(symbols='Al', positions=pos, cell=cell)
         basis_store.set_repeat([2, 2, 2])
         basis_store.to_hdf(hdf_obj, "simple_structure")
         basis = Atoms().from_hdf(hdf_obj, group_name="simple_structure")
         self.assertEqual(len(basis), 8)
         self.assertEqual(basis.get_majority_species()[1], "Al")
         self.assertEqual(basis.get_spacegroup()['Number'], 225)
    def from_hdf(self, hdf=None, group_name=None):
        """
        Restore the ExampleJob object in the HDF5 File

        Args:
            hdf (ProjectHDFio): HDF5 group object - optional
            group_name (str): HDF5 subgroup name - optional
        """
        super(MonteCarloMaster, self).from_hdf(hdf=hdf, group_name=group_name)
        with self.project_hdf5.open("input") as hdf5_input:
            self.structure_sublattice = Atoms().from_hdf(
                hdf5_input, group_name="structure_sublattice")
            self.structure_lattice = Atoms().from_hdf(
                hdf5_input, group_name="structure_lattice")
Example #14
0
 def test_to_hdf(self):
     if sys.version_info[0] >= 3:
         filename = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                 "../../static/atomistics/test_hdf")
         abs_filename = os.path.abspath(filename)
         hdf_obj = FileHDFio(abs_filename)
         pos, cell = generate_fcc_lattice()
         basis = Atoms(symbols='Al', positions=pos, cell=cell)
         basis.set_repeat([2, 2, 2])
         basis.to_hdf(hdf_obj, "test_structure")
         self.assertTrue(
             np.array_equal(hdf_obj["test_structure/positions"],
                            basis.positions))
         basis_new = Atoms().from_hdf(hdf_obj, "test_structure")
         self.assertEqual(basis, basis_new)
Example #15
0
    def test_calc_minimize_input(self):
        # Ensure defaults match control
        atoms = Atoms("Fe8", positions=np.zeros((8, 3)), cell=np.eye(3))
        self.minimize_control_job.structure = atoms
        self.minimize_control_job.input.control.calc_minimize()
        self.minimize_control_job._interactive_lammps_input()
        self.minimize_job.structure = atoms
        self.minimize_job.calc_minimize()
        self.minimize_job._interactive_lammps_input()

        self.assertEqual(
            self.minimize_control_job._interactive_library._command,
            self.minimize_job._interactive_library._command)

        # Ensure that pressure inputs are being parsed OK
        self.minimize_job.calc_minimize(pressure=0)
        self.minimize_job._interactive_lammps_input()
        self.assertTrue(
            ("fix ensemble all box/relax x 0.0 y 0.0 z 0.0 couple none"
             in self.minimize_job._interactive_library._command))

        self.minimize_job.calc_minimize(pressure=[1, 2, None, 0., 0., None])
        self.minimize_job._interactive_lammps_input()
        self.assertTrue((
            "fix ensemble all box/relax x 10000.0 y 20000.0 xy 0.0 xz 0.0 couple none"
            in self.minimize_job._interactive_library._command))
Example #16
0
    def setUpClass(cls):
        cls.execution_path = os.path.dirname(os.path.abspath(__file__))
        cls.project = Project(os.path.join(cls.execution_path, "lammps"))

        structure = Atoms(
            symbols="Fe2",
            positions=np.outer(np.arange(2), np.ones(3)),
            cell=2 * np.eye(3),
        )

        cls.job = Lammps(
            project=ProjectHDFio(project=cls.project, file_name="lammps"),
            job_name="lammps",
        )
        cls.job.server.run_mode.interactive = True
        cls.job.structure = structure

        cls.minimize_job = Lammps(
            project=ProjectHDFio(project=cls.project, file_name="lammps"),
            job_name="minimize_lammps",
        )
        cls.minimize_control_job = Lammps(
            project=ProjectHDFio(project=cls.project, file_name="lammps"),
            job_name="minimize_control_lammps",
        )
Example #17
0
 def test_copy(self):
     pos, cell = generate_fcc_lattice()
     basis = Atoms(symbols='Al', positions=pos, cell=cell)
     basis_copy = basis.copy()
     self.assertEqual(basis, basis_copy)
     basis_copy[:] = "Pt"
     self.assertNotEqual(basis, basis_copy)
Example #18
0
    def from_hdf_old(self, hdf, group_name="electronic_structure"):
        """
        Retrieve the object from the hdf5 file

        Args:
            hdf: Path to the hdf5 file/group in the file
            group_name: Name of the group under which the attributes are stored
        """
        with hdf.open(group_name) as h_es:
            if "structure" in h_es.list_nodes():
                self.structure = Atoms().from_hdf(h_es)
            nodes = h_es.list_nodes()
            self.kpoint_list = h_es["k_points"]
            self.kpoint_weights = h_es["k_point_weights"]
            self.eigenvalue_matrix = h_es["eigenvalue_matrix"]
            self.occupancy_matrix = h_es["occupancy_matrix"]
            try:
                self.dos_energies = h_es["dos_energies"]
                self.dos_densities = h_es["dos_densities"]
                self.dos_idensities = h_es["dos_idensities"]
            except ValueError:
                pass
            if "fermi_level" in nodes:
                self.efermi = h_es["fermi_level"]
            if "grand_dos_matrix" in nodes:
                self.grand_dos_matrix = h_es["grand_dos_matrix"]
            if "resolved_densities" in nodes:
                self.resolved_densities = h_es["resolved_densities"]
        self.generate_from_matrices()
Example #19
0
 def test_pbc(self):
     CO = Atoms("CO",
                positions=[[0, 0, 0], [0, 0, 2]],
                cell=[[1, 0, 0], [0, 1, 0], [0, 0, 1]],
                pbc=[True, True, True])
     self.assertTrue((CO.pbc == np.array([True, True, True])).all())
     CO.set_pbc((True, True, False))
Example #20
0
 def _get_voronoi_vertices(self):
     cell = 2.2 * np.identity(3)
     Al = Atoms('AlAl',
                scaled_positions=[(0, 0, 0), (0.5, 0.5, 0.5)],
                cell=cell)
     pos, box = Al._get_voronoi_vertices()
     self.assertEqual(len(pos), 14)
Example #21
0
 def test_structure_atomic(self):
     atoms = Atoms("Fe1", positions=np.zeros((1, 3)), cell=np.eye(3))
     lmp_structure = LammpsStructure()
     lmp_structure._el_eam_lst = ["Fe"]
     lmp_structure.structure = atoms
     self.assertEqual(
         lmp_structure._dataset["Value"],
         [
             "Start File for LAMMPS",
             "1 atoms",
             "1 atom types",
             "",
             "0. 1.000000000000000 xlo xhi",
             "0. 1.000000000000000 ylo yhi",
             "0. 1.000000000000000 zlo zhi",
             "",
             "Masses",
             "",
             "1 55.845000",
             "",
             "Atoms",
             "",
             "1 1 0.000000000000000 0.000000000000000 0.000000000000000",
             "",
         ],
     )
Example #22
0
 def test_selective_dynamics(self):
     atoms = Atoms("Fe8", positions=np.zeros((8, 3)), cell=np.eye(3))
     atoms.add_tag(selective_dynamics=[True, True, True])
     self.job.structure = atoms
     self.job._set_selective_dynamics()
     self.assertFalse(
         "group" in self.job.input.control._dataset["Parameter"])
     atoms.add_tag(selective_dynamics=None)
     atoms.selective_dynamics[1] = [True, True, False]
     atoms.selective_dynamics[2] = [True, False, True]
     atoms.selective_dynamics[3] = [False, True, True]
     atoms.selective_dynamics[4] = [False, True, False]
     atoms.selective_dynamics[5] = [False, False, True]
     atoms.selective_dynamics[6] = [True, False, False]
     atoms.selective_dynamics[7] = [False, False, False]
     self.job.structure = atoms
     self.job._set_selective_dynamics()
     self.assertTrue("group___constraintx" in
                     self.job.input.control._dataset["Parameter"])
     self.assertTrue("group___constrainty" in
                     self.job.input.control._dataset["Parameter"])
     self.assertTrue("group___constraintz" in
                     self.job.input.control._dataset["Parameter"])
     self.assertTrue("group___constraintxy" in
                     self.job.input.control._dataset["Parameter"])
     self.assertTrue("group___constraintyz" in
                     self.job.input.control._dataset["Parameter"])
     self.assertTrue("group___constraintxz" in
                     self.job.input.control._dataset["Parameter"])
     self.assertTrue("group___constraintxyz" in
                     self.job.input.control._dataset["Parameter"])
    def get_structure(self, job_specifier, iteration_step=-1, wrap_atoms=True):
        """
        Gets the structure from a given iteration step of the simulation (MD/ionic relaxation). For static calculations
        there is only one ionic iteration step
        Args:
            job_specifier (str, int): name of the job or job ID
            iteration_step (int): Step for which the structure is requested
            wrap_atoms (bool): True if the atoms are to be wrapped back into the unit cell

        Returns:
            atomistics.structure.atoms.Atoms object
        """
        job = self.inspect(job_specifier)
        snapshot = Atoms().from_hdf(job["input"], "structure")
        if "output" in job.project_hdf5.list_groups() and iteration_step != 0:
            snapshot.cell = job.get("output/generic/cells")[iteration_step]
            snapshot.positions = job.get("output/generic/positions")[iteration_step]
            if "indices" in job.get("output/generic").list_nodes():
                snapshot.indices = job.get("output/generic/indices")[iteration_step]
            if (
                "dft" in job["output/generic"].list_groups()
                and "atom_spins" in job["output/generic/dft"].list_nodes()
            ):
                snapshot.set_initial_magnetic_moments(
                    job.get("output/generic/dft/atom_spins")[iteration_step]
                )
        if wrap_atoms:
            return snapshot.center_coordinates_in_unit_cell()
        else:
            return snapshot
Example #24
0
 def test_get_symmetry_dataset(self):
     cell = 2.2 * np.identity(3)
     Al_sc = Atoms('AlAl',
                   scaled_positions=[(0, 0, 0), (0.5, 0.5, 0.5)],
                   cell=cell)
     Al_sc.set_repeat([2, 2, 2])
     self.assertEqual(Al_sc.get_symmetry_dataset()['number'], 229)
Example #25
0
    def test_potential_check(self):
        """
        Verifies that job.potential accepts only potentials that contain the
        species in the set structure.
        """

        self.job.structure = Atoms("Al1", positions=[3 * [0]], cell=np.eye(3))
        with self.assertRaises(ValueError):
            self.job.potential = "Fe_C_Becquart_eam"

        potential = pd.DataFrame({
            'Name': ['Fe Morse'],
            'Filename': [[]],
            'Model': ['Morse'],
            'Species': [['Fe']],
            'Config': [[
                'atom_style full\n',
                'pair_coeff 1 2 morse 0.019623 1.8860 3.32833\n'
            ]]
        })

        with self.assertRaises(ValueError):
            self.job.potential = potential

        potential['Species'][0][0] = 'Al'
        self.job.potential = potential  # shouldn't raise ValueError
Example #26
0
 def test_new_array(self):
     pos, cell = generate_fcc_lattice()
     basis = Atoms(symbols='Al', positions=pos, cell=cell)
     basis.set_repeat([10, 10, 10])
     spins = np.ones(len(basis))
     basis.new_array(name="spins", a=spins)
     self.assertTrue(np.array_equal(basis.arrays['spins'], spins))
Example #27
0
 def _structure_from_hdf(self):
     if (
         "structure" in self.project_hdf5["input"].list_groups()
         and self._generic_input["structure"] == "atoms"
     ):
         with self.project_hdf5.open("input") as hdf5_input:
             self.structure = Atoms().from_hdf(hdf5_input)
Example #28
0
    def get_structure(self, job_specifier, iteration_step=-1):
        """
        Gets the structure from a given iteration step of the simulation (MD/ionic relaxation). For static calculations
        there is only one ionic iteration step
        Args:
            job_specifier (str, int): name of the job or job ID
            iteration_step (int): Step for which the structure is requested

        Returns:
            atomistics.structure.atoms.Atoms object
        """
        job = self.inspect(job_specifier)
        snapshot = Atoms().from_hdf(job['input'], 'structure')
        if 'output' in job.project_hdf5.list_groups() and iteration_step != 0:
            snapshot.cell = job.get("output/generic/cells")[iteration_step]
            snapshot.positions = job.get(
                "output/generic/positions")[iteration_step]
            if 'indices' in job.get('output/generic').list_nodes():
                snapshot.indices = job.get(
                    "output/generic/indices")[iteration_step]
            if 'dft' in job['output/generic'].list_groups(
            ) and 'atom_spins' in job['output/generic/dft'].list_nodes():
                snapshot.set_initial_magnetic_moments(
                    job.get("output/generic/dft/atom_spins")[iteration_step])
        return snapshot
Example #29
0
    def read_cube_file(self, filename="cube_file.cube"):
        """
        Generate data from a CUBE file

        Args:
            filename (str): Filename to parse

        """
        with open(filename, "r") as f:
            lines = f.readlines()
            n_atoms = int(lines[2].strip().split()[0])
            cell_data = np.genfromtxt(lines[3:6])
            cell_grid = cell_data[:, 1:]
            grid_shape = np.array(cell_data[:, 0], dtype=int)
            # total_data = np.zeros(grid_shape)
            cell = np.array(
                [val * grid_shape[i] for i, val in enumerate(cell_grid)])
            pos_data = np.genfromtxt(lines[6:n_atoms + 6])
            if n_atoms == 1:
                pos_data = np.array([pos_data])
            atomic_numbers = np.array(pos_data[:, 0], dtype=int)
            positions = pos_data[:, 2:]
            self._atoms = Atoms(numbers=atomic_numbers,
                                positions=positions,
                                cell=cell)
            end_int = n_atoms + 6 + int(np.prod(grid_shape) / 6)
            data = np.genfromtxt(lines[n_atoms + 6:end_int])
            data_flatten = np.hstack(data)
            if np.prod(grid_shape) % 6 > 0:
                data_flatten = np.append(
                    data_flatten,
                    [float(val) for val in lines[end_int].split()])
            n_x, n_y, n_z = grid_shape
            self._total_data = data_flatten.reshape((n_x, n_y, n_z))
Example #30
0
    def get_structure(self, iteration_step=-1):
        """
        Gets the structure from a given iteration step of the simulation (MD/ionic relaxation). For static calculations
        there is only one ionic iteration step
        Args:
            iteration_step (int): Step for which the structure is requested

        Returns:
            atomistics.structure.atoms.Atoms object
        """
        if (self.server.run_mode.interactive or self.server.run_mode.interactive_non_modal):
            # Warning: We only copy symbols, positions and cell information - no tags.
            if len(self.output.indices) != 0:
                indices = self.output.indices[iteration_step]
            else:
                indices = self.get("output/generic/indices")
            if len(self._interactive_species_lst) == 0:
                el_lst = [el.Abbreviation for el in self.structure.species]
            else:
                el_lst = self._interactive_species_lst.tolist()
            if indices is not None:
                return Atoms(symbols=np.array([el_lst[el] for el in indices]),
                             positions=self.output.positions[iteration_step],
                             cell=self.output.cells[iteration_step])
            else:
                return None
        else:
            if self.get("output/generic/cells") is not None and len(self.get("output/generic/cells")) != 0:
                return super(GenericInteractive, self).get_structure(iteration_step=iteration_step)
            else:
                return None