def MakesGauInputs(mol_file, dihed_atoms_file, w, num_conform=19):
    """
    Creates Gaussian input files in its own folder for mol_file structues that
    freezes the central angle at iterations of 180/num_conform degrees. This
    function requires Gaussian output file of molecule in question and file
    with dihedral atoms to be in the current working directory.
    """

    molecule_name = mol_file.split('/')[-1][:-12]
    mol_pymat = Molecule.from_file(mol_file)
    molecule = pmgmol_to_rdmol(mol_pymat)[0]

    with open(dihed_atoms_file, 'r') as fn:
        data = fn.readlines()
        dihedral1 = data[0].split(',')[0]
        dihedral2 = data[0].split(',')[1]

    d1atom1_num = int(dihedral1.split()[0])
    d1atom2_num = int(dihedral1.split()[1])
    d1atom3_num = int(dihedral1.split()[2])
    d1atom4_num = int(dihedral1.split()[3])

    phi = np.linspace(start=0, stop=180, num=num_conform)
    for P in phi:
        dir_name = "{}/{}_{:.0f}deg/".format(os.getcwd(), molecule_name, P)
        os.mkdir(dir_name)
        file_name = "{}/{}_{:.0f}deg".format(dir_name, molecule_name, P)

        SetDihedralDeg(molecule.GetConformer(), d1atom1_num, d1atom2_num,
                       d1atom3_num, d1atom4_num, P)
        with open(dir_name + "temp.xyz", 'w+') as fout:
            fout.write(str(MolToXYZBlock(molecule)))
        mol = Molecule.from_file(dir_name + 'temp.xyz')
        os.remove(dir_name + 'temp.xyz')
        gau = GaussianInput(mol=mol,
                            charge=0,
                            spin_multiplicity=1,
                            functional='uLC-wPBE',
                            basis_set='cc-pVDZ',
                            route_parameters={
                                "iop(3/107={}, 3/108={})".format(w, w): "",
                                "opt": "modredundant"
                            },
                            link0_parameters={
                                '%mem': '5GB',
                                '%chk':
                                '{}.chk'.format(file_name.split('/')[-1])
                            })
        gjf_file = gau.write_file(dir_name + 'temp.gjf')

        with open(dir_name + 'temp.gjf') as temp:
            lines = temp.readlines()
        os.remove(dir_name + 'temp.gjf')
        with open(file_name + '.gjf', 'w') as gjf:
            gjf.writelines([item for item in lines[:-2]])
            gjf.write("D * {} {} * F\n\n".format(d1atom2_num + 1,
                                                 d1atom3_num + 1))

    print(
        "Torsion Gaussian input files for {} finsihed!".format(molecule_name))
    def setUpClass(cls):

        cls.pt_mol = Molecule.from_file(
            os.path.join(module_dir, "..", "..", "test_files",
                         "pt_gs_wb97mv_tz_initial.xyz"))
        cls.pt_rot_90_mol = Molecule.from_file(
            os.path.join(module_dir, "..", "..", "test_files",
                         "pt_rotated_90.0.xyz"))
Exemplo n.º 3
0
    def test_random_seed(self, water, ethanol):
        """
        Confirm that seed = -1 generates random structures
        while seed = 1 is deterministic
        """
        # deterministic output
        with tempfile.TemporaryDirectory() as scratch_dir:
            pw = PackmolWrapper(
                scratch_dir,
                molecules=[
                    {
                        "name": "water",
                        "number": 10,
                        "coords": water
                    },
                    {
                        "name": "ethanol",
                        "number": 20,
                        "coords": ethanol
                    },
                ],
                seed=1,
                inputfile="input.in",
                outputfile="output.xyz",
            )
            pw.make_packmol_input()
            pw.run_packmol()
            out1 = Molecule.from_file(os.path.join(scratch_dir, "output.xyz"))
            pw.run_packmol()
            out2 = Molecule.from_file(os.path.join(scratch_dir, "output.xyz"))
            assert np.array_equal(out1.cart_coords, out2.cart_coords)

        # randomly generated structures
        with tempfile.TemporaryDirectory() as scratch_dir:
            pw = PackmolWrapper(
                scratch_dir,
                molecules=[
                    {
                        "name": "water",
                        "number": 10,
                        "coords": water
                    },
                    {
                        "name": "ethanol",
                        "number": 20,
                        "coords": ethanol
                    },
                ],
                seed=-1,
                inputfile="input.in",
                outputfile="output.xyz",
            )
            pw.make_packmol_input()
            pw.run_packmol()
            out1 = Molecule.from_file(os.path.join(scratch_dir, "output.xyz"))
            pw.run_packmol()
            out2 = Molecule.from_file(os.path.join(scratch_dir, "output.xyz"))
            assert not np.array_equal(out1.cart_coords, out2.cart_coords)
