예제 #1
0
    def minimize(self):
        nreps = self.nrep
        nbins = self.nebins
        visitsT = (self.visits1d)
        #print "min vis", np.min(visitsT)
        self.logP = np.where(visitsT != 0, np.log(visitsT), 0)
        #print "minlogp", np.min(self.logP)
        self.reduced_energy = self.binenergy[np.newaxis, :] / (
            self.Tlist[:, np.newaxis] * self.k_B)

        self.whampot = WhamPotential(self.logP, self.reduced_energy)

        X = np.random.rand(nreps + nbins)
        E = self.whampot.getEnergy(X)
        #print "energy", E

        #print "quenching"
        try:
            from pygmin.optimize import mylbfgs as quench
            ret = quench(X, self.whampot, iprint=-1, maxstep=1e4)
        except ImportError:
            from pygmin.optimize import lbfgs_scipy as quench
            ret = quench(X, self.whampot)
        #print "quench energy", ret.energy
        X = ret.coords

        self.logn_E = X[nreps:]
        self.w_i_final = X[:nreps]
예제 #2
0
def guessts(coords1, coords2, pot):
    from pygmin.optimize import lbfgs_py as quench
#    from pygmin.mindist.minpermdist_stochastic import minPermDistStochastic as mindist
    from pygmin.transition_states import NEB
    from pygmin.systems import LJCluster
    ret1 = quench(coords1, pot.getEnergyGradient)
    ret2 = quench(coords2, pot.getEnergyGradient)
    coords1 = ret1[0]
    coords2 = ret2[0]
    natoms = len(coords1)/3
    system = LJCluster(natoms)
    mindist = system.get_mindist()
    dist, coords1, coords2 = mindist(coords1, coords2) 
    print "dist", dist
    print "energy coords1", pot.getEnergy(coords1)
    print "energy coords2", pot.getEnergy(coords2)
    from pygmin.transition_states import InterpolatedPath
    neb = NEB(InterpolatedPath(coords1, coords2, 20), pot)
    #neb.optimize(quenchParams={"iprint" : 1})
    neb.optimize(iprint=-30, nsteps=100)
    neb.MakeAllMaximaClimbing()
    #neb.optimize(quenchParams={"iprint": 30, "nsteps":100})
    for i in xrange(len(neb.energies)):
        if(neb.isclimbing[i]):
            coords = neb.coords[i,:]
    return pot, coords, neb.coords[0,:], neb.coords[-1,:]
예제 #3
0
def guesstsATLJ():
    from pygmin.potentials.ATLJ import ATLJ
    pot = ATLJ(Z = 2.)
    a = 1.12 #2.**(1./6.)
    theta = 60./360*np.pi
    coords1 = np.array([ 0., 0., 0., \
              -a, 0., 0., \
              -a/2, -a*np.cos(theta), 0. ])
    coords2 = np.array([ 0., 0., 0., \
              -a, 0., 0., \
              a, 0., 0. ])
    from pygmin.optimize import lbfgs_py as quench
    from pygmin.transition_states import InterpolatedPath
    ret1 = quench(coords1, pot.getEnergyGradient)
    ret2 = quench(coords2, pot.getEnergyGradient)
    coords1 = ret1[0]
    coords2 = ret2[0]
    from pygmin.transition_states import NEB
    neb = NEB(InterpolatedPath(coords1, coords2, 30), pot)
    neb.optimize()
    neb.MakeAllMaximaClimbing()
    #neb.optimize()
    for i in xrange(len(neb.energies)):
        if(neb.isclimbing[i]):
            coords = neb.coords[i,:]
    return pot, coords
def guesstsATLJ():
    from pygmin.potentials.ATLJ import ATLJ
    pot = ATLJ(Z=2.)
    a = 1.12  #2.**(1./6.)
    theta = 60. / 360 * np.pi
    coords1 = np.array([ 0., 0., 0., \
              -a, 0., 0., \
              -a/2, -a*np.cos(theta), 0. ])
    coords2 = np.array([ 0., 0., 0., \
              -a, 0., 0., \
              a, 0., 0. ])
    from pygmin.optimize import lbfgs_py as quench
    from pygmin.transition_states import InterpolatedPath
    ret1 = quench(coords1, pot.getEnergyGradient)
    ret2 = quench(coords2, pot.getEnergyGradient)
    coords1 = ret1[0]
    coords2 = ret2[0]
    from pygmin.transition_states import NEB
    neb = NEB(InterpolatedPath(coords1, coords2, 30), pot)
    neb.optimize()
    neb.MakeAllMaximaClimbing()
    #neb.optimize()
    for i in xrange(len(neb.energies)):
        if (neb.isclimbing[i]):
            coords = neb.coords[i, :]
    return pot, coords
def guessts(coords1, coords2, pot):
    from pygmin.optimize import lbfgs_py as quench
    #    from pygmin.mindist.minpermdist_stochastic import minPermDistStochastic as mindist
    from pygmin.transition_states import NEB
    from pygmin.systems import LJCluster
    ret1 = quench(coords1, pot.getEnergyGradient)
    ret2 = quench(coords2, pot.getEnergyGradient)
    coords1 = ret1[0]
    coords2 = ret2[0]
    natoms = len(coords1) / 3
    system = LJCluster(natoms)
    mindist = system.get_mindist()
    dist, coords1, coords2 = mindist(coords1, coords2)
    print "dist", dist
    print "energy coords1", pot.getEnergy(coords1)
    print "energy coords2", pot.getEnergy(coords2)
    from pygmin.transition_states import InterpolatedPath
    neb = NEB(InterpolatedPath(coords1, coords2, 20), pot)
    #neb.optimize(quenchParams={"iprint" : 1})
    neb.optimize(iprint=-30, nsteps=100)
    neb.MakeAllMaximaClimbing()
    #neb.optimize(quenchParams={"iprint": 30, "nsteps":100})
    for i in xrange(len(neb.energies)):
        if (neb.isclimbing[i]):
            coords = neb.coords[i, :]
    return pot, coords, neb.coords[0, :], neb.coords[-1, :]
예제 #6
0
 def minimize(self):
     nreps = self.nrep
     nbins = self.nebins
     visitsT = (self.visits1d)
     #print "min vis", np.min(visitsT)
     self.logP = np.where( visitsT != 0, np.log( visitsT ), 0 )
     #print "minlogp", np.min(self.logP)
     self.reduced_energy = self.binenergy[np.newaxis,:] / (self.Tlist[:,np.newaxis] * self.k_B)
     
     self.whampot = WhamPotential(self.logP, self.reduced_energy)
     
     
     X = np.random.rand( nreps + nbins )
     E = self.whampot.getEnergy(X)
     #print "energy", E 
     
     #print "quenching"
     try: 
         from pygmin.optimize import mylbfgs as quench
         ret = quench(X, self.whampot, iprint=-1, maxstep=1e4)
     except ImportError:
         from pygmin.optimize import lbfgs_scipy as quench
         ret = quench(X, self.whampot)            
     #print "quench energy", ret.energy
     X = ret.coords
     
     self.logn_E = X[nreps:]
     self.w_i_final = X[:nreps]
예제 #7
0
    def minimize(self):
        #shape(visits2d) is now (nqbins, nebins, nreps)
        #we need it to be (nreps, nqbins*nebins)
        #first reorder indices
        nreps = self.nrep
        nebins = self.nebins
        nqbins = self.nqbins
        nbins = self.nebins * self.nqbins
        #visits = np.zeros([nreps, nebins, nqbins], np.integer)
        reduced_energy = np.zeros([nreps, nebins, nqbins])
