From 778f4d338c784d4697c1ca70ac1622d02d204b43 Mon Sep 17 00:00:00 2001 From: sjplimp Date: Fri, 22 Jul 2016 22:57:54 +0000 Subject: [PATCH] git-svn-id: svn://svn.icms.temple.edu/lammps-ro/trunk@15358 f3b2605a-c512-4ea7-a41b-209d697bcdaa --- python/.gitignore | 1 + python/examples/demo.py | 22 +- python/examples/gui.py | 10 +- python/examples/mc.py | 19 +- python/examples/pizza/dump.py | 232 ++++++------- python/examples/pizza/gl.py | 31 +- python/examples/pizza/gnu.py | 19 +- python/examples/pizza/pdbfile.py | 33 +- python/examples/pizza/vmd.py | 19 +- python/examples/plot.py | 5 +- python/examples/simple.py | 9 +- python/examples/split.py | 13 +- python/examples/trivial.py | 3 +- python/examples/viz_atomeye.py | 5 +- python/examples/viz_gl.py | 11 +- python/examples/viz_pymol.py | 5 +- python/examples/viz_vmd.py | 7 +- python/examples/vizplotgui_atomeye.py | 10 +- python/examples/vizplotgui_gl.py | 15 +- python/examples/vizplotgui_pymol.py | 10 +- python/examples/vizplotgui_vmd.py | 10 +- python/lammps.py | 451 ++++++++++++++++++++++++-- 22 files changed, 694 insertions(+), 246 deletions(-) diff --git a/python/.gitignore b/python/.gitignore index 27ffc2f17f..e069c0ec3b 100644 --- a/python/.gitignore +++ b/python/.gitignore @@ -1,2 +1,3 @@ *.pyc +__pycache__ build diff --git a/python/examples/demo.py b/python/examples/demo.py index fb212d0e12..958ebcd04b 100755 --- a/python/examples/demo.py +++ b/python/examples/demo.py @@ -6,13 +6,14 @@ # Syntax: demo.py # uses in.demo as LAMMPS input script +from __future__ import print_function import sys # parse command line argv = sys.argv if len(argv) != 1: - print "Syntax: demo.py" + print("Syntax: demo.py") sys.exit() from lammps import lammps @@ -22,29 +23,32 @@ lmp = lammps() lmp.file("in.demo") -print "\nPython output:" +print("\nPython output:") natoms = lmp.extract_global("natoms",0) mass = lmp.extract_atom("mass",2) x = lmp.extract_atom("x",3) -print "Natoms, mass, x[0][0] coord =",natoms,mass[1],x[0][0] +print("Natoms, mass, x[0][0] coord =",natoms,mass[1],x[0][0]) temp = lmp.extract_compute("thermo_temp",0,0) -print "Temperature from compute =",temp +print("Temperature from compute =",temp) eng = lmp.extract_variable("eng",None,0) -print "Energy from equal-style variable =",eng +print("Energy from equal-style variable =",eng) vy = lmp.extract_variable("vy","all",1) -print "Velocity component from atom-style variable =",vy[1] +print("Velocity component from atom-style variable =",vy[1]) + +vol = lmp.get_thermo("vol") +print("Volume from get_thermo = ",vol) natoms = lmp.get_natoms() -print "Natoms from get_natoms =",natoms +print("Natoms from get_natoms =",natoms) xc = lmp.gather_atoms("x",1,3) -print "Global coords from gather_atoms =",xc[0],xc[1],xc[31] +print("Global coords from gather_atoms =",xc[0],xc[1],xc[31]) xc[0] = xc[0] + 1.0 lmp.scatter_atoms("x",1,3,xc) -print "Changed x[0][0] via scatter_atoms =",x[0][0] +print("Changed x[0][0] via scatter_atoms =",x[0][0]) diff --git a/python/examples/gui.py b/python/examples/gui.py index 0b4981cf57..3fc1d7e36c 100755 --- a/python/examples/gui.py +++ b/python/examples/gui.py @@ -10,6 +10,7 @@ # IMPORTANT: this script cannot yet be run in parallel via Pypar, # because I can't seem to do a MPI-style broadcast in Pypar +from __future__ import print_function import sys,time # methods called by GUI @@ -31,7 +32,7 @@ def quit(): argv = sys.argv if len(argv) != 3: - print "Syntax: gui.py in.lammps Nfreq" + print("Syntax: gui.py in.lammps Nfreq") sys.exit() infile = sys.argv[1] @@ -60,7 +61,10 @@ runflag = 0 temptarget = 1.0 if me == 0: - from Tkinter import * + try: + from Tkinter import * + except: + from tkinter import * tkroot = Tk() tkroot.withdraw() root = Toplevel(tkroot) @@ -108,5 +112,5 @@ while 1: time.sleep(0.01) # uncomment if running in parallel via Pypar -#print "Proc %d out of %d procs has" % (me,nprocs), lmp +#print("Proc %d out of %d procs has" % (me,nprocs), lmp) #pypar.finalize() diff --git a/python/examples/mc.py b/python/examples/mc.py index 8e556f3c52..9e7317218b 100755 --- a/python/examples/mc.py +++ b/python/examples/mc.py @@ -6,6 +6,7 @@ # Syntax: mc.py in.mc # in.mc = LAMMPS input script +from __future__ import print_function import sys,random,math # set these parameters @@ -21,7 +22,7 @@ random.seed(27848) argv = sys.argv if len(argv) != 2: - print "Syntax: mc.py in.mc" + print("Syntax: mc.py in.mc") sys.exit() infile = sys.argv[1] @@ -50,7 +51,7 @@ lmp.command("variable emin equal $e") x = lmp.extract_atom("x",3) -for i in xrange(natoms): +for i in range(natoms): x[i][0] += deltaperturb * (2*random.random()-1) x[i][1] += deltaperturb * (2*random.random()-1) @@ -68,7 +69,7 @@ estart = lmp.extract_compute("thermo_pe",0,0) / natoms elast = estart naccept = 0 -for i in xrange(nloop): +for i in range(nloop): iatom = random.randrange(0,natoms) x0 = x[iatom][0] y0 = x[iatom][1] @@ -100,9 +101,9 @@ nbuild = lmp.extract_variable("nbuild",None,0) lmp.command("run 0") estop = lmp.extract_compute("thermo_pe",0,0) / natoms -print "MC stats:" -print " starting energy =",estart -print " final energy =",estop -print " minimum energy of perfect lattice =",emin -print " accepted MC moves =",naccept -print " neighbor list rebuilds =",nbuild +print("MC stats:") +print(" starting energy =",estart) +print(" final energy =",estop) +print(" minimum energy of perfect lattice =",emin) +print(" accepted MC moves =",naccept) +print(" neighbor list rebuilds =",nbuild) diff --git a/python/examples/pizza/dump.py b/python/examples/pizza/dump.py index 76e1f3bcee..ec18cba62e 100644 --- a/python/examples/pizza/dump.py +++ b/python/examples/pizza/dump.py @@ -6,6 +6,10 @@ # certain rights in this software. This software is distributed under # the GNU General Public License. +# for python3 compatibility + +from __future__ import print_function + # dump tool oneline = "Read, write, manipulate dump files and particle attributes" @@ -179,7 +183,7 @@ d.extra(data) extract bond/tri/line list from data # Imports and external programs -import sys, commands, re, glob, types +import sys, re, glob, types from os import popen from math import * # any function could be used by set() @@ -220,7 +224,7 @@ class dump: self.flist = [] for word in words: self.flist += glob.glob(word) if len(self.flist) == 0 and len(list) == 1: - raise StandardError,"no dump file specified" + raise StandardError("no dump file specified") if len(list) == 1: self.increment = 0 @@ -245,19 +249,19 @@ class dump: snap = self.read_snapshot(f) while snap: self.snaps.append(snap) - print snap.time, + print(snap.time,end='') sys.stdout.flush() snap = self.read_snapshot(f) f.close() - print + print() # sort entries by timestep, cull duplicates self.snaps.sort(self.compare_time) self.cull() self.nsnaps = len(self.snaps) - print "read %d snapshots" % self.nsnaps + print("read %d snapshots" % self.nsnaps) # select all timesteps and atoms @@ -266,36 +270,36 @@ class dump: # set default names for atom columns if file wasn't self-describing if len(self.snaps) == 0: - print "no column assignments made" + print("no column assignments made") elif len(self.names): - print "assigned columns:",self.names2str() + print("assigned columns:",self.names2str()) elif self.snaps[0].atoms == None: - print "no column assignments made" + print("no column assignments made") elif len(self.snaps[0].atoms[0]) == 5: self.map(1,"id",2,"type",3,"x",4,"y",5,"z") - print "assigned columns:",self.names2str() + print("assigned columns:",self.names2str()) elif len(self.snaps[0].atoms[0]) == 8: self.map(1,"id",2,"type",3,"x",4,"y",5,"z",6,"ix",7,"iy",8,"iz") - print "assigned columns:",self.names2str() + print("assigned columns:",self.names2str()) else: - print "no column assignments made" + print("no column assignments made") # if snapshots are scaled, unscale them if (not self.names.has_key("x")) or \ (not self.names.has_key("y")) or \ (not self.names.has_key("z")): - print "no unscaling could be performed" + print("no unscaling could be performed") elif self.nsnaps > 0: if self.scaled(self.nsnaps-1): self.unscale() - else: print "dump is already unscaled" + else: print("dump is already unscaled") # -------------------------------------------------------------------- # read next snapshot from list of files def next(self): - if not self.increment: raise StandardError,"cannot read incrementally" + if not self.increment: raise StandardError("cannot read incrementally") # read next snapshot in current file using eof as pointer # if fail, try next file @@ -307,15 +311,15 @@ class dump: snap = self.read_snapshot(f) if not snap: self.nextfile += 1 - if self.nextfile == len(self.flist): return -1 + if self.nextfile == len(self.flist): return -1 f.close() - self.eof = 0 - continue + self.eof = 0 + continue self.eof = f.tell() f.close() try: self.findtime(snap.time) - continue + continue except: break # select the new snapshot with all its atoms @@ -324,7 +328,7 @@ class dump: snap = self.snaps[self.nsnaps] snap.tselect = 1 snap.nselect = snap.natoms - for i in xrange(snap.natoms): snap.aselect[i] = 1 + for i in range(snap.natoms): snap.aselect[i] = 1 self.nsnaps += 1 self.nselect += 1 @@ -370,14 +374,14 @@ class dump: if snap.natoms: words = f.readline().split() ncol = len(words) - for i in xrange(1,snap.natoms): + for i in range(1,snap.natoms): words += f.readline().split() floats = map(float,words) if oldnumeric: atoms = np.zeros((snap.natoms,ncol),np.Float) else: atoms = np.zeros((snap.natoms,ncol),np.float) start = 0 stop = ncol - for i in xrange(snap.natoms): + for i in range(snap.natoms): atoms[i] = floats[start:stop] start = stop stop += ncol @@ -413,7 +417,7 @@ class dump: def map(self,*pairs): if len(pairs) % 2 != 0: - raise StandardError, "dump map() requires pairs of mappings" + raise StandardError("dump map() requires pairs of mappings") for i in range(0,len(pairs),2): j = i + 1 self.names[pairs[j]] = pairs[i]-1 @@ -430,15 +434,15 @@ class dump: self.nsnaps -= 1 ndel += 1 else: i += 1 - print "%d snapshots deleted" % ndel - print "%d snapshots remaining" % self.nsnaps + print("%d snapshots deleted" % ndel) + print("%d snapshots remaining" % self.nsnaps) # -------------------------------------------------------------------- # scale coords to 0-1 for all snapshots or just one def scale(self,*list): if len(list) == 0: - print "Scaling dump ..." + print("Scaling dump ...") x = self.names["x"] y = self.names["y"] z = self.names["z"] @@ -466,7 +470,7 @@ class dump: def unscale(self,*list): if len(list) == 0: - print "Unscaling dump ..." + print("Unscaling dump ...") x = self.names["x"] y = self.names["y"] z = self.names["z"] @@ -493,7 +497,7 @@ class dump: # wrap coords from outside box to inside def wrap(self): - print "Wrapping dump ..." + print("Wrapping dump ...") x = self.names["x"] y = self.names["y"] @@ -515,7 +519,7 @@ class dump: # unwrap coords from inside box to outside def unwrap(self): - print "Unwrapping dump ..." + print("Unwrapping dump ...") x = self.names["x"] y = self.names["y"] @@ -537,7 +541,7 @@ class dump: # wrap coords to same image as atom ID stored in "other" column def owrap(self,other): - print "Wrapping to other ..." + print("Wrapping to other ...") id = self.names["id"] x = self.names["x"] @@ -554,9 +558,9 @@ class dump: zprd = snap.zhi - snap.zlo atoms = snap.atoms ids = {} - for i in xrange(snap.natoms): + for i in range(snap.natoms): ids[atoms[i][id]] = i - for i in xrange(snap.natoms): + for i in range(snap.natoms): j = ids[atoms[i][iother]] atoms[i][x] += (atoms[i][ix]-atoms[j][ix])*xprd atoms[i][y] += (atoms[i][iy]-atoms[j][iy])*yprd @@ -570,7 +574,7 @@ class dump: pairs = self.names.items() values = self.names.values() str = "" - for i in xrange(ncol): + for i in range(ncol): if i in values: str += pairs[values.index(i)][0] + ' ' return str @@ -581,12 +585,12 @@ class dump: def sort(self,*list): if len(list) == 0: - print "Sorting selected snapshots ..." + print("Sorting selected snapshots ...") id = self.names["id"] for snap in self.snaps: if snap.tselect: self.sort_one(snap,id) elif type(list[0]) is types.StringType: - print "Sorting selected snapshots by %s ..." % list[0] + print("Sorting selected snapshots by %s ..." % list[0]) id = self.names[list[0]] for snap in self.snaps: if snap.tselect: self.sort_one(snap,id) @@ -602,7 +606,7 @@ class dump: atoms = snap.atoms ids = atoms[:,id] ordering = np.argsort(ids) - for i in xrange(len(atoms[0])): + for i in range(len(atoms[0])): atoms[:,i] = np.take(atoms[:,i],ordering) # -------------------------------------------------------------------- @@ -614,33 +618,33 @@ class dump: else: f = open(file,"a") for snap in self.snaps: if not snap.tselect: continue - print snap.time, + print(snap.time,end='') sys.stdout.flush() if header: - print >>f,"ITEM: TIMESTEP" - print >>f,snap.time - print >>f,"ITEM: NUMBER OF ATOMS" - print >>f,snap.nselect - print >>f,"ITEM: BOX BOUNDS" - print >>f,snap.xlo,snap.xhi - print >>f,snap.ylo,snap.yhi - print >>f,snap.zlo,snap.zhi - print >>f,"ITEM: ATOMS",namestr + print("ITEM: TIMESTEP",file=f) + print(snap.time,file=f) + print("ITEM: NUMBER OF ATOMS",file=f) + print(snap.nselect,file=f) + print("ITEM: BOX BOUNDS",file=f) + print(snap.xlo,snap.xhi,file=f) + print(snap.ylo,snap.yhi,file=f) + print(snap.zlo,snap.zhi,file=f) + print("ITEM: ATOMS",namestr,file=f) atoms = snap.atoms nvalues = len(atoms[0]) - for i in xrange(snap.natoms): + for i in range(snap.natoms): if not snap.aselect[i]: continue line = "" - for j in xrange(nvalues): + for j in range(nvalues): if (j < 2): line += str(int(atoms[i][j])) + " " else: line += str(atoms[i][j]) + " " - print >>f,line + print(line,file=f) f.close() - print "\n%d snapshots" % self.nselect + print("\n%d snapshots" % self.nselect) # -------------------------------------------------------------------- # write one dump file per snapshot from current selection @@ -649,34 +653,34 @@ class dump: if len(self.snaps): namestr = self.names2str() for snap in self.snaps: if not snap.tselect: continue - print snap.time, + print(snap.time,end='') sys.stdout.flush() file = root + "." + str(snap.time) f = open(file,"w") - print >>f,"ITEM: TIMESTEP" - print >>f,snap.time - print >>f,"ITEM: NUMBER OF ATOMS" - print >>f,snap.nselect - print >>f,"ITEM: BOX BOUNDS" - print >>f,snap.xlo,snap.xhi - print >>f,snap.ylo,snap.yhi - print >>f,snap.zlo,snap.zhi - print >>f,"ITEM: ATOMS",namestr + print("ITEM: TIMESTEP",file=f) + print(snap.time,file=f) + print("ITEM: NUMBER OF ATOMS",file=f) + print(snap.nselect,file=f) + print("ITEM: BOX BOUNDS",file=f) + print(snap.xlo,snap.xhi,file=f) + print(snap.ylo,snap.yhi,file=f) + print(snap.zlo,snap.zhi,file=f) + print("ITEM: ATOMS",namestr,file=f) atoms = snap.atoms nvalues = len(atoms[0]) - for i in xrange(snap.natoms): + for i in range(snap.natoms): if not snap.aselect[i]: continue line = "" - for j in xrange(nvalues): + for j in range(nvalues): if (j < 2): line += str(int(atoms[i][j])) + " " else: line += str(atoms[i][j]) + " " - print >>f,line + print(line,file=f) f.close() - print "\n%d snapshots" % self.nselect + print("\n%d snapshots" % self.nselect) # -------------------------------------------------------------------- # find min/max across all selected snapshots/atoms for a particular column @@ -688,7 +692,7 @@ class dump: for snap in self.snaps: if not snap.tselect: continue atoms = snap.atoms - for i in xrange(snap.natoms): + for i in range(snap.natoms): if not snap.aselect[i]: continue if atoms[i][icol] < min: min = atoms[i][icol] if atoms[i][icol] > max: max = atoms[i][icol] @@ -698,7 +702,7 @@ class dump: # set a column value via an equation for all selected snapshots def set(self,eq): - print "Setting ..." + print("Setting ...") pattern = "\$\w*" list = re.findall(pattern,eq) @@ -715,14 +719,14 @@ class dump: for snap in self.snaps: if not snap.tselect: continue - for i in xrange(snap.natoms): - if snap.aselect[i]: exec ceq + for i in range(snap.natoms): + if snap.aselect[i]: exec(ceq) # -------------------------------------------------------------------- # set a column value via an input vec for all selected snapshots/atoms def setv(self,colname,vec): - print "Setting ..." + print("Setting ...") if not self.names.has_key(colname): self.newcolumn(colname) icol = self.names[colname] @@ -730,10 +734,10 @@ class dump: for snap in self.snaps: if not snap.tselect: continue if snap.nselect != len(vec): - raise StandardError,"vec length does not match # of selected atoms" + raise StandardError("vec length does not match # of selected atoms") atoms = snap.atoms m = 0 - for i in xrange(snap.natoms): + for i in range(snap.natoms): if snap.aselect[i]: atoms[i][icol] = vec[m] m += 1 @@ -746,12 +750,12 @@ class dump: icol = self.names[col] id = self.names["id"] ids = {} - for i in xrange(self.snaps[istep].natoms): + for i in range(self.snaps[istep].natoms): ids[self.snaps[istep].atoms[i][id]] = i for snap in self.snaps: if not snap.tselect: continue atoms = snap.atoms - for i in xrange(snap.natoms): + for i in range(snap.natoms): if not snap.aselect[i]: continue j = ids[atoms[i][id]] atoms[i][icol] = self.snaps[istep].atoms[j][icol] @@ -765,14 +769,14 @@ class dump: inew = self.names[new] min,max = self.minmax(old) - print "min/max = ",min,max + print("min/max = ",min,max) gap = max - min invdelta = n/gap for snap in self.snaps: if not snap.tselect: continue atoms = snap.atoms - for i in xrange(snap.natoms): + for i in range(snap.natoms): if not snap.aselect[i]: continue ivalue = int((atoms[i][iold] - min) * invdelta) + 1 if ivalue > n: ivalue = n @@ -796,7 +800,7 @@ class dump: def atom(self,n,*list): if len(list) == 0: - raise StandardError, "no columns specified" + raise StandardError("no columns specified") columns = [] values = [] for name in list: @@ -809,11 +813,11 @@ class dump: for snap in self.snaps: if not snap.tselect: continue atoms = snap.atoms - for i in xrange(snap.natoms): + for i in range(snap.natoms): if atoms[i][id] == n: break if atoms[i][id] != n: - raise StandardError, "could not find atom ID in snapshot" - for j in xrange(ncol): + raise StandardError("could not find atom ID in snapshot") + for j in range(ncol): values[j][m] = atoms[i][columns[j]] m += 1 @@ -827,7 +831,7 @@ class dump: snap = self.snaps[self.findtime(n)] if len(list) == 0: - raise StandardError, "no columns specified" + raise StandardError("no columns specified") columns = [] values = [] for name in list: @@ -836,9 +840,9 @@ class dump: ncol = len(columns) m = 0 - for i in xrange(snap.natoms): + for i in range(snap.natoms): if not snap.aselect[i]: continue - for j in xrange(ncol): + for j in range(ncol): values[j][m] = snap.atoms[i][columns[j]] m += 1 @@ -887,7 +891,7 @@ class dump: def iterator(self,flag): start = 0 if flag: start = self.iterate + 1 - for i in xrange(start,self.nsnaps): + for i in range(start,self.nsnaps): if self.snaps[i].tselect: self.iterate = i return i,self.snaps[i].time,1 @@ -912,7 +916,7 @@ class dump: # need Numeric/Numpy mode here atoms = [] - for i in xrange(snap.natoms): + for i in range(snap.natoms): if not snap.aselect[i]: continue atom = snap.atoms[i] atoms.append([atom[id],atom[type],atom[x],atom[y],atom[z]]) @@ -927,7 +931,7 @@ class dump: bonds = [] if self.bondflag: alist = {} - for i in xrange(len(atoms)): alist[int(atoms[i][0])] = i + for i in range(len(atoms)): alist[int(atoms[i][0])] = i for bond in self.bondlist: try: i = alist[bond[2]] @@ -953,9 +957,9 @@ class dump: # -------------------------------------------------------------------- def findtime(self,n): - for i in xrange(self.nsnaps): + for i in range(self.nsnaps): if self.snaps[i].time == n: return i - raise StandardError, "no step %d exists" % n + raise StandardError("no step %d exists" % n) # -------------------------------------------------------------------- # return maximum box size across all selected snapshots @@ -982,7 +986,7 @@ class dump: for snap in self.snaps: if not snap.tselect: continue atoms = snap.atoms - for i in xrange(snap.natoms): + for i in range(snap.natoms): if not snap.aselect[i]: continue if atoms[i][icol] > max: max = atoms[i][icol] return int(max) @@ -1004,11 +1008,11 @@ class dump: nbonds = int(f.readline()) item = f.readline() if not re.search("BONDS",item): - raise StandardError, "could not read bonds from dump file" + raise StandardError("could not read bonds from dump file") words = f.readline().split() ncol = len(words) - for i in xrange(1,nbonds): + for i in range(1,nbonds): words += f.readline().split() f.close() @@ -1019,7 +1023,7 @@ class dump: ints = [abs(int(value)) for value in words] start = 0 stop = 4 - for i in xrange(nbonds): + for i in range(nbonds): bondlist[i] = ints[start:stop] start += ncol stop += ncol @@ -1027,7 +1031,7 @@ class dump: self.bondflag = 1 self.bondlist = bondlist except: - raise StandardError,"could not read from bond dump file" + raise StandardError("could not read from bond dump file") # request bonds from data object @@ -1043,7 +1047,7 @@ class dump: self.bondflag = 1 self.bondlist = bondlist except: - raise StandardError,"could not extract bonds from data object" + raise StandardError("could not extract bonds from data object") # request tris/lines from cdata object @@ -1057,7 +1061,7 @@ class dump: self.lineflag = 1 self.linelist = lines except: - raise StandardError,"could not extract tris/lines from cdata object" + raise StandardError("could not extract tris/lines from cdata object") # request tris from mdump object @@ -1066,10 +1070,10 @@ class dump: self.triflag = 2 self.triobj = arg except: - raise StandardError,"could not extract tris from mdump object" + raise StandardError("could not extract tris from mdump object") else: - raise StandardError,"unrecognized argument to dump.extra()" + raise StandardError("unrecognized argument to dump.extra()") # -------------------------------------------------------------------- @@ -1103,7 +1107,7 @@ class tselect: snap.tselect = 1 data.nselect = len(data.snaps) data.aselect.all() - print "%d snapshots selected out of %d" % (data.nselect,data.nsnaps) + print("%d snapshots selected out of %d" % (data.nselect,data.nsnaps)) # -------------------------------------------------------------------- @@ -1115,7 +1119,7 @@ class tselect: data.snaps[i].tselect = 1 data.nselect = 1 data.aselect.all() - print "%d snapshots selected out of %d" % (data.nselect,data.nsnaps) + print("%d snapshots selected out of %d" % (data.nselect,data.nsnaps)) # -------------------------------------------------------------------- @@ -1124,7 +1128,7 @@ class tselect: for snap in data.snaps: snap.tselect = 0 data.nselect = 0 - print "%d snapshots selected out of %d" % (data.nselect,data.nsnaps) + print("%d snapshots selected out of %d" % (data.nselect,data.nsnaps)) # -------------------------------------------------------------------- @@ -1140,7 +1144,7 @@ class tselect: snap.tselect = 0 data.nselect -= 1 data.aselect.all() - print "%d snapshots selected out of %d" % (data.nselect,data.nsnaps) + print("%d snapshots selected out of %d" % (data.nselect,data.nsnaps)) # -------------------------------------------------------------------- @@ -1149,14 +1153,14 @@ class tselect: snaps = data.snaps cmd = "flag = " + teststr.replace("$t","snaps[i].time") ccmd = compile(cmd,'','single') - for i in xrange(data.nsnaps): + for i in range(data.nsnaps): if not snaps[i].tselect: continue - exec ccmd + exec(ccmd) if not flag: snaps[i].tselect = 0 data.nselect -= 1 data.aselect.all() - print "%d snapshots selected out of %d" % (data.nselect,data.nsnaps) + print("%d snapshots selected out of %d" % (data.nselect,data.nsnaps)) # -------------------------------------------------------------------- # atom selection class @@ -1173,12 +1177,12 @@ class aselect: if len(args) == 0: # all selected timesteps for snap in data.snaps: if not snap.tselect: continue - for i in xrange(snap.natoms): snap.aselect[i] = 1 + for i in range(snap.natoms): snap.aselect[i] = 1 snap.nselect = snap.natoms else: # one timestep n = data.findtime(args[0]) snap = data.snaps[n] - for i in xrange(snap.natoms): snap.aselect[i] = 1 + for i in range(snap.natoms): snap.aselect[i] = 1 snap.nselect = snap.natoms # -------------------------------------------------------------------- @@ -1201,29 +1205,29 @@ class aselect: if len(args) == 0: # all selected timesteps for snap in data.snaps: if not snap.tselect: continue - for i in xrange(snap.natoms): + for i in range(snap.natoms): if not snap.aselect[i]: continue - exec ccmd + exec(ccmd) if not flag: snap.aselect[i] = 0 snap.nselect -= 1 - for i in xrange(data.nsnaps): + for i in range(data.nsnaps): if data.snaps[i].tselect: - print "%d atoms of %d selected in first step %d" % \ - (data.snaps[i].nselect,data.snaps[i].natoms,data.snaps[i].time) + print("%d atoms of %d selected in first step %d" % \ + (data.snaps[i].nselect,data.snaps[i].natoms,data.snaps[i].time)) break - for i in xrange(data.nsnaps-1,-1,-1): + for i in range(data.nsnaps-1,-1,-1): if data.snaps[i].tselect: - print "%d atoms of %d selected in last step %d" % \ - (data.snaps[i].nselect,data.snaps[i].natoms,data.snaps[i].time) + print("%d atoms of %d selected in last step %d" % \ + (data.snaps[i].nselect,data.snaps[i].natoms,data.snaps[i].time)) break else: # one timestep n = data.findtime(args[0]) snap = data.snaps[n] - for i in xrange(snap.natoms): + for i in range(snap.natoms): if not snap.aselect[i]: continue - exec ccmd + exec(ccmd) if not flag: snap.aselect[i] = 0 snap.nselect -= 1 diff --git a/python/examples/pizza/gl.py b/python/examples/pizza/gl.py index 71db5b63e7..765653c983 100644 --- a/python/examples/pizza/gl.py +++ b/python/examples/pizza/gl.py @@ -6,6 +6,9 @@ # certain rights in this software. This software is distributed under # the GNU General Public License. +# for python3 compatibility +from __future__ import print_function + # gl tool oneline = "3d interactive visualization via OpenGL" @@ -73,7 +76,7 @@ g.ldef() default = 0 fill if atom/bond/tri/line has type > # defined properties, is an error from vizinfo import colors access color list -print colors list defined color names and RGB values +print(colors) list defined color names and RGB values colors["nickname"] = [R,G,B] set new RGB values from 0 to 255 140 pre-defined colors: red, green, blue, purple, yellow, black, white, etc @@ -499,7 +502,7 @@ class gl: # add GL-specific info to each bond def reload(self): - print "Loading data into gl tool ..." + print("Loading data into gl tool ...") data = self.data self.timeframes = [] @@ -527,9 +530,9 @@ class gl: self.triframes.append(tris) self.lineframes.append(lines) - print time, + print(time,end='') sys.stdout.flush() - print + print() self.nframes = len(self.timeframes) self.distance = compute_distance(self.boxframes[0]) @@ -651,7 +654,7 @@ class gl: self.w.tkRedraw() self.save(file) - print time, + print(time,end='') sys.stdout.flush() i += 1 n += 1 @@ -690,7 +693,7 @@ class gl: fraction*(self.scale_stop - self.scale_start) self.viewupright() - if n == nstart or self.panflag: self.center = compute_center(box) + if n == nstart or self.panflag: self.center = compute_center(box) if bonds: self.bonds_augment(bonds) @@ -706,11 +709,11 @@ class gl: self.w.tkRedraw() self.save(file) - print n, + print(n,end='') sys.stdout.flush() n += 1 - print "\n%d images" % ncount + print("\n%d images" % ncount) # -------------------------------------------------------------------- @@ -776,11 +779,11 @@ class gl: ncolor = self.vizinfo.nlcolor for line in self.linedraw: itype = int(line[1]) - if itype > ncolor: raise StandardError,"line type too big" + if itype > ncolor: raise StandardError("line type too big") red,green,blue = self.vizinfo.lcolor[itype] glColor3f(red,green,blue) thick = self.vizinfo.lrad[itype] - glLineWidth(thick) + glLineWidth(thick) glBegin(GL_LINES) glVertex3f(line[2],line[3],line[4]) glVertex3f(line[5],line[6],line[7]) @@ -825,7 +828,7 @@ class gl: for bond in self.bonddraw: if bond[10] > bound: continue itype = int(bond[1]) - if itype > ncolor: raise StandardError,"bond type too big" + if itype > ncolor: raise StandardError("bond type too big") red,green,blue = self.vizinfo.bcolor[itype] rad = self.vizinfo.brad[itype] glPushMatrix() @@ -848,7 +851,7 @@ class gl: ncolor = self.vizinfo.ntcolor for tri in self.tridraw: itype = int(tri[1]) - if itype > ncolor: raise StandardError,"tri type too big" + if itype > ncolor: raise StandardError("tri type too big") red,green,blue = self.vizinfo.tcolor[itype] glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION,[red,green,blue,1.0]); glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,self.shiny); @@ -906,7 +909,7 @@ class gl: ymin >= ylo and ymax <= yhi and zmin >= zlo and zmax <= zhi: if bond[10] > bound: continue itype = int(bond[1]) - if itype > ncolor: raise StandardError,"bond type too big" + if itype > ncolor: raise StandardError("bond type too big") red,green,blue = self.vizinfo.bcolor[itype] rad = self.vizinfo.brad[itype] glPushMatrix() @@ -938,7 +941,7 @@ class gl: ymin >= ylo and ymax <= yhi and \ zmin >= zlo and zmax <= zhi: itype = int(tri[1]) - if itype > ncolor: raise StandardError,"tri type too big" + if itype > ncolor: raise StandardError("tri type too big") red,green,blue = self.vizinfo.tcolor[itype] glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION, [red,green,blue,1.0]); diff --git a/python/examples/pizza/gnu.py b/python/examples/pizza/gnu.py index f6f0167330..7d796d5586 100644 --- a/python/examples/pizza/gnu.py +++ b/python/examples/pizza/gnu.py @@ -6,6 +6,9 @@ # certain rights in this software. This software is distributed under # the GNU General Public License. +# for python3 compatibility +from __future__ import print_function + # gnu tool oneline = "Create plots via GnuPlot plotting program" @@ -87,7 +90,7 @@ g.curve(N,'r') set color of curve N import types, os try: from DEFAULTS import PIZZA_GNUPLOT -except: PIZZA_GNUPLOT = "gnuplot" +except: PIZZA_GNUPLOT = "gnuplot -p" try: from DEFAULTS import PIZZA_GNUTERM except: PIZZA_GNUTERM = "x11" @@ -133,7 +136,7 @@ class gnu: self.export(file,linear,vectors[0]) self.figures[self.current-1].ncurves = 1 else: - if len(vectors) % 2: raise StandardError,"vectors must come in pairs" + if len(vectors) % 2: raise StandardError("vectors must come in pairs") for i in range(0,len(vectors),2): file = self.file + ".%d.%d" % (self.current,i/2+1) self.export(file,vectors[i],vectors[i+1]) @@ -167,13 +170,13 @@ class gnu: def export(self,filename,*vectors): n = len(vectors[0]) for vector in vectors: - if len(vector) != n: raise StandardError,"vectors must be same length" + if len(vector) != n: raise StandardError("vectors must be same length") f = open(filename,'w') nvec = len(vectors) - for i in xrange(n): - for j in xrange(nvec): - print >>f,vectors[j][i], - print >>f + for i in range(n): + for j in range(nvec): + print(str(vectors[j][i])+" ",file=f,end='') + print ("",file=f) f.close() # -------------------------------------------------------------------- @@ -350,7 +353,7 @@ class gnu: self.__call__("set key off") cmd = 'plot ' - for i in range(fig.ncurves): + for i in range(int(fig.ncurves)): file = self.file + ".%d.%d" % (self.current,i+1) if len(fig.colors) > i and fig.colors[i]: cmd += "'" + file + "' using 1:2 with line %d, " % fig.colors[i] diff --git a/python/examples/pizza/pdbfile.py b/python/examples/pizza/pdbfile.py index 1713ada043..2ca85b64da 100644 --- a/python/examples/pizza/pdbfile.py +++ b/python/examples/pizza/pdbfile.py @@ -6,6 +6,9 @@ # certain rights in this software. This software is distributed under # the GNU General Public License. +# for python3 compatibility +from __future__ import print_function + # pdb tool oneline = "Read, write PDB files in combo with LAMMPS snapshots" @@ -83,7 +86,7 @@ class pdbfile: elif len(args) == 2: filestr = args[0] self.data = args[1] - else: raise StandardError, "invalid args for pdb()" + else: raise StandardError("invalid args for pdb()") # flist = full list of all PDB input file names # append .pdb if needed @@ -97,14 +100,14 @@ class pdbfile: for i in xrange(len(flist)): if flist[i][-4:] != ".pdb": flist[i] += ".pdb" if len(flist) == 0: - raise StandardError,"no PDB file specified" + raise StandardError("no PDB file specified") self.files = flist else: self.files = [] if len(self.files) > 1 and self.data: - raise StandardError, "cannot use multiple PDB files with data object" + raise StandardError("cannot use multiple PDB files with data object") if len(self.files) == 0 and not self.data: - raise StandardError, "no input PDB file(s)" + raise StandardError("no input PDB file(s)") # grab PDB file from http://rcsb.org if not a local file @@ -112,7 +115,7 @@ class pdbfile: try: open(self.files[0],'r').close() except: - print "downloading %s from http://rcsb.org" % self.files[0] + print("downloading %s from http://rcsb.org" % self.files[0]) fetchstr = "http://www.rcsb.org/pdb/cgi/export.cgi/%s?format=PDB&pdbId=2cpk&compression=None" % self.files[0] urllib.urlretrieve(fetchstr,self.files[0]) @@ -142,20 +145,20 @@ class pdbfile: which,time,flag = self.data.iterator(flag) if flag == -1: break self.convert(f,which) - print >>f,"END" - print time, + print("END",file=f) + print(time,end='') sys.stdout.flush() n += 1 else: for file in self.files: f.write(open(file,'r').read()) - print >>f,"END" - print file, + print("END",file=f) + print(file,end='') sys.stdout.flush() f.close() - print "\nwrote %d datasets to %s in PDB format" % (n,file) + print("\nwrote %d datasets to %s in PDB format" % (n,file)) # -------------------------------------------------------------------- # write series of numbered PDB files @@ -190,7 +193,7 @@ class pdbfile: self.convert(f,which) f.close() - print time, + print(time,end='') sys.stdout.flush() n += 1 @@ -210,12 +213,12 @@ class pdbfile: f = open(file,'w') f.write(open(infile,'r').read()) f.close() - print file, + print(file,end='') sys.stdout.flush() n += 1 - print "\nwrote %d datasets to %s*.pdb in PDB format" % (n,root) + print("\nwrote %d datasets to %s*.pdb in PDB format" % (n,root)) # -------------------------------------------------------------------- # write a single PDB file @@ -280,10 +283,10 @@ class pdbfile: if self.atomlines.has_key(id): (begin,end) = self.atomlines[id] line = "%s%8.3f%8.3f%8.3f%s" % (begin,atom[2],atom[3],atom[4],end) - print >>f,line, + print(line,file=f,end='') else: for atom in atoms: begin = "ATOM %6d %2d R00 1 " % (atom[0],atom[1]) middle = "%8.3f%8.3f%8.3f" % (atom[2],atom[3],atom[4]) end = " 1.00 0.00 NONE" - print >>f,begin+middle+end + print(begin+middle+end,file=f) diff --git a/python/examples/pizza/vmd.py b/python/examples/pizza/vmd.py index 7a49617b4c..fb5095617a 100644 --- a/python/examples/pizza/vmd.py +++ b/python/examples/pizza/vmd.py @@ -6,6 +6,9 @@ # certain rights in this software. This software is distributed under # the GNU General Public License. +# for python3 compatibility +from __future__ import print_function + # vmd tool # Minimalistic VMD embedding for Pizza.py @@ -52,7 +55,7 @@ except: PIZZA_VMDDIR = "/usr/local/lib/vmd" try: from DEFAULTS import PIZZA_VMDDEV except: PIZZA_VMDDEV = "win" try: from DEFAULTS import PIZZA_VMDARCH -except: PIZZA_VMDARCH = "LINUX" +except: PIZZA_VMDARCH = "LINUXAMD64" # try these settings for a Mac #PIZZA_VMDNAME = "vmd" @@ -62,8 +65,8 @@ except: PIZZA_VMDARCH = "LINUX" try: import pexpect except: - print "pexpect from http://pypi.python.org/pypi/pexpect", \ - "is required for vmd tool" + print("pexpect from http://pypi.python.org/pypi/pexpect", \ + "is required for vmd tool") raise # Class definition @@ -109,7 +112,7 @@ class vmd: self.VMD.sendline(command) self.VMD.expect('vmd >') if self.debugme: - print "call+result:"+self.VMD.before + print("call+result:"+self.VMD.before) return # -------------------------------------------------------------------- @@ -127,9 +130,9 @@ class vmd: # turn on debugging info def debug(self,status=True): if status and not self.debugme: - print 'Turning vmd.py debugging ON.' + print('Turning vmd.py debugging ON.') if not status and self.debugme: - print 'Turning vmd.py debugging OFF.' + print('Turning vmd.py debugging OFF.') self.debugme = status # -------------------------------------------------------------------- @@ -141,14 +144,14 @@ class vmd: try: command = raw_input("vmd > ") except EOFError: - print "(EOF)" + print("(EOF)") self.__call__('menu main off') return if command == "quit" or command == "exit": self.__call__('menu main off') return if command == "gopython": - print "gopython not supported here" + print("gopython not supported here") continue self.__call__(command) diff --git a/python/examples/plot.py b/python/examples/plot.py index a3f465ca19..efb9ecaa68 100755 --- a/python/examples/plot.py +++ b/python/examples/plot.py @@ -10,6 +10,7 @@ # compute-ID = ID of compute that calculates temperature # (or any other scalar quantity) +from __future__ import print_function import sys sys.path.append("./pizza") from gnu import gnu @@ -18,7 +19,7 @@ from gnu import gnu argv = sys.argv if len(argv) != 5: - print "Syntax: plot.py in.lammps Nfreq Nsteps compute-ID" + print("Syntax: plot.py in.lammps Nfreq Nsteps compute-ID") sys.exit() infile = sys.argv[1] @@ -71,5 +72,5 @@ while ntimestep < nsteps: lmp.command("run 0 pre no post yes") # uncomment if running in parallel via Pypar -#print "Proc %d out of %d procs has" % (me,nprocs), lmp +#print("Proc %d out of %d procs has" % (me,nprocs), lmp) #pypar.finalize() diff --git a/python/examples/simple.py b/python/examples/simple.py index 4ca4b81a8d..9315a555fc 100755 --- a/python/examples/simple.py +++ b/python/examples/simple.py @@ -11,13 +11,14 @@ # in.lammps = LAMMPS input script # also need to uncomment either Pypar or mpi4py sections below +from __future__ import print_function import sys # parse command line argv = sys.argv if len(argv) != 2: - print "Syntax: simple.py in.lammps" + print("Syntax: simple.py in.lammps") sys.exit() infile = sys.argv[1] @@ -56,13 +57,13 @@ lmp.scatter_atoms("x",1,3,x) lmp.command("run 1"); f = lmp.extract_atom("f",3) -print "Force on 1 atom via extract_atom: ",f[0][0] +print("Force on 1 atom via extract_atom: ",f[0][0]) fx = lmp.extract_variable("fx","all",1) -print "Force on 1 atom via extract_variable:",fx[0] +print("Force on 1 atom via extract_variable:",fx[0]) # uncomment if running in parallel via Pypar -#print "Proc %d out of %d procs has" % (me,nprocs), lmp +#print("Proc %d out of %d procs has" % (me,nprocs), lmp) #pypar.finalize() # uncomment if running in parallel via mpi4py diff --git a/python/examples/split.py b/python/examples/split.py index 65cf395581..719877d826 100755 --- a/python/examples/split.py +++ b/python/examples/split.py @@ -7,13 +7,14 @@ # Syntax: split.py in.lammps # in.lammps = LAMMPS input script +from __future__ import print_function import sys # parse command line argv = sys.argv if len(argv) != 2: - print "Syntax: simple.py in.lammps" + print("Syntax: simple.py in.lammps") sys.exit() infile = sys.argv[1] @@ -57,12 +58,12 @@ if color == 0: lmp.command("run 1"); f = lmp.extract_atom("f",3) - print "Force on 1 atom via extract_atom: ",f[0][0] + print("Force on 1 atom via extract_atom: ",f[0][0]) fx = lmp.extract_variable("fx","all",1) - print "Force on 1 atom via extract_variable:",fx[0] - print "Proc %d out of %d procs has" % (me,nprocs), lmp - print "Calculation on partition 0 complete" + print("Force on 1 atom via extract_variable:",fx[0]) + print("Proc %d out of %d procs has" % (me,nprocs), lmp) + print("Calculation on partition 0 complete") else: # could run a 2nd calculation on second partition @@ -71,7 +72,7 @@ else: import time time.sleep(2) - print "Calculation on partition 1 complete" + print("Calculation on partition 1 complete") # shutdown mpi4py diff --git a/python/examples/trivial.py b/python/examples/trivial.py index 7e61b97cb3..0e3d6b91af 100755 --- a/python/examples/trivial.py +++ b/python/examples/trivial.py @@ -6,13 +6,14 @@ # Syntax: trivial.py in.lammps # in.lammps = LAMMPS input script +from __future__ import print_function import sys # parse command line argv = sys.argv if len(argv) != 2: - print "Syntax: trivial.py in.lammps" + print("Syntax: trivial.py in.lammps") sys.exit() infile = sys.argv[1] diff --git a/python/examples/viz_atomeye.py b/python/examples/viz_atomeye.py index ca0d60f443..3803b2e79c 100755 --- a/python/examples/viz_atomeye.py +++ b/python/examples/viz_atomeye.py @@ -8,6 +8,7 @@ # Nfreq = dump and viz shapshot every this many steps # Nsteps = run for this many steps +from __future__ import print_function import sys,os # set this to point to AtomEye version 3 executable @@ -19,7 +20,7 @@ ATOMEYE3 = "/home/sjplimp/tools/atomeye3/A3.i686-20060530 > atomeye.out" argv = sys.argv if len(argv) != 4: - print "Syntax: viz_atomeye.py in.lammps Nfreq Nsteps" + print("Syntax: viz_atomeye.py in.lammps Nfreq Nsteps") sys.exit() infile = sys.argv[1] @@ -68,5 +69,5 @@ while ntimestep < nsteps: lmp.command("run 0 pre no post yes") # uncomment if running in parallel via Pypar -#print "Proc %d out of %d procs has" % (me,nprocs), lmp +#print("Proc %d out of %d procs has" % (me,nprocs), lmp) #pypar.finalize() diff --git a/python/examples/viz_gl.py b/python/examples/viz_gl.py index fcb92e03f2..476509ad43 100755 --- a/python/examples/viz_gl.py +++ b/python/examples/viz_gl.py @@ -8,6 +8,7 @@ # Nfreq = dump and viz shapshot every this many steps # Nsteps = run for this many steps +from __future__ import print_function import sys sys.path.append("./pizza") @@ -15,7 +16,7 @@ sys.path.append("./pizza") argv = sys.argv if len(argv) != 4: - print "Syntax: viz_gl.py in.lammps Nfreq Nsteps" + print("Syntax: viz_gl.py in.lammps Nfreq Nsteps") sys.exit() infile = sys.argv[1] @@ -48,7 +49,11 @@ ntimestep = 0 # just proc 0 handles reading of dump file and viz if me == 0: - import Tkinter + tkroot = None + try: + import Tkinter + except: + import tkinter as Tkinter tkroot = Tkinter.Tk() tkroot.withdraw() @@ -79,5 +84,5 @@ while ntimestep < nsteps: lmp.command("run 0 pre no post yes") # uncomment if running in parallel via Pypar -#print "Proc %d out of %d procs has" % (me,nprocs), lmp +#print("Proc %d out of %d procs has" % (me,nprocs), lmp) #pypar.finalize() diff --git a/python/examples/viz_pymol.py b/python/examples/viz_pymol.py index 17f3d44810..02178a0fb0 100755 --- a/python/examples/viz_pymol.py +++ b/python/examples/viz_pymol.py @@ -8,6 +8,7 @@ # Nfreq = dump and viz shapshot every this many steps # Nsteps = run for this many steps +from __future__ import print_function import sys sys.path.append("./pizza") @@ -15,7 +16,7 @@ sys.path.append("./pizza") argv = sys.argv if len(argv) != 4: - print "Syntax: viz_pymol.py in.lammps Nfreq Nsteps" + print("Syntax: viz_pymol.py in.lammps Nfreq Nsteps") sys.exit() infile = sys.argv[1] @@ -78,5 +79,5 @@ while ntimestep < nsteps: lmp.command("run 0 pre no post yes") # uncomment if running in parallel via Pypar -#print "Proc %d out of %d procs has" % (me,nprocs), lmp +#print("Proc %d out of %d procs has" % (me,nprocs), lmp) #pypar.finalize() diff --git a/python/examples/viz_vmd.py b/python/examples/viz_vmd.py index 47f27d26ff..807a8c9d55 100755 --- a/python/examples/viz_vmd.py +++ b/python/examples/viz_vmd.py @@ -8,6 +8,7 @@ # Nfreq = dump and viz shapshot every this many steps # Nsteps = run for this many steps +from __future__ import print_function import sys sys.path.append("./pizza") @@ -15,7 +16,7 @@ sys.path.append("./pizza") argv = sys.argv if len(argv) != 4: - print "Syntax: viz_vmd.py in.lammps Nfreq Nsteps" + print("Syntax: viz_vmd.py in.lammps Nfreq Nsteps") sys.exit() infile = sys.argv[1] @@ -82,10 +83,10 @@ if me == 0: v.flush() # uncomment the following, if you want to work with the viz some more. #v('menu main on') - #print "type quit to terminate." + #print("type quit to terminate.") #v.enter() #v.stop() # uncomment if running in parallel via Pypar -#print "Proc %d out of %d procs has" % (me,nprocs), lmp +#print("Proc %d out of %d procs has" % (me,nprocs), lmp) #pypar.finalize() diff --git a/python/examples/vizplotgui_atomeye.py b/python/examples/vizplotgui_atomeye.py index 935123d2b6..71730974df 100755 --- a/python/examples/vizplotgui_atomeye.py +++ b/python/examples/vizplotgui_atomeye.py @@ -12,6 +12,7 @@ # IMPORTANT: this script cannot yet be run in parallel via Pypar, # because I can't seem to do a MPI-style broadcast in Pypar +from __future__ import print_function import sys,os,time sys.path.append("./pizza") @@ -50,7 +51,7 @@ def update(ntimestep): argv = sys.argv if len(argv) != 4: - print "Syntax: vizplotgui_atomeye.py in.lammps Nfreq compute-ID" + print("Syntax: vizplotgui_atomeye.py in.lammps Nfreq compute-ID") sys.exit() infile = sys.argv[1] @@ -97,7 +98,10 @@ if me == 0: # display GUI with run/stop buttons and slider for temperature if me == 0: - from Tkinter import * + try: + from Tkinter import * + except: + from tkinter import * tkroot = Tk() tkroot.withdraw() root = Toplevel(tkroot) @@ -161,5 +165,5 @@ while 1: lmp.command("run 0 pre no post yes") # uncomment if running in parallel via Pypar -#print "Proc %d out of %d procs has" % (me,nprocs), lmp +#print("Proc %d out of %d procs has" % (me,nprocs), lmp) #pypar.finalize() diff --git a/python/examples/vizplotgui_gl.py b/python/examples/vizplotgui_gl.py index ee26487bb2..937670e511 100755 --- a/python/examples/vizplotgui_gl.py +++ b/python/examples/vizplotgui_gl.py @@ -12,6 +12,7 @@ # IMPORTANT: this script cannot yet be run in parallel via Pypar, # because I can't seem to do a MPI-style broadcast in Pypar +from __future__ import print_function import sys,time sys.path.append("./pizza") @@ -46,7 +47,7 @@ def update(ntimestep): argv = sys.argv if len(argv) != 4: - print "Syntax: vizplotgui_gl.py in.lammps Nfreq compute-ID" + print("Syntax: vizplotgui_gl.py in.lammps Nfreq compute-ID") sys.exit() infile = sys.argv[1] @@ -86,7 +87,10 @@ temptarget = 1.0 # just proc 0 handles reading of dump file and viz if me == 0: - from Tkinter import * + try: + from Tkinter import * + except: + from tkinter import * tkroot = Tk() tkroot.withdraw() @@ -107,7 +111,10 @@ if me == 0: # display GUI with run/stop buttons and slider for temperature if me == 0: - from Tkinter import * + try: + from Tkinter import * + except: + from tkinter import * tkroot = Tk() tkroot.withdraw() root = Toplevel(tkroot) @@ -171,5 +178,5 @@ while 1: lmp.command("run 0 pre no post yes") # uncomment if running in parallel via Pypar -#print "Proc %d out of %d procs has" % (me,nprocs), lmp +#print("Proc %d out of %d procs has" % (me,nprocs), lmp) #pypar.finalize() diff --git a/python/examples/vizplotgui_pymol.py b/python/examples/vizplotgui_pymol.py index c0628a2b1b..c7a8a00c6d 100755 --- a/python/examples/vizplotgui_pymol.py +++ b/python/examples/vizplotgui_pymol.py @@ -12,6 +12,7 @@ # IMPORTANT: this script cannot yet be run in parallel via Pypar, # because I can't seem to do a MPI-style broadcast in Pypar +from __future__ import print_function import sys,time sys.path.append("./pizza") @@ -48,7 +49,7 @@ def update(ntimestep): argv = sys.argv if len(argv) != 4: - print "Syntax: vizplotgui_pymol.py in.lammps Nfreq compute-ID" + print("Syntax: vizplotgui_pymol.py in.lammps Nfreq compute-ID") sys.exit() infile = sys.argv[1] @@ -106,7 +107,10 @@ if me == 0: # display GUI with run/stop buttons and slider for temperature if me == 0: - from Tkinter import * + try: + from Tkinter import * + except: + from tkinter import * tkroot = Tk() tkroot.withdraw() root = Toplevel(tkroot) @@ -170,5 +174,5 @@ while 1: lmp.command("run 0 pre no post yes") # uncomment if running in parallel via Pypar -#print "Proc %d out of %d procs has" % (me,nprocs), lmp +#print("Proc %d out of %d procs has" % (me,nprocs), lmp) #pypar.finalize() diff --git a/python/examples/vizplotgui_vmd.py b/python/examples/vizplotgui_vmd.py index d969666a1a..9eab0865e2 100755 --- a/python/examples/vizplotgui_vmd.py +++ b/python/examples/vizplotgui_vmd.py @@ -12,6 +12,7 @@ # IMPORTANT: this script cannot yet be run in parallel via Pypar, # because I can't seem to do a MPI-style broadcast in Pypar +from __future__ import print_function import sys,time sys.path.append("./pizza") @@ -47,7 +48,7 @@ def update(ntimestep): argv = sys.argv if len(argv) != 4: - print "Syntax: vizplotgui_vmd.py in.lammps Nfreq compute-ID" + print("Syntax: vizplotgui_vmd.py in.lammps Nfreq compute-ID") sys.exit() infile = sys.argv[1] @@ -105,7 +106,10 @@ if me == 0: # display GUI with run/stop buttons and slider for temperature if me == 0: - from Tkinter import * + try: + from Tkinter import * + except: + from tkinter import * tkroot = Tk() tkroot.withdraw() root = Toplevel(tkroot) @@ -169,5 +173,5 @@ while 1: lmp.command("run 0 pre no post yes") # uncomment if running in parallel via Pypar -#print "Proc %d out of %d procs has" % (me,nprocs), lmp +#print("Proc %d out of %d procs has" % (me,nprocs), lmp) #pypar.finalize() diff --git a/python/lammps.py b/python/lammps.py index bbc46cf2b9..1931e5e0c7 100644 --- a/python/lammps.py +++ b/python/lammps.py @@ -11,17 +11,26 @@ # See the README file in the top-level LAMMPS directory. # ------------------------------------------------------------------------- -# Python wrapper on LAMMPS library via ctypes +# Python wrappers on LAMMPS library via ctypes +# for python3 compatibility +from __future__ import print_function + +# imports for simple LAMMPS python wrapper module "lammps" import sys,traceback,types from ctypes import * from os.path import dirname,abspath,join from inspect import getsourcefile -class lammps: - +# imports for advanced LAMMPS python wrapper modules "PyLammps" and "IPyLammps" +from collections import namedtuple +import os +import select +import re + +class lammps(object): # detect if Python is using version of mpi4py that can pass a communicator - + has_mpi4py_v2 = False try: from mpi4py import MPI @@ -32,11 +41,11 @@ class lammps: pass # create instance of LAMMPS - + def __init__(self,name="",cmdargs=None,ptr=None,comm=None): # determine module location - + modpath = dirname(abspath(getsourcefile(lambda:0))) # load liblammps.so unless name is given. @@ -62,12 +71,12 @@ class lammps: # if ptr, then are embedding Python in LAMMPS input script # ptr is the desired instance of LAMMPS # just convert it to ctypes ptr and store in self.lmp - + if not ptr: # with mpi4py v2, can pass MPI communicator to LAMMPS # need to adjust for type of MPI communicator object # allow for int (like MPICH) or void* (like OpenMPI) - + if lammps.has_mpi4py_v2 and comm != None: if lammps.MPI._sizeof(lammps.MPI.Comm) == sizeof(c_int): MPI_Comm = c_int @@ -112,13 +121,16 @@ class lammps: self.lib.lammps_open_no_mpi(0,None,byref(self.lmp)) # could use just this if LAMMPS lib interface supported it # self.lmp = self.lib.lammps_open_no_mpi(0,None) - + else: - self.opened = 0 - # magic to convert ptr to ctypes ptr - pythonapi.PyCObject_AsVoidPtr.restype = c_void_p - pythonapi.PyCObject_AsVoidPtr.argtypes = [py_object] - self.lmp = c_void_p(pythonapi.PyCObject_AsVoidPtr(ptr)) + if isinstance(ptr,lammps): + # magic to convert ptr to ctypes ptr + pythonapi.PyCObject_AsVoidPtr.restype = c_void_p + pythonapi.PyCObject_AsVoidPtr.argtypes = [py_object] + self.lmp = c_void_p(pythonapi.PyCObject_AsVoidPtr(ptr)) + else: + self.lmp = None + raise TypeError('Unsupported type passed as "ptr"') def __del__(self): if self.lmp and self.opened: self.lib.lammps_close(self.lmp) @@ -131,15 +143,15 @@ class lammps: return self.lib.lammps_version(self.lmp) def file(self,file): - file = file.encode() + if file: file = file.encode() self.lib.lammps_file(self.lmp,file) def command(self,cmd): - cmd = cmd.encode() + if cmd: cmd = cmd.encode() self.lib.lammps_command(self.lmp,cmd) def extract_global(self,name,type): - name = name.encode() + if name: name = name.encode() if type == 0: self.lib.lammps_extract_global.restype = POINTER(c_int) elif type == 1: @@ -149,7 +161,7 @@ class lammps: return ptr[0] def extract_atom(self,name,type): - name = name.encode() + if name: name = name.encode() if type == 0: self.lib.lammps_extract_atom.restype = POINTER(c_int) elif type == 1: @@ -163,7 +175,7 @@ class lammps: return ptr def extract_compute(self,id,style,type): - id = id.encode() + if id: id = id.encode() if type == 0: if style > 0: return None self.lib.lammps_extract_compute.restype = POINTER(c_double) @@ -181,9 +193,9 @@ class lammps: # in case of global datum, free memory for 1 double via lammps_free() # double was allocated by library interface function - + def extract_fix(self,id,style,type,i=0,j=0): - id = id.encode() + if id: id = id.encode() if style == 0: self.lib.lammps_extract_fix.restype = POINTER(c_double) ptr = self.lib.lammps_extract_fix(self.lmp,id,style,type,i,j) @@ -205,10 +217,10 @@ class lammps: # free memory for 1 double or 1 vector of doubles via lammps_free() # for vector, must copy nlocal returned values to local c_double vector # memory was allocated by library interface function - + def extract_variable(self,name,group,type): - name = name.encode() - group = group.encode() + if name: name = name.encode() + if group: group = group.encode() if type == 0: self.lib.lammps_extract_variable.restype = POINTER(c_double) ptr = self.lib.lammps_extract_variable(self.lmp,name,group) @@ -230,21 +242,28 @@ class lammps: # set variable value # value is converted to string # returns 0 for success, -1 if failed - + def set_variable(self,name,value): - name = name.encode() - value = str(value).encode() + if name: name = name.encode() + if value: value = str(value).encode() return self.lib.lammps_set_variable(self.lmp,name,str(value)) + # return current value of thermo keyword + + def get_thermo(self,name): + if name: name = name.encode() + self.lib.lammps_get_thermo.restype = c_double + return self.lib.lammps_get_thermo(self.lmp,name) + # return total number of atoms in system - + def get_natoms(self): return self.lib.lammps_get_natoms(self.lmp) # return vector of atom properties gathered across procs, ordered by atom ID def gather_atoms(self,name,type,count): - name = name.encode() + if name: name = name.encode() natoms = self.lib.lammps_get_natoms(self.lmp) if type == 0: data = ((count*natoms)*c_int)() @@ -259,7 +278,379 @@ class lammps: # assume vector is of correct type and length, as created by gather_atoms() def scatter_atoms(self,name,type,count,data): - name = name.encode() + if name: name = name.encode() self.lib.lammps_scatter_atoms(self.lmp,name,type,count,data) +################################################################################ +# Alternative Python Wrapper +# Written by Richard Berger +################################################################################ + +class OutputCapture(object): + """ Utility class to capture LAMMPS library output """ + + def __init__(self): + self.stdout_pipe_read, self.stdout_pipe_write = os.pipe() + self.stdout_fd = 1 + + def __enter__(self): + self.stdout = os.dup(self.stdout_fd) + os.dup2(self.stdout_pipe_write, self.stdout_fd) + return self + + def __exit__(self, type, value, tracebac): + os.dup2(self.stdout, self.stdout_fd) + + # check if we have more to read from the pipe + def more_data(self, pipe): + r, _, _ = select.select([pipe], [], [], 0) + return bool(r) + + # read the whole pipe + def read_pipe(self, pipe): + out = "" + while self.more_data(pipe): + out += os.read(pipe, 1024).decode() + return out + + @property + def output(self): + return self.read_pipe(self.stdout_pipe_read) + + +class Variable(object): + def __init__(self, lammps_wrapper_instance, name, style, definition): + self.wrapper = lammps_wrapper_instance + self.name = name + self.style = style + self.definition = definition.split() + + @property + def value(self): + if self.style == 'atom': + return list(self.wrapper.lmp.extract_variable(self.name, "all", 1)) + else: + value = self.wrapper.lmp_print('"${%s}"' % self.name).strip() + try: + return float(value) + except ValueError: + return value + + +class AtomList(object): + def __init__(self, lammps_wrapper_instance): + self.lmp = lammps_wrapper_instance + self.natoms = self.lmp.system.natoms + + def __getitem__(self, index): + return Atom(self.lmp, index + 1) + + +class Atom(object): + def __init__(self, lammps_wrapper_instance, index): + self.lmp = lammps_wrapper_instance + self.index = index + + @property + def id(self): + return int(self.lmp.eval("id[%d]" % self.index)) + + @property + def type(self): + return int(self.lmp.eval("type[%d]" % self.index)) + + @property + def mol(self): + return self.lmp.eval("mol[%d]" % self.index) + + @property + def mass(self): + return self.lmp.eval("mass[%d]" % self.index) + + @property + def position(self): + return (self.lmp.eval("x[%d]" % self.index), + self.lmp.eval("y[%d]" % self.index), + self.lmp.eval("z[%d]" % self.index)) + + @property + def velocity(self): + return (self.lmp.eval("vx[%d]" % self.index), + self.lmp.eval("vy[%d]" % self.index), + self.lmp.eval("vz[%d]" % self.index)) + + @property + def force(self): + return (self.lmp.eval("fx[%d]" % self.index), + self.lmp.eval("fy[%d]" % self.index), + self.lmp.eval("fz[%d]" % self.index)) + + @property + def charge(self): + return self.lmp.eval("q[%d]" % self.index) + + +class PyLammps(object): + """ + More Python-like wrapper for LAMMPS (e.g., for iPython) + See examples/ipython for usage + """ + + def __init__(self,name="",cmdargs=None,ptr=None,comm=None): + if ptr: + if isinstance(ptr,PyLammps): + self.lmp = ptr.lmp + elif isinstance(ptr,lammps): + self.lmp = ptr + else: + self.lmp = None + raise TypeError('Unsupported type passed as "ptr"') + else: + self.lmp = lammps(name=name,cmdargs=cmdargs,ptr=None,comm=comm) + print("LAMMPS output is captured by PyLammps wrapper") + + def __del__(self): + if self.lmp: self.lmp.close() + self.lmp = None + + def close(self): + if self.lmp: self.lmp.close() + self.lmp = None + + def version(self): + return self.lmp.version() + + def file(self,file): + self.lmp.file(file) + + def command(self,cmd): + self.lmp.command(cmd) + + @property + def atoms(self): + return AtomList(self) + + @property + def system(self): + output = self.info("system") + d = self._parse_info_system(output) + return namedtuple('System', d.keys())(*d.values()) + + @property + def communication(self): + output = self.info("communication") + d = self._parse_info_communication(output) + return namedtuple('Communication', d.keys())(*d.values()) + + @property + def computes(self): + output = self.info("computes") + return self._parse_element_list(output) + + @property + def dumps(self): + output = self.info("dumps") + return self._parse_element_list(output) + + @property + def fixes(self): + output = self.info("fixes") + return self._parse_element_list(output) + + @property + def groups(self): + output = self.info("groups") + return self._parse_groups(output) + + @property + def variables(self): + output = self.info("variables") + vars = {} + for v in self._parse_element_list(output): + vars[v['name']] = Variable(self, v['name'], v['style'], v['def']) + return vars + + def eval(self, expr): + value = self.lmp_print('"$(%s)"' % expr).strip() + try: + return float(value) + except ValueError: + return value + + def _split_values(self, line): + return [x.strip() for x in line.split(',')] + + def _get_pair(self, value): + return [x.strip() for x in value.split('=')] + + def _parse_info_system(self, output): + lines = output[6:-2] + system = {} + + for line in lines: + if line.startswith("Units"): + system['units'] = self._get_pair(line)[1] + elif line.startswith("Atom style"): + system['atom_style'] = self._get_pair(line)[1] + elif line.startswith("Atom map"): + system['atom_map'] = self._get_pair(line)[1] + elif line.startswith("Atoms"): + parts = self._split_values(line) + system['natoms'] = int(self._get_pair(parts[0])[1]) + system['ntypes'] = int(self._get_pair(parts[1])[1]) + system['style'] = self._get_pair(parts[2])[1] + elif line.startswith("Kspace style"): + system['kspace_style'] = self._get_pair(line)[1] + elif line.startswith("Dimensions"): + system['dimensions'] = int(self._get_pair(line)[1]) + elif line.startswith("Orthogonal box"): + system['orthogonal_box'] = [float(x) for x in self._get_pair(line)[1].split('x')] + elif line.startswith("Boundaries"): + system['boundaries'] = self._get_pair(line)[1] + elif line.startswith("xlo"): + keys, values = [self._split_values(x) for x in self._get_pair(line)] + for key, value in zip(keys, values): + system[key] = float(value) + elif line.startswith("ylo"): + keys, values = [self._split_values(x) for x in self._get_pair(line)] + for key, value in zip(keys, values): + system[key] = float(value) + elif line.startswith("zlo"): + keys, values = [self._split_values(x) for x in self._get_pair(line)] + for key, value in zip(keys, values): + system[key] = float(value) + elif line.startswith("Molecule type"): + system['molecule_type'] = self._get_pair(line)[1] + elif line.startswith("Bonds"): + parts = self._split_values(line) + system['nbonds'] = int(self._get_pair(parts[0])[1]) + system['nbondtypes'] = int(self._get_pair(parts[1])[1]) + system['bond_style'] = self._get_pair(parts[2])[1] + elif line.startswith("Angles"): + parts = self._split_values(line) + system['nangles'] = int(self._get_pair(parts[0])[1]) + system['nangletypes'] = int(self._get_pair(parts[1])[1]) + system['angle_style'] = self._get_pair(parts[2])[1] + elif line.startswith("Dihedrals"): + parts = self._split_values(line) + system['ndihedrals'] = int(self._get_pair(parts[0])[1]) + system['nangletypes'] = int(self._get_pair(parts[1])[1]) + system['dihedral_style'] = self._get_pair(parts[2])[1] + elif line.startswith("Impropers"): + parts = self._split_values(line) + system['nimpropers'] = int(self._get_pair(parts[0])[1]) + system['nimpropertypes'] = int(self._get_pair(parts[1])[1]) + system['improper_style'] = self._get_pair(parts[2])[1] + + return system + + def _parse_info_communication(self, output): + lines = output[6:-3] + comm = {} + + for line in lines: + if line.startswith("MPI library"): + comm['mpi_version'] = line.split(':')[1].strip() + elif line.startswith("Comm style"): + parts = self._split_values(line) + comm['comm_style'] = self._get_pair(parts[0])[1] + comm['comm_layout'] = self._get_pair(parts[1])[1] + elif line.startswith("Processor grid"): + comm['proc_grid'] = [int(x) for x in self._get_pair(line)[1].split('x')] + elif line.startswith("Communicate velocities for ghost atoms"): + comm['ghost_velocity'] = (self._get_pair(line)[1] == "yes") + elif line.startswith("Nprocs"): + parts = self._split_values(line) + comm['nprocs'] = int(self._get_pair(parts[0])[1]) + comm['nthreads'] = int(self._get_pair(parts[1])[1]) + return comm + + def _parse_element_list(self, output): + lines = output[6:-3] + elements = [] + + for line in lines: + element_info = self._split_values(line.split(':')[1].strip()) + element = {'name': element_info[0]} + for key, value in [self._get_pair(x) for x in element_info[1:]]: + element[key] = value + elements.append(element) + return elements + + def _parse_groups(self, output): + lines = output[6:-3] + groups = [] + group_pattern = re.compile(r"(?P.+) \((?P.+)\)") + + for line in lines: + m = group_pattern.match(line.split(':')[1].strip()) + group = {'name': m.group('name'), 'type': m.group('type')} + groups.append(group) + return groups + + def lmp_print(self, s): + """ needed for Python2 compatibility, since print is a reserved keyword """ + return self.__getattr__("print")(s) + + def __getattr__(self, name): + def handler(*args, **kwargs): + cmd_args = [name] + [str(x) for x in args] + + with OutputCapture() as capture: + self.lmp.command(' '.join(cmd_args)) + output = capture.output + lines = output.splitlines() + + if len(lines) > 1: + return lines + elif len(lines) == 1: + return lines[0] + return None + + return handler + + +class IPyLammps(PyLammps): + """ + iPython wrapper for LAMMPS which adds embedded graphics capabilities + """ + + def __init__(self,name="",cmdargs=None,ptr=None,comm=None): + super(IPyLammps, self).__init__(name=name,cmdargs=cmdargs,ptr=ptr,comm=comm) + + def image(self, filename="snapshot.png", group="all", color="type", diameter="type", + size=None, view=None, center=None, up=None, zoom=1.0): + cmd_args = [group, "image", filename, color, diameter] + + if size: + width = size[0] + height = size[1] + cmd_args += ["size", width, height] + + if view: + theta = view[0] + phi = view[1] + cmd_args += ["view", theta, phi] + + if center: + flag = center[0] + Cx = center[1] + Cy = center[2] + Cz = center[3] + cmd_args += ["center", flag, Cx, Cy, Cz] + + if up: + Ux = up[0] + Uy = up[1] + Uz = up[2] + cmd_args += ["up", Ux, Uy, Uz] + + if zoom: + cmd_args += ["zoom", zoom] + + cmd_args.append("modify backcolor white") + + self.write_dump(*cmd_args) + from IPython.core.display import Image + return Image('snapshot.png')