def load_coords_pymol(self, coordslist, oname, index=1): # pragma: no cover """load the coords into pymol the new object must be named oname so we can manipulate it later Parameters ---------- coordslist : list of arrays oname : str the new pymol object must be named oname so it can be manipulated later index : int we can have more than one molecule on the screen at one time. index tells which one to draw. They are viewed at the same time, so should be visually distinct, e.g. different colors. accepted values are 1 or 2 Notes ----- the implementation here is a bit hacky. we create a temporary xyz file from coords and load the molecule in pymol from this file. """ # pymol is imported here so you can do, e.g. basinhopping without installing pymol import pymol # create the temporary file suffix = ".xyz" f = tempfile.NamedTemporaryFile(mode="w", suffix=suffix) fname = f.name # write the coords into the xyz file from pele.mindist import CoMToOrigin for coords in coordslist: coords = CoMToOrigin(coords.copy()) write_xyz(f, coords, title=oname, atomtypes=["LA"]) f.flush() # load the molecule from the temporary file pymol.cmd.load(fname) # get name of the object just create and change it to oname objects = pymol.cmd.get_object_list() objectname = objects[-1] pymol.cmd.set_name(objectname, oname) # set the representation pymol.cmd.hide("everything", oname) pymol.cmd.show("spheres", oname) # set the color according to index if index == 1: pymol.cmd.color("red", oname) else: pymol.cmd.color("gray", oname)
def load_coords_pymol(self, coordslist, oname, index=1): # pragma: no cover """load the coords into pymol the new object must be named oname so we can manipulate it later Parameters ---------- coordslist : list of arrays oname : str the new pymol object must be named oname so it can be manipulated later index : int we can have more than one molecule on the screen at one time. index tells which one to draw. They are viewed at the same time, so should be visually distinct, e.g. different colors. accepted values are 1 or 2 Notes ----- the implementation here is a bit hacky. we create a temporary xyz file from coords and load the molecule in pymol from this file. """ # pymol is imported here so you can do, e.g. basinhopping without installing pymol from . import pymol # create the temporary file suffix = ".xyz" f = tempfile.NamedTemporaryFile(mode="w", suffix=suffix) fname = f.name # write the coords into the xyz file from pele.mindist import CoMToOrigin for coords in coordslist: coords = CoMToOrigin(coords.copy()) write_xyz(f, coords, title=oname, atomtypes=["LA"]) f.flush() # load the molecule from the temporary file pymol.cmd.load(fname) # get name of the object just create and change it to oname objects = pymol.cmd.get_object_list() objectname = objects[-1] pymol.cmd.set_name(objectname, oname) # set the representation pymol.cmd.hide("everything", oname) pymol.cmd.show("spheres", oname) # set the color according to index if index == 1: pymol.cmd.color("red", oname) else: pymol.cmd.color("gray", oname)
def load_coords_pymol(self, coordslist, oname, index=1): """load the coords into pymol the new object must be named oname so we can manipulate it later Parameters ---------- coordslist : list of arrays oname : str the new pymol object must be named oname so it can be manipulated later index : int we can have more than one molecule on the screen at one time. index tells which one to draw. They are viewed at the same time, so they should be visually distinct, e.g. different colors. accepted values are 1 or 2 Notes ----- the implementation here is a bit hacky. we create a temporary xyz file from coords and load the molecule in pymol from this file. """ # pymol is imported here so you can do, e.g. basinhopping without installing pymol import pymol # create the temporary file (.xyz or .pdb, or whatever else pymol can read) # note: this is the part that will be really system dependent. f = tempfile.NamedTemporaryFile(mode="w", suffix=".xyz") fname = f.name # write the coords into file for coords in coordslist: write_xyz(f, coords, title=oname) f.flush() # load the molecule from the temporary file pymol.cmd.load(fname) # get name of the object just create and change it to oname objects = pymol.cmd.get_object_list() objectname = objects[-1] pymol.cmd.set_name(objectname, oname) # here you might want to change the representation of the molecule, e.g. # >>> pymol.cmd.hide("everything", oname) # >>> pymol.cmd.show("spheres", oname) # set the color according to index if index == 1: pymol.cmd.color("red", oname) else: pymol.cmd.color("gray", oname)
def _compute_energy_in_SA(self, replica): """compute the energy of the coordinates in replica.coords in the harmonic superposition approximation This is where most of the difficulty is in the algorithm. This is also where all the system dependence is """ # quench to nearest minimum qresult = self.minimizer(replica.x) # check if that minimum is in the database. reject if not m, transformation = self.minima_searcher.get_minima( qresult.energy, qresult.coords) if m is None: return None # put replica.coords into best alignment with the structure stored in m.coords # this involves accounting for symmetries of the Hamiltonian like translational, # rotational and permutations symmetries. You can use the coordinates in qresult.coords # to help find the best permutation. Ultimately it must be aligned with the structure in m.coords # The hessian eigenvectors were computed with a given permutation # e.g. account for trivial translational and rotational degrees of freedom x = replica.x.copy() if transformation is not None: # transformation is the set of transformations that put qresult.coords into exact # alignment with m.coords. If we apply these transformations to replica.x then # replica.x will be in good (although not perfect) alignment already with m.coords x = self.compare_structures.apply_transformation(x, transformation) # Do a final round of optimization to further improve the alignment if self.mindist is not None: dist, x0, x = self.mindist(m.coords.copy(), x) if self.debug: diff = np.linalg.norm(x0 - m.coords) if diff > .01: with open("error.xyz", "w") as fout: from pele.utils.xyz import write_xyz write_xyz(fout, x0) write_xyz(fout, m.coords) raise Exception( "warning, mindist appears to have changed x0. the norm of the difference is %g" % diff) assert (x0 == m.coords).all() energy = self.sa_sampler.compute_energy(x, m) return energy
def water(xyzfile): # TIP4P-16.xyz" ref = xyz.read_xyz(open(xyzfile)) xyz.write_xyz(open("test.xyz", "w"), coords=ref.coords) # lookup table for atom masses mass_lookup = {'O': 16., 'H': 1.} rb_sites = [] for atomtype, x, i in zip(ref.atomtypes, ref.coords, xrange(len(ref.atomtypes))): # every 3rd atom, define a new reigid molecule if i % 3 == 0: rb = rigidbody.RigidFragment() rb_sites.append(rb) rb.add_atom(atomtype, x, mass_lookup[atomtype]) # finalize the rigid body setup for rb in rb_sites: rb.finalize_setup() return rb_sites, ref
def _compute_energy_in_SA(self, replica): """compute the energy of the coordinates in replica.coords in the harmonic superposition approximation This is where most of the difficulty is in the algorithm. This is also where all the system dependence is """ # quench to nearest minimum qresult = self.minimizer(replica.x) # check if that minimum is in the database. reject if not m, transformation = self.minima_searcher.get_minima(qresult.energy, qresult.coords) if m is None: return None # put replica.coords into best alignment with the structure stored in m.coords # this involves accounting for symmetries of the Hamiltonian like translational, # rotational and permutations symmetries. You can use the coordinates in qresult.coords # to help find the best permutation. Ultimately it must be aligned with the structure in m.coords # The hessian eigenvectors were computed with a given permutation # e.g. account for trivial translational and rotational degrees of freedom x = replica.x.copy() if transformation is not None: # transformation is the set of transformations that put qresult.coords into exact # alignment with m.coords. If we apply these transformations to replica.x then # replica.x will be in good (although not perfect) alignment already with m.coords x = self.compare_structures.apply_transformation(x, transformation) # Do a final round of optimization to further improve the alignment if self.mindist is not None: dist, x0, x = self.mindist(m.coords.copy(), x) if self.debug: diff = np.linalg.norm(x0 - m.coords) if diff > .01: with open("error.xyz", "w") as fout: from pele.utils.xyz import write_xyz write_xyz(fout, x0) write_xyz(fout, m.coords) raise Exception("warning, mindist appears to have changed x0. the norm of the difference is %g" % diff) assert (x0 == m.coords).all() energy = self.sa_sampler.compute_energy(x, m) return energy
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 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 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 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 printpath(fout, coordslist): nimages = len(coordslist[:,0]) for i in range(nimages): write_xyz(fout, coordslist[i,:])
def printwrapper(self, E, coords, accepted): if self.count % self.printfrq == 0: self.center(coords) write_xyz(self.fout, coords, title=str(E)) self.count += 1
def printpath(fout, coordslist, atomtypes = ["LA"]): nimages = len(coordslist[:,0]) for i in range(nimages): write_xyz(fout, coordslist[i,:], atom_type=atomtypes)
def load_coords_pymol(self, coordslist, oname, index=1): """load the coords into pymol the new object must be named oname so we can manipulate it later Parameters ---------- coordslist : list of arrays oname : str the new pymol object must be named oname so it can be manipulated later index : int we can have more than one molecule on the screen at one time. index tells which one to draw. They are viewed at the same time, so should be visually distinct, e.g. different colors. accepted values are 1 or 2 Notes ----- the implementation here is a bit hacky. we create a temporary xyz file from coords and load the molecule in pymol from this file. """ # pymol is imported here so you can do, e.g. basinhopping without installing pymol import pymol # create the temporary file suffix = ".xyz" f = tempfile.NamedTemporaryFile(mode="w", suffix=suffix) fname = f.name # write the atomistic coords into the xyz file from pele.mindist import CoMToOrigin for coords in coordslist: if hasattr(self, "atom_types"): atom_types = self.atom_types else: atom_types = ["O"] atom_coords = self.aasystem.to_atomistic(coords) write_xyz(f, atom_coords, title=oname, atomtypes=atom_types) f.flush() # load the molecule from the temporary file into pymol pymol.cmd.load(fname) # get name of the object just create and change it to oname objects = pymol.cmd.get_object_list() objectname = objects[-1] pymol.cmd.set_name(objectname, oname) # set the representation as spheres pymol.cmd.hide("everything", oname) pymol.cmd.show("spheres", oname) # draw the bonds if hasattr(self, "draw_bonds"): pymol.cmd.unbond(oname, oname) for i1, i2 in self.draw_bonds: pymol.cmd.bond("id %d and %s" % (i1+1, oname), "id %d and %s" % (i2+1, oname)) pymol.cmd.show("lines", oname) # set the color of index 2 so they appear different if index == 2: pymol.cmd.color("gray", oname)
com = np.array([ 0.,0.,0., 1.,0.,0., 0.,1.,0. ]) aacoords = np.array([ 1.,0.,0., 0.,1.,0., 0.,0.,1.,] ) coords = np.zeros( 3*2*nmol, np.float64) coords[0:3*nmol] = com[:] coords[3*nmol:] = aacoords[:] printlist = [] printlist.append( coords.copy() ) grad, E = sandbox.getenergygradient(coords, [2*nmol]) print E, grad sandbox.takestep(coords, False, True, s, os, myas,[natoms]) printlist.append( coords.copy() ) sandbox.takestep(coords, True, False, s, os, myas,[natoms]) printlist.append( coords.copy() ) from pele.utils.xyz import write_xyz with open("out.xyz", "w") as fout: for x in printlist: write_xyz(fout, x)
def testpot1(): import itertools pot, coords, coords1, coords2 = guesstsLJ() coordsinit = np.copy(coords) 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) print "" from pele.utils.xyz import write_xyz #print ret with open("out.xyz", "w") as fout: e = pot.getEnergy(coords1) print "energy of minima 1", e write_xyz(fout, coords1, title=str(e)) e, grad = pot.getEnergyGradient(coordsinit) print "energy of NEB guess for the transition state", e, "rms grad", \ np.linalg.norm(grad) / np.sqrt(float(len(coords))/3.) write_xyz(fout, coordsinit, title=str(e)) e = pot.getEnergy(coords2) print "energy of minima 2", e write_xyz(fout, coords2, title=str(e)) #mess up coords a bit coords += np.random.uniform(-1,1,len(coords))*0.05 e = pot.getEnergy(coords) write_xyz(fout, coords, title=str(e)) printevent = PrintEvent(fout) print "" print "starting the transition state search" ret = findTransitionState(coords, pot, iprint=-1) print ret #coords, eval, evec, e, grad, rms = ret e = pot.getEnergy(ret.coords) write_xyz(fout, coords2, title=str(e)) print "finished searching for transition state" print "energy", e print "rms grad", ret.rms print "eigenvalue", ret.eigenval if False: print "now try the same search with the dimer method" from pele.NEB.dimer import findTransitionState as dimerfindTS coords = coordsinit.copy() tau = np.random.uniform(-1,1,len(coords)) tau /= np.linalg.norm(tau) ret = dimerfindTS(coords, pot, tau ) enew, grad = pot.getEnergyGradient(ret.coords) print "energy", enew print "rms grad", np.linalg.norm(grad) / np.sqrt(float(len(ret.coords))/3.)
coords[k : k + 3] = rot.random_aa() #set up the takestep routine from pele.potentials.rigid_bodies.take_step import RBTakeStep takestep = RBTakeStep() #set up the class to save lowest energy structures from pele.storage.savenlowest import SaveN saveit = SaveN(100) #set up basinhopping from pele.basinhopping import BasinHopping bh = BasinHopping(coords, mysys, takestep, storage=saveit.insert ) #run basin hopping bh.run(40) #print the saved coords fname = "otp.xyz" print "saving xyz coords to", fname from pele.utils.xyz import write_xyz with open(fname, "w") as fout: for minimum in saveit.data: xyz = mysys.getxyz(minimum.coords) write_xyz( fout, xyz, atomtypes=["N", "O", "O"])
Example 3: Saving all minima found to an xyz file """ from pele.systems import LJCluster from pele.utils.xyz import write_xyz natoms = 12 niter = 100 system = LJCluster(natoms) db = system.create_database() bh = system.get_basinhopping(database=db) bh.run(niter) with open("lowest", "w") as fout: for minimum in db.minima(): title = "energy = ", str(minimum.energy) write_xyz(fout, minimum.coords, title) ############################################################ # some visualization ############################################################ try: import pele.utils.pymolwrapper as pym pym.start() frame=1 for minimum in db.minima(): pym.draw_spheres(minimum.coords.reshape(-1, 3), "A", frame) frame=frame+1 except: print "Could not draw using pymol, skipping this step"
mints, S, energies = myconnect.returnPath() nmin = (len(mints)-1)/2 + 1 nts = nmin-1 print "the path has %d minima and %d transition states" % (nmin, nts) eofs = "path.EofS" print "saving energies to", eofs with open(eofs, "w") as fout: for i in range(len(S)): fout.write("%f %f\n" % (S[i], energies[i])) xyzfile = "path.xyz" print "saving path in xyz format to", xyzfile with open(xyzfile, "w") as fout: for m in mints: write_xyz(fout, m.coords, title=str(m.energy)) xyzfile = "path.smooth.xyz" print "saving smoothed path in xyz format to", xyzfile clist = [m.coords for m in mints] smoothed = smoothPath(clist, mindist) with open(xyzfile, "w") as fout: for coords in smoothed: write_xyz(fout, coords) if False: try: import matplotlib.pyplot as plt plt.plot(S, energies) plt.show()
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 with open(fname, "w") as fout: for xyz,line2 in printlist: #xyz = putInBox(xyz, boxl) write_xyz(fout, xyz, title=line2)
import numpy as np from copy import deepcopy from pele.angleaxis import RBTopology, RBSystem # For rigid fragment import numpy as np from pele.potentials import LJ from pele.utils import xyz from pele.angleaxis import rigidbody from pele.optimize import lbfgs_py # read in coordinates from xyz file ref = xyz.read_xyz(open("TIP4P-16.xyz")) xyz.write_xyz(open("test.xyz", "w"), coords=ref.coords) # lookup table for atom masses mass_lookup = {'O': 16., 'H': 1.} def water(xyzfile): # TIP4P-16.xyz" ref = xyz.read_xyz(open(xyzfile)) xyz.write_xyz(open("test.xyz", "w"), coords=ref.coords) # lookup table for atom masses mass_lookup = {'O': 16., 'H': 1.} rb_sites = [] for atomtype, x, i in zip(ref.atomtypes, ref.coords, xrange(len(ref.atomtypes))): # every 3rd atom, define a new reigid molecule if i % 3 == 0: rb = rigidbody.RigidFragment() rb_sites.append(rb) rb.add_atom(atomtype, x, mass_lookup[atomtype]) # finalize the rigid body setup for rb in rb_sites:
import ambgmin_ as GMIN import pele.potentials.gminpotential as gminpot import numpy as np import pele.basinhopping as bh from pele.optimize import _quench as quench from pele.takestep import displace # export PYTHONPATH=/home/ss2029/svn/GMIN/bin:$PWD/../.. GMIN.initialize() pot = gminpot.GMINPotental(GMIN) coords = pot.getCoords() step = displace.RandomDisplacement(stepsize=0.7) opt = bh.BasinHopping(coords, pot, takeStep=step, quench=quench.lbfgs_py) opt.quenchParameters['tol'] = 1e-4 opt.run(3) # some visualization try: import pele.utils.pymolwrapper as pym pym.start() pym.draw_spheres(opt.coords, "A", 1) except: print "Could not draw using pymol, skipping this step" from pele.utils.xyz import write_xyz write_xyz(open("final.xyz", "w"), opt.coords)
def load_coords_pymol(self, coordslist, oname, index=1): # pragma: no cover """load the coords into pymol the new object must be named oname so we can manipulate it later Parameters ---------- coordslist : list of arrays oname : str the new pymol object must be named oname so it can be manipulated later index : int we can have more than one molecule on the screen at one time. index tells which one to draw. They are viewed at the same time, so should be visually distinct, e.g. different colors. accepted values are 1 or 2 Notes ----- the implementation here is a bit hacky. we create a temporary xyz file from coords and load the molecule in pymol from this file. """ # pymol is imported here so you can do, e.g. basinhopping without installing pymol import pymol # create the temporary file suffix = ".xyz" f = tempfile.NamedTemporaryFile(mode="w", suffix=suffix) fname = f.name # write the atomistic coords into the xyz file for coords in coordslist: if hasattr(self, "atom_types"): atom_types = self.atom_types else: atom_types = ["O"] atom_coords = self.aasystem.to_atomistic(coords) write_xyz(f, atom_coords, title=oname, atomtypes=atom_types) f.flush() # load the molecule from the temporary file into pymol pymol.cmd.load(fname) # get name of the object just create and change it to oname objects = pymol.cmd.get_object_list() objectname = objects[-1] pymol.cmd.set_name(objectname, oname) # set the representation as spheres pymol.cmd.hide("everything", oname) pymol.cmd.show("spheres", oname) # draw the bonds if hasattr(self, "draw_bonds"): pymol.cmd.unbond(oname, oname) for i1, i2 in self.draw_bonds: pymol.cmd.bond("id %d and %s" % (i1 + 1, oname), "id %d and %s" % (i2 + 1, oname)) pymol.cmd.show("lines", oname) # set the color of index 2 so they appear different if index == 2: pymol.cmd.color("gray", oname)
In the above we used three imports. We used the `numpy` library to construct a random one dimensional array. We used the Lennard-Jones potential :class:`.LJ`, and we used the minimization routine :func:`.lbfgs_py` which is just a wrapper for the class :class:`.LBFGS`. The return value is an optimization result, which is just a container (:class:`.Result`) that stores the final energy, final coordinates, the number of function calls, etc. If we want to then save the minimized coordinates in an xyz file we can use the function :func:`.write_xyz` :: from pele.utils.xyz import write_xyz with open("out.xyz", "w") as fout: title = "energy = " + str(result.energy) write_xyz(fout, result.coords, title=title) """ import numpy as np from pele.potentials import LJ from pele.optimize import lbfgs_py natoms = 5 x = np.random.uniform(-2, 2, natoms * 3) pot = LJ() result = lbfgs_py(x, pot) print result from pele.utils.xyz import write_xyz with open("out.xyz", "w") as fout: title = "energy = " + str(result.energy) write_xyz(fout, result.coords, title=title)
print "" mints, S, energies = myconnect.returnPath() nmin = (len(mints) - 1) / 2 + 1 nts = nmin - 1 print "the path has %d minima and %d transition states" % (nmin, nts) eofs = "path.EofS" print "saving energies to", eofs with open(eofs, "w") as fout: for i in range(len(S)): fout.write("%f %f\n" % (S[i], energies[i])) xyzfile = "path.xyz" print "saving path in xyz format to", xyzfile with open(xyzfile, "w") as fout: for m in mints: write_xyz(fout, m.coords, title=str(m.energy)) xyzfile = "path.smooth.xyz" print "saving smoothed path in xyz format to", xyzfile clist = [m.coords for m in mints] smoothed = smoothPath(clist, mindist) with open(xyzfile, "w") as fout: for coords in smoothed: write_xyz(fout, coords) if False: try: import matplotlib.pyplot as plt plt.plot(S, energies) plt.show()
import ambgmin_ as GMIN import pele.potentials.gminpotential as gminpot import numpy as np import pele.basinhopping as bh from pele.optimize import _quench as quench from pele.takestep import displace # export PYTHONPATH=/home/ss2029/svn/GMIN/bin:$PWD/../.. GMIN.initialize() pot = gminpot.GMINPotental(GMIN) coords = pot.getCoords() step = displace.RandomDisplacement(stepsize=0.7) opt = bh.BasinHopping(coords, pot, takeStep=step, quenchRoutine=quench.lbfgs_py) opt.quenchParameters['tol'] = 1e-4 opt.run(3) # some visualization try: import pele.utils.pymolwrapper as pym pym.start() pym.draw_spheres(opt.coords, "A", 1) except: print "Could not draw using pymol, skipping this step" from pele.utils.xyz import write_xyz write_xyz(open("final.xyz", "w"), opt.coords)
from __future__ import print_function from builtins import str from pele.systems import LJCluster from pele.utils.xyz import write_xyz natoms = 12 niter = 100 system = LJCluster(natoms) db = system.create_database() bh = system.get_basinhopping(database=db) bh.run(niter) with open("lowest", "w") as fout: for minimum in db.minima(): title = "energy = ", str(minimum.energy) write_xyz(fout, minimum.coords, title) ############################################################ # some visualization ############################################################ try: import pele.utils.pymolwrapper as pym pym.start() frame = 1 for minimum in db.minima(): pym.draw_spheres(minimum.coords.reshape(-1, 3), "A", frame) frame += 1 except: print("Could not draw using pymol, skipping this step")
from __future__ import print_function from builtins import zip from builtins import range import numpy as np from pele.potentials import LJ from pele.utils import xyz from pele.angleaxis import rigidbody from pele.optimize import lbfgs_py # read in coordinates from xyz file ref = xyz.read_xyz(open("water.xyz")) xyz.write_xyz(open("test.xyz", "w"), coords=ref.coords) # lookup table for atom masses mass_lookup = {'O': 16., 'H': 1.} #ref.coords[:] *= 3 # now define a new rigid body system rb_sites = [] for atomtype, x, i in zip(ref.atomtypes, ref.coords, range(len(ref.atomtypes))): # every 3rd atom, define a new reigid molecule if i % 3 == 0: rb = rigidbody.RigidFragment() rb_sites.append(rb) rb.add_atom(atomtype, x, mass_lookup[atomtype]) # finalize the rigid body setup for rb in rb_sites: rb.finalize_setup()
In the above we used three imports. We used the `numpy` library to construct a random one dimensional array. We used the Lennard-Jones potential :class:`.LJ`, and we used the minimization routine :func:`.lbfgs_py` which is just a wrapper for the class :class:`.LBFGS`. The return value is an optimization result, which is just a container (:class:`.Result`) that stores the final energy, final coordinates, the number of function calls, etc. If we want to then save the minimized coordinates in an xyz file we can use the function :func:`.write_xyz` :: from pele.utils.xyz import write_xyz with open("out.xyz", "w") as fout: title = "energy = " + str(result.energy) write_xyz(fout, result.coords, title=title) """ import numpy as np from pele.potentials import LJ from pele.optimize import lbfgs_py natoms = 5 x = np.random.uniform(-2, 2, natoms*3) pot = LJ() result = lbfgs_py(x, pot) print result from pele.utils.xyz import write_xyz with open("out.xyz", "w") as fout: title = "energy = " + str(result.energy) write_xyz(fout, result.coords, title=title)
import numpy as np from src.runmc import mc_cython from lj_run import LJClusterNew, MonteCarloCompiled from nested_sampling import MonteCarloChain from pele.takestep import RandomDisplacement from pele.utils.xyz import write_xyz system = LJClusterNew(31) x = system.get_random_configuration() with open("test.xyz", "w") as fout: write_xyz(fout, x) mciter = 100000 stepsize = .01 Emax = 1e20 radius = 2.5 mcc = MonteCarloCompiled(system, radius) mcc(x.copy(), mciter, stepsize, Emax) print mcc.naccept, mcc.nsteps, mcc.energy takestep = RandomDisplacement(stepsize=stepsize) mc = MonteCarloChain(system.get_potential(), x.copy(), takestep, Emax, system.get_config_tests()) for i in xrange(mciter): mc.step() print mc.naccept, mc.nsteps, mc.energy
import numpy as np from pele.potentials import LJ from pele.utils import xyz from pele.angleaxis import rigidbody from pele.optimize import lbfgs_py # read in coordinates from xyz file ref = xyz.read_xyz(open("water.xyz")) xyz.write_xyz(open("test.xyz", "w"), coords = ref.coords) # lookup table for atom masses mass_lookup = {'O': 16., 'H': 1.} #ref.coords[:] *= 3 # now define a new rigid body system rb_sites = [] for atomtype, x, i in zip(ref.atomtypes, ref.coords, xrange(len(ref.atomtypes))): # every 3rd atom, define a new reigid molecule if i%3 == 0: rb = rigidbody.RigidFragment() rb_sites.append(rb) rb.add_atom(atomtype, x, mass_lookup[atomtype]) # finalize the rigid body setup for rb in rb_sites: rb.finalize_setup() # define a new rigid body system rbsystem = rigidbody.RBSystem() rbsystem.add_sites(rb_sites)
def load_coords_pymol(self, coordslist, oname, index=1): """load the coords into pymol the new object must be named oname so we can manipulate it later Parameters ---------- coordslist : list of arrays oname : str the new pymol object must be named oname so it can be manipulated later index : int we can have more than one molecule on the screen at one time. index tells which one to draw. They are viewed at the same time, so should be visually distinct, e.g. different colors. accepted values are 1 or 2 Notes ----- the implementation here is a bit hacky. we create a temporary xyz file from coords and load the molecule in pymol from this file. """ #pymol is imported here so you can do, e.g. basinhopping without installing pymol import pymol #create the temporary file suffix = ".xyz" f = tempfile.NamedTemporaryFile(mode="w", suffix=suffix) fname = f.name #write the coords into the xyz file from pele.mindist import CoMToOrigin labels = ["LA" for i in range(self.ntypeA)] + \ ["LB" for i in range(self.natoms - self.ntypeA)] for coords in coordslist: coords = CoMToOrigin(coords.copy()) write_xyz(f, coords, title=oname, atomtypes=labels) f.flush() # self.f = f # so the file is not deleted # print fname #load the molecule from the temporary file pymol.cmd.load(fname) #get name of the object just create and change it to oname objects = pymol.cmd.get_object_list() objectname = objects[-1] pymol.cmd.set_name(objectname, oname) #set the representation pymol.cmd.hide("everything", oname) pymol.cmd.show("spheres", oname) #make the B atoms smaller seleA = "%s and name LA" % (oname) seleB = "%s and name LB" % (oname) pymol.cmd.set("sphere_scale", value=1.0, selection=seleA) pymol.cmd.set("sphere_scale", value=0.8, selection=seleB) #set the color according to index if index == 1: pymol.cmd.color("red", selection=seleA) pymol.cmd.color("firebrick", selection=seleB) else: pymol.cmd.color("deepolive", selection=seleA) pymol.cmd.color("smudge", selection=seleB)
def __call__(self, coords, **kwargs): from pele.utils.xyz import write_xyz write_xyz(self.fout, coords) self.coordslist.append( coords.copy() )