Exemplo n.º 1
0
    def generateBuildingBlockXYZ(self):
        # pick n random points in the specified envelope within a cubic region of space.
        points = self.VPCBBG.generateBuildingBlock(self.numPoints, 
                                                   self.x1, 
                                                   self.x2, 
                                                   self.y1, 
                                                   self.y2, 
                                                   self.z1, 
                                                   self.z2, 
                                                   self.networkMinDist, 
                                                   envelopeList=self.envelopeList,
                                                   pointsToAvoid=self.envelopeList,
                                                   visualiseEnvelope=self.visualiseEnvelope)

        if self.dumpInterimFiles==1:
            fIO.saveXYZ(points.blockXYZVals, 'C', 'pointsInCube.xyz')

        # generate a random graph of connections between all the points,
        # such that no node has more than 3 connections and every node has at least one edge
        g = self.splitPointsIntoGraphs(points.blockXYZVals)
        
        if self.dumpInterimFiles==1:
            self.visualiseNetwork(g, points.blockXYZVals, self.monomerMinDist)

        return self.connectGraphWithConstrainedPolymer(g, points.blockXYZVals)
Exemplo n.º 2
0
    def generateBuildingBlock(self,
                              numPoints,
                              pointA,
                              pointB,
                              minDist,
                              bondLength,
                              pointsToAvoid=[],
                              envelope="None"):

        self.numPoints = numPoints
        self.pointA = pointA
        self.pointB = pointB
        self.baseLength = np.linalg.norm(pointA - pointB)
        self.bondLength = float(bondLength)
        self.minDist = minDist
        self.pointA = np.array([-self.baseLength / 2, 0.0, 0.0])
        self.pointB = np.array([self.baseLength / 2, 0.0, 0.0])
        self.pointsToAvoid = pointsToAvoid
        self.envelope = envelope.split()

        # generate the transformation information from building block to pointA and pointB
        self.labDirector, self.labRefPoint, self.labRotation = self.computeTransform(
        )

        # convert the pointsToAvoid information from the labFrame to the block frame
        self.pointsToAvoid = self.transformFromLabFrameToBlockFrame(
            self.labDirector, self.labRefPoint, self.labRotation,
            pointsToAvoid)

        fIO.saveXYZ([self.pointA, self.pointB], 'S', 'endPoints.xyz')

        return BBG.generateBuildingBlock(self, numPoints)
Exemplo n.º 3
0
def makeHSADistribution(num0, num1, num2, num3, num4, num5, x, y, z, minDist):

    # create the cubic distribution
    cubeGen = VPCBBG('VolumePackCuboid.txt')

    # create the NPack object.
    numPoints = num0 + num1 + num2 + num3 + num4 + num5

    # generate the building block
    SpacePackBB = cubeGen.generateBuildingBlock(numPoints, -x / 2, x / 2,
                                                -y / 2, y / 2, -z / 2, z / 2,
                                                minDist)

    # dump the base points to file
    fIO.saveXYZ(SpacePackBB.blockXYZVals, 'CA', 'points.xyz')

    # generate sufficient random orientiation vectors
    thetaPhiArray = [
        coords.pickRandomPointOnUnitSphere() for _ in range(numPoints)
    ]
    directors = [
        coords.sphericalPolar2XYZ(np.array([1.0, angs[0], angs[1]]))
        for angs in thetaPhiArray
    ]

    xyzVals0, names0 = genHsaPoints('hsa_apo.xyz',
                                    SpacePackBB.blockXYZVals[0:num0],
                                    directors[0:num1])
    xyzVals1, names1 = genHsaPoints('hsa_with1.xyz',
                                    SpacePackBB.blockXYZVals[num0:num0 + num1],
                                    directors[num0:num0 + num1])
    xyzVals2, names2 = genHsaPoints(
        'hsa_with2.xyz',
        SpacePackBB.blockXYZVals[num0 + num1:num0 + num1 + num2],
        directors[num0 + num1:num0 + num1 + num2])
    xyzVals3, names3 = genHsaPoints(
        'hsa_with3.xyz',
        SpacePackBB.blockXYZVals[num0 + num1 + num2:num0 + num1 + num2 + num3],
        directors[num0 + num1 + num2:num0 + num1 + num2 + num3])
    xyzVals4, names4 = genHsaPoints(
        'hsa_with4.xyz',
        SpacePackBB.blockXYZVals[num0 + num1 + num2 + num3:num0 + num1 + num2 +
                                 num3 + num4],
        directors[num0 + num1 + num2 + num3:num0 + num1 + num2 + num3 + num4])
    xyzVals5, names5 = genHsaPoints(
        'hsa_with5.xyz',
        SpacePackBB.blockXYZVals[num0 + num1 + num2 + num3 + num4:],
        directors[num0 + num1 + num2 + num3 + num4:])

    fIO.saveXYZList(xyzVals0, names0, 'hsa0All.xyz')
    fIO.saveXYZList(xyzVals1, names1, 'hsa1All.xyz')
    fIO.saveXYZList(xyzVals2, names2, 'hsa2All.xyz')
    fIO.saveXYZList(xyzVals3, names3, 'hsa3All.xyz')
    fIO.saveXYZList(xyzVals4, names4, 'hsa4All.xyz')
    fIO.saveXYZList(xyzVals5, names5, 'hsa5All.xyz')
Exemplo n.º 4
0
 def visualiseNetwork(self, g, points, radius):
     dZ = 0.1 * radius # ten particles per radius 
     xyzVals = []
     for edge in g.edges:
         node1 =  points[edge[0]]
         node2 =  points[edge[1]]
         director = node2 - node1
         length = np.linalg.norm(director)
         director = director/length
         numPoints = int(length/dZ)
         xyzVals += [  node1 + float(zIndex) * dZ * director for zIndex in range(0, numPoints)   ]
             
     fIO.saveXYZ(xyzVals, 'P', 'rawNetwork.xyz')        
Exemplo n.º 5
0
    def generateBuildingBlockXYZ(self):
        xyzVals = self.generateSpaceCurve()

        if self.dumpInterimFiles == 1:
            fIO.saveXYZ(xyzVals, 'Ca', 'initialChain.xyz')

        #print("Ensuring structure is inside envelope")
        xyzVals = self.foldInsideEnvelope(xyzVals)

        if self.dumpInterimFiles == 1:
            fIO.saveXYZ(xyzVals, 'Fe', 'foldedChain.xyz')

        return xyzVals
Exemplo n.º 6
0
    def constructLoop(self, BB1, BB2, loopGen, pointsToAvoid):

        connectorA = BB1.getConnectionAtoms(
            1)  # 1 is the C terminus of interest
        connectorB = BB2.getConnectionAtoms(
            0)  # 0 is the N terminus of interest

        # generate TNB frames at either connector
        TNBA = coords.constructTNBFrame(connectorA[0], connectorA[1],
                                        connectorA[2])
        TNBB = coords.constructTNBFrame(connectorB[0], connectorB[1],
                                        connectorB[2])

        # C terminus is CCN triad (new atom will be an N).
        betaA = self.angleC
        alphaA = self.phi
        # N Terminus is CNC triad. (new atom will be a C).
        betaB = self.angleN
        alphaB = self.psi

        # compute the coil start and end points
        pointA = connectorA[2] + self.CNbondLength * coords.generateTNBVecXYZ(
            TNBA, betaA, alphaA)
        pointB = connectorB[2] + self.CNbondLength * coords.generateTNBVecXYZ(
            TNBB, betaB, alphaB)

        if self.dumpInterimFiles:
            fIO.saveXYZList([pointA, connectorA[2], pointB, connectorB[2]],
                            ['Ca', 'S', 'O', 'S'], 'connectionDetails.xyz')
            fIO.saveXYZ(pointsToAvoid, 'K', 'pointsToAvoid.xyz')

        numCrankMoves = 0
        if self.parallel:
            iSphereR = 0.4 * self.strandLength * 3.5
        else:
            iSphereR = 0.9 * self.betaStrandSeparation / 2.0

        # create the loop building Blockss
        return loopGen.generateBuildingBlock(
            self.numLoopResidues,
            pointA,
            pointB,
            self.minDist,
            numCrankMoves,
            pointsToAvoid=pointsToAvoid,
            envelopeList=["innersphere " + str(iSphereR)])