Exemplo n.º 4
0
    def test_random_seed(self, water, ethanol):
        """
        Confirm that seed = -1 generates random structures
        while seed = 1 is deterministic
        """
        mm = MoleculeMatcher()

        # deterministic output
        with tempfile.TemporaryDirectory() as scratch_dir:
            pw = PackmolBoxGen(
                seed=1,
                inputfile="input.in",
                outputfile="output.xyz",
            ).get_input_set(
                # scratch_dir,
                molecules=[
                    {
                        "name": "water",
                        "number": 10,
                        "coords": water
                    },
                    {
                        "name": "ethanol",
                        "number": 20,
                        "coords": ethanol
                    },
                ], )
            pw.write_input(scratch_dir)
            pw.run(scratch_dir)
            out1 = Molecule.from_file(os.path.join(scratch_dir, "output.xyz"))
            pw.run(scratch_dir)
            out2 = Molecule.from_file(os.path.join(scratch_dir, "output.xyz"))
            assert mm.fit(out1, out2)

        # randomly generated structures
        with tempfile.TemporaryDirectory() as scratch_dir:
            pw = PackmolBoxGen(
                seed=-1,
                inputfile="input.in",
                outputfile="output.xyz",
            ).get_input_set(molecules=[
                {
                    "name": "water",
                    "number": 10,
                    "coords": water
                },
                {
                    "name": "ethanol",
                    "number": 20,
                    "coords": ethanol
                },
            ], )
            pw.write_input(scratch_dir)
            pw.run(scratch_dir)
            out1 = Molecule.from_file(os.path.join(scratch_dir, "output.xyz"))
            pw.run(scratch_dir)
            out2 = Molecule.from_file(os.path.join(scratch_dir, "output.xyz"))
            assert not mm.fit(out1, out2)
Exemplo n.º 5
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.º 6
0
def WriteXYZ(in_file, out_dir):
    """
    Write xyz file.
    """
    mol = Molecule.from_file(in_file)
    fout = os.path.join(out_dir, in_file.split('/')[-1])
    mol.to(filename=fout)
Exemplo n.º 7
0
def generate_gjf(in_fn,
                 out_dir,
                 functional='LC-wHPBE',
                 basis_set='TZVP',
                 charge=0,
                 calculation='opt',
                 omega=None,
                 oldchk=None):
    """
    Convert an individually inputted xyz file to a gjf Gaussian input file
    """
    mol = Molecule.from_file(in_fn)
    mol.perturb(0.1)
    mol_name = in_fn.split('/')[-1][:14]
    link0_parameters = {'%mem': '5GB', '%chk': '{}.chk'.format(calculation)}
    route_parameters = {
        calculation: '',
        'SCF': '(MaxCycle=250)',
        'Int': '(Grid=Ultrafine)'
    }
    if calculation == 'tddft':
        route_parameters = {'TD(NStates=5, 50-50)': ''}
    if omega is not None:
        route_parameters["iop(3/107={}, 3/108={})".format(omega, omega)] = ''
    if oldchk:
        link0_parameters['%oldchk'] = '{}.chk'.format(oldchk)
        route_parameters['Geom'] = 'AllCheck'
    gau = GaussianInput(mol=mol,
                        charge=charge,
                        functional=functional,
                        basis_set=basis_set,
                        route_parameters=route_parameters,
                        link0_parameters=link0_parameters)
    gjf_file = gau.write_file('{}/{}.gjf'.format(out_dir, calculation))
    return gjf_file
