Exemplo n.º 1
0
 def test_init(self):
     mol = Molecule(["C", "H", "H", "H", "H"], self.coords)
     gau = GaussianInput(mol,
                         charge=1,
                         route_parameters={
                             "SP": "",
                             "SCF": "Tight"
                         })
     self.assertEqual(gau.spin_multiplicity, 2)
     mol = Molecule(["C", "H", "H", "H", "H"], self.coords, charge=-1)
     gau = GaussianInput(mol, route_parameters={"SP": "", "SCF": "Tight"})
     self.assertEqual(gau.spin_multiplicity, 2)
     self.assertRaises(ValueError, GaussianInput, mol, spin_multiplicity=1)
Exemplo n.º 2
0
    def setUpClass(cls):
        # head molecule
        cls.peo_head = Molecule.from_file(
            os.path.join(test_dir, "peo_head.xyz"))
        charges = [
            -0.1187, 0.0861, 0.0861, 0.0861, -0.2792, -0.0326, 0.0861, 0.0861
        ]
        cls.peo_head.add_site_property("charge", charges)
        s_head = 0
        s_tail = 5

        # chain molecule
        cls.peo_bulk = Molecule.from_file(
            os.path.join(test_dir, "peo_bulk.xyz"))
        charges = [-0.0326, 0.0861, 0.0861, -0.2792, -0.0326, 0.0861, 0.0861]
        cls.peo_bulk.add_site_property("charge", charges)
        head = 0
        tail = 4

        # terminal molecule
        cls.peo_tail = Molecule.from_file(
            os.path.join(test_dir, "peo_tail.xyz"))
        charges = [
            -0.0326, 0.0861, 0.0861, -0.2792, -0.1187, 0.0861, 0.0861, 0.0861
        ]
        cls.peo_tail.add_site_property("charge", charges)
        e_head = 0
        e_tail = 4

        cls.n_units = 25
        link_distance = 1.5075

        # create the polymer
        cls.peo_polymer = Polymer(cls.peo_head, s_head, s_tail, cls.peo_bulk,
                                  head, tail, cls.peo_tail, e_head, e_tail,
                                  cls.n_units, link_distance)

        # linear chain
        cls.peo_polymer_linear = Polymer(cls.peo_head,
                                         s_head,
                                         s_tail,
                                         cls.peo_bulk,
                                         head,
                                         tail,
                                         cls.peo_tail,
                                         e_head,
                                         e_tail,
                                         cls.n_units,
                                         link_distance,
                                         linear_chain=True)
Exemplo n.º 3
0
    def convert_obatoms_to_molecule(self,
                                    atoms,
                                    residue_name=None,
                                    site_property="ff_map"):
        """
        Convert list of openbabel atoms to MOlecule.

        Args:
            atoms ([OBAtom]): list of OBAtom objects
            residue_name (str): the key in self.map_residue_to_mol. Usec to
                restore the site properties in the final packed molecule.
            site_property (str): the site property to be restored.

        Returns:
            Molecule object
        """

        restore_site_props = True if residue_name is not None else False

        if restore_site_props and not hasattr(self, "map_residue_to_mol"):
            self._set_residue_map()

        coords = []
        zs = []
        for atm in atoms:
            coords.append(list(atm.coords))
            zs.append(atm.atomicnum)

        mol = Molecule(zs, coords)

        if restore_site_props:

            props = []

            ref = self.map_residue_to_mol[residue_name].copy()

            # sanity check
            assert len(mol) == len(ref)
            assert ref.formula == mol.formula

            # the packed molecules have the atoms in the same order..sigh!
            for i, site in enumerate(mol):
                assert site.specie.symbol == ref[i].specie.symbol
                props.append(getattr(ref[i], site_property))

            mol.add_site_property(site_property, props)

        return mol
Exemplo n.º 4
0
 def test_get_atoms_from_molecule(self):
     m = Molecule.from_file(os.path.join(test_dir, "acetylene.xyz"))
     atoms = aio.AseAtomsAdaptor.get_atoms(m)
     ase_composition = Composition(atoms.get_chemical_formula())
     self.assertEqual(ase_composition, m.composition)
     self.assertTrue(atoms.cell is None or not atoms.cell.any())
     self.assertTrue(atoms.get_pbc() is None or not atoms.get_pbc().any())
Exemplo n.º 5
0
    def fit(self, p: Molecule):
        """Order, rotate and transform all of the matched `p` molecule
        according to the given `threshold`.

        Args:
            p: a `Molecule` object what will be matched with the target one.

        Returns:
            Array of the possible matches where the elements are:
                p_prime: Rotated and translated of the `p` `Molecule` object
                rmsd: Root-mean-square-deviation between `p_prime` and the `target`
        """
        out = []
        for inds in self.permutations(p):
            p_prime = p.copy()
            p_prime._sites = [p_prime[i] for i in inds]

            U, V, rmsd = super().match(p_prime)

            # Rotate and translate matrix `p` onto the target molecule.
            # P' = P * U + V
            for site in p_prime:
                site.coords = np.dot(site.coords, U) + V

            out.append((p_prime, rmsd))

        return out
Exemplo n.º 6
0
def import_Structure(type, config):
	if type == 'xyz':
		molecule = Molecule.from_file(config['filename'])
		lattice = Lattice([config["lattice_parameters"]["vectors"]['i'],config["lattice_parameters"]["vectors"]["j"],config["lattice_parameters"]["vectors"]["k"]])
		return Structure(lattice, generate_atom_list(molecule.species), generate_coordinate_list(molecule))
	else:
		return None 	
