Ejemplo n.º 1
0
    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)
Ejemplo n.º 2
0
def BuildSolventBox ( crystalClass, symmetryParameters, molecule, density, log = logFile, randomNumberGenerator = None ):
    """Build a solvent box.

    No attempt is made to avoid overlapping molecules as it is assumed this will be corrected in a subsequent optimization process.
    """

    # . Initialization.
    solvent = None

    # . Find the number of solvent molecules that fit in the box.
    nmolecules = SolventMoleculeNumber ( molecule, symmetryParameters, density )

    # . Check the number of molecules.
    if nmolecules > 0:

        # . Create the solvent system.
        molecule.coordinates3.ToPrincipalAxes ( )
        solvent = MergeRepeatByAtom ( molecule, nmolecules )
        solvent.DefineSymmetry ( crystalClass = crystalClass, a     = symmetryParameters.a,     \
                                                              b     = symmetryParameters.b,     \
                                                              c     = symmetryParameters.c,     \
                                                              alpha = symmetryParameters.alpha, \
                                                              beta  = symmetryParameters.beta,  \
                                                              gamma = symmetryParameters.gamma  )

        # . Check the random number generator.
        if randomNumberGenerator is None: randomNumberGenerator = RandomNumberGenerator.WithRandomSeed ( )

        # . Do random rotations and translations.
        natoms      = len ( molecule.atoms )
        rotation    = Matrix33.Null ( )
        selection   = Selection.FromIterable ( range ( natoms ) )
        translation = Vector3.Null ( )
        for i in range ( nmolecules ):
            rotation.RandomRotation ( randomNumberGenerator )
            solvent.coordinates3.Rotate  ( rotation,    selection = selection )
            for j in range ( 3 ): translation[j] = randomNumberGenerator.NextReal ( )
            symmetryParameters.M.ApplyTo ( translation )
            solvent.coordinates3.Translate ( translation, selection = selection )
            selection.Increment ( natoms )

        # . Do some printing.
        if LogFileActive ( log ):
            summary = log.GetSummary ( )
            summary.Start ( "Cubic Solvent Box Summary" )
            summary.Entry ( "Number of Molecules", "{:d}"  .format ( nmolecules                        ) )
            summary.Entry ( "Density (kg m^-3)",   "{:.3f}".format ( SystemDensity ( solvent )         ) )
            summary.Entry ( "Box Volume",          "{:.3f}".format ( solvent.symmetryParameters.volume ) )
            summary.Stop ( )

    # . Return the system.
    return solvent
Ejemplo n.º 3
0
    def runTest(self):
        """The test."""

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

        # . Define the molecule.
        molecule = XYZFile_ToSystem(
            os.path.join(dataPath, "xyz", "serineOctamerZD4L4.xyz"))
        molecule.Summary(log=log)

        # . Define the randomNumberGenerator so as to have reproducible results.
        randomNumberGenerator = RandomNumberGenerator.WithSeed(314159)

        # . Do the test - 250000+ trajectories are generally necessary.
        observed = HardSphereIonMobilities(
            molecule,
            nreflections=30,
            ntrajectories=100000,
            log=log,
            randomNumberGenerator=randomNumberGenerator)

        # . Remove non-real values.
        keys = observed.keys()
        for key in keys:
            if not isinstance(observed[key], float): del observed[key]

        # . Generate the reference data.
        if self.generateReferenceData:
            referenceData = TestDataSet("Ion Mobilities")
            for (key, value) in observed.iteritems():
                referenceData.AddDatum(
                    TestReal(key,
                             value,
                             referenceData,
                             percentErrorTolerance=_percentErrorTolerance))
            referenceData.Summary(log=log)
            Pickle(self.referenceDataPath, referenceData)
            isOK = True
        # . Verify the observed data against the reference data.
        else:
            referenceData = Unpickle(self.referenceDataPath)
            results = referenceData.VerifyAgainst(observed)
            results.Summary(log=log, fullSummary=self.fullVerificationSummary)
            isOK = results.WasSuccessful()

        # . Success/failure.
        self.assertTrue(isOK)
