コード例 #1
0
 def test_clean_copy(self):
     badammoniumdichromate = Molecule('(NH4)2Cr2XqO7')
     fixed = badammoniumdichromate.clean_copy()
     self.assertTrue(fixed.check_symbols())
     self.assertEqual('(NH4)2Cr2O7', str(fixed))
コード例 #2
0
 def test_str(self):
     if self.pretest: self.test_no_super_class()
     for d in self.good_data:
         m = Molecule(d[1])
         self.assertEqual(d[1], str(m),
                          "str(Molecule({0})) should be {0}".format(d[1]))
コード例 #3
0
                En = grab_energy(e, directory + '/c{:d}n/output.dat'.format(x))
                hessian[x][y] = (Ep + En - 2 * E0) / (h**2)
            else:  # Second derivative with respect to two different variables
                Epx = grab_energy(e,
                                  directory + '/c{:d}p/output.dat'.format(x))
                Epy = grab_energy(e,
                                  directory + '/c{:d}p/output.dat'.format(y))
                Enx = grab_energy(e,
                                  directory + '/c{:d}n/output.dat'.format(x))
                Eny = grab_energy(e,
                                  directory + '/c{:d}n/output.dat'.format(y))
                Epp = grab_energy(
                    e, directory + '/c{:d}c{:d}p/output.dat'.format(x, y))
                Enn = grab_energy(
                    e, directory + '/c{:d}c{:d}n/output.dat'.format(x, y))
                hessian[x][y] = (Epp + Enn - Epx - Enx - Epy - Eny +
                                 2 * E0) / (2 * h**2)
                hessian[y][x] = hessian[x][y]
    out = open('hessian.dat', 'w')
    out.write(mwrite(hessian))
    out.close()


water = Molecule('../../extra-files/molecule.xyz')
water.bohr()
generate_inputs(water, '../../extra-files/template.dat')
run_jobs(water)
build_hessian(water)
H = Hessian(water, 'hessian.dat')
H.output()
コード例 #4
0
ファイル: test_grid.py プロジェクト: BERTHA-4c-DKS/pybertha
import sys
import os
sys.path.append("/usr/local/xcfun_py3/lib64/python")
#sys.path.append("/usr/local/PyADF-myfork/src/")
import numpy as np
import psi4
from pkg_resources import parse_version
from molecule import Molecule

#psi4.set_num_threads(16)
h2o=Molecule('H2O.xyz')
h2o.append('symmetry c1' +'\n' + 'no_com' + '\n' + 'no_reorient' + '\n')
psi4.set_options({'basis': 'aug-cc-pvdz', # can be defined later maybe?
                  'puream': 'True',
                  'DF_SCF_GUESS': 'False',
                  'scf_type': 'direct',
                  'dft_radial_scheme' : 'becke',
                  'dft_radial_points': 50,
                  'dft_spherical_points' : 194,
                  'e_convergence': 1e-8,
                  'd_convergence': 1e-8})
h2o_mol=psi4.geometry(h2o.geometry)
ene, h2o_wfn = psi4.energy('blyp', return_wfn=True)
C_h2o=np.array(h2o_wfn.Ca_subset("AO","OCC"))
D_h2o=np.array(h2o_wfn.Da())

# 2.1 map A and B density on grid points
from grid import GridFactoryDensity 
#we use the total system grid
Vpot = h2o_wfn.V_potential()
x, y, z, w = Vpot.get_np_xyzw()
コード例 #5
0
#!/usr/bin/env python

import sys, numpy as np

sys.path.insert(0, '../../')
from molecule import Molecule
from hessian import Hessian
from frequencies import Frequencies

ref = [1853.0679, 2335.9382, 2475.0096][::-1]

f = open("template.dat", "r").read()
mol = Molecule(f)
mol.toBohr()
mol.toRadian()
water = Hessian(mol, f)

##  build Gmatrix for water  ##
muO = 1 / mol.masses[0]
muH = 1 / mol.masses[1]
r = mol.coords[0]
phi = mol.coords[2]

G = np.zeros((3, 3))
G[0, 0] = G[1, 1] = muO + muH
G[1, 0] = G[0, 1] = muO * np.cos(phi)
G[0, 2] = G[2, 0] = -muO * np.sin(phi) / r
G[2, 1] = G[1, 2] = -muO * np.sin(phi) / r
G[2, 2] = 2 * (muO + muH - muO * np.cos(phi)) / r**2

h = open("FCMINT", "r").read()
コード例 #6
0
ファイル: make100.py プロジェクト: kavi9030/auto-ts
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

#from autots import Molecule
#from autots import Mutation
#from autots import connect

from molecule import Molecule
from mutation import Mutation
from utils import connect

import random

if __name__ == "__main__":

    mol = Molecule("examples/diels-alder.xyz")

    muts1 = [
        Mutation("mutations/8.xyz"),
        #Mutation("mutations/cn.xyz"),
        #Mutation("mutations/cooh.xyz"),
        #Mutation("mutations/nh2.xyz"),
        #Mutation("mutations/oh.xyz")
    ]

    unique_structures = []

    for i in range(100):
        print('Generating', i, '...')
        # How many mutations?
        #n = random.randint(1, 3)