Exemplo n.º 8
0
 def test_packmol_with_str(self):
     """
     Test coords input as strings
     """
     with tempfile.TemporaryDirectory() as scratch_dir:
         pw = PackmolBoxGen().get_input_set(molecules=[
             {
                 "name":
                 "EMC",
                 "number":
                 10,
                 "coords":
                 os.path.join(test_dir, "subdir with spaces", "EMC.xyz")
             },
             {
                 "name": "LiTFSi",
                 "number": 20,
                 "coords": os.path.join(test_dir, "LiTFSi.xyz")
             },
         ], )
         pw.write_input(scratch_dir)
         pw.run(scratch_dir)
         assert os.path.exists(os.path.join(scratch_dir, "packmol_out.xyz"))
         out = Molecule.from_file(
             os.path.join(scratch_dir, "packmol_out.xyz"))
         assert out.composition.num_atoms == 10 * 15 + 20 * 16
Exemplo n.º 9
0
    def test_isomorphic(self):
        ethylene = Molecule.from_file(
            os.path.join(
                PymatgenTest.TEST_FILES_DIR,
                "graphs/ethylene.xyz",
            ))
        # switch carbons
        ethylene[0], ethylene[1] = ethylene[1], ethylene[0]

        eth_copy = MoleculeGraph.with_edges(
            ethylene,
            {
                (0, 1): {
                    "weight": 2
                },
                (1, 2): {
                    "weight": 1
                },
                (1, 3): {
                    "weight": 1
                },
                (0, 4): {
                    "weight": 1
                },
                (0, 5): {
                    "weight": 1
                },
            },
        )
        # If they are equal, they must also be isomorphic
        eth_copy = copy.deepcopy(self.ethylene)
        self.assertTrue(self.ethylene.isomorphic_to(eth_copy))
        self.assertFalse(self.butadiene.isomorphic_to(self.ethylene))
Exemplo n.º 10
0
    def run_task(self, fw_spec):

        self["constituent_molecules"]
        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, str):
            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.º 11
0
    def test_parse_pass_rotate_write(self):

        input_file = "pt_gs_wb97mv_tz_initial.in"
        output_file = "pt_gs_wb97mv_tz_initial_1_job.out"
        calc_dir = os.path.join(module_dir, "..", "..", "test_files")

        p_task = QChemToDb(calc_dir=calc_dir,
                           input_file=input_file,
                           output_file=output_file,
                           db_file=">>db_file<<")
        fw1 = Firework([p_task])
        atom_indexes = [6, 8, 9, 10]
        angle = 90.0
        rot_task = RotateTorsion(atom_indexes=atom_indexes, angle=angle)
        w_task = WriteInputFromIOSet(qchem_input_set="OptSet",
                                     write_to_dir=module_dir)
        fw2 = Firework([rot_task, w_task], parents=fw1)
        wf = Workflow([fw1, fw2])

        self.lp.add_wf(wf)
        rapidfire(
            self.lp,
            fworker=FWorker(env={"db_file": os.path.join(db_dir, "db.json")}))

        test_mol = QCInput.from_file(os.path.join(module_dir,
                                                  "mol.qin")).molecule
        act_mol = Molecule.from_file(
            os.path.join(module_dir, "..", "..", "test_files",
                         "pt_rotated_90.0.xyz"))
        np.testing.assert_equal(act_mol.species, test_mol.species)
        np.testing.assert_allclose(act_mol.cart_coords,
                                   test_mol.cart_coords,
                                   atol=0.0001)
Exemplo n.º 12
0
 def test_packmol_with_path(self):
     """
     Test coords input as Path. Use a subdirectory with spaces.
     """
     p1 = Path(os.path.join(test_dir, "subdir with spaces", "EMC.xyz"))
     p2 = Path(os.path.join(test_dir, "LiTFSi.xyz"))
     with tempfile.TemporaryDirectory() as scratch_dir:
         pw = PackmolWrapper(
             scratch_dir,
             molecules=[
                 {
                     "name": "EMC",
                     "number": 10,
                     "coords": p1
                 },
                 {
                     "name": "LiTFSi",
                     "number": 20,
                     "coords": p2
                 },
             ],
         )
         pw.make_packmol_input()
         pw.run_packmol()
         assert os.path.exists(os.path.join(scratch_dir, "packmol_out.xyz"))
         out = Molecule.from_file(
             os.path.join(scratch_dir, "packmol_out.xyz"))
         assert out.composition.num_atoms == 10 * 15 + 20 * 16
