Пример #1
0
    def prepare_semiempirical_model(self, system, method_name, charge,
                                    multiplicity, restricted):
        """Prepare common settings for computing with semiempirical models.

        :param system: input system with geometry
        :type system : pMolecule.System.System
        :param method_name: name of semiempirical model to apply
        :type method_name : str
        :param charge: system charge
        :type charge : int
        :param multiplicity: system multiplicity
        :type multiplicity : int
        :param restricted: whether to run a spin-restricted calculation
        :type restricted : bool
        :return: prepared system
        :rtype : pMolecule.System.System
        """

        es = ElectronicState(charge=charge, multiplicity=multiplicity)
        converger = DIISSCFConverger(densityTolerance=1.0e-6,
                                     maximumSCFCycles=999)

        qcmodel = QCModelMNDO(method_name,
                              converger=converger,
                              isSpinRestricted=restricted)

        system.electronicState = es
        system.DefineQCModel(qcmodel)

        return system
Пример #2
0
    def runTest(self):
        """The test."""

        # . Initialization.
        isOK = True
        log = self.GetLog()

        # . Paths.
        sourcePath = os.path.join(os.getenv("PDYNAMO_ROOT"),
                                  "molecularStructures",
                                  "gaussianGeometryOptimization")
        statesPath = os.path.join(sourcePath, "states.yaml")
        xyzPaths = glob.glob(os.path.join(sourcePath, "xyz", "*.xyz"))
        xyzPaths.sort()

        # . Get the states.
        states = YAMLUnpickle(statesPath)

        # . Loop over the molecules.
        reports = {}
        numberNotConverged = 0
        for xyzPath in xyzPaths:

            # . Basic set up.
            label = os.path.split(xyzPath)[1][0:-4]
            (charge, multiplicity) = states.get(label, (0, 1))
            system = XYZFile_ToSystem(xyzPath)
            system.electronicState = ElectronicState(charge=charge,
                                                     multiplicity=multiplicity)
            system.DefineQCModel(QCModelMNDO("am1", isSpinRestricted=True))
            system.Summary(log=log)

            # . Skip molecules that are too large.
            if len(system.atoms) > _MaximumMoleculeSize: continue

            # . Loop over the optimizers.
            tagReports = {}
            for (tag, minimizer, options) in _Minimizers:

                # . Reset the system.
                system.coordinates3 = XYZFile_ToCoordinates3(xyzPath)
                system.Energy(log=log)

                # . Minimization.
                keywordArguments = dict(options)
                keywordArguments["log"] = log
                cpu = CPUTime()
                tagReports[tag] = minimizer(system, **keywordArguments)
                tagReports[tag]["CPU Time"] = cpu.Current()
                if not tagReports[tag].get("Converged", False):
                    numberNotConverged += 1

            # . Save the results.
            reports[label] = tagReports

        # . Finish up.
        self.ReportsSummary(reports, log=log)
        self.assertTrue(numberNotConverged == 0)
 def __init__(self, *args):
     """Constructor."""
     super(CrystalQCMMTest, self).__init__(*args)
     # . Options.
     self.checkEnergies = False
     self.doLong = True
     self.doQCMM = True
     self.doQCQC = False
     self.geometryOptimize = True
     # . QC model.
     converger = DIISSCFConverger(densityTolerance=1.0e-8,
                                  maximumSCFCycles=250)
     self.qcModel = QCModelMNDO(converger=converger)
Пример #4
0
 def setUp(self):
     """Set up the calculation."""
     # . Set up the systems.
     self.qcmmTestSystems = qcmmTestSystems
     # . Define the QC models for each system.
     self.qcModels = {}
     for label in _qcModels:
         qcModels = []
         for qcModelOptions in _qcModels[label]:
             kwargs = {
                 key: value
                 for (key,
                      value) in zip(_qcModelKeywordLabels, qcModelOptions)
             }
             kwargs["converger"] = DIISSCFConverger(
                 densityTolerance=1.0e-11, maximumSCFCycles=250)
             kwargs["keepOrbitalData"] = True
             qcModels.append(QCModelMNDO("am1", **kwargs))
         self.qcModels[label] = qcModels
