Пример #1
0
def test_distpot():
    #define two structures
    natoms = 12
    X1 = np.random.uniform(-1, 1, [natoms * 3]) * (float(natoms))**(1. / 3)

    X2 = np.random.uniform(-1, 1, [natoms * 3]) * (float(natoms))**(1. / 3)
    #make X2 a rotation of X1
    print "testing with", natoms, "atoms, with X2 a rotated and permuted isomer of X1"
    aa = rot.random_aa()
    rot_mx = rot.aa2mx(aa)
    for j in range(natoms):
        i = 3 * j
        X2[i:i + 3] = np.dot(rot_mx, X1[i:i + 3])
    #import random, mindistutils
    #perm = range(natoms)
    #random.shuffle( perm )
    #print perm
    #X2 = mindistutils.permuteArray( X2, perm)

    pot = MinPermDistPotential(X1, X2, L=.2)

    aa = rot.random_aa()
    e = pot.getEnergy(aa)
    print "energy", e
    de, dg = pot.getEnergyGradient(aa)
    print "energy from gradient", de, "diff", e - de

    den, dgn = pot.getEnergyGradientNumerical(aa)
    maxgrad = np.max(np.abs(dg))
    maxdiff = np.max(np.abs(dg - dgn))
    print "maximum gradient", maxgrad
    print "max difference in analytical vs numerical gradient", maxdiff
Пример #2
0
def test_distpot():
    #define two structures
    natoms = 12
    X1 = np.random.uniform(-1,1,[natoms*3])*(float(natoms))**(1./3)
    
    X2 = np.random.uniform(-1,1,[natoms*3])*(float(natoms))**(1./3)
    #make X2 a rotation of X1
    print "testing with", natoms, "atoms, with X2 a rotated and permuted isomer of X1"
    aa = rot.random_aa()
    rot_mx = rot.aa2mx( aa )
    for j in range(natoms):
        i = 3*j
        X2[i:i+3] = np.dot( rot_mx, X1[i:i+3] )
    #import random, mindistutils
    #perm = range(natoms)
    #random.shuffle( perm )
    #print perm
    #X2 = mindistutils.permuteArray( X2, perm)

    pot = MinPermDistPotential(X1, X2, L = .2)
    
    aa = rot.random_aa()
    e = pot.getEnergy(aa)
    print "energy", e
    de, dg = pot.getEnergyGradient(aa)
    print "energy from gradient", de, "diff", e-de
    
    den, dgn = pot.getEnergyGradientNumerical(aa)
    maxgrad= np.max( np.abs( dg ) )
    maxdiff = np.max( np.abs( dg - dgn ) )
    print "maximum gradient", maxgrad
    print "max difference in analytical vs numerical gradient", maxdiff
Пример #3
0
    def testBLJ_isomer(self):
        """
        test with BLJ potential.  We have two classes of permutable atoms  
        
        test case where X2 is an isomer of X1.
        """
        import pygmin.utils.rotations as rot
        X1i = np.copy(self.X1)
        X1 = np.copy(self.X1)        
        X2 = np.copy(X1)
        
        #rotate X2 randomly
        aa = rot.random_aa()
        rot_mx = rot.aa2mx( aa )
        for j in range(self.natoms):
            i = 3*j
            X2[i:i+3] = np.dot( rot_mx, X1[i:i+3] )
        
        #permute X2
        import random, copy
        from pygmin.mindist.permutational_alignment import permuteArray
        for atomlist in self.permlist:
            perm = copy.copy(atomlist)
            random.shuffle( perm )
            X2 = permuteArray( X2, perm)

        X2i = np.copy(X2)
        
        #distreturned, X1, X2 = self.runtest(X1, X2)
        distreturned, X1, X2 = self.runtest(X1, X2, minPermDistStochastic)

        
        #it's an isomer, so the distance should be zero
        self.assertTrue( abs(distreturned) < 1e-14, "didn't find isomer: dist = %g" % (distreturned) )
Пример #4
0
def randomCoords(nmol):
    coords = np.zeros(2*3*nmol, np.float64)
    coords[0:3*nmol] = np.random.uniform(-1,1,[nmol*3]) * 1.3*(3*nmol)**(1./3)
    for i in range(nmol):
        k = 3*nmol + 3*i
        coords[k : k + 3] = rot.random_aa()
    return coords
Пример #5
0
    def testBLJ_isomer(self):
        """
        test with BLJ potential.  We have two classes of permutable atoms  
        
        test case where X2 is an isomer of X1.
        """
        import pygmin.utils.rotations as rot
        X1i = np.copy(self.X1)
        X1 = np.copy(self.X1)
        X2 = np.copy(X1)

        #rotate X2 randomly
        aa = rot.random_aa()
        rot_mx = rot.aa2mx(aa)
        for j in range(self.natoms):
            i = 3 * j
            X2[i:i + 3] = np.dot(rot_mx, X1[i:i + 3])

        #permute X2
        import random, copy
        from pygmin.mindist.permutational_alignment import permuteArray
        for atomlist in self.permlist:
            perm = copy.copy(atomlist)
            random.shuffle(perm)
            X2 = permuteArray(X2, perm)

        X2i = np.copy(X2)

        #distreturned, X1, X2 = self.runtest(X1, X2)
        distreturned, X1, X2 = self.runtest(X1, X2, minPermDistStochastic)

        #it's an isomer, so the distance should be zero
        self.assertTrue(
            abs(distreturned) < 1e-14,
            "didn't find isomer: dist = %g" % (distreturned))
Пример #6
0
 def get_random_coordinates(self):
     coords = np.zeros([self.nmol*2, 3])
     coords[:self.nmol,:] = np.random.uniform(-1,1,[self.nmol,3]) * (self.nmol*3)**(-1./3) * 1.5
     from pygmin.utils.rotations import random_aa
     for i in range(self.nmol, self.nmol*2):
         coords[i,:] = random_aa()
     return coords.flatten()
