Beispiel #1
0
    def parse_grad(
        self,
        state,
        tempfileout=None,
    ):

        if tempfileout is None:
            tempfileout = 'scratch/{:03}/{}/output.dat'.format(
                self.ID, self.node_id)
        # GET GRADIENT FOR QMMMM -- REGULAR GRADIENT IS PARSED THROUGH grad.xyz
        # QMMM is done differently :(
        if "prmtop" in self.file_options.ActiveOptions:
            tmpgrad = []
            with open(tempfileout, "r") as f:
                for line in f:
                    if line.startswith("dE/dX", 8):
                        for i in range(self.QM_atoms):
                            findline = next(f, '').strip()
                            mobj = re.match(r'(\S+)\s+(\S+)\s+(\S+)\s*$',
                                            findline)
                            tmpgrad.append([
                                float(mobj.group(1)),
                                float(mobj.group(2)),
                                float(mobj.group(3)),
                            ])
                        for i in range(self.link_atoms):
                            next(f)
                        # read two lines seperating the QM and MM regions
                        next(f)
                        next(f)
                        for i in range(self.MM_atoms):
                            findline = next(f, '').strip()
                            mobj = re.match(r'(\S+)\s+(\S+)\s+(\S+)\s*$',
                                            findline)
                            tmpgrad.append([
                                float(mobj.group(1)),
                                float(mobj.group(2)),
                                float(mobj.group(3)),
                            ])

            tmpgrad = np.asarray(tmpgrad)
            grad = np.zeros_like(tmpgrad)
            grad[self.qmindices] = tmpgrad[:len(self.qmindices)]
            grad[self.mm_indices] = tmpgrad[len(self.qmindices):]
        else:
            # getting gradient of non-prmtop job
            gradfile = 'scratch/{:03}/{}/grad_{}_{}.xyz'.format(
                self.ID, self.node_id, state[0], state[1])
            grad = manage_xyz.read_xyz(gradfile, scale=1.0)
            grad = manage_xyz.xyz_to_np(grad)
        self._Gradients[state] = self.Gradient(grad, "Hartree/Bohr")
Beispiel #2
0
 def parse_coup(self):
     tempfileout = 'scratch/{:03}/{}/output.dat'.format(
         self.ID, self.node_id)
     if "prmtop" in self.file_options.ActiveOptions:
         tmpcoup = []
         with open(tempfileout, "r") as f:
             for line in f:
                 if line.startswith("dE/dX",
                                    8):  # will work for SA-MC and RSPT2 HF
                     for i in range(self.QM_atoms):
                         findline = next(f, '').strip()
                         mobj = re.match(r'(\S+)\s+(\S+)\s+(\S+)\s*$',
                                         findline)
                         tmpcoup.append([
                             float(mobj.group(1)),
                             float(mobj.group(2)),
                             float(mobj.group(3)),
                         ])
                     # read link atoms
                     for i in range(self.link_atoms):
                         next(f)
                     next(f)
                     next(
                         f
                     )  # read two lines seperating the QM and MM regions
                     for i in range(self.MM_atoms):
                         findline = next(f, '').strip()
                         mobj = re.match(r'(\S+)\s+(\S+)\s+(\S+)\s*$',
                                         findline)
                         tmpcoup.append([
                             float(mobj.group(1)),
                             float(mobj.group(2)),
                             float(mobj.group(3)),
                         ])
         tmpcoup = np.asarray(tmpcoup)
         coup = np.zeros_like(tmpcoup)
         coup[self.qmindices] = tmpcoup[:len(self.qmindices)]
         coup[self.mm_indices] = tmpcoup[len(self.qmindices):]
     else:
         coupfile = 'scratch/{:03}/{}/coup_{}_{}.xyz'.format(
             self.ID, self.node_id, self.coupling_states[0],
             self.coupling_states[1])
         coup = manage_xyz.read_xyz(coupfile, scale=1.0)
         coup = manage_xyz.xyz_to_np(coup)
     self.Couplings[self.coupling_states] = self.Coupling(
         coup, 'Hartree/Bohr')