Ejemplo n.º 4
0
def BuildHydrogenCoordinates3FromConnectivity(system,
                                              log=logFile,
                                              randomNumberGenerator=None):
    """Build hydrogen coordinates.

    The coordinates are built using connectivity information only (bonds
    and angles) which means that no account is taken of non-connectivity
    information (such as hydrogen-bonding). These interactions will have
    to be optimized separately using energy minimization or dynamics.

    Note that bonds to other hydrogens are ignored and unbound hydrogens
    or hydrogens linked to more than one heavy atom will not be built."""

    # . Check for a system object.
    if isinstance(system, System) and (system.connectivity is not None) and (
            system.connectivity.HasFullConnectivity()):

        # . Check whether there are undefined coordinates.
        coordinates3 = system.coordinates3
        numberUndefined0 = coordinates3.numberUndefined
        if numberUndefined0 > 0:

            # . Initialization.
            bonds = system.connectivity.bonds
            direction = Vector3.Null()
            if randomNumberGenerator is None:
                randomNumberGenerator = RandomNumberGenerator.WithRandomSeed()

            # . Loop over heavy atoms with defined coordinates.
            for (c, atom) in enumerate(system.atoms):
                if (atom.atomicNumber !=
                        1) and (c not in coordinates3.undefined):

                    # . Initialization.
                    built = []
                    builth = []
                    tobuild = []
                    unbuildable = []

                    # . Loop over the connected atoms.
                    others = bonds.GetConnectedAtoms(c)
                    for i in others:
                        other = system.atoms[i]
                        QBUILT = (i not in coordinates3.undefined)
                        # . Hydrogens.
                        if other.atomicNumber == 1:
                            if QBUILT: builth.append(i)
                            elif len(bonds.GetConnectedAtoms(i)) == 1:
                                tobuild.append(i)
                            else:
                                unbuildable.append(i)
                        # . Other atoms.
                        else:
                            if QBUILT: built.append(i)
                            else: unbuildable.append(i)

                    # . Skip this atom if the number of connections is greater than four, there are no hydrogens to build or there are unbuildable atoms.
                    if (len(others) > 4) or (len(tobuild)
                                             == 0) or (len(unbuildable) > 0):
                        continue

                    # . Order the lists and put built hydrogens after built heavy atoms as it is reasoned that heavy atom coordinates will be more reliable.
                    built.sort()
                    builth.sort()
                    tobuild.sort()
                    built += builth

                    # . Get coordination data for the center.
                    nconnections = len(built) + len(tobuild)
                    bondlength = PeriodicTable.Element(
                        atom.atomicNumber).GetSingleBondDistance(1)
                    if bondlength is None: bondlength = _DEFAULTBONDDISTANCE
                    angle = PeriodicTable.Element(
                        atom.atomicNumber).GetCoordinationAngle(nconnections)
                    if angle is None:
                        angle = _COORDINATIONANGLES.get(nconnections, 0.0)
                    planeangle = _COORDINATIONPLANEANGLES.get(
                        nconnections, 0.0)

                    # . Build the hydrogens.
                    while len(tobuild) > 0:

                        # . Get the hydrogen index.
                        h = tobuild.pop(0)

                        # . Build according to the number of built connected atoms.
                        nbuilt = len(built)

                        # . Get a random normalized vector.
                        if (nbuilt == 0) or (nbuilt == 1):
                            for i in range(3):
                                direction[i] = 2.0 * (
                                    randomNumberGenerator.NextReal() - 0.5)
                            direction.Normalize()

                        # . Put the hydrogen in a random direction from the center.
                        # . Works for all cases.
                        if nbuilt == 0:
                            coordinates3.BuildPointFromDistance(
                                h, c, bondlength, direction)

                            # . Put the hydrogen at the correct angle from the center and built atom but in a random plane.
                            # . Works for all cases given correct choice of angle.
                        elif nbuilt == 1:
                            coordinates3.BuildPointFromDistanceAngle(
                                h, c, built[0], bondlength, angle, direction)

                        # . Put the hydrogen away from the other built points at an appropriate angle from their plane.
                        # . The sign of the plane angle is arbitrary.
                        # . Works for cases 3, 4, 5 (square pyramidal), 6 with correct choice of planeangle.
                        elif nbuilt == 2:
                            coordinates3.BuildPointFromDistancePlaneAngle(
                                h, c, built[0], built[1], bondlength,
                                planeangle)

                        # . Put the hydrogen using a tetrahedral tripod.
                        # . Only works for tetrahedral coordination.
                        elif nbuilt == 3:
                            coordinates3.BuildPointFromDistanceTetrahedralTripod(
                                h, c, built[0], built[1], built[2], bondlength)

                        # . Cannot handle valencies greater than 4 for the moment.
                        else:
                            break

                        # . The hydrogen has been built.
                        built.append(h)
                        coordinates3.FlagCoordinateAsDefined(h)

            # . Output a summary.
            if LogFileActive(log):
                numberToBuild = coordinates3.numberUndefined
                numberBuilt = (numberUndefined0 - numberToBuild)
                if numberBuilt <= 0:
                    log.Paragraph("Coordinates for no hydrogens were built.")
                elif numberBuilt == 1:
                    log.Paragraph("Coordinates for one hydrogen were built.")
                else:
                    log.Paragraph(
                        "Coordinates for {:d} hydrogens were built.".format(
                            numberBuilt))
    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 ) )