Пример #7
0
def test_binary_LJ(natoms=12, **kwargs):
    import pygmin.defaults
    import pygmin.utils.rotations as rot
    quench = pygmin.defaults.quenchRoutine

    printlist = []

    ntypea = int(natoms * .8)
    from pygmin.potentials.ljpshift import LJpshift
    lj = LJpshift(natoms, ntypea)
    permlist = [range(ntypea), range(ntypea, natoms)]

    X1 = np.random.uniform(-1, 1, [natoms * 3]) * (float(natoms))**(1. / 3) / 2
    printlist.append((X1.copy(), "very first"))
    #quench X1
    ret = quench(X1, lj.getEnergyGradient)
    X1 = ret[0]
    printlist.append((X1.copy(), "after quench"))

    X2 = np.random.uniform(-1, 1, [natoms * 3]) * (float(natoms))**(1. / 3)
    #make X2 a rotation of X1
    print "testing with", natoms, "atoms,", ntypea, "type A atoms, with X2 a rotated and permuted isomer of X1"
    aa = rot.random_aa()
    rot_mx = rot.aa2mx(aa)
    for j in range(natoms):
        i = 3 * j
        X2[i:i + 3] = np.dot(rot_mx, X1[i:i + 3])
    printlist.append((X2.copy(), "x2 after rotation"))

    import random, copy
    from pygmin.mindist.permutational_alignment import permuteArray

    for atomlist in permlist:
        perm = copy.copy(atomlist)
        random.shuffle(perm)
        print perm
        X2 = permuteArray(X2, perm)
    printlist.append((X2.copy(), "x2 after permutation"))

    #X1 = np.array( [ 0., 0., 0., 1., 0., 0., 0., 0., 1.,] )
    #X2 = np.array( [ 0., 0., 0., 1., 0., 0., 0., 1., 0.,] )
    X1i = copy.copy(X1)
    X2i = copy.copy(X2)

    atomtypes = ["N" for i in range(ntypea)]
    for i in range(natoms - ntypea):
        atomtypes.append("O")

    print "******************************"
    print "testing binary LJ  ISOMER"
    print "******************************"
    test(X1, X2, lj, atomtypes=atomtypes, permlist=permlist, **kwargs)

    print "******************************"
    print "testing binary LJ  non isomer"
    print "******************************"
    X2 = np.random.uniform(-1, 1, [natoms * 3]) * (float(natoms))**(1. / 3)
    ret = quench(X2, lj.getEnergyGradient)
    X2 = ret[0]
    test(X1, X2, lj, atomtypes=atomtypes, permlist=permlist, **kwargs)
Пример #8
0
def random_coords(nmol, nsites = None):
    if nsites == None: nsites = nmol
    coords = np.zeros(2*3*nmol)
    coords[0:nmol*3] = np.random.uniform(-1,1,[nmol*3]) * 1.3*(nsites)**(1./3)
    for i in range(nmol):
        k = nmol*3 + 3*i
        coords[k : k + 3] = rot.random_aa()
    return coords
Пример #9
0
def randomCoords(nmol):
    coords = np.zeros(2 * 3 * nmol, np.float64)
    coords[0:3 * nmol] = np.random.uniform(
        -1, 1, [nmol * 3]) * 1.3 * (3 * nmol)**(1. / 3)
    for i in range(nmol):
        k = 3 * nmol + 3 * i
        coords[k:k + 3] = rot.random_aa()
    return coords
Пример #10
0
 def get_random_coordinates(self):
     coords = np.zeros([self.nmol * 2, 3])
     coords[:self.nmol, :] = np.random.uniform(
         -1, 1, [self.nmol, 3]) * (self.nmol * 3)**(-1. / 3) * 1.5
     from pygmin.utils.rotations import random_aa
     for i in range(self.nmol, self.nmol * 2):
         coords[i, :] = random_aa()
     return coords.flatten()
Пример #11
0
def randomCoordsAA(nmol):
    import pygmin.utils.rotations as rot

    coords = np.zeros(2 * 3 * nmol, np.float64)
    coords[0 : 3 * nmol] = np.random.uniform(-1, 1, [nmol * 3]) * 1.3 * (3 * nmol) ** (1.0 / 3)
    for i in range(nmol):
        k = 3 * nmol + 3 * i
        coords[k : k + 3] = rot.random_aa()
    return coords
Пример #12
0
def random_coords(nmol, nsites=None):
    if nsites == None: nsites = nmol
    coords = np.zeros(2 * 3 * nmol)
    coords[0:nmol *
           3] = np.random.uniform(-1, 1, [nmol * 3]) * 1.3 * (nsites)**(1. / 3)
    for i in range(nmol):
        k = nmol * 3 + 3 * i
        coords[k:k + 3] = rot.random_aa()
    return coords
Пример #13
0
    def __call__(self, coords1, coords2):
        '''
        Parameters
        ----------
        coords1, coords2 : np.array 
            the structures to align.  X2 will be aligned with X1, both
            the center of masses will be shifted to the origin
            
        Returns
        -------
        a tripple of (dist, coords1, coords2). coords1 are the unchanged coords1
        and coords2 are brought in best alignment with coords2
    '''
        # we don't want to change the given coordinates
        check_inversion = False
        x1 = np.copy(coords1)
        x2 = np.copy(coords2)

        com1 = self.measure.get_com(x1)
        self.transform.translate(x1, -com1)
        com2 = self.measure.get_com(x2)
        self.transform.translate(x2, -com2)

        self.com_shift = com1

        self.mxbest = np.identity(3)
        self.distbest = self.measure.get_dist(x1, x2)
        self.x2_best = x2.copy()

        if self.distbest < self.tol:
            return self.distbest, x1, x2

        for rot, invert in self._standard_alignments(x1, x2):
            self.check_match(x1, x2, rot, invert)
            if self.distbest < self.tol:
                dist, x2 = self.finalize_best_match(coords1)
                return dist, coords1, x2

        # if we didn't find a perfect match here, try random rotations to optimize the match
        for i in range(self.niter):
            rot = rotations.aa2mx(rotations.random_aa())
            self.check_match(x1, x2, rot, False)
            if (self.transform.can_invert()):
                self.check_match(x1, x2, rot, True)


#        self.transform.rotate(X2, mxbest)
#        dist, perm = self.measure.find_permutation(X1, X2)
#        X2 = self.transform.permute(X2, perm)
#        tmp, mx = self.measure.find_rotation(X1.copy(), X2.copy())
#        self.transform.rotate(X2, mx)

# TODO: should we do an additional sanity check for permutation / rotation?

        dist, x2 = self.finalize_best_match(coords1)
        return dist, coords1, x2