Exemplo n.º 7
0
    def run_task(self, fw_spec):

        molecules = self["constituent_molecules"]
        mols_number = self["mols_number"]
        input_filename = self["input_filename"]
        forcefield = self["forcefield"]
        topologies = self["topologies"]

        user_settings = self.get("user_settings", {})
        data_filename = self.get("data_filename",
                                 user_settings.get("data_file", "lammps.data"))
        final_molecule = self["final_molecule"]

        # if the final molecule was generated using packmol
        if fw_spec.get("packed_mol", None):
            final_molecule = fw_spec["packed_mol"]
        elif isinstance(final_molecule, six.string_types):
            final_molecule = Molecule.from_file(final_molecule)

        #molecules, mols_number, final_molecule
        lammps_ff_data = LammpsData.from_ff_and_topologies(
            forcefield, topologies, self["box_size"])

        lammps_input_set = LammpsInputSet.from_file(
            "ff-inputset",
            self["input_file"],
            user_settings=user_settings,
            lammps_data=lammps_ff_data,
            data_filename=data_filename,
            is_forcefield=True)

        lammps_input_set.write_input(input_filename, data_filename)
Exemplo n.º 8
0
 def setUp(self):
     coords = [[0.000000, 0.000000, 0.000000],
               [0.000000, 0.000000, 1.089000],
               [1.026719, 0.000000, -0.363000],
               [-0.513360, -0.889165, -0.363000],
               [-0.513360, 0.889165, -0.363000]]
     self.mol = Molecule(["C", "H", "H", "H", "H"], coords)
Exemplo n.º 9
0
 def setUp(self):
     coords = [
         [0.000000, 0.000000, 0.000000],
         [0.000000, 0.000000, 1.089000],
         [1.026719, 0.000000, -0.363000],
         [-0.513360, -0.889165, -0.363000],
         [-0.513360, 0.889165, -0.363000],
     ]
     self.coords = coords
     mol = Molecule(["C", "H", "H", "H", "H"], coords)
     self.cellin = FiestaInput(
         mol,
         correlation_grid={"dE_grid": u"0.500", "n_grid": u"14"},
         Exc_DFT_option={"rdVxcpsi": u"1"},
         COHSEX_options={
             "eigMethod": u"C",
             "mix_cohsex": u"0.500",
             "nc_cohsex": u"0",
             "nit_cohsex": u"0",
             "nv_cohsex": u"0",
             "resMethod": u"V",
             "scf_cohsex_wf": u"0",
         },
         GW_options={"nc_corr": u"10", "nit_gw": u"3", "nv_corr": u"10"},
         BSE_TDDFT_options={
             "do_bse": u"1",
             "do_tddft": u"0",
             "nc_bse": u"382",
             "nit_bse": u"50",
             "npsi_bse": u"1",
             "nv_bse": u"21",
         },
     )
Exemplo n.º 10
0
 def test_simple_molecule_graph(self):
     mol = Molecule(["C", "H", "O"], [[0, 0, 0], [1, 0, 0], [2, 0, 0]])
     graph = SimpleMolGraph().convert(mol)
     self.assertListEqual(to_list(graph["atom"]), [6, 1, 8])
     self.assertTrue(np.allclose(graph["bond"], [1, 2, 1, 1, 2, 1]))
     self.assertListEqual(to_list(graph["index1"]), [0, 0, 1, 1, 2, 2])
     self.assertListEqual(to_list(graph["index2"]), [1, 2, 0, 2, 0, 1])
Exemplo n.º 11
0
    def get_mol_object(self, id=0):
        """
        make the pymatgen molecule object

        Args:
            id: the index of molecules in the given site

        Returns:
            a molecule object
        """
        coord0 = self.mol.cart_coords.dot(self.orientation.matrix.T)  #
        # Obtain the center in absolute coords
        if id <= len(self.wp.generators):
            op = self.wp.generators[id]
            center_relative = op.operate(self.position)
            center_relative -= np.floor(center_relative)
            #print(center_relative)
            center_absolute = np.dot(center_relative, self.lattice.matrix)
            # Rotate the molecule (Euclidean metric)
            op_m = self.wp.generators_m[id]
            rot = op_m.affine_matrix[0:3][:, 0:3].T
            tau = op_m.affine_matrix[0:3][:, 3]
            tmp = np.dot(coord0, rot) + tau
            # Add absolute center to molecule
            tmp += center_absolute
            return Molecule(self.symbols, tmp)
        else:
            raise ValueError("id is greater than the number of molecules")
Exemplo n.º 12
0
 def setUp(self):
     pymagen_sodium = Molecule(species=['Na'],
                               coords=[[999.0, 999.0, 999.0]],
                               charge=1)
     # noinspection PyProtectedMember
     sodium_obmol = BabelMolAdaptor(pymagen_sodium)._obmol
     acetoxyq_anion_qcout = QcOutput(
         os.path.join(test_dir, "acetoxyq_anion.out"))
     pymatgen_acetoxyq = acetoxyq_anion_qcout.data[0]["molecules"][-1]
     acetoxyq_obmol = BabelMolAdaptor(pymatgen_acetoxyq)._obmol
     tfsi_qcout = QcOutput(os.path.join(test_dir, "tfsi.qcout"))
     pymatgen_tfsi = tfsi_qcout.data[0]["molecules"][-1]
     # noinspection PyProtectedMember
     tfsi_obmol = BabelMolAdaptor(pymatgen_tfsi)._obmol
     fragments = [sodium_obmol, tfsi_obmol]
     nums_fragments = [1, 1]
     self.acetoxyq_natfsi_placer = IonPlacer(acetoxyq_obmol, fragments,
                                             nums_fragments, None)
     rad_util = AtomicRadiusUtils(covalent_radius_scale=3.0,
                                  metal_radius_scale=1.5)
     mol_radius = rad_util.get_radius(acetoxyq_obmol)
     cation_radius = rad_util.get_radius(sodium_obmol)
     anion_radius = rad_util.get_radius(tfsi_obmol)
     mol_coords = IonPlacer.normalize_molecule(acetoxyq_obmol)
     fragments_atom_radius = [cation_radius, anion_radius]
     nums_fragments = [1, 1]
     self.detector = ContactDetector(mol_coords, mol_radius,
                                     fragments_atom_radius, nums_fragments)
