Example #1
0
    def test_cpp_align(self):
        x1 = np.array([random_aa() for _ in range(2*self.nrigid)]).ravel()
        x2 = np.array([random_aa() for _ in range(2*self.nrigid)]).ravel()
        
        x1_cpp = x1.copy()
        x2_cpp = x2.copy()
        x1_python = x1.copy()
        x2_python = x2.copy()
        
        ret = self.measure._align_pythonic(x1_python, x2_python)
        self.assertIsNone(ret)
        ret = self.measure.align(x1_cpp, x2_cpp)
        self.assertIsNone(ret)
        
        assert_arrays_almost_equal(self, x1_python, x1)
        assert_arrays_almost_equal(self, x1_cpp, x1)
        
        # assert that the center of mass coordinates didn't change
        assert_arrays_almost_equal(self, x2_python[:3*self.nrigid], x2[:3*self.nrigid])
        assert_arrays_almost_equal(self, x2_cpp[:3*self.nrigid], x2[:3*self.nrigid])
        
        # assert that x2 actually changed
        max_change = np.max(np.abs(x2_cpp - x2))
        self.assertGreater(max_change, 1e-3)

        assert_arrays_almost_equal(self, x2_python, x2_cpp)
Example #2
0
    def test_cpp_align(self):
        x1 = np.array([random_aa() for _ in range(2 * self.nrigid)]).ravel()
        x2 = np.array([random_aa() for _ in range(2 * self.nrigid)]).ravel()

        x1_cpp = x1.copy()
        x2_cpp = x2.copy()
        x1_python = x1.copy()
        x2_python = x2.copy()

        ret = self.measure._align_pythonic(x1_python, x2_python)
        self.assertIsNone(ret)
        ret = self.measure.align(x1_cpp, x2_cpp)
        self.assertIsNone(ret)

        assert_arrays_almost_equal(self, x1_python, x1)
        assert_arrays_almost_equal(self, x1_cpp, x1)

        # assert that the center of mass coordinates didn't change
        assert_arrays_almost_equal(self, x2_python[:3 * self.nrigid],
                                   x2[:3 * self.nrigid])
        assert_arrays_almost_equal(self, x2_cpp[:3 * self.nrigid],
                                   x2[:3 * self.nrigid])

        # assert that x2 actually changed
        max_change = np.max(np.abs(x2_cpp - x2))
        self.assertGreater(max_change, 1e-3)

        assert_arrays_almost_equal(self, x2_python, x2_cpp)
Example #3
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
    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 pele.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 pele.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, MinPermDistCluster(measure=MeasureAtomicCluster(permlist=self.permlist)))

        
        #it's an isomer, so the distance should be zero
        self.assertTrue( abs(distreturned) < 1e-14, "didn't find isomer: dist = %g" % distreturned)
Example #5
0
File: otp.py Project: js850/pele
 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 pele.utils.rotations import random_aa
     for i in range(self.nmol, self.nmol*2):
         coords[i,:] = random_aa()
     return coords.flatten()
    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 pele.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 pele.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, MinPermDistCluster(measure=MeasureAtomicCluster(permlist=self.permlist)))

        
        #it's an isomer, so the distance should be zero
        self.assertTrue( abs(distreturned) < 1e-14, "didn't find isomer: dist = %g" % distreturned)
Example #7
0
    def test_cpp_rotate(self):
        x0 = np.array([random_aa() for _ in range(2 * self.nrigid)]).ravel()
        aa = random_aa()
        mx = aa2mx(aa)

        x0_rotated = x0.copy()
        self.transform.rotate(x0_rotated, mx)

        x0_rotated_python = x0.copy()
        self.transform._rotate_python(x0_rotated_python, mx)

        assert_arrays_almost_equal(self, x0_rotated, x0_rotated_python)

        mx_reverse = aa2mx(-aa)
        self.transform.rotate(x0_rotated, mx_reverse)
        assert_arrays_almost_equal(self, x0, x0_rotated)
Example #8
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.0 / 3)
    for i in range(nmol):
        k = 3 * nmol + 3 * i
        coords[k : k + 3] = rot.random_aa()
    return coords