Ejemplo n.º 6
0
    def runTest(self):
        """The test."""

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

        # . Energy models.
        mmModel = MMModelOPLS("protein")
        nbModel = NBModelFull()

        # . Get the files.
        molFiles = glob.glob(os.path.join(dataPath, "*.mol"))

        # . Initialization.
        numberErrors = 0
        numberFailures = 0

        # . Loop over the files.
        for molFile in molFiles:

            try:

                # . Get the system.
                try:
                    system = MOLFile_ToSystem(molFile)
                    system.DefineMMModel(mmModel, log=log)
                    system.DefineNBModel(nbModel)
                    system.Summary(log=log)
                except:
                    continue

                # . Calculate an energy.
                eBefore = system.Energy(log=log, doGradients=True)

                # . Define all hydrogen positions as undefined.
                for (i, atom) in enumerate(system.atoms):
                    if atom.atomicNumber == 1:
                        system.coordinates3.FlagCoordinateAsUndefined(i)

                # . Build as many undefined coordinates as possible.
                randomNumberGenerator = RandomNumberGenerator.WithSeed(957197)
                BuildHydrogenCoordinates3FromConnectivity(
                    system,
                    log=log,
                    randomNumberGenerator=randomNumberGenerator)

                # . Calculate an energy if all coordinates have been defined.
                if system.coordinates3.numberUndefined > 0:
                    numberFailures += 1
                    if log is not None:
                        log.Paragraph("Not all hydrogens have been rebuilt.")
                else:
                    eAfter = system.Energy(log=log, doGradients=True)
                    if log is not None:
                        log.Paragraph(
                            "Energy difference after rebuilding = {:.1f}.".
                            format(eAfter - eBefore))

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

        # . Success/failure.
        self.assertTrue(((numberErrors == 0) and (numberFailures == 0)))
