def runTest ( self ): """The test.""" # . Initialization. log = self.GetLog ( ) # . Set up the generators. _NVALUES = 11 generators = [ ( "Direct" , PairListGenerator ( minimumPoints = 100000 ) ) ] for i in range ( _NVALUES ): s = float ( i + 1 ) * 0.25 generators.append ( ( "CC {:6.3f}".format ( s ), PairListGenerator ( cutoffCellSizeFactor = s, minimumCellExtent = 0, minimumPoints = 100, sortIndices = False, useGridByCell = True ) ) ) for i in range ( _NVALUES ): s = float ( i + 1 ) * 0.25 generators.append ( ( "PC {:6.3f}".format ( s ), PairListGenerator ( cutoffCellSizeFactor = s, minimumCellExtent = 0, minimumPoints = 100, sortIndices = False, useGridByCell = False ) ) ) # . Loop over test systems. numberEnergyFailures = 0 for testSystem in testSystems: # . Get the system. system = testSystem.GetSystem ( log = log ) # . Energies. energies = [] for ( label, generator ) in generators: nbModel = NBModelABFS ( generator = generator ) nbModel.Summary ( log = log ) system.DefineNBModel ( nbModel ) cpuTime = CPUTime ( ) e = system.Energy ( doGradients = True, log = log ) c = cpuTime.CurrentAsString ( ) energies.append ( ( e, c, label ) ) system.configuration.nbState.StatisticsSummary ( log = log ) # . Print summary of results. if log is not None: e0 = energies[0][0] n = 0 table = log.GetTable ( columns = [ 6, 10, 16, 16, 16, 20 ] ) table.Start ( ) table.Title ( "Energies and CPU Times for {:s}:".format ( system.label ) ) for ( i, ( e, c, l ) ) in enumerate ( energies ): deltaE = math.fabs ( e - e0 ) if deltaE > 1.0e-2: n += 1 table.Entry ( "{:d}".format ( i ) ) table.Entry ( l ) table.Entry ( "{:15.3f}".format ( e ) ) table.Entry ( "{:15.3f}".format ( e0 ) ) table.Entry ( "{:15.3f}".format ( deltaE ) ) table.Entry ( " {:s}".format ( c ) ) table.Stop ( ) if log is not None: if n == 0: log.Paragraph ( "All tests were successful." ) else: log.Paragraph ( "{:d} tests failed.".format ( n ) ) numberEnergyFailures += n # . Check for success/failure. self.assertTrue ( ( numberEnergyFailures == 0 ) )
def __init__ ( self, **kwargs ): """Constructor.""" for ( attribute, value ) in kwargs.iteritems ( ): setattr ( self, attribute, value ) self.mmModel = MMModelOPLS ( ) self.nbModel = NBModelABFS ( ) self.p1Factor = 1.0
def runTest(self): """The test.""" # . Initialization. isOK = True numberErrors = 0 # . Energy models. mmModel = MMModelOPLS("protein") nbModel = NBModelABFS() # . Paths. dataPath = os.path.join(os.getenv("PDYNAMO_PBABEL"), "data") modelPath = os.path.join(dataPath, "pdbModel") pdbPath = os.path.join(dataPath, "pdb") outPath = None if self.resultPath is not None: outPath = os.path.join(self.resultPath, "xyz") log = self.GetLog() # . Set up the output directory. if outPath is not None: if not os.path.exists(outPath): os.mkdir(outPath) outFiles = glob.glob(os.path.join(outPath, "*.xyz")) for outFile in outFiles: os.remove(outFile) # . Get the files to process. modelFiles = glob.glob(os.path.join(modelPath, "*.model")) # . Get the model file names. pdbNames = set() for modelFile in modelFiles: (head, tail) = os.path.split(modelFile) pdbNames.add(tail[0:-6]) pdbNames = list(pdbNames) pdbNames.sort() # . Loop over the files. for pdbName in pdbNames: # . Check file names. modelFile = os.path.join(modelPath, pdbName + ".model") pdbFile = os.path.join(pdbPath, pdbName + ".pdb") if os.path.exists(modelFile) and os.path.exists(pdbFile): # . Get the model and its raw counterpart. model1 = PDBModel_FromModelFile(modelFile, log=log) rawModel = PDBFile_ToPDBModel(pdbFile, log=log) # . Route 1 - make an atomic model. model1.Summary(log=log) try: # . Make the atomic model. model1.MakeAtomicModelFromComponentLibrary(log=log) model1.ExtractAtomData(rawModel, log=log) model1.Summary(log=log) # . Make a system. system1 = model1.MakeSystem() system1.Summary(log=log) # . Add energy models. system1.DefineMMModel(mmModel, log=log) system1.DefineNBModel(nbModel) # . Build as many undefined coordinates as possible. if system1.coordinates3.numberUndefined > 0: rng = RandomNumberGenerator.WithSeed(117513) BuildHydrogenCoordinates3FromConnectivity( system1, log=log, randomNumberGenerator=rng) # . Calculate an energy if all coordinates have been defined. if system1.coordinates3.numberUndefined <= 0: system1.Energy(log=log, doGradients=True) # . Error. except Exception as e: numberErrors += 1 if log is not None: log.Text("\nError occurred> " + e.args[0] + "\n") # . Route 2 - extract atoms. model2 = PDBModel_FromModelFile(modelFile, log=log) model2.ExtractAtoms(rawModel, log=log) model2.Summary(log=log) system2 = model2.MakeSystem() system2.Summary(log=log) # . Output the xyz file if there are no undefined coordinates. n = system2.coordinates3.numberUndefined if n > 0: if log is not None: log.Paragraph( "System has {:d} undefined coordinates.".format(n)) elif outPath is not None: XYZFile_FromSystem(os.path.join(outPath, pdbName + ".xyz"), system2) # . Separator. if log is not None: log.Separator() # . Success/failure. self.assertTrue(isOK and (numberErrors == 0))
def runTest(self): """The test.""" # . Paths. dataPath = os.path.join(os.getenv("PDYNAMO_PMOLECULE"), "data", "pdb") log = self.GetLog() # . Models. mmModel = MMModelOPLS("protein") nbModel = NBModelABFS() # . Get all files. pdbFiles = glob.glob(os.path.join(dataPath, "*.pdb")) pdbFiles.sort() # . Read all PDB files. numberFailed = 0 for pdbFile in pdbFiles: if log is not None: log.Text("\nProcessing " + pdbFile + ":\n") system = PDBFile_ToSystem(pdbFile, log=log, useComponentLibrary=True) BuildHydrogenCoordinates3FromConnectivity(system) try: # . Setup. if system.coordinates3.numberUndefined > 0: raise system.DefineMMModel(mmModel, log=log) system.DefineNBModel(nbModel) system.Summary(log=log) system.Energy(log=log, doGradients=True) # . Selection. selector = SQLAtomSelector(system) # . Standard selections. aromatics = selector.aromatics backbone = selector.backbone boundaryAtoms = selector.boundaryAtoms counterions = selector.counterions heavyAtoms = selector.heavyAtoms hydrogens = selector.hydrogens mmAtoms = selector.mmAtoms polymerAtoms1 = selector.linearPolymerAtoms protein = selector.protein qcAtoms = selector.qcAtoms ringAtoms = selector.ringAtoms water = selector.water # . Where selections. nearOrigin1 = selector.Where("X*X + Y*Y + Z*Z < 25.0") positive = selector.Where("Charge > 0.0") threonines1 = selector.Where("Path LIKE '%:THR.%:%'") threonines2 = selector.Where("ResNam='THR'") # . Atom selection methods. nearOrigin2 = nearOrigin1.Within(5.0).ByComponent() polymerAtoms2 = threonines1.ByLinearPolymer() neighbors = threonines1.ByBondedNeighbor(iterations=3) # . Atom selection operators. complementNearOrigin2 = ~nearOrigin2 null = (nearOrigin2 & complementNearOrigin2) total1 = (nearOrigin2 | complementNearOrigin2) total2 = (nearOrigin2 ^ complementNearOrigin2) # . Basic checks. n = len(system.atoms) isOK = ( len ( boundaryAtoms ) == 0 ) and \ ( len ( qcAtoms ) == 0 ) and \ ( len ( mmAtoms ) == n ) and \ ( len ( heavyAtoms ) + len ( hydrogens ) == n ) and \ ( len ( polymerAtoms1 ) == len ( polymerAtoms2 ) ) and \ ( len ( counterions ) + len ( protein ) + len ( water ) == n ) and \ ( len ( threonines1 ) == len ( threonines2 ) ) and \ ( len ( null ) == 0 ) and \ ( len ( total1 ) == len ( total2 ) ) and \ ( len ( total1 ) == n ) if not isOK: raise except Exception as e: numberFailed += 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("SQL Atom Selection Tests") summary.Entry("Successes", "{:d}".format(len(pdbFiles) - numberFailed)) summary.Entry("Failures", "{:d}".format(numberFailed)) summary.Stop() # . Success/failure. self.assertTrue((numberFailed == 0))
from pCore import Selection, Pickle, Unpickle from pMolecule import NBModelABFS from pMoleculeScripts import BuildHydrogenCoordinates3FromConnectivity # . Define the atoms IDs and the parameters. _ToBuild = ( ( "A:LYS.8:CB" , "A:LYS.8:CA" , "A:LYS.8:N" , "A:LYS.8:CG" , 1.54, 109.5, 0.0 ), \ ( "I:SER.17:OG", "I:SER.17:CB", "I:SER.17:CA", "A:ATP.400:PG", 1.40, 109.5, 0.0 ) ) # . Get the system. system = Unpickle ( os.path.join ( outPath, "step4.pkl" ) ) system.Summary ( ) # . Build the coordinates of the missing heavy atoms. for ( id1, id2, id3, id4, r, theta, phi ) in _ToBuild: i = system.sequence.AtomIndex ( id1 ) j = system.sequence.AtomIndex ( id2 ) k = system.sequence.AtomIndex ( id3 ) l = system.sequence.AtomIndex ( id4 ) system.coordinates3.BuildPointFromDistanceAngleDihedral ( i, j, k, l, r, theta, phi ) # . Build the hydrogen atom coordinates. BuildHydrogenCoordinates3FromConnectivity ( system ) # . Save the system. Pickle ( os.path.join ( outPath, "step6.pkl" ), system ) # . Calculate an energy if all atoms now have coordinates. if system.coordinates3.numberUndefined <= 0: system.DefineNBModel ( NBModelABFS ( ) ) system.Energy ( doGradients = True )
sys.path.append ( os.path.join ( os.path.dirname ( os.path.realpath ( __file__ ) ), "..", "data" ) ) from Definitions import outPath from pBabel import PDBFile_FromSystem from pCore import Clone, NormalDeviateGenerator, Pickle, RandomNumberGenerator, Selection, Unpickle from pMolecule import AtomSelection, MMModelOPLS, NBModelABFS, SoftConstraintContainer, SoftConstraintEnergyModelHarmonic, SoftConstraintMultipleTether from pMoleculeScripts import ConjugateGradientMinimize_SystemGeometry, LangevinDynamics_SystemGeometry, SolvateSystemBySuperposition # . Parameters. # . Refine options. _Optimize = True _Refine = True _Steps = 2000 # . Define the MM and NB models. nbModel = NBModelABFS ( ) # . Get the solute system. solute = Unpickle ( os.path.join ( outPath, "step8_a.pkl" ) ) solute.Summary ( ) # . Get the solvent system. solvent = Unpickle ( os.path.join ( outPath, "waterBox.pkl" ) ) solvent.DefineNBModel ( nbModel ) solvent.Summary ( ) # . Create the solvated system. solution = SolvateSystemBySuperposition ( solute, solvent, reorientSolute = False ) solution.label = "Solvated PKA Simulation System - Chains A and I Only" solution.DefineNBModel ( nbModel ) solution.Summary ( )
def runTest ( self ): """The test.""" # . 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" ) # mmModel = MMModelOPLS ( "protein" ) nbModel = NBModelABFS ( ) # . Get all files. pdbFiles = glob.glob ( os.path.join ( dataPath, "*.pdb" ) ) pdbFiles.sort ( ) # . Read all PDB files. failures = 0 otherFailures = 0 successes = 0 for pdbFile in pdbFiles: ( 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 ) BuildHydrogenCoordinates3FromConnectivity ( system ) try: # . Setup. if system.coordinates3.numberUndefined > 0: raise system.DefineMMModel ( mmModel, log = log ) 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" , "{:d}".format ( 2 * len ( pdbFiles ) ) ) summary.Entry ( "Loop Failures" , "{:d}".format ( otherFailures ) ) summary.Stop ( ) # . Success/failure. self.assertTrue ( ( failures == 0 ) and ( otherFailures == 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. observed = {} gromacsReference = True # . We have two references: One for energies obtained with Gromacs; another for pDynamo energies if gromacsReference: referenceDataPath = os.path.join( os.getenv("PDYNAMO_PBABEL"), "data", "reference/GromacsTopCrdRead_gromacsValues.pkl") else: referenceDataPath = os.path.join( os.getenv("PDYNAMO_PBABEL"), "data", "reference/GromacsTopCrdRead_pDynamoValues.pkl") # . Output setup. dataPath = os.path.join(os.getenv("PDYNAMO_PBABEL"), "data", "gromacs") outPath = None self.resultPath = dataPath if self.resultPath is not None: outPath = os.path.join(self.resultPath, "pdb") if not os.path.exists(outPath): os.mkdir(outPath) log = self.GetLog() # . Generate systems. for label in _SystemLabels: # . Force field. for ff in _ForceFields: # . Header. if log is not None: log.Text("\n" + (120 * "=") + "\n") log.Text(label + "-" + ff + "\n") log.Text(120 * "=" + "\n") # . Get the parameters. filename = os.path.join(dataPath, label + "_" + ff) parameters = GromacsParameters_ToParameters(filename + ".top", log=log) system = GromacsDefinitions_ToSystem(filename + ".top", parameters=parameters, log=log) system.coordinates3 = GromacsCrdFile_ToCoordinates3(filename + ".gro", log=log) system.label = label if hasattr(system.configuration, "symmetryParameters"): system.DefineNBModel(NBModelABFS(**ABFS_options)) else: system.DefineNBModel(NBModelFull()) system.Summary(log=log) energy = system.Energy(log=log) log.Text("\nEnergy (kcal/mole) = {:.4f}\n".format( energy / UNITS_ENERGY_KILOCALORIES_PER_MOLE_TO_KILOJOULES_PER_MOLE)) # . Get the dictionary of energies. localObserved = system.configuration.energyTerms.Terms( asDictionary=True) localObserved["Potential Energy"] = energy # . U-B term in Gromacs includes harmonic angle contribution, but not in pDynamo. Their sum should be equal, though. if gromacsReference and (ff == "CHARMM"): localObserved["Harmonic Angle + U-B"] = localObserved[ "Harmonic Angle"] + localObserved["Urey-Bradley"] del localObserved["Harmonic Angle"] del localObserved["Urey-Bradley"] # . Test gradients. if len(system.atoms) <= _MaximumAtoms: of = SystemGeometryObjectiveFunction.FromSystem(system) of.TestGradients(log=log) localObserved["Gradient Error"] = of.TestGradients(log=log) # . Write PDB file if outPath is not None: PDBFile_FromSystem(os.path.join(outPath, label + ".pdb"), system) # . Accumulate current data dataLabel = label + "-" + ff observed[dataLabel] = localObserved # . Verify the observed data against the reference data. referenceData = Unpickle(referenceDataPath) results = referenceData.VerifyAgainst(observed) isOK = results.WasSuccessful() results.Summary(log=log, fullSummary=True) # . Success/failure. self.assertTrue(isOK)
#=========================================================== logFile.Header("Infrared fluorescent protein (parent)") parameters = ( "par_all27_prot_na.inp", "par.inp", ) mol = CHARMMPSFFile_ToSystem( "parent_waterbox.psf", isXPLOR=True, parameters=CHARMMParameterFiles_ToParameters(parameters)) mol.coordinates3 = XYZFile_ToCoordinates3("geometry.xyz") mol.Summary() nb_model = NBModelABFS() mol.DefineNBModel(nb_model) #=========================================================== # traj = XTCTrajectoryFileWriter ("saved_geometry.xtc", mol) # traj.WriteOwnerData () # traj.Summary () #=========================================================== traj3 = XTCTrajectoryFileWriter("optimize.xtc", mol) ConjugateGradientMinimize_SystemGeometry(mol, logFrequency=1, maximumIterations=50, rmsGradientTolerance=0.04, trajectories=[(traj3, 1)]) traj3.Summary()
def runTest ( self ): """The test.""" # . Paths. dataPath = os.path.join ( os.getenv ( "PDYNAMO_PMOLECULE" ), "data", "mol2" ) 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 ( ) # . NB models. nbModelNoC = NBModelABFS ( useCentering = False ) nbModelC = NBModelABFS ( useCentering = True ) # . Set up the system. system = ImportSystem ( os.path.join ( dataPath, "waterBox.mol2" ), log = log ) system.DefineMMModel ( MMModelOPLS ( "bookSmallExamples" ) ) system.DefineNBModel ( nbModelC ) system.Summary ( log = log ) system.Energy ( log = log ) # . Do a short dynamics. # . Define a normal deviate generator in a given state. normalDeviateGenerator = NormalDeviateGenerator.WithRandomNumberGenerator ( RandomNumberGenerator.WithSeed ( 614108 ) ) # . Dynamics. trajectoryPath = os.path.join ( outPath, "waterBox_C_1ps.dcd" ) trajectory = DCDTrajectoryFileWriter ( trajectoryPath, system ) LangevinDynamics_SystemGeometry ( system , collisionFrequency = 25.0 , log = log , logFrequency = _NLog , normalDeviateGenerator = normalDeviateGenerator , steps = _NSteps , temperature = 300.0 , timeStep = 0.001 , trajectories = [ ( trajectory, _NSave ) ] ) # . Calculate trajectory energies with different NB models. energies = [] for ( i, nbModel ) in enumerate ( ( nbModelC, nbModelNoC ) ): system.DefineNBModel ( nbModel ) trajectory = DCDTrajectoryFileReader ( trajectoryPath, system ) trajectory.ReadHeader ( ) e = [] while trajectory.RestoreOwnerData ( ): e.append ( system.Energy ( log = None ) ) trajectory.Close ( ) energies.append ( e ) # . Check deviations. ( e0, e1 ) = energies maximumDeviation = 0.0 for i in range ( len ( e0 ) ): maximumDeviation = max ( maximumDeviation, math.fabs ( e0[i] - e1[i] ) ) # . Summary of results. if log is not None: log.Paragraph ( "Maximum deviation = {:.5f}".format ( maximumDeviation ) ) # . Success/failure. self.assertTrue ( ( maximumDeviation <= _Tolerance ) )