Exemplo n.º 13
0
def make_a_mol_entry():
    r"""
    Make a symmetric (fake) molecule with ring.
                O(0)
               / \
              /   \
      H(1)--C(2)--C(3)--H(4)
             |     |
            H(5)  H(6)
    """
    species = ["O", "H", "C", "C", "H", "H", "H"]
    coords = [
        [0.0, 1.0, 0.0],
        [-1.5, 0.0, 0.0],
        [-0.5, 0.0, 0.0],
        [0.5, 0.0, 0.0],
        [1.5, 0.0, 0.0],
        [-0.5, -1.0, 0.0],
        [0.5, -1.0, 0.0],
    ]

    m = Molecule(species, coords)
    entry = MoleculeEntry(m, energy=0.0)

    return entry
Exemplo n.º 14
0
def random_purturbation_index():
    if is_pbc():
       struct=readstructure(crystal=True,molecule=False)
       natom=len(struct)
       d=np.zeros(2,dtype=int)
       while d[0]==d[1]:
           d=np.random.randint(0,natom,2)
       coord=struct.frac_coords
       coord[[d[0], d[1]], :] = coord[[d[1], d[0]], :]
       tmp_struct=Structure(struct.lattice,struct.species,coord)
       fname='swap_'+str(d[0]+1)+'_'+str(d[1]+1)+'.vasp'
       proc_str="Saving data to "+ fname +" File ..."
       procs(proc_str,0,sp='-->>')
       tmp_struct.to(filename=fname,fmt='poscar')
    else:
       struct=readstructure(crystal=False,molecule=True)
      # print(struct)     
       coord=struct.cart_coords
       natom=len(struct)
       d=np.zeros(2,dtype=int)
       while d[0]==d[1]:
           d=np.random.randint(0,natom,2)
       coord[[d[0], d[1]], :] = coord[[d[1], d[0]], :]
       tmp_struct=Molecule(struct.species,coord)
       fname='swap_'+str(d[0]+1)+'_'+str(d[1]+1)+'.xyz'
       proc_str="Saving data to "+ fname +" File ..."
       procs(proc_str,0,sp='-->>')
       tmp_struct.to(filename=fname,fmt='xyz')
    return
Exemplo n.º 15
0
def generate_shell(structs,fnames,center_atom,radius,shell=None,vacuum=15):
    for struct,fname in zip(structs,fnames):
        center_coord=struct[center_atom].coords
        if shell is None:
            sites=struct.get_neighbors_in_shell(center_coord,0,radius)
            file_name="sphere_"+fname+".vasp"
        else:
            sites=struct.get_neighbors_in_shell(center_coord,radius,shell)
            file_name="shell_"+fname+".vasp"
        coords=[site[0].coords for site in sites]
        species=[site[0].specie for site in sites]
        mol=Molecule(coords=coords,species=species)
        max_dist=np.max(mol.distance_matrix)
        a=b=c=max_dist+vacuum
        box_struct=mol.get_boxed_structure(a,b,c)
        box_struct.to(filename=file_name,fmt='poscar')
Exemplo n.º 16
0
    def run_task(self, fw_spec):

        molecules = self["constituent_molecules"]
        mols_number = self["mols_number"]
        input_filename = self["input_filename"]
        forcefield = self["forcefield"]
        topologies = self["topologies"]

        user_settings = self.get("user_settings", {})
        data_filename = self.get("data_filename", user_settings.get("data_file", "lammps.data"))
        final_molecule = self["final_molecule"]

        # if the final molecule was generated using packmol
        if fw_spec.get("packed_mol", None):
            final_molecule = fw_spec["packed_mol"]
        elif isinstance(final_molecule, six.string_types):
            final_molecule = Molecule.from_file(final_molecule)

        #molecules, mols_number, final_molecule
        lammps_ff_data = LammpsData.from_ff_and_topologies(forcefield, topologies, self["box_size"])

        lammps_input_set = LammpsInputSet.from_file("ff-inputset", self["input_file"],
                                                    user_settings=user_settings,
                                                    lammps_data=lammps_ff_data,
                                                    data_filename=data_filename,
                                                    is_forcefield=True)

        lammps_input_set.write_input(input_filename, data_filename)
