def GetSystem(self, doQCMM=True, log=logFile, nbModel=None, qcModel=None):
     """Get the system with the energy model defined."""
     # . Basic setup.
     molecule = MOLFile_ToSystem(
         os.path.join(self.dataPath, self.fileName + ".mol"))
     molecule.label = self.label
     molecule.DefineMMModel(self.mmModel)
     # . Set up the QC model.
     if qcModel is not None:
         molecule.electronicState = ElectronicState(
             charge=self.qcCharge, multiplicity=self.multiplicity)
         if doQCMM:
             molecule.DefineQCModel(qcModel, qcSelection=self.qcSelection)
         else:
             molecule.DefineQCModel(qcModel)
     # . Set up the NB model.
     if (qcModel is None) or doQCMM:
         if nbModel is None: molecule.DefineNBModel(self.nbModel)
         else: molecule.DefineNBModel(nbModel)
     # . Summary.
     if LogFileActive(log):
         molecule.Summary(log=log)
         log.Paragraph("\nFormula = " + molecule.atoms.FormulaString() +
                       ".")
     # . Finish up.
     return molecule
 def GetSystem(self, log=logFile, maximumAtoms=None):
     """Get the system with the energy model defined."""
     # . Get the QC model options.
     convergerKeywords = getattr(self, "convergerKeywords", {})
     qcModelArguments = getattr(self, "qcModelArguments", [])
     qcModelClass = getattr(self, "qcModelClass", None)
     qcModelKeywords = getattr(self, "qcModelKeywords", {})
     # . Basic setup.
     if self.fileFormat == "mol":
         molecule = MOLFile_ToSystem(
             os.path.join(self.dataPath, self.fileName + ".mol"))
     elif self.fileFormat == "xyz":
         molecule = XYZFile_ToSystem(
             os.path.join(self.dataPath, self.fileName + ".xyz"))
     molecule.electronicState = ElectronicState(
         charge=getattr(self, "charge", 0),
         multiplicity=getattr(self, "multiplicity", 1))
     molecule.label = self.label
     # . Only keep the molecule if it is not too large.
     if (maximumAtoms is None) or ((maximumAtoms is not None) and
                                   (len(molecule.atoms) <= maximumAtoms)):
         # . Define the QC model.
         if qcModelClass is not None:
             converger = DIISSCFConverger(**convergerKeywords)
             kwargs = dict(qcModelKeywords)
             kwargs["converger"] = converger
             qcModel = qcModelClass(*qcModelArguments, **kwargs)
             molecule.DefineQCModel(qcModel, log=log)
         # . Summary.
         if LogFileActive(log):
             molecule.Summary(log=log)
             log.Paragraph("\nFormula = " + molecule.atoms.FormulaString() +
                           ".")
     # . Molecule rejected.
     else:
         molecule = None
     # . Finish up.
     return molecule
示例#3
0
    def runTest(self):
        """The test."""

        # . Initialization.
        dataPath = os.path.join(os.getenv("PDYNAMO_PMOLECULE"), "data", "mol")
        log = self.GetLog()
        translation = Vector3.Uninitialized()

        # . Get the individual systems.
        energies = []
        molecules = []
        for (i, label) in enumerate(_Molecules):
            molecule = MOLFile_ToSystem(os.path.join(dataPath, label + ".mol"))
            molecule.label = label
            molecule.DefineMMModel(_mmModel)
            molecule.DefineNBModel(_nbModel)
            molecule.Summary(log=log)
            molecule.coordinates3.TranslateToCenter()
            molecule.configuration.Clear()
            energies.append(molecule.Energy(log=log, doGradients=True))
            molecules.append(molecule)

        # . Data initialization.
        observed = {}
        referenceData = TestDataSet("Merge/Prune Energies")

        # . Loop over the tests.
        for (testIndex, (moleculeFrequencies,
                         moleculePruneIndices)) in enumerate(_Tests):

            # . Heading.
            if log is not None:
                log.Heading("Merge/Prune Test {:d}".format(testIndex),
                            QBLANKLINE=True)

            # . Initialization.
            mergedEnergy = 0.0
            prunedEnergy = 0.0
            translation.Set(0.0)

            # . Gather items.
            index = 0
            numberAtoms = 0
            pruneIndices = []
            toMerge = []
            for (i, frequency) in enumerate(moleculeFrequencies):
                molecule = molecules[i]
                mergedEnergy += energies[i] * frequency
                for f in range(frequency):
                    cloned = Clone(molecule)
                    translation[0] += _Displacement
                    cloned.coordinates3.Translate(translation)
                    toMerge.append(cloned)
                    if index in moleculePruneIndices:
                        pruneIndices.extend(
                            range(numberAtoms,
                                  numberAtoms + len(cloned.atoms)))
                        prunedEnergy += energies[i]
                    index += 1
                    numberAtoms += len(cloned.atoms)

            # . Merging.
            merged = toMerge[0].Merge(toMerge[1:])
            merged.Summary(log=log)
            eMerged = merged.Energy(log=log)

            # . Pruning.
            pruned = merged.Prune(Selection.FromIterable(pruneIndices))
            pruned.Summary(log=log)
            ePruned = pruned.Energy(log=log)

            # . Get the observed and reference data.
            for (tag, eObserved,
                 eReference) in (("Merged Energy {:d}".format(testIndex),
                                  eMerged, mergedEnergy),
                                 ("Pruned Energy {:d}".format(testIndex),
                                  ePruned, prunedEnergy)):
                observed[tag] = eObserved
                referenceData.AddDatum(
                    TestReal(
                        tag,
                        eReference,
                        referenceData,
                        absoluteErrorTolerance=_EnergyAbsoluteErrorTolerance,
                        toleranceFormat="{:.3f}",
                        valueFormat="{:.3f}"))

        # . Finish up.
        if log is not None: log.Separator()

        # . 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

        # . Success/failure.
        self.assertTrue(isOK)
    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)