Exemplo n.º 13
0
 def test_packmol_with_molecule(self, water, ethanol):
     """
     Test coords input as Molecule
     """
     with tempfile.TemporaryDirectory() as scratch_dir:
         pw = PackmolWrapper(
             scratch_dir,
             molecules=[
                 {
                     "name": "water",
                     "number": 10,
                     "coords": water
                 },
                 {
                     "name": "ethanol",
                     "number": 20,
                     "coords": ethanol
                 },
             ],
         )
         pw.make_packmol_input()
         pw.run_packmol()
         assert os.path.exists(os.path.join(scratch_dir, "packmol_out.xyz"))
         out = Molecule.from_file(
             os.path.join(scratch_dir, "packmol_out.xyz"))
         assert out.composition.num_atoms == 10 * 3 + 20 * 9
Exemplo n.º 14
0
    def get_structures(self):
        host_path = self.args["input"][0]
        guest_path = self.args["input"][1]

        host = Structure.from_file(host_path)
        guest = Molecule.from_file(guest_path)

        return host, guest
Exemplo n.º 15
0
def example_opt_restart(orca_code, opt_calc_pk=None, submit=True):
    """Run simple DFT calculation"""

    # This line is needed for tests only
    if opt_calc_pk is None:
        opt_calc_pk = pytest.opt_calc_pk  # pylint: disable=no-member

    # structure
    thisdir = os.path.dirname(os.path.realpath(__file__))
    xyz_path = os.path.join(thisdir, 'h2co.xyz')
    structure = StructureData(pymatgen_molecule=Molecule.from_file(xyz_path))

    # old gbw file
    retr_fldr = load_node(opt_calc_pk).outputs.retrieved
    gbw_file = SinglefileData(
        os.path.join(retr_fldr._repository._get_base_folder().abspath,
                     'aiida.gbw'))  #pylint: disable=protected-access

    # parameters
    parameters = Dict(
        dict={
            'charge': 0,
            'multiplicity': 1,
            'input_blocks': {
                'scf': {
                    'convergence': 'tight',
                    'moinp': '"aiida_old.gbw"',
                },
                'pal': {
                    'nproc': 2,
                },
            },
            'input_keywords': ['B3LYP/G', 'def2-TZVP', 'Opt'],
            'extra_input_keywords': ['MOREAD'],
        })

    # Construct process builder
    builder = OrcaCalculation.get_builder()

    builder.structure = structure
    builder.parameters = parameters
    builder.code = orca_code
    builder.file = {
        'gbw': gbw_file,
    }
    builder.metadata.options.resources = {
        'num_machines': 1,
        'num_mpiprocs_per_machine': 1,
    }
    builder.metadata.options.max_wallclock_seconds = 1 * 10 * 60
    if submit:
        print('Testing Orca Opt Calculations...')
        res, pk = run_get_pk(builder)
        print('calculation pk: ', pk)
        print('SCF Energy is :', res['output_parameters'].dict['scfenergies'])
    else:
        builder.metadata.dry_run = True
        builder.metadata.store_provenance = False
Exemplo n.º 16
0
def MakesGauInputs(fn,w):
    """
    Convert an individually imputted xyz file to a gjf Gaussian input file
    """
    mol = Molecule.from_file(fn)
    mol_name = fn.split('/')[-1][:-12]
    gau = GaussianInput(mol=mol,charge=0,spin_multiplicity=1,functional='uLC-wPBE',basis_set='cc-pVDZ',  route_parameters={"iop(3/107={}, 3/108={})".format(w,w):"","opt":"modredundant"},   link0_parameters={'%mem':'5GB','%chk':'{}.chk'.format(mol_name)})
    gjf_file = gau.write_file('{}.gjf'.format(fn.split('.')[0]))
    return gjf_file
Exemplo n.º 17
0
 def mol_object(mol_fn):
     """
     Get pymatgen object in preparation for further processing
     Returns:
         A pymatgen object
     """
     try:
         return Molecule.from_file(mol_fn)
     except FileNotFoundError:
         print("File does not exist: {}".format(mol_fn))