Exemplo n.º 7
0
def dumpCubes(PosList, X, Y, Z, KagomeAngle, filename, particleName):
    posOut = []
    curPos = 0
    R = np.matrix([[np.cos(KagomeAngle), 0, -np.sin(KagomeAngle)], [0, 1, 0],
                   [np.sin(KagomeAngle), 0,
                    np.cos(KagomeAngle)]])

    Diag = np.sqrt(np.power(X, 2) + np.power(Z, 2)) / 2.0
    BAngle = np.arctan2(X, Z)

    P1 = np.array([Diag * np.sin(BAngle), 0, Diag * np.cos(BAngle)])
    P2 = np.array([Diag * np.cos(BAngle), 0, -Diag * np.sin(BAngle)])
    P3 = np.array([-Diag * np.sin(BAngle), 0, -Diag * np.cos(BAngle)])
    P4 = np.array([-Diag * np.cos(BAngle), 0, Diag * np.sin(BAngle)])

    P1R = P1.dot(R).A1
    P2R = P2.dot(R).A1
    P3R = P3.dot(R).A1
    P4R = P4.dot(R).A1

    for pos in PosList:
        if curPos == 0:
            posOut = [pos + P1R + np.array([0, Y / 2, 0])]
            posOut.append(pos + P2R + np.array([0, Y / 2, 0]))
            posOut.append(pos + P3R + np.array([0, Y / 2, 0]))
            posOut.append(pos + P4R + np.array([0, Y / 2, 0]))
            posOut.append(pos + P1R - np.array([0, Y / 2, 0]))
            posOut.append(pos + P2R - np.array([0, Y / 2, 0]))
            posOut.append(pos + P3R - np.array([0, Y / 2, 0]))
            posOut.append(pos + P4R - np.array([0, Y / 2, 0]))
        else:
            posOut.append(pos + P1R + np.array([0, Y / 2, 0]))
            posOut.append(pos + P2R + np.array([0, Y / 2, 0]))
            posOut.append(pos + P3R + np.array([0, Y / 2, 0]))
            posOut.append(pos + P4R + np.array([0, Y / 2, 0]))
            posOut.append(pos + P1R - np.array([0, Y / 2, 0]))
            posOut.append(pos + P2R - np.array([0, Y / 2, 0]))
            posOut.append(pos + P3R - np.array([0, Y / 2, 0]))
            posOut.append(pos + P4R - np.array([0, Y / 2, 0]))
        curPos += 1

    fIO.saveXYZ(posOut, particleName, filename)
Exemplo n.º 8
0
    def visualiseEnvelopeFunc(self, N, X, Y, Z, filename):

        posList = [
            np.array(
                [rnd.uniform(-X, X),
                 rnd.uniform(-Y, Y),
                 rnd.uniform(-Z, Z)]) for _ in range(N)
        ]

        posOut = []
        n = 0
        for pos in posList:
            if n % 1000 == 0:
                print("Visualising Envelope:", str(n), "out of",
                      str(len(posList)))
            if self.checkPointInBounds(pos, ignorePTA=True):
                posOut.append(pos)
            n += 1
        fIO.saveXYZ(posOut, 'Ne', filename)

        return
Exemplo n.º 9
0
    def generateBuildingBlockXYZ(self):
        print "Generating initial conformation in blockspace."
        xyzVals = self.generateSpaceCurve()

        fIO.saveXYZ(xyzVals, 'O', 'CP_Stage1_initCurve.xyz')

        # clean up Zeros"
        xyzVals = self.cleanUpZeroes(xyzVals)

        #print "correcting bondLengths"
        #xyzVals = self.correctBondLengths(xyzVals)

        #fIO.saveXYZ(xyzVals, 'O', 'CP_Stage2_evenBondLengths.xyz')

        #print "Scrambling adjacent atoms"
        #xyzVals = self.scrambleAdjacentAtoms(xyzVals, self.numPasses)

        #fIO.saveXYZ(xyzVals, 'O', 'CP_Stage3_scrambleAdjacentAtoms.xyz')

        print "Randomising the structure with crank shaft moves."
        xyzVals = self.crankShaftMoves(xyzVals, self.numCrankShaftMoves)

        fIO.saveXYZ(xyzVals, 'O', 'CP_Stage4_crankshaft_randomization.xyz')

        print "Ensuring structure is inside envelope"
        xyzVals = self.foldInsideEnvelope(xyzVals)

        fIO.saveXYZ(xyzVals, 'O', 'CP_Stage5_enveloped.xyz')

        return xyzVals
Exemplo n.º 10
0
    def generateSpaceCurve2(self, curveLength):
        # optimise the parameters to yield for the given curveLength and baseLength.
        finalResult = minimize(self.deltaLengthSpaceCurve,
                               self.initialModelParams,
                               args=(self.baseLength, curveLength))

        # compute the XYZ points of the curve over uniform domain spacings in parameter.
        spaceCurveXyzVals = self.spaceCurveDefinition(self.baseLength,
                                                      self.numPoints,
                                                      finalResult['x'])

        fIO.saveXYZ(spaceCurveXyzVals, 'O', 'spaceCurve.xyz')

        # compute the arc length at each point of the space curve.
        arcLengthSource = self.computeArcLengthFromSpaceXYZ(spaceCurveXyzVals)

        # compute the desired arc lengths for the particle positions.
        sPos = [n * self.bondLength for n in range(0, self.numPoints)]

        # compute the interpolated xyz points at each desired arc length
        return self.interpXYZFromArcLength(sPos, arcLengthSource,
                                           spaceCurveXyzVals)
Exemplo n.º 11
0
def makeWormNetwork(numNodesInit, nodeDist, xSize, ySize, zSize, WormRadius,
                    MaxTubeLength, MaxNumAttempts, ValidNodesPerCluster,
                    minDist, packingFraction):

    VolumeBBG = VPCBBG('VolumePackCuboid.txt')

    # generate the XYZVals of the network nodes packed in the volume
    NetworkNodesXYZ = VolumeBBG.generateBuildingBlock(numNodesInit, -xSize / 2,
                                                      xSize / 2, -ySize / 2,
                                                      ySize / 2, -zSize / 2,
                                                      zSize / 2, nodeDist)

    fIO.saveXYZ(NetworkNodesXYZ.blockXYZVals, 'O', 'cubepackedPoints.xyz')

    # create a list of groups of indices which together form a good network
    ListOfNetworkGroups = groupNodesInNetwork(NetworkNodesXYZ.blockXYZVals,
                                              WormRadius, MaxTubeLength,
                                              ValidNodesPerCluster,
                                              MaxNumAttempts)

    # dump output as file
    outputWormNetworkAsAtoms(ListOfNetworkGroups, NetworkNodesXYZ.blockXYZVals,
                             TubeRadius)

    # for each cluster in the network generate a series of points and directors
    networkPoints = populateClusters(ListOfNetworkGroups,
                                     NetworkNodesXYZ.blockXYZVals, WormRadius,
                                     minDist, packingFraction)

    # repack each list
    xyzVals = [points[0] for points in networkPoints]
    directors = [points[1] for points in networkPoints]
    names = [points[2] for points in networkPoints]

    # return flattened lists
    return ([point for minorList in xyzVals for point in minorList],
            [director for minorList in directors for director in minorList
             ], [name for minorList in names for name in minorList])
Exemplo n.º 12
0
    def generateSpaceCurve(self):
        # Over-rides the generate space curve function of the parent to generate a peptide backbone
        # and a pseudo energy landscape approach to find an initial chain with the end point fixed
        # at point B.

        # create a regular b0a14ckBone using block Points A as the first residue
        peptideBackbone = self.PBG.generateBuildingBlock(
            self.numResidues, seedResidue=self.blockPointsA)

        if self.dumpInterimFiles == 1:
            fIO.saveXYZList(peptideBackbone.blockXYZVals,
                            peptideBackbone.blockAtomNames,
                            'initialPeptideBackbone.xyz')

        # extract the xyzValues
        xyzVals = peptideBackbone.getAtomsXYZ()

        # perform the energy minimisation that moves the free end to blockPointsB
        xyzVals = self.minimiseEnergy(xyzVals, self.allowedList)

        if self.dumpInterimFiles == 1:
            fIO.saveXYZ(xyzVals, 'K', 'chainConnectedBlockFrame.xyz')

        return xyzVals
