def GetSystem ( self, doQCMM = False, doQCQC = False, expandToP1 = False, log = logFile, qcModel = None, useSymmetry = True ):
     """Get the system with the energy model defined."""
     # . Read the molecule.
     molecule              = AmberTopologyFile_ToSystem  ( os.path.join ( _dataPath, self.label + ".top" ), mmModel = self.mmModel, log = log )
     molecule.coordinates3 = AmberCrdFile_ToCoordinates3 ( os.path.join ( _dataPath, self.label + ".crd" ), log = log )
     molecule.label        = self.label
     # . Set up symmetry.
     if useSymmetry:
         kwargs = { "crystalClass" : self.crystalClass, "transformations" : self.transformations }
         kwargs.update ( self.crystalParameters )
         molecule.DefineSymmetry ( **kwargs )
         if expandToP1:
             self.p1Factor = float ( len ( molecule.symmetry.transformations ) * _numberCells )
             molecule      = CrystalExpandToP1 ( molecule, aRange = _aRange, bRange = _bRange, cRange = _cRange )
     # . Set up the QC model.
     if qcModel is not None:
         # . QC/MM.
         if doQCMM:
             if self.qcCharge != 0: molecule.electronicState = ElectronicState ( charge = self.qcCharge )
             # . For the tests do not worry if the MM charge is not zero or integral.
             try:    molecule.DefineQCModel ( qcModel, qcSelection = self.qcSelection )
             except: pass
         else:
             molecule.DefineQCModel ( qcModel )
     # . Set up the NB model.
     if ( qcModel is None ) or doQCMM or doQCQC: molecule.DefineNBModel  ( self.nbModel )
     # . Summary.
     if LogFileActive ( log ):
         molecule.Summary ( log = log )
         log.Paragraph ( "\nFormula = " + molecule.atoms.FormulaString ( ) + "." )
     # . Finish up.
     return molecule
 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 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
Example #4
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)
Example #5
0
 def ToSystem ( self ):
     """Return a system."""
     system = None
     if self.QPARSED:
         system                 = System.FromAtoms ( self.atomicNumbers )
         system.label           = self.title
         system.coordinates3    = self.ToCoordinates3 ( )
         system.electronicState = ElectronicState ( charge = self.charge, multiplicity = self.multiplicity )
     return system
 def ToElectronicState(self, frameIndex=-1):
     """Return an electronic state object."""
     if self.QPARSED:
         frame = self.frames[frameIndex]
         charge = frame.GetItem("Charge", default=0)
         multiplicity = frame.GetItem("Multiplicity", default=1)
         return ElectronicState(charge, multiplicity)
     else:
         return None
Example #7
0
 def ToElectronicState(self):
     """Return an electronic state object."""
     if self.QPARSED:
         if hasattr(self, "charge"): charge = self.charge
         else: charge = 0
         if hasattr(self, "multiplicity"): multiplicity = self.multiplicity
         else: multiplicity = 1
         return ElectronicState(charge, multiplicity)
     else:
         return None
Example #8
0
    def runTest(self):
        """The test."""

        # . Initialization.
        isOK = True

        # . Output setup.
        dataPath = os.path.join(os.getenv("PDYNAMO_PMOLECULE"), "data", "xyz")
        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()

        # . Loop over energy models.
        for (qcLabel, qcModel) in _QCModels:

            # . Read the system.
            molecule = XYZFile_ToSystem(
                os.path.join(dataPath, _SystemLabel + ".xyz"))
            molecule.electronicState = ElectronicState(charge=-1)
            molecule.DefineQCModel(qcModel)
            molecule.Summary(log=log)
            molecule.Energy(log=log)

            # . Orbital energies.
            (energies, H**O,
             LUMO) = molecule.energyModel.qcModel.OrbitalEnergies(
                 molecule.configuration)
            if log is not None:
                if energies is not None:
                    energies.Print(log=log, title="Orbital Energies")
                log.Paragraph("H**O and LUMO indices: {:d}, {:d}.".format(
                    H**O, LUMO))
            indices = [H**O, LUMO]

            # . Write out the cube files.
            GaussianCubeFile_FromSystemDensity(os.path.join(
                outPath,
                _SystemLabel + "_" + qcLabel + "_density" + _Extension),
                                               molecule,
                                               gridspacing=_GridSpacing,
                                               log=log)
            GaussianCubeFile_FromSystemOrbitals(os.path.join(
                outPath,
                _SystemLabel + "_" + qcLabel + "_orbitals" + _Extension),
                                                molecule,
                                                gridspacing=_GridSpacing,
                                                orbitals=indices,
                                                log=log)
        #    GaussianCubeFile_FromSystemPotential ( os.path.join ( outPath, _SystemLabel + "_" + qclabel + "_potential" + _Extension ), molecule, gridspacing = _GridSpacing, log = log )

        # . Success/failure.
        self.assertTrue(isOK)