Exemplo n.º 17
0
    def test__str__(self):
        species = ["C", "O"]
        coords = [[-9.5782000000, 0.6241500000, 0.0000000000],
                  [-7.5827400000, 0.5127000000, -0.0000000000]]
        molecule = Molecule(species=species, coords=coords)
        rem = OrderedDict({
            "jobtype": "opt",
            "method": "wB97M-V",
            "basis": "def2-QZVPPD",
            "max_scf_cycles": "300",
            "gen_scfman": "true"
        })
        str_test = QCInput(molecule=molecule, rem=rem).__str__()
        str_actual = """$molecule
 0 1
 C     -9.5782000000      0.6241500000      0.0000000000
 O     -7.5827400000      0.5127000000     -0.0000000000
$end

$rem
   jobtype = opt
   method = wB97M-V
   basis = def2-QZVPPD
   max_scf_cycles = 300
   gen_scfman = true
$end
"""
        self.assertEqual(str_actual, str_test)
Exemplo n.º 18
0
def parse_symmetry(pos):
    mol = Molecule(['C'] * len(pos), pos)
    try:
        symbol = PointGroupAnalyzer(mol, tolerance=0.1).sch_symbol
    except:
        symbol = 'N/A'
    return symbol
Exemplo n.º 19
0
 def test_init(self):
     inner_charge = np.random.rand(10) - 0.5
     outer_charge = np.random.rand(10) - 0.5
     inner_velo = np.random.rand(10, 3) - 0.5
     outer_velo = np.random.rand(10, 3) - 0.5
     m = Molecule(["H"] * 10,
                  np.random.rand(10, 3) * 100,
                  site_properties={
                      "ff_map": ["D"] * 10,
                      "charge": inner_charge,
                      "velocities": inner_velo
                  })
     # q and v from site properties, while type from species_string
     topo = Topology(sites=m)
     self.assertListEqual(topo.type_by_sites, ["H"] * 10)
     np.testing.assert_array_equal(topo.charges, inner_charge)
     np.testing.assert_array_equal(topo.velocities, inner_velo)
     # q and v from overriding, while type from site property
     topo_override = Topology(sites=m,
                              ff_label="ff_map",
                              charges=outer_charge,
                              velocities=outer_velo)
     self.assertListEqual(topo_override.type_by_sites, ["D"] * 10)
     np.testing.assert_array_equal(topo_override.charges, outer_charge)
     np.testing.assert_array_equal(topo_override.velocities, outer_velo)
     # test using a list of sites instead of SiteCollection
     topo_from_list = Topology(sites=m.sites)
     self.assertListEqual(topo_from_list.type_by_sites, topo.type_by_sites)
     np.testing.assert_array_equal(topo_from_list.charges, topo.charges)
     np.testing.assert_array_equal(topo_from_list.velocities,
                                   topo.velocities)
Exemplo n.º 20
0
    def test_coulomb_matrix(self):
        # flat
        cm = CoulombMatrix(flatten=True)
        df = pd.DataFrame({"s": [self.diamond, self.nacl]})
        with self.assertRaises(NotFittedError):
            df = cm.featurize_dataframe(df, "s")
        df = cm.fit_featurize_dataframe(df, "s")
        labels = cm.feature_labels()
        self.assertListEqual(labels,
                             ["coulomb matrix eig 0", "coulomb matrix eig 1"])
        self.assertArrayAlmostEqual(df[labels].iloc[0], [49.169453, 24.546758],
                                    decimal=5)
        self.assertArrayAlmostEqual(df[labels].iloc[1],
                                    [153.774731, 452.894322],
                                    decimal=5)

        # matrix
        species = ["C", "C", "H", "H"]
        coords = [[0, 0, 0], [0, 0, 1.203], [0, 0, -1.06], [0, 0, 2.263]]
        acetylene = Molecule(species, coords)
        morig = CoulombMatrix(flatten=False).featurize(acetylene)
        mtarget = [[36.858, 15.835391290, 2.995098235, 1.402827813], \
                   [15.835391290, 36.858, 1.4028278132103624, 2.9950982], \
                   [2.9368896127, 1.402827813, 0.5, 0.159279959], \
                   [1.4028278132, 2.995098235, 0.159279959, 0.5]]
        self.assertAlmostEqual(int(np.linalg.norm(morig - np.array(mtarget))),
                               0)
        m = CoulombMatrix(diag_elems=False,
                          flatten=False).featurize(acetylene)[0]
        self.assertAlmostEqual(m[0][0], 0.0)
        self.assertAlmostEqual(m[1][1], 0.0)
        self.assertAlmostEqual(m[2][2], 0.0)
        self.assertAlmostEqual(m[3][3], 0.0)
Exemplo n.º 21
0
    def test_element_stats(self):
        test = ElementStats({'H': [4, 2, 3],
                             'O': [2, 3, 4]},
                            stats=['min', 'max', 'moment:1:10'])
        self.assertEqual(test.transform(['H2O']).shape, (1, 36))

        res = test.transform(['H2O', 'H2O'])
        self.assertEqual(res.shape, (2, 36))

        res2 = test.transform([Composition('H2O'), Composition('H2O')])
        np.testing.assert_allclose(res.values, res2.values)

        dummy_h2o = Molecule(['H', 'H', 'O'], [[-0.5, 0, 0], [0.5, 0, 0], [0, 0, 0]])
        res3 = test.transform([dummy_h2o, dummy_h2o])
        np.testing.assert_allclose(res.values, res3.values)

        stats = ['min', 'max', *['moment:%d:None' % i for i in range(1, 11)]]
        p0_names = ['p0_%s' % i for i in stats]
        p1_names = ['p1_%s' % i for i in stats]
        p2_names = ['p2_%s' % i for i in stats]
        all_names = []
        for i, j, k in zip(p0_names, p1_names, p2_names):
            all_names.extend([i, j, k])

        self.assertListEqual(list(res.columns), all_names)