Пример #14
0
 def takeStep(self, coords, **kwargs):
     # easy access to coordinates
     ca = CoordsAdapter(nrigid=coords.size/6, coords = coords)
     
     # random displacement for positions
     #ca.posRigid[:] = 2.*self.radius*(np.random.random(ca.posRigid.shape)-0.5)
     
     # random rotation for angle-axis vectors
     for rot in ca.rotRigid:
         rot[:] = rotations.random_aa()
Пример #15
0
    def takeStep(self, coords, **kwargs):
        # easy access to coordinates
        ca = CoordsAdapter(nrigid=coords.size / 6, coords=coords)

        # random displacement for positions
        #ca.posRigid[:] = 2.*self.radius*(np.random.random(ca.posRigid.shape)-0.5)

        # random rotation for angle-axis vectors
        for rot in ca.rotRigid:
            rot[:] = rotations.random_aa()
Пример #16
0
    def __call__(self, coords1, coords2):        
        '''
        Parameters
        ----------
        coords1, coords2 : np.array 
            the structures to align.  X2 will be aligned with X1, both
            the center of masses will be shifted to the origin
            
        Returns
        -------
        a tripple of (dist, coords1, coords2). coords1 are the unchanged coords1
        and coords2 are brought in best alignment with coords2
    '''
    # we don't want to change the given coordinates
        check_inversion = False
        x1 = np.copy(coords1)
        x2 = np.copy(coords2)
    
        com1 = self.measure.get_com(x1)
        self.transform.translate(x1, -com1)
        com2 = self.measure.get_com(x2)
        self.transform.translate(x2, -com2)

        self.com_shift = com1
        
        self.mxbest = np.identity(3)
        self.distbest = self.measure.get_dist(x1, x2)
        self.x2_best = x2.copy()
        
        if self.distbest < self.tol:
            return self.distbest, x1, x2
        
        for rot, invert in self._standard_alignments(x1, x2):
            self.check_match(x1, x2, rot, invert)
            if self.distbest < self.tol:
                dist, x2 = self.finalize_best_match(coords1)
                return dist, coords1, x2
        
        # if we didn't find a perfect match here, try random rotations to optimize the match
        for i in range(self.niter):
            rot = rotations.aa2mx(rotations.random_aa())
            self.check_match(x1, x2, rot, False)
            if(self.transform.can_invert()):
                self.check_match(x1, x2, rot, True)

#        self.transform.rotate(X2, mxbest)
#        dist, perm = self.measure.find_permutation(X1, X2)
#        X2 = self.transform.permute(X2, perm)
#        tmp, mx = self.measure.find_rotation(X1.copy(), X2.copy())
#        self.transform.rotate(X2, mx)
        
        # TODO: should we do an additional sanity check for permutation / rotation?        
        
        dist, x2 = self.finalize_best_match(coords1)                
        return dist, coords1, x2
Пример #17
0
def test_LJ(natoms = 12, **kwargs):
    from pygmin.potentials.lj import LJ
    from pygmin.optimize import mylbfgs
    import pygmin.utils.rotations as rot
    from pygmin.mindist.permutational_alignment import permuteArray
    import random
    
    quench = mylbfgs
    lj = LJ()
    X1 = np.random.uniform(-1,1,[natoms*3])*(float(natoms))**(1./3)
    #quench X1
    ret = quench( X1, lj)
    X1 = ret.coords
    X2 = np.random.uniform(-1,1,[natoms*3])*(float(natoms))**(1./3)
    #make X2 a rotation of X1
    print "testing with", natoms, "atoms, with X2 a rotated and permuted isomer of X1"
    aa = rot.random_aa()
    rot_mx = rot.aa2mx( aa )
    for j in range(natoms):
        i = 3*j
        X2[i:i+3] = np.dot( rot_mx, X1[i:i+3] )
    perm = range(natoms)
    random.shuffle( perm )
    print perm
    X2 = permuteArray( X2, perm)

    #X1 = np.array( [ 0., 0., 0., 1., 0., 0., 0., 0., 1.,] )
    #X2 = np.array( [ 0., 0., 0., 1., 0., 0., 0., 1., 0.,] )
    import copy
    X1i = copy.copy(X1)
    X2i = copy.copy(X2)
 
    print "******************************"
    print "testing normal LJ  ISOMER"
    print "******************************"
    test(X1, X2, lj, **kwargs)
    
    print "******************************"
    print "testing normal LJ  non isomer"
    print "******************************"
    X2 = np.random.uniform(-1,1,[natoms*3])*(float(natoms))**(1./3)
    ret = quench( X2, lj)
    X2 = ret.coords
    
    Y = X1.reshape([-1,3])
    Y+=np.random.random(3)
    X1[:] = Y.flatten()
 
    test(X1, X2, lj, **kwargs)
    

    distinit = np.linalg.norm(X1-X2)
    print "distinit", distinit
Пример #18
0
def test_LJ(natoms=12, **kwargs):
    from pygmin.potentials.lj import LJ
    from pygmin.optimize import mylbfgs
    import pygmin.utils.rotations as rot
    from pygmin.mindist.permutational_alignment import permuteArray
    import random

    quench = mylbfgs
    lj = LJ()
    X1 = np.random.uniform(-1, 1, [natoms * 3]) * (float(natoms))**(1. / 3)
    #quench X1
    ret = quench(X1, lj)
    X1 = ret.coords
    X2 = np.random.uniform(-1, 1, [natoms * 3]) * (float(natoms))**(1. / 3)
    #make X2 a rotation of X1
    print "testing with", natoms, "atoms, with X2 a rotated and permuted isomer of X1"
    aa = rot.random_aa()
    rot_mx = rot.aa2mx(aa)
    for j in range(natoms):
        i = 3 * j
        X2[i:i + 3] = np.dot(rot_mx, X1[i:i + 3])
    perm = range(natoms)
    random.shuffle(perm)
    print perm
    X2 = permuteArray(X2, perm)

    #X1 = np.array( [ 0., 0., 0., 1., 0., 0., 0., 0., 1.,] )
    #X2 = np.array( [ 0., 0., 0., 1., 0., 0., 0., 1., 0.,] )
    import copy
    X1i = copy.copy(X1)
    X2i = copy.copy(X2)

    print "******************************"
    print "testing normal LJ  ISOMER"
    print "******************************"
    test(X1, X2, lj, **kwargs)

    print "******************************"
    print "testing normal LJ  non isomer"
    print "******************************"
    X2 = np.random.uniform(-1, 1, [natoms * 3]) * (float(natoms))**(1. / 3)
    ret = quench(X2, lj)
    X2 = ret.coords

    Y = X1.reshape([-1, 3])
    Y += np.random.random(3)
    X1[:] = Y.flatten()

    test(X1, X2, lj, **kwargs)

    distinit = np.linalg.norm(X1 - X2)
    print "distinit", distinit