Пример #5
0
 def GetSystem(self, log=logFile):
     """Get the system with the energy model defined."""
     # . Define the QC model.
     kwargs = {
         key: value
         for (key, value) in zip(_qcModelKeywordLabels, self.qcModelOptions)
     }
     kwargs["converger"] = DIISSCFConverger(densityTolerance=1.0e-10,
                                            maximumSCFCycles=250)
     kwargs["keepOrbitalData"] = True
     kwargs.update(_AlgorithmKeywords)
     qcModel = QCModelMNDO("am1", **kwargs)
     # . Read the molecule.
     molecule = XYZFile_ToSystem(
         os.path.join(_dataPath, self.directory, self.label + ".xyz"))
     molecule.label = self.label
     molecule.electronicState = ElectronicState(
         charge=self.charge, multiplicity=self.multiplicity)
     molecule.DefineQCModel(qcModel)
     molecule.Summary(log=log)
     # . Finish up.
     return molecule
    def runTest ( self ):
        """The test."""

        # . Paths.
        dataPath = os.path.join ( os.getenv ( "PDYNAMO_PMOLECULE" ), "data", "mol" )
        if self.resultPath is None: outPath  = os.path.join ( os.getenv ( "PDYNAMO_SCRATCH" ), _Destination )
        else:                       outPath  = os.path.join ( self.resultPath                , _Destination )
        if not os.path.exists ( outPath ): os.mkdir ( outPath )
        log = self.GetLog ( )

        # . Energy models.
        mmModel = MMModelOPLS ( "protein" )
        nbModel = NBModelFull ( )
        qcModel = QCModelMNDO ( converger = DIISSCFConverger ( densityTolerance = 1.0e-10 ) )

        # . Initialization.
        numberFailures = 0

        # . Loop over molecules.
        for moleculeLabel in _MoleculeLabels:

            # . Get the system.
            system = MOLFile_ToSystem ( os.path.join ( dataPath, moleculeLabel + ".mol" ) )
            if moleculeLabel in _QCModels:
                system.DefineQCModel ( qcModel )
            else:
                system.DefineMMModel ( mmModel, log = log )
                system.DefineNBModel ( nbModel )
            system.Summary ( log = log )
            system.Energy  ( log = log )

            # . Minimize well.
            LBFGSMinimize_SystemGeometry ( system,
                                           log                  =           log ,
                                           logFrequency         = _LogFrequency ,
                                           maximumIterations    =   _Iterations ,
                                           rmsGradientTolerance =    _Tolerance )

            # . Normal mode analysis.
            nmState = NormalModes_SystemGeometry ( system, log = log )

            # . Do a dynamics simulation: equilibration and then data collection.
            normalDeviateGenerator = NormalDeviateGenerator.WithRandomNumberGenerator ( RandomNumberGenerator.WithSeed ( _Seed ) )
            LangevinDynamics_SystemGeometry ( system                                          ,
                                              collisionFrequency     = _CollisionFrequency    ,
                                              log                    = log                    ,
                                              logFrequency           = _LogFrequency          ,
                                              normalDeviateGenerator = normalDeviateGenerator ,
                                              steps                  = _NSteps0               ,
                                              temperature            = _Temperature           ,
                                              timeStep               = 0.001                  )
            reference3 = Clone ( system.coordinates3 )
            trajectory = AmberTrajectoryFileWriter ( os.path.join ( outPath, moleculeLabel + ".crd" ), system )
            LangevinDynamics_SystemGeometry ( system                                          ,
                                              collisionFrequency     = _CollisionFrequency    ,
                                              log                    = log                    ,
                                              logFrequency           = _LogFrequency          ,
                                              normalDeviateGenerator = normalDeviateGenerator ,
                                              steps                  = _NSteps1               ,
                                              temperature            = _Temperature           ,
                                              timeStep               = 0.001                  ,
                                              trajectories           = [ ( trajectory, _SaveFrequency ) ] )

            # . Check RMSs.
            masses = system.atoms.GetItemAttributes ( "mass" )
            rms0   = system.coordinates3.RMSDeviation ( reference3, weights = masses )
            system.coordinates3.Superimpose ( reference3, weights = masses )
            rms1 = system.coordinates3.RMSDeviation ( reference3, weights = masses )
            if ( math.fabs ( rms1 - rms0 ) >= _RMSAbsoluteErrorTolerance ): numberFailures += 1

            # . Do a quasi-harmonic analysis.
            trajectory = AmberTrajectoryFileReader ( os.path.join ( outPath, moleculeLabel + ".crd" ), system )
            qhState    = QuasiHarmonic_SystemGeometry ( system, log = log, temperature = _Temperature, trajectories = [ trajectory ] )

        # . Success/failure.
        self.assertTrue ( ( numberFailures == 0 ) )
    def runTest(self):
        """The test."""

        # . Output setup.
        dataPath = os.path.join(os.getenv("PDYNAMO_PMOLECULE"), "data", "mol")
        log = self.GetLog()

        # . Define the MM, NB and QC models.
        mmModel = MMModelOPLS("bookSmallExamples")
        nbModel = NBModelFull()
        qcModel = QCModelMNDO()

        # . Define the dimer with an MM model.
        dimer = MOLFile_ToSystem(os.path.join(dataPath, "waterDimer_cs.mol"))
        dimer.DefineMMModel(mmModel)
        dimer.Summary(log=log)

        # . Define the monomer selections.
        selection1 = Selection.FromIterable(range(0, 3))
        selection2 = Selection.FromIterable(range(3, 6))

        # . Get the monomer energies.
        e1 = self.MonomerEnergies(dimer, selection1, nbModel, qcModel, log=log)
        e2 = self.MonomerEnergies(dimer, selection2, nbModel, qcModel, log=log)

        # . Get the binding energies.
        e12 = {}
        for model1 in _Models:
            for model2 in _Models:
                key = model1 + " " + model2
                if log is not None:
                    log.Heading(model1 + "/" + model2 + " Dimer Calculation",
                                QBLANKLINE=True)
                # . Define the energy model.
                if key == "QC QC": dimer.DefineQCModel(qcModel)
                elif key == "QC MM":
                    dimer.DefineQCModel(qcModel, qcSelection=selection1)
                elif key == "MM QC":
                    dimer.DefineQCModel(qcModel, qcSelection=selection2)
                else:
                    dimer.energyModel.ClearQCModel(dimer.configuration)
                if "MM" in key: dimer.DefineNBModel(nbModel)
                dimer.Summary(log=log)
                # . Store the results.
                e12[key] = dimer.Energy(log=log) - e1[model1] - e2[model2]

        # . Output the results.
        if log is not None:
            keys = e12.keys()
            keys.sort()
            table = log.GetTable(columns=[20, 20, 20])
            table.Start()
            table.Title("Water Dimer Binding Energies")
            table.Heading("Monomer 1")
            table.Heading("Monomer 2")
            table.Heading("Binding Energy")
            for key in keys:
                (model1, model2) = key.split()
                table.Entry(model1)
                table.Entry(model2)
                table.Entry("{:.1f}".format(e12[key]))
            table.Stop()

        # . Success/failure.
        isOK = True
        for e in e12.values():
            if (e < _LowerBound) or (e > _UpperBound):
                isOK = False
                break
        self.assertTrue(isOK)
    def runTest(self):
        """The test."""

        # . Initialization.
        log = self.GetLog()
        numberErrors = 0
        if self.testGradients:
            maximumGradientDeviation = 0.0

        # . Loop over systems and QC models.
        labels = self.qcmmTestSystems.keys()
        labels.sort()
        for label in labels:
            testSystem = self.qcmmTestSystems[label]
            if testSystem.multiplicity != 1: continue

            # . Get the QC model.
            converger = DIISSCFConverger(densityTolerance=1.0e-10,
                                         maximumSCFCycles=250)
            qcModel = QCModelMNDO(
                "am1",
                converger=converger,
                isSpinRestricted=(testSystem.multiplicity == 1))

            # . Get the molecule.
            molecule = testSystem.GetSystem(log=log, qcModel=qcModel)

            # . Energy.
            try:
                energy = molecule.Energy(log=log, doGradients=True)

                # . Charges.
                charges = molecule.AtomicCharges()
                charges.Print(log=log, title="Charges")
                if log is not None:
                    log.Paragraph("Total Charge = {:.3f}".format(sum(charges)))
                charges = molecule.AtomicCharges(spinDensities=True)
                charges.Print(log=log, title="Spin Densities")
                if log is not None:
                    log.Paragraph("Total Spin Density = {:.3f}".format(
                        sum(charges)))

                # . Gradient testing.
                if self.testGradients and (len(molecule.atoms) <
                                           self.maximumAtoms):
                    of = SystemGeometryObjectiveFunction.FromSystem(molecule)
                    gradientDeviation = of.TestGradients(delta=1.0e-04,
                                                         log=log,
                                                         tolerance=1.0e-03)
                    maximumGradientDeviation = max(maximumGradientDeviation,
                                                   gradientDeviation)

            # . Error.
            except Exception as e:
                numberErrors += 1
                if log is not None:
                    log.Text("\nError occurred> " + e.args[0] + "\n")

        # . Get the observed and reference data.
        observed = {}
        referenceData = TestDataSet("MNDO QC/MM Energies")
        if self.testGradients:
            observed["Gradient Error"] = maximumGradientDeviation
            referenceData.AddDatum(
                TestReal(
                    "Gradient Error",
                    0.0,
                    referenceData,
                    absoluteErrorTolerance=_GradientAbsoluteErrorTolerance,
                    toleranceFormat="{:.3f}",
                    valueFormat="{:.3f}"))

        # . Check for success/failure.
        if len(observed) > 0:
            results = referenceData.VerifyAgainst(observed)
            results.Summary(log=log, fullSummary=self.fullVerificationSummary)
            isOK = results.WasSuccessful()
        else:
            isOK = True
        isOK = isOK and (numberErrors == 0)
        self.assertTrue(isOK)