Ejemplo n.º 7
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))
Ejemplo n.º 8
0
def BuildCubicSolventBox ( molecule, nmolecules, log = logFile, moleculesize = None, excludeHydrogens = True, QRANDOMROTATION = True, randomNumberGenerator = None, scalesafety = 1.1 ):
    """Build a cubic solvent box."""

    # . Get the number of molecules in each direction.
    nlinear = int ( math.ceil ( math.pow ( float ( nmolecules ), 1.0 / 3.0 ) ) )

    # . Get the indices of the occupied sites.
    sites = sample ( range ( nlinear**3 ), nmolecules )
    sites.sort ( )

    # . Get the number of atoms in the molecule and an appropriate selection.
    natoms    = len ( molecule.atoms )
    selection = Selection.FromIterable ( range ( natoms ) )

    # . Get a copy of molecule's coordinates (reorientated).
    coordinates3 = Clone ( molecule.coordinates3 )
    coordinates3.ToPrincipalAxes ( )

    # . Get the molecule size depending upon the input options.
    # . A molecule size has been specified.
    if moleculesize is not None:
        size = moleculesize
    # . Determine the size of the molecule as the diagonal distance across its enclosing orthorhombic box.
    else:
        radii = molecule.atoms.GetItemAttributes ( "vdwRadius" )
        if excludeHydrogens:
            atomicNumbers = molecule.atoms.GetItemAttributes ( "atomicNumber" )
            for ( i, atomicNumber ) in enumerate ( molecule.atoms.GetItemAttributes ( "atomicNumber" ) ):
                if atomicNumber == 1: radii[i] = 0.0
        ( origin, extents ) = coordinates3.EnclosingOrthorhombicBox ( radii = radii )
        size                = extents.Norm2 ( ) * scalesafety

    # . Create the new system - temporarily resetting the coordinates.
    temporary3            = molecule.coordinates3
    molecule.coordinates3 = coordinates3
    solvent               = MergeByAtom ( nmolecules * [ molecule ] )
    molecule.coordinates3 = temporary3

    # . Set the system symmetry.
    solvent.DefineSymmetry ( crystalClass = CrystalClassCubic ( ), a = size * float ( nlinear ) )

    # . Set up for random rotations.
    if QRANDOMROTATION:
        if randomNumberGenerator is None: randomNumberGenerator = RandomNumberGenerator.WithRandomSeed ( )
        rotation = Matrix33.Null ( )

    # . Loop over the box sites.
    origin      = 0.5 * float ( 1 - nlinear ) * size
    n           = 0
    translation = Vector3.Null ( )
    for i in range ( nlinear ):
        translation[0] = origin + size * float ( i )
        for j in range ( nlinear ):
            translation[1] = origin + size * float ( j )
            for k in range ( nlinear ):
                if len ( sites ) == 0: break
                translation[2] = origin + size * float ( k )
                # . Check for an occupied site.
                if sites[0] == n:
                    sites.pop ( 0 )
                    # . Randomly rotate the coordinates.
                    if QRANDOMROTATION:
                        rotation.RandomRotation ( randomNumberGenerator )
                        solvent.coordinates3.Rotate ( rotation, selection = selection )
                    # . Translate the coordinates.
                    solvent.coordinates3.Translate ( translation, selection = selection )
                    # . Increment the selection for the next molecule.
                    selection.Increment ( natoms )
                n += 1

    # . Do some printing.
    if LogFileActive ( log ):
        summary = log.GetSummary ( )
        summary.Start ( "Cubic Solvent Box Summary" )
        summary.Entry ( "Number of Molecules", "{:d}"  .format ( nmolecules                   ) )
        summary.Entry ( "Density (kg m^-3)",   "{:.3f}".format ( SystemDensity ( solvent )    ) )
        summary.Entry ( "Box Side",            "{:.3f}".format ( solvent.symmetryParameters.a ) )
        summary.Entry ( "Molecule Size",       "{:.3f}".format ( size                         ) )
        summary.Stop ( )

    # . Return the cubic system.
    return solvent