Exemplo n.º 18
0
    def set_mol(self, mol_file, nmol):
        '''
        set molecule files and number of molecules

        # ---------- args
        mol_file (list): list of path for molecular files (.xyz, etc)
                         one can also use pre-defined strings such as
                         H2O, CH4, benzene, ... etc.
                         see PyXtal document

        nmol (list): number of molecules

        # ---------- example
        # ------ 4 benzene molecules in unit cell
        mol_file = ['benzene']
        nmol = [4]
        # ------ molecules you make (2 * mol_1 and 2 * mol_2)
        mol_file = ['./mol_1.xyz', './mol_2.xyz']
        nmol = [2, 2]
        '''
        # ---------- check args
        # ------ mol_file
        if type(mol_file) is not list:
            raise ValueError('mol_file must be list')
        for s in mol_file:
            if type(s) is not str:
                raise ValueError('elements in mol_file must be string')
        # ------ nmol
        if type(nmol) is not list:
            raise ValueError('nmol must be list')
        for i in nmol:
            if type(i) is not int:
                raise ValueError('elements in nmol must be int')
        # ------ mol_file and nmol
        if not len(mol_file) == len(nmol):
            raise ValueError('not len(mol_file) == len(nmol)')
        # ----------
        mol_data = []
        pyxtal_mol_data = Collection('molecules')
        pyxtal_mol_names = list(Collection('molecules'))
        for i, mf in enumerate(mol_file):
            if os.path.isfile(mf):
                mol = Molecule.from_file(mf)
            elif mf in pyxtal_mol_names:
                mol = pyxtal_mol_data[mf]
            else:
                raise ValueError('no molecular files')
            mol_data.append(mol)
        # ---------- self.xxx
        self.nmol = nmol
        self.mol_data = mol_data
def MakeJSON(mol_dir,omega_file,json_file):
    """
    For a molecule rotation directory, mol_dir, this finds the energy, xyz, and
    degree of rotation and places those into  json_file.
    """
    mol_name = str(mol_dir.split('/')[-1])
    energy = 0
    mol_xyz = 0
    try:
    # if 0 == 0:
        log_fn = [x for x in os.listdir(mol_dir) if x.endswith('opt_0.log')][0]
        log_path = os.path.join(mol_dir,log_fn)
        mol = GaussianOutput(log_path)
        if mol.properly_terminated:
            num_electrons = mol.electrons[0]
            eigens = list(mol.eigenvalues.values())[0]
            h**o = eigens[num_electrons - 1] * 27.2114
            lumo = eigens[num_electrons] * 27.2114
            homo_lumo_gap = lumo - h**o
            pymat_mol = Molecule.from_file(log_path)
            smi_mol = pmgmol_to_rdmol(pymat_mol)[1]
            with open(omega_file,'r') as fn:
                omega_data = fn.readlines()[-2].split()[1]
                omega = "0{}".format(omega_data.split('.')[1])
            normal = 1
        else:
            normal = 0
            print("Error. wtuning for did not properly terminate for {}".format(mol_name))
    except Exception as e:
        normal = 0
        print("Error. Data NOT collected for {}. Energy calculations for dihedral rotations may not have finished!".format(mol_name))
        print(e)
    if normal == 1:
        json_data = {
        "molecule_name" : mol_name,
        "smiles" : smi_mol,
        "tuned_omega" : omega,
        "h**o" : h**o,
        "lumo" : lumo,
        "homo_lumo_gap" : homo_lumo_gap
        }
        with open(json_file,'w+') as fn:
            json.dump(json_data, fn)
            print("Data collected for {}".format(mol_name))
    else:
        pass
    try:
        json_file.close()
        omega_file.close()
    except:
        pass
Exemplo n.º 20
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.º 21
0
    def test_no_opt_Fragmentation(self):
        db_file = os.path.join(db_dir, "db.json")
        mmdb = QChemCalcDb.from_db_file(db_file, admin=True)
        with open(
                os.path.join(module_dir, "..", "..", "test_files",
                             "sb40.json")) as f:
            tmp = json.load(f)
            for entry in tmp:
                mmdb.insert(entry)
        with patch("atomate.qchem.firetasks.fragmenter.FWAction"
                   ) as FWAction_patch:
            mock_FWAction = MagicMock()
            FWAction_patch.return_value = mock_FWAction
            mock_FWAction.as_dict.return_value = {
                "stored_data": {},
                "exit": False,
                "update_spec": {},
                "mod_spec": [],
                "additions": [],
                "detours": [],
                "defuse_children": False,
                "defuse_workflow": False,
            }

            # define starting molecule and workflow object
            initial_mol = Molecule.from_file(
                os.path.join(module_dir, "..", "..", "test_files", "top_11",
                             "EC.xyz"))
            initial_mol.set_charge_and_spin(charge=-1)
            wf = get_fragmentation_wf(
                molecule=initial_mol,
                depth=1,
                pcm_dielectric=40.0,
                do_optimization=False,
                check_db=True,
            )
            self.lp.add_wf(wf)
            rapidfire(
                self.lp,
                fworker=FWorker(env={
                    "max_cores": 24,
                    "db_file": db_file
                }),
                pdb_on_exception=True,
            )

            self.assertEqual(len(FWAction_patch.call_args[1]["additions"]), 0)
        mmdb.reset()