Exemplo n.º 22
0
    def test_element_stats(self):
        test = ElementStats({
            "H": [4, 2, 3],
            "O": [2, 3, 4]
        },
                            stats=["min", "max", "moment:1:10"])
        self.assertEqual(test.transform(["H2O"]).shape, (1, 36))

        res = test.transform(["H2O", "H2O"])
        self.assertEqual(res.shape, (2, 36))

        res2 = test.transform([Composition("H2O"), Composition("H2O")])
        np.testing.assert_allclose(res.values, res2.values)

        dummy_h2o = Molecule(["H", "H", "O"],
                             [[-0.5, 0, 0], [0.5, 0, 0], [0, 0, 0]])
        res3 = test.transform([dummy_h2o, dummy_h2o])
        np.testing.assert_allclose(res.values, res3.values)

        stats = ["min", "max", *["moment:%d:None" % i for i in range(1, 11)]]
        p0_names = ["p0_%s" % i for i in stats]
        p1_names = ["p1_%s" % i for i in stats]
        p2_names = ["p2_%s" % i for i in stats]
        all_names = []
        for i, j, k in zip(p0_names, p1_names, p2_names):
            all_names.extend([i, j, k])

        self.assertListEqual(list(res.columns), all_names)
Exemplo n.º 23
0
    def run_task(self, fw_spec):

        molecules = self["constituent_molecules"]
        mols_number = self["mols_number"]
        input_filename = self["input_filename"]
        forcefield = self["forcefield"]
        topologies = self["topologies"]

        user_settings = self.get("user_settings", {})
        data_filename = user_settings.get("data_file", "lammps.data")
        final_molecule = self["final_molecule"]
        if isinstance(final_molecule, six.string_types):
            final_molecule = Molecule.from_file(final_molecule)

        lammps_ff_data = LammpsForceFieldData.from_forcefield_and_topology(
            molecules, mols_number, self["box_size"], final_molecule,
            forcefield, topologies)

        lammps_input_set = LammpsInputSet.from_file(
            "forcefield",
            self["input_file"],
            user_settings=user_settings,
            lammps_data=lammps_ff_data,
            data_filename=data_filename,
            is_forcefield=True)

        lammps_input_set.write_input(input_filename, data_filename)
Exemplo n.º 24
0
def create_LiEC_pymatgen_mol():
    """
            O(3) -- Li(6)
            ||
             C(1)
           /   \
          O(0)  O(4)
          |     |
        C(2) --- C(5)



    """
    atoms = ["O", "C", "C", "O", "O", "C", "Li", "H", "H", "H", "H"]
    coords = [
        [0.3103, -1.1776, -0.3722],
        [-0.6822, -0.5086, 0.3490],
        [1.5289, -0.4938, -0.0925],
        [-1.9018, -0.6327, -0.0141],
        [-0.2475, 0.9112, 0.3711],
        [1.1084, 0.9722, -0.0814],
        [-2.0519, 1.1814, -0.2310],
        [2.2514, -0.7288, -0.8736],
        [1.9228, -0.8043, 0.8819],
        [1.1406, 1.4103, -1.0835],
        [1.7022, 1.5801, 0.6038],
    ]
    charge = 0

    m = Molecule(atoms, coords, charge)

    return m
Exemplo n.º 25
0
    def test__str__(self):
        species = ["C", "O"]
        coords = [
            [-9.5782000000, 0.6241500000, 0.0000000000],
            [-7.5827400000, 0.5127000000, -0.0000000000],
        ]
        molecule = Molecule(species=species, coords=coords)
        rem = {
            "jobtype": "opt",
            "method": "wb97m-v",
            "basis": "def2-qzvppd",
            "max_scf_cycles": "300",
            "gen_scfman": "true",
        }
        str_test = QCInput(molecule=molecule, rem=rem).__str__().split("\n")
        str_actual_list = [
            "$molecule",
            " 0 1",
            " C     -9.5782000000      0.6241500000      0.0000000000",
            " O     -7.5827400000      0.5127000000     -0.0000000000",
            "$end",
            "$rem",
            "   job_type = opt",
            "   method = wb97m-v",
            "   basis = def2-qzvppd",
            "   max_scf_cycles = 300",
            "   gen_scfman = true",
            "$end",
        ]

        for i_str in str_actual_list:
            self.assertIn(i_str, str_test)
Exemplo n.º 26
0
 def test_simple_molecule_graph(self):
     mol = Molecule(['C', 'H', 'O'], [[0, 0, 0], [1, 0, 0], [2, 0, 0]])
     graph = SimpleMolGraph().convert(mol)
     self.assertListEqual(graph['atom'], [6, 1, 8])
     self.assertTrue(np.allclose(graph['bond'], [1, 2, 1, 1, 2, 1]))
     self.assertListEqual(graph['index1'], [0, 0, 1, 1, 2, 2])
     self.assertListEqual(graph['index2'], [1, 2, 0, 2, 0, 1])
Exemplo n.º 27
0
 def setUpClass(cls):
     cls.structure = Structure.from_file(
         os.path.join(MODULE_DIR, "cifs", "BaTiO3_mp-2998_computed.cif"))
     cls.molecule = Molecule(["C", "O", "O"],
                             [[0, 0, 0], [-1, 0, 0], [1, 0, 0]])
     cls.mall = MinimumDistanceNNAll(4)
     cls.aapair = AllAtomPairs()