Пример #19
0
def test_LJ(natoms = 12, **kwargs):
    from pygmin.potentials.lj import LJ
    import pygmin.defaults
    import pygmin.utils.rotations as rot
    from pygmin.mindist.permutational_alignment import permuteArray
    import random

    quench = pygmin.defaults.quenchRoutine
    lj = LJ()
    X1 = np.random.uniform(-1,1,[natoms*3])*(float(natoms))**(1./3)
    #quench X1
    ret = quench( X1, lj.getEnergyGradient)
    X1 = ret[0]
    X2 = np.random.uniform(-1,1,[natoms*3])*(float(natoms))**(1./3)
    #make X2 a rotation of X1
    print "testing with", natoms, "atoms, with X2 a rotated and permuted isomer of X1"
    aa = rot.random_aa()
    rot_mx = rot.aa2mx( aa )
    for j in range(natoms):
        i = 3*j
        X2[i:i+3] = np.dot( rot_mx, X1[i:i+3] )
    perm = range(natoms)
    random.shuffle( perm )
    print perm
    X2 = permuteArray( X2, perm)

    #X1 = np.array( [ 0., 0., 0., 1., 0., 0., 0., 0., 1.,] )
    #X2 = np.array( [ 0., 0., 0., 1., 0., 0., 0., 1., 0.,] )
    import copy
    X1i = copy.copy(X1)
    X2i = copy.copy(X2)
    
    print "******************************"
    print "testing normal LJ  ISOMER"
    print "******************************"
    test(X1, X2, lj, **kwargs)
    
    print "******************************"
    print "testing normal LJ  non isomer"
    print "******************************"
    X2 = np.random.uniform(-1,1,[natoms*3])*(float(natoms))**(1./3)
    ret = quench( X2, lj.getEnergyGradient)
    X2 = ret[0]
    test(X1, X2, lj, **kwargs)
    

    distinit = np.linalg.norm(X1-X2)
    print "distinit", distinit
Пример #20
0
 def takeStep(self, coords, **kwargs):
     # easy access to coordinates
     ca = CoordsAdapter(nrigid=coords.size/6, coords = coords)
     
     backbone = np.zeros(3)
     
     # random rotation for angle-axis vectors
     for pos, rot in zip(ca.posRigid, ca.rotRigid):
         backbone = backbone + rotations.vec_random( )*0.7525            
         
         # choose a random rotation
         rot[:] = rotations.random_aa()
         
         # calcualte center of base from backgone
         a1 = np.dot(rotations.aa2mx(rot), np.array([1., 0., 0.]))
         pos[:]  = backbone + 0.4 * a1                        
Пример #21
0
def test_LJ(natoms=12, **kwargs):
    from pygmin.potentials.lj import LJ
    import pygmin.defaults
    import pygmin.utils.rotations as rot
    from pygmin.mindist.permutational_alignment import permuteArray
    import random

    quench = pygmin.defaults.quenchRoutine
    lj = LJ()
    X1 = np.random.uniform(-1, 1, [natoms * 3]) * (float(natoms))**(1. / 3)
    #quench X1
    ret = quench(X1, lj.getEnergyGradient)
    X1 = ret[0]
    X2 = np.random.uniform(-1, 1, [natoms * 3]) * (float(natoms))**(1. / 3)
    #make X2 a rotation of X1
    print "testing with", natoms, "atoms, with X2 a rotated and permuted isomer of X1"
    aa = rot.random_aa()
    rot_mx = rot.aa2mx(aa)
    for j in range(natoms):
        i = 3 * j
        X2[i:i + 3] = np.dot(rot_mx, X1[i:i + 3])
    perm = range(natoms)
    random.shuffle(perm)
    print perm
    X2 = permuteArray(X2, perm)

    #X1 = np.array( [ 0., 0., 0., 1., 0., 0., 0., 0., 1.,] )
    #X2 = np.array( [ 0., 0., 0., 1., 0., 0., 0., 1., 0.,] )
    import copy
    X1i = copy.copy(X1)
    X2i = copy.copy(X2)

    print "******************************"
    print "testing normal LJ  ISOMER"
    print "******************************"
    test(X1, X2, lj, **kwargs)

    print "******************************"
    print "testing normal LJ  non isomer"
    print "******************************"
    X2 = np.random.uniform(-1, 1, [natoms * 3]) * (float(natoms))**(1. / 3)
    ret = quench(X2, lj.getEnergyGradient)
    X2 = ret[0]
    test(X1, X2, lj, **kwargs)

    distinit = np.linalg.norm(X1 - X2)
    print "distinit", distinit
Пример #22
0
    def translation_step(self, coords):
        """
        take a random translational step.

        note: this step is rotationally invariant, which is different than the normal take_step routine
        note: this method also favors shorter steps than the normal take_step routine
        """
        nmol = len(coords) / 2 / 3
        stepsize = self.getTStep()
        for j in range(nmol):
            #get a random unit vector
            #this is a dumb way to do it
            v = rot.random_aa()
            #make the step length random and uniform in [0,stepsize]
            v *= self.RNG() * stepsize / np.linalg.norm(v)
            #print "rand ", rand
            coords[3 * j:3 * j + 3] += v
Пример #23
0
    def translation_step(self, coords):
        """
        take a random translational step.

        note: this step is rotationally invariant, which is different than the normal take_step routine
        note: this method also favors shorter steps than the normal take_step routine
        """
        nmol = len(coords) / 2 / 3
        stepsize = self.getTStep()
        for j in range(nmol):
            #get a random unit vector
            #this is a dumb way to do it
            v = rot.random_aa()
            #make the step length random and uniform in [0,stepsize]
            v *= self.RNG() * stepsize / np.linalg.norm(v)
            #print "rand ", rand
            coords[3*j : 3*j + 3] += v