Ejemplo n.º 9
0
    heavies   = Selection.FromIterable ( protein - hydrogens )
    protein   = Selection.FromIterable ( protein )

    # . Fix all protein atoms.
    solution.DefineFixedAtoms ( protein )
    solution.Summary ( )

    # . Optimization.
    if _Optimize:
        ConjugateGradientMinimize_SystemGeometry ( solution                    ,
                                                   maximumIterations    =  200 ,
                                                   logFrequency         =   10 ,
                                                   rmsGradientTolerance = 10.0 )

    # . Define a normal deviate generator in a given state.
    normalDeviateGenerator = NormalDeviateGenerator.WithRandomNumberGenerator ( RandomNumberGenerator.WithSeed ( 517152 ) )

    # . Dynamics loop - fixed atoms then tether constraints.
    for forceConstant in ( None, 500.0, 100.0, 20.0, 4.0 ):

        # . Harmonically constrain protein heavy atoms.
        tethers = None
        if ( forceConstant is not None ):
            reference          = Clone ( solution.coordinates3 )
            tetherEnergyModel  = SoftConstraintEnergyModelHarmonic ( 0.0, forceConstant )
            tethers            = SoftConstraintContainer ( )
            tethers["tethers"] = SoftConstraintMultipleTether ( heavies, reference, tetherEnergyModel )
        solution.DefineSoftConstraints ( tethers )

        # . Dynamics.
        LangevinDynamics_SystemGeometry ( solution                        ,
Ejemplo n.º 10
0
 def SetRandomVariables(self):
     """Initialization to random variables."""
     rng = RandomNumberGenerator.WithRandomSeed()
     rng.NextReals(self.work)
     self.VariablesPut(self.work)
    def VelocitiesAssign ( self, temperature, normalDeviateGenerator = None ):
        """Set up the velocities for the system at a particular temperature.

        If |temperature| is None the velocities must already exist.
        """
        # . Check for an existing set of velocities of the correct size.
        velocities = self.system.configuration.__dict__.get ( "velocities", None )
        QASSIGN = ( velocities is None ) or ( ( velocities is not None ) and ( len ( velocities ) != self.nvariables ) )
        # . Assign velocities.
        if QASSIGN:
            if temperature is None:
                raise ValueError ( "Velocities need to be assigned for the system but a temperature has not been specified." )
            else:
                # . Get the generator.
                if normalDeviateGenerator is None:
                    normalDeviateGenerator = NormalDeviateGenerator.WithRandomNumberGenerator ( RandomNumberGenerator.WithRandomSeed ( ) )
                # . Get the velocities.
                sigma      = _MS_TO_APS * math.sqrt ( CONSTANT_BOLTZMANN * temperature / CONSTANT_ATOMIC_MASS )
                velocities = Real1DArray.WithExtent ( self.NumberOfVariables ( ) )
                normalDeviateGenerator.NextStandardDeviates ( velocities )
                velocities.Scale ( ( sigma ) )
                self.system.configuration.velocities = velocities
        # . Project out linear constraints.
        if self.linearVectors is not None: self.linearVectors.ProjectOutOfArray ( velocities )
        # . Scale velocities if necessary (even for assigned velocities).
        if temperature is not None:
            ( ke, tactual ) = self.Temperature ( velocities )
            velocities.Scale ( math.sqrt ( temperature / tactual ) )
from Definitions import outPath
from pBabel import PDBFile_FromSystem
from pCore import NormalDeviateGenerator, Pickle, RandomNumberGenerator, Unpickle
from pMoleculeScripts import LangevinDynamics_SystemGeometry

# . Parameters.
_Steps = 10000

# . Get the system with no fixed atoms and an appropriate NB model.
system = Unpickle(os.path.join(outPath, "step8_b.pkl"))
system.Summary()

# . Define a normal deviate generator in a given state.
normalDeviateGenerator = NormalDeviateGenerator.WithRandomNumberGenerator(
    RandomNumberGenerator.WithSeed(511717))

# . Dynamics.
LangevinDynamics_SystemGeometry(system,
                                collisionFrequency=25.0,
                                logFrequency=100,
                                normalDeviateGenerator=normalDeviateGenerator,
                                steps=_Steps,
                                temperature=300.0,
                                timeStep=0.001)

# . Save the system.
Pickle(os.path.join(outPath, "step9.pkl"), system)

# . Print PDB file.
PDBFile_FromSystem(os.path.join(outPath, "step9.pdb"), system)
    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 ) )