Пример #9
0
from pMolecule import ElectronicState, QCModelDFT, QCModelMNDO

#===================================================================================================================================
# . Parameters.
#===================================================================================================================================
# . The destination for results.
_Destination = "gaussianCubeFiles"

# . The file extension.
_Extension = ".cube"

# . Grid spacing.
_GridSpacing = 0.3

# . Energy models.
_QCModels = [("am1", QCModelMNDO(keepOrbitalData=True)),
             ("dft", QCModelDFT(keepOrbitalData=True))]

# . The system.
_SystemLabel = "fch3cl"


#===================================================================================================================================
# . Class.
#===================================================================================================================================
class GaussianCubeFileWriteTest(TestCase):
    """A test case for writing Gaussian cube files."""
    def runTest(self):
        """The test."""

        # . Initialization.
Пример #10
0
import math, os.path

from pCore import logFile, LogFileActive, Selection, TestCase, TestDataSet, TestReal
from pMolecule import DIISSCFConverger, ElectronicState, MultiLayerSystemGeometryObjectiveFunction, NBModelABFS, QCModelDFT, QCModelMNDO, QCModelORCA
from QCMMTestSystems import qcmmTestSystems

#===================================================================================================================================
# . Parameters for system definitions.
#===================================================================================================================================
# . Model definitions.
_converger = DIISSCFConverger(densityTolerance=1.0e-8, maximumSCFCycles=250)
_qcModelDFT = QCModelDFT(converger=_converger,
                         densityBasis="demon",
                         orbitalBasis="321g")