Beispiel #3
0
    def copy_from_options(MoleculeA,
                          xyz=None,
                          fnm=None,
                          new_node_id=1,
                          copy_wavefunction=True):
        """Create a copy of MoleculeA"""
        print(" Copying from MoleculA {}".format(MoleculeA.node_id))
        PES = type(MoleculeA.PES).create_pes_from(
            PES=MoleculeA.PES, options={'node_id': new_node_id})

        if xyz is not None:
            new_geom = manage_xyz.np_to_xyz(MoleculeA.geometry, xyz)
            coord_obj = type(MoleculeA.coord_obj)(
                MoleculeA.coord_obj.options.copy().set_values({"xyz": xyz}))
        elif fnm is not None:
            new_geom = manage_xyz.read_xyz(fnm, scale=1.)
            xyz = manage_xyz.xyz_to_np(new_geom)
            coord_obj = type(MoleculeA.coord_obj)(
                MoleculeA.coord_obj.options.copy().set_values({"xyz": xyz}))
        else:
            new_geom = MoleculeA.geometry
            coord_obj = type(MoleculeA.coord_obj)(
                MoleculeA.coord_obj.options.copy())

        return Molecule(MoleculeA.Data.copy().set_values({
            'PES':
            PES,
            'coord_obj':
            coord_obj,
            'geom':
            new_geom,
            'node_id':
            new_node_id,
            'copy_wavefunction':
            copy_wavefunction,
        }))
Beispiel #4
0
            for tup in self.states:
                self._Gradients[tup] = self.Gradients(None, None)
        elif self.gradient_states and self.coupling_states or runtype == 'gh':
            self.run(geom, 'gh')
        elif self.gradient_states and not self.coupling_states or runtype == 'gradient':
            self.run(geom, 'gradient')
        else:
            raise RuntimeError

        self.hasRanForCurrentCoords = True
        return


if __name__ == "__main__":
    # ,units.ANGSTROM_TO_AU)
    geom = manage_xyz.read_xyz('../../data/ethylene.xyz')
    B = BAGEL.from_options(states=[(1, 0), (1, 1)],
                           gradient_states=[(1, 0), (1, 1)],
                           coupling_states=(0, 1),
                           geom=geom,
                           lot_inp_file='bagel.txt',
                           node_id=0)
    coords = manage_xyz.xyz_to_np(geom)
    E0 = B.get_energy(coords, 1, 0)
    E1 = B.get_energy(coords, 1, 1)
    g0 = B.get_gradient(coords, 1, 0)
    g1 = B.get_gradient(coords, 1, 1)
    c = B.get_coupling(coords, 1, 0, 1)
    print(E0, E1)
    print(g0.T)
    print(g1.T)
Beispiel #5
0
                                                 self.PES2.ad_idx,
                                                 runtype='energy')
                cc += 1
            rc += 1

        return E1, E2