#        for k in range(self.nrep):
#            for j in range(self.nqbins):
#                for i in range(self.nebins):
#                    #visits[k,i,j] = self.visits2d[i,j,k]
#                    reduced_energy[k,i,j] = self.binenergy[i] / (self.Tlist[k]*self.k_B)
        for j in range(self.nqbins):
            reduced_energy[:,:,j] = self.binenergy[np.newaxis,:] / (self.Tlist[:,np.newaxis]*self.k_B)
                    
        visits = self.visits2d
        visits = np.reshape( visits, [nreps, nbins ]) 
        reduced_energy = np.reshape( reduced_energy, [nreps, nbins])           
        self.logP = np.where( visits != 0, np.log( visits.astype(float) ), 0 )

        
        from wham_potential import WhamPotential
        whampot = WhamPotential( self.logP, reduced_energy )
        
        nvar = nbins + nreps
        X = np.random.rand(nvar)
        print "initial energy", whampot.getEnergy(X)
        try: 
            from pygmin.optimize import mylbfgs as quench
            ret = quench(X, whampot, iprint=10, maxstep = 1e4)
        except ImportError:
            from pygmin.optimize import lbfgs_scipy as quench
            ret = quench(X, whampot)            

        print "quenched energy", ret.energy
        
        global_min = False
        if global_min:
            from pygmin.basinhopping import BasinHopping
            from pygmin.takestep.displace import RandomDisplacement
            takestep = RandomDisplacement(stepsize=10.)
            takestep.useAdaptiveStep()
            takestep.adaptive_class.f = 2.
            bh = BasinHopping(X, whampot, takestep)
            bh.run(1000)
        
        
        #self.logn_Eq = zeros([nebins,nqbins], float64)
        X = ret.coords
        self.logn_Eq = X[nreps:]
        self.w_i_final = X[:nreps]
        
        self.logn_Eq = np.reshape(self.logn_Eq, [nebins, nqbins])
        self.logn_Eq = np.where( self.visits2d.sum(0) == 0, self.LOGMIN, self.logn_Eq )
예제 #8
0
def runtest(X, pot, natoms=100, iprint=-1):
    from lbfgs_py import PrintEvent
    tol = 1e-5
    maxstep = 0.005

    Xinit = np.copy(X)
    e, g = pot.getEnergyGradient(X)
    print "energy", e

    lbfgs = LBFGS(X, pot, maxstep=0.1)
    printevent = PrintEvent("debugout.xyz")
    #lbfgs.attachEvent(printevent)

    ret = lbfgs.run(10000, tol=tol, iprint=iprint)
    print "done", ret[1], ret[2], ret[3], ret[5]

    print ""
    print "now do the same with scipy lbfgs"
    from pygmin.optimize import lbfgs_scipy as quench
    ret = quench(Xinit, pot.getEnergyGradient, tol=tol)
    print ret[1], ret[2], ret[3]

    if False:
        print "now do the same with scipy bfgs"
        from pygmin.optimize import bfgs as oldbfgs
        ret = oldbfgs(Xinit, pot.getEnergyGradient, tol=tol)
        print ret[1], ret[2], ret[3]

    if False:
        print "now do the same with gradient + linesearch"
        import bfgs
        gpl = bfgs.GradientPlusLinesearch(Xinit, pot, maxstep=0.1)
        ret = gpl.run(1000, tol=1e-6)
        print ret[1], ret[2], ret[3]

    if True:
        print ""
        print "calling from wrapper function"
        from pygmin.optimize import mylbfgs as quench
        ret = quench(Xinit, pot.getEnergyGradient, tol=tol)
        print ret[1], ret[2], ret[3]

    if True:
        print ""
        print "now do the same with lbfgs_py"
        from pygmin.optimize import lbfgs_py
        ret = lbfgs_py(Xinit, pot.getEnergyGradient, tol=tol)
        print ret[1], ret[2], ret[3]

    if False:
        import pygmin.utils.pymolwrapper as pym
        pym.start()
        for n, coords in enumerate(printevent.coordslist):
            coords = coords.reshape(natoms, 3)
            pym.draw_spheres(coords, "A", n)
예제 #9
0
def test_LWOTP(nmol=5):
    from pygmin.potentials.rigid_bodies.molecule import Molecule, setupLWOTP
    from pygmin.potentials.rigid_bodies.sandbox import RBSandbox
    from pygmin.potentials.lj import LJ
    from pygmin.optimize import lbfgs_py as quench

    printlist = []

    #set up system
    otp = setupLWOTP()
    #set up a list of molecules
    mols = [otp for i in range(nmol)]
    # 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 the RBSandbox object
    mysys = RBSandbox(mols, interaction_matrix)
    nsites = mysys.nsites

    permlist = [range(nmol)]

    #define initial coords
    coords1 = randomCoords(nmol)
    printlist.append((coords1.copy(), "very first"))
    #quench X1
    ret = quench(coords1, mysys.getEnergyGradient)
    coords1 = ret[0]

    #define initial coords2
    coords2 = randomCoords(nmol)
    printlist.append((coords2.copy(), "very first"))
    #quench X2
    ret = quench(coords2, mysys.getEnergyGradient)
    coords2 = ret[0]
    coords2in = coords2.copy()

    printlist.append((coords1.copy(), "after quench"))
    printlist.append((coords2.copy(), "after quench"))

    print "******************************"
    print "testing for OTP not isomer"
    print "******************************"
    d, c1new, c2new = test(coords1, coords2, mysys, permlist)

    print "******************************"
    print "testing for OTP ISOMER"
    print "******************************"
    coords1 = coords2in.copy()
    coords2 = c2new.copy()
    #try to reverse the permutations and symmetry operations we just applied
    test(coords1, coords2, mysys, permlist)
예제 #10
0
def test_LWOTP(nmol = 5):
    from pygmin.potentials.rigid_bodies.molecule import Molecule, setupLWOTP
    from pygmin.potentials.rigid_bodies.sandbox import RBSandbox
    from pygmin.potentials.lj import LJ
    from pygmin.optimize import lbfgs_py as quench

    printlist = []
    
    #set up system
    otp = setupLWOTP()
    #set up a list of molecules
    mols = [otp for i in range(nmol)]
    # 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 the RBSandbox object
    mysys = RBSandbox(mols, interaction_matrix)
    nsites = mysys.nsites

    permlist = [range(nmol)]

    #define initial coords
    coords1 = randomCoords(nmol)
    printlist.append( (coords1.copy(), "very first"))
    #quench X1
    ret = quench( coords1, mysys.getEnergyGradient)
    coords1 = ret[0]
    
    #define initial coords2
    coords2 = randomCoords(nmol)
    printlist.append( (coords2.copy(), "very first"))
    #quench X2
    ret = quench( coords2, mysys.getEnergyGradient)
    coords2 = ret[0]
    coords2in = coords2.copy()
    
    printlist.append((coords1.copy(), "after quench"))
    printlist.append((coords2.copy(), "after quench"))

    print "******************************"
    print "testing for OTP not isomer"
    print "******************************"
    d, c1new, c2new = test(coords1, coords2, mysys, permlist)
    
    print "******************************"
    print "testing for OTP ISOMER"
    print "******************************"
    coords1 = coords2in.copy()
    coords2 = c2new.copy()
    #try to reverse the permutations and symmetry operations we just applied 
    test(coords1, coords2, mysys, permlist)