_qcModelMNDO = QCModelMNDO(converger=_converger)
_qcModelORCA = QCModelORCA("HF:6-31G*", "SCFCONV10", "EXTREMESCF")
_nbModel = NBModelABFS()

# . Job data.
# . Options: doQCMM for bottom layer, QC model for upper layer and QC selection for upper layer.
_jobData = { "Water Dimer 1"     : ( ( False, _qcModelDFT,  Selection.FromIterable ( range (  3     ) ) ), \
                                     ( False, _qcModelORCA, Selection.FromIterable ( range (  3,  6 ) ) ), \
                                     ( True,  _qcModelDFT,  Selection.FromIterable ( range (  3     ) ) )  ), \
             "Water Dimer 2"     : ( ( True,  _qcModelORCA, Selection.FromIterable ( range (  3,  6 ) ) ), ), \
             "Cyclohexane 9"     : ( ( False, _qcModelDFT,  Selection.FromIterable ( range (  6     ) ) ), \
                                     ( True,  _qcModelORCA, Selection.FromIterable ( range (  3,  6 ) ) )  ), \
             "Alanine Dipeptide" : ( ( False, _qcModelDFT,  Selection.FromIterable ( range ( 10, 14 ) ) ), \
                                     ( False, _qcModelORCA, Selection.FromIterable ( range ( 10, 14 ) ) ), \
                                     ( True,  _qcModelDFT,  Selection.FromIterable ( range ( 10, 14 ) ) ), \
                                     ( True,  _qcModelORCA, Selection.FromIterable ( range ( 10, 14 ) ) )  ) }