if __name__ == '__main__':

    from level_of_theories.pytc import PyTC
    import psiw
    import lightspeed as ls

    filepath = '../../data/ethylene.xyz'
    geom = manage_xyz.read_xyz(filepath, scale=1)
    # => Job Data <= #####
    states = [(1, 0), (1, 1)]
    charge = 0
    nocc = 7
    nactive = 2
    basis = '6-31gs'

    # => PSIW Obj <= ######
    nifty.printcool("Build resources")
    resources = ls.ResourceList.build()
    nifty.printcool('{}'.format(resources))

    molecule = ls.Molecule.from_xyz_file(filepath)
    geom = psiw.geometry.Geometry.build(
        resources=resources,
Beispiel #6
0
    def __init__(
        self,
        options,
    ):
        """ Constructor """

        self.options = options

        # properties
        self.Energy = namedtuple('Energy', 'value unit')
        self.Gradient = namedtuple('Gradient', 'value unit')
        self.Coupling = namedtuple('Coupling', 'value unit')
        self._Energies = {}
        self._Gradients = {}
        self._Couplings = {}

        # count number of states
        singlets = self.search_tuple(self.states, 1)
        doublets = self.search_tuple(self.states, 2)
        triplets = self.search_tuple(self.states, 3)
        quartets = self.search_tuple(self.states, 4)
        quintets = self.search_tuple(self.states, 5)

        #TODO do this for all states, since it catches if states are put in lazy e.g [(1,1)]
        if singlets:
            len_singlets = max(singlets, key=lambda x: x[1])[1] + 1
        else:
            len_singlets = 0
        len_doublets = len(doublets)
        len_triplets = len(triplets)
        len_quartets = len(quartets)
        len_quintets = len(quintets)

        # DO this before fixing states if put in lazy
        if self.options['gradient_states'] == None and self.calc_grad:
            print(" Assuming gradient states are ", self.states)
            self.options['gradient_states'] = self.options['states']

        if len(
                self.states
        ) < len_singlets + len_doublets + len_triplets + len_quartets + len_quintets:
            print('fixing states to be proper length')
            tmp = []
            # TODO put in rest of fixed states
            for i in range(len_singlets):
                tmp.append((1, i))
            for i in range(len_triplets):
                tmp.append((3, i))
            self.states = tmp
            print(' New states ', self.states)

        self.geom = self.options['geom']
        if self.geom is not None:
            print(" initializing LOT from geom")
        elif self.options['fnm'] is not None:
            print(" initializing LOT from file")
            if not os.path.exists(self.options['fnm']):
                logger.error(
                    'Tried to create LOT object from a file that does not exist: %s\n'
                    % self.options['fnm'])
                raise IOError
            self.geom = manage_xyz.read_xyz(self.options['fnm'], scale=1.)
        else:
            raise RuntimeError("Need to initialize LOT object")

        # Cache some useful atributes - other useful attributes are properties
        self.currentCoords = manage_xyz.xyz_to_np(self.geom)
        self.atoms = manage_xyz.get_atoms(self.geom)
        self.ID = self.options['ID']
        self.nproc = self.options['nproc']
        self.charge = self.options['charge']
        self.node_id = self.options['node_id']
        self.lot_inp_file = self.options['lot_inp_file']

        # Bools for running
        self.hasRanForCurrentCoords = False
        self.has_nelectrons = False

        # Read file options if they exist and not already set
        if self.file_options is None:
            self.file_options = File_Options(self.lot_inp_file)

        #package  specific implementation
        #TODO MOVE to specific package !!!
        # tc cloud
        self.options['job_data']['orbfile'] = self.options['job_data'].get(
            'orbfile', '')
        # pytc? TODO
        self.options['job_data']['lot'] = self.options['job_data'].get(
            'lot', None)

        print(" making folder scratch/{:03}/{}".format(self.ID, self.node_id))
        os.system('mkdir -p scratch/{:03}/{}'.format(self.ID, self.node_id))
Beispiel #7
0
        self.grada.append((multiplicity, gradient))
        # print(gradient)

    @property
    def system(self):
        return self.options['job_data']['system']

    @system.setter
    def system(self, value):
        self.options['job_data']['system'] = value


if __name__ == "__main__":

    # QMMM
    #filepath='/export/zimmerman/craldaz/kevin2/tropcwatersphere.xyz'
    #geom = manage_xyz.read_xyz(filepath)
    #filepath='tropcwatersphere.xyz'
    #lot = pDynamo.from_options(states=[(5,0)],charge=-1,nproc=16,fnm=filepath,lot_inp_file='pdynamo_options_qmmm.txt')
    #lot.run(geom)

    # DFTB
    filepath = '../../data/ethylene.xyz'
    geom = manage_xyz.read_xyz(filepath)
    lot = pDynamo.from_options(states=[(1, 0)],
                               charge=0,
                               nproc=16,
                               fnm=filepath,
                               lot_inp_file='pdynamo_options_dftb.txt')
    lot.run(geom)
Beispiel #8
0
    def __init__(self, options, **kwargs):

        self.Data = options

        # => Read in the coordinates <= #
        # important first try to read in geom

        t0 = time()
        if self.Data['geom'] is not None:
            print(" getting cartesian coordinates from geom")
            atoms = manage_xyz.get_atoms(self.Data['geom'])
            xyz = manage_xyz.xyz_to_np(self.Data['geom'])
        elif self.Data['fnm'] is not None:
            print(" reading cartesian coordinates from file")
            if self.Data['ftype'] is None:
                self.Data['ftype'] = os.path.splitext(self.Data['fnm'])[1][1:]
            if not os.path.exists(self.Data['fnm']):
                #logger.error('Tried to create Molecule object from a file that does not exist: %s\n' % self.Data['fnm'])
                raise IOError
            geom = manage_xyz.read_xyz(self.Data['fnm'], scale=1.)
            xyz = manage_xyz.xyz_to_np(geom)
            atoms = manage_xyz.get_atoms(geom)

        else:
            raise RuntimeError

        t1 = time()
        print(" Time to get coords= %.3f" % (t1 - t0))
        #resid=[]
        #for a in ob.OBMolAtomIter(mol.OBMol):
        #    res = a.GetResidue()
        #    resid.append(res.GetName())
        #self.resid = resid

        # Perform all the sanity checks and cache some useful attributes

        # TODO make PES property
        self.PES = type(self.Data['PES']).create_pes_from(
            PES=self.Data['PES'],
            options={'node_id': self.Data['node_id']},
            copy_wavefunction=self.Data['copy_wavefunction'])
        if not hasattr(atoms, "__getitem__"):
            raise TypeError("atoms must be a sequence of atomic symbols")

        for a in atoms:
            if not isinstance(a, str):
                raise TypeError("atom symbols must be strings")

        if type(xyz) is not np.ndarray:
            raise TypeError("xyz must be a numpy ndarray")
        if xyz.shape != (len(atoms), 3):
            raise ValueError("xyz must have shape natoms x 3")
        self.Data['xyz'] = xyz.copy()

        # create a dictionary from atoms
        # atoms contain info you need to know about the atoms
        self.atoms = [ELEMENT_TABLE.from_symbol(atom) for atom in atoms]

        tx = time()
        print(" Time to create PES,elements %.3f" % (tx - t1))
        t1 = tx

        if not isinstance(self.Data['comment'], str):
            raise TypeError("comment for a Molecule must be a string")

        # Create the coordinate system
        if self.Data['coord_obj'] is not None:
            print(" getting coord_object from options")
            self.coord_obj = self.Data['coord_obj']
        else:
            print(
                " Disabling this feature, Molecule cannot create coordinate system"
            )
            raise NotImplementedError
        #elif self.Data['coordinate_type'] == "Cartesian":
        #    self.coord_obj = CartesianCoordinates.from_options(xyz=self.xyz,atoms=self.atoms)
        #elif self.Data['coordinate_type'] == "DLC":
        #    print(" building coordinate object")
        #    self.coord_obj = DelocalizedInternalCoordinates.from_options(xyz=self.xyz,atoms=self.atoms,connect=True,extra_kwargs =self.Data['top_settings'])
        #elif self.Data['coordinate_type'] == "HDLC":
        #    self.coord_obj = DelocalizedInternalCoordinates.from_options(xyz=self.xyz,atoms=self.atoms,addcart=True,extra_kwargs =self.Data['top_settings'])
        #elif self.Data['coordinate_type'] == "TRIC":
        #    self.coord_obj = DelocalizedInternalCoordinates.from_options(xyz=self.xyz,atoms=self.atoms,addtr=True,extra_kwargs =self.Data['top_settings'])
        self.Data['coord_obj'] = self.coord_obj

        t2 = time()
        print(" Time  to build coordinate system= %.3f" % (t2 - t1))

        #TODO
        self.gradrms = 0.
        self.isTSnode = False
        self.bdist = 0.
        self.newHess = 5

        if self.Data['Hessian'] is None and self.Data['Form_Hessian']:
            if self.Data['Primitive_Hessian'] is None and type(
                    self.coord_obj) is not CartesianCoordinates:
                self.form_Primitive_Hessian()
            t3 = time()
            print(" Time to build Prim Hessian %.3f" % (t3 - t2))
            if self.Data['Primitive_Hessian'] is not None:
                print(" forming Hessian in basis")
                self.form_Hessian_in_basis()
            else:
                self.form_Hessian()

        #logger.info("Molecule %s constructed.", repr(self))
        #logger.debug("Molecule %s constructed.", repr(self))
        print(" molecule constructed")
Beispiel #9
0
        #    drij.append(AtomContact(xyz,AtomIterator,box=np.array([self.boxes[sn].a, self.boxes[sn].b, self.boxes[sn].c])))
        # else:
        drij.append(AtomContact(xyz, AtomIterator))
        return AtomIterator, drij


if __name__ == '__main__' and __package__ is None:
    from os import sys, path
    sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

    #filepath='../../data/butadiene_ethene.xyz'
    #filepath='crystal.xyz'
    filepath1 = 'multi1.xyz'
    filepath2 = 'multi2.xyz'

    geom1 = manage_xyz.read_xyz(filepath1)
    geom2 = manage_xyz.read_xyz(filepath2)
    atom_symbols = manage_xyz.get_atoms(geom1)
    xyz1 = manage_xyz.xyz_to_np(geom1)
    xyz2 = manage_xyz.xyz_to_np(geom2)

    ELEMENT_TABLE = elements.ElementData()
    atoms = [ELEMENT_TABLE.from_symbol(atom) for atom in atom_symbols]
    #print(atoms)

    #hybrid_indices = list(range(0,10)) + list(range(21,26))
    hybrid_indices = list(range(16, 26))

    G1 = Topology.build_topology(xyz1, atoms, hybrid_indices=hybrid_indices)
    G2 = Topology.build_topology(xyz2, atoms, hybrid_indices=hybrid_indices)