Пример #24
0
 def createBasinHopping(self):
     import pygmin.basinhopping as bh
     import pygmin.utils.rotations as rot
     mysys = self.createSystem()
     nsites = mysys.nsites
     nmol = self.nmol
     #set up initial coords
     coords = np.zeros(2*3*nmol)
     coords[0:nmol*3] = np.random.uniform(-1,1,[nmol*3]) * 1.0*(nsites)**(1./3)
     for i in range(nmol):
         k = nmol*3 + 3*i
         coords[k : k + 3] = rot.random_aa()
     #set up take step routine
     from pygmin.potentials.rigid_bodies.take_step import RBTakeStep
     step = RBTakeStep()
     opt = bh.BasinHopping(coords,mysys,
                       temperature=1., takeStep=step, outstream=None)
     return opt
Пример #25
0
def _optimizePermRot(X1, X2, niter, permlist, verbose=False, use_quench=True):
    if use_quench:
        pot = MinPermDistPotential(X1, X2.copy(), permlist=permlist)

    distbest = getDistxyz(X1, X2)
    mxbest = np.identity(3)
    X20 = X2.copy()
    for i in range(niter):
        #get and apply a random rotation
        aa = random_aa()
        if not use_quench:
            mx = aa2mx(aa)
            mxtot = mx
            #print "X2.shape", X2.shape
        else:
            #optimize the rotation using a permutationally invariand distance metric
            ret = defaults.quenchRoutine(aa, pot.getEnergyGradient, tol=0.01)
            aa1 = ret[0]
            mx1 = aa2mx(aa1)
            mxtot = mx1
        X2 = applyRotation(mxtot, X20)
        
        #optimize the permutations
        dist, X1, X2 = findBestPermutation(X1, X2, permlist)
        if verbose:
            print "dist", dist, "distbest", distbest
        #print "X2.shape", X2.shape
        
        #optimize the rotation
        dist, Q2 = getAlignRotation(X1, X2)
#        print "dist", dist, "Q2", Q2
        mx2 = q2mx(Q2)
        mxtot = np.dot(mx2, mxtot)
        
        if dist < distbest:
            distbest = dist
            mxbest = mxtot
    return distbest, mxbest
Пример #26
0
def _optimizePermRot(X1, X2, niter, permlist, verbose=False, use_quench=True):
    if use_quench:
        pot = MinPermDistPotential(X1, X2.copy(), permlist=permlist)

    distbest = getDistxyz(X1, X2)
    mxbest = np.identity(3)
    X20 = X2.copy()
    for i in range(niter):
        #get and apply a random rotation
        aa = random_aa()
        if not use_quench:
            mx = aa2mx(aa)
            mxtot = mx
            #print "X2.shape", X2.shape
        else:
            #optimize the rotation using a permutationally invariand distance metric
            ret = defaults.quenchRoutine(aa, pot.getEnergyGradient, tol=0.01)
            aa1 = ret[0]
            mx1 = aa2mx(aa1)
            mxtot = mx1
        X2 = applyRotation(mxtot, X20)

        #optimize the permutations
        dist, X1, X2 = findBestPermutation(X1, X2, permlist)
        if verbose:
            print "dist", dist, "distbest", distbest
        #print "X2.shape", X2.shape

        #optimize the rotation
        dist, Q2 = getAlignRotation(X1, X2)
        #        print "dist", dist, "Q2", Q2
        mx2 = q2mx(Q2)
        mxtot = np.dot(mx2, mxtot)

        if dist < distbest:
            distbest = dist
            mxbest = mxtot
    return distbest, mxbest
Пример #27
0
def test_takestep(nmol = 4):
    #get an initial set of coordinates
    import copy
    
    nsites = nmol*3
    comcoords = np.random.uniform(-1,1,[nmol*3]) * 1.3*(nsites)**(1./3)
    aacoords = np.array( [copy.copy(rot.random_aa()) for i in range(nmol)] )
    aacoords = aacoords.reshape(3*nmol)
    coords = np.zeros(2*3*nmol, np.float64)
    coords[0:3*nmol] = comcoords[:]
    coords[3*nmol:2*3*nmol] = aacoords[:]
    print "lencoords, len aacoords", len (coords), len(aacoords), len(comcoords)

    takestep = RBTakeStep()
    print coords
    oldcoords = coords.copy()
    takestep.translation_step(coords)
    print coords
    print coords - oldcoords
    
    print ""
    print "taking orientational step"
    print ""
    oldcoords = coords.copy()
    takestep.orientational_step(coords)
    print coords
    print coords - oldcoords
    
    print ""
    print "taking one of each step"
    print ""
    oldcoords = coords.copy()
    takestep.takeStep(coords)
    takestep.takeStep(coords)
    print coords
    print coords - oldcoords
Пример #28
0
def test_takestep(nmol=4):
    #get an initial set of coordinates
    import copy

    nsites = nmol * 3
    comcoords = np.random.uniform(-1, 1, [nmol * 3]) * 1.3 * (nsites)**(1. / 3)
    aacoords = np.array([copy.copy(rot.random_aa()) for i in range(nmol)])
    aacoords = aacoords.reshape(3 * nmol)
    coords = np.zeros(2 * 3 * nmol, np.float64)
    coords[0:3 * nmol] = comcoords[:]
    coords[3 * nmol:2 * 3 * nmol] = aacoords[:]
    print "lencoords, len aacoords", len(coords), len(aacoords), len(comcoords)

    takestep = RBTakeStep()
    print coords
    oldcoords = coords.copy()
    takestep.translation_step(coords)
    print coords
    print coords - oldcoords

    print ""
    print "taking orientational step"
    print ""
    oldcoords = coords.copy()
    takestep.orientational_step(coords)
    print coords
    print coords - oldcoords

    print ""
    print "taking one of each step"
    print ""
    oldcoords = coords.copy()
    takestep.takeStep(coords)
    takestep.takeStep(coords)
    print coords
    print coords - oldcoords
