def guessts(coords1, coords2, pot): from pele.optimize import lbfgs_py as quench # from pele.mindist.minpermdist_stochastic import minPermDistStochastic as mindist from pele.transition_states import NEB from pele.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 pele.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,:]
def guesstsATLJ(): from pele.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 pele.optimize import lbfgs_py as quench from pele.transition_states import InterpolatedPath ret1 = quench(coords1, pot.getEnergyGradient) ret2 = quench(coords2, pot.getEnergyGradient) coords1 = ret1[0] coords2 = ret2[0] from pele.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 test_LWOTP(nmol=5): from pele.potentials.rigid_bodies.molecule import Molecule, setupLWOTP from pele.potentials.rigid_bodies.sandbox import RBSandbox from pele.potentials.lj import LJ from pele.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)
def main(): # pragma: no cover #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 pele.optimize import mylbfgs as quench quench( coords, lj, iprint=1 )
def setUp(self): from pele.potentials.rigid_bodies.molecule import Molecule, setupLWOTP from pele.potentials.rigid_bodies.sandbox import RBSandbox from pele.potentials.lj import LJ from pele.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]
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 pele.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 pele.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 pele.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 pele.optimize import lbfgs_py ret = lbfgs_py(Xinit, pot, tol = tol) print ret try: import pele.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"
def main(): # pragma: no cover # 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 pele.optimize import mylbfgs as quench quench(coords, lj, iprint=1)
def get_minimizer(self, nsteps=1e6, M=4, iprint=0, maxstep=1.0, **kwargs): from pele.optimize import lbfgs_cpp as quench return lambda coords: quench(coords, self.get_potential(), tol=self.minimizer_tolerance, nsteps=nsteps, M=M, iprint=iprint, maxstep=maxstep, **kwargs)
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 pele.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 pele.utils.xyz import write_xyz 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: write_xyz(fout, coords)
def testOPT(self): from pele.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)
def testing(): # pragma: no cover # 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 pele.optimize import mylbfgs as quench ret = quench(coords, lj, iprint=-1) print("energy ", ret.energy) print("rms gradient", ret.rms) print("number of function calls", ret.nfev) from pele.utils.xyz import write_xyz printlist = [] for i in range(100): coords = np.random.uniform(-1, 1, natoms * 3) * 2 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: write_xyz(fout, coords)
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 pele.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
def minimize(self): """compute the best estimate for the density of states""" nreps = self.nrep nbins = self.nebins visitsT = (self.visits1d) #print "min vis", np.min(visitsT) #print "minlogp", np.min(self.logP) self.reduced_energy = self.binenergy[np.newaxis, :] / ( self.Tlist[:, np.newaxis] * self.k_B) self.whampot = WhamPotential(visitsT, self.reduced_energy) if False: X = np.random.rand(nreps + nbins) else: # estimate an initial guess for the offsets and density of states # so the minimizer converges more rapidly offsets_estimate, log_dos_estimate = wham_utils.estimate_dos( self.visits1d, self.reduced_energy) X = np.concatenate((offsets_estimate, log_dos_estimate)) E0, grad = self.whampot.getEnergyGradient(X) rms0 = np.linalg.norm(grad) / np.sqrt(grad.size) try: from pele.optimize import lbfgs_cpp as quench if self.verbose: print "minimizing with pele lbfgs" ret = quench(X, self.whampot, tol=1e-3, maxstep=1e4, nsteps=10000) except ImportError: from wham_utils import lbfgs_scipy if self.verbose: print "minimizing with scipy lbfgs" ret = lbfgs_scipy(X, self.whampot, tol=1e-3, nsteps=10000) #print "quench energy", ret.energy if self.verbose: print "chi^2 went from %g (rms %g) to %g (rms %g) in %d iterations" % ( E0, rms0, ret.energy, ret.rms, ret.nfev) X = ret.coords self.logn_E = X[nreps:] self.w_i_final = X[:nreps]
def minimize(self): """compute the best estimate for the density of states""" nreps = self.nrep nbins = self.nebins visitsT = (self.visits1d) #print "min vis", np.min(visitsT) #print "minlogp", np.min(self.logP) self.reduced_energy = self.binenergy[np.newaxis,:] / (self.Tlist[:,np.newaxis] * self.k_B) self.whampot = WhamPotential(visitsT, self.reduced_energy) if False: X = np.random.rand( nreps + nbins ) else: # estimate an initial guess for the offsets and density of states # so the minimizer converges more rapidly offsets_estimate, log_dos_estimate = wham_utils.estimate_dos(self.visits1d, self.reduced_energy) X = np.concatenate((offsets_estimate, log_dos_estimate)) E0, grad = self.whampot.getEnergyGradient(X) rms0 = np.linalg.norm(grad) / np.sqrt(grad.size) try: from pele.optimize import lbfgs_cpp as quench if self.verbose: print "minimizing with pele lbfgs" ret = quench(X, self.whampot, tol=1e-3, maxstep=1e4, nsteps=10000) except ImportError: from wham_utils import lbfgs_scipy if self.verbose: print "minimizing with scipy lbfgs" ret = lbfgs_scipy(X, self.whampot, tol=1e-3, nsteps=10000) #print "quench energy", ret.energy if self.verbose: print "chi^2 went from %g (rms %g) to %g (rms %g) in %d iterations" % ( E0, rms0, ret.energy, ret.rms, ret.nfev) X = ret.coords self.logn_E = X[nreps:] self.w_i_final = X[:nreps]
def main(): # pragma: no cover #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 pele.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
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 pele.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
def main(): # pragma: no cover # 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 pele.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)
def testenergy(self): natoms = 10 coords = np.random.uniform(-1,1,natoms*3)*2 from pele.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) )
def test(): natoms = 100 tol = 1e-6 from pele.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 pele.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 pele.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]
def testenergy(self): natoms = 10 coords = np.random.uniform(-1, 1, natoms * 3) * 2 from pele.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))
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 pele.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 pele.utils.xyz import write_xyz with open(fname, "w") as fout: for xyz, line2 in printlist: xyz = putInBox(xyz, boxl) write_xyz(fout, xyz, title=line2) from scipy.optimize import check_grad res = check_grad(pot.getEnergy, pot.getGradient, coords) print "testing gradient (should be small)", res
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 pele.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 pele.utils.xyz import write_xyz with open(fname, "w") as fout: for xyz,line2 in printlist: xyz = putInBox(xyz, boxl) write_xyz(fout, xyz, title=line2) from scipy.optimize import check_grad res = check_grad(pot.getEnergy, pot.getGradient, coords) print "testing gradient (should be small)", res
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 pele.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 pele.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
def minimize(pot, coords0): from pele.optimize import lbfgs_cpp as quench return quench(coords0, pot, iprint=1, tol=1.0e-3, nsteps=100)
if self.count % self.printfrq == 0: self.center(coords) write_xyz(self.fout, coords, title=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")
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)
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 pele.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
def get_minimizer(self, **kwargs): from pele.optimize import lbfgs_cpp as quench return lambda coords: quench(coords, self.get_potential(),tol=0.00001,**kwargs)
def myMinimizer(coords,pot,**kwargs): from pele.optimize import lbfgs_cpp as quench #print coords return quench(coords,pot,**kwargs)
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 pele.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
def myMinimizer(coords, pot, **kwargs): from pele.optimize import lbfgs_cpp as quench #print coords return quench(coords, pot, **kwargs)
#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 pele.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 pele.utils.xyz import write_xyz
def testpot1(): from pele.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 pele.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]