Exemplo n.º 28
0
def get_snap_site_features(d):
    feature = []
    data_filename = "lammps_snap.data"
    input_template = "lammps_snap_template.in"
    input_filename = "lammps_snap.in"
    dump_filename =  "dump.sna"
    log_filename = "log.lammps"

    sbp.check_call(["rm", "-f", input_filename])
    sbp.check_call(["rm", "-f", data_filename])    
    sbp.check_call(["rm", "-f", dump_filename])
    sbp.check_call(["rm", "-f", log_filename])

    structure = Structure.from_dict(d["structure"])
    feature.append(structure[d["absorbing_atom"]].specie.number)
    try:
        mol = Molecule.from_dict(d["cluster"])
    except TypeError:
        atoms = Atoms(structure, d["absorbing_atom"], 10.0)
        mol = atoms.cluster
    logger.info(mol.formula)
    lmp_data = LammpsData.from_structure(mol, [[0,25], [0,25],[0,25]], translate=False)    

    lmp_data.write_file(data_filename)
    el_sorted = sorted(mol.composition, key=lambda x:x.atomic_mass)
    cutoff = ""
    weight = ""
    for i, e in enumerate(el_sorted):
        cutoff += " {}".format(float(e.atomic_radius))
        weight += " {}".format(1.0)
        settings = {
            'data_file': data_filename,
            'rcutfac': 1.4, 
            'rfac0': 0.993630,
            'twojmax': 6.0,
            'cutoff': cutoff,
            'weight': weight,
            'dump_file': dump_filename
        }
    lmp_in = LammpsInput.from_file(input_template, settings)
    lmp_in.write_file(input_filename)
    #try:
    logger.info("Running LAMMPS ... ")
    exit_code = sbp.check_call(["./lmp_serial", "-in", input_filename])
    if exit_code != 0:
        logger.error("lammps run failed")
        raise RuntimeError("lammps run failed")                
    logger.info("Processing LAMMPS outputs ... ")
    lmp_run = LammpsRun(data_filename, dump_filename, log_filename)
    t = list(lmp_run.trajectory[0])
    try:
        assert np.linalg.norm(t[2:5]) <= 1e-6
    except AssertionError:
        logger.info("xyz: {}".format(t[2:5]))
        logger.error("assertion failed: first one not at origin")
        raise
    logger.info("# bispectrum coeffs: {}".format(len(t[5:])))
    feature.extend(t[5:])
    return feature
Exemplo n.º 29
0
 def test_adsorb_both_surfaces(self):
     o = Molecule("O", [[0, 0, 0]])
     adslabs = self.asf_100.adsorb_both_surfaces(o)
     for adslab in adslabs:
         sg = SpacegroupAnalyzer(adslab)
         sites = sorted(adslab, key=lambda site: site.frac_coords[2])
         self.assertTrue(sites[0].species_string == "O")
         self.assertTrue(sites[-1].species_string == "O")
Exemplo n.º 30
0
 def test_adsorb_both_surfaces(self):
     o = Molecule("O", [[0, 0, 0]])
     adslabs = adsorb_both_surfaces(self.slab_dict["111"], o)
     for adslab in adslabs:
         sites = sorted(adslab, key=lambda site: site.frac_coords[2])
         self.assertTrue(sites[0].species_string == "O")
         self.assertTrue(sites[-1].species_string == "O")
         self.assertTrue(adslab.is_symmetric())
Exemplo n.º 31
0
    def test_apply_transformation(self):
        co = Molecule(["C", "O"], [[0, 0, 0], [0, 0, 1.23]])
        trans = AddAdsorbateTransformation(co)
        pt = Structure(Lattice.cubic(5), ["Pt"], [[0, 0, 0]])  # fictitious
        slab = SlabTransformation([0, 0, 1], 20, 10).apply_transformation(pt)
        out = trans.apply_transformation(slab)

        self.assertEqual(out.composition.reduced_formula, "Pt4CO")
Exemplo n.º 32
0
    def test_from_multi_jobs_file(self):
        job_list_test = QCInput.from_multi_jobs_file(
            os.path.join(test_dir, "pt_n2_wb97mv_0.0.in"))
        species = [
            "S", "C", "H", "C", "H", "C", "H", "C", "C", "C", "H", "C", "H",
            "C", "H", "S"
        ]
        coords = [[-0.00250959, -0.05817469, -0.02921636],
                  [1.70755408, -0.03033788, -0.01382912],
                  [2.24317221, -0.05215019, 0.92026728],
                  [2.21976393, 0.01718014, -1.27293235],
                  [3.27786220, 0.04082146, -1.48539646],
                  [1.20867399, 0.04478540, -2.27007793],
                  [1.40292257, 0.10591684, -3.33110912],
                  [-0.05341046, 0.01577217, -1.74839343],
                  [-1.32843436, 0.03545064, -2.45531187],
                  [-1.55195156, 0.08743920, -3.80184635],
                  [-0.75245172, 0.10267657, -4.52817967],
                  [-2.93293778, 0.08408786, -4.13352169],
                  [-3.31125108, 0.11340328, -5.14405819],
                  [-3.73173288, 0.02741365, -3.03412864],
                  [-4.80776535, 0.00535688, -2.99564645],
                  [-2.81590978, -0.00516172, -1.58990580]]
        molecule_1_actual = Molecule(species, coords)
        rem_1_actual = {
            "job_type": "opt",
            "method": "wb97m-v",
            "basis": "def2-tzvppd",
            "gen_scfman": "true",
            "geom_opt_max_cycles": "75",
            "max_scf_cycles": "300",
            "scf_algorithm": "diis",
            "scf_guess": "sad",
            "sym_ignore": "true",
            "symmetry": "false",
            "thresh": "14"
        }
        opt_1_actual = {"CONSTRAINT": ["tors 6 8 9 10 0.0"]}
        self.assertEqual(molecule_1_actual, job_list_test[0].molecule)
        self.assertEqual(rem_1_actual, job_list_test[0].rem)
        self.assertEqual(opt_1_actual, job_list_test[0].opt)

        molecule_2_actual = "read"
        rem_2_actual = {
            "job_type": "sp",
            "method": "wb97m-v",
            "basis": "def2-tzvppd",
            "gen_scfman": "true",
            "geom_opt_max_cycles": "75",
            "max_scf_cycles": "300",
            "scf_algorithm": "diis",
            "scf_guess": "read",
            "sym_ignore": "true",
            "symmetry": "false",
            "thresh": "14"
        }
        self.assertEqual(molecule_2_actual, job_list_test[1].molecule)
        self.assertEqual(rem_2_actual, job_list_test[1].rem)