예제 #11
0
파일: _mylbfgs.py 프로젝트: js850/PyGMIN
def runtest(X, pot, natoms = 100, iprint=-1):
    from _lbfgs_py import PrintEvent
    tol = 1e-5
    maxstep = 0.005

    Xinit = np.copy(X)
    e, g = pot.getEnergyGradient(X)
    print "energy", e
    
    lbfgs = LBFGS(X, pot, maxstep = 0.1, nsteps=10000, tol=tol,
                  iprint=iprint, H0=2.)
    printevent = PrintEvent( "debugout.xyz")
    lbfgs.attachEvent(printevent)
    
    ret = lbfgs.run()
    print ret
    
    print ""
    print "now do the same with scipy lbfgs"
    from pygmin.optimize import lbfgs_scipy as quench
    ret = quench(Xinit, pot, tol = tol)
    print ret
    #print ret[1], ret[2], ret[3]    
    
    if False:
        print "now do the same with scipy bfgs"
        from pygmin.optimize import bfgs as oldbfgs
        ret = oldbfgs(Xinit, pot, tol = tol)
        print ret
    
    if False:
        print "now do the same with gradient + linesearch"
        import _bfgs
        gpl = _bfgs.GradientPlusLinesearch(Xinit, pot, maxstep = 0.1)  
        ret = gpl.run(1000, tol = 1e-6)
        print ret
            
    if False:
        print "calling from wrapper function"
        from pygmin.optimize import lbfgs_py
        ret = lbfgs_py(Xinit, pot, tol = tol)
        print ret
        
    if True:
        print ""
        print "now do the same with lbfgs_py"
        from pygmin.optimize import lbfgs_py
        ret = lbfgs_py(Xinit, pot, tol = tol)
        print ret



    try:
        import pygmin.utils.pymolwrapper as pym
        pym.start()
        for n, coords in enumerate(printevent.coordslist):
            coords=coords.reshape(natoms, 3)
            pym.draw_spheres(coords, "A", n)
    except ImportError:
        print "error loading pymol"
예제 #12
0
    def setUp(self):
        from pygmin.potentials.rigid_bodies.molecule import Molecule, setupLWOTP
        from pygmin.potentials.rigid_bodies.sandbox import RBSandbox
        from pygmin.potentials.lj import LJ
        from pygmin.optimize import lbfgs_py as quench

        #set up system
        nmol = 5
        self.nmol = nmol
        otp = setupLWOTP()
        #set up a list of molecules
        mols = [otp for i in range(nmol)]
        # 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 the RBSandbox object
        mysys = RBSandbox(mols, interaction_matrix)
        self.pot = mysys
        self.nsites = mysys.nsites

        self.permlist = [range(nmol)]

        self.coords1 = testmindist.randomCoordsAA(nmol)
        ret = quench(self.coords1, self.pot.getEnergyGradient)
        self.coords1 = ret[0]
예제 #13
0
 def setUp(self):
     from pygmin.potentials.rigid_bodies.molecule import Molecule, setupLWOTP
     from pygmin.potentials.rigid_bodies.sandbox import RBSandbox
     from pygmin.potentials.lj import LJ
     from pygmin.optimize import lbfgs_py as quench
     
     #set up system
     nmol = 5
     self.nmol = nmol
     otp = setupLWOTP()
     #set up a list of molecules
     mols = [otp for i in range(nmol)]
     # 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 the RBSandbox object
     mysys = RBSandbox(mols, interaction_matrix)
     self.pot = mysys
     self.nsites = mysys.nsites
 
     self.permlist = [range(nmol)]
     
     self.coords1 = testmindist.randomCoordsAA(nmol)
     ret = quench(self.coords1, self.pot.getEnergyGradient)
     self.coords1 = ret[0]
예제 #14
0
파일: lj.py 프로젝트: wwwtyro/PyGMIN
def main():
    #test class
    natoms = 12
    coords = np.random.uniform(-1,1,natoms*3)*2
    
    lj = LJ()
    E = lj.getEnergy(coords)
    print "E", E 
    E, V = lj.getEnergyGradient(coords)
    print "E", E 
    print "V"
    print V

    print "try a quench"
    from pygmin.optimize import mylbfgs as quench
    quench( coords, lj.getEnergyGradient, iprint=1 )
예제 #15
0
파일: ATLJ.py 프로젝트: wwwtyro/PyGMIN
def main():
    # test class
    natoms = 3
    coords = np.random.uniform(-1, 1, natoms * 3) * 2

    lj = ATLJ(Z=1.0)

    E = lj.getEnergy(coords)
    print "E", E
    E, V = lj.getEnergyGradient(coords)
    print "E", E
    print "V"
    print V

    print "try a quench"
    from pygmin.optimize import mylbfgs as quench

    ret = quench(coords, lj.getEnergyGradient, iprint=-1)
    # quench( coords, lj.getEnergyGradientNumerical, iprint=1 )
    print "energy ", ret[1]
    print "rms gradient", ret[2]
    print "number of function calls", ret[3]

    from pygmin.printing.print_atoms_xyz import printAtomsXYZ as printxyz

    coords = ret[0]

    printlist = []
    for i in range(100):
        coords = np.random.uniform(-1, 1, natoms * 3) * 2
        # coords = np.array([0,0,1., 0,0,0, 0,0,2])
        # coords[6:] += np.random.uniform(-1,1,3)*0.1
        ret = quench(coords, lj.getEnergyGradient, iprint=-1)
        coords = ret[0]
        X = np.reshape(coords, [natoms, 3])
        com = X.sum(0) / natoms
        X[:, :] -= com[np.newaxis, :]
        printlist.append(np.reshape(X, natoms * 3))

    with open("out.xyz", "w") as fout:
        for coords in printlist:
            printxyz(fout, coords)
예제 #16
0
    def testOPT(self):
        from pygmin.optimize import lbfgs_py as quench
        coords1 = np.copy(self.coords1)
        coords1i = np.copy(coords1)
        
        coords2 = testmindist.randomCoordsAA(self.nmol)
        ret = quench(coords2, self.pot.getEnergyGradient)
        coords2 = ret[0]
        coords2i = np.copy(coords2)

        self.runtest( coords1, coords2)
예제 #17
0
    def testOPT(self):
        from pygmin.optimize import lbfgs_py as quench
        coords1 = np.copy(self.coords1)
        coords1i = np.copy(coords1)

        coords2 = testmindist.randomCoordsAA(self.nmol)
        ret = quench(coords2, self.pot.getEnergyGradient)
        coords2 = ret[0]
        coords2i = np.copy(coords2)

        self.runtest(coords1, coords2)
예제 #18
0
def main():
    #test class
    natoms = 3
    coords = np.random.uniform(-1, 1, natoms * 3) * 2

    lj = ATLJ(Z=1.)

    E = lj.getEnergy(coords)
    print "E", E
    E, V = lj.getEnergyGradient(coords)
    print "E", E
    print "V"
    print V

    print "try a quench"
    from pygmin.optimize import mylbfgs as quench
    ret = quench(coords, lj, iprint=-1)
    #quench( coords, lj.getEnergyGradientNumerical, iprint=1 )
    print "energy ", ret.energy
    print "rms gradient", ret.rms
    print "number of function calls", ret.nfev

    from pygmin.printing.print_atoms_xyz import printAtomsXYZ as printxyz
    coords = ret.coords

    printlist = []
    for i in range(100):
        coords = np.random.uniform(-1, 1, natoms * 3) * 2
        #coords = np.array([0,0,1., 0,0,0, 0,0,2])
        #coords[6:] += np.random.uniform(-1,1,3)*0.1
        ret = quench(coords, lj.getEnergyGradient, iprint=-1)
        coords = ret.coords
        X = np.reshape(coords, [natoms, 3])
        com = X.sum(0) / natoms
        X[:, :] -= com[np.newaxis, :]
        printlist.append(np.reshape(X, natoms * 3))

    with open("out.xyz", "w") as fout:
        for coords in printlist:
            printxyz(fout, coords)