def HardSphereIonMobilities(molecule,
                            nreflections=30,
                            ntrajectories=600000,
                            randomNumberGenerator=None,
                            temperature=298.0,
                            log=logFile):
    """Calculate ion mobilities with a hard-sphere model."""

    # . Get the atom data.
    hsradii = _GetHardSphereRadii(molecule.atoms)
    masses = molecule.atoms.GetItemAttributes("mass")
    totalmass = masses.Sum()

    # . Get initial coordinates, move to center of mass and convert to metres.
    xyz0 = Clone(molecule.coordinates3)
    xyz0.TranslateToCenter(weights=masses)
    xyz0.Scale(1.0e-10)

    # . Get the mass constant.
    massHe = PeriodicTable.Element(2).mass
    massconstant = _MASSCONSTANT * math.sqrt((1.0 / massHe) +
                                             (1.0 / totalmass))

    # . Get the random number generator.
    if randomNumberGenerator is None:
        randomNumberGenerator = RandomNumberGenerator.WithRandomSeed()
    rotation = Matrix33.Null()

    # . Initialize some calculation variables.
    cof = Real1DArray.WithExtent(nreflections)
    cof.Set(0.0)
    crof = Real1DArray.WithExtent(nreflections)
    crof.Set(0.0)
    crb = 0.0
    mreflections = 0

    # . Loop over the trajectories.
    for it in range(ntrajectories):

        # . Randomly rotate the coordinate set.
        rotation.RandomRotation(randomNumberGenerator)
        xyz = Clone(xyz0)
        xyz.Rotate(rotation)

        # . Loop over the collisions.
        QCOLLISION = False
        for ir in range(nreflections):

            # . Initial collision - at a random point in the yz plane along the x-axis.
            if ir == 0:
                (origin, extents) = xyz.EnclosingOrthorhombicBox(radii=hsradii)
                yzarea = extents[1] * extents[2]
                yc = origin[1] + extents[1] * randomNumberGenerator.NextReal()
                zc = origin[2] + extents[2] * randomNumberGenerator.NextReal()
                xaxis = Vector3.WithValues(1.0, 0.0, 0.0)
            # . Subsequent collisions - always along the x-axis.
            else:
                yc = 0.0
                zc = 0.0

            # . Initialization.
            ic = -1  # . The index of the colliding particle.
            xc = origin[0] + extents[0]  # . The largest x-coordinate.

            # . Loop over particles.
            for (i, h) in enumerate(hsradii):
                # . After the first collision only x-values > 0 are allowed.
                if (ir == 0) or (xyz[i, 0] > 1.0e-16):
                    # . yd and zd are the coordinates of the impact points for the ith atom
                    # . with respect to its own coordinates (if such a point exists).
                    # . dev is the impact parameter.
                    h2 = h * h
                    y = yc - xyz[i, 1]
                    z = zc - xyz[i, 2]
                    yz2 = y * y + z * z
                    # . If there is a collision with the ith atom, check to see if it occurs before previous collisions.
                    if yz2 < h2:
                        x = xyz[i, 0] - math.sqrt(h2 - yz2)
                        if x < xc:
                            xc = x
                            ic = i

            # . Check mreflections.
            if ir >= mreflections: mreflections = ir + 1

            # . There was a collision.
            if ic >= 0:
                QCOLLISION = True
                # . Translate the coordinates so that the collision point is at the origin.
                xyz.Translate(Vector3.WithValues(-xc, -yc, -zc))
                # . Rotate the coordinates so that the outgoing vector is along the x-axis.
                h = xyz.GetRow(
                    ic
                )  # . Normalized vector from the collision point to the ic-th atom.
                h.Normalize(tolerance=1.0e-20)
                axis = Vector3.WithValues(
                    0.0, h[2], -h[1])  # . Normalized axis of rotation.
                axis.Normalize(tolerance=1.0e-20)
                alpha = math.pi - 2.0 * math.acos(h[0])  # . Angle of rotation.
                rotation.RotationAboutAxis(alpha, axis)
                xyz.Rotate(rotation)
                rotation.ApplyTo(xaxis)
                # . Calculate the cosine of the angle between the incoming vector and the normal to a plane,
                # . the reflection from which would be equivalent to the accumulated reflection.
                # . This is equal to h[0] when ir = 0.
                cof[ir] = math.cos(0.5 * (math.pi - math.acos(xaxis[0])))
                # . Check outgoing.
                # . Get the outgoing vector (the ingoing vector is always [1,0,0]).
                out = Vector3.WithValues(1.0 - 2.0 * h[0] * h[0],
                                         -2.0 * h[0] * h[1],
                                         -2.0 * h[0] * h[2])
                rotation.ApplyTo(out)
                out[0] -= 1.0
                if out.Norm2() > 1.0e-6:
                    print(
                        "Invalid Rotation: {:10.3f} {:10.3f} {:10.3f}.".format(
                            out[0], out[1], out[2]))
            # . There was no collision.
            else:
                # . Top up the remaining elements of cof with the last valid value of cof.
                if ir == 0: t = 0.0
                else: t = cof[ir - 1]
                for i in range(ir, nreflections):
                    cof[i] = t
                # . Exit.
                break

        # . End of collisions.
        # . Projection approximation.
        if QCOLLISION: crb += yzarea
        # . Hard-sphere approximation.
        for ir in range(nreflections):
            crof[ir] += yzarea * cof[ir] * cof[ir]

    # . End of trajectories.
    crof.Scale(2.0 / float(ntrajectories))
    pacs = crb / float(ntrajectories)
    pamob = massconstant / (pacs * math.sqrt(temperature))
    hscs = crof[mreflections - 1]
    hsmob = massconstant / (hscs * math.sqrt(temperature))

    # . Output results.
    if LogFileActive(log):
        summary = log.GetSummary()
        summary.Start("Hard-Sphere Ion Mobilities")
        summary.Entry("MC Trajectories", "{:d}".format(ntrajectories))
        summary.Entry("Reflection Limit", "{:d}".format(nreflections))
        summary.Entry("PA Mobility", "{:.4g}".format(pamob))
        summary.Entry("PA Cross-Section", "{:.4g}".format(pacs * 1.0e+20))
        summary.Entry("HS Mobility", "{:.4g}".format(hsmob))
        summary.Entry("HS Cross-Section", "{:.4g}".format(hscs * 1.0e+20))
        summary.Entry("Max. Reflections", "{:d}".format(mreflections))
        summary.Stop()

    # . Finish up.
    results = {
        "MC Trajectories": ntrajectories,
        "Reflection Limit": nreflections,
        "PA Mobility": pamob,
        "PA Cross-Section": pacs * 1.0e+20,
        "HS Mobility": hsmob,
        "HS Cross-Section": hscs * 1.0e+20,
        "Maximum Reflections": mreflections
    }
    return results