Exemplo n.º 13
0
def outputWormNetworkAsAtoms(ListOfNetworkGroups, XYZList, radius):
    dZ = 0.1 * radius  # ten particles per radius
    xyzVals = np.array([])
    for cluster in ListOfNetworkGroups:
        rootNodePos = XYZList[cluster[0]]
        for endNode in cluster[1:]:
            endNodePos = XYZList[endNode]
            director = endNodePos - rootNodePos
            length = np.linalg.norm(director)
            director = director / length
            numPoints = int(length / dZ)
            if xyzVals.size == 0:
                xyzVals = [
                    rootNodePos + float(zIndex) * dZ * director
                    for zIndex in range(0, numPoints)
                ]
                xyzVals = np.concatenate((xyzVals, [endNodePos]), 0)
            else:
                xyzVals = np.concatenate((xyzVals, [
                    rootNodePos + float(zIndex) * dZ * director
                    for zIndex in range(0, numPoints)
                ]), 0)

    fIO.saveXYZ(xyzVals, 'P', 'rawNetwork.xyz')
Exemplo n.º 14
0
    def generateBuildingBlockXYZ(self):

        print "load spidroin coil information"
        spidroinCoilSpecies1Names, spidroinCoilSpecies1XYZ = fIO.loadXYZ(
            self.spidroinSpecies1FName)
        spidroinCoilSpecies2Names, spidroinCoilSpecies2XYZ = fIO.loadXYZ(
            self.spidroinSpecies2FName)

        print "Generating spidroin sites within cluster"
        spidroinPositionBB = self.SPEBBG.generateBuildingBlock(
            self.numPointsInCluster, self.clusterRX, self.clusterRY,
            self.clusterRZ, -90.0, 90.0, -180.0, 180.0, self.SpidroinRadius)

        # compute the positions and orientations of each individual spidroin within it's cluster
        spidroinPositions = spidroinPositionBB.blockXYZVals
        spidroinDirectors = [spidPos for spidPos in spidroinPositions]
        spidroinDirectorsHat = [
            spidDir / np.linalg.norm(spidDir) for spidDir in spidroinDirectors
        ]
        spidroinRots = [
            rnd.uniform(0, 360) for _ in range(0, self.numPointsInCluster)
        ]

        print "Generating cluster positions within the larger aggregate"
        clusterPositionBB = self.VPEBBG.generateBuildingBlock(
            self.numClustersInAggregate, self.aggregateRX, self.aggregateRY,
            self.aggregateRZ, -90.0, 90.0, -180.0, 180.0,
            (max(self.clusterRX, self.clusterRY, self.clusterRZ) +
             self.species2AltitudeBoost + self.TerminalExtension))
        clusterPositions = clusterPositionBB.blockXYZVals
        clusterDirectors = [clustPos for clustPos in clusterPositions]
        clusterDirectorsHat = [
            clustDir / np.linalg.norm(clustDir)
            for clustDir in clusterDirectors
        ]
        clusterRots = [
            rnd.uniform(0, 360) for _ in range(0, self.numClustersInAggregate)
        ]

        fIO.saveXYZ(clusterPositions, 'Ne', 'aggClusterPoints.xyz')

        print "Producing Cluster"
        # sety up output arrays
        clusterXYZ = []
        clusterNames = []
        spidroinNum = 0
        # loop through the right number of times for the species1 data
        for rotation, director, position in zip(
                spidroinRots[0:self.numSpidroinSpecies1],
                spidroinDirectorsHat[0:self.numSpidroinSpecies1],
                spidroinPositions[0:self.numSpidroinSpecies1]):
            print spidroinNum
            if len(clusterXYZ) == 0:
                xyzVals = coords.transformFromBlockFrameToLabFrame(
                    director, position, rotation, np.array([0.0, 0.0, 1.0]),
                    np.array([0.0, 0.0, 0.0]), spidroinCoilSpecies1XYZ[:])
                clusterXYZ = xyzVals[:]
                clusterNames = spidroinCoilSpecies1Names
            else:
                xyzVals = coords.transformFromBlockFrameToLabFrame(
                    director, position, rotation, np.array([0.0, 0.0, 1.0]),
                    np.array([0.0, 0.0, 0.0]), spidroinCoilSpecies1XYZ[:])
                clusterXYZ = np.concatenate((clusterXYZ, xyzVals[:]), 0)
                clusterNames = np.concatenate(
                    (clusterNames[:], spidroinCoilSpecies1Names), 0)
            spidroinNum += 1

        # loop throught the species2 data and add the species two data at a slightly higher altitude.
        for rotation, director, position in zip(
                spidroinRots[self.numSpidroinSpecies1:],
                spidroinDirectorsHat[self.numSpidroinSpecies1:],
                spidroinPositions[self.numSpidroinSpecies1:]):
            print spidroinNum
            xyzVals = coords.transformFromBlockFrameToLabFrame(
                director, position + director * self.species2AltitudeBoost,
                rotation, np.array([0.0, 0.0, 1.0]), np.array([0.0, 0.0, 0.0]),
                spidroinCoilSpecies2XYZ[:])
            clusterXYZ = np.concatenate((clusterXYZ, xyzVals[:]), 0)
            clusterNames = np.concatenate(
                (clusterNames[:], spidroinCoilSpecies2Names), 0)
            spidroinNum += 1

        fIO.saveXYZList(clusterXYZ, clusterNames, "cluster.xyz")

        print "Producing aggregate"
        # sety up output arrays
        aggregateXYZ = []
        aggregateNames = []
        clusterNum = 0
        # loop through the right number of times for the species1 data
        for rotation, director, position in zip(clusterRots,
                                                clusterDirectorsHat,
                                                clusterPositions):
            print clusterNum
            if len(aggregateXYZ) == 0:
                xyzVals = coords.transformFromBlockFrameToLabFrame(
                    director, position, rotation, np.array([0.0, 0.0, 1.0]),
                    np.array([0.0, 0.0, 0.0]), clusterXYZ)
                aggregateXYZ = xyzVals[:]
                aggregateNames = clusterNames
            else:
                xyzVals = coords.transformFromBlockFrameToLabFrame(
                    director, position, rotation, np.array([0.0, 0.0, 1.0]),
                    np.array([0.0, 0.0, 0.0]), clusterXYZ)
                aggregateXYZ = np.concatenate((aggregateXYZ, xyzVals[:]), 0)
                aggregateNames = np.concatenate((aggregateNames, clusterNames),
                                                0)
            clusterNum += 1

        fIO.saveXYZList(aggregateXYZ, aggregateNames, "spidroinAggregate.xyz")

        self.namesTemp = aggregateNames
        return aggregateXYZ
Exemplo n.º 15
0
    pointB = np.array([0.0, 0.0, 0.0])
    
    print "Estimate min num residues: ", np.linalg.norm(pointA-pointB)/3.5
    
    seedResidue.placeAtom(2, pointA)
    seedResidue.setBlockRefPoint(pointA)
    seedResidue.orientToDirector(np.array([-1.0, 1.0, 0.0]))
    pointsA = seedResidue.blockXYZVals[:]
    
    seedResidue.placeAtom(2, pointB)
    seedResidue.setBlockRefPoint(pointB)
    seedResidue.orientToDirector(np.array([1.0, 0.0, 1.0]))
    pointsB = seedResidue.blockXYZVals[:]
    
    minDist = 1.0
    numCrankMoves = 0
    fIO.saveXYZList([pointsA[0], pointsA[1], pointsA[2], pointsB[0], pointsB[1], pointsB[2]], ['Ca', 'Ca', 'Ca', 'O', 'O', 'O'], 'labEndPoints.xyz')

    envelopeList=["innersphere 4", "frustum 11.0 20.0 -5.0 2.0"]
    
    pointsToAvoid = backboneGenerator.generateBuildingBlock(10)
    pointsToAvoid.translateRefPointToTarget( (pointsA[2] + pointsB[2])/2.0 )
    newDirector = (pointsA[2] - pointsB[2] - np.array([3.0, 0.0, 3.0]))
    newDirectorHat = newDirector/np.linalg.norm(newDirector)
    pointsToAvoid.orientToDirector(newDirectorHat)
    fIO.saveXYZ(pointsToAvoid.blockXYZVals, 'Li', "pointsToAvoid.xyz")
    
    # build building block and dump to file
    hairpinBuildingBlock = hairPinGen.generateBuildingBlock(numResidues, pointsA, pointsB, minDist, numCrankMoves, pointsToAvoid = pointsToAvoid.blockXYZVals, envelopeList=envelopeList)
    hairpinBuildingBlock.exportBBK(fIO.fileRootFromInfile(filename, 'txt'))
    print "hairpin done"