Exemplo n.º 33
0
    def convert_obatoms_to_molecule(self, atoms, residue_name=None, site_property="ff_map"):
        """
        Convert list of openbabel atoms to MOlecule.

        Args:
            atoms ([OBAtom]): list of OBAtom objects
            residue_name (str): the key in self.map_residue_to_mol. Usec to
                restore the site properties in the final packed molecule.
            site_property (str): the site property to be restored.

        Returns:
            Molecule object
        """

        restore_site_props = True if residue_name is not None else False

        if restore_site_props and not hasattr(self, "map_residue_to_mol"):
            self._set_residue_map()

        coords = []
        zs = []
        for atm in atoms:
            coords.append(list(atm.coords))
            zs.append(atm.atomicnum)

        mol = Molecule(zs, coords)

        if restore_site_props:

            props = []

            ref = self.map_residue_to_mol[residue_name].copy()

            # sanity check
            assert len(mol) == len(ref)
            assert ref.formula == mol.formula

            # the packed molecules have the atoms in the same order..sigh!
            for i, site in enumerate(mol):
                assert site.specie.symbol == ref[i].specie.symbol
                props.append(getattr(ref[i], site_property))

            mol.add_site_property(site_property, props)

        return mol
Exemplo n.º 34
0
 def from_dict(cls, d):
     return GaussianInput(mol=Molecule.from_dict(d["molecule"]),
                          functional=d["functional"],
                          basis_set=d["basis_set"],
                          route_parameters=d["route_parameters"],
                          title=d["title"],
                          charge=d["charge"],
                          spin_multiplicity=d["spin_multiplicity"],
                          input_parameters=d["input_parameters"],
                          link0_parameters=d["link0_parameters"])
Exemplo n.º 35
0
 def __init__(self, start_monomer, s_head, s_tail,
              monomer, head, tail,
              end_monomer, e_head, e_tail,
              n_units, link_distance=1.0, linear_chain=False):
     """
     Args:
         start_monomer (Molecule): Starting molecule
         s_head (int): starting atom index of the start_monomer molecule
         s_tail (int): tail atom index of the start_monomer
         monomer (Molecule): The monomer
         head (int): index of the atom in the monomer that forms the head
         tail (int): tail atom index. monomers will be connected from
             tail to head
         end_monomer (Molecule): Terminal molecule
         e_head (int): starting atom index of the end_monomer molecule
         e_tail (int): tail atom index of the end_monomer
         n_units (int): number of monomer units excluding the start and
             terminal molecules
         link_distance (float): distance between consecutive monomers
         linear_chain (bool): linear or random walk polymer chain
     """
     self.start = s_head
     self.end = s_tail
     self.monomer = monomer
     self.n_units = n_units
     self.link_distance = link_distance
     self.linear_chain = linear_chain
     # translate monomers so that head atom is at the origin
     start_monomer.translate_sites(range(len(start_monomer)),
                                   - monomer.cart_coords[s_head])
     monomer.translate_sites(range(len(monomer)),
                             - monomer.cart_coords[head])
     end_monomer.translate_sites(range(len(end_monomer)),
                                 - monomer.cart_coords[e_head])
     self.mon_vector = monomer.cart_coords[tail] - monomer.cart_coords[head]
     self.moves = {1: [1, 0, 0],
                   2: [0, 1, 0],
                   3: [0, 0, 1],
                   4: [-1, 0, 0],
                   5: [0, -1, 0],
                   6: [0, 0, -1]}
     self.prev_move = 1
     # places the start monomer at the beginning of the chain
     self.molecule = start_monomer.copy()
     self.length = 1
     # create the chain
     self._create(self.monomer, self.mon_vector)
     # terminate the chain with the end_monomer
     self.n_units += 1
     end_mon_vector = end_monomer.cart_coords[e_tail] - \
                      end_monomer.cart_coords[e_head]
     self._create(end_monomer, end_mon_vector)
     self.molecule = Molecule.from_sites(self.molecule.sites)