Exemplo n.º 22
0
 def setUpClass(cls) -> None:
     cls.ec = Molecule.from_file(filename=os.path.join(test_dir, "EC.xyz"))
     cls.emc = Molecule.from_file(
         filename=os.path.join(test_dir, "EMC.xyz"))
     cls.dec = Molecule.from_file(
         filename=os.path.join(test_dir, "DEC.xyz"))
     cls.pf6 = Molecule.from_file(
         filename=os.path.join(test_dir, "PF6.xyz"))
     cls.tfsi = Molecule.from_file(
         filename=os.path.join(test_dir, "TFSI.xyz"))
     cls.litfsi = Molecule.from_file(
         filename=os.path.join(test_dir, "LiTFSI.xyz"))
     cls.lipf6 = Molecule.from_file(
         filename=os.path.join(test_dir, "LiPF6.xyz"))
Exemplo n.º 23
0
def example_opt(orca_code, submit=True):
    """Run simple DFT calculation"""

    # structure
    thisdir = os.path.dirname(os.path.realpath(__file__))
    xyz_path = os.path.join(thisdir, 'h2co.xyz')
    structure = StructureData(pymatgen_molecule=Molecule.from_file(xyz_path))

    # parameters
    parameters = Dict(
        dict={
            'charge': 0,
            'multiplicity': 1,
            'input_blocks': {
                'scf': {
                    'convergence': 'tight',
                },
                'pal': {  #Uncomment for parallel run.
                    'nproc': 2,
                }
            },
            'input_keywords': ['B3LYP/G', 'SV(P)', 'Opt'],
            'extra_input_keywords': [],
        })

    # Construct process builder

    builder = OrcaBaseWorkChain.get_builder()

    builder.orca.structure = structure
    builder.orca.parameters = parameters
    builder.orca.code = orca_code

    builder.orca.metadata.options.resources = {
        'num_machines': 1,
        'num_mpiprocs_per_machine': 1,
    }
    builder.orca.metadata.options.max_wallclock_seconds = 1 * 10 * 60
    if submit:
        print('Testing Orca Opt Calculations...')
        res, pk = run_get_pk(builder)
        print('calculation pk: ', pk)
        print('SCF Energy is :', res['output_parameters'].dict['scfenergies'])
        pytest.opt_calc_pk = pk
    else:
        builder.metadata.dry_run = True
        builder.metadata.store_provenance = False
Exemplo n.º 24
0
def XYZtoGJF(xyz_fn, out_dir, functional, basis_set, charge=0):
    """
    Convert an individually imputted xyz file to a gjf Gaussian input file
    """
    mol = Molecule.from_file(xyz_fn)
    mol_name = xyz_fn.split('/')[-1].split('.')[0]
    gau = GaussianInput(mol=mol,
                        charge=charge,
                        functional=functional,
                        basis_set=basis_set,
                        route_parameters={"opt": ""},
                        link0_parameters={
                            '%mem': '5GB',
                            '%chk': '{}.chk'.format(mol_name)
                        })
    gjf_file = gau.write_file('{}/{}.gjf'.format(out_dir, mol_name))
    return gjf_file