Exemplo n.º 16
0
    def foldInsideEnvelope(self, xyzVals):

        # Perform a random dihedral twist using the allowed list. If there are points intersecting
        # reject it out of hand.
        # if there are less points outside the zone than previously accept it.
        # if there are more points outside the zone then accept it with a probability that depends
        # exponentially on the difference between the current minimum number of points inside.

        # check which indices are outside the array
        curIndicesOutside = self.checkEnvelope(xyzVals)
        curXYZVals = xyzVals
        minXYZVals = xyzVals
        curNumIndicesOutside = len(curIndicesOutside)
        minNumIndicesOutside = curNumIndicesOutside
        minIndices = curIndicesOutside
        maxStepScale = 1.0
        numMoves = 0
        curMin = 0
        while minNumIndicesOutside > 0 and numMoves < self.maxNumFoldingMoves:

            # Do the dihedral move on the current working set.
            newXYZVals = self.dihedralTwist(curXYZVals, maxStepScale)

            # if new vals self-intersect then reject it
            for n, pos in enumerate(newXYZVals[0:-1]):
                goodPos = self.checkPointAgainstList(newXYZVals[n + 1:], pos)
                if goodPos == False:
                    newXYZVals = curXYZVals
                    break

            # find indices outside the envelope and count them.
            newIndicesOutside = self.checkEnvelope(newXYZVals)
            newNumIndicesOutside = len(newIndicesOutside)

            # if a new global minimum number of indices inside the envelope then keep the move.
            if newNumIndicesOutside < minNumIndicesOutside:
                curMin += 1
                # keep a permanent log of the the new best set.
                minXYZVals = newXYZVals[:]
                minNumIndicesOutside = newNumIndicesOutside
                minIndices = newIndicesOutside

                # update the working copy
                curXYZVals = newXYZVals[:]
                curNumIndicesOutside = newNumIndicesOutside

                if self.dumpInterimFiles == 1:
                    fIO.saveXYZ(minXYZVals, 'C', 'min' + str(curMin) + '.xyz')

                if self.verbose == 1:
                    print("step: ", numMoves, " minNumIndicesOutside: ",
                          minNumIndicesOutside, "curNumIndicesOutside:",
                          curNumIndicesOutside)

            # if the new move means that the num indices outside has gone up above the curXYZVals then
            # roll the die to decide whether or not to replace the curXYZVals
            if newNumIndicesOutside >= curNumIndicesOutside:
                # roll the die:
                if rnd.uniform(0.0, 1.0) < np.exp(
                    (minNumIndicesOutside - newNumIndicesOutside) /
                        self.foldingTemp):
                    # update the working copy of coords but don't replace the current global minimum
                    curXYZVals = newXYZVals
                    curNumIndicesOutside = newNumIndicesOutside

            numMoves += 1

            if numMoves % 10 == 0 and self.verbose == 0:
                print("step: ", numMoves, " minNumIndicesOutside: ",
                      minNumIndicesOutside, "curNumIndicesOutside:",
                      curNumIndicesOutside)

        if minNumIndicesOutside > 0:
            print(
                "Warning: there are points outside the envelope that were not moved inside."
            )
            if self.dumpInterimFiles:
                xyzVals = [minXYZVals[index] for index in minIndices]
                fIO.saveXYZ(xyzVals, 'B', 'outsideEnvelope.xyz')

        return minXYZVals
Exemplo n.º 17
0
    def generateBuildingBlock(self,
                              numPoints,
                              minDist,
                              showBlockDirector=False,
                              visualiseEnvelope=(0, 20, 'envelope.xyz'),
                              envelopeList=['None'],
                              pointsToAvoid=[],
                              defaultBlockRefPoint=None):
        # Returns a building block object with numPoints xyz values and names.
        # A reference point and principal direction of the building block are defined in the block Ref Frame.

        if defaultBlockRefPoint is not None:
            self.blockRefPoint = defaultBlockRefPoint

        # store num points
        self.numPoints = numPoints

        # store min Dist
        self.minDist = minDist

        # envelopeList
        self.parseEnvelopeList(envelopeList)

        # visualise envelope if requested
        if visualiseEnvelope[0] > 0:
            print("Visualising envelope")
            self.visualiseEnvelopeFunc(visualiseEnvelope[0],
                                       visualiseEnvelope[1],
                                       visualiseEnvelope[1],
                                       visualiseEnvelope[1],
                                       visualiseEnvelope[2])

        # from the points to avoid list remove those points that would fail the envelope test
        self.pointsToAvoid = []
        indicesOfPointsToRemoveFromPointsToAvoid = self.checkAllPointsInBounds(
            pointsToAvoid)
        if len(indicesOfPointsToRemoveFromPointsToAvoid) > 0:
            self.pointsToAvoid = [
                pointsToAvoid[index] for index in range(0, len(pointsToAvoid))
                if not index in indicesOfPointsToRemoveFromPointsToAvoid
            ]

        # save the pointsToAvoid if we're dumping files
        if self.dumpInterimFiles == 1:
            fIO.saveXYZ(self.pointsToAvoid, 'Li', "pointsToAvoid.xyz")

        # generate the xyz positions
        self.buildingBlockXYZ = self.generateBuildingBlockXYZ()

        # generate the BuildingBlock reference point
        self.blockRefPoint = self.generateBuildingBlockRefPoint()

        # generate the BuildingBlock director unit vector
        self.blockDirectorHat = self.generateBuildingBlockDirector()

        # generate the BuildingBlock names
        self.blockNames = self.generateBuildingBlockNames()

        if showBlockDirector:
            # This is is a little hack for visualising the building Block Director in
            # blender for debugging purposes. Insert this sequence into the middle of the chain (at point 15)
            # because the end of the chain is used to connect coils etc.
            insertIndex = int(np.floor(len(self.buildingBlockXYZ) / 2))
            [
                self.buildingBlockXYZ.insert(
                    insertIndex,
                    self.blockRefPoint + i * self.blockDirectorHat)
                for i in range(0, 10)
            ]
            [self.blockNames.insert(insertIndex, 'CA') for i in range(0, 10)]

        # generate the BuildingBlock connector indices
        self.blockConnectors = self.generateBuildingBlockConnectors()

        # call the function to construct and return a building block from the
        # information in the generator object.
        return self.getBuildingBlock()
Exemplo n.º 18
0
    bondLength = 2.0
    curlyFactor = 1.4
    pointsToAvoid=[]
    visualiseEnvelope=(0,20)
    envelopeList=["None"]
    angularRange=[0.0, 10, 165, 175]
    # envelopeList=["outersphere 12.0", "innersphere 10.0"],
    # pointsToAvoid=pointsToAvoid
    coneAngle = 45 * np.pi/180
    minAngle = 165 * np.pi/180
    threshold = 0.7
    maxNeighbours = 3
    
        
    # generate a set of points and build a constrained polymer pack network between them
    BranchedPolymerPackBB = BPPBBG.generateBuildingBlock(  numPoints, 
                                                           x1, x2,
                                                           y1, y2,
                                                           z1, z2, 
                                                           networkMinDist,
                                                           neighborRadius,
                                                           monomerMinDist, 
                                                           bondLength,
                                                           curlyFactor,
                                                           coneAngle,
                                                           minAngle,
                                                           threshold,
                                                           maxNeighbours)

    fIO.saveXYZ(BranchedPolymerPackBB.blockXYZVals, 'C', "branchedPolymerNetwork.xyz")
    print("branched Polymer Done")