예제 #19
0
def testpot3():
    from transition_state_refinement import guesstsLJ
    pot, coords, coords1, coords2 = guesstsLJ()
    coordsinit = np.copy(coords)

    eigpot = LowestEigPot(coords, pot)
    
    vec = np.random.rand(len(coords))
    
    from pygmin.optimize import lbfgs_py as quench
    ret = quench(vec, eigpot.getEnergyGradient, iprint=400, tol = 1e-5, maxstep = 1e-3, \
                 rel_energy = True)

    eigval = ret[1]
    eigvec = ret[0]
    print "eigenvalue ", eigval
    print "eigenvector", eigvec

    if True:
        e, g, hess = pot.getEnergyGradientHessian(coords)
        u, v = np.linalg.eig(hess)
        u = u.real
        v = v.real
        print "eigenvalues", sorted(u)
        #for i in range(len(u)):
        #    print "eigenvalue", u[i], "eigenvector", v[:,i]
        #find minimum eigenvalue, vector
        imin = 0
        umin = 10.
        for i in range(len(u)):
            if np.abs(u[i]) < 1e-10: continue
            if u[i] < umin:
                umin = u[i]
                imin = i
        #print "lowest eigenvalue ", umin, imin
        #print "lowest eigenvector", v[:,imin]
        
        
        
        trueval, truevec = u[imin], v[:,imin]
        print "analytical lowest eigenvalue", trueval
        maxdiff = np.max(np.abs(truevec - eigvec))
        print "maximum difference between estimated and analytical eigenvectors", maxdiff, \
            np.linalg.norm(eigvec), np.linalg.norm(truevec), np.dot(truevec, eigvec)
        if True:
            print eigvec
            print truevec
예제 #20
0
def testpot3():
    from transition_state_refinement import guesstsLJ
    pot, coords, coords1, coords2 = guesstsLJ()
    coordsinit = np.copy(coords)

    eigpot = LowestEigPot(coords, pot)

    vec = np.random.rand(len(coords))

    from pygmin.optimize import lbfgs_py as quench
    ret = quench(vec, eigpot.getEnergyGradient, iprint=400, tol = 1e-5, maxstep = 1e-3, \
                 rel_energy = True)

    eigval = ret[1]
    eigvec = ret[0]
    print "eigenvalue ", eigval
    print "eigenvector", eigvec

    if True:
        e, g, hess = pot.getEnergyGradientHessian(coords)
        u, v = np.linalg.eig(hess)
        u = u.real
        v = v.real
        print "eigenvalues", sorted(u)
        #for i in range(len(u)):
        #    print "eigenvalue", u[i], "eigenvector", v[:,i]
        #find minimum eigenvalue, vector
        imin = 0
        umin = 10.
        for i in range(len(u)):
            if np.abs(u[i]) < 1e-10: continue
            if u[i] < umin:
                umin = u[i]
                imin = i
        #print "lowest eigenvalue ", umin, imin
        #print "lowest eigenvector", v[:,imin]

        trueval, truevec = u[imin], v[:, imin]
        print "analytical lowest eigenvalue", trueval
        maxdiff = np.max(np.abs(truevec - eigvec))
        print "maximum difference between estimated and analytical eigenvectors", maxdiff, \
            np.linalg.norm(eigvec), np.linalg.norm(truevec), np.dot(truevec, eigvec)
        if True:
            print eigvec
            print truevec
예제 #21
0
 def globalMinimization(self):
     """
     in experimentation i've never been able to find more than
     one minimum
     """
     nreps = self.nrep
     nbins = self.nebins
     visitsT = (self.visits1d)
     #print "min vis", np.min(visitsT)
     self.logP = np.where( visitsT != 0, np.log( visitsT ), 0 )
     #print "minlogp", np.min(self.logP)
     self.reduced_energy = self.binenergy[np.newaxis,:] / (self.Tlist[:,np.newaxis] * self.k_B)
     
     self.whampot = WhamPotential(self.logP, self.reduced_energy)
     
     X = np.random.rand( nreps + nbins )
     E = self.whampot.getEnergy(X)
     print "energy", E 
     
     print "quenching"
     from pygmin.optimize import lbfgs_scipy as quench
     ret = quench(X, self.whampot)
     print "quench energy", ret.energy
     
     from pygmin.basinhopping import BasinHopping
     from pygmin.takestep.displace import RandomDisplacement
     takestep = RandomDisplacement(stepsize=10)
     takestep.useAdaptiveStep()
     takestep.adaptive_class.f = 1.5 #i have no idea what a good stepsize should be
     bh = BasinHopping(X, self.whampot, takestep )
     
     import matplotlib.pyplot as plt
     for i in range(10):
         bh.run(2000)
         self.logn_E = bh.coords[nreps:]
         cvdata = self.calc_Cv(400)
         plt.plot(cvdata[:,0], cvdata[:,5], '-')
     plt.show()
         
         
     
     X = bh.coords
     self.logn_E = X[nreps:]
     self.w_i_final = X[:nreps]
예제 #22
0
    def globalMinimization(self):
        """
        in experimentation i've never been able to find more than
        one minimum
        """
        nreps = self.nrep
        nbins = self.nebins
        visitsT = (self.visits1d)
        #print "min vis", np.min(visitsT)
        self.logP = np.where(visitsT != 0, np.log(visitsT), 0)
        #print "minlogp", np.min(self.logP)
        self.reduced_energy = self.binenergy[np.newaxis, :] / (
            self.Tlist[:, np.newaxis] * self.k_B)

        self.whampot = WhamPotential(self.logP, self.reduced_energy)

        X = np.random.rand(nreps + nbins)
        E = self.whampot.getEnergy(X)
        print "energy", E

        print "quenching"
        from pygmin.optimize import lbfgs_scipy as quench
        ret = quench(X, self.whampot)
        print "quench energy", ret.energy

        from pygmin.basinhopping import BasinHopping
        from pygmin.takestep.displace import RandomDisplacement
        takestep = RandomDisplacement(stepsize=10)
        takestep.useAdaptiveStep()
        takestep.adaptive_class.f = 1.5  #i have no idea what a good stepsize should be
        bh = BasinHopping(X, self.whampot, takestep)

        import matplotlib.pyplot as plt
        for i in range(10):
            bh.run(2000)
            self.logn_E = bh.coords[nreps:]
            cvdata = self.calc_Cv(400)
            plt.plot(cvdata[:, 0], cvdata[:, 5], '-')
        plt.show()

        X = bh.coords
        self.logn_E = X[nreps:]
        self.w_i_final = X[:nreps]