Пример #11
0
#   orbitalBasis     - the orbital basis set. The default is "321g".
#   qcChargeModel    - the charge model to use in QC/MM interactions. Use the default for the moment which is "Lowdin".
#
# . Good combinations of orbital and density basis sets are (in increasing order of cost):
#
#   321g/demon; 631gs/ahlrichs; svp/weigend.
#
# . To perform QC/MM calculations, proceed in the usual way. Any of the NB models that can be used with
#   QCModelMNDO can also be used with QCModelDFT.
#

# . Define the SCF converger.
converger = DIISSCFConverger(densityTolerance=1.0e-8, maximumSCFCycles=25)

# . Define the energy models.
energyModels = [ QCModelMNDO ( "am1"  ),
                 QCModelDFT  ( converger = converger, densityBasis = "demon",    functional = "lda",  orbitalBasis = "321g"  ), \
                 QCModelDFT  ( converger = converger, densityBasis = "demon",    functional = "blyp", orbitalBasis = "321g"  ), \
                 QCModelDFT  ( converger = converger, densityBasis = "ahlrichs", functional = "lda",  orbitalBasis = "631gs" ), \
                 QCModelDFT  ( converger = converger, densityBasis = "ahlrichs", functional = "blyp", orbitalBasis = "631gs" ), \
                 QCModelDFT  ( converger = converger, densityBasis = "weigend",  functional = "lda",  orbitalBasis = "svp"   ), \
                 QCModelDFT  ( converger = converger, densityBasis = "weigend",  functional = "blyp", orbitalBasis = "svp"   )  ]

# . Get the fileName.
fileName = os.path.join(os.getenv("PDYNAMO_PMOLECULE"), "data", "xyz",
                        "water.xyz")

# . Loop over the energy models.
results = []
for model in energyModels:
    molecule = XYZFile_ToSystem(fileName)
Пример #12
0
    def runTest ( self ):
        """The test."""

        # . Initialization.
        failures      = 0
        otherFailures = 0
        successes     = 0

        # . Paths.
        dataPath = os.path.join ( os.getenv ( "PDYNAMO_PMOLECULE" ), "data", "pdb" )
        if self.resultPath is None: outPath  = os.path.join ( os.getenv ( "PDYNAMO_SCRATCH" ), _Destination )
        else:                       outPath  = os.path.join ( self.resultPath, _Destination )
        if not os.path.exists ( outPath ): os.mkdir ( outPath )
        log = self.GetLog ( )

        # . Models.
        mmModel = MMModelCHARMM ( "c36a2" )
        nbModel = NBModelABFS ( )
        qcModel = QCModelMNDO ( )

        # . Get the file.
        pdbFile = os.path.join ( dataPath, "2E4E_folded_solvated.pdb" )
        ( head, tail ) = os.path.split ( pdbFile )
        tag = tail[0:-4]

        if log is not None: log.Text ( "\nProcessing " + pdbFile + ":\n" )
        system = PDBFile_ToSystem ( pdbFile, log = log, useComponentLibrary = True )
        try:

            # . Fixed atoms.
            fixedAtoms = Selection ( ~ AtomSelection.FromAtomPattern ( system, "A:*:*" ) )

            # . QC selection.
            indices = set ( )
            for atomTag in _Tags:
                indices.add ( system.sequence.AtomIndex ( "A:TYR.2:" + atomTag ) )
            tyrosine = Selection ( indices )

            # . Setup.
            system.electronicState = ElectronicState ( charge = 0, multiplicity = 1 )
            system.DefineFixedAtoms ( fixedAtoms )
            system.DefineSymmetry   ( crystalClass = CrystalClassCubic ( ), a = _BoxSize )
            system.DefineMMModel    ( mmModel, log = log )
            system.DefineQCModel    ( qcModel, qcSelection = tyrosine )
            system.DefineNBModel    ( nbModel )
            system.Summary ( log = log )
            referenceEnergy = system.Energy  ( log = log, doGradients = True )

            # . Pickling.
            pklFile  = os.path.join ( outPath, tag + ".pkl"  )
            yamlFile = os.path.join ( outPath, tag + ".yaml" )
            Pickle     ( pklFile , system )
            YAMLPickle ( yamlFile, system )

            # . Unpickling.
            pklSystem = Unpickle ( pklFile )
            pklSystem.label += " (Pickled)"
            pklSystem.Summary ( log = log )
            pklEnergy = pklSystem.Energy  ( log = log, doGradients = True )
            if math.fabs ( referenceEnergy - pklEnergy  <= _Tolerance ): successes += 1
            else:                                                        failures  += 1

            yamlSystem = YAMLUnpickle ( yamlFile )
            yamlSystem.label += " (YAMLPickled)"
            yamlSystem.Summary ( log = log )
            yamlEnergy = yamlSystem.Energy  ( log = log, doGradients = True )
            if math.fabs ( referenceEnergy - yamlEnergy  <= _Tolerance ): successes += 1
            else:                                                         failures  += 1

        except Exception as e:
            otherFailures += 1
            if log is not None: log.Text ( "\nError occurred> " +  e.args[0] + "\n" )

        # . Summary of results.
        if log is not None:
            summary = log.GetSummary ( )
            summary.Start ( "Pickle Tests" )
            summary.Entry ( "Pickle Successes", "{:d}".format ( successes            ) )
            summary.Entry ( "Pickle Failures" , "{:d}".format ( failures             ) )
            summary.Entry ( "Total Tests"     , "2"                                    )
            summary.Entry ( "Loop Failures"   , "{:d}".format ( otherFailures        ) )
            summary.Stop  ( )

        # . Success/failure.
        self.assertTrue ( ( failures == 0 ) and ( otherFailures == 0 ) )