Exemplo n.º 36
0
    def setUpClass(cls):
        # head molecule
        cls.peo_head = Molecule.from_file(os.path.join(test_dir, "peo_head.xyz"))
        charges = [-0.1187, 0.0861, 0.0861, 0.0861, -0.2792, -0.0326, 0.0861, 0.0861]
        cls.peo_head.add_site_property("charge", charges)
        s_head = 0
        s_tail = 5

        # chain molecule
        cls.peo_bulk = Molecule.from_file(os.path.join(test_dir, "peo_bulk.xyz"))
        charges = [-0.0326, 0.0861, 0.0861, -0.2792, -0.0326, 0.0861, 0.0861]
        cls.peo_bulk.add_site_property("charge", charges)
        head = 0
        tail = 4

        # terminal molecule
        cls.peo_tail = Molecule.from_file(os.path.join(test_dir, "peo_tail.xyz"))
        charges = [-0.0326, 0.0861, 0.0861, -0.2792, -0.1187, 0.0861, 0.0861, 0.0861]
        cls.peo_tail.add_site_property("charge", charges)
        e_head = 0
        e_tail = 4

        cls.n_units = 25
        link_distance = 1.5075

        # create the polymer
        cls.peo_polymer = Polymer(cls.peo_head, s_head, s_tail,
                                  cls.peo_bulk, head, tail,
                                  cls.peo_tail, e_head, e_tail,
                                  cls.n_units, link_distance)

        # linear chain
        cls.peo_polymer_linear = Polymer(cls.peo_head, s_head, s_tail,
                                         cls.peo_bulk, head, tail,
                                         cls.peo_tail, e_head, e_tail,
                                         cls.n_units, link_distance, linear_chain=True)
Exemplo n.º 37
0
    def from_dict(d):
        a = d["about"]
        dec = MontyDecoder()

        created_at = dec.process_decoded(a["created_at"]) if "created_at" in a \
            else None
        data = {k: v for k, v in d["about"].items()
                if k.startswith("_")}
        data = dec.process_decoded(data)

        structure = Structure.from_dict(d) if "lattice" in d \
            else Molecule.from_dict(d)
        return MPStructureNL(structure, a["authors"],
                             projects=a.get("projects", None),
                             references=a.get("references", ""),
                             remarks=a.get("remarks", None), data=data,
                             history=a.get("history", None),
                             created_at=created_at)
Exemplo n.º 38
0
 def setUpClass(cls):
     ethanol_coords = [[0.00720, -0.56870, 0.00000],
                       [-1.28540, 0.24990, 0.00000],
                       [1.13040, 0.31470, 0.00000],
                       [0.03920, -1.19720, 0.89000],
                       [0.03920, -1.19720, -0.89000],
                       [-1.31750, 0.87840, 0.89000],
                       [-1.31750, 0.87840, -0.89000],
                       [-2.14220, -0.42390, -0.00000],
                       [1.98570, -0.13650, -0.00000]]
     water_coords = [[9.626, 6.787, 12.673],
                     [9.626, 8.420, 12.673],
                     [10.203, 7.604, 12.673]]
     cls.ethanol_atoms = ["C", "C", "O", "H", "H", "H", "H", "H", "H"]
     cls.water_atoms = ["H", "H", "O"]
     ethanol = Molecule(cls.ethanol_atoms, ethanol_coords)
     water = Molecule(cls.water_atoms, water_coords)
     cls.mols = [ethanol, water]
     cls.cocktail = Molecule.from_file(
         os.path.join(test_dir, "cocktail.xyz"))
     cls.packmol_config = [{"number": 1}, {"number": 15}]
Exemplo n.º 39
0
    def __init__(self, sites, ff_label=None, charges=None, velocities=None,
                 topologies=None):
        """

        Args:
            sites ([Site] or SiteCollection): A group of sites in a
                list or as a Molecule/Structure.
            ff_label (str): Site property key for labeling atoms of
                different types. Default to None, i.e., use
                site.species_string.
            charges ([q, ...]): Charge of each site in a (n,)
                array/list, where n is the No. of sites. Default to
                None, i.e., search site property for charges.
            velocities ([[vx, vy, vz], ...]): Velocity of each site in
                a (n, 3) array/list, where n is the No. of sites.
                Default to None, i.e., search site property for
                velocities.
            topologies (dict): Bonds, angles, dihedrals and improper
                dihedrals defined by site indices. Default to None,
                i.e., no additional topology. All four valid keys
                listed below are optional.
                {
                    "Bonds": [[i, j], ...],
                    "Angles": [[i, j, k], ...],
                    "Dihedrals": [[i, j, k, l], ...],
                    "Impropers": [[i, j, k, l], ...]
                }

        """
        if not isinstance(sites, (Molecule, Structure)):
            sites = Molecule.from_sites(sites)

        if ff_label:
            type_by_sites = sites.site_properties.get(ff_label)
        else:
            type_by_sites = [site.specie.symbol for site in sites]
        # search for site property if not override
        if charges is None:
            charges = sites.site_properties.get("charge")
        if velocities is None:
            velocities = sites.site_properties.get("velocities")
        # validate shape
        if charges is not None:
            charge_arr = np.array(charges)
            assert charge_arr.shape == (len(sites),),\
                "Wrong format for charges"
            charges = charge_arr.tolist()
        if velocities is not None:
            velocities_arr = np.array(velocities)
            assert velocities_arr.shape == (len(sites), 3), \
                "Wrong format for velocities"
            velocities = velocities_arr.tolist()

        if topologies:
            topologies = {k: v for k, v in topologies.items()
                          if k in SECTION_KEYWORDS["topology"]}

        self.sites = sites
        self.ff_label = ff_label
        self.charges = charges
        self.velocities = velocities
        self.topologies = topologies
        self.type_by_sites = type_by_sites
        self.species = set(type_by_sites)
Exemplo n.º 40
0
 def setUp(self):
     self.benzene = Molecule.from_file(os.path.join(test_dir, "benzene.xyz"))
     self.acetylene = Molecule.from_file(os.path.join(test_dir, "acetylene.xyz"))