예제 #23
0
파일: _bfgs.py 프로젝트: js850/PyGMIN
def lineSearch(X, V, pot, aguess = 0.1, tol = 1e-3):
    """
    minimize the potential along the line defined by X + a * V
    
    i'm sure there's a better way to do this
    """
    tol /= np.sqrt(len(X)) #normalize the tolerance because we're reducing dimensionality
    ls = LineSearchPot(X, V, pot)
    
    einit = pot.getEnergy(X)
    #from optimize.quench import steepest_descent as quench
    from pygmin.optimize import lbfgs_scipy as quench
    a = np.zeros(1) * aguess
    ret = quench(a, ls.getEnergyGradient, tol=tol)
    a = ret[0][0]
    e = ret[1]
    funcalls = ret[3] 
    
    #print "    linesearch step size", a, e, einit, e - einit, funcalls
    return a, e, funcalls
예제 #24
0
def main():
    #test class
    natoms = 12
    coords = np.random.uniform(-1,1,natoms*3)*2
    
    lj = LJ()
    E = lj.getEnergy(coords)
    print "E", E 
    E, V = lj.getEnergyGradient(coords)
    print "E", E 
    print "V"
    print V

    print "try a quench"
    from pygmin.optimize import mylbfgs as quench
    ret = quench( coords, lj, iprint=-1 )
    #quench( coords, lj.getEnergyGradientNumerical, iprint=1 )
    print "energy ", ret.energy
    print "rms gradient", ret.rms
    print "number of function calls", ret.nfev
예제 #25
0
파일: lj_simple.py 프로젝트: wwwtyro/PyGMIN
def main():
    #test class
    natoms = 12
    coords = np.random.uniform(-1,1,natoms*3)*2
    
    lj = LJ()
    E = lj.getEnergy(coords)
    print "E", E 
    E, V = lj.getEnergyGradient(coords)
    print "E", E 
    print "V"
    print V

    print "try a quench"
    from pygmin.optimize import mylbfgs as quench
    ret = quench( coords, lj.getEnergyGradient, iprint=-1 )
    #quench( coords, lj.getEnergyGradientNumerical, iprint=1 )
    print "energy ", ret[1]
    print "rms gradient", ret[2]
    print "number of function calls", ret[3]
예제 #26
0
파일: ATLJ.py 프로젝트: js850/PyGMIN
    def testenergy(self):
        natoms = 10
        coords = np.random.uniform(-1,1,natoms*3)*2
        
        from pygmin.optimize import mylbfgs as quench
        lj = LJ()
        ret = quench(coords, lj)
        coords = ret.coords
        
        
        atlj = ATLJ(Z=3.)
        e2 = atlj.getEnergySlow(coords)
#        e1 = atlj.getEnergyWeave(coords)
#        #print "%g - %g = %g" % (e1, e2, e1-e2)
#        self.assertTrue( abs(e1 - e2) < 1e-12, "ATLJ: two energy methods give different results: %g - %g = %g" % (e1, e2, e1-e2) )

        
        e1 = atlj.getEnergyFortran(coords)
        #print "%g - %g = %g" % (e1, e2, e1-e2)
        #print e1/e2
        self.assertTrue( abs(e1 - e2) < 1e-12, "ATLJ: fortran energy gives different results: %g - %g = %g" % (e1, e2, e1-e2) )
예제 #27
0
def lineSearch(X, V, pot, aguess=0.1, tol=1e-3):
    """
    minimize the potential along the line defined by X + a * V
    
    i'm sure there's a better way to do this
    """
    tol /= np.sqrt(
        len(X))  #normalize the tolerance because we're reducing dimensionality
    ls = LineSearchPot(X, V, pot)

    einit = pot.getEnergy(X)
    #from optimize.quench import steepest_descent as quench
    from pygmin.optimize import lbfgs_scipy as quench
    a = np.zeros(1) * aguess
    ret = quench(a, ls.getEnergyGradient, tol=tol)
    a = ret[0][0]
    e = ret[1]
    funcalls = ret[3]

    #print "    linesearch step size", a, e, einit, e - einit, funcalls
    return a, e, funcalls
예제 #28
0
파일: _bfgs.py 프로젝트: js850/PyGMIN
def test():
    natoms = 100
    tol = 1e-6
    
    from pygmin.potentials.lj import LJ
    pot = LJ()
    
    X = getInitialCoords(natoms, pot)
    X += np.random.uniform(-1,1,[3*natoms]) * 0.3
    
    #do some steepest descent steps so we don't start with a crazy structure
    #from optimize.quench import _steepest_descent as steepestDescent
    #ret = steepestDescent(X, pot.getEnergyGradient, iprint = 1, dx = 1e-4, nsteps = 100, gtol = 1e-3, maxstep = .5)
    #X = ret[0]
    #print X

    
    Xinit = np.copy(X)
    e, g = pot.getEnergyGradient(X)
    print "energy", e
    
    lbfgs = BFGS(X, pot, maxstep = 0.1)
    
    ret = lbfgs.run(100, tol = tol, iprint=1)
    print "done", ret[1], ret[2], ret[3]
    
    print "now do the same with scipy lbfgs"
    from pygmin.optimize import lbfgs_scipy as quench
    ret = quench(Xinit, pot.getEnergyGradient, tol = tol)
    print ret[1], ret[2], ret[3]    
    
    print "now do the same with scipy bfgs"
    from pygmin.optimize import bfgs as oldbfgs
    ret = oldbfgs(Xinit, pot.getEnergyGradient, tol = tol)
    print ret[1], ret[2], ret[3]    
    
    print "now do the same with old gradient + linesearch"
    gpl = GradientPlusLinesearch(Xinit, pot, maxstep = 0.1)  
    ret = gpl.run(100, tol = 1e-6)
    print ret[1], ret[2], ret[3]    
예제 #29
0
def test():
    natoms = 100
    tol = 1e-6

    from pygmin.potentials.lj import LJ
    pot = LJ()

    X = getInitialCoords(natoms, pot)
    X += np.random.uniform(-1, 1, [3 * natoms]) * 0.3

    #do some steepest descent steps so we don't start with a crazy structure
    #from optimize.quench import _steepest_descent as steepestDescent
    #ret = steepestDescent(X, pot.getEnergyGradient, iprint = 1, dx = 1e-4, nsteps = 100, gtol = 1e-3, maxstep = .5)
    #X = ret[0]
    #print X

    Xinit = np.copy(X)
    e, g = pot.getEnergyGradient(X)
    print "energy", e

    lbfgs = BFGS(X, pot, maxstep=0.1)

    ret = lbfgs.run(100, tol=tol, iprint=1)
    print "done", ret[1], ret[2], ret[3]

    print "now do the same with scipy lbfgs"
    from pygmin.optimize import lbfgs_scipy as quench
    ret = quench(Xinit, pot.getEnergyGradient, tol=tol)
    print ret[1], ret[2], ret[3]

    print "now do the same with scipy bfgs"
    from pygmin.optimize import bfgs as oldbfgs
    ret = oldbfgs(Xinit, pot.getEnergyGradient, tol=tol)
    print ret[1], ret[2], ret[3]

    print "now do the same with old gradient + linesearch"
    gpl = GradientPlusLinesearch(Xinit, pot, maxstep=0.1)
    ret = gpl.run(100, tol=1e-6)
    print ret[1], ret[2], ret[3]