Example #9
0
 def test_cpp_rotate(self):
     x0 = np.array([random_aa() for _ in range(2*self.nrigid)]).ravel()
     aa = random_aa()
     mx = aa2mx(aa)
     
     x0_rotated = x0.copy()
     self.transform.rotate(x0_rotated, mx)
     
     x0_rotated_python = x0.copy()
     self.transform._rotate_python(x0_rotated_python, mx)
     
     assert_arrays_almost_equal(self, x0_rotated, x0_rotated_python)
     
     mx_reverse = aa2mx(-aa)
     self.transform.rotate(x0_rotated, mx_reverse)
     assert_arrays_almost_equal(self, x0, x0_rotated)
Example #10
0
 def get_random_configuration(self):
     coords = 5. * np.random.uniform(-1, 1,
                                     6 * self.aatopology.get_nrigid())
     ca = self.aasystem.coords_adapter(coords)
     for p in ca.rotRigid:
         p[:] = rotations.random_aa()
     return coords
Example #11
0
def test(): # pragma: no cover
    from math import sin, cos, pi
    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 pele.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)
    
    print "torque", np.linalg.norm(np.cross(grad, v))
    rbgrad = system.transform_gradient(rbcoords, grad)
    p = rbcoords[3:]
    x = rbcoords[0:3]
    gp = rbgrad[3:]
    gx = rbgrad[:3]
    
    R, R1, R2, R3 = rotations.rot_mat_derivatives(p)        
    
    print "test1", np.linalg.norm(R1*gp[0])     
    print "test2", np.linalg.norm(R2*gp[1])     
    print "test3", np.linalg.norm(R3*gp[2])
    print "test4", np.linalg.norm(R1*gp[0]) + np.linalg.norm(R2*gp[1]) + np.linalg.norm(R3*gp[2])
         
    dR = R1*gp[0] + R2*gp[1] + R3*gp[2]
    print "test", np.linalg.norm(R1*gp[0] + R2*gp[1] + R3*gp[2])
    print np.trace(np.dot(dR, dR.transpose()))
    G = water.metric_tensor_aa(p)
    print np.dot(p, np.dot(G, p))     
    exit()
    
    
    gnew = system.redistribute_forces(rbcoords, rbgrad)
    print gnew
    print system.transform_grad(rbcoords, gnew)
    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
        coords1 = coords1.copy()
        coords2 = coords2.copy()
        
        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:
            dist, x2 = self.finalize_best_match(coords1)
            return self.distbest, coords1, 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
Example #13
0
 def get_random_configuration(self):
     # js850> this is a bit sketchy because nrigid might not be defined here.
     # probably we can get the number of molecules some other way.
     coords = 10.*np.random.random(6*self.nrigid)
     ca = self.aasystem.coords_adapter(coords)
     for p in ca.rotRigid:
         p[:] = rotations.random_aa()
     return coords
Example #14
0
 def get_random_configuration(self):
     # js850> this is a bit sketchy because nrigid might not be defined here.
     # probably we can get the number of molecules some other way.
     coords = 10.*np.random.random(6*self.nrigid)
     ca = self.aasystem.coords_adapter(coords)
     for p in ca.rotRigid:
         p[:] = rotations.random_aa()
     return coords
Example #15
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
Example #16
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()
Example #17
0
 def test_align_exact(self):
     x1 = np.array([random_aa() for _ in range(2*self.nrigid)]).ravel()
     x2 = x1.copy()
     tet = create_tetrahedron()
     mx = tet.symmetries[2].copy() 
     p = x2[-3:].copy()
     x2[-3:] = rotations.rotate_aa(rotations.mx2aa(mx), p)
     
     self.measure._align_pythonic(x1, x2)
     assert_arrays_almost_equal(self, x1, x2)
Example #18
0
    def test_align_exact(self):
        x1 = np.array([random_aa() for _ in range(2 * self.nrigid)]).ravel()
        x2 = x1.copy()
        tet = create_tetrahedron()
        mx = tet.symmetries[2].copy()
        p = x2[-3:].copy()
        x2[-3:] = rotations.rotate_aa(rotations.mx2aa(mx), p)

        self.measure._align_pythonic(x1, x2)
        assert_arrays_almost_equal(self, x1, x2)