Exemplo n.º 19
0
    def generateBuildingBlock(self,
                              numPoints,
                              pointA,
                              pointB,
                              minDist,
                              bondLength,
                              numCrankMoves,
                              pointsToAvoid=[],
                              envelopeList=["None"]):

        self.numPoints = numPoints
        self.labPointA = pointA
        self.labPointB = pointB
        self.baseLength = np.linalg.norm(pointA - pointB)
        self.bondLength = float(bondLength)
        self.minDist = minDist
        self.blockPointA = np.array([-self.baseLength / 2, 0.0, 0.0])
        self.blockPointB = np.array([self.baseLength / 2, 0.0, 0.0])
        self.numCrankMoves = numCrankMoves
        self.allowedList = self.generateAllowedList()

        if self.dumpInterimFiles:
            fIO.saveXYZList([self.blockPointA, self.blockPointB], ['Ca', 'O'],
                            'blockPoints.xyz')

        # generate the BuildingBlock reference point earlier than usual because
        # we need the transformation for the pointsToAvoid input.
        self.blockRefPoint = self.generateBuildingBlockRefPoint()

        # generate the BuildingBlock director unit vector earlier than usual because
        # we need the transformation for the pointsToAvoid input.
        self.blockDirectorHat = self.generateBuildingBlockDirector()

        # generate the transformation information from building block to labPointA and labPointB
        self.labDirector, self.labRefPoint, self.labRotation = self.computeTransform(
        )

        # convert the pointsToAvoid information from the labFrame to the block frame
        blockPointsToAvoid = coords.transformFromLabFrameToBlockFrame(
            self.labDirector, self.labRefPoint, self.labRotation,
            self.blockDirectorHat, self.blockRefPoint, pointsToAvoid)

        if self.dumpInterimFiles == 1:
            # these are debugging tests to make sure the transform is correct
            blockPointATrans = coords.transformFromLabFrameToBlockFrame(
                self.labDirector, self.labRefPoint, self.labRotation,
                self.blockDirectorHat, self.blockRefPoint, [pointA])[0]
            blockPointBTrans = coords.transformFromLabFrameToBlockFrame(
                self.labDirector, self.labRefPoint, self.labRotation,
                self.blockDirectorHat, self.blockRefPoint, [pointB])[0]

            fIO.saveXYZList([blockPointATrans, blockPointBTrans], ['Ca', 'O'],
                            "blockPointsTransFromLab.xyz")
            fIO.saveXYZ(blockPointsToAvoid, 'Li', "blockPointsToAvoid.xyz")
            labPointsToAvoidTrans = coords.transformFromBlockFrameToLabFrame(
                self.labDirector, self.labRefPoint, self.labRotation,
                self.blockDirectorHat, self.blockRefPoint, blockPointsToAvoid)
            fIO.saveXYZ(labPointsToAvoidTrans, 'Be',
                        "labPointsToAvoidTrans.xyz")

        # parse the envelope list now to check pointA and point B
        self.parseEnvelopeList(envelopeList)

        # store points to avoid to check pointA and point B
        self.pointsToAvoid = blockPointsToAvoid

        # check starting points are legal or it's gonna be a long wait.
        if not self.checkPointInBounds(self.blockPointA):
            print "Error Warning: PointA out of bounds"
            time.sleep(3)

        if not self.checkPointInBounds(self.blockPointB):
            print "Error Warning: PointB out of bounds"
            time.sleep(3)

        return BBG.generateBuildingBlock(self,
                                         numPoints,
                                         minDist,
                                         envelopeList=envelopeList,
                                         pointsToAvoid=blockPointsToAvoid)
Exemplo n.º 20
0
def makeWormNetwork(numGen1Worms,
                    xSize,
                    ySize,
                    zSize,
                    alpha1,
                    alpha2,
                    beta1,
                    beta2,
                    wormRadius,
                    backboneSegmentLength,
                    unimerMinDist,
                    packingFraction,
                    minSegmentsPerWorm,
                    coneAngleWorm,
                    wormDirector,
                    wormAlignmentAngularRange,
                    numWormGenerations,
                    minBranchAngle,
                    wormBranchDensity,
                    maxNumAttempts,
                    selfAvoid=False,
                    pointsToAvoid=[],
                    visualiseEnvelope=(0, 20, 'envelope.xyz'),
                    envelopeList=["None"]):

    # create the work network generator
    wormNetworkBackboneBBG = BPPBBG('branchedPolymerNetwork.txt')
    packNetworkBBG = PNBBG('packnetwork.txt')

    # generate a set of points and create a random polymer pack network in a region of space
    BranchedPolymerPackBB, networkGraph = wormNetworkBackboneBBG.generateBuildingBlock(
        numGen1Worms,
        -xSize / 2,
        xSize / 2,
        -ySize / 2,
        ySize / 2,
        -zSize / 2,
        zSize / 2,
        2 * wormRadius,
        alpha1,
        alpha2,
        beta1,
        beta2,
        0.9 * backboneSegmentLength,
        backboneSegmentLength,
        minSegmentsPerWorm,
        maxNumAttempts,
        selfAvoid,
        coneAngleWorm,
        wormAlignmentAngularRange,
        wormDirector,
        numWormGenerations,
        wormBranchDensity,
        minBranchAngle,
        visualiseEnvelope=visualiseEnvelope,
        pointsToAvoid=pointsToAvoid,
        envelopeList=envelopeList,
        SpaceCurveTransform=False)

    fIO.saveXYZ(BranchedPolymerPackBB.blockXYZVals, 'C',
                "wormBackBoneNetwork.xyz")

    # takes the graph of the network and the set of points to which the graph refers (the node names in the graph
    # are indices in the point list) and returns a set of xyzPoints and directors that populate the surface
    # of a cylindrical tube a distance worm radius from the backdone described by each individual cluster in the network.
    # the density of the xyzPoints are defined by unimerMinDist
    return populateClusters(networkGraph, BranchedPolymerPackBB.blockXYZVals,
                            wormRadius, unimerMinDist, packingFraction)
Exemplo n.º 21
0
    # generate backbone realtime parameters
    numPoints = 100
    pointA = 11.0 * np.array(
        [1.0 / np.sqrt(3.0), 1.0 / np.sqrt(3.0), 1.0 / np.sqrt(3)])
    pointB = 11.0 * np.array(
        [-1.0 / np.sqrt(3.0), -1.0 / np.sqrt(3.0), -1.0 / np.sqrt(3)])
    minDist = 1.0
    bondLength = 1.5
    crankMoves = 20
    spherePointGenerator = EPBBG('../../Library/EllipsoidPacking.txt')
    spherePoints = spherePointGenerator.generateBuildingBlock(
        30, 11, 11, 11, -90, 90, -180, 180, 4)
    pointsToAvoid = spherePoints.getAtomsXYZ()

    fIO.saveXYZList([pointA, pointB], ['Ca', 'O'], 'labPoints.xyz')
    fIO.saveXYZ(pointsToAvoid, 'Na', 'labPointsToAvoid.xyz')

    # generate a curve between the speicifed points
    ConstrainedPolymerPackBB = ConstrainedPolymerPackGBB.generateBuildingBlock(
        numPoints,
        pointA,
        pointB,
        minDist,
        bondLength,
        crankMoves,
        envelopeList=["outersphere 12.0", "innersphere 10.0"],
        pointsToAvoid=pointsToAvoid)
    ConstrainedPolymerPackGBB.checkBondLengths()
    ConstrainedPolymerPackBB.exportBBK(fIO.fileRootFromInfile(filename, 'txt'))
    print "constrainedPolymer Done"