예제 #30
0
    def testenergy(self):
        natoms = 10
        coords = np.random.uniform(-1, 1, natoms * 3) * 2

        from pygmin.optimize import mylbfgs as quench
        lj = LJ()
        ret = quench(coords, lj)
        coords = ret.coords

        atlj = ATLJ(Z=3.)
        e2 = atlj.getEnergySlow(coords)
        #        e1 = atlj.getEnergyWeave(coords)
        #        #print "%g - %g = %g" % (e1, e2, e1-e2)
        #        self.assertTrue( abs(e1 - e2) < 1e-12, "ATLJ: two energy methods give different results: %g - %g = %g" % (e1, e2, e1-e2) )

        e1 = atlj.getEnergyFortran(coords)
        #print "%g - %g = %g" % (e1, e2, e1-e2)
        #print e1/e2
        self.assertTrue(
            abs(e1 - e2) < 1e-12,
            "ATLJ: fortran energy gives different results: %g - %g = %g" %
            (e1, e2, e1 - e2))
예제 #31
0
def test_soft_sphere(natoms = 9):
    rho = 1.6
    boxl = 1.
    meandiam = boxl / (float(natoms)/rho)**(1./3)
    print "mean diameter", meandiam 
    
    #set up potential
    diams = np.array([meandiam for i in range(natoms)]) #make them all the same
    pot = SoftSphere(diams = diams)

    #initial coordinates
    coords = np.random.uniform(-1,1,[natoms*3]) * (natoms)**(1./3)
    print len(coords)
    E = pot.getEnergy(coords)
    print "initial energy", E 

    printlist = []
    printlist.append((coords.copy(), "intial coords"))
    
    #test a quench with default lbfgs
    from pygmin.optimize import lbfgs_scipy as quench
    coords, E, rms, funcalls = quench(coords, pot.getEnergyGradient, iprint=-1)
    printlist.append((coords.copy(), "intial coords"))
    print "energy post quench", pot.getEnergy(coords)

    fname = "out.xyz"
    print "saving coordinates to", fname
    from pygmin.printing.print_atoms_xyz import printAtomsXYZ as printxyz
    with open(fname, "w") as fout:
        for xyz,line2 in printlist:
            xyz = putInBox(xyz, boxl)
            printxyz(fout, xyz, line2=line2) 
            
    
    from scipy.optimize import check_grad
    res = check_grad(pot.getEnergy, pot.getGradient, coords)
    print "testing gradient (should be small)", res
예제 #32
0
def test_soft_sphere(natoms=9):
    rho = 1.6
    boxl = 1.
    meandiam = boxl / (float(natoms) / rho)**(1. / 3)
    print "mean diameter", meandiam

    #set up potential
    diams = np.array([meandiam
                      for i in range(natoms)])  #make them all the same
    pot = SoftSphere(diams=diams)

    #initial coordinates
    coords = np.random.uniform(-1, 1, [natoms * 3]) * (natoms)**(1. / 3)
    print len(coords)
    E = pot.getEnergy(coords)
    print "initial energy", E

    printlist = []
    printlist.append((coords.copy(), "intial coords"))

    #test a quench with default lbfgs
    from pygmin.optimize import mylbfgs as quench
    res = quench(coords, pot, iprint=-1)
    printlist.append((res.coords.copy(), "intial coords"))
    print "energy post quench", pot.getEnergy(coords)

    fname = "out.xyz"
    print "saving coordinates to", fname
    from pygmin.printing.print_atoms_xyz import printAtomsXYZ as printxyz
    with open(fname, "w") as fout:
        for xyz, line2 in printlist:
            xyz = putInBox(xyz, boxl)
            printxyz(fout, xyz, line2=line2)

    from scipy.optimize import check_grad
    res = check_grad(pot.getEnergy, pot.getGradient, coords)
    print "testing gradient (should be small)", res
예제 #33
0
def testpot1():
    from pygmin.potentials.lj import LJ
    import itertools
    pot = LJ()
    a = 1.12  #2.**(1./6.)
    theta = 60. / 360 * np.pi
    coords = [ 0., 0., 0., \
              -a, 0., 0., \
              -a/2, a*np.cos(theta), 0., \
              -a/2, -a*np.cos(theta), 0.1 \
              ]
    natoms = len(coords) / 3
    c = np.reshape(coords, [-1, 3])
    for i, j in itertools.combinations(range(natoms), 2):
        r = np.linalg.norm(c[i, :] - c[j, :])
        print i, j, r

    e, g = pot.getEnergyGradient(coords)
    print "initial E", e
    print "initial G", g, np.linalg.norm(g)

    eigpot = LowestEigPot(coords, pot)
    vec = np.random.rand(len(coords))
    e, g = eigpot.getEnergyGradient(vec)
    print "eigenvalue", e
    print "eigenvector", g

    if True:
        e, g, hess = pot.getEnergyGradientHessian(coords)
        print "shape hess", np.shape(hess)
        print "hessian", hess
        u, v = np.linalg.eig(hess)
        print "max imag value", np.max(np.abs(u.imag))
        print "max imag vector", np.max(np.abs(v.imag))
        u = u.real
        v = v.real
        print "eigenvalues", u
        for i in range(len(u)):
            print "eigenvalue", u[i], "eigenvector", v[:, i]
        #find minimum eigenvalue, vector
        imin = 0
        umin = 10.
        for i in range(len(u)):
            if np.abs(u[i]) < 1e-10: continue
            if u[i] < umin:
                umin = u[i]
                imin = i
        print "lowest eigenvalue ", umin, imin
        print "lowest eigenvector", v[:, imin]

    from pygmin.optimize import lbfgs_py as quench
    ret = quench(vec, eigpot.getEnergyGradient, iprint=10, tol = 1e-5, maxstep = 1e-3, \
                 rel_energy = True)
    print ret

    print "lowest eigenvalue "
    print umin, imin
    print "lowest eigenvector"
    print v[:, imin]
    print "now the estimate"
    print ret[1]
    print ret[0]
예제 #34
0
coords = np.random.uniform(-1,1,[natoms*3]) * (natoms)**(1./3)
E = pot.getEnergy(coords)
print "initial energy", E 


#set up quench routine
#from optimize.quench import fire as quench
#from optimize.quench import cg as quench
from pygmin.optimize import lbfgs_scipy as quench #numpy lbfgs routine
#from optimize.quench import fmin as quench
#from optimize.quench import steepest_descent as quench



#start from quenched coordinates
ret = quench(coords, pot.getEnergyGradient)
coords = ret[0]
        


#set up functions to pass to basin hopping

#set up the step taking routine
#Normal basin hopping takes each step from the quenched coords.  This modified step taking routine takes a step from the 
#last accepted coords, not from the quenched coords
from pygmin.take_step.random_displacement import takeStep
takestep = takeStep(stepsize=.01)


#pass a function which rejects the step if the system leaved the inital basin.
import do_quenching
예제 #35
0

# initial coordinates
coords = np.random.uniform(-1, 1, [natoms * 3]) * (natoms) ** (1.0 / 3)
E = pot.getEnergy(coords)
print "initial energy", E

printlist = []  # list of coordinates saved for printing
printlist.append((coords.copy(), "intial coords"))


# test a quench with default lbfgs
# from optimize.quench import quench
from pygmin.optimize import lbfgs_ase as quench

coords, E, rms, funcalls = quench(coords, pot.getEnergyGradient, iprint=1)
printlist.append((coords.copy(), "intial coords"))
print "energy post quench", pot.getEnergy(coords)


from scipy.optimize import check_grad

res = check_grad(pot.getEnergy, pot.getGradient, coords)
print "testing gradient (should be small)", res


fname = "out.xyz"
print "saving coordinates to", fname
from pygmin.printing.print_atoms_xyz import printAtomsXYZ as printxyz