Пример #29
0
 def takeStep(self, coords, **kwargs):
     ''' takeStep routine to generate random cell '''        
     ca = self.coordsadapter        
     ca.updateCoords(coords)
     
     atomistic = np.zeros(3*GMIN.getNAtoms())
     valid_configuration = False
     for i in xrange(50):
         volumeTarget = self.expand_current*lattice.volume(ca.lattice)
          
         # random box
         ca.lattice[[0,3,5]] = 1.0 + self.expand * np.random.random(3)  
         ca.lattice[[1,2,4]] = self.shear * np.random.random(3)
         
         if(self.volume != None):
             volumeTarget = self.volume[0] + (self.volume[1] - self.volume[0]) * np.random.random()
                     
         vol = lattice.volume(ca.lattice)
         ca.lattice[:] = ca.lattice * (volumeTarget / vol)**(1.0/3.0)
         GMIN.reduceCell(coords)
         
         for i in xrange(50):# first choose random positions and rotations
             for i in xrange(GMIN.getNRigidBody()):
                 ca.posRigid[i] = np.random.random()
                 ca.rotRigid[i] = rotations.random_aa()
     
             if self.overlap is None:
                 return
         
         
             GMIN.toAtomistic(atomistic, coords)
             if not crystals.has_overlap(atomistic, self.overlap):
                 return
                         
         print "Could generate valid configuration for current box, choose new box"
     raise Exception("GenRandomCrystal: failed to generate a non-overlapping configuration")
Пример #30
0
def random_rotation( aa):
    aanew = rot.random_aa()
    #print "aanew ", aanew
    aa[:] = aanew[:]
Пример #31
0
def test_sandbox(nmol = 6):
    import copy
    from pygmin.potentials.lj import LJ

    #define the molecule types.
    #here use only one type, LWOTP
    otp = molecule.setupLWOTP()


    # define the interaction matrix for the system.
    # for LWOTP there is only one atom type, so this is trivial
    lj = LJ()
    interaction_matrix = [[lj]]


    #set up a list of molecules
    mols = [otp for i in range(nmol)]

    #set up the RBSandbox object
    mysys = RBSandbox(mols, interaction_matrix)
    nsites = mysys.nsites
    

    #get an initial set of coordinates
    comcoords = np.random.uniform(-1,1,[nmol*3]) * 1.3*(nsites)**(1./3)
    aacoords = np.array( [copy.copy(rot.random_aa()) for i in range(nmol)] )
    aacoords = aacoords.reshape(3*nmol)
    coords = np.zeros(2*3*nmol, np.float64)
    coords[0:3*nmol] = comcoords[:]
    coords[3*nmol:2*3*nmol] = aacoords[:]
    print "lencoords, len aacoords", len (coords), len(aacoords), len(comcoords)

    #print "xyz coords", mysys.transformToXYZ(coords)

    #save the initial set of coords
    printlist = []
    xyz = mysys.getxyz( coords )
    printlist.append( (xyz.copy(), "initial"))

    #calculate the initial energy
    Einit = mysys.getEnergy(coords)
    print "initial energy", Einit

    #test the gradient
    numericV = mysys.NumericalDerivative(coords, 1e-10)
    numericV = numericV.copy()
    print "numeric V", numericV

    E, V = mysys.getEnergyGradient(coords)
    print "energy from gradient", E, "difference", E - Einit
    #print "analytic gradient", V
    maxgrad_relative = np.max(np.abs(V-numericV)/np.abs(V))
    maxgraddiff = np.max(np.abs(V - numericV))
    print "max error in gradient", maxgraddiff, "max relative", maxgrad_relative

    #do a quench to make sure everything is working well
    from pygmin.optimize import lbfgs_scipy
    coords, E, rms, funcalls = lbfgs_scipy(coords, mysys.getEnergyGradient, iprint=-1)
    print "postquench E", E, "rms", rms, "funtion calls", funcalls
    xyz = mysys.getxyz(coords )
    printlist.append( (xyz.copy(), "post quench"))


    #print the saved coords
    fname = "otp.xyz"
    print "saving xyz coords to", fname
    from pygmin.printing.print_atoms_xyz import printAtomsXYZ as printxyz
    with open(fname, "w") as fout:
        for xyz, line2 in printlist:
            printxyz( fout, xyz, line2=line2, atom_type=["N", "O", "O"])
            
    
    test_symmetries(coords, mysys)
Пример #32
0
def test_sandbox(nmol=6):
    import copy
    from pygmin.potentials.lj import LJ

    #define the molecule types.
    #here use only one type, LWOTP
    otp = molecule.setupLWOTP()

    # define the interaction matrix for the system.
    # for LWOTP there is only one atom type, so this is trivial
    lj = LJ()
    interaction_matrix = [[lj]]

    #set up a list of molecules
    mols = [otp for i in range(nmol)]

    #set up the RBSandbox object
    mysys = RBSandbox(mols, interaction_matrix)
    nsites = mysys.nsites

    #get an initial set of coordinates
    comcoords = np.random.uniform(-1, 1, [nmol * 3]) * 1.3 * (nsites)**(1. / 3)
    aacoords = np.array([copy.copy(rot.random_aa()) for i in range(nmol)])
    aacoords = aacoords.reshape(3 * nmol)
    coords = np.zeros(2 * 3 * nmol, np.float64)
    coords[0:3 * nmol] = comcoords[:]
    coords[3 * nmol:2 * 3 * nmol] = aacoords[:]
    print "lencoords, len aacoords", len(coords), len(aacoords), len(comcoords)

    #print "xyz coords", mysys.transformToXYZ(coords)

    #save the initial set of coords
    printlist = []
    xyz = mysys.getxyz(coords)
    printlist.append((xyz.copy(), "initial"))

    #calculate the initial energy
    Einit = mysys.getEnergy(coords)
    print "initial energy", Einit

    #test the gradient
    numericV = mysys.NumericalDerivative(coords, 1e-10)
    numericV = numericV.copy()
    print "numeric V", numericV

    E, V = mysys.getEnergyGradient(coords)
    print "energy from gradient", E, "difference", E - Einit
    #print "analytic gradient", V
    maxgrad_relative = np.max(np.abs(V - numericV) / np.abs(V))
    maxgraddiff = np.max(np.abs(V - numericV))
    print "max error in gradient", maxgraddiff, "max relative", maxgrad_relative

    #do a quench to make sure everything is working well
    from pygmin.optimize import lbfgs_scipy
    coords, E, rms, funcalls = lbfgs_scipy(coords,
                                           mysys.getEnergyGradient,
                                           iprint=-1)
    print "postquench E", E, "rms", rms, "funtion calls", funcalls
    xyz = mysys.getxyz(coords)
    printlist.append((xyz.copy(), "post quench"))

    #print the saved coords
    fname = "otp.xyz"
    print "saving xyz coords to", fname
    from pygmin.printing.print_atoms_xyz import printAtomsXYZ as printxyz
    with open(fname, "w") as fout:
        for xyz, line2 in printlist:
            printxyz(fout, xyz, line2=line2, atom_type=["N", "O", "O"])

    test_symmetries(coords, mysys)