Example #9
0
def SetUpSystem(path, forceNoQC=False, useSystemWithTimings=True):
    """Set up the system."""
    # . Get system data.
    systemData = YAMLUnpickle(os.path.join(path, _TestDataFileName))
    # . Get the parameters.
    parameters = CHARMMParameterFiles_ToParameters(
        glob.glob(os.path.join(path, "*.prm")))
    # . Get the test name.
    name = os.path.split(path)[-1]
    # . Generate the system.
    system = CHARMMPSFFile_ToSystem(os.path.join(path, name + ".psfx"),
                                    isXPLOR=True,
                                    parameters=parameters)
    if useSystemWithTimings: system = SystemWithTimings.FromSystem(system)
    system.coordinates3 = XYZFile_ToCoordinates3(
        os.path.join(path, name + ".xyz"))
    system.label = systemData["Label"]
    # . Symmetry.
    if systemData.get("Crystal Class", None) is not None:
        symmetryOptions = systemData["Symmetry Parameters"]
        symmetryOptions["crystalClass"] = _CrystalClasses[
            systemData["Crystal Class"]]
        system.DefineSymmetry(**symmetryOptions)
    # . QC data.
    if not forceNoQC:
        qcData = systemData.get(_QCRegionKey, None)
        if qcData is not None:
            # . Electronic state.
            system.electronicState = ElectronicState(
                charge=qcData.get("Charge", 0),
                multiplicity=qcData.get("Multiplicity", 1))
            # . QC atoms.
            qcAtoms = set()
            for path in qcData["Atoms"]:
                index = system.sequence.AtomIndex(path)
                qcAtoms.add(index)
            system.DefineQCModel(_QCModel, qcSelection=Selection(qcAtoms))
    # . Finish set up.
    system.DefineNBModel(_NBModel)
    return system
 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 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
    def runTest(self):
        """The test."""

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

        # . Loop over systems and jobs.
        labels = self.jobs.keys()
        labels.sort()
        for label in labels:
            testSystem = self.qcmmTestSystems[label]
            for (doQCMM, qcModelU, qcSelectionU) in self.jobs.get(label, []):

                # . Check if ORCA tests are to be skipped.
                if self.skipORCATests and (qcModelU is _qcModelORCA): continue

                # . Get the molecule.
                molecule = testSystem.GetSystem(doQCMM=doQCMM,
                                                log=log,
                                                nbModel=_nbModel,
                                                qcModel=_qcModelMNDO)

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

                    # . Define the object function.
                    of = MultiLayerSystemGeometryObjectiveFunction.FromSystem(
                        molecule)

                    # . First layer.
                    of.DefineQCLayer(qcSelectionU,
                                     qcModelU,
                                     electronicState=ElectronicState(charge=0))
                    of.SubsystemSummary(log=log)

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

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

                # . Clear up.
                finally:
                    if qcModelU is _qcModelORCA: _qcModelORCA.DeleteJobFiles()

        # . Get the observed and reference data.
        observed = {}
        referenceData = TestDataSet("ONIOM 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)
Example #13
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 ) )
    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)