with open(fname, "w") as fout:
예제 #36
0
    for i in range(nimages - 1):
        xyz1 = neb.coords[i, :]
        xyz2 = neb.coords[i + 1, :]
        dist = np.linalg.norm(xyz1 - xyz2)
        E = getEnergy(xyz1)
        fout.write(str(S) + " " + str(E) + "\n")
        S += dist
    xyz = neb.coords[-1, :]
    E = getEnergy(xyz)
    fout.write(str(S) + " " + str(E) + "\n")


lj = LJ()
natoms = 17
X1 = np.random.uniform(-1, 1, [natoms * 3]) * (float(natoms))**(1. / 3)
ret = quench(X1, lj.getEnergyGradient)
X1 = ret[0]
X2 = np.random.uniform(-1, 1, [natoms * 3]) * (float(natoms))**(1. / 3)
ret = quench(X2, lj.getEnergyGradient)
X2 = ret[0]

dist, X1, X2 = minpermdist(X1, X2, niter=100)
distf = np.linalg.norm(X1 - X2)
print "dist returned        ", dist
print "dist from structures ", distf

#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)
예제 #37
0
파일: LJ_MC.py 프로젝트: js850/PyGMIN
        if self.count % self.printfrq == 0: 
            self.center(coords)
            printxyz(self.fout, coords, line2=str(E))
        self.count += 1

#def center(E, coords, accepted):
 #   c = np.reshape()

natoms = 40

coords = np.random.rand(natoms*3)


lj = LJ() 

ret = quench(coords, lj)
coords = ret.coords

takestep = TakeStep(stepsize=0.1 )

#do equilibration steps, adjusting stepsize
tsadapt = AdaptiveStepsize(takestep)
mc = MonteCarlo(coords, lj, tsadapt, temperature = 0.5)
equilout = open("equilibration","w")
#mc.outstream = equilout
mc.setPrinting(equilout, 1)
mc.run(10000)

#fix stepsize and do production run
mc.takeStep = takestep
mcout = open("mc.out", "w")
예제 #38
0
파일: LJ_MC.py 프로젝트: wwwtyro/PyGMIN
        if self.count % self.printfrq == 0: 
            self.center(coords)
            printxyz(self.fout, coords, line2=str(E))
        self.count += 1

#def center(E, coords, accepted):
 #   c = np.reshape()

natoms = 40

coords = np.random.rand(natoms*3)


lj = LJ() 

ret = quench(coords, lj.getEnergyGradient)
coords = ret[0]

takestep = TakeStep(stepsize=0.1 )

#do equilibration steps, adjusting stepsize
tsadapt = AdaptiveStepsize(takestep)
mc = MonteCarlo(coords, lj, tsadapt, temperature = 0.5)
equilout = open("equilibration","w")
#mc.outstream = equilout
mc.setPrinting(equilout, 1)
mc.run(10000)

#fix stepsize and do production run
mc.takeStep = takestep
mcout = open("mc.out", "w")
예제 #39
0
파일: run_ptmc.py 프로젝트: wwwtyro/PyGMIN
def runptmc(nsteps_tot = 100000):
    natoms = 31
    nreplicas = 4
    Tmin = 0.2
    Tmax = 0.4
    
    nsteps_equil = 10000
    nsteps_tot   = 100000
    histiprint  =  nsteps_tot / 10
    exchange_frq = 100*nreplicas
    
    coords=np.random.random(3*natoms)
    #quench the coords so we start from a reasonable location
    mypot = lj.LJ()
    ret = quench(coords, mypot.getEnergyGradient)
    coords = ret[0]
    
    
    Tlist = getTemps(Tmin, Tmax, nreplicas)
    replicas = []
    ostreams = []
    histograms = []
    takesteplist = []
    radius = 2.5
    for i in range(nreplicas):
        T = Tlist[i]
        potential = lj.LJ()
        
        takestep = RandomDisplacement( stepsize=0.01)
        adaptive = AdaptiveStepsize(takestep, last_step = nsteps_equil)
        takesteplist.append( adaptive )
        
        file = "mcout." + str(i+1)
        ostream = open(file, "w")
        
        hist = EnergyHistogram( -134., 10., 1000)
        histograms.append(hist)
        event_after_step=[hist]
        
        radiustest = SphericalContainer(radius)
        accept_tests = [radiustest]
        
        mc = MonteCarlo(coords, potential, takeStep=takestep, temperature=T, \
                        outstream=ostream, event_after_step = event_after_step, \
                        confCheck = accept_tests)
        mc.histogram = hist #for convienence
        mc.printfrq = 1
        replicas.append(mc)
    
    
    #is it possible to pickle a mc object?
    #cp = copy.deepcopy(replicas[0])
    #import pickle
    #with open("mc.pickle", "w") as fout:
        #pickle.dump(takesteplist[0], fout)
    
    
    
    #attach an event to print xyz coords
    from pygmin.printing.print_atoms_xyz import PrintEvent
    printxyzlist = []
    for n, rep in enumerate(replicas):
        outf = "dumpstruct.%d.xyz" % (n+1) 
        printxyz = PrintEvent(outf, frq=500)
        printxyzlist.append( printxyz)
        rep.addEventAfterStep(printxyz)
        
    
    #attach an event to print histograms
    for n, rep in enumerate(replicas):
        outf = "hist.%d" % (n+1)
        histprint = PrintHistogram(outf, rep.histogram, histiprint)
        rep.addEventAfterStep(histprint)
    
    
    ptmc = PTMC(replicas)
    ptmc.use_independent_exchange = True
    ptmc.exchange_frq = exchange_frq
    ptmc.run(nsteps_tot)
    
    
    
    #do production run
    #fix the step sizes
    #for takestep in takesteplist:
    #    takestep.useFixedStep()
    #ptmc.run(30000)
    
    
    if False: #this doesn't work
        print "final energies"
        for rep in ptmc.replicas:
            print rep.temperature, rep.markovE
        for rep in ptmc.replicas_par:
            print rep.mcsys.markovE
        for k in range(nreplicas):
            e,T = ptmc.getRepEnergyT(k)
            print T, e
    
    if False: #this doesn't work
        print "histograms"
        for i,hist in enumerate(histograms):
            fname = "hist." + str(i)
            print fname
            with open(fname, "w") as fout:
                for (e, visits) in hist:
                    fout.write( "%g %d\n" % (e, visits) )
    
    ptmc.end() #close the open threads
예제 #40
0
파일: bljrun.py 프로젝트: js850/PyGMIN
        S += dist
    xyz = neb.coords[-1, :]
    E = getEnergy(xyz)
    fout.write(str(S) + " " + str(E) + "\n")


from potentials.ljpshift import LJpshift

natoms = 17
ntypea = int(natoms * 0.8)
lj = LJpshift(natoms, ntypea)
permlist = [range(ntypea), range(ntypea, natoms)]


X1 = np.random.uniform(-1, 1, [natoms * 3]) * (float(natoms)) ** (1.0 / 3) * 0.8
ret = quench(X1, lj.getEnergyGradient)
X1 = ret[0]
X2 = np.random.uniform(-1, 1, [natoms * 3]) * (float(natoms)) ** (1.0 / 3) * 0.8
ret = quench(X2, lj.getEnergyGradient)
X2 = ret[0]

dist, X1, X2 = minpermdist(X1, X2, niter=100, permlist=permlist)
distf = np.linalg.norm(X1 - X2)
print "dist returned        ", dist
print "dist from structures ", distf
print "energies ", lj.getEnergy(X1), lj.getEnergy(X2)
print X2

# 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
예제 #41
0
#pot = SoftSphere(diams = diams)
pot = SoftSphere()