Exemplo n.º 22
0
def makeWormNetwork(numGen1Worms,
                    xSize,
                    ySize,
                    zSize,
                    alpha1,
                    alpha2,
                    beta1,
                    beta2,
                    wormRadius,
                    backboneSegmentLength,
                    unimerMinDist,
                    packingFraction,
                    minSegmentsPerWorm,
                    coneAngleWorm,
                    wormDirector,
                    wormAlignmentAngularRange,
                    numWormGenerations,
                    minBranchAngle,
                    wormBranchDensity,
                    maxNumAttempts,
                    epsilon,
                    selfAvoid=False,
                    pointsToAvoid=[],
                    visualiseEnvelope=(0, 20, 'envelope.xyz'),
                    envelopeList=["None"]):

    # create the work network generator
    wormNetworkBackboneBBG = BPPBBG('branchedPolymerNetwork.txt')
    packNetworkBBG = PNBBG('networkPack.txt')

    # generate a set of points and create a random polymer pack network in a region of space
    BranchedPolymerPackBB, networkGraph = wormNetworkBackboneBBG.generateBuildingBlock(
        numGen1Worms,
        -xSize / 2,
        xSize / 2,
        -ySize / 2,
        ySize / 2,
        -zSize / 2,
        zSize / 2,
        2 * wormRadius,
        alpha1,
        alpha2,
        beta1,
        beta2,
        0.9 * backboneSegmentLength,
        backboneSegmentLength,
        minSegmentsPerWorm,
        maxNumAttempts,
        selfAvoid,
        coneAngleWorm,
        wormAlignmentAngularRange,
        wormDirector,
        numWormGenerations,
        wormBranchDensity,
        minBranchAngle,
        visualiseEnvelope=visualiseEnvelope,
        pointsToAvoid=pointsToAvoid,
        envelopeList=envelopeList,
        SpaceCurveTransform=False)

    fIO.saveXYZ(BranchedPolymerPackBB.blockXYZVals, 'C',
                "wormBackBoneNetwork.xyz")

    # dump the network to file to help judge the output
    #fIO.visualiseNetwork(networkGraph, BranchedPolymerPackBB.blockXYZVals, 'visualisedNetwork.xyz', particleName='P', dZ=0.1)

    # guestimate number of points
    nEdges = len(networkGraph.edges)

    #numpoints = total surface area of network surface/ area of unimer. Just an approximationto total surface area.
    # can adjust packingRatio to get desired results. factor of 2pi cancels out.
    numPoints = int(packingFraction * nEdges * wormRadius *
                    backboneSegmentLength / unimerMinDist)

    # generate the networkpacked building block - get a set of points and director for each point
    (NetworkPackBB, directors) = packNetworkBBG.generateBuildingBlock(
        numPoints, unimerMinDist, networkGraph,
        BranchedPolymerPackBB.blockXYZVals, [wormRadius], 'surface', epsilon)

    fIO.saveXYZ(NetworkPackBB.blockXYZVals, 'C', "networkPack.xyz")

    dirPosns = [
        pos + director
        for (pos, director) in zip(NetworkPackBB.blockXYZVals, directors)
    ]

    fIO.saveXYZ(dirPosns, 'O', "networkPackDirectorPoints.xyz")

    return NetworkPackBB.blockXYZVals, directors
Exemplo n.º 23
0
    def minimiseEnergy(self, xyzVals):
        # Returns a polymer chain which minimises a simple PE function.
        # Performs random dihedral twists on the free end of a polymer,
        # starting at a random bond.
        # Moves resulting in lower energy arrangements are accepted.
        # Moves resulting in higher energy arrangements are accepted
        # with probability that is exponentially smaller with increasing energy difference.
        # Since the primary structure is just a straight line and we are only
        # doing sparse dihedral twists, with only a single bias towards to the pointB,
        # there is a low probability of a self-intersection especially for long chains.
        # This rapidly finds a structure where the point B is within arbitrary distance of pointB.
        # The step size scales in proportion to the distance from point B. So only tiny steps are taken
        # near to the only minimum of the entire potential. Converges fairly rapidly even for large N.

        lowestEnergyMinimum = xyzVals[:]
        initPE, initDist = self.PE(xyzVals)
        curPE = initPE
        minPE = initPE
        curDist = initDist
        minDist = initDist
        maxStepRange = 1.0
        numMoves = 0
        curMin = 0
        while minDist > self.distEpsilon and numMoves < self.maxNumConnectingMoves:

            # compute new conformation based on a random dihedral twist
            newXYZ = self.dihedralTwist(xyzVals, maxStepRange)

            # compute energy and distance of new move
            newPE, newDist = self.PE(newXYZ)

            # compute energy difference with current minimum PE
            deltaPE = newPE - minPE

            # assume we will accept the move.
            acceptMove = True
            # if the currentPE is greater than the minimum then only accept
            # the move with a probability given by the difference in
            # energy of the minimum and current states
            if deltaPE > 0:
                # pick a random value between 0 and 1
                prob = rnd.uniform(0, 1)

                # if that value is larger than the threshold reject the move.
                # The threshold decreases with increasing deltaE, so the
                # higher the energy of the new state relative to the old one
                # the more likely it is we reject the move
                if prob > np.exp(-deltaPE / self.connectingTemp):
                    acceptMove = False

            # if we accept the move then store the new coords
            # and record the energy of the newest accepted move
            if acceptMove:
                xyzVals = newXYZ[:]
                curPE = newPE
                curDist = newDist

            # check the curPE against the minimum energy
            # if we have a new min energy then retain for the future and dump to file.
            if curPE < minPE:
                lowestEnergyMinimum = xyzVals[:]
                minPE = curPE
                minDist = curDist

                maxStepRange = min(1.0, minDist / self.distanceScale)

                # if the minDist is close then regenerate the allowed list with the short parameter set.
                # In this case only make moves in the ten residues closest to the target.
                #if minDist<3.0:
                #    self.generateAllowedList(short=True)

                curMin += 1
                if self.dumpInterimFiles > 1:
                    self.outline(numMoves, self.maxNumConnectingMoves, minDist,
                                 minPE, maxStepRange)
                if curMin <= 20 and self.dumpInterimFiles > 1:
                    fIO.saveXYZ(lowestEnergyMinimum, 'Be',
                                'min_' + str(curMin) + '.xyz')
                if curMin > 20 and curMin % 10 == 0 and self.dumpInterimFiles > 1:
                    fIO.saveXYZ(lowestEnergyMinimum, 'Be',
                                'min_' + str(curMin) + '.xyz')
                if curMin > 100 and curMin % 100 == 0 and self.dumpInterimFiles > 1:
                    fIO.saveXYZ(lowestEnergyMinimum, 'Be',
                                'min_' + str(curMin) + '.xyz')

            numMoves += 1

            if numMoves % 100 == 0:
                self.outline(numMoves, self.maxNumConnectingMoves, minDist,
                             minPE, maxStepRange)

        # regenerate the allowed list at full length
        self.generateAllowedList(short=False)

        return lowestEnergyMinimum
Exemplo n.º 24
0
    AX = 15.0
    AY = 15.0
    AZ = 15.0
    BX = 8.0
    BY = 8.0
    BZ = 8.0

    print "Computing Lattice Positions"

    # compute positions and directions of each cube in the super array
    APosList, BPosList, ADirList, BDirList = computeKagomeLattice(
        NumAX, NumAY, NumAZ, KagomeAngle, AX, AY, AZ, BX, BY, BZ)

    dumpCubes(APosList, AX, AY, AZ, 0.0, 'ACubeCorners.xyz', 'H')
    dumpCubes(BPosList, BX, BY, BZ, KagomeAngle, 'BCubeCorners.xyz', 'O')
    fIO.saveXYZ(APosList, 'Ca', 'ACubeCenters.xyz')
    fIO.saveXYZ(BPosList, 'O', 'BCubeCenters.xyz')

    # cube internal parameters
    numPolymersPerCubeA = 120
    thetad1A = -5.0
    thetad2A = 5.0
    phid1A = -10.0
    phid2A = 10.0
    polymerCylinderDiamA = 2.0
    polymerCylinderLengthA = 0.8 * AX
    numSpheresPerParticleA = 2

    numPolymersPerCubeB = 200
    thetad1B = -75.0
    thetad2B = -65.0
