def test_average(self): a_0 = 2.855312531 atoms = Atoms("Fe2", positions=[3 * [0], 3 * [0.5 * a_0]], cell=a_0 * np.eye(3)) self.job_average.structure = atoms self.job_average.potential = 'Fe_C_Becquart_eam' file_directory = os.path.join(self.execution_path, "..", "static", "lammps_test_files") self.job_average.collect_dump_file(cwd=file_directory, file_name="dump_average.out") self.job_average.collect_output_log(cwd=file_directory, file_name="log_average.lammps")
def phonopy_to_atoms(ph_atoms): """ Convert Phonopy Atoms to ASE-like Atoms Args: ph_atoms: Phonopy Atoms object Returns: ASE-like Atoms object """ return Atoms(symbols=list(ph_atoms.get_chemical_symbols()), positions=list(ph_atoms.get_positions()), cell=list(ph_atoms.get_cell()), pbc=True)
def test_write_cube(self): cd_obj = VaspVolumetricData() file_name = os.path.join( self.execution_path, "../../static/vasp_test_files/chgcar_samples/CHGCAR_no_spin", ) cd_obj.from_file(filename=file_name) data_before = cd_obj.total_data.copy() cd_obj.write_cube_file( filename=os.path.join(self.execution_path, "chgcar.cube") ) cd_obj.read_cube_file(filename=os.path.join(self.execution_path, "chgcar.cube")) data_after = cd_obj.total_data.copy() self.assertTrue(np.allclose(data_before, data_after)) n_x, n_y, n_z = (3, 4, 2) random_array = np.random.rand(n_x, n_y, n_z) rd_obj = VolumetricData() rd_obj.atoms = Atoms("H2O", cell=np.eye(3) * 10, positions=np.eye(3)) rd_obj.total_data = random_array rd_obj.write_vasp_volumetric( filename=os.path.join(self.execution_path, "random_CHGCAR") ) cd_obj.from_file(filename=os.path.join(self.execution_path, "random_CHGCAR")) self.assertTrue( np.allclose( cd_obj.total_data * cd_obj.atoms.get_volume(), rd_obj.total_data ) ) file_name = os.path.join( self.execution_path, "../../static/vasp_test_files/chgcar_samples/CHGCAR_water", ) cd_obj = VaspVolumetricData() cd_obj.from_file(file_name) data_before = cd_obj.total_data.copy() cd_obj.write_cube_file( filename=os.path.join(self.execution_path, "chgcar.cube") ) cd_obj.read_cube_file(filename=os.path.join(self.execution_path, "chgcar.cube")) self.assertIsNotNone(cd_obj.atoms) data_after = cd_obj.total_data.copy() self.assertTrue(np.allclose(data_before, data_after)) data_before = cd_obj.total_data.copy() cd_obj.write_vasp_volumetric( filename=os.path.join(self.execution_path, "random_CHGCAR") ) cd_obj.from_file( filename=os.path.join(self.execution_path, "random_CHGCAR"), normalize=False ) data_after = cd_obj.total_data.copy() self.assertTrue(np.allclose(data_before, data_after))
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)
def get_structure(self, 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: iteration_step (int): Step for which the structure is requested wrap_atoms (bool): 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 self.output.indices is not None and len( self.output.indices) != 0: indices = self.output.indices[iteration_step] else: return None 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: if wrap_atoms: positions = self.output.positions[iteration_step] else: if len(self.output.unwrapped_positions) > max( [iteration_step, 0]): positions = self.output.unwrapped_positions[ iteration_step] else: positions = ( self.output.positions[iteration_step] + self.output.total_displacements[iteration_step]) atoms = Atoms( symbols=np.array([el_lst[el] for el in indices]), positions=positions, cell=self.output.cells[iteration_step], pbc=self.structure.pbc, ) # Update indicies to match the indicies in the cache. atoms.set_species( [self._periodic_table.element(el) for el in el_lst]) atoms.indices = indices if wrap_atoms: atoms = atoms.center_coordinates_in_unit_cell() return atoms 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, wrap_atoms=wrap_atoms) else: return None
def setUpClass(cls): cls.file_location = os.path.dirname(os.path.abspath(__file__)) poscar_directory = os.path.join( cls.file_location, "../static/vasp_test_files/poscar_samples") file_list = os.listdir(poscar_directory) cls.file_list = [ posixpath.join(poscar_directory, f) for f in file_list ] atom_numbers = np.random.randint(low=1, high=99, size=(1, 3)).flatten() cell = 10.0 * np.eye(3) pos = 0.5 * np.ones((3, 3)) - 0.5 * np.eye(3) cls.structure = Atoms(numbers=atom_numbers, cell=cell, positions=pos) cls.structure.repeat([2, 2, 2]) cls.element_list = cls.structure.get_chemical_elements()
def setUpClass(cls): cls.file_location = os.path.dirname(os.path.abspath(__file__)) cls.project = Project( os.path.join(cls.file_location, "../static/sphinx")) cls.sphinx = cls.project.create_job("Sphinx", "job_sphinx") cls.sphinx.structure = Atoms(elements=['Fe'] * 2, scaled_positions=[3 * [0.0], 3 * [0.5]], cell=2.6 * np.eye(3)) cls.sphinx.structure.set_initial_magnetic_moments(np.ones(2)) cls.current_dir = os.path.abspath(os.getcwd()) cls.sphinx._create_working_directory() cls.sphinx.write_input() cls.sphinx.version = "2.6" cls.sphinx.server.run_mode.interactive = True
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(HessianJob, self).from_hdf(hdf=hdf, group_name=group_name) with self.project_hdf5.open("input") as hdf5_input: if "structure" in hdf5_input.list_groups(): self._reference_structure = Atoms().from_hdf(hdf5_input) if "force_constants" in hdf5_input.list_nodes(): self._force_constants = hdf5_input["force_constants"]
def from_hdf(self, hdf=None, group_name=None): """ Restore the StructureListMaster object in the HDF5 File Args: hdf (ProjectHDFio): HDF5 group object - optional group_name (str): HDF5 subgroup name - optional """ super(StructureListMaster, self).from_hdf(hdf=hdf, group_name=group_name) with self.project_hdf5.open("input/structures") as hdf5_input: self._structure_lst = [ Atoms().from_hdf(hdf5_input, group_name) for group_name in sorted(hdf5_input.list_groups()) ]
def test_manip_contcar(self): for f in self.file_list: if "CONTCAR_Mg" in f: struct = read_atoms(f) Mg_indices = struct.select_index("Mg") add_pos = np.zeros_like(struct.positions) max_Mg = np.argmax(struct.positions[Mg_indices, 2]) init_z = struct.positions[max_Mg, 2] add_pos[np.argsort(vasp_sorter(struct))[max_Mg], 2] += 5.0 manip_contcar(filename=f, new_filename="manip_file", add_pos=add_pos) new_struct = read_atoms("manip_file") Mg_indices = new_struct.select_index("Mg") max_Mg = np.argmax(new_struct.positions[Mg_indices, 2]) final_z = new_struct.positions[max_Mg, 2] self.assertEqual(round(final_z - init_z, 3), 5.0) os.remove("manip_file") break positions = np.ones((3, 3)) positions[0] = [5., 5., 5.] positions[1] = [5., 5.7, 5.7] positions[2] = [5., -5.7, -5.7] struct = Atoms(["O", "H", "H"], positions=positions, cell=10. * np.eye(3)) write_poscar(structure=struct, filename="simple_water") add_pos = np.zeros_like(positions) poscar_order = np.argsort(vasp_sorter(struct)) add_pos[poscar_order[struct.select_index("O")], 2] += 3 manip_contcar("simple_water", "simple_water_new", add_pos) new_struct = read_atoms("simple_water_new") self.assertEqual(new_struct.positions[new_struct.select_index("O"), 2], 8) os.remove("simple_water") os.remove("simple_water_new")
def test_calc_md_input(self): # Ensure that defaults match control defaults atoms = Atoms("Fe8", positions=np.zeros((8, 3)), cell=np.eye(3)) self.md_control_job.structure = atoms self.md_control_job.input.control.calc_md() self.md_job.sturcture = atoms self.md_job._prism = UnfoldingPrism(atoms.cell) self.md_job.calc_md() for k in self.job.input.control.keys(): self.assertEqual(self.md_job.input.control[k], self.md_control_job.input.control[k]) # Ensure that pressure inputs are being parsed OK self.md_control_job.calc_md(temperature=300.0, pressure=0) self.assertEqual( self.md_control_job.input.control['fix___ensemble'], "all npt temp 300.0 300.0 0.1 iso 0.0 0.0 1.0" ) self.md_control_job.calc_md(temperature=300.0, pressure=[0.0, 0.0, 0.0]) self.assertEqual( self.md_control_job.input.control['fix___ensemble'], "all npt temp 300.0 300.0 0.1 x 0.0 0.0 1.0 y 0.0 0.0 1.0 z 0.0 0.0 1.0" ) cnv = LAMMPS_UNIT_CONVERSIONS[self.md_control_job.input.control["units"]]["pressure"] self.md_control_job.calc_md(temperature=300.0, pressure=-2.0) m = re.match(r"all +npt +temp +300.0 +300.0 +0.1 +iso +([-\d.]+) +([-\d.]+) 1.0$", self.md_control_job.input.control['fix___ensemble'].strip()) self.assertTrue(m) self.assertTrue(np.isclose(float(m.group(1)), -2.0 * cnv)) self.assertTrue(np.isclose(float(m.group(2)), -2.0 * cnv)) self.md_control_job.calc_md(temperature=300.0, pressure=[1, 2, None, 3., 0., None]) m = re.match(r"all +npt +temp +300.0 +300.0 +0.1 +" r"x +([\d.]+) +([\d.]+) +1.0 +y +([\d.]+) +([\d.]+) +1.0 +" r"xy +([\d.]+) +([\d.]+) +1.0 +xz +([\d.]+) +([\d.]+) +1.0$", self.md_control_job.input.control['fix___ensemble'].strip()) self.assertTrue(m) self.assertTrue(np.isclose(float(m.group(1)), 1.0 * cnv)) self.assertTrue(np.isclose(float(m.group(2)), 1.0 * cnv)) self.assertTrue(np.isclose(float(m.group(3)), 2.0 * cnv)) self.assertTrue(np.isclose(float(m.group(4)), 2.0 * cnv)) self.assertTrue(np.isclose(float(m.group(5)), 3.0 * cnv)) self.assertTrue(np.isclose(float(m.group(6)), 3.0 * cnv)) self.assertTrue(np.isclose(float(m.group(7)), 0.0 * cnv)) self.assertTrue(np.isclose(float(m.group(8)), 0.0 * cnv))
def test_get_global_shells(self): structure = CrystalStructure(elements='Al', lattice_constants=4, bravais_basis='fcc').repeat(2) neigh = structure.get_neighbors() self.assertTrue(np.array_equal(neigh.shells, neigh.get_global_shells())) structure += Atoms(elements='C', positions=[[0, 0, 0.5*4]]) neigh = structure.get_neighbors() self.assertFalse(np.array_equal(neigh.shells, neigh.get_global_shells())) structure = CrystalStructure(elements='Al', lattice_constants=4, bravais_basis='fcc').repeat(2) neigh = structure.get_neighbors() shells = neigh.get_global_shells() structure.positions += 0.01*(np.random.random((len(structure), 3))-0.5) neigh = structure.get_neighbors() self.assertTrue(np.array_equal(shells, neigh.get_global_shells(cluster_by_vecs=True, cluster_by_distances=True))) neigh.reset_clusters() self.assertTrue(np.array_equal(shells, neigh.get_global_shells(cluster_by_vecs=True))) self.assertFalse(np.array_equal(shells, neigh.get_global_shells()))
def setUpClass(cls): cls.execution_path = os.path.dirname(os.path.abspath(__file__)) cls.project = Project(os.path.join(cls.execution_path, "gpaw")) atoms = Atoms("Fe1", positions=np.zeros((1, 3)), cell=np.eye(3)) job = Gpaw( project=ProjectHDFio(project=cls.project, file_name="gpaw"), job_name="gpaw", ) job.structure = atoms job.encut = 300 job.set_kpoints([5, 5, 5]) job.to_hdf() cls.job = Gpaw( project=ProjectHDFio(project=cls.project, file_name="gpaw"), job_name="gpaw", ) cls.job.from_hdf()
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)
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(SxUniqDispl, self).from_hdf(hdf=hdf, group_name=group_name) with self.project_hdf5.open("input") as hdf5_input: self.input.from_hdf(hdf5_input) if "output" in self.project_hdf5.list_groups(): with self.project_hdf5.open("output") as hdf5_output: self.structure_lst = [ Atoms().from_hdf(hdf5_output, group_name) for group_name in hdf5_output.list_groups() ]
def test_set_species(self): pos, cell = generate_fcc_lattice() pse = PeriodicTable() el = pse.element("Pt") basis = Atoms(symbols='Al', positions=pos, cell=cell) self.assertEqual(basis.get_chemical_formula(), "Al") basis.set_species([el]) self.assertEqual(basis.get_chemical_formula(), "Pt") self.assertTrue("Al" not in [sp.Abbreviation] for sp in basis._species_to_index_dict.keys()) self.assertTrue("Pt" in [sp.Abbreviation] for sp in basis._species_to_index_dict.keys())
def test_run(self): basis = Atoms(elements=8 * ['Fe'], scaled_positions=np.random.random(24).reshape(-1, 3), cell=2.6 * np.eye(3)) job = self.project.create_job( self.project.job_type.AtomisticExampleJob, "job_single") job.server.run_mode.interactive = True job.structure = basis artint = self.project.create_job('ART', 'job_art') artint.ref_job = job with self.assertRaises(AssertionError): artint.validate_ready_to_run() artint.input.art_id = 0 artint.input.direction = np.ones(3) artint.run() self.assertEqual(artint.output.forces.shape, (1, 8, 3)) artint.interactive_close() self.assertTrue(artint.status.finished)
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(RandSpg, self).from_hdf(hdf=hdf, group_name=group_name) with self.project_hdf5.open("input") as hdf5_input: self.input.from_hdf(hdf5_input) self._lst_of_struct = [] with self.project_hdf5.open("output/structures") as hdf5_output: structure_names = hdf5_output.list_groups() for group in structure_names: with self.project_hdf5.open("output/structures/" + group) as hdf5_output: self._lst_of_struct.append( [group, Atoms().from_hdf(hdf5_output)])
def test_dump_parser(self): structure = Atoms(elements=2 * ['Fe'], cell=2.78 * np.eye(3), positions=2.78 * np.outer(np.arange(2), np.ones(3)) * 0.5) self.job_dump.structure = structure file_directory = os.path.join(self.execution_path, "..", "static", "lammps_test_files") self.job_dump.collect_dump_file(cwd=file_directory, file_name='dump_static.out') self.assertTrue( np.array_equal(self.job_dump['output/generic/forces'].shape, (1, 2, 3))) self.assertTrue( np.array_equal(self.job_dump['output/generic/positions'].shape, (1, 2, 3))) self.assertTrue( np.array_equal(self.job_dump['output/generic/cells'].shape, (1, 3, 3)))
def test_validate(self): with self.assertRaises(ValueError): self.job_fail.validate_ready_to_run() a_0 = 2.855312531 atoms = Atoms("Fe2", positions=[3 * [0], 3 * [0.5 * a_0]], cell=a_0 * np.eye(3), pbc=False) self.job_fail.structure = atoms # with self.assertRaises(ValueError): # self.job_fail.validate_ready_to_run() self.job_fail.potential = self.job_fail.list_potentials()[-1] self.job_fail.validate_ready_to_run() self.job_fail.structure.positions[0, 0] -= 2.855 with self.assertRaises(ValueError): self.job_fail.validate_ready_to_run() self.job_fail.structure.pbc = True self.job_fail.validate_ready_to_run() self.job_fail.structure.pbc = [True, True, False] self.job_fail.validate_ready_to_run() self.job_fail.structure.pbc = [False, True, True] with self.assertRaises(ValueError): self.job_fail.validate_ready_to_run()
def test_calc_minimize_input(self): # Ensure that defaults match control defaults 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_job.sturcture = atoms self.minimize_job._prism = UnfoldingPrism(atoms.cell) self.minimize_job.calc_minimize() for k in self.job.input.control.keys(): self.assertEqual(self.minimize_job.input.control[k], self.minimize_control_job.input.control[k]) # Ensure that pressure inputs are being parsed OK self.minimize_control_job.calc_minimize(pressure=0) self.assertEqual( self.minimize_control_job.input.control['fix___ensemble'], "all box/relax iso 0.0" ) self.minimize_control_job.calc_minimize(pressure=[0.0, 0.0, 0.0]) self.assertEqual( self.minimize_control_job.input.control['fix___ensemble'], "all box/relax x 0.0 y 0.0 z 0.0 couple none" ) cnv = LAMMPS_UNIT_CONVERSIONS[self.minimize_control_job.input.control["units"]]["pressure"] self.minimize_control_job.calc_minimize(pressure=-2.0) m = re.match(r"all +box/relax +iso +([-\d.]+)$", self.minimize_control_job.input.control['fix___ensemble'].strip()) self.assertTrue(m) self.assertTrue(np.isclose(float(m.group(1)), -2.0 * cnv)) self.minimize_control_job.calc_minimize(pressure=[1, 2, None, 3., 0., None]) m = re.match(r"all +box/relax +x +([\d.]+) +y ([\d.]+) +xy +([\d.]+) +xz +([\d.]+) +couple +none$", self.minimize_control_job.input.control['fix___ensemble'].strip()) self.assertTrue(m) self.assertTrue(np.isclose(float(m.group(1)), 1.0 * cnv)) self.assertTrue(np.isclose(float(m.group(2)), 2.0 * cnv)) self.assertTrue(np.isclose(float(m.group(3)), 3.0 * cnv)) self.assertTrue(np.isclose(float(m.group(4)), 0.0 * cnv))
def test_calc_minimize_input(self): # Ensure that defaults match control defaults atoms = Atoms("Fe", 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_job.sturcture = atoms self.minimize_job.calc_minimize() for k in self.job.input.control.keys(): self.assertEqual(self.minimize_job.input.control[k], self.minimize_control_job.input.control[k]) # Ensure that pressure inputs are being parsed OK self.minimize_control_job.calc_minimize(pressure=0) self.assertEqual( self.minimize_control_job.input.control['fix___ensemble'], "all box/relax x 0.0 y 0.0 z 0.0 couple none") self.minimize_control_job.calc_minimize( pressure=[1, 2, None, 0., 0., None]) self.assertEqual( self.minimize_control_job.input.control['fix___ensemble'], "all box/relax x 10000.0 y 20000.0 xy 0.0 xz 0.0 couple none")
def from_hdf(self, hdf=None, group_name=None): """ Restore the ParameterMaster from an HDF5 file Args: hdf (ProjectHDFio): HDF5 group object - optional group_name (str): HDF5 subgroup name - optional """ super(MapMaster, self).from_hdf(hdf=hdf, group_name=group_name) with self.project_hdf5.open("input") as hdf5_input: if "structures" in hdf5_input.list_groups(): with hdf5_input.open("structures") as hdf5_input_str: self.parameter_list = [ Atoms().from_hdf(hdf5_input_str, group_name) for group_name in sorted(hdf5_input_str.list_groups()) ] else: self.parameter_list = hdf5_input["parameters_list"] function_str = hdf5_input["map_function"] if function_str == "None": self._map_function = None else: self._map_function = get_function_from_string(function_str)
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
def test_dump_parser(self): structure = Atoms( elements=2 * ["Fe"], cell=2.78 * np.eye(3), positions=2.78 * np.outer(np.arange(2), np.ones(3)) * 0.5, ) self.job_dump.structure = structure self.job_dump.potential = self.job_dump.list_potentials()[0] file_directory = os.path.join(self.execution_path, "..", "static", "lammps_test_files") self.job_dump.collect_dump_file(cwd=file_directory, file_name="dump_static.out") self.assertTrue( np.array_equal(self.job_dump["output/generic/forces"].shape, (1, 2, 3))) self.assertTrue( np.array_equal(self.job_dump["output/generic/positions"].shape, (1, 2, 3))) self.assertTrue( np.array_equal(self.job_dump["output/generic/cells"].shape, (1, 3, 3))) self.assertTrue( np.array_equal(self.job_dump["output/generic/indices"].shape, (1, 2)))
def setUpClass(cls): cls.file_location = os.path.dirname(os.path.abspath(__file__)) cls.project = Project( os.path.join(cls.file_location, "hessian_class") ) cls.project.remove_jobs_silently(recursive=True) cls.job = cls.project.create_job( "HessianJob", "job_test_hessian" ) structure = Atoms( positions=[[0, 0, 0], [1, 1, 1]], elements=["Fe", "Fe"], cell=2 * np.eye(3) ) cls.job.set_reference_structure(structure) cls.job.structure.apply_strain(0.01) cls.job.structure.positions[0, 0] = 0.1 cls.job.structure.center_coordinates_in_unit_cell() cls.job.set_force_constants(force_constants=1) cls.job.set_elastic_moduli(bulk_modulus=1, shear_modulus=1) cls.job.server.run_mode.interactive = True cls.job.run() cls.job.structure.positions[0, 1] -= 0.1 cls.job.run() cls.job.structure.positions[0,1] -= 0.1 cls.job.run()
def test_cluster_analysis(self): import random cell = 2.2 * np.identity(3) Al_sc = Atoms(elements=['Al', 'Al'], scaled_positions=[(0, 0, 0), (0.5, 0.5, 0.5)], cell=cell) Al_sc.set_repeat([4, 4, 4]) radius = Al_sc.get_shell_radius() neighbors = Al_sc.get_neighbors(radius=radius, num_neighbors=100, t_vec=False, exclude_self=True) c_Zn = 0.1 pse = PeriodicTable() Zn = pse.element("Zn") random.seed(123456) for _ in range(1): Zn_ind = random.sample(range(len(Al_sc)), int(c_Zn * len(Al_sc))) # for i_Zn in Zn_ind: # Al_sc.elements[i_Zn] = Zn cluster = Al_sc.cluster_analysis(Zn_ind, neighbors) cluster_len = np.sort([len(v) for k, v in cluster.items()])
def structure(self): if isinstance(self.job, JobPath): return Atoms().from_hdf(self.job, "output/structure") else: return self.job.structure
def from_hdf(self, hdf=None, group_name=None): super(Gaussian, self).from_hdf(hdf=hdf, group_name=group_name) with self.project_hdf5.open("input") as hdf5_input: self.input.from_hdf(hdf5_input) self.structure = Atoms().from_hdf(hdf5_input)
def visualize_MO(self, index, particle_size=0.5, show_bonds=True): ''' Visualize the MO identified by its index. **Arguments** index index of the MO, as listed by print_MO() particle_size size of the atoms for visualization, lower value if orbital is too small to see show_bonds connect atoms or not **Notes** This function should always be accompanied with the following commands (in a separate cell) view[1].update_surface(isolevel=1, color='blue', opacity=.3) view[2].update_surface(isolevel=-1, color='red', opacity=.3) This makes sure that the bonding and non-bonding MO's are plotted and makes them transparent ''' n_MO = self.get('output/structure/dft/scf_density').shape[0] assert index >= 0 and index < n_MO assert len( self.get('output/structure/numbers') ) < 50 # check whether structure does not become too large for interactive calculation of cube file # print orbital information occ_alpha = int( self.get('output/structure/dft/n_alpha_electrons') > index) occ_beta = int( self.get('output/structure/dft/n_beta_electrons') > index) if self.get('output/structure/dft/beta_orbital_e') is None: orbital_energy = self.get( 'output/structure/dft/alpha_orbital_e')[index] print("Orbital energy = {:>10.5f} \t Occ. = {}".format( orbital_energy, occ_alpha + occ_beta)) else: orbital_energy = [ self.get('output/structure/dft/alpha_orbital_e')[index], self.get('output/structure/dft/beta_orbital_e')[index] ] print( "Orbital energies (alpha,beta) = {:>10.5f},{:>10.5f} \t Occ. = {},{}" .format(orbital_energy[0], orbital_energy[1], occ_alpha, occ_beta)) # make cube file path = self.path + '_hdf5/' + self.name + '/input' out = subprocess.check_output( "ml load Gaussian/g16_E.01-intel-2019a;module use /apps/gent/CO7/haswell-ib/modules/all; cubegen 1 MO={} {}.fchk {}.cube" .format(index + 1, path, path), stderr=subprocess.STDOUT, universal_newlines=True, shell=True, ) # visualize cube file try: import nglview except ImportError: raise ImportError( "The animate_nma_mode() function requires the package nglview to be installed" ) atom_numbers = [] atom_positions = [] with open('{}.cube'.format(path), 'r') as f: for i in range(2): f.readline() n_atoms = int(f.readline().split()[0][1:]) for i in range(3): f.readline() for n in range(n_atoms): line = f.readline().split() atom_numbers.append(int(line[0])) atom_positions.append( np.array([float(m) for m in line[2:]]) / angstrom) structure = Atoms(numbers=np.array(atom_numbers), positions=atom_positions) view = nglview.show_ase(structure) if not show_bonds: view.add_spacefill(radius_type='vdw', scale=0.5, radius=particle_size) view.remove_ball_and_stick() else: view.add_ball_and_stick() view.add_component('{}.cube'.format(path)) view.add_component('{}.cube'.format(path)) return view