#initial coordinates
coords = np.random.uniform(-1, 1, [natoms * 3]) * (natoms)**(1. / 3)
E = pot.getEnergy(coords)
print "initial energy", E

printlist = []  #list of coordinates saved for printing
printlist.append((coords.copy(), "intial coords"))

#test a quench with default lbfgs
#from optimize.quench import quench
from pygmin.optimize import lbfgs_ase as quench

coords, E, rms, funcalls = quench(coords, pot.getEnergyGradient, iprint=1)
printlist.append((coords.copy(), "intial coords"))
print "energy post quench", pot.getEnergy(coords)

from scipy.optimize import check_grad

res = check_grad(pot.getEnergy, pot.getGradient, coords)
print "testing gradient (should be small)", res

fname = "out.xyz"
print "saving coordinates to", fname
from pygmin.printing.print_atoms_xyz import printAtomsXYZ as printxyz
with open(fname, "w") as fout:
    for xyz, line2 in printlist:
        #xyz = putInBox(xyz, boxl)
        printxyz(fout, xyz, line2=line2)
예제 #42
0
def testpot1():
    from pygmin.potentials.lj import LJ
    import itertools
    pot = LJ()
    a = 1.12 #2.**(1./6.)
    theta = 60./360*np.pi
    coords = [ 0., 0., 0., \
              -a, 0., 0., \
              -a/2, a*np.cos(theta), 0., \
              -a/2, -a*np.cos(theta), 0.1 \
              ]
    natoms = len(coords)/3
    c = np.reshape(coords, [-1,3])
    for i, j in itertools.combinations(range(natoms), 2):
        r = np.linalg.norm(c[i,:] - c[j,:])
        print i, j, r 
    
    e, g = pot.getEnergyGradient(coords)
    print "initial E", e
    print "initial G", g, np.linalg.norm(g)

    eigpot = LowestEigPot(coords, pot)
    vec = np.random.rand(len(coords))
    e, g = eigpot.getEnergyGradient(vec)
    print "eigenvalue", e 
    print "eigenvector", g
    
    if True:
        e, g, hess = pot.getEnergyGradientHessian(coords)
        print "shape hess", np.shape(hess)
        print "hessian", hess
        u, v = np.linalg.eig(hess)
        print "max imag value", np.max(np.abs(u.imag))
        print "max imag vector", np.max(np.abs(v.imag))
        u = u.real
        v = v.real
        print "eigenvalues", u
        for i in range(len(u)):
            print "eigenvalue", u[i], "eigenvector", v[:,i]
        #find minimum eigenvalue, vector
        imin = 0
        umin = 10.
        for i in range(len(u)):
            if np.abs(u[i]) < 1e-10: continue
            if u[i] < umin:
                umin = u[i]
                imin = i
        print "lowest eigenvalue ", umin, imin
        print "lowest eigenvector", v[:,imin]

    
    from pygmin.optimize import lbfgs_py as quench
    ret = quench(vec, eigpot.getEnergyGradient, iprint=10, tol = 1e-5, maxstep = 1e-3, \
                 rel_energy = True)
    print ret
    
    print "lowest eigenvalue "
    print umin, imin
    print "lowest eigenvector"
    print v[:,imin]
    print "now the estimate"
    print ret[1]
    print ret[0]
예제 #43
0
        if self.count % self.printfrq == 0:
            self.center(coords)
            printxyz(self.fout, coords, line2=str(E))
        self.count += 1


#def center(E, coords, accepted):
#   c = np.reshape()

natoms = 40

coords = np.random.rand(natoms * 3)

lj = LJ()

ret = quench(coords, lj)
coords = ret.coords

takestep = TakeStep(stepsize=0.1)

#do equilibration steps, adjusting stepsize
tsadapt = AdaptiveStepsize(takestep)
mc = MonteCarlo(coords, lj, tsadapt, temperature=0.5)
equilout = open("equilibration", "w")
#mc.outstream = equilout
mc.setPrinting(equilout, 1)
mc.run(10000)

#fix stepsize and do production run
mc.takeStep = takestep
mcout = open("mc.out", "w")
예제 #44
0
파일: run_ptmc.py 프로젝트: yfyh2013/PyGMIN
def runptmc(nsteps_tot=100000):
    natoms = 31
    nreplicas = 4
    Tmin = 0.2
    Tmax = 0.4

    nsteps_equil = 10000
    nsteps_tot = 100000
    histiprint = nsteps_tot / 10
    exchange_frq = 100 * nreplicas

    coords = np.random.random(3 * natoms)
    #quench the coords so we start from a reasonable location
    mypot = lj.LJ()
    ret = quench(coords, mypot)
    coords = ret.coords

    Tlist = getTemps(Tmin, Tmax, nreplicas)
    replicas = []
    ostreams = []
    histograms = []
    takesteplist = []
    radius = 2.5
    # create all the replicas which will be passed to PTMC
    for i in range(nreplicas):
        T = Tlist[i]
        potential = lj.LJ()

        takestep = RandomDisplacement(stepsize=0.01)
        adaptive = AdaptiveStepsize(takestep, last_step=nsteps_equil)
        takesteplist.append(adaptive)

        file = "mcout." + str(i + 1)
        ostream = open(file, "w")

        hist = EnergyHistogram(-134., 10., 1000)
        histograms.append(hist)
        event_after_step = [hist]

        radiustest = SphericalContainer(radius)
        accept_tests = [radiustest]

        mc = MonteCarlo(coords, potential, takeStep=takestep, temperature=T, \
                        outstream=ostream, event_after_step = event_after_step, \
                        confCheck = accept_tests)
        mc.histogram = hist  #for convienence
        mc.printfrq = 1
        replicas.append(mc)

    #is it possible to pickle a mc object?
    #cp = copy.deepcopy(replicas[0])
    #import pickle
    #with open("mc.pickle", "w") as fout:
    #pickle.dump(takesteplist[0], fout)

    #attach an event to print xyz coords
    from pygmin.printing.print_atoms_xyz import PrintEvent
    printxyzlist = []
    for n, rep in enumerate(replicas):
        outf = "dumpstruct.%d.xyz" % (n + 1)
        printxyz = PrintEvent(outf, frq=500)
        printxyzlist.append(printxyz)
        rep.addEventAfterStep(printxyz)

    #attach an event to print histograms
    for n, rep in enumerate(replicas):
        outf = "hist.%d" % (n + 1)
        histprint = PrintHistogram(outf, rep.histogram, histiprint)
        rep.addEventAfterStep(histprint)

    ptmc = PTMC(replicas)
    ptmc.use_independent_exchange = True
    ptmc.exchange_frq = exchange_frq
    ptmc.run(nsteps_tot)

    #do production run
    #fix the step sizes
    #for takestep in takesteplist:
    #    takestep.useFixedStep()
    #ptmc.run(30000)

    if False:  #this doesn't work
        print "final energies"
        for rep in ptmc.replicas:
            print rep.temperature, rep.markovE
        for rep in ptmc.replicas_par:
            print rep.mcsys.markovE
        for k in range(nreplicas):
            e, T = ptmc.getRepEnergyT(k)
            print T, e

    if False:  #this doesn't work
        print "histograms"
        for i, hist in enumerate(histograms):
            fname = "hist." + str(i)
            print fname
            with open(fname, "w") as fout:
                for (e, visits) in hist:
                    fout.write("%g %d\n" % (e, visits))

    ptmc.end()  #close the open threads