Example #19
0
    def takeStep(self, coords, **kwargs):
        # easy access to coordinates
        ca = CoordsAdapter(nrigid=old_div(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()
Example #20
0
    def align_structures(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 triple 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
        coords1 = coords1.copy()
        coords2 = coords2.copy()

        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()

        # sn402: The unlikely event that the structures are already nearly perfectly aligned.
        if self.distbest < self.tol:
            dist, x2 = self.finalize_best_match(coords1)
            return self.distbest, coords1, 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)

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

        dist, x2 = self.finalize_best_match(coords1)

        return dist, coords1, x2
    def align_structures(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 triple 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
        coords1 = coords1.copy()
        coords2 = coords2.copy()
        
        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()
        
        # sn402: The unlikely event that the structures are already nearly perfectly aligned.
        if self.distbest < self.tol:
            dist, x2 = self.finalize_best_match(coords1)
            return self.distbest, coords1, 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)

        # TODO: should we do an additional sanity check for permutation / rotation?        
        
        dist, x2 = self.finalize_best_match(coords1)
        
        return dist, coords1, x2
Example #22
0
def test():  # pragma: no cover
    from math import pi
    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 pele.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)

    print "torque", np.linalg.norm(np.cross(grad, v))
    rbgrad = system.transform_gradient(rbcoords, grad)
    p = rbcoords[3:]
    x = rbcoords[0:3]
    gp = rbgrad[3:]
    gx = rbgrad[:3]

    R, R1, R2, R3 = rotations.rot_mat_derivatives(p)

    print "test1", np.linalg.norm(R1 * gp[0])
    print "test2", np.linalg.norm(R2 * gp[1])
    print "test3", np.linalg.norm(R3 * gp[2])
    print "test4", np.linalg.norm(R1 * gp[0]) + np.linalg.norm(
        R2 * gp[1]) + np.linalg.norm(R3 * gp[2])

    dR = R1 * gp[0] + R2 * gp[1] + R3 * gp[2]
    print "test", np.linalg.norm(R1 * gp[0] + R2 * gp[1] + R3 * gp[2])
    print np.trace(np.dot(dR, dR.transpose()))
def test_LJ(natoms = 12, **kwargs):
    from pele.potentials.lj import LJ
    from pele.optimize import mylbfgs
    import pele.utils.rotations as rot
    from pele.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
Example #24
0
def test_LJ(natoms=12, **kwargs):  # pragma: no cover
    from pele.potentials.lj import LJ
    from pele.optimize import mylbfgs
    import pele.utils.rotations as rot
    from pele.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 = list(range(natoms))
    random.shuffle(perm)
    print(perm)
    X2 = permuteArray(X2, perm)

    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)
def test_LJ(natoms = 12, **kwargs):
    from pele.potentials.lj import LJ
    import pele.defaults
    import pele.utils.rotations as rot
    from pele.mindist.permutational_alignment import permuteArray
    import random

    quench = pele.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