Пример #33
0
interaction_matrix = [[lj]]

#set up a list of molecules
mols = [otp for i in range(nmol)]

#set up the RBSandbox object
mysys = sandbox.RBSandbox(mols, interaction_matrix)
nsites = mysys.nsites

#get an initial set of coordinates
coords = np.zeros(2 * 3 * nmol, np.float64)
coords[0:nmol *
       3] = np.random.uniform(-1, 1, [nmol * 3]) * 1.3 * (nsites)**(1. / 3)
for i in range(nmol):
    k = nmol * 3 + 3 * i
    coords[k:k + 3] = rot.random_aa()

#set up the takestep routine
from pygmin.potentials.rigid_bodies.take_step import RBTakeStep
takestep = RBTakeStep()

#set up the class to save lowest energy structures
from pygmin.storage.savenlowest import SaveN
saveit = SaveN(100)

#set up basinhopping
from pygmin.basinhopping import BasinHopping
bh = BasinHopping(coords, mysys, takestep, storage=saveit.insert)

#run basin hopping
bh.run(40)
Пример #34
0
def test_molecule():
    otp = setupLWOTP()

    xyz = otp.getxyz()
    from pygmin.printing.print_atoms_xyz import printAtomsXYZ as printxyz
    import sys
    #with open("out.xyz", "w") as fout:
    printxyz(sys.stdout, xyz)

    aa = np.array([.2, .3, .4])
    for xyz, aanew in otp.getSymmetries(np.zeros(3), aa):
        printxyz(sys.stdout, xyz, line2="symmetry")
        xyz = otp.getxyz(aa=aanew)
        printxyz(sys.stdout, xyz, line2="symmetry from returned aa")


if __name__ == "__main__":
    test_molecule()

    aa1 = rot.random_aa()
    aa2 = rot.random_aa()
    rmat1 = rot.aa2mx(aa1)
    rmat2 = rot.aa2mx(aa2)

    rmat21 = np.dot(rmat2, rmat1)
    aa21 = rot.rotate_aa(aa1, aa2)
    rmat21aa = rot.aa2mx(aa21)
    print rmat21
    print rmat21aa
    print abs(rmat21 - rmat21aa) < 1e-12
Пример #35
0
 def get_random_configuration(self):
     coords = 5.*np.random.random(6*self.nrigid)
     ca = self.aasystem.coords_adapter(coords)
     for p in ca.rotRigid:
         p = rotations.random_aa()
     return coords
Пример #36
0
 from copy import deepcopy
 water = RigidFragment()
 rho   = 0.9572
 theta = 104.52/180.0*pi      
 water.add_atom("O", np.array([0., -1., 0.]), 1.)
 water.add_atom("O", np.array([0., 1., 0.]), 1.)
 #water.add_atom("H", rho*np.array([0.0, sin(0.5*theta), cos(0.5*theta)]), 1.)
 #water.add_atom("H", rho*np.array([0.0, -sin(0.5*theta), cos(0.5*theta)]), 1.)
 water.finalize_setup()
 # define the whole water system
 system = RBTopology()
 nrigid = 1
 system.add_sites([deepcopy(water) for i in xrange(nrigid)])
 from pygmin.utils import rotations
 rbcoords=np.zeros(6)
 rbcoords[3:]= rotations.random_aa()
 
 coords = system.to_atomistic(rbcoords)
 
 print "rb coords\n", rbcoords
 print "coords\n", coords
 grad = (np.random.random(coords.shape) -0.5)
 
 v = coords[1] - coords[0]
 v/=np.linalg.norm(v)
 
 grad[0] -= np.dot(grad[0], v)*v
 grad[1] -= np.dot(grad[1], v)*v
 
 grad -= np.average(grad, axis=0)
 grad /= np.linalg.norm(grad)
Пример #37
0
interaction_matrix = [[lj]]


#set up a list of molecules
mols = [otp for i in range(nmol)]

#set up the RBSandbox object
mysys = sandbox.RBSandbox(mols, interaction_matrix)
nsites = mysys.nsites

#get an initial set of coordinates
coords = np.zeros(2*3*nmol, np.float64)
coords[0:nmol*3] = np.random.uniform(-1,1,[nmol*3]) * 1.3*(nsites)**(1./3)
for i in range(nmol):
    k = nmol*3 + 3*i
    coords[k : k + 3] = rot.random_aa()


#set up the takestep routine
from  pygmin.potentials.rigid_bodies.take_step import RBTakeStep
takestep = RBTakeStep()

#set up the class to save lowest energy structures
from pygmin.storage.savenlowest import SaveN
saveit = SaveN(100)

#set up basinhopping
from  pygmin.basinhopping import BasinHopping
bh = BasinHopping(coords, mysys, takestep, storage=saveit.insert )

#run basin hopping
Пример #38
0
    x = np.random.random([natoms,3])*5
    masses = [1., 1., 16.] #np.random.random(natoms)
    print masses
    x -= np.average(x, axis=0, weights=masses)
    cog = np.average(x, axis=0)
    S=np.zeros([3,3])
    for i in xrange(3):
        for j in xrange(3):
            S[i][j]=np.sum(x[:,i]*x[:,j])
    site = AASiteType(M=natoms, S=S, W=natoms, cog=cog)
    X1=np.zeros(3)
    p1=np.zeros(3)    
    
    X1 = 10.1*np.random.random(3)
    X2 = 10.1*np.random.random(3)
    p1 = rotations.random_aa()
    p2 = rotations.random_aa()
        
    R1 = rotations.aa2mx(p1)
    R2 = rotations.aa2mx(p2)
    
    x1 = np.dot(R1, x.transpose()).transpose() + X1
    x2 = np.dot(R2, x.transpose()).transpose() + X2
    
    import _aadist
    print "site representation:", np.sum((x1-x2)**2)
    print "distance function:  ", site.distance_squared(X1, p1, X2, p2)

    print "fortran function:  ", _aadist.sitedist(X2 - X1, p1, p2, site.S, site.W, cog)

    coords1 = np.random.random(120)