Ejemplo n.º 15
0
def MatrixMultiply ( extent, cpuTimer, ndg ):
    a = Real2DArray ( extent, extent ) ; a.Set ( 0.0 )
    b = Real2DArray ( extent, extent ) ; b.Set ( 0.0 )
    c = Real2DArray ( extent, extent ) ; c.Set ( 0.0 )
    for i in range ( extent ):
        for j in range ( extent ):
            a[i,j] = ndg.NextDeviate ( )
            b[i,j] = ndg.NextDeviate ( )
    tStart = cpuTimer.Current ( )
    c.MatrixMultiply ( a, b )
    return ( cpuTimer.Current ( ) - tStart )

# . Initialization.
cpuTimer = CPUTime ( )
rng      = RandomNumberGenerator.WithSeed ( 314159 )
ndg      = NormalDeviateGenerator.WithRandomNumberGenerator ( rng, mu = 0.0, sigma = 5.0 )

# . Calculation.
for ( extents, function, tag ) in ( ( eExtents, Eigenvalues   , "Eigenvalue"      ) ,
                                    ( mExtents, MatrixMultiply, "Matrix Multiply" ) ):
    times = [ function ( extent, cpuTimer, ndg ) for extent in extents ]
    table = logFile.GetTable ( columns = [ 10, 20, 20 ] )
    table.Start   ( )
    table.Title   ( tag + " Timings" )
    table.Heading ( "Extent" )
    table.Heading ( "Times", columnSpan = 2 )
    for ( extent, time ) in zip ( extents, times ):
        table.Entry ( "{:d}"  .format ( extent ) )
        table.Entry ( "{:.3f}".format ( time   ) )
        table.Entry ( CPUTime.TimeToString ( time ) )