Exemplo n.º 25
0
    def foldInsideEnvelope(self, xyzVals):

        # Perform a random crank shaft using the allowed list. If there are points intersecting reject it out of hand.
        # if there are less points outside the zone accept it.
        # if there are more points outside the zone then accept it with a probability that depends
        # exponentially on the difference between the current minimum number of points inside.

        # check which indices are outside the array
        curIndicesOutside = self.checkEnvelope(xyzVals)
        curXYZVals = xyzVals
        minXYZVals = xyzVals
        curNumIndicesOutside = len(curIndicesOutside)
        minNumIndicesOutside = curNumIndicesOutside
        minIndices = curIndicesOutside
        maxStepScale = 1.0
        numMoves = 0
        curMin = 0
        threshold = 1.0

        while minNumIndicesOutside > 0 and numMoves < self.maxNumFoldingMoves:

            # Do the crank shaft move on the current working set.
            # Already rejects crossovers with pointsToAvoid and selfcrossovers.
            # Will return the current set in those cases so no move on number of points.
            newXYZVals, numValidMoves = self.crankShaftMoves(
                curXYZVals, 1, maxStepScale)

            # find indices outside the envelope and count them.
            newIndicesOutside = self.checkEnvelope(newXYZVals)
            newNumIndicesOutside = len(newIndicesOutside)

            if numValidMoves == 1:
                acceptedMove = False
                # if a new global minimum number of indices inside the envelope then keep the move.
                if newNumIndicesOutside < minNumIndicesOutside:
                    acceptedMove = True
                    # keep a permanent log of the the new best set.
                    minXYZVals = newXYZVals[:]
                    minNumIndicesOutside = newNumIndicesOutside
                    minIndices = newIndicesOutside

                    # update the working copy
                    curXYZVals = newXYZVals[:]
                    curNumIndicesOutside = newNumIndicesOutside

                    curMin += 1
                    if curMin < 10 and self.dumpInterimFiles == 1:
                        fIO.saveXYZList(minXYZVals, self.blockNames,
                                        "foldMin" + str(curMin) + '.xyz')
                    if curMin > 10 and self.dumpInterimFiles == 1 and curMin % 10 == 0:
                        fIO.saveXYZList(minXYZVals, self.blockNames,
                                        "foldMin" + str(curMin) + '.xyz')
                    if curMin > 100 and self.dumpInterimFiles == 1 and curMin % 100 == 0:
                        fIO.saveXYZList(minXYZVals, self.blockNames,
                                        "foldMin" + str(curMin) + '.xyz')

                # if the new move means that the num indices outside has gone up above the curXYZVals then
                # roll the die to decide whether or not to replace the curXYZVals
                if newNumIndicesOutside >= minNumIndicesOutside:
                    # roll the die. The larger the gap between newNum and minNum the smaller the threshold and the less likely we will accept the move and go back to the curXyzVals.
                    threshold = np.exp(
                        -(float(newNumIndicesOutside - minNumIndicesOutside)) /
                        self.foldingTemp)
                    if rnd.uniform(0.0, 1.0) < threshold:
                        acceptedMove = True
                        # update the working copy of coords but don't replace the current global minimum
                        curXYZVals = newXYZVals
                        curNumIndicesOutside = newNumIndicesOutside

                acceptedString = "rejected"
                if acceptedMove == True:
                    acceptedString = "accepted"
                print("step:", numMoves, "out of", self.maxNumFoldingMoves,
                      "minNumIndicesOutside:", minNumIndicesOutside,
                      "curNumIndicesOutside:", curNumIndicesOutside,
                      "threshold", threshold, acceptedString)
            numMoves += 1

        if minNumIndicesOutside > 0:
            print(
                "Warning: there are points outside the envelope that were not moved inside."
            )
            if self.dumpInterimFiles:
                fIO.saveXYZ(minXYZVals[minIndices], 'B', 'outsideEnvelope.xyz')

        return minXYZVals
Exemplo n.º 26
0
    xSize = 1000
    ySize = 1000
    zSize = 200
    MaxTubeLength = 500
    MaxNumAttempts = 1000
    ValidNodesPerCluster = [4]
    unimerBaseDist = 2
    packingFraction = 0.01
    # generate the XYZVals packed in the outer cylinder
    WormNetwork = makeWormNetwork(numNodesInit, nodeDist, xSize, ySize, zSize,
                                  TubeRadius, MaxTubeLength, MaxNumAttempts,
                                  ValidNodesPerCluster, unimerBaseDist,
                                  packingFraction)
    fIO.saveXYZList(WormNetwork[0], WormNetwork[2], "wormBasePointNetwork.xyz")
    fIO.saveXYZ([
        point + director
        for point, director in zip(WormNetwork[0], WormNetwork[1])
    ], 'O', "directorNetwork.xyz")

    from Projects.GeneralPolymerBrush import GeneralBlockPolymer as GBCP

    numUnimers = len(WormNetwork[0])
    UnimerStrands = []
    # generate unique polymer strands
    for basePos, director, index in zip(WormNetwork[0], WormNetwork[1],
                                        range(0, numUnimers)):
        print(index, " unimers out of: ", numUnimers)
        UnimerStrands += [GBCP(polymerBrushDict)]

    # transform the strands to the worm network positions
    xyzValsList = []
    allNames = []