Пример #39
0
 x = np.random.random([natoms,3])*5
 masses = [1., 1., 16.] #np.random.random(natoms)
 print masses
 x -= np.average(x, axis=0, weights=masses)
 cog = np.average(x, axis=0)
 S=np.zeros([3,3])
 for i in xrange(3):
     for j in xrange(3):
         S[i][j]=np.sum(x[:,i]*x[:,j])
 site = AASiteType(M=natoms, S=S, W=natoms, cog=cog)
 X1=np.zeros(3)
 p1=np.zeros(3)    
 
 X1 = 10.1*np.random.random(3)
 X2 = 10.1*np.random.random(3)
 p1 = rotations.random_aa()
 p2 = rotations.random_aa()
     
 R1 = rotations.aa2mx(p1)
 R2 = rotations.aa2mx(p2)
 
 x1 = np.dot(R1, x.transpose()).transpose() + X1
 x2 = np.dot(R2, x.transpose()).transpose() + X2
 
 print "site representation:", np.sum((x1-x2)**2)
 print "distance function:  ", site.distance_squared(X1, p1, X2, p2)
 print site.distance_squared_grad(X1, p1, X2, p2)
 g_M = np.zeros(3)
 g_P = np.zeros(3)
 
 for i in xrange(3):
Пример #40
0
    from copy import deepcopy
    water = RigidFragment()
    rho = 0.9572
    theta = 104.52 / 180.0 * pi
    water.add_atom("O", np.array([0., -1., 0.]), 1.)
    water.add_atom("O", np.array([0., 1., 0.]), 1.)
    #water.add_atom("H", rho*np.array([0.0, sin(0.5*theta), cos(0.5*theta)]), 1.)
    #water.add_atom("H", rho*np.array([0.0, -sin(0.5*theta), cos(0.5*theta)]), 1.)
    water.finalize_setup()
    # define the whole water system
    system = RBTopology()
    nrigid = 1
    system.add_sites([deepcopy(water) for i in xrange(nrigid)])
    from pygmin.utils import rotations
    rbcoords = np.zeros(6)
    rbcoords[3:] = rotations.random_aa()

    coords = system.to_atomistic(rbcoords)

    print "rb coords\n", rbcoords
    print "coords\n", coords
    grad = (np.random.random(coords.shape) - 0.5)

    v = coords[1] - coords[0]
    v /= np.linalg.norm(v)

    grad[0] -= np.dot(grad[0], v) * v
    grad[1] -= np.dot(grad[1], v) * v

    grad -= np.average(grad, axis=0)
    grad /= np.linalg.norm(grad)
Пример #41
0
def random_rotation(aa):
    aanew = rot.random_aa()
    #print "aanew ", aanew
    aa[:] = aanew[:]
Пример #42
0
    xyz = otp.getxyz()
    from pygmin.printing.print_atoms_xyz import printAtomsXYZ as printxyz
    import sys
    #with open("out.xyz", "w") as fout:
    printxyz(sys.stdout, xyz)
    
    aa = np.array([.2, .3, .4])
    for xyz, aanew in otp.getSymmetries( np.zeros(3), aa):
        printxyz(sys.stdout, xyz, line2="symmetry")
        xyz = otp.getxyz(aa = aanew)
        printxyz(sys.stdout, xyz, line2="symmetry from returned aa")




if __name__ == "__main__":
    test_molecule()
    
    aa1 = rot.random_aa()
    aa2 = rot.random_aa()
    rmat1 = rot.aa2mx(aa1)
    rmat2 = rot.aa2mx(aa2)
    
    rmat21 = np.dot(rmat2, rmat1)
    aa21 = rot.rotate_aa(aa1, aa2)
    rmat21aa = rot.aa2mx(aa21)
    print rmat21
    print rmat21aa
    print abs(rmat21 - rmat21aa) < 1e-12
Пример #43
0
 def get_random_configuration(self):
     coords = 5.*np.random.random(6*self.nrigid)
     ca = self.aasystem.coords_adapter(coords)
     for p in ca.rotRigid:
         p = rotations.random_aa()
     return coords
Пример #44
0
def test_binary_LJ(natoms = 12, **kwargs):
    import pygmin.defaults
    import pygmin.utils.rotations as rot
    quench = pygmin.defaults.quenchRoutine

    printlist = []
    
    ntypea = int(natoms*.8)
    from pygmin.potentials.ljpshift import LJpshift
    lj = LJpshift(natoms, ntypea)
    permlist = [range(ntypea), range(ntypea, natoms)]

    X1 = np.random.uniform(-1,1,[natoms*3])*(float(natoms))**(1./3)/2
    printlist.append( (X1.copy(), "very first"))
    #quench X1
    ret = quench( X1, lj.getEnergyGradient)
    X1 = ret[0]
    printlist.append((X1.copy(), "after quench"))

    X2 = np.random.uniform(-1,1,[natoms*3])*(float(natoms))**(1./3)
    #make X2 a rotation of X1
    print "testing with", natoms, "atoms,", ntypea, "type A atoms, with X2 a rotated and permuted isomer of X1"
    aa = rot.random_aa()
    rot_mx = rot.aa2mx( aa )
    for j in range(natoms):
        i = 3*j
        X2[i:i+3] = np.dot( rot_mx, X1[i:i+3] )
    printlist.append((X2.copy(), "x2 after rotation"))
    

    

    import random, copy
    from pygmin.mindist.permutational_alignment import permuteArray

    for atomlist in permlist:
        perm = copy.copy(atomlist)
        random.shuffle( perm )
        print perm
        X2 = permuteArray( X2, perm)
    printlist.append((X2.copy(), "x2 after permutation"))


    #X1 = np.array( [ 0., 0., 0., 1., 0., 0., 0., 0., 1.,] )
    #X2 = np.array( [ 0., 0., 0., 1., 0., 0., 0., 1., 0.,] )
    X1i = copy.copy(X1)
    X2i = copy.copy(X2)
    
    atomtypes = ["N" for i in range(ntypea)]
    for i in range(natoms-ntypea):
        atomtypes.append("O")
    
    print "******************************"
    print "testing binary LJ  ISOMER"
    print "******************************"
    test(X1, X2, lj, atomtypes=atomtypes, permlist = permlist, **kwargs)
    
    print "******************************"
    print "testing binary LJ  non isomer"
    print "******************************"
    X2 = np.random.uniform(-1,1,[natoms*3])*(float(natoms))**(1./3)
    ret = quench( X2, lj.getEnergyGradient)
    X2 = ret[0]
    test(X1, X2, lj, atomtypes=atomtypes, permlist=permlist, **kwargs)