def MakeJSON(mol_dir, json_file):
    """
    For a molecule rotation directory, mol_dir, this finds the energy, xyz, and
    degree of rotation and places those into  json_file.
    """
    mol_name = str(mol_dir.split('/')[-1])
    degree = str((mol_name.split('_')[-1])[:-3])
    energy = 0
    mol_xyz = 0
    try:
        for f in mol_dir:
            gen = [x for x in os.listdir(mol_dir) if x.endswith('.log')]
            for mol_file in gen:
                mol_file_path = os.path.join(mol_dir, mol_file)
                with open(mol_file_path) as fn:
                    normal = 0
                    for line in fn:
                        if re.search('Normal termination', line):
                            normal = 1
                        if re.search('SCF Done', line):
                            possible_E = line.split()[4]
                    if normal == 1:
                        energy = possible_E
                mol_pymat = Molecule.from_file(mol_file_path)
                mol_xyz = mol_pymat.to(fmt="xyz")
    except:
        print(
            "Error! Data NOT collected for {}. Energy calculations for dihedral rotations may not have finished!"
            .format(mol_name))
    if energy == 0 or mol_xyz == 0:
        print(
            "Error! Data NOT collected for {}. Energy calculations for dihedral rotations may not have finished!"
            .format(mol_name))
    else:
        print(degree)
        json_data = {
            "molecule_name": mol_name,
            "degree": degree,
            "xyz": mol_xyz,
            "energy (Hartrees)": energy
        }
        print(json_data)
        with open(json_file, 'w+') as fn:
            json.dump(json_data, fn)
        print("Data collected for {}".format(d))
Exemplo n.º 26
0
def XYZtoGJF(fn):
    """
    Convert an individually imputted xyz file to a gjf Gaussian input file
    """
    mol = Molecule.from_file(fn)
    gau = GaussianInput(mol=mol,
                        charge=0,
                        spin_multiplicity=1,
                        functional='PM6',
                        basis_set='',
                        route_parameters={'': ''},
                        link0_parameters={
                            '%mem': '5GB',
                            '%nproc': '1',
                            '%chk': '{}.chk'.format(fn.split('.')[0])
                        })
    gjf_file = gau.write_file('{}.gjf'.format(fn.split('.')[0]))
    return gjf_file
Exemplo n.º 27
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.º 28
0
def to_system_data(file_name, protect_layer=9):
    mol = Molecule.from_file(file_name)
    elem_mol = list(str(site.species.elements[0]) for site in mol.sites)
    elem_counter = Counter(elem_mol)
    atom_names = list(elem_counter.keys())
    atom_numbs = list(elem_counter.values())
    atom_types = [list(atom_names).index(e) for e in elem_mol]
    natoms = np.sum(atom_numbs)

    tmpcoord = np.copy(mol.cart_coords)

    system = {}
    system['atom_names'] = atom_names
    system['atom_numbs'] = atom_numbs
    system['atom_types'] = np.array(atom_types, dtype=int)
    # center = [c - h_cell_size for c in mol.center_of_mass]
    system['orig'] = np.array([0, 0, 0])

    system['coords'] = [tmpcoord]
    system['cells'] = [10.0 * np.eye(3)]
    return system
Exemplo n.º 29
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.º 30
0
 def test_arbitrary_filenames(self, water, ethanol):
     """
     Make sure custom input and output filenames work.
     Use a subdirectory with spaces.
     """
     with tempfile.TemporaryDirectory() as scratch_dir:
         os.mkdir(os.path.join(scratch_dir, "subdirectory with spaces"))
         pw = PackmolBoxGen(inputfile="input.in",
                            outputfile=Path("output.xyz"),
                            stdoutfile=Path("stdout.txt")).get_input_set(
                                molecules=[
                                    {
                                        "name": "water",
                                        "number": 10,
                                        "coords": water
                                    },
                                    {
                                        "name": "ethanol",
                                        "number": 20,
                                        "coords": ethanol
                                    },
                                ], )
         pw.write_input(
             os.path.join(scratch_dir, "subdirectory with spaces"), )
         assert os.path.exists(
             os.path.join(scratch_dir, "subdirectory with spaces",
                          "input.in"))
         pw.run(os.path.join(scratch_dir, "subdirectory with spaces"), )
         assert os.path.exists(
             os.path.join(scratch_dir, "subdirectory with spaces",
                          "output.xyz"))
         assert os.path.exists(
             os.path.join(scratch_dir, "subdirectory with spaces",
                          "stdout.txt"))
         out = Molecule.from_file(
             os.path.join(scratch_dir, "subdirectory with spaces",
                          "output.xyz"))
         assert out.composition.num_atoms == 10 * 3 + 20 * 9