Exemplo n.º 27
0
if __name__ == "__main__":
    SphereBBG = SPSBBG('SurfacePackSphere.txt')
    PolymerGenerator = RPBBG('RandomPolymer.txt')

    numPoints = 100
    radius = 20
    theta1 = -90
    theta2 = 90
    phi1 = -180
    phi2 = 180
    minDist = 1

    baseSPhereBB = SphereBBG.generateBuildingBlock(numPoints, radius, theta1,
                                                   theta2, phi1, phi2, minDist)
    fIO.saveXYZ(baseSPhereBB.blockXYZVals, 'C', "mollieShere.xyz")

    numMonomers = 100
    pointA = np.array([0.0, 0.0, 0.0])

    alpha1 = 40
    alpha2 = 50
    beta1 = 110
    beta2 = 130
    minDist = 1.0
    bondLength = 2.0

    polymers = [
        PolymerGenerator.generateBuildingBlock(numMonomers, pointA, alpha1,
                                               alpha2, beta1, beta2, minDist,
                                               bondLength)
Exemplo n.º 28
0
    def foldInsideEnvelope(self, xyzVals):

        # Perform a random crank shaft using the allowed list. If there are points intersecting reject it out of hand.
        # if there are less points outside the zone than previously accept it.
        # if there are more points outside the zone then accept it with a probability that depends
        # exponentially on the difference between the current minimum number of points inside.

        # check which indices are outside the array
        curIndicesOutside = self.checkEnvelope(xyzVals)
        curXYZVals = xyzVals
        minXYZVals = xyzVals
        curNumIndicesOutside = len(curIndicesOutside)
        minNumIndicesOutside = curNumIndicesOutside
        minIndices = curIndicesOutside
        maxStepScale = 1.0
        numMoves = 0

        while minNumIndicesOutside > 0 and numMoves < self.maxNumFoldingMoves:

            # Do the crank shaft move on the current working set.
            # Already rejects crossovers with pointsToAvoid and selfcrossovers.
            # Will return the current set in those cases so no move on number of points.
            newXYZVals = self.crankShaftMoves(curXYZVals, 1, maxStepScale)

            # find indices outside the envelope and count them.
            newIndicesOutside = self.checkEnvelope(newXYZVals)
            newNumIndicesOutside = len(newIndicesOutside)

            # if a new global minimum number of indices inside the envelope then keep the move.
            if newNumIndicesOutside < minNumIndicesOutside:
                # keep a permanent log of the the new best set.
                minXYZVals = newXYZVals[:]
                minNumIndicesOutside = newNumIndicesOutside
                minIndices = newIndicesOutside

                # update the working copy
                curXYZVals = newXYZVals[:]
                curNumIndicesOutside = newNumIndicesOutside

                print "step: ", numMoves, " minNumIndicesOutside: ", minNumIndicesOutside, "curNumIndicesOutside:", curNumIndicesOutside

            # if the new move means that the num indices outside has gone up above the curXYZVals then
            # roll the die to decide whether or not to replace the curXYZVals
            if newNumIndicesOutside >= curNumIndicesOutside:
                # roll the die:
                if rnd.uniform(0.0, 1.0) < np.exp(
                    (minNumIndicesOutside - newNumIndicesOutside) /
                        self.foldingTemp):
                    # update the working copy of coords but don't replace the current global minimum
                    curXYZVals = newXYZVals
                    curNumIndicesOutside = newNumIndicesOutside

            numMoves += 1

            if numMoves % 10 == 0:
                print "step: ", numMoves, " minNumIndicesOutside: ", minNumIndicesOutside, "curNumIndicesOutside:", curNumIndicesOutside

        if minNumIndicesOutside > 0:
            print "Warning: there are points outside the envelope that were not moved inside."
            if self.dumpInterimFiles:
                fIO.saveXYZ(minXYZVals[minIndices], 'B', 'outsideEnvelope.xyz')

        return minXYZVals
Exemplo n.º 29
0
            names = ['N', 'C', 'C'] * self.numResidues
        if (self.polarity == "CN"):
            names = ['C', 'C', 'N'] * self.numResidues
        return names

        
if __name__ == "__main__":
    
    
    # get the file name from the command line
    filename = sys.argv[1]

    # create the backbone generator object.
    hairPinGen = peptideHairpinGenerator(filename)

    # generate a backbone
    numResidues = 5
    bondLength = 3.5
    pointA = np.array([3, 0, 0])
    pointB = np.array([-3, 0, 0])
    pointC = pointA + bondLength * np.array([0.77, 0.77, 0.0])
    pointD = pointC + bondLength * np.array([0.0, 1.0, 0.0])
    pointE = pointD + bondLength * np.array([0.0, 1.0, 1.0])
    minDist = 3
    polarity = 'NC'
    fIO.saveXYZ([pointA, pointB, pointC, pointD, pointE], 'Ca', 'externalPoint.xyz')

    # build building block and dump to file
    hairpinBuildingBlock = hairPinGen.generateBuildingBlock(numResidues, pointA, pointB, pointC, pointD, pointE, minDist, bondLength, polarity)
    hairpinBuildingBlock.exportBBK(fIO.fileRootFromInfile(filename, 'txt'))
    print "hairpin done"
Exemplo n.º 30
0
    def generateBuildingBlockXYZ(self):
        # The spidroin model consists of two alpha helical termini proteins which are taken from PDB files
        # and a spidroinHairpin Coil which is a coarse grain representation of the spidroin coil that connects 
        # the two points at the end of the termini.  
        # The centre of mass of the two termini are placed at +/- spidroinTerminusSeparation/2.0 on the x axis.
        
        print "CTerminus"
        refPosCTerm = np.array([-self.spidroinTerminusSeparation/2.0, 0.0, -2.7]) # this last 2.7 is a total hack to get pointB in the envelope
        self.CTerminusAll = self.CTerminusGen.generateBuildingBlock(backboneOnly = False, director = self.CTermDirectorHat, showBlockDirector=False)
        self.CTerminusBackbone = self.CTerminusGen.generateBuildingBlock(backboneOnly = True, director = self.CTermDirectorHat, showBlockDirector=False)
        self.CTerminusAll.transformBBToLabFrame(self.spidroinDirector, refPosCTerm, self.CTermRot)
        self.CTerminusBackbone.transformBBToLabFrame(self.spidroinDirector, refPosCTerm, self.CTermRot) 
        self.CTerminusGen.exportPDBWithNewCoords(self.CTerminusAll.blockXYZVals, 'CTerminus_Positioned.pdb')
        
        if self.dumpInterimFiles==1:
            fIO.saveXYZ(self.CTerminusBackbone.blockXYZVals, self.CTerminalAtomName, "CTerminal.xyz")
        
        print "NTerminus"
        refPosNTerm  = np.array([self.spidroinTerminusSeparation/2.0, 0.0, 0.0])
        self.NTerminusAll = self.NTerminusGen.generateBuildingBlock(backboneOnly = False, director = self.NTermDirectorHat, showBlockDirector=False)
        self.NTerminusBackbone = self.NTerminusGen.generateBuildingBlock(backboneOnly = True, director = self.NTermDirectorHat, showBlockDirector=False)
        self.NTerminusAll.transformBBToLabFrame(self.spidroinDirector, refPosNTerm, self.NTermRot)
        self.NTerminusBackbone.transformBBToLabFrame(self.spidroinDirector, refPosNTerm, self.NTermRot) 
        self.NTerminusGen.exportPDBWithNewCoords(self.NTerminusAll.blockXYZVals, 'NTerminus_Positioned.pdb')
        
        if self.dumpInterimFiles==1:
            fIO.saveXYZ(self.NTerminusBackbone.blockXYZVals, self.NTerminalAtomName, "NTerminal.xyz")
        
        print "Compute end points of spidroin coil"
        # Compute the coil start (A) and end (B) points. 
        ConnectionA = self.NTerminusBackbone.getConnectionAtoms(1)

        # N (psi) C (phi) C (omega) N (psi) C (phi) C connection
        # s0      s1        s2      m2      m1        m0
        # a C to N terminus connection
        pointsA = self.findCoilPoints(ConnectionA[0], 
                                      ConnectionA[1], 
                                      ConnectionA[2], 
                                      self.CNbondLength,
                                      self.CNbondLength,
                                      self.CCbondLength,
                                      self.phi,
                                      self.angleC,
                                      self.omega,
                                      self.angleN,
                                      self.psi,
                                      self.angleC)
        pointA = pointsA[2]
        
        # find the N-terminus end of the C terminus and calculate where the coil should start
        ConnectionB = self.CTerminusBackbone.getConnectionAtoms(0)

        # C (phi) C (omega) N (psi) C (phi) C (omega) N connection
        # s0      s1        s2      m2      m1        m0
        # an N to C terminus connection
        pointsB = self.findCoilPoints(ConnectionB[0], 
                                      ConnectionB[1], 
                                      ConnectionB[2], 
                                      self.CNbondLength,
                                      self.CCbondLength,
                                      self.CNbondLength,
                                      self.omega,
                                      self.angleN,
                                      self.psi,
                                      self.angleC,
                                      self.phi,
                                      self.angleC)

        pointB = pointsB[2]

        if self.dumpInterimFiles == 1:
            fIO.saveXYZList([pointA, pointB], ['Ca', 'O'], "labEndPoints.xyz")

        print "Generating Coil"
        # generate a spidroin coil between each terminus.
        minDist = 1.0
        numCrankMoves = 0
        envelopeList = ['innersphere ' + str(0.9 * self.spidroinTerminusSeparation), 'frustum ' + str(self.SpidroinFrustumZ1 + 2.0) + ' ' + str(self.SpidroinFrustumMaxRadius) + ' ' + str(self.SpidroinFrustumZ2) + ' ' + str(self.SpidroinFrustumMinRadius)]
        visualiseEnvelopeEnvelope = 400.0 
        
        # build building block and dump to file
        self.spidroinHairpin = self.SpidroinCoilGen.generateBuildingBlock(self.species, pointA, pointB, minDist, numCrankMoves, envelopeList=envelopeList, visualiseEnvelope=(1000000, visualiseEnvelopeEnvelope, 'envelope_' + str(self.species) + '.xyz'))

        if self.dumpInterimFiles==1:
            fIO.saveXYZ(self.spidroinHairpin.blockXYZVals, self.spidroinHairpinAtomName, "hPinCG.xyz")

        print "Coarse grained hairpin done"

        # populate each section of the coarse grained spidroin hairpin with a peptide hairpin between the start and end points. 
        numGUnits = self.SP2NumGUnits
        lenGUnit = self.SP2LenGUnitRes
        lenPQUnit = self.SP2LenPQUnitRes
        if self.species=='SP1':
            numGUnits = self.SP1NumGUnits 
            lenGUnit = self.SP1LenGunitRes
            lenPQUnit = self.SP1LenPQunitRes
            
        radii = [minDist * self.envRadiusFactor] * numGUnits * 2
        residues = [lenPQUnit, lenGUnit] * numGUnits
        if self.species=='SP2':
            residues = residues + [lenPQUnit]
            radii = radii + [minDist * self.envRadiusFactor]
        
        pointsA = [ xyzVal for xyzVal,name in zip(self.spidroinHairpin.blockXYZVals, self.spidroinHairpin.blockAtomNames) if name == 'N' ]
        pointsB = [ xyzVal for xyzVal,name in zip(self.spidroinHairpin.blockXYZVals, self.spidroinHairpin.blockAtomNames) if name == 'C' ]
            
        if self.dumpInterFiles ==1:
            fIO.saveXYZList(pointsA + pointsB, ['Ca'] * len(pointsA) + ['O'] * len(pointsB), "labPoints.xyz")
            
        self.COfChainsBB = CCGen.generateBuildingBlock(residues, pointsA, pointsB, radii, minDist, visualiseEnvelope=(0, 50, 'envelope.xyz'))
        
        if self.dumpInterimFiles==1:
            fIO.saveXYZ(self.COfChainsBB.blockXYZVals, self.spidroinHairpinAtomName, "hPin.xyz")

        print "detailed hairpin done"

            
        # assemble the components into a single final block of xyz values
        spidroinXYZ = self.NTerminusBackbone.blockXYZVals
        spidroinXYZ = np.concatenate( (spidroinXYZ, self.COfChainsBB.blockXYZVals), 0 )
        spidroinXYZ = np.concatenate( (spidroinXYZ , self.CTerminusBackbone.blockXYZVals), 0 )

        if self.dumpInterimFiles==1:
            fIO.saveXYZ(spidroinXYZ, self.spidroinAtomName, "spidroinAsBlock.xyz")

        print "Spidroin Done"
        return spidroinXYZ