diff --git a/src/animate.py b/src/animate.py index cb672fd..293c447 100644 --- a/src/animate.py +++ b/src/animate.py @@ -8,10 +8,17 @@ # animate tool +# Imports and external programs + +from __future__ import absolute_import +import sys, os, subprocess, re, glob +from tkinter import * + oneline = "Animate a series of image files" docstr = """ a = animate("image*.png") create GUI to animate set of image files +a = animate("image*.png",1) 2nd arg = sort filenames, 0 = no sort, def = 1 Actions (same as GUI widgets): @@ -45,11 +52,6 @@ a.delay(0.4) set delay slider # delay_value = delay between frames (secs) # delay_msec = delay in millisec -# Imports and external programs - -import sys, os, commands, re, glob -from Tkinter import * -from ImageTk import PhotoImage # Class definition @@ -57,23 +59,24 @@ class animate: # -------------------------------------------------------------------- - def __init__(self,filestr): + def __init__(self,filestr,sortflag=1): self.loop_flag = 0 self.delay_value = 0.0 self.delay_msec = 0 # convert filestr into full list of files - list = str.split(filestr) + flist = str.split(filestr) self.files = [] - for file in list: self.files += glob.glob(file) + for file in flist: self.files += glob.glob(file) self.nframes = len(self.files) - if self.nframes == 0: raise StandardError, "No files to load" + if self.nframes == 0: raise Exception("No files to load") + if sortflag: self.files.sort() # load all images self.images = [] - for i in xrange(self.nframes): + for i in range(self.nframes): self.images.append(PhotoImage(file=self.files[i])) # grab Tk instance from main diff --git a/src/bdump.py b/src/bdump.py index 420c907..9f680c3 100644 --- a/src/bdump.py +++ b/src/bdump.py @@ -8,6 +8,13 @@ # bdump tool +# Imports and external programs + +from __future__ import absolute_import +import sys, subprocess, re, glob, types +import functools +from os import popen + oneline = "Read dump files with bond info" docstr = """ @@ -60,11 +67,6 @@ time,box,atoms,bonds,tris,lines = b.viz(index) return list of viz objects # natoms = # of atoms # atoms[i][j] = 2d array of floats, i = 0 to natoms-1, j = 0 to ncols-1 -# Imports and external programs - -import sys, commands, re, glob, types -from os import popen - try: import numpy as np oldnumeric = False @@ -92,7 +94,7 @@ class bdump: self.flist = [] for word in words: self.flist += glob.glob(word) if len(self.flist) == 0 and len(list) == 1: - raise StandardError,"no bdump file specified" + raise Exception("no bdump file specified") if len(list) == 1: self.increment = 0 @@ -117,26 +119,26 @@ class bdump: 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.snaps.sort(key = functools.cmp_to_key(self.compare_time)) self.cull() self.nsnaps = len(self.snaps) - print "read %d snapshots" % self.nsnaps + print("read %d snapshots" % self.nsnaps) # -------------------------------------------------------------------- # read next snapshot from list of files def next(self): - if not self.increment: raise StandardError,"cannot read incrementally" + if not self.increment: raise Exception("cannot read incrementally") # read next snapshot in current file using eof as pointer # if fail, try next file @@ -183,14 +185,14 @@ class bdump: 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) + floats = list(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 @@ -205,7 +207,7 @@ class bdump: def map(self,*pairs): if len(pairs) % 2 != 0: - raise StandardError, "bdump map() requires pairs of mappings" + raise Exception("bdump map() requires pairs of mappings") for i in range(0,len(pairs),2): j = i + 1 self.names[pairs[j]] = pairs[i]-1 @@ -269,7 +271,7 @@ class bdump: # abs() of type since could be negative bonds = [] - for i in xrange(snap.natoms): + for i in range(snap.natoms): atom = snap.atoms[i] bonds.append([int(atom[id]),abs(int(atom[type])), int(atom[atom1]),int(atom[atom2])]) diff --git a/src/cdata.py b/src/cdata.py index d74a9d0..12495d7 100644 --- a/src/cdata.py +++ b/src/cdata.py @@ -10,6 +10,14 @@ # cdata tool +# Imports and external programs + +from __future__ import print_function, division, absolute_import +import sys, glob +from os import popen +from math import sqrt,pi,cos,sin,fabs +from copy import deepcopy + oneline = "Read, create, manipulate ChemCell data files" docstr = """ @@ -154,13 +162,6 @@ time,box,atoms,bonds,tris,lines = c.viz(index) return list of viz objects # ids = dictionary of IDs that points to object index # objs = list of objects, style = REGION, SURFACE, GROUP, UNION -# Imports and external programs - -import sys, glob -from os import popen -from math import sqrt,pi,cos,sin,fabs -from copy import deepcopy - try: from DEFAULTS import PIZZA_GUNZIP except: PIZZA_GUNZIP = "gunzip" @@ -170,25 +171,25 @@ class cdata: # -------------------------------------------------------------------- - def __init__(self,*list): + def __init__(self,*clist): self.nselect = 1 self.ids = {} self.objs = [] self.random = Random(12345) - if len(list): self.read(*list) + if len(clist): self.read(*clist) # -------------------------------------------------------------------- - def read(self,*list): + def read(self,*inlist): # flist = list of all data file names - words = list[0].split() + words = inlist[0].split() flist = [] for word in words: flist += glob.glob(word) - if len(flist) == 0 and len(list) == 1: - raise StandardError,"no data file specified" + if len(flist) == 0 and len(inlist) == 1: + raise Exception("no data file specified") for file in flist: @@ -210,8 +211,8 @@ class cdata: elif line.find("facets") == 0: flag = "facets" elif line.find("region") == 0: flag = "region" else: - print "unknown line:",line - raise StandardError, "unrecognized ChemCell data file" + print("unknown line:",line) + raise Exception("unrecognized ChemCell data file") # create a surface object from set of triangles or facets @@ -220,26 +221,26 @@ class cdata: nvert = int(nvert) ntri = int(ntri) - if self.ids.has_key(id): - raise StandardError,"ID %s is already in use" % id + if id in self.ids: + raise Exception("ID %s is already in use" % id) f.readline() vertices = [] - for i in xrange(nvert): - list = f.readline().split() - vertices.append([float(value) for value in list[1:]]) + for i in range(nvert): + inlist = f.readline().split() + vertices.append([float(value) for value in inlist[1:]]) f.readline() triangles = [] - for i in xrange(ntri): - list = f.readline().split() - triangles.append([int(value) for value in list[1:]]) + for i in range(ntri): + inlist = f.readline().split() + triangles.append([int(value) for value in inlist[1:]]) if flag == "triangles": f.readline() connections = [] - for i in xrange(ntri): - list = f.readline().split() - connections.append([int(value) for value in list[1:]]) + for i in range(ntri): + inlist = f.readline().split() + connections.append([int(value) for value in inlist[1:]]) else: connections = connect(nvert,ntri,triangles) @@ -256,7 +257,7 @@ class cdata: obj.connections = connections obj.center() - print id, + print(id, end=' ') sys.stdout.flush() # create a group object from list of particles @@ -266,14 +267,14 @@ class cdata: id = words[1] npart = int(words[2]) - if self.ids.has_key(id): - raise StandardError,"ID %s is already in use" % id + if id in self.ids: + raise Exception("ID %s is already in use" % id) f.readline() xyz = [] - for i in xrange(npart): - list = f.readline().split() - xyz.append([float(value) for value in list[1:]]) + for i in range(npart): + inlist = f.readline().split() + xyz.append([float(value) for value in inlist[1:]]) obj = Group() obj.select = 1 @@ -287,7 +288,7 @@ class cdata: obj.xyz = xyz obj.center() - print id, + print(id, end=' ') sys.stdout.flush() # create a region object from ChemCell region command @@ -310,18 +311,18 @@ class cdata: obj.id = id obj.style = REGION - print id, + print(id, end=' ') sys.stdout.flush() f.close() - print + print() # -------------------------------------------------------------------- # create box region def box(self,id,*args): - if self.ids.has_key(id): - raise StandardError,"ID %s is already in use" % id + if id in self.ids: + raise Exception("ID %s is already in use" % id) obj = Box(*args) obj.select = 1 self.ids[id] = len(self.objs) @@ -334,8 +335,8 @@ class cdata: # create sphere region def sphere(self,id,*args): - if self.ids.has_key(id): - raise StandardError,"ID %s is already in use" % id + if id in self.ids: + raise Exception("ID %s is already in use" % id) obj = Sphere(*args) obj.select = 1 self.ids[id] = len(self.objs) @@ -348,8 +349,8 @@ class cdata: # create shell region def shell(self,id,*args): - if self.ids.has_key(id): - raise StandardError,"ID %s is already in use" % id + if id in self.ids: + raise Exception("ID %s is already in use" % id) obj = Shell(*args) obj.select = 1 self.ids[id] = len(self.objs) @@ -362,8 +363,8 @@ class cdata: # create cylinder region def cyl(self,id,*args): - if self.ids.has_key(id): - raise StandardError,"ID %s is already in use" % id + if id in self.ids: + raise Exception("ID %s is already in use" % id) obj = Cylinder(*args) obj.select = 1 self.ids[id] = len(self.objs) @@ -376,8 +377,8 @@ class cdata: # create a capped-cylinder region def cap(self,id,*args): - if self.ids.has_key(id): - raise StandardError,"ID %s is already in use" % id + if id in self.ids: + raise Exception("ID %s is already in use" % id) obj = Capped(*args) obj.select = 1 self.ids[id] = len(self.objs) @@ -392,19 +393,19 @@ class cdata: def q(self,id,*args): obj = self.objs[self.ids[id]] if obj.style != REGION: - raise StandardError,"Can only use q() on a region object" + raise Exception("Can only use q() on a region object") n = 1 for arg in args: cmd = "obj.q%d = arg" % n - exec cmd + exec(cmd) n += 1 # -------------------------------------------------------------------- # create a line object with single line def line(self,id,*args): - if self.ids.has_key(id): - raise StandardError,"ID %s is already in use" % id + if id in self.ids: + raise Exception("ID %s is already in use" % id) obj = Line() obj.select = 1 self.ids[id] = len(self.objs) @@ -420,8 +421,8 @@ class cdata: # create a line object with 12 lines for a box def lbox(self,id,*args): - if self.ids.has_key(id): - raise StandardError,"ID %s is already in use" % id + if id in self.ids: + raise Exception("ID %s is already in use" % id) obj = Line() obj.select = 1 self.ids[id] = len(self.objs) @@ -449,8 +450,8 @@ class cdata: # create a triangulated surface object from a region object def surf(self,id,id_region): - if self.ids.has_key(id): - raise StandardError,"ID %s is already in use" % id + if id in self.ids: + raise Exception("ID %s is already in use" % id) region = self.objs[self.ids[id_region]] region.triangulate() @@ -472,9 +473,9 @@ class cdata: # create a triangulated surface object # from list of tri indices (1-N) in id_surf obj - def surftri(self,id,id_surf,*list): - if self.ids.has_key(id): - raise StandardError,"ID %s is already in use" % id + def surftri(self,id,id_surf,*tlist): + if id in self.ids: + raise Exception("ID %s is already in use" % id) o = self.objs[self.ids[id_surf]] @@ -491,7 +492,7 @@ class cdata: # subtract 1 from tri and vert to convert to C indexing from (1-N) - for i in list: + for i in tlist: v1 = o.triangles[i-1][0] v2 = o.triangles[i-1][1] v3 = o.triangles[i-1][2] @@ -512,8 +513,8 @@ class cdata: # from subset of tris in id_surf obj that meet test string def surfselect(self,id,id_surf,teststr): - if self.ids.has_key(id): - raise StandardError,"ID %s is already in use" % id + if id in self.ids: + raise Exception("ID %s is already in use" % id) o = self.objs[self.ids[id_surf]] @@ -552,9 +553,13 @@ class cdata: v1 = tri[0] - 1 v2 = tri[1] - 1 v3 = tri[2] - 1 - exec ccmd1 - exec ccmd2 - exec ccmd3 + ldict = {'o':o,'v1':v1,'v2':v2,'v3':v3} + exec(ccmd1,globals(),ldict) + flag1 = ldict['flag1'] + exec(ccmd2,globals(),ldict) + flag2 = ldict['flag2'] + exec(ccmd3,globals(),ldict) + flag3 = ldict['flag3'] if flag1 and flag2 and flag3: obj.vertices.append(o.vertices[v1][:]) obj.vertices.append(o.vertices[v2][:]) @@ -574,7 +579,7 @@ class cdata: def bins(self,id,nx,ny): obj = self.objs[self.ids[id]] if obj.style != SURFACE: - raise StandardError,"Can only set bins for surface" + raise Exception("Can only set bins for surface") obj.nbinx = nx obj.nbiny = ny @@ -583,8 +588,8 @@ class cdata: # use inside and outside as constraints on particle coords def part(self,id,npart,in_id,out_id=None): - if self.ids.has_key(id): - raise StandardError,"ID %s is already in use" % id + if id in self.ids: + raise Exception("ID %s is already in use" % id) obj = Group() obj.select = 1 @@ -625,14 +630,14 @@ class cdata: count += 1 obj.center() - print "Created %d particles in %d attempts" % (count,attempt) + print("Created %d particles in %d attempts" % (count,attempt)) # -------------------------------------------------------------------- # create a group object with npart 2d particles on surface of on_id object def part2d(self,id,npart,on_id): - if self.ids.has_key(id): - raise StandardError,"ID %s is already in use" % id + if id in self.ids: + raise Exception("ID %s is already in use" % id) obj = Group() obj.select = 1 @@ -647,16 +652,16 @@ class cdata: on_obj = self.objs[self.ids[on_id]] if on_obj.style != SURFACE and on_obj.style != REGION and \ on_obj.style != UNION: - raise StandardError,"Illegal ID to place particles on" + raise Exception("Illegal ID to place particles on") totalarea = on_obj.area() - for count in xrange(npart): + for count in range(npart): area = self.random() * totalarea pt,norm = on_obj.loc2d(area,self.random) obj.xyz.append(pt) obj.center() - print "Created %d particles on area of %g" % (npart,totalarea) + print("Created %d particles on area of %g" % (npart,totalarea)) # -------------------------------------------------------------------- # create a 3d array of particles @@ -665,8 +670,8 @@ class cdata: # array spacing = dx,dy,dz def partarray(self,id,nx,ny,nz,x,y,z,dx,dy,dz): - if self.ids.has_key(id): - raise StandardError,"ID %s is already in use" % id + if id in self.ids: + raise Exception("ID %s is already in use" % id) obj = Group() obj.select = 1 @@ -678,16 +683,16 @@ class cdata: obj.npart = nx * ny * nz obj.xyz = [] - for k in xrange(nz): + for k in range(nz): znew = z + k*dz - for j in xrange(ny): + for j in range(ny): ynew = y + j*dy - for i in xrange(nx): + for i in range(nx): xnew = x + i*dx obj.xyz.append([xnew,ynew,znew]) obj.center() - print "Created %d particles" % (nx*ny*nz) + print("Created %d particles" % (nx*ny*nz)) # -------------------------------------------------------------------- # create a ring of N particles @@ -695,8 +700,8 @@ class cdata: # ring axis = 'x' or 'y' or 'z' def partring(self,id,n,x,y,z,r,axis): - if self.ids.has_key(id): - raise StandardError,"ID %s is already in use" % id + if id in self.ids: + raise Exception("ID %s is already in use" % id) obj = Group() obj.select = 1 @@ -709,7 +714,7 @@ class cdata: obj.xyz = [] deltheta = 2.0*pi / n - for i in xrange(n): + for i in range(n): if axis == 'x': xnew = x ynew = y + r * cos(i*deltheta) @@ -725,7 +730,7 @@ class cdata: obj.xyz.append([xnew,ynew,znew]) obj.center() - print "Created %d particles" % n + print("Created %d particles" % n) # -------------------------------------------------------------------- # change surface assignment for a 2d group of particles @@ -733,9 +738,9 @@ class cdata: def partsurf(self,id,on_id): obj = self.objs[self.ids[id]] if obj.style != GROUP: - raise StandardError,"Must use particle group with partsurf()" + raise Exception("Must use particle group with partsurf()") if obj.on_id == "": - raise StandardError,"Must use partsurf() with 2d particles" + raise Exception("Must use partsurf() with 2d particles") obj.on_id = on_id # -------------------------------------------------------------------- @@ -750,7 +755,7 @@ class cdata: def random(self,id): obj = self.objs[self.ids[id]] if obj.style != SURFACE and obj.style != REGION: - raise StandardError,"Must use surf or region with random()" + raise Exception("Must use surf or region with random()") totalarea = obj.area() area = self.random() * totalarea @@ -766,10 +771,10 @@ class cdata: def project(self,id,id2,dx,dy,dz,EPS,flag=None): obj = self.objs[self.ids[id]] if obj.style != GROUP: - raise StandardError,"Must use particle group as 1st obj of project()" + raise Exception("Must use particle group as 1st obj of project()") obj_on = self.objs[self.ids[id2]] if obj_on.style != SURFACE and obj_on.style != REGION: - raise StandardError,"Must use surf or region as 2nd obj of project()" + raise Exception("Must use surf or region as 2nd obj of project()") # pre-process SURFACE to bin its triangles for faster searching @@ -783,7 +788,7 @@ class cdata: factor = 2 maxscale = 10.0 - for i in xrange(obj.npart): + for i in range(obj.npart): x,y,z = obj.xyz[i] if flag: dir = [dx-x,dy-y,dz-z] else: dir = [dx,dy,dz] @@ -814,7 +819,7 @@ class cdata: scale *= factor if bracket == start: - raise StandardError,"Could not find bracket point for particle %d" % i + raise Exception("Could not find bracket point for particle %d" % i) # bisection search to zoom in to within EPS of surface # separation = distance between 2 points @@ -846,7 +851,7 @@ class cdata: def center(self,id,x,y,z): obj = self.objs[self.ids[id]] if obj.style != SURFACE and obj.style != GROUP: - raise StandardError,"Can only use center() on a surface or group object" + raise Exception("Can only use center() on a surface or group object") obj.center(x,y,z) # -------------------------------------------------------------------- @@ -856,7 +861,7 @@ class cdata: def trans(self,id,dx,dy,dz): obj = self.objs[self.ids[id]] if obj.style != SURFACE and obj.style != GROUP: - raise StandardError,"Can only use trans() on a surface or group object" + raise Exception("Can only use trans() on a surface or group object") obj.xc += dx obj.yc += dy obj.zc += dz @@ -864,12 +869,12 @@ class cdata: # apply translation to each vertex or part coord if obj.style == SURFACE: - for i in xrange(obj.nvert): + for i in range(obj.nvert): obj.vertices[i][0] += dx obj.vertices[i][1] += dy obj.vertices[i][2] += dz elif obj.style == GROUP: - for i in xrange(obj.npart): + for i in range(obj.npart): obj.xyz[i][0] += dx obj.xyz[i][1] += dy obj.xyz[i][2] += dz @@ -886,7 +891,7 @@ class cdata: def rotate(self,id,axis1,i1,j1,k1,axis2,i2,j2,k2): obj = self.objs[self.ids[id]] if obj.style != SURFACE and obj.style != GROUP: - raise StandardError,"Can only use rotate() on a surface or group object" + raise Exception("Can only use rotate() on a surface or group object") # create xyz old and new @@ -894,15 +899,15 @@ class cdata: if axis1 == 'x': xnew = [i1,j1,k1] elif axis1 == 'y': ynew = [i1,j1,k1] elif axis1 == 'z': znew = [i1,j1,k1] - else: raise StandardError,"Illegal rotate arguments" + else: raise Exception("Illegal rotate arguments") if axis2 == 'x': xnew = [i2,j2,k2] elif axis2 == 'y': ynew = [i2,j2,k2] elif axis2 == 'z': znew = [i2,j2,k2] - else: raise StandardError,"Illegal rotate arguments" + else: raise Exception("Illegal rotate arguments") if not xnew: xnew = cross(ynew,znew) elif not ynew: ynew = cross(znew,xnew) elif not znew: znew = cross(xnew,ynew) - else: raise StandardError,"Illegal rotate arguments" + else: raise Exception("Illegal rotate arguments") normalize(xnew) normalize(ynew) normalize(znew) @@ -910,7 +915,7 @@ class cdata: # apply rotation matrix of direction cosines to each vertex or part coord if obj.style == SURFACE: - for i in xrange(obj.nvert): + for i in range(obj.nvert): x = obj.vertices[i][0] - obj.xc y = obj.vertices[i][1] - obj.yc z = obj.vertices[i][2] - obj.zc @@ -921,7 +926,7 @@ class cdata: obj.vertices[i][1] = yn + obj.yc obj.vertices[i][2] = zn + obj.zc elif obj.style == GROUP: - for i in xrange(obj.npart): + for i in range(obj.npart): x = obj.xyz[i][0] - obj.xc y = obj.xyz[i][1] - obj.yc z = obj.xyz[i][2] - obj.zc @@ -939,14 +944,14 @@ class cdata: def scale(self,id,sx,sy,sz): obj = self.objs[self.ids[id]] if obj.style != SURFACE and obj.style != GROUP: - raise StandardError,"Can only use scale() on a surface or group object" + raise Exception("Can only use scale() on a surface or group object") if obj.style == SURFACE: - for i in xrange(obj.nvert): + for i in range(obj.nvert): obj.vertices[i][0] = obj.xc + sx * (obj.vertices[i][0] - obj.xc) obj.vertices[i][1] = obj.yc + sy * (obj.vertices[i][1] - obj.yc) obj.vertices[i][2] = obj.zc + sz * (obj.vertices[i][2] - obj.zc) elif obj.style == GROUP: - for i in xrange(obj.npart): + for i in range(obj.npart): obj.xyz[i][0] = obj.xc + sx * (obj.xyz[i][0] - obj.xc) obj.xyz[i][1] = obj.yc + sy * (obj.xyz[i][1] - obj.yc) obj.xyz[i][2] = obj.zc + sz * (obj.xyz[i][2] - obj.zc) @@ -954,10 +959,10 @@ class cdata: # -------------------------------------------------------------------- # create union object from list of other objects - def union(self,id,*list): - if self.ids.has_key(id): - raise StandardError,"ID %s is already in use" % id - obj = Union(self.ids,self.objs,*list) + def union(self,id,*objlist): + if id in self.ids: + raise Exception("ID %s is already in use" % id) + obj = Union(self.ids,self.objs,*objlist) obj.select = 1 self.ids[id] = len(self.objs) self.objs.append(obj) @@ -968,12 +973,12 @@ class cdata: # join objects in list to form a new object # only possible for group, surface, line objects - def join(self,id,*list): - style = self.objs[self.ids[list[0]]].style + def join(self,id,*objlist): + style = self.objs[self.ids[objlist[0]]].style if style == GROUP: obj = Group() elif style == SURFACE: obj = Surface() elif style == LINE: obj = Line() - else: raise StandardError,"Cannot perform join on these object styles" + else: raise Exception("Cannot perform join on these object styles") obj.select = 1 self.ids[id] = len(self.objs) self.objs.append(obj) @@ -981,7 +986,7 @@ class cdata: obj.style = style if style == GROUP: - obj.on_id = self.objs[self.ids[list[0]]].on_id + obj.on_id = self.objs[self.ids[objlist[0]]].on_id obj.npart = 0 obj.xyz = [] elif style == SURFACE: @@ -993,17 +998,17 @@ class cdata: obj.nline = 0 obj.pairs = [] - for id in list: + for id in objlist: o = self.objs[self.ids[id]] if o.style != style: - raise StandardError,"All joined objects must be of same style" + raise Exception("All joined objects must be of same style") # force deep copy of particle coords if style == GROUP: if o.on_id != obj.on_id: - raise StandardError,"Particle group surfaces do not match" - for i in xrange(o.npart): + raise Exception("Particle group surfaces do not match") + for i in range(o.npart): xyz = o.xyz[i][:] obj.xyz.append(xyz) obj.npart += o.npart @@ -1013,10 +1018,10 @@ class cdata: # increment vertex and triangle indices b/c now have previous surfaces elif style == SURFACE: - for i in xrange(o.nvert): + for i in range(o.nvert): vert = o.vertices[i][:] obj.vertices.append(vert) - for i in xrange(o.ntri): + for i in range(o.ntri): tri = [iv+obj.nvert for iv in o.triangles[i]] obj.triangles.append(tri) connect = o.connections[i][:] @@ -1039,12 +1044,12 @@ class cdata: # delete each object in list # reset values in ids since some indices are decremented - def delete(self,*list): - for id in list: + def delete(self,*objlist): + for id in objlist: i = self.ids[id] del self.ids[id] del self.objs[i] - for key in self.ids.keys(): + for key in list(self.ids.keys()): j = self.ids[key] if j > i: self.ids[key] = j-1 @@ -1054,8 +1059,8 @@ class cdata: def rename(self,idold,idnew): i = self.ids[idold] - if self.ids.has_key(idnew): - raise StandardError,"ID %s is already in use" % id + if idnew in self.ids: + raise Exception("ID %s is already in use" % id) self.ids[idnew] = i self.objs[i].id = idnew del self.ids[idold] @@ -1067,8 +1072,8 @@ class cdata: def copy(self,idold,idnew): obj = deepcopy(self.objs[self.ids[idold]]) obj.select = 1 - if self.ids.has_key(idnew): - raise StandardError,"ID %s is already in use" % id + if idnew in self.ids: + raise Exception("ID %s is already in use" % id) self.ids[idnew] = len(self.objs) self.objs.append(obj) obj.id = idnew @@ -1077,9 +1082,9 @@ class cdata: # set selection flag for each object in list # if list is empty, select all - def select(self,*list): - if len(list) == 0: list = self.ids.keys() - for id in list: + def select(self,*objlist): + if len(objlist) == 0: objlist = list(self.ids.keys()) + for id in objlist: obj = self.objs[self.ids[id]] obj.select = 1 @@ -1087,9 +1092,9 @@ class cdata: # unset selection flag for each object in list # if list is empty, unselect all - def unselect(self,*list): - if len(list) == 0: list = self.ids.keys() - for id in list: + def unselect(self,*objlist): + if len(objlist) == 0: objlist = list(self.ids.keys()) + for id in objlist: obj = self.objs[self.ids[id]] obj.select = 0 @@ -1097,11 +1102,11 @@ class cdata: # write out list of objects to data file via filewrite() # open a new file - def write(self,file,*list): - if not len(list): vlist = range(len(self.objs)) + def write(self,file,*objlist): + if not len(objlist): vlist = list(range(len(self.objs))) else: vlist = [] - for id in list: vlist.append(self.ids[id]) + for id in objlist: vlist.append(self.ids[id]) fp = open(file,'w') self.filewrite(fp,vlist) @@ -1111,11 +1116,11 @@ class cdata: # append list of objects to data file via filewrite() # open existing file for appending - def append(self,file,*list): - if not len(list): vlist = range(len(self.objs)) + def append(self,file,*objlist): + if not len(objlist): vlist = list(range(len(self.objs))) else: vlist = [] - for id in list: vlist.append(self.ids[id]) + for id in objlist: vlist.append(self.ids[id]) fp = open(file,'a') self.filewrite(fp,vlist) @@ -1131,30 +1136,30 @@ class cdata: if not obj.select: continue if obj.style == GROUP: if not obj.on_id: - print >>fp,"particles %s %d" % (obj.id,obj.npart) + print("particles %s %d" % (obj.id,obj.npart), file=fp) else: - print >>fp,"particles %s %d %s" % (obj.id,obj.npart,obj.on_id) - print >>fp - for i in xrange(obj.npart): - print >>fp,i+1,obj.xyz[i][0],obj.xyz[i][1],obj.xyz[i][2] - print >>fp + print("particles %s %d %s" % (obj.id,obj.npart,obj.on_id), file=fp) + print(file=fp) + for i in range(obj.npart): + print(i+1,obj.xyz[i][0],obj.xyz[i][1],obj.xyz[i][2], file=fp) + print(file=fp) if obj.style == SURFACE: - print >>fp,"triangles %s %d %d" % (obj.id,obj.nvert,obj.ntri) - print >>fp - for i in xrange(obj.nvert): - print >>fp,i+1,obj.vertices[i][0],obj.vertices[i][1], \ - obj.vertices[i][2] - print >>fp - for i in xrange(obj.ntri): - print >>fp,i+1,obj.triangles[i][0],obj.triangles[i][1], \ - obj.triangles[i][2] - print >>fp - for i in xrange(obj.ntri): - print >>fp,i+1,obj.connections[i][0],obj.connections[i][1], \ + print("triangles %s %d %d" % (obj.id,obj.nvert,obj.ntri), file=fp) + print(file=fp) + for i in range(obj.nvert): + print(i+1,obj.vertices[i][0],obj.vertices[i][1], \ + obj.vertices[i][2], file=fp) + print(file=fp) + for i in range(obj.ntri): + print(i+1,obj.triangles[i][0],obj.triangles[i][1], \ + obj.triangles[i][2], file=fp) + print(file=fp) + for i in range(obj.ntri): + print(i+1,obj.connections[i][0],obj.connections[i][1], \ obj.connections[i][2],obj.connections[i][3], \ - obj.connections[i][4],obj.connections[i][5] + obj.connections[i][4],obj.connections[i][5], file=fp) if obj.style == REGION: - print >>fp,"region %s" % obj.command() + print("region %s" % obj.command(), file=fp) # -------------------------------------------------------------------- # iterator called from other tools @@ -1168,7 +1173,7 @@ class cdata: def viz(self,isnap): if isnap: - raise StandardError, "cannot call cdata.viz() with isnap != 0" + raise Exception("cannot call cdata.viz() with isnap != 0") # create atom list from sum of all particle groups # id = running count @@ -1227,7 +1232,7 @@ class cdata: def findtime(self,n): if n == 0: return 0 - raise StandardError, "no step %d exists" % (n) + raise Exception("no step %d exists" % (n)) # -------------------------------------------------------------------- # return box size @@ -1285,7 +1290,7 @@ class Random: self.seed = seed def __call__(self): - k = self.seed/IQ + k = self.seed//IQ self.seed = IA*(self.seed-k*IQ) - IR*k if self.seed < 0: self.seed += IM return AM*self.seed @@ -1344,16 +1349,16 @@ class Surface: self.dxinv = 1.0 / (xsize / self.nbinx + EPSILON) self.dyinv = 1.0 / (ysize / self.nbiny + EPSILON) - print "Binning %d triangles into %d by %d bins ..." % \ - (self.ntri,self.nbinx,self.nbiny) + print("Binning %d triangles into %d by %d bins ..." % \ + (self.ntri,self.nbinx,self.nbiny)) self.bin = [] - for i in xrange(self.nbinx): + for i in range(self.nbinx): self.bin.append(self.nbiny*[0]) - for j in xrange(self.nbiny): + for j in range(self.nbiny): self.bin[i][j] = [] - for m in xrange(self.ntri): + for m in range(self.ntri): v1 = self.vertices[self.triangles[m][0]-1] v2 = self.vertices[self.triangles[m][1]-1] v3 = self.vertices[self.triangles[m][2]-1] @@ -1365,11 +1370,11 @@ class Surface: ihi = int((xmax - self.xlo) * self.dxinv) jlo = int((ymin - self.ylo) * self.dyinv) jhi = int((ymax - self.ylo) * self.dyinv) - for i in xrange(ilo,ihi+1): - for j in xrange(jlo,jhi+1): + for i in range(ilo,ihi+1): + for j in range(jlo,jhi+1): self.bin[i][j].append(m) - print "Done with binning" + print("Done with binning") # check for inside assumes that surf is a closed set of triangles # consider a line segment from x,y,z to x,y,INF @@ -1390,7 +1395,7 @@ class Surface: n = len(self.bin[ix][iy]) hit = 0 - for m in xrange(n): + for m in range(n): itri = self.bin[ix][iy][m] tri = self.triangles[itri] @@ -1465,7 +1470,7 @@ class Surface: # return a random location on one of triangles def loc2d(self,area,random): - for i in xrange(self.ntri): + for i in range(self.ntri): if area < self.areas[i]: break v1 = self.vertices[self.triangles[i][0]-1] v2 = self.vertices[self.triangles[i][1]-1] @@ -1479,23 +1484,23 @@ class Surface: x = v1[0] + r1*(v2[0] - v1[0]) + r2*(v3[0] - v2[0]) y = v1[1] + r1*(v2[1] - v1[1]) + r2*(v3[1] - v2[1]) z = v1[2] + r1*(v2[2] - v1[2]) + r2*(v3[2] - v2[2]) - list = v1 + v2 + v3 - return [x,y,z],normal(list[0:3],list[3:6],list[6:9]) + vlist = v1 + v2 + v3 + return [x,y,z],normal(vlist[0:3],vlist[3:6],vlist[6:9]) # -------------------------------------------------------------------- # group of particles class Group: def bbox(self): - list = [xyz[0] for xyz in self.xyz] - xlo = min(list) - xhi = max(list) - list = [xyz[1] for xyz in self.xyz] - ylo = min(list) - yhi = max(list) - list = [xyz[2] for xyz in self.xyz] - zlo = min(list) - zhi = max(list) + xyzlist = [xyz[0] for xyz in self.xyz] + xlo = min(xyzlist) + xhi = max(xyzlist) + xyzlist = [xyz[1] for xyz in self.xyz] + ylo = min(xyzlist) + yhi = max(xyzlist) + xyzlist = [xyz[2] for xyz in self.xyz] + zlo = min(xyzlist) + zhi = max(xyzlist) return (xlo,ylo,zlo,xhi,yhi,zhi) @@ -1516,13 +1521,13 @@ class Group: # box region class Box: - def __init__(self,*list): - self.xlo = float(list[0]) - self.ylo = float(list[1]) - self.zlo = float(list[2]) - self.xhi = float(list[3]) - self.yhi = float(list[4]) - self.zhi = float(list[5]) + def __init__(self,*blist): + self.xlo = float(blist[0]) + self.ylo = float(blist[1]) + self.zlo = float(blist[2]) + self.xhi = float(blist[3]) + self.yhi = float(blist[4]) + self.zhi = float(blist[5]) self.q1 = self.q2 = self.q3 = 1 # bounding box around region @@ -1548,13 +1553,13 @@ class Box: self.nvert = len(vertices) self.ntri = len(triangles) self.vertices = [] - for i in xrange(self.nvert): + for i in range(self.nvert): v1 = self.xlo + vertices[i][0]*(self.xhi-self.xlo) v2 = self.ylo + vertices[i][1]*(self.yhi-self.ylo) v3 = self.zlo + vertices[i][2]*(self.zhi-self.zlo) self.vertices.append([v1,v2,v3]) self.triangles = [] - for i in xrange(self.ntri): + for i in range(self.ntri): self.triangles.append([triangles[i][0],triangles[i][1],triangles[i][2]]) self.connections = connect(self.nvert,self.ntri,self.triangles) @@ -1610,11 +1615,11 @@ class Box: # sphere region class Sphere: - def __init__(self,*list): - self.x = float(list[0]) - self.y = float(list[1]) - self.z = float(list[2]) - self.r = float(list[3]) + def __init__(self,*slist): + self.x = float(slist[0]) + self.y = float(slist[1]) + self.z = float(slist[2]) + self.r = float(slist[3]) self.rsq = self.r*self.r self.q1 = 2 @@ -1645,7 +1650,7 @@ class Sphere: self.nvert = len(vertices) self.ntri = len(triangles) self.vertices = [] - for i in xrange(self.nvert): + for i in range(self.nvert): v1 = vertices[i][0] - 0.5 v2 = vertices[i][1] - 0.5 v3 = vertices[i][2] - 0.5 @@ -1656,7 +1661,7 @@ class Sphere: c[2] = self.z + self.r*c[2] self.vertices.append(c) self.triangles = [] - for i in xrange(self.ntri): + for i in range(self.ntri): self.triangles.append([triangles[i][0],triangles[i][1],triangles[i][2]]) self.connections = connect(self.nvert,self.ntri,self.triangles) @@ -1689,8 +1694,8 @@ class Sphere: # loc2d is only only outer surface, inherited from Sphere class Shell(Sphere): - def __init__(self,*list): - self.rinner = float(list[4]) + def __init__(self,*slist): + self.rinner = float(slist[4]) self.innersq = self.rinner*self.rinner def inside(self,x,y,z): @@ -1709,13 +1714,13 @@ class Shell(Sphere): # cylinder region class Cylinder: - def __init__(self,*list): - self.axis = list[0] - self.c1 = list[1] - self.c2 = list[2] - self.r = list[3] - self.lo = list[4] - self.hi = list[5] + def __init__(self,*clist): + self.axis = clist[0] + self.c1 = clist[1] + self.c2 = clist[2] + self.r = clist[3] + self.lo = clist[4] + self.hi = clist[5] self.rsq = self.r*self.r self.q1 = 2 self.q2 = 1 @@ -1764,7 +1769,7 @@ class Cylinder: self.nvert = len(vertices) self.ntri = len(triangles) self.vertices = [] - for i in xrange(self.nvert): + for i in range(self.nvert): v1 = vertices[i][0] - 0.5 v2 = vertices[i][1] - 0.5 v3 = vertices[i][2] @@ -1781,7 +1786,7 @@ class Cylinder: elif self.axis == 'y': self.vertices.append([p1,p3,p2]) elif self.axis == 'z': self.vertices.append([p1,p2,p3]) self.triangles = [] - for i in xrange(self.ntri): + for i in range(self.ntri): self.triangles.append([triangles[i][0],triangles[i][1],triangles[i][2]]) self.connections = connect(self.nvert,self.ntri,self.triangles) @@ -1852,13 +1857,13 @@ class Cylinder: # capped-cylinder region class Capped: - def __init__(self,*list): - self.axis = list[0] - self.c1 = list[1] - self.c2 = list[2] - self.r = list[3] - self.lo = list[4] - self.hi = list[5] + def __init__(self,*clist): + self.axis = clist[0] + self.c1 = clist[1] + self.c2 = clist[2] + self.r = clist[3] + self.lo = clist[4] + self.hi = clist[5] self.rsq = self.r*self.r self.q1 = 2 self.q2 = 1 @@ -1908,14 +1913,14 @@ class Capped: # convert tuples returned by box_triangluate (used for dict lookup) to lists def triangulate(self): - if self.q1 % 2: raise StandardError,"Capped cylinder q1 must be even" + if self.q1 % 2: raise Exception("Capped cylinder q1 must be even") vertices,triangles = box_triangulate(self.q1,self.q1,self.q2+self.q1) self.nvert = len(vertices) self.ntri = len(triangles) self.vertices = [] cutlo = self.q1/2 * 1.0/(self.q2+self.q1) + EPSILON cuthi = 1.0 - cutlo - for i in xrange(self.nvert): + for i in range(self.nvert): v1 = vertices[i][0] v2 = vertices[i][1] v3 = vertices[i][2] @@ -1941,7 +1946,7 @@ class Capped: elif self.axis == 'y': self.vertices.append([p1,p3,p2]) elif self.axis == 'z': self.vertices.append([p1,p2,p3]) self.triangles = [] - for i in xrange(self.ntri): + for i in range(self.ntri): self.triangles.append([triangles[i][0],triangles[i][1],triangles[i][2]]) self.connections = connect(self.nvert,self.ntri,self.triangles) @@ -2031,18 +2036,18 @@ class Capped: class Line: def bbox(self): - list = [pair[0] for pair in self.pairs] - list += [pair[3] for pair in self.pairs] - xlo = min(list) - xhi = max(list) - list = [pair[1] for pair in self.pairs] - list += [pair[4] for pair in self.pairs] - ylo = min(list) - yhi = max(list) - list = [pair[2] for pair in self.pairs] - list += [pair[5] for pair in self.pairs] - zlo = min(list) - zhi = max(list) + plist = [pair[0] for pair in self.pairs] + plist += [pair[3] for pair in self.pairs] + xlo = min(plist) + xhi = max(plist) + plist = [pair[1] for pair in self.pairs] + plist += [pair[4] for pair in self.pairs] + ylo = min(plist) + yhi = max(plist) + plist = [pair[2] for pair in self.pairs] + plist += [pair[5] for pair in self.pairs] + zlo = min(plist) + zhi = max(plist) return (xlo,ylo,zlo,xhi,yhi,zhi) def addline(self,coords): @@ -2054,12 +2059,12 @@ class Line: # self.objs = list of child objects class Union: - def __init__(self,ids,objs,*list): + def __init__(self,ids,objs,*ulist): self.objs = [] - for id in list: + for id in ulist: obj = objs[ids[id]] if obj.style != SURFACE and obj.style != REGION and obj.style != UNION: - raise StandardError,"Union child object is of invalid style" + raise Exception("Union child object is of invalid style") self.objs.append(obj) # bounding box around all child objects @@ -2098,7 +2103,7 @@ class Union: # return a random location on surface of one of child objects def loc2d(self,area,random): - for i in xrange(len(self.objs)): + for i in range(len(self.objs)): if area < self.areas[i]: break if i > 0: area -= self.areas[i] return self.objs[i].loc2d(area,random) @@ -2158,15 +2163,15 @@ def connect(nvert,ntri,triangles): # create inverted v2tri where each vertex has list of triangles it is in v2tri = [] - for i in xrange(nvert): v2tri.append([]); + for i in range(nvert): v2tri.append([]); - for i in xrange(ntri): + for i in range(ntri): for vert in triangles[i]: v2tri[vert-1].append(i) # loop over triangles to reset connections connections = [] - for i in xrange(ntri): + for i in range(ntri): # zero connections @@ -2223,7 +2228,7 @@ def connect(nvert,ntri,triangles): # return index of where v is in vertices list def vertex(v,vertices,vdict): - if vdict.has_key(v): return vdict[v] + if v in vdict: return vdict[v] n = len(vertices) vertices.append(v) vdict[v] = n @@ -2241,8 +2246,8 @@ def box_triangulate(q1,q2,q3): vdict = {} vertices = [] triangles = [] - for j in xrange(q2): - for k in xrange(q3): + for j in range(q2): + for k in range(q3): v1 = (0, j*dy, k*dz) v2 = (0, (j+1)*dy, k*dz) v3 = (0, (j+1)*dy, (k+1)*dz) @@ -2263,8 +2268,8 @@ def box_triangulate(q1,q2,q3): iv4 = vertex(v4,vertices,vdict) triangles.append([iv1+1,iv2+1,iv3+1]) triangles.append([iv1+1,iv3+1,iv4+1]) - for i in xrange(q1): - for k in xrange(q3): + for i in range(q1): + for k in range(q3): v1 = (i*dx, 0, k*dz) v2 = ((i+1)*dx, 0, k*dz) v3 = ((i+1)*dx, 0, (k+1)*dz) @@ -2285,8 +2290,8 @@ def box_triangulate(q1,q2,q3): iv4 = vertex(v4,vertices,vdict) triangles.append([iv1+1,iv3+1,iv2+1]) triangles.append([iv1+1,iv4+1,iv3+1]) - for i in xrange(q1): - for j in xrange(q2): + for i in range(q1): + for j in range(q2): v1 = (i*dx, j*dy, 0) v2 = ((i+1)*dx, j*dy, 0) v3 = ((i+1)*dx, (j+1)*dy, 0) diff --git a/src/cfg.py b/src/cfg.py index bbd930e..4c17579 100644 --- a/src/cfg.py +++ b/src/cfg.py @@ -8,6 +8,11 @@ # cfg tool +# Imports and external programs + +from __future__ import absolute_import +import sys + oneline = "Convert LAMMPS snapshots to AtomEye CFG format" docstr = """ @@ -34,10 +39,6 @@ c.single(N,"file") write snapshot for timestep N to file.cfg # Variables # data = data file to read from -# Imports and external programs - -import sys - # Class definition class cfg: @@ -65,18 +66,18 @@ class cfg: ylen = box[4]-box[1] zlen = box[5]-box[2] - print >>f,"Number of particles = %d " % len(atoms) - print >>f,"# Timestep %d \n#\nA = 1.0 Angstrom" % time - print >>f,"H0(1,1) = %20.10f A " % xlen - print >>f,"H0(1,2) = 0.0 A " - print >>f,"H0(1,3) = 0.0 A " - print >>f,"H0(2,1) = 0.0 A " - print >>f,"H0(2,2) = %20.10f A " % ylen - print >>f,"H0(2,3) = 0.0 A " - print >>f,"H0(3,1) = 0.0 A " - print >>f,"H0(3,2) = 0.0 A " - print >>f,"H0(3,3) = %20.10f A " % zlen - print >>f,"#" + print("Number of particles = %d " % len(atoms), file=f) + print("# Timestep %d \n#\nA = 1.0 Angstrom" % time, file=f) + print("H0(1,1) = %20.10f A " % xlen, file=f) + print("H0(1,2) = 0.0 A ", file=f) + print("H0(1,3) = 0.0 A ", file=f) + print("H0(2,1) = 0.0 A ", file=f) + print("H0(2,2) = %20.10f A " % ylen, file=f) + print("H0(2,3) = 0.0 A ", file=f) + print("H0(3,1) = 0.0 A ", file=f) + print("H0(3,2) = 0.0 A ", file=f) + print("H0(3,3) = %20.10f A " % zlen, file=f) + print("#", file=f) for atom in atoms: itype = int(atom[1]) @@ -84,14 +85,14 @@ class cfg: yfrac = (atom[3]-box[1])/ylen zfrac = (atom[4]-box[2])/zlen # print >>f,"1.0 %d %15.10f %15.10f %15.10f %15.10f %15.10f %15.10f " % (itype,xfrac,yfrac,zfrac,atom[5],atom[6],atom[7]) - print >>f,"1.0 %d %15.10f %15.10f %15.10f 0.0 0.0 0.0 " % (itype,xfrac,yfrac,zfrac) + print("1.0 %d %15.10f %15.10f %15.10f 0.0 0.0 0.0 " % (itype,xfrac,yfrac,zfrac), file=f) - print time, + print(time, end=' ') sys.stdout.flush() n += 1 f.close() - print "\nwrote %d snapshots to %s in CFG format" % (n,file) + print("\nwrote %d snapshots to %s in CFG format" % (n,file)) # -------------------------------------------------------------------- @@ -120,18 +121,18 @@ class cfg: ylen = box[4]-box[1] zlen = box[5]-box[2] - print >>f,"Number of particles = %d " % len(atoms) - print >>f,"# Timestep %d \n#\nA = 1.0 Angstrom" % time - print >>f,"H0(1,1) = %20.10f A " % xlen - print >>f,"H0(1,2) = 0.0 A " - print >>f,"H0(1,3) = 0.0 A " - print >>f,"H0(2,1) = 0.0 A " - print >>f,"H0(2,2) = %20.10f A " % ylen - print >>f,"H0(2,3) = 0.0 A " - print >>f,"H0(3,1) = 0.0 A " - print >>f,"H0(3,2) = 0.0 A " - print >>f,"H0(3,3) = %20.10f A " % zlen - print >>f,"#" + print("Number of particles = %d " % len(atoms), file=f) + print("# Timestep %d \n#\nA = 1.0 Angstrom" % time, file=f) + print("H0(1,1) = %20.10f A " % xlen, file=f) + print("H0(1,2) = 0.0 A ", file=f) + print("H0(1,3) = 0.0 A ", file=f) + print("H0(2,1) = 0.0 A ", file=f) + print("H0(2,2) = %20.10f A " % ylen, file=f) + print("H0(2,3) = 0.0 A ", file=f) + print("H0(3,1) = 0.0 A ", file=f) + print("H0(3,2) = 0.0 A ", file=f) + print("H0(3,3) = %20.10f A " % zlen, file=f) + print("#", file=f) for atom in atoms: itype = int(atom[1]) @@ -139,14 +140,14 @@ class cfg: yfrac = (atom[3]-box[1])/ylen zfrac = (atom[4]-box[2])/zlen # print >>f,"1.0 %d %15.10f %15.10f %15.10f %15.10f %15.10f %15.10f " % (itype,xfrac,yfrac,zfrac,atom[5],atom[6],atom[7]) - print >>f,"1.0 %d %15.10f %15.10f %15.10f 0.0 0.0 0.0 " % (itype,xfrac,yfrac,zfrac) + print("1.0 %d %15.10f %15.10f %15.10f 0.0 0.0 0.0 " % (itype,xfrac,yfrac,zfrac), file=f) - print time, + print(time, end=' ') sys.stdout.flush() f.close() n += 1 - print "\nwrote %s snapshots in CFG format" % n + print("\nwrote %s snapshots in CFG format" % n) # -------------------------------------------------------------------- @@ -163,18 +164,18 @@ class cfg: ylen = box[4]-box[1] zlen = box[5]-box[2] - print >>f,"Number of particles = %d " % len(atoms) - print >>f,"# Timestep %d \n#\nA = 1.0 Angstrom" % time - print >>f,"H0(1,1) = %20.10f A " % xlen - print >>f,"H0(1,2) = 0.0 A " - print >>f,"H0(1,3) = 0.0 A " - print >>f,"H0(2,1) = 0.0 A " - print >>f,"H0(2,2) = %20.10f A " % ylen - print >>f,"H0(2,3) = 0.0 A " - print >>f,"H0(3,1) = 0.0 A " - print >>f,"H0(3,2) = 0.0 A " - print >>f,"H0(3,3) = %20.10f A " % zlen - print >>f,"#" + print("Number of particles = %d " % len(atoms), file=f) + print("# Timestep %d \n#\nA = 1.0 Angstrom" % time, file=f) + print("H0(1,1) = %20.10f A " % xlen, file=f) + print("H0(1,2) = 0.0 A ", file=f) + print("H0(1,3) = 0.0 A ", file=f) + print("H0(2,1) = 0.0 A ", file=f) + print("H0(2,2) = %20.10f A " % ylen, file=f) + print("H0(2,3) = 0.0 A ", file=f) + print("H0(3,1) = 0.0 A ", file=f) + print("H0(3,2) = 0.0 A ", file=f) + print("H0(3,3) = %20.10f A " % zlen, file=f) + print("#", file=f) for atom in atoms: itype = int(atom[1]) @@ -182,6 +183,6 @@ class cfg: yfrac = (atom[3]-box[1])/ylen zfrac = (atom[4]-box[2])/zlen # print >>f,"1.0 %d %15.10f %15.10f %15.10f %15.10f %15.10f %15.10f " % (itype,xfrac,yfrac,zfrac,atom[5],atom[6],atom[7]) - print >>f,"1.0 %d %15.10f %15.10f %15.10f 0.0 0.0 0.0 " % (itype,xfrac,yfrac,zfrac) + print("1.0 %d %15.10f %15.10f %15.10f 0.0 0.0 0.0 " % (itype,xfrac,yfrac,zfrac), file=f) f.close() diff --git a/src/chain.py b/src/chain.py index bd795b6..e508bea 100644 --- a/src/chain.py +++ b/src/chain.py @@ -8,6 +8,12 @@ # chain tool +# Imports and external programs + +from __future__ import print_function, division, absolute_import +import math +from data import data + oneline = "Create bead-spring chains for LAMMPS input" docstr = """ @@ -52,11 +58,6 @@ c.write("data.file") write out all built chains to LAMMPS data file # xlo,ylo,zlo = -xyz prd / 2 # xhi,yhi,zhi = x,y,zprd /2 -# Imports and external programs - -import math -from data import data - # Class definition class chain: @@ -92,12 +93,12 @@ class chain: self.zlo = -self.zprd/2.0 self.zhi = self.zprd/2.0 - print "Simulation box: %g by %g by %g" % (self.xprd,self.yprd,self.zprd) + print("Simulation box: %g by %g by %g" % (self.xprd,self.yprd,self.zprd)) # -------------------------------------------------------------------- def build(self,n,nper): - for ichain in xrange(n): + for ichain in range(n): atoms = [] bonds = [] id_atom_prev = id_mol_prev = id_bond_prev = 0 @@ -107,7 +108,7 @@ class chain: if len(self.bonds): id_bond_prev = self.bonds[-1][0] - for imonomer in xrange(nper): + for imonomer in range(nper): if imonomer == 0: x = self.xlo + self.random()*self.xprd y = self.ylo + self.random()*self.yprd @@ -146,7 +147,7 @@ class chain: if idmol > nper/2: idmol = nper - imonomer else: - raise StandardError,"chain ID is not a valid value" + raise Exception("chain ID is not a valid value") atoms.append([idatom,idmol,self.mtype,x,y,z,ix,iy,iz]) if imonomer: @@ -160,8 +161,8 @@ class chain: def write(self,file): if len(self.atoms) != self.n: - raise StandardError,"%d monomers instead of requested %d" % \ - (len(self.atoms),self.n) + raise Exception("%d monomers instead of requested %d" % \ + (len(self.atoms),self.n)) list = [atom[2] for atom in self.atoms] atypes = max(list) @@ -229,7 +230,7 @@ class chain: # -------------------------------------------------------------------- def random(self): - k = self.seed/IQ + k = self.seed//IQ self.seed = IA*(self.seed-k*IQ) - IR*k if self.seed < 0: self.seed += IM diff --git a/src/clog.py b/src/clog.py index 432caa5..abe6440 100644 --- a/src/clog.py +++ b/src/clog.py @@ -8,6 +8,12 @@ # clog tool +# Imports and external programs + +from __future__ import absolute_import +import sys, re, glob +from os import popen + oneline = "Read ChemCell and SPPARKS log files and extract time-series data" docstr = """ @@ -46,11 +52,6 @@ c.write("file.txt","A","B",...) write listed vectors to a file # data[i][j] = 2d array of floats, i = 0 to # of entries, j = 0 to nvecs-1 # firststr = string that begins a time-series section in log file -# Imports and external programs - -import sys, re, glob -from os import popen - try: tmp = PIZZA_GUNZIP except: PIZZA_GUNZIP = "gunzip" @@ -74,7 +75,7 @@ class clog: self.flist = [] for word in words: self.flist += glob.glob(word) if len(self.flist) == 0 and len(list) == 1: - raise StandardError,"no log file specified" + raise Exception("no log file specified") if len(list) > 1 and len(list[1]): self.firststr = list[1] if len(list) == 3: self.ave = 1 @@ -86,12 +87,12 @@ class clog: def read_all(self): self.read_header(self.flist[0]) - if self.nvec == 0: raise StandardError,"log file has no values" + if self.nvec == 0: raise Exception("log file has no values") # read all files for file in self.flist: self.read_one(file) - print + print() # if no average, sort entries by timestep, cull duplicates # if average, call self.average() @@ -102,17 +103,17 @@ class clog: else: self.average() self.nlen = len(self.data) - print "read %d log entries" % self.nlen + print("read %d log entries" % self.nlen) # -------------------------------------------------------------------- def get(self,*keys): if len(keys) == 0: - raise StandardError, "no log vectors specified" + raise Exception("no log vectors specified") map = [] for key in keys: - if self.ptr.has_key(key): + if key in self.ptr: map.append(self.ptr[key]) else: count = 0 @@ -123,12 +124,12 @@ class clog: if count == 1: map.append(index) else: - raise StandardError, "unique log vector %s not found" % key + raise Exception("unique log vector %s not found" % key) vecs = [] for i in range(len(keys)): vecs.append(self.nlen * [0]) - for j in xrange(self.nlen): + for j in range(self.nlen): vecs[i][j] = self.data[j][map[i]] if len(keys) == 1: return vecs[0] @@ -140,7 +141,7 @@ class clog: if len(keys): map = [] for key in keys: - if self.ptr.has_key(key): + if key in self.ptr: map.append(self.ptr[key]) else: count = 0 @@ -151,15 +152,15 @@ class clog: if count == 1: map.append(index) else: - raise StandardError, "unique log vector %s not found" % key + raise Exception("unique log vector %s not found" % key) else: - map = range(self.nvec) + map = list(range(self.nvec)) f = open(filename,"w") - for i in xrange(self.nlen): - for j in xrange(len(map)): - print >>f,self.data[i][map[j]], - print >>f + for i in range(self.nlen): + for j in range(len(map)): + print(self.data[i][map[j]], end=' ', file=f) + print(file=f) f.close() # -------------------------------------------------------------------- @@ -195,12 +196,12 @@ class clog: data.append(self.nvec*[0]) nlen += 1 counts[j] += 1 - for m in xrange(self.nvec): data[j][m] += self.data[i][m] + for m in range(self.nvec): data[j][m] += self.data[i][m] j += 1 i += 1 - for i in xrange(nlen): - for j in xrange(self.nvec): + for i in range(nlen): + for j in range(self.nvec): data[i][j] /= counts[j] self.nlen = nlen @@ -291,11 +292,11 @@ class clog: lines = chunk.split("\n") for line in lines: words = line.split() - self.data.append(map(float,words)) + self.data.append(list(map(float,words))) # print last timestep of chunk - print int(self.data[len(self.data)-1][0]), + print(int(self.data[len(self.data)-1][0]), end=' ') sys.stdout.flush() return eof diff --git a/src/data.py b/src/data.py index 5e2277b..a830bf9 100644 --- a/src/data.py +++ b/src/data.py @@ -8,6 +8,11 @@ # data tool +# Imports and external programs + +from __future__ import absolute_import +from os import popen + oneline = "Read, write, manipulate LAMMPS data files" docstr = """ @@ -70,10 +75,6 @@ d.write("data.new") write a LAMMPS data file # sections = dictionary with section name as key, array of lines as values # nselect = 1 = # of snapshots -# Imports and external programs - -from os import popen - try: tmp = PIZZA_GUNZIP except: PIZZA_GUNZIP = "gunzip" @@ -129,15 +130,14 @@ class data: keyword,length = pair[0],pair[1] if keyword == line: found = 1 - if not headers.has_key(length): - raise StandardError, \ - "data section %s has no matching header value" % line + if length not in headers: + raise Exception("data section %s has no matching header value" % line) f.readline() list = [] - for i in xrange(headers[length]): list.append(f.readline()) + for i in range(headers[length]): list.append(f.readline()) sections[keyword] = list if not found: - raise StandardError,"invalid section %s in data file" % line + raise Exception("invalid section %s in data file" % line) f.readline() line = f.readline() if not line: @@ -153,7 +153,7 @@ class data: def map(self,*pairs): if len(pairs) % 2 != 0: - raise StandardError, "data map() requires pairs of mappings" + raise Exception("data map() requires pairs of mappings") for i in range(0,len(pairs),2): j = i + 1 self.names[pairs[j]] = pairs[i]-1 @@ -161,19 +161,19 @@ class data: # -------------------------------------------------------------------- # extract info from data file fields - def get(self,*list): - if len(list) == 1: - field = list[0] + def get(self,*flist): + if len(flist) == 1: + field = flist[0] array = [] lines = self.sections[field] for line in lines: words = line.split() - values = map(float,words) + values = list(map(float,words)) array.append(values) return array - elif len(list) == 2: - field = list[0] - n = list[1] - 1 + elif len(flist) == 2: + field = flist[0] + n = flist[1] - 1 vec = [] lines = self.sections[field] for line in lines: @@ -181,7 +181,7 @@ class data: vec.append(float(words[n])) return vec else: - raise StandardError, "invalid arguments for data.get()" + raise Exception("invalid arguments for data.get()") # -------------------------------------------------------------------- # reorder columns in a data file field @@ -192,10 +192,10 @@ class data: oldlines = self.sections[name] newlines = natoms*[""] for index in order: - for i in xrange(len(newlines)): + for i in range(len(newlines)): words = oldlines[i].split() newlines[i] += words[index-1] + " " - for i in xrange(len(newlines)): + for i in range(len(newlines)): newlines[i] += "\n" self.sections[name] = newlines @@ -206,7 +206,7 @@ class data: lines = self.sections[name] newlines = [] j = icol - 1 - for i in xrange(len(lines)): + for i in range(len(lines)): line = lines[i] words = line.split() words[j] = str(vector[i]) @@ -222,19 +222,15 @@ class data: def newxyz(self,dm,ntime): nsnap = dm.findtime(ntime) - if dm.scaled(nsnap): scaleflag = 1 - else: scaleflag = 0 dm.sort(ntime) - if scaleflag: dm.unscale(ntime) x,y,z = dm.vecs(ntime,"x","y","z") - if scaleflag: dm.scale(ntime) self.replace("Atoms",self.names['x']+1,x) self.replace("Atoms",self.names['y']+1,y) self.replace("Atoms",self.names['z']+1,z) - if dm.names.has_key("ix") and self.names.has_key("ix"): + if "ix" in dm.names and "ix" in self.names: ix,iy,iz = dm.vecs(ntime,"ix","iy","iz") self.replace("Atoms",self.names['ix']+1,ix) self.replace("Atoms",self.names['iy']+1,iy) @@ -245,33 +241,33 @@ class data: def delete(self,keyword): - if self.headers.has_key(keyword): del self.headers[keyword] - elif self.sections.has_key(keyword): del self.sections[keyword] - else: raise StandardError, "keyword not found in data object" + if keyword in self.headers: del self.headers[keyword] + elif keyword in self.sections: del self.sections[keyword] + else: raise Exception("keyword not found in data object") # -------------------------------------------------------------------- # write out a LAMMPS data file def write(self,file): f = open(file,"w") - print >>f,self.title + print(self.title, file=f) for keyword in hkeywords: - if self.headers.has_key(keyword): + if keyword in self.headers: if keyword == "xlo xhi" or keyword == "ylo yhi" or \ keyword == "zlo zhi": pair = self.headers[keyword] - print >>f,pair[0],pair[1],keyword + print(pair[0],pair[1],keyword, file=f) elif keyword == "xy xz yz": triple = self.headers[keyword] - print >>f,triple[0],triple[1],triple[2],keyword + print(triple[0],triple[1],triple[2],keyword, file=f) else: - print >>f,self.headers[keyword],keyword + print(self.headers[keyword],keyword, file=f) for pair in skeywords: keyword = pair[0] - if self.sections.has_key(keyword): - print >>f,"\n%s\n" % keyword + if keyword in self.sections: + print("\n%s\n" % keyword, file=f) for line in self.sections[keyword]: - print >>f,line, + print(line, end=' ', file=f) f.close() # -------------------------------------------------------------------- @@ -286,13 +282,13 @@ class data: def findtime(self,n): if n == 0: return 0 - raise StandardError, "no step %d exists" % (n) + raise Exception("no step %d exists" % (n)) # -------------------------------------------------------------------- # return list of atoms and bonds to viz for data object def viz(self,isnap): - if isnap: raise StandardError, "cannot call data.viz() with isnap != 0" + if isnap: raise Exception("cannot call data.viz() with isnap != 0") id = self.names["id"] type = self.names["type"] @@ -318,7 +314,7 @@ class data: # assumes atoms are sorted so can lookup up the 2 atoms in each bond bonds = [] - if self.sections.has_key("Bonds"): + if "Bonds" in self.sections: bondlines = self.sections["Bonds"] for line in bondlines: words = line.split() diff --git a/src/dump.py b/src/dump.py index 5f5f892..9a853f7 100644 --- a/src/dump.py +++ b/src/dump.py @@ -8,6 +8,14 @@ # dump tool +# Imports and external programs + +import sys, subprocess, re, glob, types +from os import popen +from math import * # any function could be used by set() +import os +import functools + oneline = "Read, write, manipulate dump files and particle attributes" docstr = """ @@ -180,19 +188,12 @@ d.extra(obj) extract bond/tri/line info from obj # xlo,xhi,ylo,yhi,zlo,zhi = box bounds (float) # atoms[i][j] = 2d array of floats, i = 0 to natoms-1, j = 0 to ncols-1 -# Imports and external programs - -import sys, commands, re, glob, types -from os import popen -from math import * # any function could be used by set() -import os - try: - import numpy as np - oldnumeric = False + import numpy as np + oldnumeric = False except: - import Numeric as np - oldnumeric = True + import Numeric as np + oldnumeric = True try: from DEFAULTS import PIZZA_GUNZIP except: PIZZA_GUNZIP = "gunzip" @@ -228,7 +229,7 @@ class dump: # check whether to output or not if "debugMode" in dictionary: outputfl = dictionary["debugMode"] - if outputfl: print "number of subprocess:", os.getpid() + if outputfl: print("number of subprocess:", os.getpid()) self.flist = dictionary["filelist"] self.multiprocflag = 1 @@ -240,7 +241,7 @@ class dump: self.flist = [] for word in words: self.flist += glob.glob(word) if len(self.flist) == 0 and len(input) == 1: - raise StandardError,"no dump file specified" + raise Exception("no dump file specified") if len(input) == 1: self.increment = 0 @@ -261,31 +262,32 @@ class dump: outputfl = True if "output" in kwargs: outputfl = kwargs["output"] - if outputfl: print "reading dump file..." + if outputfl: print("reading dump file...") for i, file in enumerate(self.flist): if file[-3:] == ".gz": f = popen("%s -c %s" % (PIZZA_GUNZIP,file),'r') - else: f = open(file) + else: + f = open(file) snap = self.read_snapshot(f) while snap: self.snaps.append(snap) - if outputfl: print snap.time, + if outputfl: print(snap.time,end=' ') self.fileNums.append(snap.time) sys.stdout.flush() snap = self.read_snapshot(f) f.close() - if outputfl: print + if outputfl: print() # sort entries by timestep, cull duplicates - self.snaps.sort(self.compare_time) + self.snaps.sort(key = functools.cmp_to_key(self.compare_time)) self.fileNums.sort() self.cull() self.nsnaps = len(self.snaps) - #print "read %d snapshots" % self.nsnaps + #print("read %d snapshots" % self.nsnaps) # select all timesteps and atoms @@ -294,32 +296,32 @@ class dump: # set default names for atom columns if file wasn't self-describing if len(self.snaps) == 0: - if outputfl: print "no column assignments made" + if outputfl: print("no column assignments made") elif len(self.names): - if outputfl: print "assigned columns:",self.names2str() + if outputfl: print("assigned columns:",self.names2str()) else: - if outputfl: print "no column assignments made" + if outputfl: print("no column assignments made") pass # 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 "dump scaling status is unknown" + if ("x" not in self.names) or \ + ("y" not in self.names) or \ + ("z" not in self.names): + print("dump scaling status is unknown") elif self.nsnaps > 0: if self.scale_original == 1: self.unscale() elif self.scale_original == 0: - if outputfl: print "dump is already unscaled" + if outputfl: print("dump is already unscaled") else: - if outputfl: print "dump scaling status is unknown" + if outputfl: print("dump scaling status is unknown") # -------------------------------------------------------------------- # read next snapshot from list of files def next(self): - if not self.increment: raise StandardError,"cannot read incrementally" + if not self.increment: raise Exception("cannot read incrementally") # read next snapshot in current file using eof as pointer # if fail, try next file @@ -345,10 +347,11 @@ class dump: # select the new snapshot with all its atoms self.snaps.append(snap) + self.fileNums.append(snap.time) 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 @@ -411,14 +414,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) + floats = list(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 @@ -433,7 +436,7 @@ class dump: def map(self,*pairs): if len(pairs) % 2 != 0: - raise StandardError, "dump map() requires pairs of mappings" + raise Exception("dump map() requires pairs of mappings") for i in range(0,len(pairs),2): j = i + 1 self.names[pairs[j]] = pairs[i]-1 @@ -445,25 +448,26 @@ class dump: ndel = i = 0 while i < self.nsnaps: if not self.snaps[i].tselect: + del self.fileNums[i] del self.snaps[i] 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 ..." + def scale(self,*dumplist): + if len(dumplist) == 0: + print("Scaling dump ...") x = self.names["x"] y = self.names["y"] z = self.names["z"] for snap in self.snaps: self.scale_one(snap,x,y,z) else: - i = self.findtime(list[0]) + i = self.findtime(dumplist[0]) x = self.names["x"] y = self.names["y"] z = self.names["z"] @@ -483,15 +487,15 @@ class dump: # -------------------------------------------------------------------- # unscale coords from 0-1 to box size for all snapshots or just one - def unscale(self,*list): - if len(list) == 0: - print "Unscaling dump ..." + def unscale(self,*dumplist): + if len(dumplist) == 0: + print("Unscaling dump ...") x = self.names["x"] y = self.names["y"] z = self.names["z"] for snap in self.snaps: self.unscale_one(snap,x,y,z) else: - i = self.findtime(list[0]) + i = self.findtime(dumplist[0]) x = self.names["x"] y = self.names["y"] z = self.names["z"] @@ -512,7 +516,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"] @@ -534,7 +538,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"] @@ -557,7 +561,7 @@ class dump: # if dynamic extra lines or triangles defined, owrap them as well def owrap(self,other): - print "Wrapping to other ..." + print("Wrapping to other ...") id = self.names["id"] x = self.names["x"] @@ -574,9 +578,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 @@ -589,11 +593,11 @@ class dump: # convert column names assignment to a string, in column order def names2str(self): - ncol = max(self.names.values()) #len(self.snaps[0].atoms[0]) - pairs = self.names.items() - values = self.names.values() + pairs = list(self.names.items()) + values = list(self.names.values()) + ncol = len(pairs) str = "" - for i in xrange(ncol): + for i in range(ncol): if i in values: str += pairs[values.index(i)][0] + ' ' return str @@ -602,24 +606,24 @@ class dump: # if arg = string, sort all steps by that column # if arg = numeric, sort atoms in single step - def sort(self,*list, **kwargs): + def sort(self,*tslist, **kwargs): # check whether to output or not outputfl = True if "output" in kwargs: outputfl = kwargs["output"] - if len(list) == 0: - if outputfl: print "Sorting selected snapshots ..." + if len(tslist) == 0: + if outputfl: 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: - if outputfl: print "Sorting selected snapshots by %s ..." % list[0] - id = self.names[list[0]] + elif isinstance(tslist[0], str): + if outputfl: print("Sorting selected snapshots by %s ..." % tslist[0]) + id = self.names[tslist[0]] for snap in self.snaps: if snap.tselect: self.sort_one(snap,id) else: - i = self.findtime(list[0]) + i = self.findtime(tslist[0]) id = self.names["id"] self.sort_one(self.snaps[i],id) @@ -630,7 +634,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) # -------------------------------------------------------------------- @@ -642,33 +646,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 @@ -677,34 +681,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 @@ -716,7 +720,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] @@ -726,15 +730,15 @@ 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) + eqlist = re.findall(pattern,eq) - lhs = list[0][1:] - if not self.names.has_key(lhs): + lhs = eqlist[0][1:] + if lhs not in self.names: self.newcolumn(lhs) - for item in list: + for item in eqlist: name = item[1:] column = self.names[name] insert = "snap.atoms[i][%d]" % (column) @@ -743,25 +747,25 @@ 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 ..." - if not self.names.has_key(colname): + print("Setting ...") + if colname not in self.names: self.newcolumn(colname) icol = self.names[colname] 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 Exception("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 @@ -774,12 +778,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] @@ -789,18 +793,18 @@ class dump: def spread(self,old,n,new): iold = self.names[old] - if not self.names.has_key(new): self.newcolumn(new) + if new not in self.names: self.newcolumn(new) 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 @@ -822,12 +826,12 @@ class dump: # -------------------------------------------------------------------- # extract vector(s) of values for atom ID n at each selected timestep - def atom(self,n,*list): - if len(list) == 0: - raise StandardError, "no columns specified" + def atom(self,n,*tslist): + if len(tslist) == 0: + raise Exception("no columns specified") columns = [] values = [] - for name in list: + for name in tslist: columns.append(self.names[name]) values.append(self.nselect * [0]) ncol = len(columns) @@ -837,40 +841,40 @@ 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 Exception("could not find atom ID in snapshot") + for j in range(ncol): values[j][m] = atoms[i][columns[j]] m += 1 - if len(list) == 1: return values[0] + if len(tslist) == 1: return values[0] else: return values # -------------------------------------------------------------------- # extract vector(s) of values for selected atoms at chosen timestep - def vecs(self,n,*list): + def vecs(self,n,*tslist): snap = self.snaps[self.findtime(n)] - if len(list) == 0: - raise StandardError, "no columns specified" + if len(tslist) == 0: + raise Exception("no columns specified") columns = [] values = [] - for name in list: + for name in tslist: columns.append(self.names[name]) values.append(snap.nselect * [0]) 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 - if len(list) == 1: return values[0] + if len(tslist) == 1: return values[0] else: return values # -------------------------------------------------------------------- @@ -915,7 +919,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 @@ -951,7 +955,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]]) @@ -970,7 +974,7 @@ class dump: elif self.bondflag == 2: tmp1,tmp2,tmp3,bondlist,tmp4,tmp5 = self.objextra.viz(time,1) 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 bondlist: try: i = alist[bond[2]] @@ -1004,9 +1008,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 Exception("no step %d exists" % n) # -------------------------------------------------------------------- # return maximum box size across all selected snapshots @@ -1033,7 +1037,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) @@ -1046,7 +1050,7 @@ class dump: # data object, grab bonds statically - if type(arg) is types.InstanceType and ".data" in str(arg.__class__): + if isinstance(arg, object) and ".data" in str(arg.__class__): self.bondflag = 0 try: bondlist = [] @@ -1059,11 +1063,11 @@ class dump: self.bondflag = 1 self.bondlist = bondlist except: - raise StandardError,"could not extract bonds from data object" + raise Exception("could not extract bonds from data object") # cdata object, grab tris and lines statically - elif type(arg) is types.InstanceType and ".cdata" in str(arg.__class__): + elif isinstance(arg, object) and ".cdata" in str(arg.__class__): self.triflag = self.lineflag = 0 try: tmp,tmp,tmp,tmp,tris,lines = arg.viz(0) @@ -1074,34 +1078,34 @@ class dump: self.lineflag = 1 self.linelist = lines except: - raise StandardError,"could not extract tris/lines from cdata object" + raise Exception("could not extract tris/lines from cdata object") # mdump object, grab tris dynamically - elif type(arg) is types.InstanceType and ".mdump" in str(arg.__class__): + elif isinstance(arg, object) and ".mdump" in str(arg.__class__): self.triflag = 2 self.objextra = arg # bdump object, grab bonds dynamically - elif type(arg) is types.InstanceType and ".bdump" in str(arg.__class__): + elif isinstance(arg, object) and ".bdump" in str(arg.__class__): self.bondflag = 2 self.objextra = arg # ldump object, grab tris dynamically - elif type(arg) is types.InstanceType and ".ldump" in str(arg.__class__): + elif isinstance(arg, object) and ".ldump" in str(arg.__class__): self.lineflag = 2 self.objextra = arg # tdump object, grab tris dynamically - elif type(arg) is types.InstanceType and ".tdump" in str(arg.__class__): + elif isinstance(arg, object) and ".tdump" in str(arg.__class__): self.triflag = 2 self.objextra = arg else: - raise StandardError,"unrecognized argument to dump.extra()" + raise Exception("unrecognized argument to dump.extra()") # -------------------------------------------------------------------- @@ -1140,7 +1144,7 @@ class tselect: snap.tselect = 1 data.nselect = len(data.snaps) data.aselect.all() - if outputfl: print "%d snapshots selected out of %d" % (data.nselect,data.nsnaps) + if outputfl: print("%d snapshots selected out of %d" % (data.nselect,data.nsnaps)) # -------------------------------------------------------------------- @@ -1152,7 +1156,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)) # -------------------------------------------------------------------- @@ -1161,7 +1165,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)) # -------------------------------------------------------------------- @@ -1177,7 +1181,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)) # -------------------------------------------------------------------- @@ -1186,14 +1190,16 @@ 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 + ldict = {'data':data,'snaps':snaps,'i':i} + exec(ccmd,globals(),ldict) + flag = ldict['flag'] 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 @@ -1210,12 +1216,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 # -------------------------------------------------------------------- @@ -1226,8 +1232,8 @@ class aselect: # replace all $var with snap.atoms references and compile test string pattern = "\$\w*" - list = re.findall(pattern,teststr) - for item in list: + testlist = re.findall(pattern,teststr) + for item in testlist: name = item[1:] column = data.names[name] insert = "snap.atoms[i][%d]" % column @@ -1238,29 +1244,33 @@ 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 + ldict = {'snap':snap,'i':i} + exec(ccmd,globals(),ldict) + flag = ldict['flag'] 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 + ldict = {'snap':snap,'i':i} + exec(ccmd,globals(),ldict) + flag = ldict['flag'] if not flag: snap.aselect[i] = 0 snap.nselect -= 1 diff --git a/src/dump2force.py b/src/dump2force.py index 44bcd08..6e71ea9 100644 --- a/src/dump2force.py +++ b/src/dump2force.py @@ -27,6 +27,7 @@ and dump match the format here - this will be checked in future! """ +from __future__ import absolute_import from evtk.vtk import VtkFile, VtkGroup, VtkUnstructuredGrid from bdump import bdump import numpy as np @@ -80,7 +81,7 @@ timestep = forcedata.next() # NOTE: the first timesteps are often blank, and then natoms returns 0, so this doesn't really work... # if forcedata.snaps[fileindex].natoms !=0 and len(forcedata.snaps[0].atoms[0]) < 12: - print "Error - dump file requires at least all parameters from a compute pair/gran/local id pos force (12 in total)" + print("Error - dump file requires at least all parameters from a compute pair/gran/local id pos force (12 in total)") sys.exit() # loop through available timesteps @@ -104,7 +105,7 @@ while timestep >= 0: if forcedata.snaps[fileindex].natoms == 0: vtufile = fileprefix+'_'+str(timestep)+'.vtu' vtufile = os.path.join(outputdir,vtufile) - vtuwrite = file(vtufile,'w') + vtuwrite = open(vtufile,'w') vtuwrite.write(""" @@ -134,8 +135,8 @@ while timestep >= 0: nconnex = ncells - nperiodic # extract the IDs as an array of integers - id1 = np.array(forcedata.snaps[fileindex].atoms[:,forcedata.names["id1"]],dtype=long) - id2 = np.array(forcedata.snaps[fileindex].atoms[:,forcedata.names["id2"]],dtype=long) + id1 = np.array(forcedata.snaps[fileindex].atoms[:,forcedata.names["id1"]],dtype=int) + id2 = np.array(forcedata.snaps[fileindex].atoms[:,forcedata.names["id2"]],dtype=int) # and convert to lists id1 = id1.tolist() @@ -153,7 +154,7 @@ while timestep >= 0: # number of points = number of unique IDs (particles) npoints = len(ids) - print 'Timestep:',str(timestep),'npoints=',str(npoints),'ncells=',str(ncells),'nperiodic=',nperiodic, 'nconnex=',str(nconnex) + print('Timestep:',str(timestep),'npoints=',str(npoints),'ncells=',str(ncells),'nperiodic=',nperiodic, 'nconnex=',str(nconnex)) # ****************************************** diff --git a/src/ensight.py b/src/ensight.py index d2cd2a1..82b12e1 100644 --- a/src/ensight.py +++ b/src/ensight.py @@ -8,6 +8,11 @@ # ensight tool +# Imports and external programs + +from __future__ import absolute_import +import sys, types + oneline = "Convert LAMMPS snapshots or meshes to Ensight format" docstr = """ @@ -50,10 +55,6 @@ e.single(N) same args as one() prepended by N, but write a single snap # which = 0 for particles, 1 for elements # change = 0 for unchanging mesh coords, 1 for changing mesh coords (def = 0) -# Imports and external programs - -import sys, types - # Class definition class ensight: @@ -64,16 +65,16 @@ class ensight: self.change = 0 self.maxtype = 0 self.data = data - if type(data) is types.InstanceType and ".dump" in str(data.__class__): + if isinstance(data, object) and ".dump" in str(data.__class__): self.which = 0 - elif type(data) is types.InstanceType and ".data" in str(data.__class__): + elif isinstance(data, object) and ".data" in str(data.__class__): self.which = 0 - elif type(data) is types.InstanceType and ".mdump" in str(data.__class__): + elif isinstance(data, object) and ".mdump" in str(data.__class__): self.which = 1 - elif type(data) is types.InstanceType and ".cdata" in str(data.__class__): + elif isinstance(data, object) and ".cdata" in str(data.__class__): self.which = 1 else: - raise StandardError,"unrecognized object passed to ensight" + raise Exception("unrecognized object passed to ensight") # -------------------------------------------------------------------- @@ -114,34 +115,34 @@ class ensight: if flag == -1: break if self.which == 0: - print >>f,"BEGIN TIME STEP" + print("BEGIN TIME STEP", file=f) time,box,atoms,bonds,tris,lines = self.data.viz(which) self.coord_file_atoms(f,box,atoms) - print >>f,"END TIME STEP" + print("END TIME STEP", file=f) elif self.change == 0 and first: - print >>f,"BEGIN TIME STEP" + print("BEGIN TIME STEP", file=f) time,box,nodes,elements,nvalues,evalues = self.data.mviz(which) self.coord_file_elements(f,box,nodes,elements) etype = len(elements[0]) first = 0 - print >>f,"END TIME STEP" + print("END TIME STEP", file=f) elif self.change: - print >>f,"BEGIN TIME STEP" + print("BEGIN TIME STEP", file=f) time,box,nodes,elements,nvalues,evalues = self.data.mviz(which) self.coord_file_elements(f,box,nodes,elements) etype = len(elements[0]) - print >>f,"END TIME STEP" + print("END TIME STEP", file=f) for i in range(len(pairs)): - print >>vfiles[i],"BEGIN TIME STEP" + print("BEGIN TIME STEP", file=vfiles[i]) values = self.data.vecs(time,pairs[i][0]) if self.which == 0: self.variable_file_atoms(vfiles[i],pairs[i][1],atoms,values) else: self.variable_file_elements(vfiles[i],pairs[i][1],etype,values) - print >>vfiles[i],"END TIME STEP" + print("END TIME STEP", file=vfiles[i]) - print time, + print(time, end=' ') sys.stdout.flush() n += 1 @@ -150,7 +151,7 @@ class ensight: f.close() for f in vfiles: f.close() - print "\nwrote %s snapshots in Ensight format" % n + print("\nwrote %s snapshots in Ensight format" % n) # -------------------------------------------------------------------- @@ -181,41 +182,41 @@ class ensight: first = 1 n = etype = 0 while 1: - time = self.data.next() + time = next(self.data) if time == -1: break times.append(time) self.data.tselect.one(time) self.data.delete() if self.which == 0: - print >>f,"BEGIN TIME STEP" + print("BEGIN TIME STEP", file=f) time,box,atoms,bonds,tris,lines = self.data.viz(0) self.coord_file_atoms(f,box,atoms) - print >>f,"END TIME STEP" + print("END TIME STEP", file=f) elif self.change == 0 and first: - print >>f,"BEGIN TIME STEP" + print("BEGIN TIME STEP", file=f) time,box,nodes,elements,nvalues,evalues = self.data.mviz(0) self.coord_file_elements(f,box,nodes,elements) etype = len(elements[0]) first = 0 - print >>f,"END TIME STEP" + print("END TIME STEP", file=f) elif self.change: - print >>f,"BEGIN TIME STEP" + print("BEGIN TIME STEP", file=f) time,box,nodes,elements,nvalues,evalues = self.data.mviz(0) self.coord_file_elements(f,box,nodes,elements) etype = len(elements[0]) - print >>f,"END TIME STEP" + print("END TIME STEP", file=f) for i in range(len(pairs)): - print >>vfiles[i],"BEGIN TIME STEP" + print("BEGIN TIME STEP", file=vfiles[i]) values = self.data.vecs(time,pairs[i][0]) if self.which == 0: self.variable_file_atoms(vfiles[i],pairs[i][1],atoms,values) else: self.variable_file_elements(vfiles[i],pairs[i][1],etype,values) - print >>vfiles[i],"END TIME STEP" + print("END TIME STEP", file=vfiles[i]) - print time, + print(time, end=' ') sys.stdout.flush() n += 1 @@ -230,7 +231,7 @@ class ensight: self.case_file(f,root,pairs,0,len(times),times) f.close() - print "\nwrote %s snapshots in Ensight format" % n + print("\nwrote %s snapshots in Ensight format" % n) # -------------------------------------------------------------------- @@ -311,11 +312,11 @@ class ensight: self.variable_file_elements(f,pairs[i][1],etype,values) f.close() - print time, + print(time, end=' ') sys.stdout.flush() n += 1 - print "\nwrote %s snapshots in Ensight format" % n + print("\nwrote %s snapshots in Ensight format" % n) # -------------------------------------------------------------------- @@ -367,55 +368,55 @@ class ensight: # write Ensight case file def case_file(self,f,root,pairs,multifile,nsnaps,times): - print >>f,"# Ensight case file\n" - print >>f,"FORMAT\ntype: ensight gold\n" + print("# Ensight case file\n", file=f) + print("FORMAT\ntype: ensight gold\n", file=f) if self.which == 0: if multifile: # print >>f,"GEOMETRY\nmodel: %s****.xyz change_coords_only\n" % root - print >>f,"GEOMETRY\nmodel: %s****.xyz\n" % root + print("GEOMETRY\nmodel: %s****.xyz\n" % root, file=f) else: # print >>f,"GEOMETRY\nmodel: 1 1 %s.xyz change_coords_only\n" % root - print >>f,"GEOMETRY\nmodel: 1 1 %s.xyz\n" % root + print("GEOMETRY\nmodel: 1 1 %s.xyz\n" % root, file=f) else: if self.change == 0: - print >>f,"GEOMETRY\nmodel: %s.xyz\n" % root + print("GEOMETRY\nmodel: %s.xyz\n" % root, file=f) elif multifile: - print >>f,"GEOMETRY\nmodel: %s****.xyz\n" % root + print("GEOMETRY\nmodel: %s****.xyz\n" % root, file=f) else: - print >>f,"GEOMETRY\nmodel: 1 1 %s.xyz\n" % root + print("GEOMETRY\nmodel: 1 1 %s.xyz\n" % root, file=f) if len(pairs): - print >>f,"VARIABLE" + print("VARIABLE", file=f) for pair in pairs: if self.which == 0: if multifile: - print >>f,"scalar per node: %s %s****.%s" % (pair[1],root,pair[0]) + print("scalar per node: %s %s****.%s" % (pair[1],root,pair[0]), file=f) else: - print >>f,"scalar per node: 1 1 %s %s.%s" % (pair[1],root,pair[0]) + print("scalar per node: 1 1 %s %s.%s" % (pair[1],root,pair[0]), file=f) else: if multifile: - print >>f,"scalar per element: %s %s****.%s" % (pair[1],root,pair[0]) + print("scalar per element: %s %s****.%s" % (pair[1],root,pair[0]), file=f) else: - print >>f,"scalar per element: 1 1 %s %s.%s" % (pair[1],root,pair[0]) - print >>f + print("scalar per element: 1 1 %s %s.%s" % (pair[1],root,pair[0]), file=f) + print(file=f) - print >>f,"TIME" - print >>f,"time set: 1" - print >>f,"number of steps:",nsnaps - print >>f,"filename start number: 0" - print >>f,"filename increment: 1" - print >>f,"time values:" + print("TIME", file=f) + print("time set: 1", file=f) + print("number of steps:",nsnaps, file=f) + print("filename start number: 0", file=f) + print("filename increment: 1", file=f) + print("time values:", file=f) for i in range(nsnaps): - print >>f,times[i], - if i % 10 == 9: print >>f - print >>f - print >>f + print(times[i], end=' ', file=f) + if i % 10 == 9: print(file=f) + print(file=f) + print(file=f) if not multifile: - print >>f,"FILE" - print >>f,"file set: 1" - print >>f,"number of steps:",nsnaps + print("FILE", file=f) + print("file set: 1", file=f) + print("number of steps:",nsnaps, file=f) # -------------------------------------------------------------------- # write Ensight coordinates for atoms @@ -423,65 +424,65 @@ class ensight: # one part = coords for all atoms of a single type def coord_file_atoms(self,f,box,atoms): - print >>f,"Particle geometry\nfor a collection of atoms" - print >>f,"node id given" - print >>f,"element id off" - print >>f,"extents" - print >>f,"%12.5e%12.5e" % (box[0],box[3]) - print >>f,"%12.5e%12.5e" % (box[1],box[4]) - print >>f,"%12.5e%12.5e" % (box[2],box[5]) + print("Particle geometry\nfor a collection of atoms", file=f) + print("node id given", file=f) + print("element id off", file=f) + print("extents", file=f) + print("%12.5e%12.5e" % (box[0],box[3]), file=f) + print("%12.5e%12.5e" % (box[1],box[4]), file=f) + print("%12.5e%12.5e" % (box[2],box[5]), file=f) - for type in xrange(1,self.maxtype+1): - print >>f,"part" - print >>f,"%10d" % type - print >>f,"type",type - print >>f,"coordinates" + for type in range(1,self.maxtype+1): + print("part", file=f) + print("%10d" % type, file=f) + print("type",type, file=f) + print("coordinates", file=f) group = [atom for atom in atoms if int(atom[1]) == type] - print >>f,"%10d" % len(group) - for atom in group: print >>f,"%10d" % int(atom[0]) - for atom in group: print >>f,"%12.5e" % atom[2] - for atom in group: print >>f,"%12.5e" % atom[3] - for atom in group: print >>f,"%12.5e" % atom[4] - print >>f,"point" - print >>f,"%10d" % len(group) - for i in xrange(1,len(group)+1): print >>f,"%10d" % i + print("%10d" % len(group), file=f) + for atom in group: print("%10d" % int(atom[0]), file=f) + for atom in group: print("%12.5e" % atom[2], file=f) + for atom in group: print("%12.5e" % atom[3], file=f) + for atom in group: print("%12.5e" % atom[4], file=f) + print("point", file=f) + print("%10d" % len(group), file=f) + for i in range(1,len(group)+1): print("%10d" % i, file=f) # -------------------------------------------------------------------- # write Ensight coordinates for elements def coord_file_elements(self,f,box,nodes,elements): - print >>f,"Element geometry\nfor a collection of elements" - print >>f,"node id given" - print >>f,"element id given" - print >>f,"extents" - print >>f,"%12.5e%12.5e" % (box[0],box[3]) - print >>f,"%12.5e%12.5e" % (box[1],box[4]) - print >>f,"%12.5e%12.5e" % (box[2],box[5]) + print("Element geometry\nfor a collection of elements", file=f) + print("node id given", file=f) + print("element id given", file=f) + print("extents", file=f) + print("%12.5e%12.5e" % (box[0],box[3]), file=f) + print("%12.5e%12.5e" % (box[1],box[4]), file=f) + print("%12.5e%12.5e" % (box[2],box[5]), file=f) - print >>f,"part" - print >>f,"%10d" % 1 - print >>f,"all elements" - print >>f,"coordinates" - print >>f,"%10d" % len(nodes) - for node in nodes: print >>f,"%10d" % int(node[0]) - for node in nodes: print >>f,"%12.5e" % node[2] - for node in nodes: print >>f,"%12.5e" % node[3] - for node in nodes: print >>f,"%12.5e" % node[4] + print("part", file=f) + print("%10d" % 1, file=f) + print("all elements", file=f) + print("coordinates", file=f) + print("%10d" % len(nodes), file=f) + for node in nodes: print("%10d" % int(node[0]), file=f) + for node in nodes: print("%12.5e" % node[2], file=f) + for node in nodes: print("%12.5e" % node[3], file=f) + for node in nodes: print("%12.5e" % node[4], file=f) - if len(elements[0]) == 5: print >>f,"tria3" - elif len(elements[0]) == 6: print >>f,"tetra4" - else: raise StandardError,"unrecognized element type" - print >>f,"%10d" % len(elements) + if len(elements[0]) == 5: print("tria3", file=f) + elif len(elements[0]) == 6: print("tetra4", file=f) + else: raise Exception("unrecognized element type") + print("%10d" % len(elements), file=f) - for element in elements: print >>f,"%10d" % int(element[0]) + for element in elements: print("%10d" % int(element[0]), file=f) if len(elements[0]) == 5: for element in elements: - print >>f,"%10d%10d%10d" % \ - (int(element[2]),int(element[3]),int(element[4])) + print("%10d%10d%10d" % \ + (int(element[2]),int(element[3]),int(element[4])), file=f) elif len(elements[0]) == 6: for element in elements: - print >>f,"%10d%10d%10d%10d" % \ - (int(element[2]),int(element[3]),int(element[4]),int(element[5])) + print("%10d%10d%10d%10d" % \ + (int(element[2]),int(element[3]),int(element[4]),int(element[5])), file=f) # -------------------------------------------------------------------- # write Ensight variable values for atoms @@ -489,22 +490,22 @@ class ensight: # one part = values for all atoms of a single type def variable_file_atoms(self,f,name,atoms,values): - print >>f,"Particle %s" % name - for type in xrange(1,self.maxtype+1): - print >>f,"part" - print >>f,"%10d" % type - print >>f,"coordinates" - group = [values[i] for i in xrange(len(atoms)) + print("Particle %s" % name, file=f) + for type in range(1,self.maxtype+1): + print("part", file=f) + print("%10d" % type, file=f) + print("coordinates", file=f) + group = [values[i] for i in range(len(atoms)) if int(atoms[i][1]) == type] - for value in group: print >>f,"%12.5e" % value + for value in group: print("%12.5e" % value, file=f) # -------------------------------------------------------------------- # write Ensight variable values for elements def variable_file_elements(self,f,name,etype,values): - print >>f,"Element %s" % name - print >>f,"part" - print >>f,"%10d" % 1 - if etype == 5: print >>f,"tria3" - elif etype == 6: print >>f,"tetra4" - for value in values: print >>f,"%12.5e" % value + print("Element %s" % name, file=f) + print("part", file=f) + print("%10d" % 1, file=f) + if etype == 5: print("tria3", file=f) + elif etype == 6: print("tetra4", file=f) + for value in values: print("%12.5e" % value, file=f) diff --git a/src/gl.py b/src/gl.py index 467ffce..cd1f91a 100644 --- a/src/gl.py +++ b/src/gl.py @@ -8,6 +8,14 @@ # gl tool +# Imports and external programs + +from math import sin,cos,sqrt,pi,acos +from OpenGL.Tk import * +from OpenGL.GLUT import * +from PIL import Image +from vizinfo import vizinfo + oneline = "3d interactive visualization via OpenGL" docstr = """ @@ -122,14 +130,6 @@ g.sview(theta,phi,x,y,scale,up) set all view parameters # up[3] = screen up direction in simulation box (unit vector) # right[3] = screen right direction in simulation box (unit vector) -# Imports and external programs - -from math import sin,cos,sqrt,pi,acos -from OpenGL.Tk import * -from OpenGL.GLUT import * -import Image -from vizinfo import vizinfo - # Class definition class gl: @@ -500,7 +500,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 = [] @@ -528,9 +528,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]) @@ -652,7 +652,7 @@ class gl: self.w.tkRedraw() self.save(file) - print time, + print(time, end=' ') sys.stdout.flush() i += 1 n += 1 @@ -707,11 +707,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) # -------------------------------------------------------------------- @@ -777,7 +777,7 @@ 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 Exception("line type too big") red,green,blue = self.vizinfo.lcolor[itype] glColor3f(red,green,blue) thick = self.vizinfo.lrad[itype] @@ -826,7 +826,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 Exception("bond type too big") red,green,blue = self.vizinfo.bcolor[itype] rad = self.vizinfo.brad[itype] glPushMatrix() @@ -849,7 +849,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 Exception("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); @@ -907,7 +907,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 Exception("bond type too big") red,green,blue = self.vizinfo.bcolor[itype] rad = self.vizinfo.brad[itype] glPushMatrix() @@ -939,7 +939,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 Exception("tri type too big") red,green,blue = self.vizinfo.tcolor[itype] glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION, [red,green,blue,1.0]); @@ -991,7 +991,7 @@ class gl: # create new calllist for each atom type - for itype in xrange(1,self.vizinfo.nacolor+1): + for itype in range(1,self.vizinfo.nacolor+1): if self.calllist[itype]: glDeleteLists(self.calllist[itype],1) ilist = glGenLists(1) self.calllist[itype] = ilist @@ -1101,7 +1101,8 @@ class gl: pstring = glReadPixels(0,0,self.xpixels,self.ypixels, GL_RGBA,GL_UNSIGNED_BYTE) - snapshot = Image.fromstring("RGBA",(self.xpixels,self.ypixels),pstring) + #snapshot = Image.fromstring("RGBA",(self.xpixels,self.ypixels),pstring) + snapshot = Image.frombytes("RGBA",(self.xpixels,self.ypixels),pstring) snapshot = snapshot.transpose(Image.FLIP_TOP_BOTTOM) if not file: file = self.file @@ -1110,8 +1111,11 @@ class gl: # -------------------------------------------------------------------- def adef(self): - self.vizinfo.setcolors("atom",range(100),"loop") - self.vizinfo.setradii("atom",range(100),0.45) + rlist = list(range(100)) + #self.vizinfo.setcolors("atom",list(range(100)),"loop") + #self.vizinfo.setradii("atom",list(range(100)),0.45) + self.vizinfo.setcolors("atom",rlist,"loop") + self.vizinfo.setradii("atom",rlist,0.45) self.make_atom_calllist() self.cachelist = -self.cachelist self.w.tkRedraw() @@ -1119,24 +1123,24 @@ class gl: # -------------------------------------------------------------------- def bdef(self): - self.vizinfo.setcolors("bond",range(100),"loop") - self.vizinfo.setradii("bond",range(100),0.25) + self.vizinfo.setcolors("bond",list(range(100)),"loop") + self.vizinfo.setradii("bond",list(range(100)),0.25) self.cachelist = -self.cachelist self.w.tkRedraw() # -------------------------------------------------------------------- def tdef(self): - self.vizinfo.setcolors("tri",range(100),"loop") - self.vizinfo.setfills("tri",range(100),0) + self.vizinfo.setcolors("tri",list(range(100)),"loop") + self.vizinfo.setfills("tri",list(range(100)),0) self.cachelist = -self.cachelist self.w.tkRedraw() # -------------------------------------------------------------------- def ldef(self): - self.vizinfo.setcolors("line",range(100),"loop") - self.vizinfo.setradii("line",range(100),0.25) + self.vizinfo.setcolors("line",list(range(100)),"loop") + self.vizinfo.setradii("line",list(range(100)),0.25) self.cachelist = -self.cachelist self.w.tkRedraw() diff --git a/src/gnu.py b/src/gnu.py index d99ab38..9454f6b 100644 --- a/src/gnu.py +++ b/src/gnu.py @@ -8,6 +8,11 @@ # gnu tool +# Imports and external programs + +from __future__ import print_function, division, absolute_import +import types, os + oneline = "Create plots via GnuPlot plotting program" docstr = """ @@ -82,10 +87,6 @@ g.curve(N,'r') set color of curve N # figures = list of figure objects with each plot's attributes # so they aren't lost between replots -# Imports and external programs - -import types, os - try: from DEFAULTS import PIZZA_GNUPLOT except: PIZZA_GNUPLOT = "gnuplot" try: from DEFAULTS import PIZZA_GNUTERM @@ -119,7 +120,7 @@ class gnu: def enter(self): while 1: - command = raw_input("gnuplot> ") + command = input("gnuplot> ") if command == "quit" or command == "exit": return self.__call__(command) @@ -129,15 +130,15 @@ class gnu: def plot(self,*vectors): if len(vectors) == 1: file = self.file + ".%d.1" % self.current - linear = range(len(vectors[0])) + linear = list(range(len(vectors[0]))) 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 Exception("vectors must come in pairs") for i in range(0,len(vectors),2): - file = self.file + ".%d.%d" % (self.current,i/2+1) + file = self.file + ".%d.%d" % (self.current,i//2+1) self.export(file,vectors[i],vectors[i+1]) - self.figures[self.current-1].ncurves = len(vectors)/2 + self.figures[self.current-1].ncurves = len(vectors)//2 self.draw() # -------------------------------------------------------------------- @@ -167,13 +168,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 Exception("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(vectors[j][i], end=' ', file=f) + print(file=f) f.close() # -------------------------------------------------------------------- @@ -353,7 +354,7 @@ class gnu: for i in range(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] + cmd += "'" + file + "' using 1:2 with lines lc %d, " % fig.colors[i] else: cmd += "'" + file + "' using 1:2 with lines, " self.__call__(cmd[:-2]) diff --git a/src/histo.py b/src/histo.py index f9ce04c..bb7c68d 100644 --- a/src/histo.py +++ b/src/histo.py @@ -43,7 +43,7 @@ class histo: if dim == 'x': idim = 2 elif dim == 'y': idim = 3 elif dim == 'z': idim = 4 - else: raise StandardError,"illegal dim value" + else: raise Exception("illegal dim value") y = nbins*[0] @@ -78,9 +78,9 @@ class histo: n += 1 x = nbins*[0] - for i in xrange(nbins): x[i] = (i+0.5)*delta + for i in range(nbins): x[i] = (i+0.5)*delta - print "histogram snapshots = ",n - print "histogram counts (per snap) = %d (%g)" % (count,float(count)/n) - print "histogram bounds = ",lo,hi + print("histogram snapshots = ",n) + print("histogram counts (per snap) = %d (%g)" % (count,float(count)/n)) + print("histogram bounds = ",lo,hi) return x,y diff --git a/src/image.py b/src/image.py index 3aea788..58e2ecd 100644 --- a/src/image.py +++ b/src/image.py @@ -8,6 +8,15 @@ # image tool +# Imports and external programs + +from __future__ import absolute_import +import sys, os, subprocess, re, glob +from math import * +from tkinter import * +import Pmw +from PIL import Image + oneline = "View and manipulate images" docstr = """ @@ -46,14 +55,6 @@ i.montage("-geometry 512x512","i*.png","new.png") 1st arg is switch # Variables -# Imports and external programs - -import sys, os, commands, re, glob -from math import * -from Tkinter import * -import Pmw -import Image,ImageTk - try: from DEFAULTS import PIZZA_CONVERT except: PIZZA_CONVERT = "convert" try: from DEFAULTS import PIZZA_MONTAGE @@ -77,7 +78,7 @@ class image: list = str.split(filestr) files = [] for file in list: files += glob.glob(file) - if len(files) == 0: raise StandardError, "no image files to load" + if len(files) == 0: raise Exception("no image files to load") # grab Tk instance from main @@ -93,7 +94,7 @@ class image: pane = scroll.interior() ncolumns = 4 - for i in xrange(len(files)): + for i in range(len(files)): # create new row frame if 1st in column @@ -107,7 +108,7 @@ class image: imt.thumbnail((60,60),Image.ANTIALIAS) basename = os.path.basename(files[i]) imt.save("tmp." + basename) - thumbnail = ImageTk.PhotoImage(file = "tmp." + basename) + thumbnail = PhotoImage(file = "tmp." + basename) os.remove("tmp." + basename) # read in full size image @@ -115,7 +116,7 @@ class image: # create button that calls the thumbnail, label with filename # buttton needs to store thumbnail else it is garbage collected - big = ImageTk.PhotoImage(file=files[i]) + big = PhotoImage(file=files[i]) obj = thumbnails(gui,files[i],big,thumbnail) Button(oneframe,image=thumbnail,command=obj.display).pack(side=TOP) Label(oneframe,text=basename).pack(side=BOTTOM) @@ -134,7 +135,7 @@ class image: def convert(self,file1,file2,switch=""): if file1.find('*') < 0 or file2.find('*') < 0: cmd = "%s %s %s %s" % (PIZZA_CONVERT,switch,file1,file2) - commands.getoutput(cmd) + subprocess.getoutput(cmd) return index = file1.index('*') @@ -150,23 +151,23 @@ class image: middle = re.search(expr,file1).group(1) file2 = "%s%s%s" % (pre2,middle,post2) cmd = "%s %s %s %s" % (PIZZA_CONVERT,switch,file1,file2) - print middle, + print(middle, end=' ') sys.stdout.flush() - commands.getoutput(cmd) - print + subprocess.getoutput(cmd) + print() # -------------------------------------------------------------------- # wrapper on ImageMagick montage command def montage(self,switch,*fileargs): nsets = len(fileargs) - if nsets < 2: raise StandardError,"montage requires 2 or more file args" + if nsets < 2: raise Exception("montage requires 2 or more file args") for i in range(nsets): if fileargs[i].find('*') < 0: cmd = "%s %s" % (PIZZA_MONTAGE,switch) for j in range(nsets): cmd += " %s" % fileargs[j] - commands.getoutput(cmd) + subprocess.getoutput(cmd) return nfiles = len(glob.glob(fileargs[0])) @@ -174,7 +175,7 @@ class image: for i in range(nsets-1): filesets.append(glob.glob(fileargs[i])) if len(filesets[-1]) != nfiles: - raise StandardError,"each montage arg must represent equal # of files" + raise Exception("each montage arg must represent equal # of files") index = fileargs[0].index('*') pre1 = fileargs[0][:index] @@ -190,10 +191,10 @@ class image: middle = re.search(expr,filesets[0][i]).group(1) fileN = "%s%s%s" % (preN,middle,postN) cmd += " %s" % fileN - commands.getoutput(cmd) - print middle, + subprocess.getoutput(cmd) + print(middle, end=' ') sys.stdout.flush() - print + print() # -------------------------------------------------------------------- # thumbnail class diff --git a/src/ldump.py b/src/ldump.py index 4f07456..23f75f3 100644 --- a/src/ldump.py +++ b/src/ldump.py @@ -8,6 +8,13 @@ # ldump tool +# Imports and external programs + +from __future__ import absolute_import +import sys, subprocess, re, glob, types +import functools +from os import popen + oneline = "Read dump files with line segment info" docstr = """ @@ -67,11 +74,6 @@ l.owrap(...) wrap lines to same image as their atoms # xlo,xhi,ylo,yhi,zlo,zhi = box bounds (float) # atoms[i][j] = 2d array of floats, i = 0 to natoms-1, j = 0 to ncols-1 -# Imports and external programs - -import sys, commands, re, glob, types -from os import popen - try: import numpy as np oldnumeric = False @@ -99,7 +101,7 @@ class ldump: self.flist = [] for word in words: self.flist += glob.glob(word) if len(self.flist) == 0 and len(list) == 1: - raise StandardError,"no ldump file specified" + raise Exception("no ldump file specified") if len(list) == 1: self.increment = 0 @@ -124,26 +126,26 @@ class ldump: 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.snaps.sort(key = functools.cmp_to_key(self.compare_time)) self.cull() self.nsnaps = len(self.snaps) - print "read %d snapshots" % self.nsnaps + print("read %d snapshots" % self.nsnaps) # -------------------------------------------------------------------- # read next snapshot from list of files def next(self): - if not self.increment: raise StandardError,"cannot read incrementally" + if not self.increment: raise Exception("cannot read incrementally") # read next snapshot in current file using eof as pointer # if fail, try next file @@ -197,14 +199,14 @@ class ldump: 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) + floats = list(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 @@ -219,7 +221,7 @@ class ldump: def map(self,*pairs): if len(pairs) % 2 != 0: - raise StandardError, "ldump map() requires pairs of mappings" + raise Exception("ldump map() requires pairs of mappings") for i in range(0,len(pairs),2): j = i + 1 self.names[pairs[j]] = pairs[i]-1 @@ -249,9 +251,9 @@ class ldump: # -------------------------------------------------------------------- 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 Exception("no step %d exists" % n) # -------------------------------------------------------------------- # delete successive snapshots with duplicate time stamp @@ -293,7 +295,7 @@ class ldump: # don't add line if all 4 values are 0 since not a line lines = [] - for i in xrange(snap.natoms): + for i in range(snap.natoms): atom = snap.atoms[i] e1x = atom[end1x] e1y = atom[end1y] @@ -323,7 +325,7 @@ class ldump: # jdump = atom J in dump's atoms that atom I was owrapped on # delx,dely = offset applied to atom I and thus to line I - for i in xrange(snap.natoms): + for i in range(snap.natoms): tag = atoms[i][id] idump = idsdump[tag] jdump = idsdump[atomsdump[idump][iother]] diff --git a/src/log.py b/src/log.py index 73c35ea..02f8969 100644 --- a/src/log.py +++ b/src/log.py @@ -8,6 +8,13 @@ # log tool +# Imports and external programs + +from __future__ import absolute_import +import sys, re, glob +import functools +from os import popen + oneline = "Read LAMMPS log files and extract thermodynamic data" docstr = """ @@ -50,11 +57,6 @@ l.write("file.txt","Time","PE",...) write listed vectors to a file # increment = 1 if log file being read incrementally # eof = ptr into incremental file for where to start next read -# Imports and external programs - -import sys, re, glob -from os import popen - try: tmp = PIZZA_GUNZIP except: PIZZA_GUNZIP = "gunzip" @@ -76,14 +78,14 @@ class log: self.flist = [] for word in words: self.flist += glob.glob(word) if len(self.flist) == 0 and len(list) == 1: - raise StandardError,"no log file specified" + raise Exception("no log file specified") if len(list) == 1: self.increment = 0 self.read_all() else: if len(self.flist) > 1: - raise StandardError,"can only incrementally read one log file" + raise Exception("can only incrementally read one log file") self.increment = 1 self.eof = 0 @@ -92,24 +94,24 @@ class log: def read_all(self): self.read_header(self.flist[0]) - if self.nvec == 0: raise StandardError,"log file has no values" + if self.nvec == 0: raise Exception("log file has no values") # read all files for file in self.flist: self.read_one(file) - print + print() # sort entries by timestep, cull duplicates - self.data.sort(self.compare) + self.data.sort(key = functools.cmp_to_key(self.compare)) self.cull() self.nlen = len(self.data) - print "read %d log entries" % self.nlen + print("read %d log entries" % self.nlen) # -------------------------------------------------------------------- def next(self): - if not self.increment: raise StandardError,"cannot read incrementally" + if not self.increment: raise Exception("cannot read incrementally") if self.nvec == 0: try: open(self.flist[0],'r') @@ -124,11 +126,11 @@ class log: def get(self,*keys): if len(keys) == 0: - raise StandardError, "no log vectors specified" + raise Exception("no log vectors specified") map = [] for key in keys: - if self.ptr.has_key(key): + if key in self.ptr: map.append(self.ptr[key]) else: count = 0 @@ -139,12 +141,12 @@ class log: if count == 1: map.append(index) else: - raise StandardError, "unique log vector %s not found" % key + raise Exception("unique log vector %s not found" % key) vecs = [] for i in range(len(keys)): vecs.append(self.nlen * [0]) - for j in xrange(self.nlen): + for j in range(self.nlen): vecs[i][j] = self.data[j][map[i]] if len(keys) == 1: return vecs[0] @@ -156,7 +158,7 @@ class log: if len(keys): map = [] for key in keys: - if self.ptr.has_key(key): + if key in self.ptr: map.append(self.ptr[key]) else: count = 0 @@ -167,15 +169,15 @@ class log: if count == 1: map.append(index) else: - raise StandardError, "unique log vector %s not found" % key + raise Exception("unique log vector %s not found" % key) else: - map = range(self.nvec) + map = list(range(self.nvec)) f = open(filename,"w") - for i in xrange(self.nlen): - for j in xrange(len(map)): - print >>f,self.data[i][map[j]], - print >>f + for i in range(self.nlen): + for j in range(len(map)): + print(self.data[i][map[j]], end=' ', file=f) + print(file=f) f.close() # -------------------------------------------------------------------- @@ -241,18 +243,18 @@ class log: # -------------------------------------------------------------------- - def read_one(self,*list): + def read_one(self,*flist): # if 2nd arg exists set file ptr to that value # read entire (rest of) file into txt - file = list[0] + file = flist[0] if file[-3:] == ".gz": - f = popen("%s -c %s" % (PIZZA_GUNZIP,file),'rb') + f = popen("%s -c %s" % (PIZZA_GUNZIP,file),'r') else: - f = open(file,'rb') + f = open(file,'r') - if len(list) == 2: f.seek(list[1]) + if len(flist) == 2: f.seek(flist[1]) txt = f.read() if file[-3:] == ".gz": eof = 0 else: eof = f.tell() @@ -318,17 +320,17 @@ class log: word1 = [re.search(pat1,section).group(1)] word2 = re.findall(pat2,section) words = word1 + word2 - self.data.append(map(float,words)) + self.data.append(list(map(float,words))) else: lines = chunk.split("\n") for line in lines: words = line.split() - self.data.append(map(float,words)) + self.data.append(list(map(float,words))) # print last timestep of chunk - print int(self.data[len(self.data)-1][0]), + print(int(self.data[len(self.data)-1][0]), end=' ') sys.stdout.flush() return eof diff --git a/src/lpp.py b/src/lpp.py index 9840022..d9696b2 100755 --- a/src/lpp.py +++ b/src/lpp.py @@ -1,32 +1,33 @@ #!/usr/bin/env python +from __future__ import print_function, absolute_import +import getopt +import os +import time +import sys +import multiprocessing +import glob +import vtk +from math import ceil +from math import floor +from dump import dump oneline = "writing pp-data in vtk format automatically, saving memory" docstr = """this is the docstr of LIGGGHTSPostProcessing""" -from dump import dump -from math import floor -from math import ceil -import vtk -import glob -import multiprocessing -import sys -import time -import os -import exceptions # changes py p.s. - include a few command line options -import getopt + class lpp: - #============================================================================= + # ============================================================================= # creates a filelist, seperates it to sublists # creates multiple processes # calls lppWorker for each sublist # lppWorker # calls dump, vtk and manyGran for the given list of files # returns 0 - #============================================================================= + # ============================================================================= def __init__(self, *list, **kwargs): # do argument parsing, raise errors if non-integers were given @@ -35,43 +36,66 @@ class lpp: self.cpunum = multiprocessing.cpu_count() self.chunksize = 8 self.overwrite = True + self.Nth = 1 + self.timesteps = "all" if "--chunksize" in kwargs: try: if int(kwargs["--chunksize"]) > 0: self.chunksize = int(kwargs["--chunksize"]) - else: raise ValueError + else: + raise ValueError except ValueError: - raise ValueError, "Invalid or no argument given for chunksize" + raise ValueError("Invalid or no argument given for chunksize") + + if "--Nth" in kwargs: + try: + if int(kwargs["--Nth"]) > 0 and int(kwargs["--Nth"]) >= self.Nth: + self.Nth = int(kwargs["--Nth"]) + else: + raise ValueError + except ValueError: + raise ValueError("Invalid or no argument given for Nth") + + if "--timesteps" in kwargs: + try: + self.timesteps = kwargs["--timesteps"] + except ValueError: + raise ValueError("Invalid or no argument given for timesteps") if "--cpunum" in kwargs: try: if int(kwargs["--cpunum"]) > 0 and int(kwargs["--cpunum"]) <= self.cpunum: self.cpunum = int(kwargs["--cpunum"]) - else: raise ValueError + else: + raise ValueError except ValueError: - raise ValueError, "Invalid or no argument given for cpunum" + raise ValueError("Invalid or no argument given for cpunum") # do not overwrite existing files if "--no-overwrite" in kwargs: self.overwrite = False # suppress output with 'False' - if "--debug" in kwargs: self.debugMode = True - else: self.debugMode = False + if "--debug" in kwargs: + self.debugMode = True + else: + self.debugMode = False if "--quiet" in kwargs: self.output = False self.debugMode = False - else: self.output = True + else: + self.output = True if self.output: - print "starting LIGGGHTS memory optimized parallel post processing" - print "chunksize:", self.chunksize, "-->",self.chunksize,\ - "files are processed per chunk. If you run out of memory reduce chunksize." - starttime = time.time() + print("starting LIGGGHTS memory optimized parallel post processing") + print("chunksize:", self.chunksize, "-->",self.chunksize,\ + "files are processed per chunk. If you run out of memory reduce chunksize.") + starttime = time.time() - if self.debugMode: print "number of process:", os.getpid() + if self.debugMode: + print("number of process:", os.getpid()) # check whether file-list is nonempty self.flist = [] @@ -86,42 +110,47 @@ class lpp: self.flist = list[0] listlen = len(self.flist) if listlen == 0 and len(list) == 1: - raise StandardError, "no dump file specified" + raise Exception("no dump file specified") if listlen == 1 and self.overwrite == False: - raise StandardError, "Cannot process single dump files with --no-overwrite." + raise Exception("Cannot process single dump files with --no-overwrite.") if self.output: - print "Working with", self.cpunum, "processes..." + print("Working with", self.cpunum, "processes...") # seperate list in pieces+rest self.slices = [] residualPresent = int(bool(listlen-floor(listlen/self.chunksize)*self.chunksize)) - for i in xrange(int(floor(listlen/self.chunksize))+residualPresent): + for i in range(int(floor(listlen/self.chunksize))+residualPresent): slice = self.flist[i*self.chunksize:(i+1)*self.chunksize] self.slices.append(slice) self.flist = [] output = "" - if "-o" in kwargs: output = kwargs["-o"] + if "-o" in kwargs: + output = kwargs["-o"] # generate input for lppWorker dumpInput = [{"filelist":self.slices[i],\ "debugMode":self.debugMode,\ "output":output,\ - "overwrite":self.overwrite} \ - for i in xrange(len(self.slices))] + "overwrite":self.overwrite,\ + "timesteps":self.timesteps,\ + "Nth":self.Nth} \ + for i in range(len(self.slices))] - if self.debugMode: print "dumpInput:",dumpInput + if self.debugMode: + print("dumpInput:",dumpInput) numberOfRuns = len(dumpInput) i = 0 while i < len(dumpInput): if self.output: - print "calculating chunks",i+1,"-",min(i+self.cpunum,numberOfRuns),"of",numberOfRuns + print("calculating chunks",i+1,"-",min(i+self.cpunum,numberOfRuns),"of",numberOfRuns) - if self.debugMode: print "input of this \"map\": ",dumpInput[i:i+self.cpunum] + if self.debugMode: + print("input of this \"map\": ",dumpInput[i:i+self.cpunum]) # create job_server job_server = multiprocessing.Pool(processes = self.cpunum) @@ -136,14 +165,16 @@ class lpp: endtime = time.time() if self.output: - print "wrote", listlen,"granular snapshots in VTK format" - print "time needed:",endtime-starttime,"sec" + print("wrote", listlen,"granular snapshots in VTK format") + print("time needed:",endtime-starttime,"sec") def lppWorker(input): flist = input["filelist"] debugMode = input["debugMode"] outfileName = input["output"] overwrite = input["overwrite"] + Nth = input["Nth"] + timesteps = input["timesteps"] flistlen = len(flist) # generate name of manyGran @@ -184,8 +215,25 @@ def lppWorker(input): # call dump, vtk, manyGran on shortFlist try: d = dump({"filelist":shortFlist, "debugMode":debugMode}) + + if timesteps != "all": + tsteps = timesteps.split(",") + filterstring = "" + j = 1 + for i in tsteps: + if j == 1: + filterstring = filterstring + "$t == " + str(i) + else: + filterstring = filterstring + " or $t == " + str(i) + j = j + 1 + d.tselect.test(filterstring) + elif Nth != 1: + d.tselect.skip(Nth) + d.delete() + v = vtk.vtk(d) - if debugMode: print "\nfileNums: ",d.fileNums,"\n" + if debugMode: + print("\nfileNums: ",d.fileNums,"\n") v.manyGran(granName,fileNos=d.fileNums,output=debugMode) except KeyboardInterrupt: raise @@ -193,21 +241,24 @@ def lppWorker(input): return 0 def printHelp(): - print "usage: pizza [options] dump.example\n where dump.example is a filename",\ - "or regular expression passing all relevant dump files to pizza." - print "Important command line options:" - print "-o fname : define output file name (default is liggghts + timestep number)" - print "--chunksize : sets the chunksize, default: 8" - print "--cpunum : sets the number of processes to start, default (and maximum)",\ - "is the amout of cpu cores avaliable at your system" - print "--help : writes this help message and exits" - print "--no-overwrite: disables overwriting of already post-processed files." - print "For details, read README_GRANULAR.txt" + print("usage: pizza [options] dump.example\n where dump.example is a filename",\ + "or regular expression passing all relevant dump files to pizza.") + print("Important command line options:") + print("-o fname : define output file name (default is liggghts + timestep number)") + print("--chunksize : sets the chunksize, default: 8") + print("--cpunum : sets the number of processes to start, default (and maximum)",\ + "is the amout of cpu cores avaliable at your system") + print("--help : writes this help message and exits") + print("--no-overwrite: disables overwriting of already post-processed files.") + print("--timesteps: time steps to be converted, input as comma seperated list.") + print("--Nth: every Nth time step will be converted, cannot be combined with timesteps.") + print("For details, read README_GRANULAR.txt") if __name__ == "__main__": if len(sys.argv) > 1: # parse options - optlist, args = getopt.gnu_getopt(sys.argv[1:],'o:',['chunksize=','cpunum=','debug','help','quiet','no-overwrite']) + optlist, args = getopt.gnu_getopt(sys.argv[1:],'o:',[ + 'chunksize=','cpunum=','Nth=','timesteps=','debug','help','quiet','no-overwrite']) optdict = dict(optlist) if "--help" in optdict: printHelp() @@ -215,17 +266,17 @@ if __name__ == "__main__": try: lpp(args,**optdict) except KeyboardInterrupt: - print "aborted by user" - except BaseException, e: - print "aborting due to errors:", e + print("aborted by user") + except BaseException as e: + print("aborting due to errors:", e) - #=========================================================================== + # =========================================================================== # except: # if sys.exc_type == exceptions.SystemExit: # pass # else: - # print sys.exc_info() - #=========================================================================== + # print(sys.exc_info()) + # =========================================================================== else: printHelp() diff --git a/src/matlab.py b/src/matlab.py index 2c55ea2..1dd15ea 100644 --- a/src/matlab.py +++ b/src/matlab.py @@ -8,6 +8,11 @@ # matlab tool +# Imports and external programs + +from __future__ import print_function, division, absolute_import +import types, os + oneline = "Create plots via MatLab numerical analysis program" docstr = """ @@ -91,10 +96,6 @@ m.curve(N,'b','-','v') set color, line style, symbol of curve N # allow for alternate export command to name the variables from Python # in MatLab and vice versa -# Imports and external programs - -import types, os - try: from DEFAULTS import PIZZA_MATLAB except: PIZZA_MATLAB = "matlab -nosplash -nodesktop -nojvm" @@ -126,7 +127,7 @@ class matlab: def enter(self): while 1: - command = raw_input("matlab> ") + command = input("matlab> ") if command == "quit" or command == "exit": return self.__call__(command) @@ -136,15 +137,15 @@ class matlab: def plot(self,*vectors): if len(vectors) == 1: file = self.file + ".%d.1" % self.current - linear = range(len(vectors[0])) + linear = list(range(len(vectors[0]))) 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 Exception("vectors must come in pairs") for i in range(0,len(vectors),2): - file = self.file + ".%d.%d" % (self.current,i/2+1) + file = self.file + ".%d.%d" % (self.current,i//2+1) self.export(file,vectors[i],vectors[i+1]) - self.figures[self.current-1].ncurves = len(vectors)/2 + self.figures[self.current-1].ncurves = len(vectors)//2 self.draw() # -------------------------------------------------------------------- @@ -174,13 +175,13 @@ class matlab: 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 Exception("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(vectors[j][i], end=' ', file=f) + print(file=f) f.close() # -------------------------------------------------------------------- diff --git a/src/mdump.py b/src/mdump.py index 089b4d3..1428c23 100644 --- a/src/mdump.py +++ b/src/mdump.py @@ -8,6 +8,14 @@ # mdump tool +# Imports and external programs + +from __future__ import absolute_import +import sys, subprocess, re, glob, types +import functools +from os import popen +from math import * # any function could be used by set() + oneline = "Read, write, manipulate mesh dump files" docstr = """ @@ -124,12 +132,6 @@ m.etype = "color" set column returned as "type" by viz # nevalues = # of node values # evalues[i][j] = 2d array of floats, i = 0 to Nel-1, j = 0 to Ncol -# Imports and external programs - -import sys, commands, re, glob, types -from os import popen -from math import * # any function could be used by set() - try: import numpy as np oldnumeric = False @@ -160,7 +162,7 @@ class mdump: 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 Exception("no dump file specified") if len(list) == 1: self.increment = 0 @@ -185,16 +187,16 @@ class mdump: 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 and combine duplicates - self.snaps.sort(self.compare_time) + self.snaps.sort(key = functools.cmp_to_key(self.compare_time)) self.cull() # sort all node, element, nvalue, evalue arrays by ID @@ -204,25 +206,25 @@ class mdump: array = snap.nodes ids = array[:,0] ordering = np.argsort(ids) - for i in xrange(len(array[0])): + for i in range(len(array[0])): array[:,i] = np.take(array[:,i],ordering) if snap.eflag: array = snap.elements ids = array[:,0] ordering = np.argsort(ids) - for i in xrange(len(array[0])): + for i in range(len(array[0])): array[:,i] = np.take(array[:,i],ordering) if snap.nvalueflag: array = snap.nvalues ids = array[:,0] ordering = np.argsort(ids) - for i in xrange(len(array[0])): + for i in range(len(array[0])): array[:,i] = np.take(array[:,i],ordering) if snap.evalueflag: array = snap.evalues ids = array[:,0] ordering = np.argsort(ids) - for i in xrange(len(array[0])): + for i in range(len(array[0])): array[:,i] = np.take(array[:,i],ordering) # reference definitions of nodes and elements in previous timesteps @@ -230,7 +232,7 @@ class mdump: self.reference() self.nsnaps = len(self.snaps) - print "read %d snapshots" % self.nsnaps + print("read %d snapshots" % self.nsnaps) # select all timesteps and elements @@ -241,7 +243,7 @@ class mdump: def next(self): - if not self.increment: raise StandardError,"cannot read incrementally" + if not self.increment: raise Exception("cannot read incrementally") # read next snapshot in current file using eof as pointer # if fail, try next file @@ -271,7 +273,7 @@ class mdump: snap.tselect = 1 snap.nselect = snap.nelements if snap.eflag: - for i in xrange(snap.nelements): snap.eselect[i] = 1 + for i in range(snap.nelements): snap.eselect[i] = 1 self.nsnaps += 1 self.nselect += 1 @@ -295,7 +297,7 @@ class mdump: elif "NUMBER OF CUBES" in str: snap.eflag = 4 elif "NUMBER OF NODE VALUES" in str: snap.nvalueflag = 1 elif "NUMBER OF ELEMENT VALUES" in str: snap.evalueflag = 1 - else: raise StandardError,"unrecognized snapshot in dump file" + else: raise Exception("unrecognized snapshot in dump file") n = int(f.readline()) if snap.eflag: snap.eselect = np.zeros(n) @@ -313,14 +315,14 @@ class mdump: if n: words = f.readline().split() ncol = len(words) - for i in xrange(1,n): + for i in range(1,n): words += f.readline().split() - floats = map(float,words) + floats = list(map(float,words)) if oldnumeric: values = np.zeros((n,ncol),np.Float) else: values = np.zeros((n,ncol),np.float) start = 0 stop = ncol - for i in xrange(n): + for i in range(n): values[i] = floats[start:stop] start = stop stop += ncol @@ -343,7 +345,7 @@ class mdump: def map(self,*pairs): if len(pairs) % 2 != 0: - raise StandardError, "mdump map() requires pairs of mappings" + raise Exception("mdump map() requires pairs of mappings") for i in range(0,len(pairs),2): j = i + 1 self.names[pairs[j]] = pairs[i]-1 @@ -360,15 +362,15 @@ class mdump: 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) # -------------------------------------------------------------------- # sort elements by ID in all selected timesteps or one timestep 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) @@ -385,7 +387,7 @@ class mdump: 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) # -------------------------------------------------------------------- @@ -406,10 +408,10 @@ class mdump: def vecs(self,n,*list): snap = self.snaps[self.findtime(n)] if not snap.evalues: - raise StandardError, "snapshot has no element values" + raise Exception("snapshot has no element values") if len(list) == 0: - raise StandardError, "no columns specified" + raise Exception("no columns specified") columns = [] values = [] for name in list: @@ -418,9 +420,9 @@ class mdump: ncol = len(columns) m = 0 - for i in xrange(len(snap.evalues)): + for i in range(len(snap.evalues)): if not snap.eselect[i]: continue - for j in xrange(ncol): + for j in range(ncol): values[j][m] = snap.evalues[i][columns[j]] m += 1 @@ -482,9 +484,9 @@ class mdump: # if not, point it at most recent shapshot that does def reference(self): - for i in xrange(len(self.snaps)): + for i in range(len(self.snaps)): if not self.snaps[i].nflag: - for j in xrange(i,-1,-1): + for j in range(i,-1,-1): if self.snaps[j].nflag: self.snaps[i].nflag = self.snaps[j].nflag self.snaps[i].nnodes = self.snaps[j].nnodes @@ -497,9 +499,9 @@ class mdump: self.snaps[i].zhi = self.snaps[j].zhi break if not self.snaps[i].nflag: - raise StandardError,"no nodal coords found in previous snapshots" + raise Exception("no nodal coords found in previous snapshots") if not self.snaps[i].eflag: - for j in xrange(i,-1,-1): + for j in range(i,-1,-1): if self.snaps[j].eflag: self.snaps[i].eflag = self.snaps[j].eflag self.snaps[i].nelements = self.snaps[j].nelements @@ -507,7 +509,7 @@ class mdump: self.snaps[i].eselect = self.snaps[j].eselect break if not self.snaps[i].eflag: - raise StandardError,"no elem connections found in previous snapshots" + raise Exception("no elem connections found in previous snapshots") # -------------------------------------------------------------------- # iterate over selected snapshots @@ -515,7 +517,7 @@ class mdump: 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 @@ -550,7 +552,7 @@ class mdump: tris = [] nodes = snap.nodes - for i in xrange(snap.nelements): + for i in range(snap.nelements): if not snap.eselect[i]: continue element = snap.elements[i] if snap.evalueflag: evalue = snap.evalues[i] @@ -699,9 +701,9 @@ class mdump: # -------------------------------------------------------------------- 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 Exception("no step %d exists" % n) # -------------------------------------------------------------------- # return maximum box size across all selected snapshots @@ -751,7 +753,7 @@ class tselect: snap.tselect = 1 data.nselect = len(data.snaps) data.eselect.all() - print "%d snapshots selected out of %d" % (data.nselect,data.nsnaps) + print("%d snapshots selected out of %d" % (data.nselect,data.nsnaps)) # -------------------------------------------------------------------- @@ -763,7 +765,7 @@ class tselect: data.snaps[i].tselect = 1 data.nselect = 1 data.eselect.all() - print "%d snapshots selected out of %d" % (data.nselect,data.nsnaps) + print("%d snapshots selected out of %d" % (data.nselect,data.nsnaps)) # -------------------------------------------------------------------- @@ -772,7 +774,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)) # -------------------------------------------------------------------- @@ -788,7 +790,7 @@ class tselect: snap.tselect = 0 data.nselect -= 1 data.eselect.all() - print "%d snapshots selected out of %d" % (data.nselect,data.nsnaps) + print("%d snapshots selected out of %d" % (data.nselect,data.nsnaps)) # -------------------------------------------------------------------- @@ -797,14 +799,16 @@ 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 + ldict = {'data':data,'snaps':snaps,'i':i} + exec(ccmd,globals(),ldict) + flag = ldict['flag'] if not flag: snaps[i].tselect = 0 data.nselect -= 1 data.eselect.all() - print "%d snapshots selected out of %d" % (data.nselect,data.nsnaps) + print("%d snapshots selected out of %d" % (data.nselect,data.nsnaps)) # -------------------------------------------------------------------- # element selection class @@ -821,12 +825,12 @@ class eselect: if len(args) == 0: # all selected timesteps for snap in data.snaps: if not snap.tselect: continue - for i in xrange(snap.nelements): snap.eselect[i] = 1 + for i in range(snap.nelements): snap.eselect[i] = 1 snap.nselect = snap.nelements else: # one timestep n = data.findtime(args[0]) snap = data.snaps[n] - for i in xrange(snap.nelements): snap.eselect[i] = 1 + for i in range(snap.nelements): snap.eselect[i] = 1 snap.nselect = snap.nelements # -------------------------------------------------------------------- @@ -849,29 +853,29 @@ class eselect: if len(args) == 0: # all selected timesteps for snap in data.snaps: if not snap.tselect: continue - for i in xrange(snap.nelements): + for i in range(snap.nelements): if not snap.eselect[i]: continue - exec ccmd + exec(ccmd) if not flag: snap.eselect[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].nelements,data.snaps[i].time) + print("%d atoms of %d selected in first step %d" % \ + (data.snaps[i].nselect,data.snaps[i].nelements,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].nelements,data.snaps[i].time) + print("%d atoms of %d selected in last step %d" % \ + (data.snaps[i].nselect,data.snaps[i].nelements,data.snaps[i].time)) break else: # one timestep n = data.findtime(args[0]) snap = data.snaps[n] - for i in xrange(snap.nelements): + for i in range(snap.nelements): if not snap.eselect[i]: continue - exec ccmd + exec(ccmd) if not flag: snap.eselect[i] = 0 snap.nselect -= 1 diff --git a/src/pair.py b/src/pair.py index 80240f7..c1e3ce3 100644 --- a/src/pair.py +++ b/src/pair.py @@ -8,6 +8,11 @@ # pair tool +# Imports and external programs + +from __future__ import absolute_import +from math import sqrt + oneline = "Compute LAMMPS pairwise energies" docstr = """ @@ -41,10 +46,6 @@ e_vdwl,e_coul = p.single(rsq,itype,jtype,q1,q2,...) compute LJ/Coul energy # Variables -# Imports and external programs - -from math import sqrt - # Class definition class pair: @@ -68,7 +69,7 @@ class pair: self.init_func = self.init_lj_charmm_coul_charmm self.single_func = self.single_lj_charmm_coul_charmm else: - raise StandardError, "this pair style not yet supported" + raise Exception("this pair style not yet supported") # -------------------------------------------------------------------- # generic coeff method @@ -99,10 +100,10 @@ class pair: self.lj3 = [] self.lj4 = [] - for i in xrange(ntypes): + for i in range(ntypes): self.lj3.append(ntypes * [0]) self.lj4.append(ntypes * [0]) - for j in xrange(ntypes): + for j in range(ntypes): epsilon_ij = sqrt(epsilon[i]*epsilon[j]) sigma_ij = sqrt(sigma[i]*sigma[j]) self.lj3[i][j] = 4.0 * epsilon_ij * pow(sigma_ij,12.0); @@ -143,10 +144,10 @@ class pair: self.lj3 = [] self.lj4 = [] - for i in xrange(ntypes): + for i in range(ntypes): self.lj3.append(ntypes * [0]) self.lj4.append(ntypes * [0]) - for j in xrange(ntypes): + for j in range(ntypes): epsilon_ij = sqrt(epsilon[i]*epsilon[j]) sigma_ij = sqrt(sigma[i]*sigma[j]) self.lj3[i][j] = 4.0 * epsilon_ij * pow(sigma_ij,12.0); @@ -197,10 +198,10 @@ class pair: self.lj3 = [] self.lj4 = [] - for i in xrange(ntypes): + for i in range(ntypes): self.lj3.append(ntypes * [0]) self.lj4.append(ntypes * [0]) - for j in xrange(ntypes): + for j in range(ntypes): epsilon_ij = sqrt(epsilon[i]*epsilon[j]) sigma_ij = 0.5 * (sigma[i] + sigma[j]) self.lj3[i][j] = 4.0 * epsilon_ij * pow(sigma_ij,12.0); diff --git a/src/patch.py b/src/patch.py index 6877d11..8651b5e 100644 --- a/src/patch.py +++ b/src/patch.py @@ -8,6 +8,12 @@ # patch tool +# Imports and external programs + +from __future__ import absolute_import +from math import sqrt,pi,cos,sin +from data import data + oneline = "Create patchy Lennard-Jones particles for LAMMPS input" docstr = """ @@ -61,11 +67,6 @@ p.write("data.patch") write out system to LAMMPS data file # seed = random seed # molecules = list of atoms, grouped by molecule -# Imports and external programs - -from math import sqrt,pi,cos,sin -from data import data - # Class definition class patch: @@ -98,8 +99,14 @@ class patch: if style == "linebox" or style == "linetri": self.style = "line" if style == "tritet" or style == "tribox": self.style = "tri" cmd = "atoms,bonds,tris,segments,volume = self.%s(*types)" % style - for i in xrange(n): - exec cmd + for i in range(n): + ldict = {'i':i,'self':self,'types':types} + exec(cmd,globals(),ldict) + atoms = ldict['atoms'] + bonds = ldict['bonds'] + tris = ldict['tris'] + segments = ldict['segments'] + volume = ldict['volume'] self.molecules.append([atoms,bonds,tris,segments]) self.volume += volume @@ -131,7 +138,7 @@ class patch: latflag = 1 if self.lattice[0]*self.lattice[1]*self.lattice[2] != \ len(self.molecules): - raise StandardError,"lattice inconsistent with # of molecules" + raise Exception("lattice inconsistent with # of molecules") else: latflag = 0 idatom = idbond = idtri = idmol = 0 @@ -343,7 +350,7 @@ class patch: if self.lattice[0] or self.lattice[1]: latflag = 1 if self.lattice[0]*self.lattice[1] != len(self.molecules): - raise StandardError,"lattice inconsistent with # of molecules" + raise Exception("lattice inconsistent with # of molecules") else: latflag = 0 idatom = idbond = idmol = 0 @@ -885,7 +892,7 @@ class patch: sep = params[1] type = params[2] if n % 2 == 0: - raise StandardError, "N in patch::star2d is not odd" + raise Exception("N in patch::star2d is not odd") middle = n/2 atoms = [] @@ -1131,7 +1138,7 @@ class patch: # -------------------------------------------------------------------- def random(self): - k = self.seed/IQ + k = self.seed//IQ self.seed = IA*(self.seed-k*IQ) - IR*k if self.seed < 0: self.seed += IM diff --git a/src/pdbfile.py b/src/pdbfile.py index 9b2238c..fb7e3e4 100644 --- a/src/pdbfile.py +++ b/src/pdbfile.py @@ -8,6 +8,11 @@ # pdb tool +# Imports and external programs + +from __future__ import absolute_import +import sys, types, glob, urllib.request, urllib.parse, urllib.error + oneline = "Read, write PDB files in combo with LAMMPS snapshots" docstr = """ @@ -62,10 +67,6 @@ index,time,flag = p.iterator(1) # atomlines = dict of ATOM lines in original PDB file # key = atom id, value = tuple of (beginning,end) of line -# Imports and external programs - -import sys, types, glob, urllib - # Class definition class pdbfile: @@ -74,7 +75,7 @@ class pdbfile: def __init__(self,*args): if len(args) == 1: - if type(args[0]) is types.StringType: + if type(args[0]) is bytes: filestr = args[0] self.data = None else: @@ -83,7 +84,7 @@ class pdbfile: elif len(args) == 2: filestr = args[0] self.data = args[1] - else: raise StandardError, "invalid args for pdb()" + else: raise Exception("invalid args for pdb()") # flist = full list of all PDB input file names # append .pdb if needed @@ -94,17 +95,17 @@ class pdbfile: for file in list: if '*' in file: flist += glob.glob(file) else: flist.append(file) - for i in xrange(len(flist)): + for i in range(len(flist)): if flist[i][-4:] != ".pdb": flist[i] += ".pdb" if len(flist) == 0: - raise StandardError,"no PDB file specified" + raise Exception("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 Exception("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 Exception("no input PDB file(s)") # grab PDB file from http://rcsb.org if not a local file @@ -112,9 +113,9 @@ 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]) + urllib.request.urlretrieve(fetchstr,self.files[0]) if self.data and len(self.files): self.read_template(self.files[0]) @@ -142,20 +143,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 +191,7 @@ class pdbfile: self.convert(f,which) f.close() - print time, + print(time, end=' ') sys.stdout.flush() n += 1 @@ -210,12 +211,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 @@ -277,13 +278,13 @@ class pdbfile: if len(self.files): for atom in atoms: id = atom[0] - if self.atomlines.has_key(id): + if id in self.atomlines: (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, end=' ', file=f) 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/src/pizza.py b/src/pizza.py index e92027c..78c5d8d 100755 --- a/src/pizza.py +++ b/src/pizza.py @@ -15,6 +15,12 @@ # ToDo list: +# modules needed by pizza.py + +from __future__ import absolute_import +import sys, subprocess, os, string, glob, re +import time + # Help strings: version = "LPP 1.0 based on pizza - 7 Oct 2011" @@ -50,18 +56,13 @@ Tools: """ # ------------------------------------------------------------------------- -# modules needed by pizza.py - -import sys, commands, os, string, exceptions, glob, re -from time import clock - # readline not available in all Pythons try: import readline readline_flag = 1 -except ImportError, exception: - print "readline option not available" +except ImportError as exception: + print("readline option not available") readline_flag = 0 # create global Tk root if Tkinter is loaded @@ -69,13 +70,13 @@ except ImportError, exception: nodisplay = False try: - import Tkinter - tkroot = Tkinter.Tk() + import tkinter + tkroot = tkinter.Tk() tkroot.withdraw() -except ImportError, exception: +except ImportError as exception: nodisplay = True pass -except Exception, exception: +except Exception as exception: nodisplay = True pass @@ -107,22 +108,22 @@ def trap(type,value,tback): words = value.text.split() if len(words) == 1 and words[0] == "?": - print intro[1:] % version - print help[1:]," ", - for tool in tools: print tool, - print + print(intro[1:] % version) + print(help[1:]," ", end=' ') + for tool in tools: print(tool, end=' ') + print() elif len(words) == 1 and words[0] == "??": for tool in tools: - exec "oneline = oneline_%s" % tool - print "%-11s%s" % (tool,oneline) - print + exec("oneline = oneline_%s" % tool) + print("%-11s%s" % (tool,oneline)) + print() scripts = [] for dir in PIZZA_SCRIPTS[1:]: - list = glob.glob("%s/*.py" % dir) - list.sort() - scripts += list + flist = glob.glob("%s/*.py" % dir) + flist.sort() + scripts += flist for script in scripts: filename = os.path.basename(script) lines = open(script,'r').readlines() @@ -133,7 +134,7 @@ def trap(type,value,tback): break if flag: doc = line[line.find("Purpose:")+8:] else: doc = " not available\n" - print "%-20s%s" % (filename,doc), + print("%-20s%s" % (filename,doc), end=' ') elif len(words) == 2 and words[0] == "?": if words[1][-3:] == ".py": @@ -145,25 +146,25 @@ def trap(type,value,tback): lineflag = 0 lines = open(filename,'r').readlines() for line in lines: - if line.find("# Purpose:") >= 0: print line[2:], + if line.find("# Purpose:") >= 0: print(line[2:], end=' ') if line.find("# Syntax:") >= 0: lineflag = 1 break - if not lineflag: print "%s has no Syntax line" % words[1] - else: print line[2:], + if not lineflag: print("%s has no Syntax line" % words[1]) + else: print(line[2:], end=' ') break if not fileflag: - print "%s is not a recognized script" % words[1] + print("%s is not a recognized script" % words[1]) else: if words[1] in tools: - exec "txt = docstr_%s" % words[1] + exec("txt = docstr_%s" % words[1]) txt = re.sub("\n\s*\n","\n",txt) txt = re.sub("\n .*","",txt) - exec "print oneline_%s" % words[1] - print txt + exec("print oneline_%s" % words[1]) + print(txt) else: - print "%s is not a recognized tool" % words[1] + print("%s is not a recognized tool" % words[1]) elif len(words) == 2 and words[0] == "??": if words[1][-3:] == ".py": @@ -175,18 +176,18 @@ def trap(type,value,tback): lines = open(filename,'r').readlines() for line in lines: if len(line.strip()) == 0: continue - if line[0] == '#': print line, + if line[0] == '#': print(line, end=' ') else: break break if not fileflag: - print "%s is not a recognized script" % words[1] + print("%s is not a recognized script" % words[1]) else: if words[1] in tools: - exec "print oneline_%s" % words[1] - exec "print docstr_%s" % words[1] + exec("print oneline_%s" % words[1]) + exec("print docstr_%s" % words[1]) else: - print "%s is not a recognized class" % words[1] + print("%s is not a recognized class" % words[1]) return @@ -208,13 +209,13 @@ def trap(type,value,tback): return elif words[0][1:] == "log": if readline_flag == 0: - print "cannot use @log without readline module" + print("cannot use @log without readline module") return f = open(words[1],"w") - print >>f,"# pizza.py log file\n" + print("# pizza.py log file\n", file=f) nlines = readline.get_current_history_length() - for i in xrange(1,nlines): - print >>f,readline.get_history_item(i) + for i in range(1,nlines): + print(readline.get_history_item(i), file=f) f.close() return elif words[0][1:] == "run": @@ -225,17 +226,17 @@ def trap(type,value,tback): fullfile = dir + '/' + file if os.path.exists(fullfile): flag = 1 - print "Executing file:",fullfile - execfile(fullfile,namespace) + print("Executing file:",fullfile) + exec(compile(open(fullfile).read(), fullfile, 'exec'),namespace) break - if not flag: print "Could not find file",file + if not flag: print("Could not find file",file) return elif words[0][1:] == "time": cmd = string.join(words[1:]) t1 = clock() - exec cmd in namespace + exec(cmd, namespace) t2 = clock() - print "CPU time = ",t2-t1 + print("CPU time = ",t2-t1) return # unrecognized command, let system handle error @@ -255,7 +256,7 @@ quitflag = 0 iarg = 1 while (iarg < len(sys.argv)): if (sys.argv[iarg][0] != '-'): - print "ERROR: arg is not a switch: %s" % (sys.argv[iarg]) + print("ERROR: arg is not a switch: %s" % (sys.argv[iarg])) sys.exit() if (sys.argv[iarg] == "-s"): silent = 1 @@ -274,37 +275,37 @@ while (iarg < len(sys.argv)): iarg = jarg elif (sys.argv[iarg] == "-f"): jarg = iarg + 1 - list = [] + flist = [] while (jarg < len(sys.argv) and sys.argv[jarg][0] != '-'): - list.append(sys.argv[jarg]) + flist.append(sys.argv[jarg]) jarg += 1 - task = ("script",list) + task = ("script",flist) tasks.append(task) iarg = jarg elif (sys.argv[iarg] == "-c"): jarg = iarg + 1 - list = [] + clist = [] while (jarg < len(sys.argv) and sys.argv[jarg][0] != '-'): - list.append(sys.argv[jarg]) + clist.append(sys.argv[jarg]) jarg += 1 - task = ("command",list) + task = ("command",clist) tasks.append(task) iarg = jarg elif (sys.argv[iarg] == "-q"): quitflag = 1 iarg += 1 else: - print "ERROR: unknown switch: %s" % (sys.argv[iarg]) + print("ERROR: unknown switch: %s" % (sys.argv[iarg])) sys.exit() # print intro message -if not silent: print intro[1:] % version, +if not silent: print(intro[1:] % version, end=' ') # error test on m,x command-line switches if len(yes_tools) > 0 and len(no_tools) > 0: - print "ERROR: cannot use -t and -x switches together" + print("ERROR: cannot use -t and -x switches together") sys.exit() # ------------------------------------------------------------------------- @@ -313,12 +314,12 @@ if len(yes_tools) > 0 and len(no_tools) > 0: # else scan for *.py files in all dirs in PIZZA_TOOLS list # and then Pizza.py src dir (sys.path[0]) -if not silent: print "Loading tools ..." -if not silent and nodisplay: print "Display not available ... no GUIs" +if not silent: print("Loading tools ...") +if not silent and nodisplay: print("Display not available ... no GUIs") try: from DEFAULTS import PIZZA_TOOLS except: PIZZA_TOOLS = [] -PIZZA_TOOLS = map(os.path.expanduser,PIZZA_TOOLS) +PIZZA_TOOLS = list(map(os.path.expanduser,PIZZA_TOOLS)) PIZZA_TOOLS.append(sys.path[0]) if len(yes_tools) > 0: tools = yes_tools @@ -359,12 +360,12 @@ for tool in tools: failed.append(tool) continue try: - exec "from %s import %s" % (tool,tool) - exec "from %s import oneline as oneline_%s" % (tool,tool) - exec "from %s import docstr as docstr_%s" % (tool,tool) - except Exception, exception: - print "%s tool did not load:" % tool - print " ",exception + exec("from %s import %s" % (tool,tool)) + exec("from %s import oneline as oneline_%s" % (tool,tool)) + exec("from %s import docstr as docstr_%s" % (tool,tool)) + except Exception as exception: + print("%s tool did not load:" % tool) + print(" ",exception) failed.append(tool) for dir in PIZZA_TOOLS: sys.path = sys.path[1:] @@ -384,7 +385,7 @@ sys.path.insert(0,'') try: from DEFAULTS import PIZZA_SCRIPTS except: PIZZA_SCRIPTS = [] -PIZZA_SCRIPTS = map(os.path.expanduser,PIZZA_SCRIPTS) +PIZZA_SCRIPTS = list(map(os.path.expanduser,PIZZA_SCRIPTS)) PIZZA_SCRIPTS.insert(0,'.') PIZZA_SCRIPTS.append(sys.path[1][:-3] + "scripts") # path for pizza.py @@ -403,27 +404,27 @@ for task in tasks: for dir in PIZZA_SCRIPTS: fullfile = dir + '/' + file if os.path.exists(fullfile): - print "Executing file:",fullfile - execfile(fullfile) + print("Executing file:",fullfile) + exec(compile(open(fullfile).read(), fullfile, 'exec')) flag = 1 break - if not flag: print "Could not find file",file - except StandardError, exception: + if not flag: print("Could not find file",file) + except Exception as exception: (type,value,tback) = sys.exc_info() - print type,value,tback + print(type,value,tback) type = str(type) type = type[type.find(".")+1:] - print "%s with value: %s" % (type,value) + print("%s with value: %s" % (type,value)) tback = tback.tb_next while tback: - print "error on line %d of file %s" % \ - (tback.tb_lineno,tback.tb_frame.f_code.co_filename) + print("error on line %d of file %s" % \ + (tback.tb_lineno,tback.tb_frame.f_code.co_filename)) tback = tback.tb_next elif task[0] == "command": argv = task[1] cmd = "" for arg in argv: cmd += arg + " " - exec cmd + exec(cmd) # ------------------------------------------------------------------------- # store global namespace diff --git a/src/plotview.py b/src/plotview.py index 7cc83c5..fb3a5a1 100644 --- a/src/plotview.py +++ b/src/plotview.py @@ -8,6 +8,12 @@ # plotview tool +# Imports and external programs + +from __future__ import absolute_import +import sys, re, glob, time +from tkinter import * + oneline = "Plot multiple vectors from a data set" docstr = """ @@ -46,11 +52,6 @@ p.save() save currently selected plot to file.eps # checkvars = list of status of check buttons # checkold = list of status of check buttons before click -# Imports and external programs - -import sys, re, glob, time -from Tkinter import * - # Class definition class plotview: @@ -148,7 +149,7 @@ class plotview: def save(self): n = self.radiovar.get() - if n == 0: raise StandardError,"no plot selected" + if n == 0: raise Exception("no plot selected") name = self.entry.get() self.plot.save(name) diff --git a/src/rasmol.py b/src/rasmol.py index 5427688..676b7b9 100644 --- a/src/rasmol.py +++ b/src/rasmol.py @@ -8,6 +8,12 @@ # rasmol tool +# Imports and external programs + +from __future__ import absolute_import +import sys, os, subprocess, re, types +from pdbfile import pdbfile + oneline = "3d visualization via RasMol program" docstr = """ @@ -38,11 +44,6 @@ r.run(N,"new.rasmol","old.rasmol") type quit to save RasMol script file # Variables -# Imports and external programs - -import sys, os, commands, re, types -from pdbfile import pdbfile - try: from DEFAULTS import PIZZA_RASMOL except: PIZZA_RASMOL = "rasmol" try: from DEFAULTS import PIZZA_DISPLAY @@ -67,7 +68,7 @@ class rasmol: def enter(self): while 1: - command = raw_input("rasmol> ") + command = input("rasmol> ") if command == "quit" or command == "exit": return self.__call__(command) @@ -85,19 +86,19 @@ class rasmol: # -------------------------------------------------------------------- - def show(self,*list): + def show(self,*arglist): # create tmp.pdb with atom data - n = list[0] + n = arglist[0] self.pdb.single(n,"tmp.pdb") # if RasMol input script specified, read it # replace load pdb "file" with load pdb "%s" # if no RasMol input script specified, use rasmol_template - if len(list) == 2: - rasmol_text = open(list[1],"r").read() + if len(arglist) == 2: + rasmol_text = open(arglist[1],"r").read() rasmol_text = re.sub('load pdb ".*"','load pdb "%s"',rasmol_text) else: rasmol_text = rasmol_template @@ -106,7 +107,7 @@ class rasmol: f = open("tmp.rasmol","w") text = rasmol_text % "tmp.pdb" - print >>f,text + print(text, file=f) f.close() # run RasMol to create image in tmp.gif @@ -119,18 +120,18 @@ class rasmol: # display the image cmd = "%s tmp.gif" % (PIZZA_DISPLAY) - commands.getoutput(cmd) + subprocess.getoutput(cmd) # -------------------------------------------------------------------- - def all(self,*list): + def all(self,*arglist): # if RasMol script specified, read it # replace load pdb "file" with load pdb "%s" # if no RasMol script specified, just use rasmol_template - if len(list) == 1: - rasmol_text = open(list[0],"r").read() + if len(arglist) == 1: + rasmol_text = open(arglist[0],"r").read() rasmol_text = re.sub('load pdb ".*"','load pdb "%s"',rasmol_text) else: rasmol_text = rasmol_template @@ -160,10 +161,10 @@ class rasmol: text = rasmol_text % file_pdb file_rasmol = "tmp%s.rasmol" % ncount f = open(file_rasmol,"w") - print >>f,text + print(text, file=f) f.close() - print time, + print(time, end=' ') sys.stdout.flush() n += 1 @@ -172,7 +173,7 @@ class rasmol: self.start() loop = n - for n in xrange(loop): + for n in range(loop): if n < 10: ncount = "000" + str(n) elif n < 100: @@ -191,24 +192,24 @@ class rasmol: # clean up - commands.getoutput("rm tmp*.pdb") - commands.getoutput("rm tmp*.rasmol") + subprocess.getoutput("rm tmp*.pdb") + subprocess.getoutput("rm tmp*.rasmol") # -------------------------------------------------------------------- - def run(self,*list): + def run(self,*arglist): # create tmp.pdb with atom data - n = list[0] + n = arglist[0] self.pdb.single(n,"tmp.pdb") # if RasMol script specified, read it # replace load pdb "file" with load pdb "%s" # if no RasMol script specified, just use rasmol_template - if len(list) == 3: - rasmol_text = open(list[2],"r").read() + if len(arglist) == 3: + rasmol_text = open(arglist[2],"r").read() rasmol_text = re.sub('load pdb ".*"','load pdb "%s"',rasmol_text) else: rasmol_text = rasmol_template @@ -217,7 +218,7 @@ class rasmol: f = open("tmp.rasmol","w") text = rasmol_template % "tmp.pdb" - print >>f,text + print(text, file=f) f.close() # run RasMol to create image in tmp.gif @@ -226,7 +227,7 @@ class rasmol: self.__call__("source tmp.rasmol") self.enter() - if len(list) > 1: newfile = list[1] + if len(arglist) > 1: newfile = arglist[1] else: newfile = "tmp.rasmol" self.__call__("write script %s" % newfile) self.stop() diff --git a/src/raster.py b/src/raster.py index abdfb69..47294bb 100644 --- a/src/raster.py +++ b/src/raster.py @@ -8,6 +8,13 @@ # raster tool +# Imports and external programs + +from __future__ import absolute_import +import sys, os, subprocess, re +from vizinfo import vizinfo +from math import fabs,atan,cos,sin + oneline = "3d visualization via Raster3d program" docstr = """ @@ -108,16 +115,10 @@ colors["nickname"] = [R,G,B] set new RGB values from 0 to 255 # vizinfo = scene attributes # xtrans,ytrans,ztrans = translation factors computed by Raster3d -# Imports and external programs - -import sys, os, commands, re -from vizinfo import vizinfo -from math import fabs,atan,cos,sin - try: from DEFAULTS import PIZZA_RENDER except: PIZZA_RENDER = "render" try: from DEFAULTS import PIZZA_LABEL3D -except: PIZZA_LABEL3D = "label3d" +except: PIZZA_LABEL3D = "render -labels" try: from DEFAULTS import PIZZA_DISPLAY except: PIZZA_DISPLAY = "display" @@ -152,6 +153,8 @@ class raster: self.tdef() self.ldef() + os.environ["TMPDIR"] = "/tmp" + # -------------------------------------------------------------------- def bg(self,color): @@ -222,7 +225,7 @@ class raster: self.xtrans = self.ytrans = self.ztrans = 0.0 output = self.single(1,self.file,box,atoms,bonds,tris,lines) - print output + print(output) nums = re.findall("translation to:\s*(\S*)\s*(\S*)\s*(\S*)\s",output) self.xtrans = float(nums[0][0]) self.ytrans = float(nums[0][1]) @@ -230,7 +233,7 @@ class raster: self.single(0,self.file,box,atoms,bonds,tris,lines) cmd = "%s %s.png" % (PIZZA_DISPLAY,self.file) - commands.getoutput(cmd) + subprocess.getoutput(cmd) # -------------------------------------------------------------------- @@ -306,7 +309,7 @@ class raster: self.ztrans = float(nums[0][2]) self.single(0,file,box,atoms,bonds,tris,lines) - print time, + print(time, end=' ') sys.stdout.flush() i += 1 n += 1 @@ -353,11 +356,11 @@ class raster: self.ztrans = float(nums[0][2]) self.single(0,file,box,atoms,bonds,tris,lines) - print n, + print(n, end=' ') sys.stdout.flush() n += 1 - print "\n%d images" % ncount + print("\n%d images" % ncount) # -------------------------------------------------------------------- @@ -374,7 +377,7 @@ class raster: (self.xpixels,self.ypixels,color[0],color[1],color[2], self.eye,matrix,self.xtrans+xshift,self.ytrans+yshift, self.ztrans,1.6*self.distance/self.scale) - print >>f,header, + print(header, end=' ', file=f) # draw box if boxflag or flag is set # flag = 1 is a pre-call of single to set frame size correctly @@ -385,53 +388,53 @@ class raster: ncolor = self.vizinfo.nacolor for atom in atoms: itype = int(atom[1]) - if itype > ncolor: raise StandardError,"atom type too big" + if itype > ncolor: raise Exception("atom type too big") color = self.vizinfo.acolor[itype] rad = self.vizinfo.arad[itype] - print >>f,2 - print >>f,atom[2],atom[3],atom[4],rad,color[0],color[1],color[2] + print(2, file=f) + print(atom[2],atom[3],atom[4],rad,color[0],color[1],color[2], file=f) # need to include vizinfo.tfill options ncolor = self.vizinfo.ntcolor for tri in tris: itype = int(tri[1]) - if itype > ncolor: raise StandardError,"tri type too big" + if itype > ncolor: raise Exception("tri type too big") color = self.vizinfo.tcolor[itype] - print >>f,1 - print >>f,tri[2],tri[3],tri[4],tri[5],tri[6],tri[7], \ - tri[8],tri[9],tri[10],color[0],color[1],color[2] + print(1, file=f) + print(tri[2],tri[3],tri[4],tri[5],tri[6],tri[7], \ + tri[8],tri[9],tri[10],color[0],color[1],color[2], file=f) bound = 0.25 * self.distance ncolor = self.vizinfo.nbcolor for bond in bonds: itype = int(bond[1]) - if itype > ncolor: raise StandardError,"bond type too big" + if itype > ncolor: raise Exception("bond type too big") color = self.vizinfo.bcolor[itype] rad = self.vizinfo.brad[itype] if fabs(bond[2]-bond[5]) > bound or fabs(bond[3]-bond[6]) > bound: continue - print >>f,5 - print >>f,bond[2],bond[3],bond[4],rad, \ - bond[5],bond[6],bond[7],0.0,color[0],color[1],color[2] + print(5, file=f) + print(bond[2],bond[3],bond[4],rad, \ + bond[5],bond[6],bond[7],0.0,color[0],color[1],color[2], file=f) ncolor = self.vizinfo.nlcolor for line in lines: itype = int(line[1]) - if itype > ncolor: raise StandardError,"line type too big" + if itype > ncolor: raise Exception("line type too big") color = self.vizinfo.lcolor[itype] thick = self.vizinfo.lrad[itype] - print >>f,3 - print >>f,line[2],line[3],line[4],thick, \ - line[5],line[6],line[7],thick,color[0],color[1],color[2] + print(3, file=f) + print(line[2],line[3],line[4],thick, \ + line[5],line[6],line[7],thick,color[0],color[1],color[2], file=f) for label in self.labels: - print >>f,15 - print >>f,10 - print >>f,label[2],label[3],label[4] - print >>f,11 - print >>f,label[0],label[1],0.0,label[5][0],label[5][1],label[5][2] - print >>f,label[6] + print(15, file=f) + print(10, file=f) + print(label[2],label[3],label[4], file=f) + print(11, file=f) + print(label[0],label[1],0.0,label[5][0],label[5][1],label[5][2], file=f) + print(label[6], file=f) f.close() @@ -440,32 +443,32 @@ class raster: else: cmd = "cat tmp.r3d | %s -png %s.png" % (PIZZA_LABEL3D,file) - output = commands.getoutput(cmd) + output = subprocess.getoutput(cmd) return output # -------------------------------------------------------------------- def adef(self): - self.vizinfo.setcolors("atom",range(100),"loop") - self.vizinfo.setradii("atom",range(100),0.45) + self.vizinfo.setcolors("atom",list(range(100)),"loop") + self.vizinfo.setradii("atom",list(range(100)),0.45) # -------------------------------------------------------------------- def bdef(self): - self.vizinfo.setcolors("bond",range(100),"loop") - self.vizinfo.setradii("bond",range(100),0.25) + self.vizinfo.setcolors("bond",list(range(100)),"loop") + self.vizinfo.setradii("bond",list(range(100)),0.25) # -------------------------------------------------------------------- def tdef(self): - self.vizinfo.setcolors("tri",range(100),"loop") - self.vizinfo.setfills("tri",range(100),0) + self.vizinfo.setcolors("tri",list(range(100)),"loop") + self.vizinfo.setfills("tri",list(range(100)),0) # -------------------------------------------------------------------- def ldef(self): - self.vizinfo.setcolors("line",range(100),"loop") - self.vizinfo.setradii("line",range(100),0.25) + self.vizinfo.setcolors("line",list(range(100)),"loop") + self.vizinfo.setradii("line",list(range(100)),0.25) # -------------------------------------------------------------------- @@ -526,32 +529,32 @@ def box_write(f,box,color,thick): green = color[1] blue = color[2] - print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ - (xlo,ylo,zlo,thick,xhi,ylo,zlo,thick,red,green,blue) - print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ - (xlo,yhi,zlo,thick,xhi,yhi,zlo,thick,red,green,blue) - print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ - (xlo,ylo,zhi,thick,xhi,ylo,zhi,thick,red,green,blue) - print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ - (xlo,yhi,zhi,thick,xhi,yhi,zhi,thick,red,green,blue) + print("3\n%g %g %g %g %g %g %g %g %g %g %g" % \ + (xlo,ylo,zlo,thick,xhi,ylo,zlo,thick,red,green,blue), file=f) + print("3\n%g %g %g %g %g %g %g %g %g %g %g" % \ + (xlo,yhi,zlo,thick,xhi,yhi,zlo,thick,red,green,blue), file=f) + print("3\n%g %g %g %g %g %g %g %g %g %g %g" % \ + (xlo,ylo,zhi,thick,xhi,ylo,zhi,thick,red,green,blue), file=f) + print("3\n%g %g %g %g %g %g %g %g %g %g %g" % \ + (xlo,yhi,zhi,thick,xhi,yhi,zhi,thick,red,green,blue), file=f) - print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ - (xlo,ylo,zlo,thick,xlo,yhi,zlo,thick,red,green,blue) - print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ - (xhi,ylo,zlo,thick,xhi,yhi,zlo,thick,red,green,blue) - print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ - (xlo,ylo,zhi,thick,xlo,yhi,zhi,thick,red,green,blue) - print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ - (xhi,ylo,zhi,thick,xhi,yhi,zhi,thick,red,green,blue) + print("3\n%g %g %g %g %g %g %g %g %g %g %g" % \ + (xlo,ylo,zlo,thick,xlo,yhi,zlo,thick,red,green,blue), file=f) + print("3\n%g %g %g %g %g %g %g %g %g %g %g" % \ + (xhi,ylo,zlo,thick,xhi,yhi,zlo,thick,red,green,blue), file=f) + print("3\n%g %g %g %g %g %g %g %g %g %g %g" % \ + (xlo,ylo,zhi,thick,xlo,yhi,zhi,thick,red,green,blue), file=f) + print("3\n%g %g %g %g %g %g %g %g %g %g %g" % \ + (xhi,ylo,zhi,thick,xhi,yhi,zhi,thick,red,green,blue), file=f) - print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ - (xlo,ylo,zlo,thick,xlo,ylo,zhi,thick,red,green,blue) - print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ - (xhi,ylo,zlo,thick,xhi,ylo,zhi,thick,red,green,blue) - print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ - (xlo,yhi,zlo,thick,xlo,yhi,zhi,thick,red,green,blue) - print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ - (xhi,yhi,zlo,thick,xhi,yhi,zhi,thick,red,green,blue) + print("3\n%g %g %g %g %g %g %g %g %g %g %g" % \ + (xlo,ylo,zlo,thick,xlo,ylo,zhi,thick,red,green,blue), file=f) + print("3\n%g %g %g %g %g %g %g %g %g %g %g" % \ + (xhi,ylo,zlo,thick,xhi,ylo,zhi,thick,red,green,blue), file=f) + print("3\n%g %g %g %g %g %g %g %g %g %g %g" % \ + (xlo,yhi,zlo,thick,xlo,yhi,zhi,thick,red,green,blue), file=f) + print("3\n%g %g %g %g %g %g %g %g %g %g %g" % \ + (xhi,yhi,zlo,thick,xhi,yhi,zhi,thick,red,green,blue), file=f) # -------------------------------------------------------------------- # compute 3x3 rotation matrix for viewing angle diff --git a/src/svg.py b/src/svg.py index db1c099..8af3ee7 100644 --- a/src/svg.py +++ b/src/svg.py @@ -8,6 +8,14 @@ # svg tool +# Imports and external programs + +from __future__ import absolute_import +import sys, os, subprocess, re +import functools +from vizinfo import vizinfo +from math import sqrt,atan,cos,sin,fabs + oneline = "3d visualization via SVG files" docstr = """ @@ -110,12 +118,6 @@ s.thick = 2.0 pixel thickness of black atom border # bgcol = color of background # vizinfo = scene attributes -# Imports and external programs - -import sys, os, commands, re -from vizinfo import vizinfo -from math import sqrt,atan,cos,sin,fabs - try: from DEFAULTS import PIZZA_DISPLAY except: PIZZA_DISPLAY = "display" @@ -202,7 +204,7 @@ class svg: self.single(self.file,box,atoms,bonds,tris,lines,1) cmd = "%s %s.svg" % (PIZZA_DISPLAY,self.file) - commands.getoutput(cmd) + subprocess.getoutput(cmd) # -------------------------------------------------------------------- @@ -273,7 +275,7 @@ class svg: if n == nstart or self.panflag: scaleflag = 1 self.single(file,box,atoms,bonds,tris,lines,scaleflag) - print time, + print(time, end=' ') sys.stdout.flush() i += 1 n += 1 @@ -315,11 +317,11 @@ class svg: if n == nstart or self.panflag: scaleflag = 1 self.single(file,box,atoms,bonds,tris,lines,scaleflag) - print n, + print(n, end=' ') sys.stdout.flush() n += 1 - print "\n%d images" % ncount + print("\n%d images" % ncount) # -------------------------------------------------------------------- @@ -420,7 +422,7 @@ class svg: # convert objects by factor/offset and sort by z-depth self.convert(olist) - olist.sort(cmprz) + olist.sort(key = functools.cmp_to_key(cmprz)) # write SVG file @@ -430,19 +432,19 @@ class svg: header = ' ' % \ (self.ypixels,self.xpixels) header += '' - print >>f,header + print(header, file=f) color = '>f,color + print(color, file=f) for element in olist: self.write(f,0,element) for label in self.labels: self.write(f,1,label) footer = "" - print >> f,footer + print(footer, file=f) f.close() @@ -514,80 +516,80 @@ class svg: if obj[0] == 0: # atom with its color and radius itype = int(obj[1]) if itype > self.vizinfo.nacolor: - raise StandardError,"atom type too big" + raise Exception("atom type too big") color = self.vizinfo.acolor[itype] rad = self.vizinfo.arad[itype] - print >>f,'' % \ + print('' % \ (obj[2],obj[3],rad*self.factor, - color[0]*255,color[1]*255,color[2]*255,self.thick) + color[0]*255,color[1]*255,color[2]*255,self.thick), file=f) elif obj[0] == 1: # tri with its color (need to add fill type) itype = int(obj[1]) if itype > self.vizinfo.ntcolor: - raise StandardError,"tri type too big" + raise Exception("tri type too big") color = self.vizinfo.tcolor[itype] - print >>f,'' % \ + print('' % \ (obj[2],obj[3],obj[5],obj[6],obj[8],obj[9], - color[0]*255,color[1]*255,color[2]*255) + color[0]*255,color[1]*255,color[2]*255), file=f) elif obj[0] == 2: # bond with its color and thickness itype = int(obj[1]) if itype > self.vizinfo.nbcolor: - raise StandardError,"bond type too big" + raise Exception("bond type too big") color = self.vizinfo.bcolor[itype] thick = self.vizinfo.brad[itype] - print >>f,'' % \ + print('' % \ (obj[2],obj[3],obj[5],obj[6], - color[0]*255,color[1]*255,color[2]*255,thick*self.factor) + color[0]*255,color[1]*255,color[2]*255,thick*self.factor), file=f) elif obj[0] == 3: # line with its color and thickness itype = int(obj[1]) if itype > self.vizinfo.nlcolor: - raise StandardError,"line type too big" + raise Exception("line type too big") color = self.vizinfo.lcolor[itype] thick = self.vizinfo.lrad[itype] - print >>f,'' % \ + print('' % \ (obj[2],obj[3],obj[5],obj[6], - color[0]*255,color[1]*255,color[2]*255,thick*self.factor) + color[0]*255,color[1]*255,color[2]*255,thick*self.factor), file=f) elif obj[0] == 4: # box line with built-in color and thickness color = self.bxcol thick = self.bxthick - print >>f,'' % \ + print('' % \ (obj[2],obj[3],obj[5],obj[6], - color[0]*255,color[1]*255,color[2]*255,thick*self.factor) + color[0]*255,color[1]*255,color[2]*255,thick*self.factor), file=f) elif flag == 1: x = (obj[0]*self.xpixels) + (self.xpixels/2.0) y = (self.ypixels/2.0) - (obj[1]*self.ypixels) color = obj[4] - print >>f,' %s ' % \ + print(' %s ' % \ (x,y,obj[3],obj[2],color[0]*255,color[1]*255,color[2]*255, - color[0]*255,color[1]*255,color[2]*255,obj[5]) + color[0]*255,color[1]*255,color[2]*255,obj[5]), file=f) # -------------------------------------------------------------------- def adef(self): - self.vizinfo.setcolors("atom",range(100),"loop") - self.vizinfo.setradii("atom",range(100),0.45) + self.vizinfo.setcolors("atom",list(range(100)),"loop") + self.vizinfo.setradii("atom",list(range(100)),0.45) # -------------------------------------------------------------------- def bdef(self): - self.vizinfo.setcolors("bond",range(100),"loop") - self.vizinfo.setradii("bond",range(100),0.25) + self.vizinfo.setcolors("bond",list(range(100)),"loop") + self.vizinfo.setradii("bond",list(range(100)),0.25) # -------------------------------------------------------------------- def tdef(self): - self.vizinfo.setcolors("tri",range(100),"loop") - self.vizinfo.setfills("tri",range(100),0) + self.vizinfo.setcolors("tri",list(range(100)),"loop") + self.vizinfo.setfills("tri",list(range(100)),0) # -------------------------------------------------------------------- def ldef(self): - self.vizinfo.setcolors("line",range(100),"loop") - self.vizinfo.setradii("line",range(100),0.25) + self.vizinfo.setcolors("line",list(range(100)),"loop") + self.vizinfo.setradii("line",list(range(100)),0.25) # -------------------------------------------------------------------- diff --git a/src/tdump.py b/src/tdump.py index 01f0464..3087760 100644 --- a/src/tdump.py +++ b/src/tdump.py @@ -8,6 +8,14 @@ # tdump tool +# Imports and external programs + +from __future__ import absolute_import +import sys, subprocess, re, glob, types +import functools +from math import sqrt +from os import popen + oneline = "Read dump files with triangle info" docstr = """ @@ -67,12 +75,6 @@ t.owrap(...) wrap tris to same image as their atoms # xlo,xhi,ylo,yhi,zlo,zhi = box bounds (float) # atoms[i][j] = 2d array of floats, i = 0 to natoms-1, j = 0 to ncols-1 -# Imports and external programs - -import sys, commands, re, glob, types -from math import sqrt -from os import popen - try: import numpy as np oldnumeric = False @@ -100,7 +102,7 @@ class tdump: self.flist = [] for word in words: self.flist += glob.glob(word) if len(self.flist) == 0 and len(list) == 1: - raise StandardError,"no ldump file specified" + raise Exception("no ldump file specified") if len(list) == 1: self.increment = 0 @@ -125,26 +127,26 @@ class tdump: 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.snaps.sort(key = functools.cmp_to_key(self.compare_time)) self.cull() self.nsnaps = len(self.snaps) - print "read %d snapshots" % self.nsnaps + print("read %d snapshots" % self.nsnaps) # -------------------------------------------------------------------- # read next snapshot from list of files def next(self): - if not self.increment: raise StandardError,"cannot read incrementally" + if not self.increment: raise Exception("cannot read incrementally") # read next snapshot in current file using eof as pointer # if fail, try next file @@ -198,14 +200,14 @@ class tdump: 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) + floats = list(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 @@ -220,7 +222,7 @@ class tdump: def map(self,*pairs): if len(pairs) % 2 != 0: - raise StandardError, "tdump map() requires pairs of mappings" + raise Exception("tdump map() requires pairs of mappings") for i in range(0,len(pairs),2): j = i + 1 self.names[pairs[j]] = pairs[i]-1 @@ -250,9 +252,9 @@ class tdump: # -------------------------------------------------------------------- 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 Exception("no step %d exists" % n) # -------------------------------------------------------------------- # delete successive snapshots with duplicate time stamp @@ -299,7 +301,7 @@ class tdump: # don't add tri if all 4 values are 0 since not a line tris = [] - for i in xrange(snap.natoms): + for i in range(snap.natoms): atom = snap.atoms[i] c1 = [atom[corner1x],atom[corner1y],atom[corner1z]] c2 = [atom[corner2x],atom[corner2y],atom[corner2z]] @@ -335,7 +337,7 @@ class tdump: # jdump = atom J in dump's atoms that atom I was owrapped on # delx,dely = offset applied to atom I and thus to line I - for i in xrange(snap.natoms): + for i in range(snap.natoms): tag = atoms[i][id] idump = idsdump[tag] jdump = idsdump[atomsdump[idump][iother]] diff --git a/src/vcr.py b/src/vcr.py index fd5c992..9f72fa6 100644 --- a/src/vcr.py +++ b/src/vcr.py @@ -8,6 +8,12 @@ # vcr tool +# Imports and external programs + +from __future__ import absolute_import +from tkinter import * +import types + oneline = "VCR-style GUI for 3d interactive OpenGL visualization" docstr = """ @@ -64,11 +70,6 @@ v.saveall() toggle save-all checkbox # delay_value = delay between frames (secs) # delay_msec = delay in millisec -# Imports and external programs - -from Tkinter import * -import types - # Class definition class vcr: @@ -88,7 +89,7 @@ class vcr: # load data for each viewer # if each viewer has different data set, nframes is for 1st viewer - if len(views) == 0: raise StandardError,"must have at least one GL viewer" + if len(views) == 0: raise Exception("must have at least one GL viewer") self.viewlist = [] for view in views: self.viewlist.append(view) for view in self.viewlist: view.reload() @@ -320,7 +321,7 @@ class vcr: # -------------------------------------------------------------------- def q(self,value): - if type(value) is not types.IntType: value = self.slider_quality.get() + if type(value) is not int: value = self.slider_quality.get() self.slider_quality.set(value) for view in self.viewlist: view.q(value) diff --git a/src/vec.py b/src/vec.py index dfe8f04..abc11fb 100644 --- a/src/vec.py +++ b/src/vec.py @@ -8,6 +8,11 @@ # vec tool +# Imports and external programs + +from __future__ import absolute_import +import types + oneline = "Create numeric vectors from columns in file or list of vecs" docstr = """ @@ -40,10 +45,6 @@ l.write("file.txt","col1",7,...) write listed vectors to a file # ptr = dictionary, key = name, value = index into data for which column # data[i][j] = 2d array of floats, i = 0 to # of entries, j = 0 to nvecs-1 -# Imports and external programs - -import types - # Class definition class vec: @@ -53,22 +54,22 @@ class vec: def __init__(self,data): self.data = [] - if type(data) == types.StringType: + if isinstance(data,str): lines = open(data,'r').readlines() for line in lines: words = line.split() if len(words) and words[0][0] in "0123456789.-": - self.data.append(map(float,words)) - elif type(data) == types.ListType: + self.data.append(list(map(float,words))) + elif isinstance(data, list): nlen = len(data[0]) - for list in data[1:]: - if len(list) != nlen: - raise StandardError,"lists are not all same length" - for i in xrange(nlen): - values = [list[i] for list in data] - self.data.append(map(float,values)) + for dlist in data[1:]: + if len(dlist) != nlen: + raise Exception("lists are not all same length") + for i in range(nlen): + values = [dlist[i] for dlist in data] + self.data.append(list(map(float,values))) else: - raise StandardError,"invalid argument to vec" + raise Exception("invalid argument to vec") if len(self.data) == 0: self.nlen = self.nvec = 0 @@ -77,25 +78,25 @@ class vec: self.nvec = len(self.data[0]) self.names = [] - for i in xrange(self.nvec): + for i in range(self.nvec): self.names.append(str("col%d" % (i+1))) self.ptr = {} - for i in xrange(self.nvec): + for i in range(self.nvec): self.ptr[self.names[i]] = i - print "read %d vectors of length %d" % (self.nvec,self.nlen) + print("read %d vectors of length %d" % (self.nvec,self.nlen)) # -------------------------------------------------------------------- def get(self,*keys): if len(keys) == 0: - raise StandardError, "no vectors specified" + raise Exception("no vectors specified") map = [] for key in keys: - if type(key) == types.IntType: map.append(key-1) - elif self.ptr.has_key(key): map.append(self.ptr[key]) + if type(key) == int: map.append(key-1) + elif key in self.ptr: map.append(self.ptr[key]) else: count = 0 for i in range(self.nvec): @@ -105,12 +106,12 @@ class vec: if count == 1: map.append(index) else: - raise StandardError, "unique vector %s not found" % key + raise Exception("unique vector %s not found" % key) vecs = [] for i in range(len(keys)): vecs.append(self.nlen * [0]) - for j in xrange(self.nlen): + for j in range(self.nlen): vecs[i][j] = self.data[j][map[i]] if len(keys) == 1: return vecs[0] @@ -122,8 +123,8 @@ class vec: if len(keys): map = [] for key in keys: - if type(key) == types.IntType: map.append(key-1) - elif self.ptr.has_key(key): map.append(self.ptr[key]) + if type(key) == int: map.append(key-1) + elif key in self.ptr: map.append(self.ptr[key]) else: count = 0 for i in range(self.nvec): @@ -133,13 +134,13 @@ class vec: if count == 1: map.append(index) else: - raise StandardError, "unique vector %s not found" % key + raise Exception("unique vector %s not found" % key) else: - map = range(self.nvec) + map = list(range(self.nvec)) f = open(filename,"w") - for i in xrange(self.nlen): - for j in xrange(len(map)): - print >>f,self.data[i][map[j]], - print >>f + for i in range(self.nlen): + for j in range(len(map)): + print(self.data[i][map[j]], end=' ', file=f) + print(file=f) f.close() diff --git a/src/vizinfo.py b/src/vizinfo.py index c5410d7..d1556d4 100644 --- a/src/vizinfo.py +++ b/src/vizinfo.py @@ -18,6 +18,7 @@ # Imports and external programs +from __future__ import absolute_import import types # Class definition @@ -66,20 +67,20 @@ class vizinfo: # convert args into lists if single values # if arg = 0, convert to full-range list - if type(ids) is types.IntType and ids == 0: - if which == "atom": ids = range(self.nacolor) - if which == "bond": ids = range(self.nbcolor) - if which == "tri": ids = range(self.ntcolor) - if which == "line": ids = range(self.nlcolor) - if type(ids) is not types.ListType and type(ids) is not types.TupleType: + if type(ids) is int and ids == 0: + if which == "atom": ids = list(range(self.nacolor)) + if which == "bond": ids = list(range(self.nbcolor)) + if which == "tri": ids = list(range(self.ntcolor)) + if which == "line": ids = list(range(self.nlcolor)) + if type(ids) is not list and type(ids) is not tuple: ids = [ids] - if type(rgbs) is not types.ListType and type(rgbs) is not types.TupleType: + if type(rgbs) is not list and type(rgbs) is not tuple: rgbs = [rgbs] # if list of types has a 0, increment each type value if 0 in ids: - for i in xrange(len(ids)): ids[i] += 1 + for i in range(len(ids)): ids[i] += 1 # extend storage list if necessary # extend other arrays for same "which" so that gl::make_atom_calllist @@ -109,12 +110,12 @@ class vizinfo: ntypes = len(ids) nrgbs = len(rgbs) - for i in xrange(ntypes): + for i in range(ntypes): id = ids[i] if rgbs[0] == "loop": - list = colors.keys() - red,green,blue = colors[list[i % len(colors)]] + colorlist = list(colors.keys()) + red,green,blue = colors[colorlist[i % len(colors)]] elif ntypes == nrgbs: red,green,blue = colors[rgbs[i]] else: @@ -144,20 +145,20 @@ class vizinfo: # convert args into lists if single values # if arg = 0, convert to full-range list - if type(ids) is types.IntType and ids == 0: - if which == "atom": ids = range(self.narad) - if which == "bond": ids = range(self.nbrad) - if which == "line": ids = range(self.nlrad) - if type(ids) is not types.ListType and type(ids) is not types.TupleType: + if type(ids) is int and ids == 0: + if which == "atom": ids = list(range(self.narad)) + if which == "bond": ids = list(range(self.nbrad)) + if which == "line": ids = list(range(self.nlrad)) + if type(ids) is not list and type(ids) is not tuple: ids = [ids] - if type(radii) is not types.ListType and \ - type(radii) is not types.TupleType: + if type(radii) is not list and \ + type(radii) is not tuple: radii = [radii] # if list of types has a 0, increment each type value if 0 in ids: - for i in xrange(len(ids)): ids[i] += 1 + for i in range(len(ids)): ids[i] += 1 # extend storage list if necessary # extend other arrays for same "which" so that gl::make_atom_calllist @@ -209,18 +210,18 @@ class vizinfo: # convert args into lists if single values # if arg = 0, convert to full-range list - if type(ids) is types.IntType and ids == 0: - ids = range(self.ntfill) - if type(ids) is not types.ListType and type(ids) is not types.TupleType: + if type(ids) is int and ids == 0: + ids = list(range(self.ntfill)) + if type(ids) is not list and type(ids) is not tuple: ids = [ids] - if type(fills) is not types.ListType and \ - type(fills) is not types.TupleType: + if type(fills) is not list and \ + type(fills) is not tuple: fills = [fills] # if list of types has a 0, increment each type value if 0 in ids: - for i in xrange(len(ids)): ids[i] += 1 + for i in range(len(ids)): ids[i] += 1 # extend storage list if necessary # extend other arrays for same "which" so that gl::make_atom_calllist @@ -234,7 +235,7 @@ class vizinfo: # if list lengths match, set directly, else set types to 1st fill value if len(fills) == len(ids): - for i in xrange(len(ids)): self.tfill[ids[i]] = int(fills[i]) + for i in range(len(ids)): self.tfill[ids[i]] = int(fills[i]) else: for id in ids: self.tfill[id] = int(fills[0]) diff --git a/src/vmd.py b/src/vmd.py index 1223451..cc5217c 100644 --- a/src/vmd.py +++ b/src/vmd.py @@ -14,6 +14,12 @@ # open a pipe to the executable, # and feed it Tcl command lines one at a time +# Imports and external programs + +from __future__ import absolute_import +import types, os +import numpy + oneline = "Control VMD from python" docstr = """ @@ -40,11 +46,6 @@ v.debug([True|False]) display generated VMD script commands? # History # 11/10, Axel Kohlmeyer (Temple U): original version -# Imports and external programs - -import types, os -import numpy - try: from DEFAULTS import PIZZA_VMDNAME except: PIZZA_VMDNAME = "vmd" try: from DEFAULTS import PIZZA_VMDDIR @@ -56,8 +57,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 @@ -103,7 +104,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 # -------------------------------------------------------------------- @@ -121,9 +122,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 # -------------------------------------------------------------------- @@ -133,16 +134,16 @@ class vmd: self.__call__('menu main on') while 1: try: - command = raw_input("vmd > ") + command = 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/src/vtk.py b/src/vtk.py index eb18050..fa26b98 100644 --- a/src/vtk.py +++ b/src/vtk.py @@ -55,7 +55,7 @@ class vtk: n = flag = 0 which,time,flag = self.data.iterator(flag) time,box,atoms,bonds,tris,lines = self.data.viz(which) - print time, + print(time, end=' ') sys.stdout.flush() if len(tris): surface(tris) @@ -70,12 +70,12 @@ class vtk: time,box,atoms,bonds,tris,lines = self.data.viz(which) for atom in atoms: allatoms.append(atom) - print time, + print(time, end=' ') sys.stdout.flush() n += 1 particle(file,allatoms) - print "\nwrote %d snapshots to %s in VTK format" % (n,file) + print("\nwrote %d snapshots to %s in VTK format" % (n,file)) # -------------------------------------------------------------------- @@ -105,11 +105,11 @@ class vtk: particle(file,atoms) - print time, + print(time, end=' ') sys.stdout.flush() n += 1 - print "\nwrote %s snapshots in VTK format" % n + print("\nwrote %s snapshots in VTK format" % n) # -------------------------------------------------------------------- def manyGran(self,*args,**kwargs): @@ -159,11 +159,11 @@ class vtk: except: nvalues = 0 particleGran(file,atoms,names,nvalues) - if outputfl: print time, + if outputfl: print(time, end=' ') if outputfl: sys.stdout.flush() n += 1 - if outputfl: print "\nwrote %s granular snapshots in VTK format" % n + if outputfl: print("\nwrote %s granular snapshots in VTK format" % n) # -------------------------------------------------------------------- def single(self,time,*args): @@ -210,7 +210,7 @@ def generateFilename(root,fileNos,n): def surface(tris): ntypes = tris[-1][1] - for i in xrange(ntypes): + for i in range(ntypes): itype = i+1 v = {} nvert = ntri = 0 @@ -218,19 +218,19 @@ def surface(tris): if tri[1] == itype: ntri += 1 vert = (tri[2],tri[3],tri[4]) - if not v.has_key(vert): + if vert not in v: v[vert] = nvert nvert += 1 vert = (tri[5],tri[6],tri[7]) - if not v.has_key(vert): + if vert not in v: v[vert] = nvert nvert += 1 vert = (tri[8],tri[9],tri[10]) - if not v.has_key(vert): + if vert not in v: v[vert] = nvert nvert += 1 - keys = v.keys() + keys = list(v.keys()) vinverse = {} for key in keys: vinverse[v[key]] = key @@ -238,15 +238,15 @@ def surface(tris): filename = "SURF" + str(itype) + ".vtk" f = open(filename,"w") - print >>f,"# vtk DataFile Version 3.0" - print >>f,"Generated by pizza.py" - print >>f,"ASCII" - print >>f,"DATASET POLYDATA" - print >>f,"POINTS %d float" % nvert - for i in xrange(nvert): + print("# vtk DataFile Version 3.0", file=f) + print("Generated by pizza.py", file=f) + print("ASCII", file=f) + print("DATASET POLYDATA", file=f) + print("POINTS %d float" % nvert, file=f) + for i in range(nvert): tuple = vinverse[i] - print >>f,tuple[0],tuple[1],tuple[2] - print >>f,"POLYGONS",ntri,4*ntri + print(tuple[0],tuple[1],tuple[2], file=f) + print("POLYGONS",ntri,4*ntri, file=f) for tri in tris: if tri[1] == itype: vert = (tri[2],tri[3],tri[4]) @@ -255,10 +255,10 @@ def surface(tris): ivert2 = v[vert] vert = (tri[8],tri[9],tri[10]) ivert3 = v[vert] - print >>f,3,ivert1,ivert2,ivert3 - print >>f - print >>f,"CELL_DATA",ntri - print >>f,"POINT_DATA",nvert + print(3,ivert1,ivert2,ivert3, file=f) + print(file=f) + print("CELL_DATA",ntri, file=f) + print("POINT_DATA",nvert, file=f) f.close() @@ -268,23 +268,23 @@ def surface(tris): def particle(file,atoms): f = open(file,"w") - print >>f,"# vtk DataFile Version 2.0" - print >>f,"Generated by pizza.py" - print >>f,"ASCII" - print >>f,"DATASET POLYDATA" - print >>f,"POINTS %d float" % len(atoms) + print("# vtk DataFile Version 2.0", file=f) + print("Generated by pizza.py", file=f) + print("ASCII", file=f) + print("DATASET POLYDATA", file=f) + print("POINTS %d float" % len(atoms), file=f) for atom in atoms: - print >>f,atom[2],atom[3],atom[4] - print >>f,"VERTICES",len(atoms),2*len(atoms) - for i in xrange(len(atoms)): - print >>f,1,i - print >>f,"POINT_DATA",len(atoms) - print >>f,"SCALARS atom_type int 1" - print >>f,"LOOKUP_TABLE default" + print(atom[2],atom[3],atom[4], file=f) + print("VERTICES",len(atoms),2*len(atoms), file=f) + for i in range(len(atoms)): + print(1,i, file=f) + print("POINT_DATA",len(atoms), file=f) + print("SCALARS atom_type int 1", file=f) + print("LOOKUP_TABLE default", file=f) for atom in atoms: itype = int(atom[1]) - print >>f,itype, - print >>f + print(itype, end=' ', file=f) + print(file=f) f.close() @@ -292,17 +292,17 @@ def particle(file,atoms): def boundingBox(file,xlo,xhi,ylo,yhi,zlo,zhi): f = open(file,"w") - print >>f,"# vtk DataFile Version 2.0" - print >>f,"Generated by pizza.py" - print >>f,"ASCII" - print >>f,"DATASET RECTILINEAR_GRID" - print >>f,"DIMENSIONS 2 2 2" - print >>f,"X_COORDINATES 2 float" - print >>f,xlo,xhi - print >>f,"Y_COORDINATES 2 float" - print >>f,ylo,yhi - print >>f,"Z_COORDINATES 2 float" - print >>f,zlo,zhi + print("# vtk DataFile Version 2.0", file=f) + print("Generated by pizza.py", file=f) + print("ASCII", file=f) + print("DATASET RECTILINEAR_GRID", file=f) + print("DIMENSIONS 2 2 2", file=f) + print("X_COORDINATES 2 float", file=f) + print(xlo,xhi, file=f) + print("Y_COORDINATES 2 float", file=f) + print(ylo,yhi, file=f) + print("Z_COORDINATES 2 float", file=f) + print(zlo,zhi, file=f) def typestr(o): string = str(type(o)) @@ -320,20 +320,20 @@ def particleGran(file,atoms,names,n_values): scalars, vectors = findScalarsAndVectors(names) # print head - print >>f,"# vtk DataFile Version 2.0" - print >>f,"Generated by lpp.py" - print >>f,"ASCII" - print >>f,"DATASET POLYDATA" - print >>f,"POINTS %d float" % len(atoms) + print("# vtk DataFile Version 2.0", file=f) + print("Generated by lpp.py", file=f) + print("ASCII", file=f) + print("DATASET POLYDATA", file=f) + print("POINTS %d float" % len(atoms), file=f) for atom in atoms: - print >>f, atom[vectors['x']], atom[vectors['x']+1], atom[vectors['x']+2] #atom[3],atom[4],atom[5] #write x,y,z [atom[0]=id, atom[1]=type] - print >>f,"VERTICES",len(atoms),2*len(atoms) - for i in xrange(len(atoms)): - print >>f,1,i - print >>f,"POINT_DATA",len(atoms) + print(atom[vectors['x']], atom[vectors['x']+1], atom[vectors['x']+2] , file=f) #atom[3],atom[4],atom[5] #write x,y,z [atom[0]=id, atom[1]=type] + print("VERTICES", len(atoms), 2*len(atoms), file=f) + for i in range(len(atoms)): + print(1,i, file=f) + print("POINT_DATA",len(atoms), file=f) if len(atoms) == 0: - print >> f + print('', file=f) f.close() return @@ -353,9 +353,9 @@ def particleGran(file,atoms,names,n_values): else: # if no atoms are present pass - print >>f,"VECTORS",key,vectortype + print("VECTORS",key,vectortype, file=f) for atom in atoms: - print >>f, atom[vectors[key]], atom[vectors[key]+1], atom[vectors[key]+2] + print(atom[vectors[key]], atom[vectors[key]+1], atom[vectors[key]+2], file=f) # print SCALARS for key in scalars.keys(): @@ -368,12 +368,12 @@ def particleGran(file,atoms,names,n_values): else: # if no atoms are present pass - print >>f,"SCALARS",key,scalartype,1 - print >>f,"LOOKUP_TABLE default" + print("SCALARS",key,scalartype,1, file=f) + print("LOOKUP_TABLE default", file=f) for atom in atoms: - print >>f, atom[scalars[key]] + print(atom[scalars[key]], file=f) - print >>f + print('', file=f) f.close() def findScalarsAndVectors(names): @@ -387,7 +387,7 @@ def findScalarsAndVectors(names): indices[names[name]]=name # fill missing indices (occurrs e.g. if output is like vx vy vz fx fy fz vx vy vz) - for i in xrange(max(indices)): + for i in range(max(indices)): if i not in indices: indices[i]="" @@ -441,7 +441,7 @@ def findScalarsAndVectors(names): i+=1 if 'x' not in vectors.keys(): - print "vector x y z has to be contained in dump file. please change liggghts input script accordingly." + print("vector x y z has to be contained in dump file. please change liggghts input script accordingly.") exit() return scalars, vectors diff --git a/src/xyz.py b/src/xyz.py index 92b6815..ea35ff8 100644 --- a/src/xyz.py +++ b/src/xyz.py @@ -8,6 +8,10 @@ # xyz tool +# Imports and external programs + +from __future__ import absolute_import +import sys oneline = "Convert LAMMPS snapshots to XYZ format" docstr = """ @@ -29,9 +33,6 @@ x.single(N,"file") write snapshot for timestep N to file.xyz # Variables # data = data file to read from -# Imports and external programs - -import sys # Class definition @@ -56,18 +57,18 @@ class xyz: if flag == -1: break time,box,atoms,bonds,tris,lines = self.data.viz(which) - print >>f,len(atoms) - print >>f,"Atoms" + print(len(atoms), file=f) + print("Atoms", file=f) for atom in atoms: itype = int(atom[1]) - print >>f,itype,atom[2],atom[3],atom[4] + print(itype,atom[2],atom[3],atom[4], file=f) - print time, + print(time, end=' ') sys.stdout.flush() n += 1 f.close() - print "\nwrote %d snapshots to %s in XYZ format" % (n,file) + print("\nwrote %d snapshots to %s in XYZ format" % (n,file)) # -------------------------------------------------------------------- @@ -91,17 +92,17 @@ class xyz: file = root + str(n) file += ".xyz" f = open(file,"w") - print >>f,len(atoms) - print >>f,"Atoms" + print(len(atoms), file=f) + print("Atoms", file=f) for atom in atoms: itype = int(atom[1]) - print >>f,itype,atom[2],atom[3],atom[4] - print time, + print(itype,atom[2],atom[3],atom[4], file=f) + print(time, end=' ') sys.stdout.flush() f.close() n += 1 - print "\nwrote %s snapshots in XYZ format" % n + print("\nwrote %s snapshots in XYZ format" % n) # -------------------------------------------------------------------- @@ -113,9 +114,9 @@ class xyz: which = self.data.findtime(time) time,box,atoms,bonds,tris,lines = self.data.viz(which) f = open(file,"w") - print >>f,len(atoms) - print >>f,"Atoms" + print(len(atoms), file=f) + print("Atoms", file=f) for atom in atoms: itype = int(atom[1]) - print >>f,itype,atom[2],atom[3],atom[4] + print(itype,atom[2],atom[3],atom[4], file=f) f.close()