Exemplo n.º 31
0
    def test_no_opt_Fragmentation(self):
        db_file = os.path.join(db_dir, "db.json")
        mmdb = QChemCalcDb.from_db_file(db_file, admin=True)
        with open(os.path.join(module_dir, "..", "..", "test_files","sb40.json")) as f:
            tmp = json.load(f)
            for entry in tmp:
                mmdb.insert(entry)
        with patch("atomate.qchem.firetasks.fragmenter.FWAction") as FWAction_patch:
            mock_FWAction = MagicMock()
            FWAction_patch.return_value = mock_FWAction
            mock_FWAction.as_dict.return_value = {'stored_data': {}, 'exit': False, 'update_spec': {}, 'mod_spec': [], 'additions': [], 'detours': [], 'defuse_children': False, 'defuse_workflow': False}

            # define starting molecule and workflow object
            initial_mol = Molecule.from_file(os.path.join(module_dir, "..", "..", "test_files", "top_11", "EC.xyz"))
            initial_mol.set_charge_and_spin(charge=-1)
            wf = get_fragmentation_wf(molecule=initial_mol, depth=1, pcm_dielectric=40.0, do_optimization=False, check_db=True)
            self.lp.add_wf(wf)
            rapidfire(
                self.lp,
                fworker=FWorker(env={"max_cores": 24, "db_file": db_file}), pdb_on_exception=True)

            self.assertEqual(len(FWAction_patch.call_args[1]["additions"]), 0)
        mmdb.reset()
Exemplo n.º 32
0
def load_molecule(filename="ethane.xyz"):
    path = os.path.join(STRUCTURES, filename)
    return Molecule.from_file(path)
Exemplo n.º 33
0
test_dir = os.path.join(
    os.path.dirname(__file__),
    "..",
    "..",
    "test_files",
    "reaction_network_files",
)

"""
Create a reaction network for testing, based on H2O molecule.
Species include H2, H2O, H, O, O2, OH, H3O, each at the -1, 0, and +1 charge states.

"""

# Make molecule objects
H2O_mol = Molecule.from_file(os.path.join(test_dir, "H2O.xyz"))
H2O_mol1 = copy.deepcopy(H2O_mol)
H2O_mol_1 = copy.deepcopy(H2O_mol)
H2O_mol1.set_charge_and_spin(charge=1)
H2O_mol_1.set_charge_and_spin(charge=-1)

H2_mol = Molecule.from_file(os.path.join(test_dir, "H2.xyz"))
H2_mol1 = copy.deepcopy(H2_mol)
H2_mol_1 = copy.deepcopy(H2_mol)
H2_mol1.set_charge_and_spin(charge=1)
H2_mol_1.set_charge_and_spin(charge=-1)

O2_mol = Molecule.from_file(os.path.join(test_dir, "O2.xyz"))
O2_mol1 = copy.deepcopy(O2_mol)
O2_mol_1 = copy.deepcopy(O2_mol)
O2_mol1.set_charge_and_spin(charge=1)
Exemplo n.º 34
0
# coding: utf-8

from __future__ import division, print_function, unicode_literals, absolute_import

from atomate.qchem.workflows.base.FF_then_fragment import get_wf_FF_then_fragment
from fireworks.core.launchpad import LaunchPad
from pymatgen.core import Molecule

mol = Molecule.from_file("BF4-.xyz")
wf = get_wf_FF_then_fragment(molecule=mol, max_cores=32)
lp = LaunchPad.auto_load()
lp.add_wf(wf)
Exemplo n.º 35
0
    """
    remainder = {}
    count_dict = get_elements_count(structure)
    weights = get_weight(stoich)
    scaled_max = max([count_dict[ele]*weights[ele] for ele in stoich.keys() ]) #determine the scaled maximum neded

    while scaled_max % lcm_list(list(weights.values())): # increase scaled max until it can accomodate correct stoichiometry
        scaled_max = scaled_max + 1

    for ele, count in count_dict.items():
        remainder[ele] = int((scaled_max - count_dict[ele]*weights[ele]) / (weights[ele]))

    return remainder


surf = Molecule.from_file('D:\\Users\\RyanTrottier\\Documents\\Scrap\\tmp.'+type)

center_i = 787
center = surf[center_i] # pymatgen.core.sites.Site
for radius in [3,4,5,6,8]:
    dr = 4

    stoich = get_stoichiometry(surf)

    sites = [center] + [ x[0] for x in surf.get_neighbors(center, radius)]

    mol = Molecule.from_sites(sites)
    remainder = get_remainder(mol, stoich)

    i = 0 # going to iterate over all sites, starting with the closest
    add_sites = surf.get_neighbors_in_shell(center.coords, radius+dr, dr)