Пример #13
0
from pCore import TestCase, TestDataSet, TestReal, UNITS_ENERGY_ELECTRON_VOLTS_TO_KILOJOULES_PER_MOLE
from pMolecule import DIISSCFConverger, QCModelMNDO

# . UHF should give a lower energy than RHF. Problem with initial guess?

#===================================================================================================================================
# . Parameters.
#===================================================================================================================================
# . Distance parameters.
_NumberIncrements = 59
_XIncrement = 0.1
_XStart = 0.2

# . QC models.
# . MNDO is used because it gives good results.
_RestrictedQCModel = QCModelMNDO("mndo")
_UnrestrictedQCModel = QCModelMNDO("mndo", isSpinRestricted=False)
_S0CIQCModel = QCModelMNDO("mndo",
                           CIMethod="Full",
                           activeElectrons=2,
                           activeOrbitals=2,
                           requiredRoot=0,
                           rootMultiplicity=1)
_S1CIQCModel = QCModelMNDO("mndo",
                           CIMethod="Full",
                           activeElectrons=2,
                           activeOrbitals=2,
                           requiredRoot=1,
                           rootMultiplicity=1)
_T1CIQCModel = QCModelMNDO("mndo",
                           CIMethod="Full",
Пример #14
0
from pMolecule import CrystalClassCubic, ElectronicState, NBModelABFS, QCModelMNDO, SystemWithTimings
from pMoleculeScripts import LangevinDynamics_SystemGeometry, VelocityVerletDynamics_SystemGeometry

#===================================================================================================================================
# . Parameters.
#===================================================================================================================================
# . File and path names.
_TestDataFileName = "systemData.yaml"
_TestRootPath = "data"

# . Other options.
_CrystalClasses = {"Cubic": CrystalClassCubic()}
_DoDynamics = True
_ForceNoQC = False
_NBModel = NBModelABFS()
_QCModel = QCModelMNDO()
_QCRegionKey = "Large QC Region"  # "Small QC Region"
_Steps = 1000
_UseLangevin = True
_UseSystemWithTimings = True


#===================================================================================================================================
# . Functions.
#===================================================================================================================================
def FindTests():
    """Find the tests."""
    paths = glob.glob(os.path.join(_TestRootPath, "*"))
    tests = []
    for path in paths:
        if os.path.exists(os.path.join(path, _TestDataFileName)):
Пример #15
0
    def runTest(self):
        """The test."""

        # . Initialization.
        isOK = True
        log = self.GetLog()
        molPath = os.path.join(os.getenv("PDYNAMO_PMOLECULE"), "data", "mol")

        # . Options.
        converger = DIISSCFConverger(densityTolerance=1.0e-6,
                                     maximumSCFCycles=500)
        qcModel = QCModelMNDO("am1",
                              converger=converger,
                              isSpinRestricted=False)
        singlet = ElectronicState(charge=1, multiplicity=1)
        triplet = ElectronicState(charge=1, multiplicity=3)

        # . Optimizer.
        optimizer = QuasiNewtonMinimizer(logFrequency=1,
                                         maximumIterations=500,
                                         rmsGradientTolerance=0.05)
        optimizer.Summary(log=log)

        # . Set up the system.
        system = MOLFile_ToSystem(os.path.join(molPath, "phenylCation.mol"))
        system.electronicState = singlet
        system.label = "Phenyl Cation"
        system.DefineQCModel(qcModel)
        system.Summary(log=log)

        # . Check both methods.
        numberNotConverged = 0
        results = {}
        for method in ("GP", "PF"):

            # . Reset coordinates.
            system.coordinates3 = MOLFile_ToCoordinates3(
                os.path.join(molPath, "phenylCation.mol"))
            system.configuration.Clear()

            # . Set up the objective function.
            seamOF = SEAMObjectiveFunction.FromSystem(system,
                                                      singlet,
                                                      triplet,
                                                      method=method)
            #seamOF.RemoveRotationTranslation ( )

            # . Minimize.
            #seamOF.TestGradients ( delta = 1.0e-05 ) # . Works with 1.0e-10 density tolerance.
            cpu = CPUTime()
            report = optimizer.Iterate(seamOF, log=log)
            report["CPU Time"] = cpu.CurrentAsString()

            # . Final energies.
            (f1, f2) = seamOF.Energies(doGradients=True, log=log)
            report["Energy 1"] = f1
            report["Energy 2"] = f2
            results[method] = report
            if not report.get("Converged", False): numberNotConverged += 1

        # . Print out a summary of the results.
        if LogFileActive(log):
            table = log.GetTable(columns=[10, 20, 20, 10, 10, 20])
            table.Start()
            table.Title("Surface Crossing Optimizations")
            table.Heading("Method")
            table.Heading("State Energies", columnSpan=2)
            table.Heading("Converged")
            table.Heading("Calls")
            table.Heading("Time")
            for method in ("GP", "PF"):
                report = results[method]
                table.Entry(method, alignment="left")
                table.Entry("{:20.1f}".format(report["Energy 1"]))
                table.Entry("{:20.1f}".format(report["Energy 2"]))
                table.Entry("{!r}".format(report.get("Converged", False)))
                table.Entry("{:d}".format(report["Function Calls"]))
                table.Entry(report["CPU Time"])
            table.Stop()

        # . Finish up.
        self.assertTrue(numberNotConverged == 0)
Пример #16
0
                        { "energyBarrier"        :  505.0             ,
                          "amberTopologyFile"    : "ratchet.top"      ,
                          "energyProduct"        :  431.6             ,
                          "energyReactant"       :  431.6             ,
                          "mmModel"              : MMModelOPLS ( )    ,
                          "nbModel"              : NBModelFull ( )    ,
                          "productsFile"         : "ratchet_2.xyz"    ,
                          "reactantsFile"        : "ratchet_1.xyz"    ,
                          "setUpCoordinatesFile" : "ratchet.crd"      ,
                          "setUpMode"            : "amber"            },
                        { "energyBarrier"        :  991.0             ,
                          "energyProduct"        :  901.8             ,
                          "energyReactant"       :  901.8             ,
                          "isLong"               : True               ,
                          "productsFile"         : "ratchetAM1_2.xyz" ,
                          "qcModel"              : QCModelMNDO ( )    ,
                          "reactantsFile"        : "ratchetAM1_1.xyz" ,
                          "setUpCoordinatesFile" : "ratchetAM1_1.xyz" ,
                          "setUpMode"            : "xyz"              },
                        # . Triazene.
                        { "energyBarrier"        :  154.0             ,
                          "energyProduct"        :  -71.7             ,
                          "energyReactant"       :  -71.7             ,
                          "productsFile"         : "triazene_2.xyz"   ,
                          "qcModel"              : QCModelMNDO ( )    ,
                          "reactantsFile"        : "triazene_1.xyz"   ,
                          "setUpCoordinatesFile" : "triazene.xyz"     ,
                          "setUpMode"            : "xyz"              } )

#===================================================================================================================================
# . Class.