コード例 #7
0
ファイル: input.py プロジェクト: rkm79791/summer-program
#!/usr/bin/env python

import sys, numpy as np
sys.path.append('../..')
from molecule import Molecule
from frequencies import Frequencies

hooh = Molecule("""
H
O 1 r1 
O 2 r2 1 a1
H 3 r1 2 a1 1 t1

r1 = 0.9625
r2 = 1.4535
a1 = 99.64
t1 = 113.7
""")

##  force constant matrix from CFOUR
h = open("FCALLEN", "r").read()

G = np.array([[
    1.05475559e+00, -1.04693939e-02, -4.24059519e-02, 0.00000000e+00,
    -1.70449781e-02, -6.59541269e-03
],
              [
                  -1.04693939e-02, 1.25039742e-01, -6.40384947e-02,
                  -1.04693939e-02, -6.40384947e-02, -1.30145626e-18
              ],
              [
コード例 #8
0
import random, time, turtle as tr
from molecule import Molecule, System

amount_of_molecules = 50
x_range = 150
y_range = 150
min_radius = 4
max_radius = 8
min_speed = 10
max_speed = 70

box_size = 500

molecules = [
    Molecule(
        x=round(random.uniform(-1, 1) * x_range),
        y=round(random.uniform(-1, 1) * y_range),
        radius=round(min_radius + random.random() * (max_radius - min_radius)),
        color='black',
        speed=round(min_radius + random.random() * (max_radius - min_radius)))
    for _ in range(amount_of_molecules)
]

System(molecules, box_size / 2)

tr.tracer(1000)
System.brownian_motion()
tr.done()
コード例 #9
0
from molecule import Molecule
import qm, mqc
from thermostat import *
from misc import data

geom = """
2
He2
He   -0.8   0.0   0.0   0.0 0.0 0.0
He    0.8   0.0   0.0   0.0 0.0 0.0
"""

mol = Molecule(geometry=geom, nstates=2)

qm = qm.gaussian09.DFT(molecule=mol, nthreads=4, memory="4gb", functional="B3LYP", basis_set="aug-cc-pVTZ", \
    g09_root_path="/opt/gaussian/")

md = mqc.BOMD(molecule=mol, nsteps=500, dt=0.125, istate=1)

bathT = rescale1(temperature=300.0, nrescale=10)

md.run(molecule=mol, qm=qm, thermostat=bathT, input_dir="./TRAJ.He2", save_scr=True, save_QMlog=False)

コード例 #10
0
from init import get_config
from energy import get_energy
from molecule import Molecule
from grad import gradient_descent
from hessian import Hessian
from frequencies import Frequencies
from pbc import pbc_sep
import numpy as np
if __name__ == '__main__':
    print("Starting to make initial configuration.")
    get_config()  # Q1
    init_mol = None
    with open("molecule.xyz") as f:
        print("Initial Configuration Generated for Arg LJ Model")
        print("Initial COnfiguration for Q1 will the saved to molecule.xyz")
        init_mol = Molecule(f, "Angstrom")
        print("Starting to do Q2 and Q3...")
        e = get_energy(np.array(init_mol.geom))  # Q2
        # print(e)
        # Q3 Steapest Descend is a heuristic.. Needs tuning of parameters...
        print("Starting Steepest Descent Algoithm to minimise Energy...")
        g = gradient_descent(0.135, 100, init_mol.geom)
        print("Steepest Descent Algoithm Ended.. Results below\n")
        print("Original Energy: ", e)
        print("New Energy:", np.min(np.array(g[1])))
        print()
        i = np.argmin(np.array(g[1]))
        print("New Configuration will be saved in new_molecule.xyz")
        with open("new_molecule.xyz", "w") as f2:
            print(len(g[0][i]), file=f2)
            print(file=f2)
コード例 #11
0
ファイル: main.py プロジェクト: sha443/CRO_RNA
    def run(self, filename, path):

        file = open(
            path + "input/" + filename,
            "r",
        )
        sequence = file.readline()

        # Clean up data
        sequence = sequence.replace(' ', '')
        sequence = sequence.upper()
        minStem = func.getMinStem(len(sequence))
        # # Override rule
        minStem = 3
        print(sequence)

        # Parameters
        iteration = 100
        popSize = 70
        KELossRate = 0.55
        MoleColl = 0.30
        InitialKE = 0
        alpha = 2
        beta = 8
        buffer = 0

        # Timer starts
        tictoc.tic()

        #----------------------------------------------------------------------------------------------
        # Population generation
        #----------------------------------------------------------------------------------------------
        mole = Molecule()
        mole.Mol(sequence, popSize, InitialKE, minStem)

        # # Save initial informations
        # minEnergy = 99999
        # index = 0
        # minIndex = 0
        # initPop = open(path+"output/initial_population_"+filename,"a")
        # for molecule in mole.molecules:
        # 	# initPop.write(population.PrintableMolecule(molecule)
        # 	# initPop.write(str(mole.PE[index]))
        # 	# initPop.write("\n")
        # 	if(mole.moleculeEnergy[index]<minEnergy):
        # 		minIndex = index
        # 		minEnergy=mole.moleculeEnergy[index]

        # 	index+=1
        # # endfor
        # initPop.write("\n")

        #----------------------------------------------------------------------------------------------
        # Optimize with CRO
        #----------------------------------------------------------------------------------------------
        C = CRO()
        # C.Init(popSize, KELossRate, MoleColl, InitialKE, alpha, beta, buffer, sequence, mole)
        sen, sp, f_m, tp, fp, fn, time, ene = C.CRO(popSize, KELossRate,
                                                    MoleColl, InitialKE, alpha,
                                                    beta, buffer, sequence,
                                                    mole, iteration, path,
                                                    filename)
        return sen, sp, f_m, tp, fp, fn, time, ene
コード例 #12
0
 def test_iter_molecules(self):
     for d in self.good_data:
         m = Molecule(d[1])
         for (i, j) in zip(sorted(d[3]), m):
             self.assertEqual(i, j, msg="not iterating atoms correctly")
コード例 #13
0
 def test_iter_atoms(self):
     for d in self.good_data:
         m = Molecule(d[1])
         for atomtuple in m:
             self.assertTrue(atomtuple in d[3])
コード例 #14
0
 def test_iter_tuples(self):
     m = Molecule('CH3COO(CH2)2CH(CH3)2')
     miter = iter(m)
     with self.assertRaises(StopIteration):
         while True:
             self.assertEqual(2, len(next(miter)))
コード例 #15
0
Test script for minimal psi4 calculation
"""
import sys
sys.path.insert(0, "../src")

from molecule import Fragment, Molecule
import psi4

minimal_frag = Fragment()

minimal_frag.natoms = 3
minimal_frag.symbols = ['O', 'H', 'H']
minimal_frag.coordinates = [[-0.0005900753, 0.0000000000, -0.0004526740],
                            [0.9256102457, 0.0000000000, -0.2481132352],
                            [-0.0000930743, 0.0000000000, 0.9582869092]]

minimal_mol = Molecule()
minimal_mol.natoms = 3
minimal_mol.fragments = [minimal_frag]

psi4.core.set_output_file("/dev/null", False)
psi4.set_memory("1GB")

psi4_mol = psi4.core.Molecule.create_molecule_from_string(
    minimal_mol.mol_comb_str([0]))
psi4_mol.update_geometry()
psi4.set_num_threads(6)
energy = psi4.energy("HF/STO-3G", molecule=psi4_mol)

print(energy)
コード例 #16
0
    def set_envmap(self, envmap):
        fmt = cl.ImageFormat(cl.channel_order.RGBA, cl.channel_type.FLOAT)
        em = np.zeros(envmap.shape[:2] + (4, ), dtype=np.float32)
        em[:, :, :3] = envmap
        em[:, :, 3] = 1
        self.envmap = cl.Image(context,
                               mf.READ_ONLY | mf.COPY_HOST_PTR,
                               fmt,
                               shape=em.shape[:2],
                               hostbuf=em)
        self.sampler = cl.Sampler(context, True, cl.addressing_mode.CLAMP,
                                  cl.filter_mode.LINEAR)

    def set_molecule(self, mol):
        self.mol = mol
        self.spheredata = cl.Buffer(context,
                                    mf.READ_ONLY | mf.COPY_HOST_PTR,
                                    hostbuf=self.mol.spheredata)

    def load_molecule(self, filename):
        self.set_molecule(Molecule(filename))


if __name__ == "__main__":

    from pfmloader import load_pfm
    r = CLRender()
    r.set_molecule(Molecule('data/sugars/sucrose.pdb'))
    r.set_envmap(load_pfm('data/probes/stpeters_probe.pfm'))
    r.compute()
コード例 #17
0
from molecule import Molecule

hooh = Molecule("""
H
O 1 0.9625
O 2 1.4535 1 99.64
H 3 0.9625 2 99.64 1 113.7
""")

print(hooh.compute_g_matrix())
コード例 #18
0
 def load_molecule(self, filename):
     self.set_molecule(Molecule(filename))
コード例 #19
0
    State(name='S',
          T0=20061.66,
          omega=3,
          we=None,
          we_xe=None,
          Be=.315050,
          alphae=None,
          D0=1.987 * 10**-7,
          Re=1.889),
    State(name='T',
          T0=24035.58,
          omega=3,
          we=None,
          we_xe=None,
          Be=.316785,
          alphae=None,
          D0=1.994 * 10**-7,
          Re=1.884),
    State(name='R',
          T0=19050.75,
          omega=0,
          we=862.0,
          we_xe=2.8,
          Be=.33232,
          alphae=.00148,
          D0=2.001 * 10**-7,
          Re=1.841)
]

ThO = Molecule(name='ThO', states=states)
コード例 #20
0
    def fgrad(x, indicate = False):
        """ Calculate the objective function and its derivatives. """
        # If the optimization algorithm tries to calculate twice for the same point, do nothing.
        # if x == fgrad.x0: return

        xyz = independent_vars_to_xyz(x)
        # these methods require 3d input
        xyzlist = np.array([xyz])
        my_bonds = core.bonds(xyzlist, ibonds).flatten()
        my_angles = core.angles(xyzlist, iangles).flatten()
        my_dihedrals = core.dihedrals(xyzlist, idihedrals, anchor=dihedrals).flatten()

        # Deviations of internal coordinates from ideal values.
        d1 = w1*(my_bonds - bonds)
        d2 = w2*(my_angles - angles)
        d3 = w3*(my_dihedrals - dihedrals)

        # Include an optional term if we have an anchor point.
        if xrefi != None:
            d4 = (x - xrefi).flatten() * w1 * w_xref
            fgrad.error = np.r_[d1, d2, np.arctan2(np.sin(d3), np.cos(d3)), d4]
        else:
            fgrad.error = np.r_[d1, d2, np.arctan2(np.sin(d3), np.cos(d3))]

        # The objective function contains another contribution from the Morse potential.
        fgrad.X = np.dot(fgrad.error, fgrad.error)
        d1s = np.dot(d1, d1)
        d2s = np.dot(d2, d2)
        d3s = np.dot(d3, d3)
        M = Molecule()
        M.elem = elem
        M.xyzs = [np.array(xyz)*10]
        if w_morse != 0.0:
            EMorse, GMorse = PairwiseMorse(M)
            EMorse = EMorse[0]
            GMorse = GMorse[0]
        else:
            EMorse = 0.0
            GMorse = np.zeros((n_atoms, 3), dtype=float)
        if indicate: 
            if fgrad.X0 != None:
                print ("LSq: %.4f (%+.4f) Distance: %.4f (%+.4f) Angle: %.4f (%+.4f) Dihedral: %.4f (%+.4f) Morse: % .4f (%+.4f)" % 
                       (fgrad.X, fgrad.X - fgrad.X0, d1s, d1s - fgrad.d1s0, d2s, d2s - fgrad.d2s0, d3s, d3s - fgrad.d3s0, EMorse, EMorse - fgrad.EM0)), 
            else:
                print "LSq: %.4f Distance: %.4f Angle: %.4f Dihedral: %.4f Morse: % .4f" % (fgrad.X, d1s, d2s, d3s, EMorse), 
                fgrad.X0 = fgrad.X
                fgrad.d1s0 = d1s
                fgrad.d2s0 = d2s
                fgrad.d3s0 = d3s
                fgrad.EM0 = EMorse
        fgrad.X += w_morse*EMorse

        # Derivatives of internal coordinates w/r.t. Cartesian coordinates.
        d_bonds = core.bond_derivs(xyz, ibonds) * w1
        d_angles = core.angle_derivs(xyz, iangles) * w2
        d_dihedrals = core.dihedral_derivs(xyz, idihedrals) * w3

        if xrefi != None:
            # the derivatives of the internal coordinates wrt the cartesian
            # this is 2d, with shape equal to n_internal x n_cartesian
            d_internal = np.vstack([gxyz_to_independent_vars(d_bonds.reshape((len(ibonds), -1))),
                                    gxyz_to_independent_vars(d_angles.reshape((len(iangles), -1))),
                                    gxyz_to_independent_vars(d_dihedrals.reshape((len(idihedrals), -1))),
                                    np.eye(len(x)) * w1 * w_xref])
        else:
            # the derivatives of the internal coordinates wrt the cartesian
            # this is 2d, with shape equal to n_internal x n_cartesian
            d_internal = np.vstack([gxyz_to_independent_vars(d_bonds.reshape((len(ibonds), -1))),
                                    gxyz_to_independent_vars(d_angles.reshape((len(iangles), -1))),
                                    gxyz_to_independent_vars(d_dihedrals.reshape((len(idihedrals), -1)))])

        # print fgrad.error.shape, d_internal.shape
        # print d_internal.shape
        # print xyz_to_independent_vars(d_internal).shape
        fgrad.G = 2*np.dot(fgrad.error, d_internal)
        fgrad.G += xyz_to_independent_vars(w_morse*GMorse.flatten())
コード例 #21
0
# other options
#basis_active = "DZP"
#fde_act_opts = {'FULLGRID':'', 'PW91k' : '', 'ENERGY' : '' }

#file_h2o = os.path.join ("./", 'H2O.xyz')
#file_nh3 = os.path.join ("./", 'NH3.xyz')

m_dummy = pyadf.molecule('NH3.xyz')
m_dummy.set_symmetry('NOSYM')
#m_nh3 = pyadf.molecule(file_nh3)
#m_nh3.set_symmetry('NOSYM')

#m_tot = m_h2o + m_nh3
#m_tot.set_symmetry('NOSYM')

h2o = Molecule('H2O.xyz')
nh3 = Molecule('NH3.xyz')

tot = Molecule('H2O.xyz')
tot.append(nh3.geometry + 'symmetry c1' + '\n' + 'no_com' + '\n' +
           'no_reorient' + '\n')
#check
tot.display_xyz()

psi4.set_num_threads(16)
psi4.core.set_output_file('output.dat', False)
### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
# Grid generation step
#
# getting a grid from psi4 for the total system
コード例 #22
0
        if gmx_acharge != amb_acharge:
            print "Atomic charges don't match for", resname, gmx_atom, amb_atom
            raise RuntimeError
        # Print the atoms that are renamed
        # if gmx_aname != amb_aname:
        #     print "%s (AMBER) %s <-> %s (GMX)" % (resname, amb_aname, gmx_aname)
        gmx_amb_amap.setdefault(resname, OrderedDict())[gmx_aname] = amb_aname
        amb_gmx_amap.setdefault(resname, OrderedDict())[amb_aname] = gmx_aname

amber_atomnames = OrderedDict([(k, set(v.keys()))
                               for k, v in amb_gmx_amap.items()])
max_reslen = max([len(v) for v in amber_atomnames.values()])

# Begin with an AMBER-compatible PDB file
# Please ensure by hand :)
pdb = Molecule(sys.argv[1], build_topology=False)
gmx_pdb = copy.deepcopy(pdb)
del gmx_pdb.Data['elem']

# Convert to a GROMACS-compatible PDB file
# This mainly involves renaming atoms and residues,
# notably hydrogen names.

# List of atoms in the current residue
anameInResidue = []
anumInResidue = []
for i in range(gmx_pdb.na):
    # Rename the ions residue names to be compatible with Gromacs
    if gmx_pdb.resname[i] == 'Na+':
        gmx_pdb.resname[i] = 'NA'
    elif gmx_pdb.resname[i] == 'Cl-':
コード例 #23
0
    def generate_reaction(self, r1, r2):
        """Given two reactants, this method tries to generate a new reaction
        where the products are a random reorganization of the
        reactants.  If one of the products has a greater free energy
        than the sum of the reactants, the generated reaction is
        considered impossible, no reaction is generated and an empty
        list is returned.

        Otherwise a list is returned of any new product molecules. These
        molecules are not added to the chemistry here.

        """
        new_species = []

        lhs_total_G = r1.G + r2.G
        ## generate p1 and p2 as a random recombination of the
        ## reactants
        reactant_atoms = ''.join(r1.atom_string + r2.atom_string)

        n_atoms_in_p1 = np.random.randint(1, len(reactant_atoms))
        n_atoms_in_p2 = len(reactant_atoms) - n_atoms_in_p1
        assert (n_atoms_in_p2 > 0)
        assert (n_atoms_in_p1 > 0)

        l = list(reactant_atoms)
        np.random.shuffle(l)

        p1_atom_string = ''.join(l[:n_atoms_in_p1])
        p2_atom_string = ''.join(l[n_atoms_in_p1:])

        if p1_atom_string in self.molecules.keys():
            p1 = self.molecules[p1_atom_string]
        else:
            p1 = None

        if p2_atom_string in self.molecules.keys():
            p2 = self.molecules[p2_atom_string]
        else:
            p2 = None

        # 2: Generate the free energies of p1 and p2 (if they don’t
        # already exist) so that the following relation holds,
        # G p1 +G p2 +heat 1⁄4 G r1 +G r2 , by portioning energies
        # according to a uniform random distribution, heat being
        # positive.
        # 3: if it is not possible to satisfy this relation, e.g. because
        # G p1 4G r1 +G r2 , then the reaction is not permitted, and no
        # new products are created.

        reaction_possible = True
        reason_for_impossibility = ''
        if p1 is None and p2 is None:
            """ Neither products already exist. """
            x = np.random.rand() * lhs_total_G  # split the energy
            y = np.random.rand() * lhs_total_G  # at these points
            a = min(x, y)
            b = max(x, y) - a
            c = lhs_total_G - max(x, y)

            heat = a
            p1_G = b
            p2_G = c

            p1 = Molecule(atom_string=p1_atom_string, G=p1_G)
            p2 = Molecule(atom_string=p2_atom_string, G=p2_G)
            assert (p1_G > 0.0)
            assert (p2_G > 0.0)
            new_species.append(p1)
            new_species.append(p2)
        elif p1 is not None and p2 is not None:
            """ Both products already exist. """
            ## There are no new species
            p1 = self.molecules[p1_atom_string]
            p2 = self.molecules[p2_atom_string]
            if p1.G + p2.G > lhs_total_G:
                self.reaction_possible = False
                logger.debug(
                    f'FR: Reaction impossible due to thermodynamics (1).')
                logger.debug(f'FR: {r1} + {r2} --> {p1} + {p2}')
        else:
            """ Exactly one of the products already exists. """
            if p1 is not None and p2 is None:
                ## put the pre-existing product in position 2
                p2, p1 = p1, p2
                p2_atom_string, p1_atom_string = p1_atom_string, p2_atom_string

            assert (p1 is None and p2 is not None)
            p2 = self.molecules[p2_atom_string]
            p2_G = p2.G
            if p2_G >= lhs_total_G:
                ## Reaction is thermodynamically impossible as
                ## prexisting proposed product is higher G than all reactants.
                ## (Step 3)
                reaction_possible = False
                logger.debug(
                    f'FR: Reaction impossible due to thermodynamics (2).')
                logger.debug(f'FR: {r1} + {r2} --> {p1} + {p2}')

            else:
                remaining_G = lhs_total_G - p2_G
                p1_G = np.random.rand() * remaining_G
                heat = (remaining_G - p1_G)
                p1 = Molecule(atom_string=p1_atom_string, G=p1_G)
                # print('%f %f %f : %f' %(p1_G, p2_G, heat, lhs_total_G))
                assert (p1_G > 0.0)
                new_species.append(p1)

        if set([r1, r2]) == set([p1, p2]):
            ## disallow reactions that do nothing
            reaction_possible = False
            logger.debug(
                f'FR: Reaction impossible due to meaninglessness (3).')
            logger.debug(f'FR: {r1} + {r2} --> {p1} + {p2}')
        logger.debug(
            f'FR: a new proposed reaction is {r1} + {r2} --> {p1} + {p2}')
        if reaction_possible:
            return {
                'products': [p1, p2],
                'new_species': new_species,
            }
        else:
            return None
コード例 #24
0
ファイル: micepes.py プロジェクト: i4hashmi/MICE-PES
def main():
    # Print GPL v3 statement and program header
    prg_start_time = time.time()
    if args.verbosity >= 1:
        msg_program_header("MICEPES", 1.0)

    molecule = Molecule("Input Structure", 0)

    # No building of internal coordinates if we just want to print the
    # structure. We'll need the energy though.
    list_of_hydrogens = []
    if args.group == "none":
        extract_molecular_data(args.inputfile,
                               molecule,
                               verbosity=args.verbosity,
                               read_coordinates=True,
                               read_qm_energy=True)
    else:
        extract_molecular_data(args.inputfile,
                               molecule,
                               verbosity=args.verbosity,
                               read_coordinates=True,
                               read_bond_orders=True,
                               build_angles=True,
                               build_dihedrals=True)

        if args.replace is not None:
            if args.verbosity >= 3:
                print("\nAdding hydrogen atoms from the --replace key")
            for i in args.replace:
                if molecule.atoms[i - 1].symbol() == "H":
                    list_of_hydrogens.append(i)
                    if args.verbosity >= 3:
                        print(
                            "Hydrogen atom ", i, " added to the list of "
                            "atoms for replacement.")
                else:
                    msg_program_warning("Atom " + str(i) + " in the input "
                                        "is not hydrogen!")
        if args.alloncarbon is not None:
            if args.verbosity >= 3:
                print("\nAdding hydrogen atoms from the --alloncarbon key")
            for i in args.alloncarbon:
                if molecule.atm_symbol(i - 1) == "C":
                    if args.verbosity >= 3:
                        print(
                            "Adding the hydrogen atoms bonded"
                            " to carbon atom ", i)
                    for j in molecule.bonds:
                        at1 = j[0]  # First atom in the bond
                        at2 = j[1]  # Second atom in the bond
                        if at1 + 1 == i and molecule.atm_symbol(at2) == "H":
                            list_of_hydrogens.append(at2 + 1)
                            if args.verbosity >= 3:
                                print(
                                    "Hydrogen atom ", at2 + 1,
                                    " added to the list of atoms"
                                    " for replacement.")
                        elif at2 + 1 == i and molecule.atm_symbol(at1) == "H":
                            list_of_hydrogens.append(at1 + 1)
                            if args.verbosity >= 3:
                                print(
                                    "Hydrogen atom ", at1 + 1,
                                    " added to the list of atoms"
                                    " for replacement.")
                else:
                    msg_program_warning("Atom " + str(i) +
                                        " in the input is not carbon!")
        if args.terminal is not None:
            if args.verbosity >= 3:
                print("\nAdding hydrogen atoms from the --terminal key")
            # Count backwards and add the hydrogen atoms to the list
            counter = 0
            for i in range(molecule.num_atoms(), 0, -1):
                if counter < args.terminal and \
                        molecule.atm_symbol(i - 1) == "H":
                    if args.verbosity >= 3:
                        print("Hydrogen atom ", i,
                              " added to the list of atoms for replacement.")
                    list_of_hydrogens.append(i)
                    counter += 1
        elif args.replace is None and args.alloncarbon is None:
            # If no instructions were given at all: default to replacing
            # the terminal 3 hydrogens
            if args.verbosity >= 2:
                print("\nDefaulting to replacement of"
                      " the last 3 hydrogen atoms")
            counter = 0
            for i in range(molecule.num_atoms(), 0, -1):
                if counter < 3 and molecule.atm_symbol(i - 1) == "H":
                    if args.verbosity >= 3:
                        print("Hydrogen atom ", i,
                              " added to the list of atoms for replacement.")
                    list_of_hydrogens.append(i)
                    counter += 1

        # Abort if we somehow managed to end up with an empty list
        if not list_of_hydrogens:
            msg_program_error("No atoms selected for replacement")

        # Ensuring our list is unique
        list_of_hydrogens = set(list_of_hydrogens)
        if args.verbosity >= 2:
            print("\nThere are ", len(list_of_hydrogens),
                  "hydrogen atoms that have been selected for replacement.")
            if args.verbosity >= 3:
                print("Hydrogen atoms: ", list_of_hydrogens)

    # From here on, we loop over our list and actually do replacements
    for j, i in enumerate(list_of_hydrogens):
        filesuffix = str(j + 1).zfill(
            int(math.ceil(math.log(len(list_of_hydrogens), 10))))
        filename, file_extension = os.path.splitext(args.inputfile)
        # Look up which replacement was selected
        if args.group == "methyl":
            newmol = replace_h_with_tetrahedral(molecule, h=(i - 1))
            newmol.name = "Molecule " + filesuffix + " out of " + str(
                len(list_of_hydrogens)) + ", hydrogen atom no. " + str(
                    i) + " replaced"
            msg = newmol.print_mol(output=args.output,
                                   file=filename + "-" + filesuffix,
                                   comment=newmol.name)
            if args.verbosity >= 3:
                print("\nNew Structure:")
                print(msg)
        elif args.group == "ethenyl":
            newmol = replace_h_with_ethenyl(molecule, h=(i - 1))
            newmol.name = "Molecule " + filesuffix + " out of " + str(
                len(list_of_hydrogens)) + ", hydrogen atom no. " + str(
                    i) + " replaced"
            msg = newmol.print_mol(output=args.output,
                                   file=filename + "-" + filesuffix,
                                   comment=newmol.name)
            if args.verbosity >= 3:
                print("\nNew Structure:")
                print(msg)
        elif args.group == "cho":
            # If we replace H by CHO, we create the three possible
            #  orientations at the same time
            for l, k in enumerate(["a", "b", "c"]):
                newmol = replace_h_with_cho(molecule, h=(i - 1), orientation=l)
                newmol.name = "Molecule " + filesuffix + " out of " + str(
                    len(list_of_hydrogens)) + ", hydrogen atom no. " + str(
                        i) + " replaced"
                msg = newmol.print_mol(output=args.output,
                                       file=filename + "-" + filesuffix + k,
                                       comment=newmol.name)
            if args.verbosity >= 3:
                print("\nNew Structure:")
                print(msg)
        elif args.group == "nh3":
            newmol = replace_h_with_tetrahedral(molecule,
                                                h=(i - 1),
                                                replacement="N")
            newmol.name = "Molecule " + filesuffix + " out of " + str(
                len(list_of_hydrogens)) + ", hydrogen atom no. " + str(
                    i) + " replaced"
            msg = newmol.print_mol(output=args.output,
                                   file=filename + "-" + filesuffix,
                                   comment=newmol.name)
            if args.verbosity >= 3:
                print("\nNew Structure:")
                print(msg)
        elif args.group == "oh":
            # If we replace H by OH, we create the three possible
            #  orientations at the same time
            for l, k in enumerate(["a", "b", "c"]):
                newmol = replace_h_with_tetrahedral(molecule,
                                                    h=(i - 1),
                                                    replacement="O",
                                                    add_h=1,
                                                    orientation=l)
                newmol.name = "Molecule " + filesuffix + " out of " + str(
                    len(list_of_hydrogens)) + ", hydrogen atom no. " + str(
                        i) + " replaced"
                msg = newmol.print_mol(output=args.output,
                                       file=filename + "-" + filesuffix + k,
                                       comment=newmol.name)
            if args.verbosity >= 3:
                print("\nNew Structure:")
                print(msg)
        elif args.group == "nh2":
            # If we replace H by NH₂, we create the three possible
            #  orientations at the same time
            for l, k in enumerate(["a", "b", "c"]):
                newmol = replace_h_with_tetrahedral(molecule,
                                                    h=(i - 1),
                                                    replacement="N",
                                                    add_h=2,
                                                    orientation=l)
                newmol.name = "Molecule " + filesuffix + " out of " + str(
                    len(list_of_hydrogens)) + ", hydrogen atom no. " + str(
                        i) + " replaced"
                msg = newmol.print_mol(output=args.output,
                                       file=filename + "-" + filesuffix + k,
                                       comment=newmol.name)
            if args.verbosity >= 3:
                print("\nNew Structure:")
                print(msg)
        elif args.group == "oh2":
            # If we replace H by OH₂, we create the three possible
            #  orientations at the same time
            for l, k in enumerate(["a", "b", "c"]):
                newmol = replace_h_with_tetrahedral(molecule,
                                                    h=(i - 1),
                                                    replacement="O",
                                                    add_h=2,
                                                    orientation=l)
                newmol.name = "Molecule " + filesuffix + " out of " + str(
                    len(list_of_hydrogens)) + ", hydrogen atom no. " + str(
                        i) + " replaced"
                msg = newmol.print_mol(output=args.output,
                                       file=filename + "-" + filesuffix + k,
                                       comment=newmol.name)
            if args.verbosity >= 3:
                print("\nNew Structure:")
                print(msg)
        elif args.group == "f":
            newmol = replace_h_with_tetrahedral(molecule,
                                                h=(i - 1),
                                                replacement="F",
                                                add_h=0)
            newmol.name = "Molecule " + filesuffix + " out of " + str(
                len(list_of_hydrogens)) + ", hydrogen atom no. " + str(
                    i) + " replaced"
            msg = newmol.print_mol(output=args.output,
                                   file=filename + "-" + filesuffix,
                                   comment=newmol.name)
            if args.verbosity >= 3:
                print("\nNew Structure:")
                print(msg)
        elif args.group == "cl":
            newmol = replace_h_with_tetrahedral(molecule,
                                                h=(i - 1),
                                                replacement="Cl",
                                                add_h=0)
            newmol.name = "Molecule " + filesuffix + " out of " + str(
                len(list_of_hydrogens)) + ", hydrogen atom no. " + str(
                    i) + " replaced"
            msg = newmol.print_mol(output=args.output,
                                   file=filename + "-" + filesuffix,
                                   comment=newmol.name)
            if args.verbosity >= 3:
                print("\nNew Structure:")
                print(msg)
        elif args.group == "br":
            newmol = replace_h_with_tetrahedral(molecule,
                                                h=(i - 1),
                                                replacement="Br",
                                                add_h=0)
            newmol.name = "Molecule " + filesuffix + " out of " + str(
                len(list_of_hydrogens)) + ", hydrogen atom no. " + str(
                    i) + " replaced"
            msg = newmol.print_mol(output=args.output,
                                   file=filename + "-" + filesuffix,
                                   comment=newmol.name)
            if args.verbosity >= 3:
                print("\nNew Structure:")
                print(msg)
        elif args.group == "i":
            newmol = replace_h_with_tetrahedral(molecule,
                                                h=(i - 1),
                                                replacement="I",
                                                add_h=0)
            newmol.name = "Molecule " + filesuffix + " out of " + str(
                len(list_of_hydrogens)) + ", hydrogen atom no. " + str(
                    i) + " replaced"
            msg = newmol.print_mol(output=args.output,
                                   file=filename + "-" + filesuffix,
                                   comment=newmol.name)
            if args.verbosity >= 3:
                print("\nNew Structure:")
                print(msg)
    # The "none" option is just an excuse for simply extracting and printing
    # the structure to a file
    if args.group == "none":
        filename, file_extension = os.path.splitext(args.inputfile)
        msg = molecule.print_mol(output=args.output,
                                 file=filename + "-micepes",
                                 comment=str(molecule.qm_energy))
        if args.verbosity >= 3:
            print("\nStructure:")
            print(msg)

    # Print program footer
    if args.verbosity >= 1:
        msg_program_footer(prg_start_time)
コード例 #25
0
def read_psi4_mol(psi4_mol, au_conversion=1.0):
    return Molecule(psi4_mol.create_psi4_string_from_molecule(), au_conversion)
コード例 #26
0
def read_qchem_mol(qchem_mol, num_atoms, au_conversion=1.0):
    molecule = """\n\n"""
    for line in qchem_mol:
        molecule += line[9:]
    return Molecule(molecule, au_conversion=1.0)
コード例 #27
0
#!/usr/bin/env python2
import sys
sys.path.insert(0, '../extra-files')
sys.path.insert(0, '../../0/winky94')
from molecule import Molecule
from masses import get_mass
import numpy as np

# Build molecule

mol = Molecule(open('../extra-files/molecule.xyz').read(), 'Bohr')
mol.bohr_to_ang()

# Read in hessian

lines = open('../extra-files/hessian.dat').readlines()

# Build mass-weighted hessian

H = []

for line in lines:
    H.append(list(map(float, line.split())))

H = np.matrix(H)

M = []

for atom in mol.atoms:
    M.append(1 / np.sqrt(get_mass(atom)))
    M.append(1 / np.sqrt(get_mass(atom)))
コード例 #28
0
import qm, mqc
from thermostat import *
from misc import data

geom = """
6
dt = 0.125 fs, nsteps = 1000, istate = 2, nesteps = 10000, T = 300 K, nrescale = 20
C    2.86124018      4.31304115      4.15521402      0.00002671     -0.00010330      0.00004871
N    5.27829773      4.08368726      4.18677408     -0.00004087      0.00017187      0.00013434
H    1.88738261      3.13911452      5.54097988     -0.00100507      0.00019113     -0.00024745
H    1.76187927      5.49131646      2.81165546      0.00089679     -0.00006276     -0.00027862
H    6.54948319      4.69589988      2.84554252     -0.00034025     -0.00092241     -0.00072712
H    5.96455902      2.68641232      5.40075458      0.00068502     -0.00036011     -0.00118705
"""

mol = Molecule(geometry=geom, nstates=3, charge=+1, unit_pos="au")

qm = qm.columbus.CASSCF(molecule=mol, basis_set="6-31g*", memory="1000", \
    active_elec=6, active_orb=4, \
    qm_path="/opt/Columbus7.0/Columbus", nthreads=1, version=7.0)

md = mqc.SHXF(molecule=mol,
              nsteps=1000,
              nesteps=10000,
              dt=0.125,
              istate=2,
              propagation="density",
              wsigma=0.02)

bathT = rescale1(temperature=300.0, nrescale=20)
コード例 #29
0
ファイル: project1.py プロジェクト: rkm79791/summer-program
import sys
from pprint import pprint
sys.path.insert(0, '../extra-files')
sys.path.insert(0, '../../0/adabbott')
import masses
from molecule import Molecule
import numpy as np

mol = Molecule(open("../extra-files/molecule.xyz").read())

mol.bohr_to_ang()
#read Hessian Values

hessian_values = open('../extra-files/hessian.dat').readlines()
#collect hessain values into matrix

H = []
A = len(mol)  #this is redefined to give number of atoms
for row in hessian_values:
    for x in row.split():
        H.append(x)
hessian = np.matrix(H, float)
hessian = np.reshape(hessian, (3 * A, 3 * A))

m = []
M = []
for atom in mol.atoms:
    m.append(masses.get_mass(atom))
    m.append(masses.get_mass(atom))
    m.append(masses.get_mass(atom))
for mass in m:
コード例 #30
0
 def test_mass_error(self):
     badwater = Molecule('H+2+O')
     with self.assertRaises(ValueError):
         badwater.mass()