def AddLinearConstraint ( self, constraint ): """Add a linear constraint.""" if len ( constraint ) != self.nvariables: raise ValueError ( "Invalid linear constraint length." ) # . Orthogonalize to existing constraints. if self.linearVectors is not None: constraint = Clone ( constraint ) self.linearVectors.ProjectOutOfArray ( constraint ) # . Check to see if the constraint is valid. cnorm2 = constraint.Norm2 ( ) if cnorm2 > 1.0e-10: constraint.Scale ( 1.0 / cnorm2 ) # . Allocate space for new constraints. ncolumns = 1 if self.linearVectors is not None: ncolumns += self.linearVectors.columns newconstraints = Real2DArray.WithExtents ( len ( constraint ), ncolumns ) # . Copy over constraints. if self.linearVectors is not None: for r in range ( self.linearVectors.rows ): for c in range ( self.linearVectors.columns ): newconstraints[r,c] = self.linearVectors[r,c] for r in range ( len ( constraint ) ): newconstraints[r,ncolumns-1] = constraint[r] self.linearVectors = newconstraints # . Determine the linear scalars. self.linearScalars = Real1DArray.WithExtent ( self.linearVectors.columns ) reference = Real1DArray.WithExtent ( self.linearVectors.rows ) if self.rtReference is None: self.system.coordinates3.CopyToArray ( reference ) else: self.rtReference.CopyToArray ( reference ) self.linearVectors.VectorMultiply ( reference, self.linearScalars, 1.0, 0.0, transpose = True ) # . Reset the number of degrees of freedom. self.degreesOfFreedom = self.nvariables - len ( self.linearScalars )
def FromSystem(selfClass, system, electronicState1, electronicState2, method="GP"): """Constructor given a system.""" # . Basic setup. system.electronicState = electronicState1 self = super(SEAMObjectiveFunction, selfClass).FromSystem(system) self.method = method # . Define the first system. self.system1 = self.system # . Define the second system without coordinates. coordinates3 = self.system1.coordinates3 symmetryParameters = self.system1.symmetryParameters self.system1.coordinates3 = None self.system1.symmetryParameters = None self.system2 = Clone(self.system1) self.system2.electronicState = electronicState2 # . Reset the coordinates for both systems so that they are the same. self.system1.coordinates3 = coordinates3 self.system2.coordinates3 = coordinates3 if symmetryParameters is not None: self.system1.symmetryParameters = symmetryParameters self.system2.symmetryParameters = symmetryParameters # . Allocate space. self.g1 = Real1DArray.WithExtent(len(self)) self.g2 = Real1DArray.WithExtent(len(self)) # . Finish up. return self
def CrystalAnalyzeTransformations(system, log=logFile): """Analyze the transformations for a crystal. Transformations must be either proper or improper rotations and have inverses. An inverse check needs to be added. """ # . Basic checks. if LogFileActive(log) and isinstance(system, System) and (system.symmetry is not None): # . Get the lattice matrices for the system. sp = system.configuration.symmetryParameters M = sp.M inverseM = sp.inverseM # . Loop over the transformations. for (i, t3) in enumerate(system.symmetry.transformations): # . Output the transformation. newt3 = Clone(t3) newt3.Orthogonalize(M, inverseM) newt3.Print(log=log, title="Transformation {:d}".format(i)) # . Check for a rotation of some sort. if newt3.rotation.IsProperRotation(): log.Paragraph("Transformation is a proper rotation.") elif newt3.rotation.IsImproperRotation(): log.Paragraph("Transformation is an improper rotation.") else: log.Paragraph( "Transformation is neither a proper nor an improper rotation." )
def RemoveRotationTranslation(inTrajectory, outTrajectory, system, reference3=None, useWeights=True): """Remove rotational and translational motion from a trajectory.""" # . Reference structure. # . Use the first trajectory structure if none specified. if reference3 is system.coordinates3: reference3 = Clone(system.coordinates3) # . Get weights. if useWeights: masses = system.atoms.GetItemAttributes("mass") else: masses = None # . Loop over trajectory frames. inTrajectory.ReadHeader() outTrajectory.WriteHeader() while inTrajectory.RestoreOwnerData(): if reference3 is None: reference3 = Clone(system.coordinates3) else: system.coordinates3.Superimpose(reference3, weights=masses) outTrajectory.WriteOwnerData() inTrajectory.ReadFooter() outTrajectory.WriteFooter() inTrajectory.Close() outTrajectory.Close()
def RemoveRotationTranslation ( self, reference = None ): """Remove rotation and translational degrees of freedom. |reference| is the reference coordinates. Nothing is done if there are fixed atoms. Weighting is done using |atomWeights| if it is has been defined. """ if self.freeAtoms is None: # . Check that RT can be removed. #QNOTETHER = ( SoftConstraints_Number_Of_Tethers ( system->constraints ) == 0 ) #QROTATION = QNOTETHER && ( ! Symmetry_Is_Periodic ( system->symmetry ) ) #QTRANSLATION = QNOTETHER QROTATION = ( self.system.symmetry is None ) or ( ( self.system.symmetry is not None ) and ( self.system.symmetry.crystalClass is None ) ) QTRANSLATION = True #print "Rotation and Translation Flags = ", QROTATION, QTRANSLATION # . Remove RT. if QROTATION or QTRANSLATION: # . Assign the reference coordinates and modify the system coordinates if necessary. if reference is None: self.rtReference = Clone ( self.system.coordinates3 ) else: self.rtReference = Clone ( reference ) self.system.coordinates3.Superimpose ( self.rtReference, weights = self.atomWeights ) # . Get the RT vectors. ( self.linearVectors, self.linearScalars ) = self.rtReference.RotationTranslationVectors ( QROTATION, QTRANSLATION, dimension = self.nvariables, weights = self.atomWeights ) self.degreesOfFreedom = self.nvariables - len ( self.linearScalars )
def Prune(self, selection): """Pruning.""" pruned = None if self.point in selection: pruned = self.__class__(selection.Position(self.point), Clone(self.origin), Clone(self.energyModel)) return pruned
def Prune(self, selection): """Pruning.""" new = None if (self.i in selection) and (self.j in selection): new = Clone(self) new.i = selection.Position(self.i) new.j = selection.Position(self.j) return new
def NormalModesTrajectory_SystemGeometry(system, trajectory, cycles=10, frames=21, mode=0, state=None, temperature=300.0): """Generate a normal mode trajectory.""" # . Get the state. if state is None: state = system.configuration.nmState # . Get state-related information. if state.freeAtoms == None: freeAtoms = range(len(system.atoms)) else: freeAtoms = state.freeAtoms frequencies = state.frequencies modes = state.modes # . Get the mode frequency. omega = math.fabs(frequencies[mode]) # . Calculate the number of frames. total = cycles * frames # . Check for a calculation. if (mode >= 0) and (mode < state.dimension) and ( omega > _LOWFREQUENCY) and (total > 0): # . Calculate the amplitude (in Angstroms). amplitude = math.sqrt( 2.0 * 1.0e-3 * CONSTANT_AVOGADRO_NUMBER * CONSTANT_BOLTZMANN * temperature) * (_TO_WAVENUMBERS / omega) # . Allocate space for the coordinates and mode. coordinates3 = Clone(system.coordinates3) displacement = Coordinates3.WithExtent(len(system.atoms)) displacement.Set(0.0) # . Get the displacement. for f in freeAtoms: displacement[f, 0] = modes[mode, 3 * f] displacement[f, 1] = modes[mode, 3 * f + 1] displacement[f, 2] = modes[mode, 3 * f + 2] # . Loop over the cycles and frames. # . Calculate the displacement prefactor using sine instead of cosine. trajectory.WriteHeader(temperature=temperature) for c in range(cycles): for f in range(frames): factor = amplitude * math.sin( 2.0 * math.pi * float(f) / float(frames)) coordinates3.CopyTo(system.coordinates3) system.coordinates3.AddScaledMatrix(factor, displacement) trajectory.WriteOwnerData() # . Finish up. trajectory.WriteFooter() trajectory.Close()
def ToSystem ( self, mmModel = None ): """Create a system.""" system = None if self.QPARSED: # . Sequence data and then basic system. sequence = self.ToSequence ( ) system = System.FromSequence ( sequence ) system.label = " ".join ( self.title ) # . Assign atomic numbers using atomic numbers if they exist, otherwise masses. atomicNumbers = getattr ( self, "atomic_number", None ) if atomicNumbers is None: for ( mass, atom ) in zip ( self.mass, system.atoms ): atom.atomicNumber = PeriodicTable.AtomicNumberFromMass ( mass ) else: for ( n, atom ) in zip ( atomicNumbers, system.atoms ): atom.atomicNumber = n # . The MM model (with some options). if mmModel is None: mmModel = MMModelAMBER ( ) # . 1-4 scaling factors. if hasattr ( self, "scee_scale_factor" ): mmModel.electrostaticScale14 = 1.0 / self.scee_scale_factor[0] if hasattr ( self, "scnb_scale_factor" ): mmModel.lennardJonesScale14 = 1.0 / self.scnb_scale_factor[0] # . Define the model. system.DefineMMModel ( mmModel, buildModel = False ) # . The MM atoms. mm = self.ToMMAtomContainer ( ) if mm is not None: system.energyModel.mmAtoms = mm # . Various MM terms. mmTerms = [] mm = self.ToHarmonicBondContainer ( ) if mm is not None: mmTerms.append ( mm ) mm = self.ToHarmonicAngleContainer ( ) if mm is not None: mmTerms.append ( mm ) self.UntangleDihedralsAnd14s ( ) if self.dihedrals is not None: mmTerms.append ( self.dihedrals ) if self.impropers is not None: mmTerms.append ( self.impropers ) if len ( mmTerms ) > 0: system.energyModel.mmTerms = MMTermContainer ( mmTerms ) # . Remaining MM data. if self.interactions14 is not None: system.energyModel.interactions14 = self.interactions14 mm = self.ToExclusionsPairList ( ) if mm is not None: system.energyModel.exclusions = mm mm = self.ToLJParameterContainer ( mmModel.lennardJonesStyle ) if mm is not None: system.energyModel.ljParameters = mm # . 1-4 parameters. scale = mmModel.lennardJonesScale14 if scale != 0.0: lj14 = Clone ( mm ) lj14.label = "1-4 Lennard-Jones" lj14.Scale ( scale ) system.energyModel.ljParameters14 = lj14 # . Symmetry data. self.ToSymmetry ( system ) return system
def _WriteMEADFiles(self, system, systemCharges, systemRadii): """For each instance of each site, write: - PQR file for the site - PQR file for the model compound - OGM file for the site - MGM file for the model compound""" grids = [] model = self.parent for stepIndex, (nodes, resolution) in enumerate(model.focusingSteps): if stepIndex < 1: grids.append("ON_GEOM_CENT %d %f\n" % (nodes, resolution)) else: x, y, z = self.center grids.append("(%f %f %f) %d %f\n" % (x, y, z, nodes, resolution)) selectSite = Selection(self.siteAtomIndices) selectModel = Selection(self.modelAtomIndices) # . In the PQR file of the model compound, charges of the site atoms must be set to zero (requirement of the my_2diel_solver program) chargesZeroSite = Clone(systemCharges) for atomIndex in self.siteAtomIndices: chargesZeroSite[atomIndex] = 0.0 for instance in self.instances: PQRFile_FromSystem( instance.modelPqr, system, selection=selectModel, charges=chargesZeroSite, radii=systemRadii, ) # . Update system charges with instance charges chargesInstance = Clone(systemCharges) for chargeIndex, atomIndex in enumerate(self.siteAtomIndices): chargesInstance[atomIndex] = instance.charges[chargeIndex] PQRFile_FromSystem( instance.sitePqr, system, selection=selectSite, charges=chargesInstance, radii=systemRadii, ) del chargesInstance # . Write OGM and MGM files (they have the same content) for fileGrid in (instance.modelGrid, instance.siteGrid): WriteInputFile(fileGrid, grids) del chargesZeroSite
def setUp(self): """Set up the calculation.""" # . Set up the systems. self.testSystems = [] for values in GetRadicalMoleculeData(): # . Basic keyword arguments. kwargs = Clone(values) # . Specific keyword arguments. kwargs["convergerKeywords"] = self.ConvergerKeywords() kwargs["qcModelArguments"] = self.QCModelArguments() kwargs["qcModelClass"] = self.QCModelClass() qcModelKeywords = kwargs.get("qcModelKeywords", {}) qcModelKeywords.update(self.QCModelKeywords()) kwargs["qcModelKeywords"] = qcModelKeywords # . Get the system. self.testSystems.append(QCTestSystem(**kwargs))
def Merge(self, indexIncrement): """Merging.""" new = Clone(self) new.point1 += indexIncrement new.point2 += indexIncrement new.point3 += indexIncrement return new
def Prune(self, selection): """Pruning.""" pruned = None if ( self.point1 in selection ) and \ ( self.point2 in selection ): pruned = self.__class__ ( selection.Position ( self.point1 ), \ selection.Position ( self.point2 ), Clone ( self.energyModel ) ) return pruned
def WHAM_Bootstrapping(paths, **keywordArguments): """Solve the WHAM equations and estimate errors using bootstrapping.""" # . Get specific options. options = dict(keywordArguments) log = options.get("log", logFile) minimizer = options.pop("minimizerFunction", WHAM_ConjugateGradientMinimize) resamples = options.pop("resamples", _Default_Resamples) # . Initial minimization - it must succeed to proceed. results = minimizer(paths, **dict(options)) if results["Converged"]: # . Reset options for resampling. options["handler"] = results.pop("Handler") options["histogram"] = Clone(results.pop("Unreduced Histogram")) options["log"] = None # . Resampling minimizations. pmfs = [] for r in range(resamples): localResults = minimizer(paths, **dict(options)) if localResults["Converged"]: pmfs.append(localResults.pop("PMF")) # . Process results. numberOfResamples = len(pmfs) results.update({ "Number Of Resamples": numberOfResamples, "PMFs": pmfs }) if numberOfResamples > 1: # . Gather some counters. lowerIndex = int(math.ceil( 0.5 * _Alpha * float(numberOfResamples))) - 1 upperIndex = int( math.floor( (1.0 - 0.5 * _Alpha) * float(numberOfResamples))) - 1 # . Do statistics. originalPMF = results["PMF"] lowerLimit = Real1DArray.WithExtent(len(originalPMF)) standardError = Real1DArray.WithExtent(len(originalPMF)) upperLimit = Real1DArray.WithExtent(len(originalPMF)) work = Real1DArray.WithExtent(numberOfResamples) for b in range(len(originalPMF)): for (r, pmf) in enumerate(pmfs): work[r] = pmf[b] work.Sort() m = originalPMF[b] lowerLimit[b] = 2.0 * m - work[upperIndex] upperLimit[b] = 2.0 * m - work[lowerIndex] standardError[b] = Statistics(work).standardDeviation # . Printing. data = (("Standard Error", standardError), ("Lower 95% Confidence Interval", lowerLimit), ("Upper 95% Confidence Interval", upperLimit)) _BootstrappingSummary(results["Histogram"], log, numberOfResamples, originalPMF, standardError, lowerLimit, upperLimit) # . Finish up. for (key, value) in data: results[key] = value return results
def CrystalCenterCoordinates(system, log=logFile, mode="bymmisolate", selection=None): """Center the coordinates of a system in the primary image.""" # . Initialization. coordinates3 = None translations = None # . Basic checks. if isinstance(system, System) and (system.symmetry is not None) and ( system.coordinates3 is not None) and (system.symmetryParameters is not None): # . Check the centering mode. option = mode.lower() if (option not in _CENTERINGOPTIONS): raise ValueError("Unknown centering mode: " + option + ".") # . Get a set of cloned coordinates. coordinates3 = Clone(system.coordinates3) # . By atom. if (option == "byatom"): system.symmetryParameters.CenterCoordinatesByAtom( coordinates3, selection=selection) # . By isolate. elif (option == "byisolate"): if (system.isolates is None): raise ValueError("Isolates for the system are not defined.") else: system.symmetryParameters.CenterCoordinatesByIsolate( coordinates3, system.isolates, selection=selection) # . By MM isolate. elif (option == "bymmisolate"): mmisolates = _GetMMIsolates(system) system.symmetryParameters.CenterCoordinatesByIsolate( coordinates3, mmisolates, selection=selection) # . Get the translations. translations = Clone(coordinates3) translations.AddScaledMatrix(-1.0, system.coordinates3) return (coordinates3, translations)
def Prune(self, selection): """Pruning.""" pruned = None # . Get reduced selection. reduced = self.selection.Prune(selection) if len(reduced) > 0: pruned = self.__class__(reduced, self.reference.Prune(selection), Clone(self.energyModel)) return pruned
def runTest(self): """The test.""" # . Paths. dataPath = os.path.join(os.getenv("PDYNAMO_PMOLECULE"), "data", "mol") log = self.GetLog() # . Get the system. molecule = MOLFile_ToSystem( os.path.join(dataPath, "tyrosineDipeptide.mol")) molecule.DefineMMModel(MMModelOPLS("protein")) molecule.DefineNBModel(NBModelFull()) molecule.Summary(log=log) molecule.Energy(log=log, doGradients=True) # . Save initial coordinates. reference3 = Clone(molecule.coordinates3) # . Do some dynamics. normalDeviateGenerator = NormalDeviateGenerator.WithRandomNumberGenerator( RandomNumberGenerator.WithSeed(247171)) LangevinDynamics_SystemGeometry( molecule, collisionFrequency=25.0, log=log, logFrequency=1000, normalDeviateGenerator=normalDeviateGenerator, steps=_NSteps, temperature=300.0, timeStep=0.001) # . Check RMSs which should be the same as rotation and translation are removed. masses = molecule.atoms.GetItemAttributes("mass") rms0 = molecule.coordinates3.RMSDeviation(reference3, weights=masses) molecule.coordinates3.Superimpose(reference3, weights=masses) rms1 = molecule.coordinates3.RMSDeviation(reference3, weights=masses) # . Get the observed and reference data. observed = {"RMS Deviation": rms1} referenceData = TestDataSet("Rotation/Translation Removal") referenceData.AddDatum( TestReal("RMS Deviation", rms0, referenceData, absoluteErrorTolerance=_RMSAbsoluteErrorTolerance, 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 self.assertTrue(isOK)
def MakeLennardJones14Parameters(self): """Make an appropriate container of LJ Parameters for the 1-4 interactions.""" lj = self.lennardJonesParameters scale = self.lennardJonesScale14 # . Remove 1-4 parameters if the scaling is zero. if scale == 0.0: lj14 = None # . Processing only if LJs are present too. elif lj is not None: # . Clone and scale. lj14 = Clone(lj) lj14.termLabel = "1-4 Lennard-Jones" lj14.ScaleEnergies(scale) # . Update by any predefined 1-4 values. oldLJ14 = self.lennardJones14Parameters if oldLJ14 is not None: lj14.UpdateParameters(oldLJ14) # . Reset the 14 parameters. self.lennardJones14Parameters = lj14
def Merge(self, indexIncrement): """Merging.""" new = None # . Loop over distances. distances = [] for (point1, point2, weight) in self.distances: distances.append( (point1 + indexIncrement, point2 + indexIncrement, weight)) # . Create object. if len(distances) > 0: new = self.__class__(distances, Clone(self.energyModel)) return new
def __init__(self, energyModel): """Constructor.""" if isinstance(energyModel, SoftConstraintEnergyModel): period = self.Period() QCLONE = ((period is None) and energyModel.isPeriodic) or ( (period is not None) and not energyModel.isPeriodic) if QCLONE: self.energyModel = Clone(energyModel) else: self.energyModel = energyModel self.energyModel.period = period self.energyModel.isPeriodic = (period is not None) else: raise TypeError("Invalid energy model.")
def Prune(self, selection, information={}): """Pruning.""" pruned = None if self.mmModel is not None: # . Basic data. pruned = self.__class__() if self.label is not None: pruned.label = Clone(self.label) if self.mmModel is not None: pruned.mmModel = Clone(self.mmModel) if (self.nbModel is not None) and (self.qcModel is None): pruned.nbModel = Clone(self.nbModel) # . Other attributes. for attribute in ("exclusions", "interactions14", "ljParameters", "ljParameters14", "mmAtoms", "mmTerms", "softConstraints"): item = getattr(self, attribute) if hasattr(item, "Prune"): prunedItem = item.Prune(selection, information=information) if prunedItem is not None: setattr(pruned, attribute, prunedItem) # . Finish up. pruned.ActivateMMTerms() return pruned
def Prune(self, selection): """Pruning.""" pruned = None # . Loop over distances. reduced = [] for (point1, point2, weight) in self.distances: if (point1 in selection) and (point2 in selection): reduced.append((selection.Position(point1), selection.Position(point2), weight)) # . Create object. if len(reduced) > 0: pruned = self.__class__(reduced, Clone(self.energyModel)) return pruned
def setUp(self): """Set up the calculation.""" # . Get basic options. convergerKeywords = self.ConvergerKeywords() qcModelClass = self.QCModelClass() qcModelOptions = self.QCModelOptions() # . Set up the systems for each set of options. self.testSystems = [] for values in GetClosedShellMoleculeData(): for (i, (arguments, keywords)) in enumerate(qcModelOptions): # . Basic keyword arguments. kwargs = Clone(values) # . Specific keyword arguments. kwargs["convergerKeywords"] = convergerKeywords kwargs["qcModelArguments"] = arguments kwargs["qcModelClass"] = qcModelClass qcModelKeywords = kwargs.get("qcModelKeywords", {}) qcModelKeywords.update(keywords) kwargs["qcModelKeywords"] = qcModelKeywords kwargs["modelLabel"] = self.modelLabels[i] # . Get the system. self.testSystems.append(QCTestSystem(**kwargs))
def Superimpose(self, reference3=None, weights=None): """Superimpose the trajectory on a reference structure using the first trajectory frame by default.""" # . Initialization. coordinates3 = self.owner.coordinates3 # . Save the owner coordinates to restore later. saved3 = Clone(coordinates3) # . Get the reference coordinates. if reference3 is coordinates3: reference3 = saved3 elif reference3 is None: self.RestoreOwnerData(index=0) reference3 = Clone(coordinates3) # . Loop over trajectory frames. results = [] for index in range(self.frames): self.RestoreOwnerData(index=index) rms0 = coordinates3.RMSDeviation(reference3, weights=weights) coordinates3.Superimpose(reference3, weights=weights) rms1 = coordinates3.RMSDeviation(reference3, weights=weights) self.WriteOwnerData(index=index) results.append((rms0, rms1)) # . Finish up. saved3.CopyTo(coordinates3) return results
def DefineQCLayer ( self, selection, qcModel, electronicState = None ): """Define a QC layer. A layer consists of two subsystems with the same atomic composition. One uses the new energy model and a weight of +1 whereas the second has the old energy model and a weight of -1. """ # . Get the latest defined system. if len ( self.subsystems ) > 0: number = len ( self.subsystems ) oldsystem = self.subsystems[-1].system else: number = 0 oldsystem = self.system # . Get the QC atom indices of the full system (excluding boundary atoms). try: oldqcset = set ( oldsystem.energyModel.qcAtoms.GetFullSelection ( ) ).difference ( set ( oldsystem.energyModel.qcAtoms.BoundaryAtomSelection ( ) ) ) except: raise ValueError ( "Unable to retrieve the previous system's QC atom indices." ) # . Map a subsystem's indices to those of the full system. if len ( self.subsystems ) > 0: mapping = self.subsystems[-1].selection unmapped = oldqcset oldqcset = set ( ) for i in unmapped: oldqcset.add ( mapping[i] ) # . Check that the selection is a subset of the previous one. newqcset = set ( selection ) if not newqcset.issubset ( oldqcset ): raise ValueError ( "The atoms in the new QC layer must be a subset of the QC atoms in the underlying system." ) # . Get the old QC model (which at this stage is known to exist). oldmodel = oldsystem.energyModel.qcModel # . Find the atomic numbers. atomicNumbers = self.system.atoms.GetItemAttributes ( "atomicNumber", selection = selection ) # . Find boundary atoms. boundaryAtoms = self.FindBoundaryAtoms ( selection, len ( atomicNumbers ) ) # . Extend atomicNumbers by the appropriate number of boundary atom hydrogens. atomicNumbers.extend ( len ( boundaryAtoms ) * [ 1 ] ) # . Define a basic QC system - it is cleaner to do this for a QC system from scratch without pruning, etc. system0 = System.FromAtoms ( atomicNumbers ) if electronicState is not None: system0.electronicState = electronicState system0.coordinates3 = Coordinates3.WithExtent ( len ( system0.atoms ) ) system0.coordinates3.Set ( 0.0 ) # . Define the subsystems of the layer. system1 = Clone ( system0 ) for ( i, ( system, model, weight ) ) in enumerate ( ( ( system0, oldmodel, -1.0 ), ( system1, qcModel, 1.0 ) ) ): system.label = "MultiLayer Objective Function Subsystem {:d} with Weight {:.1f}".format ( number+i, weight ) system.DefineQCModel ( model ) subsystem = MultiLayerSubsystem ( system, weight, selection, boundaryAtoms = boundaryAtoms ) subsystem.VariablesPut ( self.system.coordinates3 ) self.subsystems.append ( subsystem )
def PDBFile_ToSystem(fileName, additionalData=None, altLoc=None, embeddedHydrogens=False, libraryPaths=None, log=logFile, modelNumber=0, pqrFormat=False, useComponentLibrary=False): """Helper function that returns a system defined by the atom data in a PDB file. This function will rarely work on an experimental PDB file. In these cases it will be necessary to pass by an explicit definition of the PDB model. """ # . Parse the file. inFile = PDBFileReader(fileName) inFile.Parse(log=log, pqrFormat=pqrFormat) inFile.Summary(log=log) # . Get the model. if (modelNumber == 0) and (len(inFile.models) > 1): modelNumber = 1 model = inFile.GetModel(modelNumber=modelNumber) # . Use the PDB component library. if useComponentLibrary: # . Build the model. rawModel = Clone(model) model.ClearAtoms() model.MakeAtomicModelFromComponentLibrary(libraryPaths=libraryPaths, log=log) model.ExtractAtomData(rawModel, log=log) model.Summary(log=log) # . Order hydrogens within each component. model.OrderHydrogens(embedded=embeddedHydrogens) # . Make the system. system = model.MakeSystem(altLoc=altLoc) # . Check if additional data is to be returned. if (additionalData is not None) and (len(additionalData) > 0): results = [system] for attribute in additionalData: results.append(model.MakeData(attribute, altLoc=altLoc)) results = tuple(results) else: results = system # . Finish up. return results
def PruneToQCRegion(self): """Return a system consisting of the QC region, including boundary atoms.""" # . Initialization. qcRegion = None # . Do nothing if there is no QC region. if (self.energyModel is not None) and (self.energyModel.qcModel is not None): # . Get the atoms to retain. toKeep = self.energyModel.qcAtoms.GetFullSelection() # . Prune the system. qcRegion = self.Prune(toKeep) # . Other attributes. qcRegion.coordinates3 = self.energyModel.qcAtoms.GetCoordinates3( self.coordinates3) if self.label is None: qcRegion.label = "QC Region" else: qcRegion.label = self.label + " - QC Region" # . Electronic state and QC model. qcRegion.electronicState = Clone(self.electronicState) qcRegion.DefineQCModel(self.energyModel.qcModel) # . Finish up. return qcRegion
def LinearlyInterpolate(selfClass, path, system, npoints, point0, pointn): """Generate structures on a trajectory by linear interpolation between two end points.""" # . Check the number of points. npoints = max(npoints, 2) # . Check for fixed atoms. hasFixedAtoms = (system.hardConstraints is not None) and ( system.hardConstraints.NumberOfFixedAtoms() > 0) # . Create the trajectory. self = selfClass(path, system, mode="w") # . Create an intermediate array. xyz = Clone(pointn) if not hasFixedAtoms: xyz.Superimpose(point0) # . Find the step. dxyz = Clone(xyz) dxyz.AddScaledMatrix(-1.0, point0) dxyz.Scale(1.0 / float(npoints - 1)) # . First point. self.WriteFrame(point0) # . Intermediate and last points. point0.CopyTo(xyz) for i in range(npoints - 1): xyz.AddScaledMatrix(1.0, dxyz) self.WriteFrame(xyz) return self
def Merge(self, atomIncrement): """Merging.""" new = Clone(self) new.i += atomIncrement new.j += atomIncrement return new
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 ) )