Example #26
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 += 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
Example #27
0
    def takeStep(self, coords, **kwargs):
        # easy access to coordinates
        ca = CoordsAdapter(nrigid=old_div(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 += 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
Example #28
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
Example #29
0
    def do(self, indices=None, stepsize=.8):
        natoms = 4
        x = np.array([rotations.random_aa() for _ in range(natoms)])
        x0 = x.copy()
        x = x.reshape(-1)

        rotate(stepsize, x, indices=indices)

        x = x.reshape(-1, 3)
        rlist = [relative_angle(x[i], x0[i]) for i in range(natoms)]
        for r in rlist:
            self.assertLessEqual(r, stepsize)

        if indices is not None:
            for i, r in enumerate(rlist):
                if i in indices:
                    self.assertGreater(r, 0)
                else:
                    self.assertAlmostEqual(r, 0, places=16)
Example #30
0
 def do(self, indices=None, stepsize=.8):
     natoms = 4
     x = np.array([rotations.random_aa() for _ in xrange(natoms)])
     x0 = x.copy()
     x = x.reshape(-1)
     
     rotate(stepsize, x, indices=indices)
     
     x = x.reshape(-1,3)
     rlist = [relative_angle(x[i], x0[i]) for i in xrange(natoms)]
     for r in rlist:
         self.assertLessEqual(r, stepsize)
     
     if indices is not None:
         for i, r in enumerate(rlist):
             if i in indices:
                 self.assertGreater(r, 0)
             else:
                 self.assertAlmostEqual(r, 0, places=16)
Example #31
0
 def test_rotation(self):
     """assert that the HSA energy is *not* invariant under rotation"""
     pot = self.system.get_potential()
     aa = rotations.random_aa()
     rmat = rotations.aa2mx(aa)
     from pele.mindist import TransformAtomicCluster
     tform = TransformAtomicCluster(can_invert=True)
     for m in self.database.minima():
         x = m.coords.copy()
         # randomly move the atoms by a small amount
         x += np.random.uniform(-1e-3, 1e-3, x.shape)
         ehsa1 = self.sampler.compute_energy(x, m, x0=m.coords)
         ecalc = pot.getEnergy(x)
         # now rotate by a random matrix
         xnew = x.copy()
         tform.rotate(xnew, rmat)
         ehsa2 = self.sampler.compute_energy(xnew, m, x0=m.coords)
         ecalc2 = pot.getEnergy(xnew)
         self.assertAlmostEqual(ecalc, ecalc2, 5)
         self.assertNotAlmostEqual(ehsa1, ehsa2, 1)
Example #32
0
 def test_rotation(self):
     """assert that the HSA energy is *not* invariant under rotation"""
     pot = self.system.get_potential()
     aa = rotations.random_aa()
     rmat = rotations.aa2mx(aa)
     from pele.mindist import TransformAtomicCluster
     tform = TransformAtomicCluster(can_invert=True)
     for m in self.database.minima():
         x = m.coords.copy()
         # randomly move the atoms by a small amount
         x += np.random.uniform(-1e-3, 1e-3, x.shape)
         ehsa1 = self.sampler.compute_energy(x, m, x0=m.coords)
         ecalc = pot.getEnergy(x)
         # now rotate by a random matrix
         xnew = x.copy()
         tform.rotate(xnew, rmat)
         ehsa2 = self.sampler.compute_energy(xnew, m, x0=m.coords)
         ecalc2 = pot.getEnergy(xnew)
         self.assertAlmostEqual(ecalc, ecalc2, 5)
         self.assertNotAlmostEqual(ehsa1, ehsa2, 1)
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
Example #34
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
Example #35
0
 def test_aa2mx(self):
     aa = random_aa()
     mx1 = aa2mx(aa)
     mx2 = rotations.aa2mx(aa)
     self.arrays_equal(mx1, mx2)
Example #36
0
 def test_rotate_aa(self):
     p1 = random_aa()
     p2 = random_aa()
     p3 = rotate_aa(p1, p2)
     p4 = rotations.rotate_aa(p1, p2)
     self.arrays_equal(p3, p4)
Example #37
0
 def test_aa2q(self):
     aa = random_aa()
     q1 = aa2q(aa)
     q2 = rotations.aa2q(aa)
     self.arrays_equal(q1, q2)
Example #38
0
 def test_aa2mx(self):
     aa = random_aa()
     mx1 = aa2mx(aa)
     mx2 = rotations.aa2mx(aa)
     self.arrays_equal(mx1, mx2)
Example #39
0
 def test_rotate_aa(self):
     p1 = random_aa()
     p2 = random_aa()
     p3 = rotate_aa(p1, p2)
     p4 = rotations.rotate_aa(p1, p2)
     self.arrays_equal(p3, p4)
Example #40
0
 def test_aa2q(self):
     aa = random_aa()
     q1 = aa2q(aa)
     q2 = rotations.aa2q(aa)
     self.arrays_equal(q1, q2)
Example #41
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
Example #42
0
 def test_align_bad_input(self):
     x1 = np.array([random_aa() for _ in range(2*self.nrigid)]).ravel()
     x2 = list(x1)
     
     with self.assertRaises(TypeError):
         self.measure.align(x1, x2)
Example #43
0
def test():  # pragma: no cover
    natoms = 3
    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 = 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)

    import time

    t0 = time.time()
    for i in xrange(1000):
        site.distance_squared(X1, p1, X2, p2)
    t1 = time.time()
    print "time python", t1 - t0
    for i in xrange(1000):
        sitedist(X2 - X1, p1, p2, site.S, site.W, cog)

        # _aadist.aadist(coords1, coords2, site.S, site.W, cog)
    t2 = time.time()
    print "time fortran", t2 - t1
    # for i in xrange(1000/20):
    #        #_aadist.sitedist(X1, p1, X2, p2, site.S, site.W, cog)
    #        _aadist.aadist(coords1, coords2, site.S, site.W, cog)
    t2 = time.time()
    print "time fortran acc", t2 - t1

    print site.distance_squared_grad(X1, p1, X2, p2)
    g_M = np.zeros(3)
    g_P = np.zeros(3)

    for i in xrange(3):
        eps = 1e-6
        delta = np.zeros(3)
        delta[i] = eps
        g_M[i] = (site.distance_squared(X1 + delta, p1, X2, p2)
                  - site.distance_squared(X1, p1, X2, p2)) / eps
        g_P[i] = (site.distance_squared(X1, p1 + delta, X2, p2)
                  - site.distance_squared(X1, p1, X2, p2)) / eps
    print g_M, g_P
    xx = site.distance_squared_grad(X1, p1, X2, p2)
    print g_M / xx[0], g_P / xx[1]
    print _aadist.sitedist_grad(X2 - X1, p1, p2, site.S, site.W, cog)
 def rrot(self, x):
     aa = rotations.random_aa()
     mx = rotations.aa2mx(aa)
     self.match.transform.rotate(x, mx)
Example #45
0
 def rrot(self, x):
     aa = rotations.random_aa()
     mx = rotations.aa2mx(aa)
     self.match.transform.rotate(x, mx)
Example #46
0
def test():  # pragma: no cover
    natoms = 3
    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 range(3):
        for j in range(3):
            S[i][j] = np.sum(x[:, i] * x[:, j])
    site = AASiteType(M=natoms, S=S, W=natoms, cog=cog)

    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

    from . 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))

    import time

    t0 = time.time()
    for i in range(1000):
        site.distance_squared(X1, p1, X2, p2)
    t1 = time.time()
    print("time python", t1 - t0)
    for i in range(1000):
        sitedist(X2 - X1, p1, p2, site.S, site.W, cog)

        # _aadist.aadist(coords1, coords2, site.S, site.W, cog)
    t2 = time.time()
    print("time fortran", t2 - t1)
    # for i in xrange(1000/20):
    #        #_aadist.sitedist(X1, p1, X2, p2, site.S, site.W, cog)
    #        _aadist.aadist(coords1, coords2, site.S, site.W, cog)
    t2 = time.time()
    print("time fortran acc", t2 - t1)

    print(site.distance_squared_grad(X1, p1, X2, p2))
    g_M = np.zeros(3)
    g_P = np.zeros(3)

    for i in range(3):
        eps = 1e-6
        delta = np.zeros(3)
        delta[i] = eps
        g_M[i] = old_div((site.distance_squared(X1 + delta, p1, X2, p2)
                  - site.distance_squared(X1, p1, X2, p2)), eps)
        g_P[i] = old_div((site.distance_squared(X1, p1 + delta, X2, p2)
                  - site.distance_squared(X1, p1, X2, p2)), eps)
    print(g_M, g_P)
    xx = site.distance_squared_grad(X1, p1, X2, p2)
    print(old_div(g_M, xx[0]), old_div(g_P, xx[1]))
    print(_aadist.sitedist_grad(X2 - X1, p1, p2, site.S, site.W, cog))
Example #47
0
def random_rotation( aa):
    aanew = rot.random_aa()
    #print "aanew ", aanew
    aa[:] = aanew[:]
Example #48
0
    def test_align_bad_input(self):
        x1 = np.array([random_aa() for _ in range(2 * self.nrigid)]).ravel()
        x2 = list(x1)

        with self.assertRaises(TypeError):
            self.measure.align(x1, x2)
Example #49
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 pele.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)