Compare commits

12 Commits

Author SHA1 Message Date
d64778295e rename 'list' variables 2023-08-23 15:12:23 +02:00
f2d890aa58 integer division 2023-08-23 15:10:19 +02:00
088e983c78 remove semicolons 2023-08-23 15:09:44 +02:00
50efb8ee82 increase python 2 - 3 compatibility
python 2 vs 3 imports
2023-08-10 16:44:58 +02:00
e77a3e64b9 add from __future__ import print_function
python 2 vs 3 compatibility
2023-08-10 15:47:46 +02:00
8c53380765 fix Tkinter vs tkinter import 2023-08-10 15:45:58 +02:00
d4f5ea374a python 3 compatibility for scripts/*.py files 2023-08-10 13:37:14 +02:00
cf710bcb9e add example files 2023-08-10 13:27:33 +02:00
e1556451fa update example dump files to contain atom property names 2023-08-10 13:26:48 +02:00
539fd060c2 python 3 compatibility for examples/*.py files
add from __future__ import
print statement -> print() function
xrange -> range
map() -> list(map())
range() -> list(range())
StandardError -> Exception
2023-08-10 13:25:36 +02:00
597e606bde python 3 compatibility for src/*.py files
move imports to top of files
add from __future__ import
commands module -> subprocesses module
print statement -> print() function
exec statement -> exec() function
xrange -> range
map() -> list(map())
StandardError -> Exception
integer division: / -> //
x.has_key(y) -> y in x
sort(): use functools.cmp_to_key
type(x) is y -> isinstance(x, y)
raw_input -> input
change variable names 'list' to avoid clashes with list class
2023-08-10 13:19:02 +02:00
d560b34214 convert tabs to spaces, remove extra spaces, fix comments 2023-08-09 16:49:09 +02:00
93 changed files with 33574 additions and 2827 deletions

6531
examples/files/data.peptide Normal file

File diff suppressed because it is too large Load Diff

View File

@ -6,7 +6,7 @@ ITEM: BOX BOUNDS
-6.2035 6.2035 -6.2035 6.2035
-6.2035 6.2035 -6.2035 6.2035
-6.2035 6.2035 -6.2035 6.2035
ITEM: ATOMS ITEM: ATOMS id type x y z
1965739326 1 -2.73852 3.76042 0.0137829 1965739326 1 -2.73852 3.76042 0.0137829
1638062651 1 -4.08446 0.411239 0.994664 1638062651 1 -4.08446 0.411239 0.994664
574343881 1 -2.25466 -3.0259 -0.036883 574343881 1 -2.25466 -3.0259 -0.036883

24054
examples/files/dump.melt Normal file

File diff suppressed because it is too large Load Diff

View File

@ -6,7 +6,7 @@ ITEM: BOX BOUNDS
0 35.8569 0 35.8569
0 35.8569 0 35.8569
-0.1 0.1 -0.1 0.1
ITEM: ATOMS ITEM: ATOMS id type xs ys zs
1 2 0.972698 0.992397 0.5 1 2 0.972698 0.992397 0.5
2 1 0.0517232 0.999069 0.5 2 1 0.0517232 0.999069 0.5
3 1 0.0504894 0.0385782 0.5 3 1 0.0504894 0.0385782 0.5

View File

@ -6,7 +6,7 @@
36.8401937129895 64.2115601793071 36.8401937129895 64.2115601793071
41.0136911525442 68.3850576188589 41.0136911525442 68.3850576188589
29.7680952261698 57.1394616924871 29.7680952261698 57.1394616924871
ITEM: ATOMS ITEM: ATOMS id type xs ys zs ix iy iz
31 3 0.22450 0.39503 0.37295 0 0 0 31 3 0.22450 0.39503 0.37295 0 0 0
306 14 0.29326 0.17604 0.15395 0 0 0 306 14 0.29326 0.17604 0.15395 0 0 0
16 8 0.31495 0.27307 0.07008 0 0 0 16 8 0.31495 0.27307 0.07008 0 0 0

View File

@ -6,7 +6,7 @@ ITEM: BOX BOUNDS
0 27.9398 0 27.9398
0 27.9398 0 27.9398
0 27.9398 0 27.9398
ITEM: ATOMS ITEM: ATOMS id type xs ys zs ix iy iz
1 1 0.410912 0.570945 0.36491 0 0 0 1 1 0.410912 0.570945 0.36491 0 0 0
2 2 0.376227 0.6013 0.339084 0 0 0 2 2 0.376227 0.6013 0.339084 0 0 0
3 3 0.397383 0.536983 0.387988 0 0 0 3 3 0.397383 0.536983 0.387988 0 0 0

View File

@ -6,7 +6,7 @@ ITEM: BOX BOUNDS
0.482127 27.3191 0.482127 27.3191
0.477796 27.3148 0.477796 27.3148
0.47406 27.3111 0.47406 27.3111
ITEM: ATOMS ITEM: ATOMS id type xs ys zs ix iy iz
1 1 0.404224 0.524373 0.362448 0 0 0 1 1 0.404224 0.524373 0.362448 0 0 0
2 2 0.364265 0.561026 0.358768 0 0 0 2 2 0.364265 0.561026 0.358768 0 0 0
3 3 0.394989 0.481736 0.350359 0 0 0 3 3 0.394989 0.481736 0.350359 0 0 0

View File

@ -5,6 +5,8 @@
# return distance sq between 2 atoms with PBC # return distance sq between 2 atoms with PBC
from __future__ import absolute_import
def distance(box,x1,y1,z1,x2,y2,z2): def distance(box,x1,y1,z1,x2,y2,z2):
delx = x2 - x1 delx = x2 - x1
@ -37,12 +39,12 @@ def distance(box,x1,y1,z1,x2,y2,z2):
# main script # main script
if len(argv) < 3: if len(argv) < 3:
raise StandardError,"group_energy.py data.file dump.file1 dump.file2 ..." raise Exception("group_energy.py data.file dump.file1 dump.file2 ...")
dt = data(argv[1]) # data file dt = data(argv[1]) # data file
q = dt.get("Atoms",4) q = dt.get("Atoms",4)
files = ' '.join(argv[2:]) # dump files files = ' '.join(argv[2:]) # dump files
d = dump(files,0) d = dump(files,0)
d.map(1,"id",2,"type",3,"x",4,"y",5,"z") d.map(1,"id",2,"type",3,"x",4,"y",5,"z")
@ -75,32 +77,32 @@ while 1:
d.aselect.test("$id >= 1 and $id <= 7243 or $id >= 7274 and $id <= 14283", d.aselect.test("$id >= 1 and $id <= 7243 or $id >= 7274 and $id <= 14283",
time) time)
id2,type2,x2,y2,z2 = d.vecs(time,"id","type","x","y","z") id2,type2,x2,y2,z2 = d.vecs(time,"id","type","x","y","z")
id1 = map(int,id1) id1 = list(map(int,id1))
id2 = map(int,id2) id2 = list(map(int,id2))
type1 = map(int,type1) type1 = list(map(int,type1))
type2 = map(int,type2) type2 = list(map(int,type2))
n1 = len(type1) n1 = len(type1)
n2 = len(type2) n2 = len(type2)
for i in xrange(n1): for i in range(n1):
id1[i] -= 1 id1[i] -= 1
type1[i] -= 1 type1[i] -= 1
for i in xrange(n2): for i in range(n2):
id2[i] -= 1 id2[i] -= 1
type2[i] -= 1 type2[i] -= 1
e_coul_sum = 0.0 e_coul_sum = 0.0
e_vdwl_sum = 0.0 e_vdwl_sum = 0.0
for i in xrange(n1): for i in range(n1):
typei = type1[i] typei = type1[i]
qi = q[id1[i]] qi = q[id1[i]]
for j in xrange(n2): for j in range(n2):
rsq = distance(box,x1[i],y1[i],z1[i],x2[j],y2[j],z2[j]) rsq = distance(box,x1[i],y1[i],z1[i],x2[j],y2[j],z2[j])
if rsq < maxcut_sq: if rsq < maxcut_sq:
eng_coul,eng_vdwl = p.single(rsq,typei,type2[j],qi,q[id2[j]]) eng_coul,eng_vdwl = p.single(rsq,typei,type2[j],qi,q[id2[j]])
e_coul_sum += eng_coul e_coul_sum += eng_coul
e_vdwl_sum += eng_vdwl e_vdwl_sum += eng_vdwl
print "eng_coul = %g at timestep %d" % (e_coul_sum,time) print("eng_coul = %g at timestep %d" % (e_coul_sum,time))
print "eng_vdwl = %g at timestep %d" % (e_vdwl_sum,time) print("eng_vdwl = %g at timestep %d" % (e_vdwl_sum,time))
d.tselect.none() d.tselect.none()
d.tselect.one(time) d.tselect.one(time)

View File

@ -1,5 +1,7 @@
# movie of flow around obstacle # movie of flow around obstacle
from __future__ import absolute_import
d = dump("dump.flow") d = dump("dump.flow")
d.map(1,"id",2,"type",3,"x",4,"y",5,"z",6,"vx",7,"vy") d.map(1,"id",2,"type",3,"x",4,"y",5,"z",6,"vx",7,"vy")
d.set("$ke = sqrt($vx*$vx + $vy*$vy)") d.set("$ke = sqrt($vx*$vx + $vy*$vy)")
@ -7,8 +9,8 @@ d.spread("vx",100,"color")
d.atype = "color" d.atype = "color"
r = raster(d) r = raster(d)
r.acol(range(100),["red","red","red","red","yellow","green","blue","purple","purple","purple","purple"]) r.acol(list(range(100)),["red","red","red","red","yellow","green","blue","purple","purple","purple","purple"])
r.arad(range(100),0.5) r.arad(list(range(100)),0.5)
r.rotate(0,-90) r.rotate(0,-90)
r.zoom(1.5) r.zoom(1.5)
r.file = "flow" r.file = "flow"

View File

@ -1,6 +1,6 @@
# movie of melting LJ solid # movie of melting LJ solid
a = dump("dump.melt") a = dump("files/dump.melt")
a.tselect.test("$t == 0") a.tselect.test("$t == 0")
a.scale() a.scale()
a.set("$ix = int($x * 4)") a.set("$ix = int($x * 4)")

View File

@ -1,10 +1,12 @@
# movie of self-assembling micelles # movie of self-assembling micelles
d = dump("dump.micelle") from __future__ import absolute_import
d = dump("files/dump.micelle")
s = svg(d) s = svg(d)
s.acol([1,2,3,4],["blue","red","cyan","yellow"]) s.acol([1,2,3,4],["blue","red","cyan","yellow"])
s.arad(range(4),0.5) s.arad(list(range(4)),0.5)
s.zoom(1.5) s.zoom(1.5)
s.file = "micelle" s.file = "micelle"

View File

@ -1,8 +1,8 @@
# movie of solvated peptide data # movie of solvated peptide data
d = dump("dump.peptide") d = dump("files/dump.peptide")
d.unwrap() d.unwrap()
p = pdb("peptide",d) p = pdbfile("files/peptide",d)
r.file = "peptide"
r = rasmol(p) r = rasmol(p)
r.all() r.all()

View File

@ -1,6 +1,6 @@
# movie of triangular particle data # movie of triangular particle data
d = dump("dump.tri") d = dump("files/dump.tri")
d.set("$center = ((int($id)-1)/36+1)*36") d.set("$center = ((int($id)-1)/36+1)*36")
d.owrap("center") d.owrap("center")

View File

@ -11,4 +11,4 @@ a.next()
a.previous() a.previous()
a.frame(1) a.frame(1)
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -9,4 +9,4 @@ dm.extra(b)
g = gl(dm) g = gl(dm)
v = vcr(g) v = vcr(g)
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -31,4 +31,4 @@ c.select("A","B","C","linebox","organelle","nuchalf")
g = gl(c) g = gl(c)
v = vcr(g) v = vcr(g)
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -9,4 +9,4 @@ x.one()
x.many() x.many()
x.single(0,"tmp.single") x.single(0,"tmp.single")
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -14,4 +14,4 @@ c.build(10,25)
c.write("tmp.data.chain") c.write("tmp.data.chain")
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -4,13 +4,13 @@
c = log("files/log.ccell") c = log("files/log.ccell")
print "# of vectors =",c.nvec print("# of vectors =",c.nvec)
print "length of vectors =",c.nlen print("length of vectors =",c.nlen)
print "names of vectors =",c.names print("names of vectors =",c.names)
time,a,b = c.get("Step","prey","predator") time,a,b = c.get("Step","prey","predator")
print a,b print(a,b)
c.write("tmp.clog") c.write("tmp.clog")
c.write("tmp.clog.two","Step","prey") c.write("tmp.clog.two","Step","prey")
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -1,18 +1,20 @@
# simple test of data tool # simple test of data tool
# requires files/data.micelle # requires files/data.micelle and dump.micelle
# creates tmp.data # creates tmp.data
from __future__ import absolute_import
d = data("files/data.micelle") d = data("files/data.micelle")
d.map(1,"id",3,"type",4,"x",5,"y",6,"z") d.map(1,"id",3,"type",4,"x",5,"y",6,"z")
coeffs = d.get("Masses") coeffs = d.get("Masses")
print "Masses",coeffs print("Masses",coeffs)
x = d.get("Atoms",4) x = d.get("Atoms",4)
print "X of 1st atom",x[0] print("X of 1st atom",x[0])
d.title = "New LAMMPS data file" d.title = "New LAMMPS data file"
natoms = d.headers["atoms"] natoms = d.headers["atoms"]
vec = range(1,natoms+1) vec = list(range(1,natoms+1))
vec.reverse() vec.reverse()
d.replace("Atoms",1,vec) d.replace("Atoms",1,vec)
@ -27,4 +29,4 @@ while 1:
d.write("tmp.data") d.write("tmp.data")
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -27,12 +27,12 @@ d.set("$xyz = $x + $y + $z")
d.spread("x",100,"color") d.spread("x",100,"color")
d.clone(0,"color") d.clone(0,"color")
print "Time",d.time() print("Time",d.time())
color = d.atom(1,"color") color = d.atom(1,"color")
print "Color of atom 1",color print("Color of atom 1",color)
d.aselect.test("$id <= 10") d.aselect.test("$id <= 10")
color = d.vecs(1000,"color") color = d.vecs(1000,"color")
print "Color of 1st 10 atoms in step 1000",color print("Color of 1st 10 atoms in step 1000",color)
d.atype = "color" d.atype = "color"
@ -42,13 +42,13 @@ while 1:
if flag == -1: break if flag == -1: break
time,box,atoms,bonds,tris,lines = d.viz(index) time,box,atoms,bonds,tris,lines = d.viz(index)
colors = [atom[1] for atom in atoms] colors = [atom[1] for atom in atoms]
print time,colors print(time,colors)
d = dump("files/dump.peptide.*",0) d = dump("files/dump.peptide.*",0)
while 1: while 1:
time = d.next() time = d.next()
if time < 0: break if time < 0: break
print "Incrementally read snaps =",d.nsnaps print("Incrementally read snaps =",d.nsnaps)
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -1,4 +1,4 @@
# simple test of xyz tool # simple test of ensight tool
# requires files/dump.micelle.* # requires files/dump.micelle.*
# creates tmp*.case, etc # creates tmp*.case, etc
@ -8,4 +8,4 @@ e.one()
e.many() e.many()
e.single(0) e.single(0)
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -2,6 +2,8 @@
# requires files/dump.kinase # requires files/dump.kinase
# creates tmp*.png # creates tmp*.png
from __future__ import absolute_import
d = dump("files/dump.kinase") d = dump("files/dump.kinase")
g = gl(d) g = gl(d)
@ -17,7 +19,7 @@ g.all()
from vizinfo import colors from vizinfo import colors
g.acol([1,4,6,8,9],["gray","red","blue","green","yellow"]) g.acol([1,4,6,8,9],["gray","red","blue","green","yellow"])
g.arad(range(9),0.3) g.arad(list(range(9)),0.3)
#g.label(0.2,0.4,'h',15,"red","test label #1") #g.label(0.2,0.4,'h',15,"red","test label #1")
#g.label(-0.2,-0.4,'h',15,"yellow","test label #2") #g.label(-0.2,-0.4,'h',15,"yellow","test label #2")
@ -25,4 +27,4 @@ g.show(0)
g.pan(60,130,1,60,30,0.5) g.pan(60,130,1,60,30,0.5)
g.all(0,10,0) g.all(0,10,0)
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -1,17 +1,19 @@
# simple test of gnu tool # simple test of gnu tool
# creates tmp.eps # creates tmp.eps
from __future__ import absolute_import
g = gnu() g = gnu()
g("plot sin(x) with lines") g("plot sin(x) with lines")
a = range(10) a = list(range(10))
b = [3,6,2,5,7,3,6,5,3,1] b = [3,6,2,5,7,3,6,5,3,1]
g.plot(a) g.plot(a)
g.plot(a,b) g.plot(a,b)
g.plot(a,b,b,a) g.plot(a,b,b,a)
g.mplot(0,10,2,"tmp",a,b) g.mplot(2,10,2,"tmp",a,b)
g.export("tmp.gnu",a,b) g.export("tmp.gnu",a,b)
@ -30,4 +32,4 @@ g.ylog()
g.save("tmp") g.save("tmp")
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -10,4 +10,4 @@ g.ytitle("Particle Count")
g.title("Histogram of Particle Density") g.title("Histogram of Particle Density")
g.plot(x,y) g.plot(x,y)
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -4,6 +4,6 @@
i = image("files/bucky*.png") i = image("files/bucky*.png")
i.convert("files/bucky*.png","tmp*.gif") i.convert("files/bucky*.png","tmp*.gif")
i.montage("","files/bucky*.png","tmp*.gif","tmpnew*.png") i.montage("","files/bucky*.png","tmp*.gif","tmpnew*.png")
i.view("") i.view("*.png")
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -12,4 +12,4 @@ g.lrad(1,5)
g.lcol(1,"green") g.lcol(1,"green")
v = vcr(g) v = vcr(g)
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -4,13 +4,13 @@
lg = log("files/log.obstacle") lg = log("files/log.obstacle")
print "# of vectors =",lg.nvec print("# of vectors =",lg.nvec)
print "length of vectors =",lg.nlen print("length of vectors =",lg.nlen)
print "names of vectors =",lg.names print("names of vectors =",lg.names)
time,temp,press = lg.get("Step","Temp","Press") time,temp,press = lg.get("Step","Temp","Press")
print temp,press print(temp,press)
lg.write("tmp.log") lg.write("tmp.log")
lg.write("tmp.log.two","Step","E_pair") lg.write("tmp.log.two","Step","E_pair")
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -1,9 +1,11 @@
# simple test of matlab tool # simple test of matlab tool
# creates tmp.eps # creates tmp.eps
from __future__ import absolute_import
m = matlab() m = matlab()
a = range(10) a = list(range(10))
b = [3,6,2,5,7,3,6,5,3,1] b = [3,6,2,5,7,3,6,5,3,1]
m.plot(a) m.plot(a)
@ -30,4 +32,4 @@ m.ylog()
m.save("tmp") m.save("tmp")
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -12,7 +12,7 @@ m.tselect.all()
m.tselect.test("$t >= 100 and $t <= 200") m.tselect.test("$t >= 100 and $t <= 200")
m.delete() m.delete()
print "Time",m.time() print("Time",m.time())
m.map(2,"spin") m.map(2,"spin")
m.etype = "spin" m.etype = "spin"
@ -23,13 +23,13 @@ while 1:
if flag == -1: break if flag == -1: break
time,box,atoms,bonds,tris,lines = m.viz(index) time,box,atoms,bonds,tris,lines = m.viz(index)
colors = [tri[1] for tri in tris] colors = [tri[1] for tri in tris]
print time,colors print(time,colors)
m = dump("files/mesh.grain",0) m = dump("files/mesh.grain",0)
while 1: while 1:
time = m.next() time = m.next()
if time < 0: break if time < 0: break
print "Incrementally read snaps =",m.nsnaps print("Incrementally read snaps =",m.nsnaps)
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -6,6 +6,6 @@ d = data("files/data.rhodo")
p.coeff(d) p.coeff(d)
p.init(8.0,10.0) p.init(8.0,10.0)
ev,ec = p.single(5.0,1,2,0.5,-0.5) ev,ec = p.single(5.0,1,2,0.5,-0.5)
print "Energies",ev,ec print("Energies",ev,ec)
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -7,4 +7,4 @@ p.build(100,"hex2",1,2,3)
p.build(50,"tri5",4,5) p.build(50,"tri5",4,5)
p.write("tmp.data.patch") p.write("tmp.data.patch")
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -15,6 +15,6 @@ while 1:
p.single(time,"tmp.single") p.single(time,"tmp.single")
n += 1 n += 1
print "Incrementally processed %d PDB files" % n print("Incrementally processed %d PDB files" % n)
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -15,4 +15,4 @@ p.no(2)
p.file("tmp.plotview") p.file("tmp.plotview")
p.save() p.save()
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -8,14 +8,14 @@ p = pdbfile("files/peptide",d)
r = rasmol(p) r = rasmol(p)
r.file = "tmp" r.file = "tmp"
print "kill image window when ready to contine ..." print("kill image window when ready to contine ...")
r.show(0) r.show(0)
r.all() r.all()
# change RasMol settings, run all() with those settings # change RasMol settings, run all() with those settings
print "change RasMol settings as desired, then type 'quit' ..." print("change RasMol settings as desired, then type 'quit' ...")
r.run(0) r.run(0)
r.all("tmp.rasmol") r.all("tmp.rasmol")
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -2,6 +2,8 @@
# requires files/dump.kinase # requires files/dump.kinase
# creates tmp*.png # creates tmp*.png
from __future__ import absolute_import
d = dump("files/dump.kinase") d = dump("files/dump.kinase")
r = raster(d) r = raster(d)
@ -10,7 +12,7 @@ r.rotate(60,130)
r.box(1) r.box(1)
r.file = "tmp" r.file = "tmp"
print "kill image window when ready to contine ..." print("kill image window when ready to contine ...")
r.show(0) r.show(0)
r.all() r.all()
a1 = animate("tmp0*png") a1 = animate("tmp0*png")
@ -18,14 +20,14 @@ a1 = animate("tmp0*png")
from vizinfo import colors from vizinfo import colors
r.acol([1,4,6,8,9],["gray","red","blue","green","yellow"]) r.acol([1,4,6,8,9],["gray","red","blue","green","yellow"])
r.arad(range(9),0.3) r.arad(list(range(9)),0.3)
r.label(0.2,0.4,'h',15,"red","test label #1") r.label(0.2,0.4,'h',15,"red","test label #1")
r.label(-0.2,-0.4,'h',15,"yellow","test label #2") r.label(-0.2,-0.4,'h',15,"yellow","test label #2")
print "kill image window when ready to contine ..." print("kill image window when ready to contine ...")
r.show(0) r.show(0)
r.pan(60,130,1,60,30,0.5) r.pan(60,130,1,60,30,0.5)
r.all(0,10,0) r.all(0,10,0)
a2 = animate("tmp0*png") a2 = animate("tmp0*png")
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -2,6 +2,8 @@
# requires files/dump.kinase # requires files/dump.kinase
# creates tmp*.png # creates tmp*.png
from __future__ import absolute_import
d = dump("files/dump.kinase") d = dump("files/dump.kinase")
s = svg(d) s = svg(d)
@ -10,20 +12,20 @@ s.rotate(60,130)
s.box(1) s.box(1)
s.file = "tmp" s.file = "tmp"
print "kill image window when ready to contine ..." print("kill image window when ready to contine ...")
s.show(0) s.show(0)
s.all() s.all()
from vizinfo import colors from vizinfo import colors
s.acol([1,4,6,8,9],["gray","red","blue","green","yellow"]) s.acol([1,4,6,8,9],["gray","red","blue","green","yellow"])
s.arad(range(9),0.3) s.arad(list(range(9)),0.3)
s.label(0.2,0.4,'h',15,"red","test label #1") s.label(0.2,0.4,'h',15,"red","test label #1")
s.label(-0.2,-0.4,'h',15,"yellow","test label #2") s.label(-0.2,-0.4,'h',15,"yellow","test label #2")
print "kill image window when ready to contine ..." print("kill image window when ready to contine ...")
s.show(0) s.show(0)
s.pan(60,130,1,60,30,0.5) s.pan(60,130,1,60,30,0.5)
s.all(0,10,0) s.all(0,10,0)
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -1,5 +1,4 @@
# simple test of vcr tool # simple test of vcr tool
# requires files/bucky*png files
d = dump("files/dump.micelle") d = dump("files/dump.micelle")
dt = data("files/data.micelle") dt = data("files/data.micelle")
@ -14,4 +13,4 @@ v.clipxlo(0.2)
v.clipxhi(0.5) v.clipxhi(0.5)
v.play() v.play()
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -4,13 +4,13 @@
v = vec("files/vec.txt") v = vec("files/vec.txt")
print "# of vectors =",v.nvec print("# of vectors =",v.nvec)
print "length of vectors =",v.nlen print("length of vectors =",v.nlen)
print "names of vectors =",v.names print("names of vectors =",v.names)
time,temp,press = v.get(1,"col2",6) time,temp,press = v.get(1,"col2",6)
print temp,press print(temp,press)
v.write("tmp.vec") v.write("tmp.vec")
v.write("tmp.vec.two","col1",3) v.write("tmp.vec.two","col1",3)
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -8,4 +8,4 @@ v.rep('VDW')
v.new('files/peptide.pdb','pdb') v.new('files/peptide.pdb','pdb')
v.flush() v.flush()
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -8,4 +8,4 @@ v.one()
v.many() v.many()
v.single(0,"tmp.single") v.single(0,"tmp.single")
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -8,4 +8,4 @@ x.one()
x.many() x.many()
x.single(0,"tmp.single") x.single(0,"tmp.single")
print "all done ... type CTRL-D to exit Pizza.py" print("all done ... type CTRL-D to exit Pizza.py")

View File

@ -17,13 +17,12 @@
import sys import sys
from dump import dump from dump import dump
from math import sqrt,acos,atan from math import sqrt,acos,atan
if not globals().has_key("argv"): argv = sys.argv if "argv" not in globals(): argv = sys.argv
# main script # main script
if len(argv) < 7: if len(argv) < 7:
raise StandardError, \ raise Exception("Syntax: angle_distribute.py datafile nbin theta_min theta_max outfile files ...")
"Syntax: angle_distribute.py datafile nbin theta_min theta_max outfile files ..."
dt = data(argv[1]) dt = data(argv[1])
nbins = int(argv[2]) nbins = int(argv[2])
@ -40,18 +39,18 @@ atype = nangles * [0]
iatom = nangles * [0] iatom = nangles * [0]
jatom = nangles * [0] jatom = nangles * [0]
katom = nangles * [0] katom = nangles * [0]
for i in xrange(nangles): for i in range(nangles):
atype[i] = int(angle[i][1] - 1) atype[i] = int(angle[i][1] - 1)
iatom[i] = int(angle[i][2] - 1) iatom[i] = int(angle[i][2] - 1)
jatom[i] = int(angle[i][3] - 1) jatom[i] = int(angle[i][3] - 1)
katom[i] = int(angle[i][4] - 1) katom[i] = int(angle[i][4] - 1)
ntypes = 0 ntypes = 0
for i in xrange(nangles): ntypes = max(angle[i][1],ntypes) for i in range(nangles): ntypes = max(angle[i][1],ntypes)
ntypes = int(ntypes) ntypes = int(ntypes)
ncount = ntypes * [0] ncount = ntypes * [0]
bin = nbins * [0] bin = nbins * [0]
for i in xrange(nbins): for i in range(nbins):
bin[i] = ntypes * [0] bin[i] = ntypes * [0]
# read snapshots one-at-a-time # read snapshots one-at-a-time
@ -76,7 +75,7 @@ while 1:
d.sort() d.sort()
x,y,z = d.vecs(time,"x","y","z") x,y,z = d.vecs(time,"x","y","z")
for i in xrange(nangles): for i in range(nangles):
delx1 = x[iatom[i]] - x[jatom[i]] delx1 = x[iatom[i]] - x[jatom[i]]
dely1 = y[iatom[i]] - y[jatom[i]] dely1 = y[iatom[i]] - y[jatom[i]]
@ -135,22 +134,22 @@ while 1:
bin[ibin][atype[i]] += nbins bin[ibin][atype[i]] += nbins
ncount[atype[i]] += 1 ncount[atype[i]] += 1
else: else:
print "Warning: angle outside specified range" print("Warning: angle outside specified range")
print "angle type:", atype[i]+1 print("angle type:", atype[i]+1)
print "angle number:", i print("angle number:", i)
print time, print(time, end=' ')
print print()
print "Printing normalized angle distributions to",outfile print("Printing normalized angle distributions to",outfile)
fp = open(outfile,"w") fp = open(outfile,"w")
theta_range = theta_max - theta_min theta_range = theta_max - theta_min
for i in xrange(nbins): for i in range(nbins):
print >>fp, theta_min + theta_range*float(i)/float(nbins), print(theta_min + theta_range*float(i)/float(nbins), end=' ', file=fp)
for j in xrange(ntypes): for j in range(ntypes):
if (ncount[j] > 0): if (ncount[j] > 0):
print >>fp, float(bin[i][j])/float(ncount[j])/theta_range, print(float(bin[i][j])/float(ncount[j])/theta_range, end=' ', file=fp)
else: else:
print >>fp, 0.0, print(0.0, end=' ', file=fp)
print >>fp print(file=fp)
fp.close() fp.close()

View File

@ -13,12 +13,12 @@
import sys import sys
from log import log from log import log
if not globals().has_key("argv"): argv = sys.argv if "argv" not in globals(): argv = sys.argv
# main script # main script
if len(argv) < 4: if len(argv) < 4:
raise StandardError, "Syntax: block.py nblocks nskip log.1 log.2 ..." raise Exception("Syntax: block.py nblocks nskip log.1 log.2 ...")
nblocks = int(argv[1]) nblocks = int(argv[1])
nskip = int(argv[2]) nskip = int(argv[2])
@ -35,8 +35,8 @@ if "Volume" in l.names:
volume = l.get("Volume") volume = l.get("Volume")
else: vflag = 0 else: vflag = 0
print "Computing %g block averages" % nblocks print("Computing %g block averages" % nblocks)
print "Skipping first %g samples" % nskip print("Skipping first %g samples" % nskip)
n = len(step) n = len(step)
n_per_block = (n-nskip)/nblocks n_per_block = (n-nskip)/nblocks
@ -48,11 +48,11 @@ e_total_ave = []
pressure_ave = [] pressure_ave = []
volume_ave = [] volume_ave = []
print print()
print " Block Samples Temperature E_bond E_pair", \ print(" Block Samples Temperature E_bond E_pair", \
" E_total Pressure Volume" " E_total Pressure Volume")
for i in xrange(nblocks): for i in range(nblocks):
temperature_sum = 0 temperature_sum = 0
e_bond_sum = 0 e_bond_sum = 0
e_pair_sum = 0 e_pair_sum = 0
@ -60,7 +60,7 @@ for i in xrange(nblocks):
pressure_sum = 0 pressure_sum = 0
volume_sum = 0 volume_sum = 0
samples = 0 samples = 0
for j in xrange(n_per_block): for j in range(n_per_block):
temperature_sum += temperature[k] temperature_sum += temperature[k]
e_bond_sum += e_bond[k] e_bond_sum += e_bond[k]
e_pair_sum += e_pair[k] e_pair_sum += e_pair[k]
@ -75,9 +75,9 @@ for i in xrange(nblocks):
e_total_ave.append(e_total_sum/samples) e_total_ave.append(e_total_sum/samples)
pressure_ave.append(pressure_sum/samples) pressure_ave.append(pressure_sum/samples)
volume_ave.append(volume_sum/samples) volume_ave.append(volume_sum/samples)
print " %5i %10i %11.2f %11.2f %11.2f %11.2f %11.2f %11.2f" % \ print(" %5i %10i %11.2f %11.2f %11.2f %11.2f %11.2f %11.2f" % \
(i+1, samples, temperature_ave[i], e_bond_ave[i], e_pair_ave[i], \ (i+1, samples, temperature_ave[i], e_bond_ave[i], e_pair_ave[i], \
e_total_ave[i], pressure_ave[i], volume_ave[i]) e_total_ave[i], pressure_ave[i], volume_ave[i]))
grand_ave_temperature = 0.0 grand_ave_temperature = 0.0
grand_ave_e_bond = 0.0 grand_ave_e_bond = 0.0
@ -91,7 +91,7 @@ stdev_e_pair = 0.0
stdev_e_total = 0.0 stdev_e_total = 0.0
stdev_pressure = 0.0 stdev_pressure = 0.0
stdev_volume = 0.0 stdev_volume = 0.0
for i in xrange(nblocks): for i in range(nblocks):
grand_ave_temperature += temperature_ave[i] grand_ave_temperature += temperature_ave[i]
grand_ave_e_bond += e_bond_ave[i] grand_ave_e_bond += e_bond_ave[i]
grand_ave_e_pair += e_pair_ave[i] grand_ave_e_pair += e_pair_ave[i]
@ -104,7 +104,7 @@ grand_ave_e_pair /= nblocks
grand_ave_e_total /= nblocks grand_ave_e_total /= nblocks
grand_ave_pressure /= nblocks grand_ave_pressure /= nblocks
grand_ave_volume /= nblocks grand_ave_volume /= nblocks
for i in xrange(nblocks): for i in range(nblocks):
stdev_temperature += (temperature_ave[i] - grand_ave_temperature)* \ stdev_temperature += (temperature_ave[i] - grand_ave_temperature)* \
(temperature_ave[i] - grand_ave_temperature) (temperature_ave[i] - grand_ave_temperature)
stdev_e_bond += (e_bond_ave[i] - grand_ave_e_bond)* \ stdev_e_bond += (e_bond_ave[i] - grand_ave_e_bond)* \
@ -125,13 +125,13 @@ stdev_e_total = sqrt(stdev_e_total/(nblocks-1))
stdev_pressure = sqrt(stdev_pressure/(nblocks-1)) stdev_pressure = sqrt(stdev_pressure/(nblocks-1))
stdev_volume = sqrt(stdev_volume/(nblocks-1)) stdev_volume = sqrt(stdev_volume/(nblocks-1))
print " ====================================================", \ print(" ====================================================", \
"===================================" "===================================")
print " Ave. %11.2f %11.2f %11.2f %11.2f %11.2f %11.2f" % \ print(" Ave. %11.2f %11.2f %11.2f %11.2f %11.2f %11.2f" % \
(grand_ave_temperature, grand_ave_e_bond, grand_ave_e_pair, \ (grand_ave_temperature, grand_ave_e_bond, grand_ave_e_pair, \
grand_ave_e_total, grand_ave_pressure, grand_ave_volume) grand_ave_e_total, grand_ave_pressure, grand_ave_volume))
print " Stdev %11.2f %11.2f %11.2f %11.2f %11.2f %11.2f" % \ print(" Stdev %11.2f %11.2f %11.2f %11.2f %11.2f %11.2f" % \
(stdev_temperature, stdev_e_bond, stdev_e_pair, \ (stdev_temperature, stdev_e_bond, stdev_e_pair, \
stdev_e_total, stdev_pressure, stdev_volume) stdev_e_total, stdev_pressure, stdev_volume))

View File

@ -17,13 +17,12 @@
import sys import sys
from dump import dump from dump import dump
from math import sqrt from math import sqrt
if not globals().has_key("argv"): argv = sys.argv if "argv" not in globals(): argv = sys.argv
# main script # main script
if len(argv) < 7: if len(argv) < 7:
raise StandardError, \ raise Exception("Syntax: bond_distribute.py datafile nbin rmin rmax outfile files ...")
"Syntax: bond_distribute.py datafile nbin rmin rmax outfile files ..."
dt = data(argv[1]) dt = data(argv[1])
nbins = int(argv[2]) nbins = int(argv[2])
@ -39,17 +38,17 @@ nbonds = len(bond)
btype = nbonds * [0] btype = nbonds * [0]
iatom = nbonds * [0] iatom = nbonds * [0]
jatom = nbonds * [0] jatom = nbonds * [0]
for i in xrange(nbonds): for i in range(nbonds):
btype[i] = int(bond[i][1] - 1) btype[i] = int(bond[i][1] - 1)
iatom[i] = int(bond[i][2] - 1) iatom[i] = int(bond[i][2] - 1)
jatom[i] = int(bond[i][3] - 1) jatom[i] = int(bond[i][3] - 1)
ntypes = 0 ntypes = 0
for i in xrange(nbonds): ntypes = max(bond[i][1],ntypes) for i in range(nbonds): ntypes = max(bond[i][1],ntypes)
ntypes = int(ntypes) ntypes = int(ntypes)
ncount = ntypes * [0] ncount = ntypes * [0]
bin = nbins * [0] bin = nbins * [0]
for i in xrange(nbins): for i in range(nbins):
bin[i] = ntypes * [0] bin[i] = ntypes * [0]
# read snapshots one-at-a-time # read snapshots one-at-a-time
@ -72,7 +71,7 @@ while 1:
d.sort() d.sort()
x,y,z = d.vecs(time,"x","y","z") x,y,z = d.vecs(time,"x","y","z")
for i in xrange(nbonds): for i in range(nbonds):
delx = x[jatom[i]] - x[iatom[i]] delx = x[jatom[i]] - x[iatom[i]]
dely = y[jatom[i]] - y[iatom[i]] dely = y[jatom[i]] - y[iatom[i]]
@ -101,22 +100,22 @@ while 1:
bin[ibin][btype[i]] += nbins bin[ibin][btype[i]] += nbins
ncount[btype[i]] += 1 ncount[btype[i]] += 1
else: else:
print "Warning: bond distance outside specified range" print("Warning: bond distance outside specified range")
print "Bond type:", btype[i]+1 print("Bond type:", btype[i]+1)
print "Bond number:", i print("Bond number:", i)
print time, print(time, end=' ')
print print()
print "Printing bond distance normalized distribution to",outfile print("Printing bond distance normalized distribution to",outfile)
fp = open(outfile,"w") fp = open(outfile,"w")
rrange = rmax - rmin rrange = rmax - rmin
for i in xrange(nbins): for i in range(nbins):
print >>fp, rmin + rrange*float(i)/float(nbins), print(rmin + rrange*float(i)/float(nbins), end=' ', file=fp)
for j in xrange(ntypes): for j in range(ntypes):
if (ncount[j] > 0): if (ncount[j] > 0):
print >>fp, float(bin[i][j])/float(ncount[j])/rrange, print(float(bin[i][j])/float(ncount[j])/rrange, end=' ', file=fp)
else: else:
print >>fp, 0.0, print(0.0, end=' ', file=fp)
print >>fp print(file=fp)
fp.close() fp.close()

View File

@ -15,18 +15,18 @@ from clog import clog
from plotview import plotview from plotview import plotview
from gnu import gnu from gnu import gnu
from matlab import matlab from matlab import matlab
if not globals().has_key("argv"): argv = sys.argv if "argv" not in globals(): argv = sys.argv
# main script # main script
if len(argv) < 3: if len(argv) < 3:
raise StandardError, "Syntax: clogview.py gnu/matlab files ..." raise Exception("Syntax: clogview.py gnu/matlab files ...")
style = argv[1] style = argv[1]
files = ' '.join(argv[2:]) files = ' '.join(argv[2:])
c = clog(files) c = clog(files)
exec "plot = %s()" % style exec("plot = %s()" % style)
p = plotview(c,plot) p = plotview(c,plot)
p.x = "Time" p.x = "Time"

View File

@ -18,7 +18,7 @@
import sys import sys
from dump import dump from dump import dump
from gnu import gnu from gnu import gnu
if not globals().has_key("argv"): argv = sys.argv if "argv" not in globals(): argv = sys.argv
# main script # main script
@ -62,7 +62,7 @@ def distance(atom1,atom2,box):
# main script # main script
if len(argv) < 6: if len(argv) < 6:
raise StandardError,"cluster.py type1 type2 cutoff nbin dump.1 dump.2 ..." raise Exception("cluster.py type1 type2 cutoff nbin dump.1 dump.2 ...")
type1 = int(argv[1]) type1 = int(argv[1])
type2 = int(argv[2]) type2 = int(argv[2])
@ -81,20 +81,20 @@ d.aselect.test("$type == %d or $type == %d" % (type1,type2))
cutsq = cutoff*cutoff cutsq = cutoff*cutoff
cluster = nbin*[0] cluster = nbin*[0]
print "Clustering ..." print("Clustering ...")
flag = 0 flag = 0
while 1: while 1:
which,time,flag = d.iterator(flag) which,time,flag = d.iterator(flag)
if flag == -1: break if flag == -1: break
time,box,atoms,bonds,tris = d.viz(which) time,box,atoms,bonds,tris = d.viz(which)
print time, print(time, end=' ')
sys.stdout.flush() sys.stdout.flush()
# loop over all type1 atoms # loop over all type1 atoms
n = len(atoms) n = len(atoms)
for i in xrange(n): for i in range(n):
itype = atoms[i][1] itype = atoms[i][1]
if itype != type1: continue if itype != type1: continue
ncount = 0 ncount = 0
@ -102,7 +102,7 @@ while 1:
# loop over all type2 atoms # loop over all type2 atoms
# increment cluster count if distance is within cutoff # increment cluster count if distance is within cutoff
for j in xrange(n): for j in range(n):
jtype = atoms[j][1] jtype = atoms[j][1]
if jtype != type2 or i == j: continue if jtype != type2 or i == j: continue
distsq = distance(atoms[i],atoms[j],box) distsq = distance(atoms[i],atoms[j],box)
@ -113,9 +113,9 @@ while 1:
if ncount >= nbin: cluster[nbin-1] += 1 if ncount >= nbin: cluster[nbin-1] += 1
else: cluster[ncount] += 1 else: cluster[ncount] += 1
print print()
print "Cluster size and count:" print("Cluster size and count:")
for i in range(nbin): print i,cluster[i] for i in range(nbin): print(i,cluster[i])
# comment out if don't want plot # comment out if don't want plot

View File

@ -14,12 +14,12 @@
import sys import sys
from dump import dump from dump import dump
if not globals().has_key("argv"): argv = sys.argv if "argv" not in globals(): argv = sys.argv
# main script # main script
if len(argv) < 5: if len(argv) < 5:
raise StandardError, "Syntax: density.py x/y/z nbin outfile files ..." raise Exception("Syntax: density.py x/y/z nbin outfile files ...")
direction = argv[1] direction = argv[1]
nbins = int(argv[2]) nbins = int(argv[2])
@ -41,7 +41,7 @@ while 1:
tmp,ntypes = d.minmax("type") tmp,ntypes = d.minmax("type")
ntypes = int(ntypes) ntypes = int(ntypes)
bin = nbins * [0] bin = nbins * [0]
for i in xrange(nbins): bin[i] = ntypes * [0] for i in range(nbins): bin[i] = ntypes * [0]
first = 0 first = 0
box = (d.snaps[-1].xlo,d.snaps[-1].ylo,d.snaps[-1].zlo, box = (d.snaps[-1].xlo,d.snaps[-1].ylo,d.snaps[-1].zlo,
@ -52,26 +52,26 @@ while 1:
elif direction == "y": type,x = d.vecs(time,"type","y") elif direction == "y": type,x = d.vecs(time,"type","y")
elif direction == "z": type,x = d.vecs(time,"type","z") elif direction == "z": type,x = d.vecs(time,"type","z")
type = map(int,type) type = list(map(int,type))
natoms = len(type) natoms = len(type)
for i in xrange(natoms): type[i] -= 1 for i in range(natoms): type[i] -= 1
for i in xrange(natoms): for i in range(natoms):
ibin = int(nbins*x[i] + 0.5) ibin = int(nbins*x[i] + 0.5)
if (ibin < 0): ibin += nbins if (ibin < 0): ibin += nbins
if (ibin > nbins-1): ibin -= nbins if (ibin > nbins-1): ibin -= nbins
bin[ibin][type[i]] += nbins/vol bin[ibin][type[i]] += nbins/vol
nsnaps += 1 nsnaps += 1
print time, print(time, end=' ')
print print()
print "Printing ", direction, "-directional density distribution in mol/L to",outfile print("Printing ", direction, "-directional density distribution in mol/L to",outfile)
conversion = 1660.53873 # convert from atoms/Angs^3 to mol/L conversion = 1660.53873 # convert from atoms/Angs^3 to mol/L
fp = open(outfile,"w") fp = open(outfile,"w")
for i in xrange(nbins): for i in range(nbins):
print >>fp, float(i)/float(nbins), print(float(i)/float(nbins), end=' ', file=fp)
for j in xrange(ntypes): for j in range(ntypes):
print >>fp, conversion*bin[i][j]/nsnaps, print(conversion*bin[i][j]/nsnaps, end=' ', file=fp)
print >>fp print(file=fp)
fp.close() fp.close()

View File

@ -18,12 +18,12 @@
import sys import sys
import numpy as np import numpy as np
from dump import dump from dump import dump
if not globals().has_key("argv"): argv = sys.argv if "argv" not in globals(): argv = sys.argv
# main script # main script
if len(argv) < 5: if len(argv) < 5:
raise StandardError, "Syntax: density.py x/y/z nbin vmin vmax outfile files ..." raise Exception("Syntax: density.py x/y/z nbin vmin vmax outfile files ...")
direction = argv[1] direction = argv[1]
nbins = int(argv[2]) nbins = int(argv[2])
@ -102,11 +102,11 @@ while 1:
zmin = max(zmin,box[0]) zmin = max(zmin,box[0])
vol = dx * dy * float(zmax - zmin) vol = dx * dy * float(zmax - zmin)
type = map(int,type) type = list(map(int,type))
natoms = len(type) natoms = len(type)
for i in xrange(natoms): type[i] -= 1 for i in range(natoms): type[i] -= 1
for i in xrange(natoms): for i in range(natoms):
ibin = int(nbins*x[i]) ibin = int(nbins*x[i])
jbin = int(nbins*y[i]) jbin = int(nbins*y[i])
zloc = float(z[i])*float(dz) zloc = float(z[i])*float(dz)
@ -117,10 +117,10 @@ while 1:
if (jbin > nbins-1): jbin = nbins - 1 if (jbin > nbins-1): jbin = nbins - 1
bin[jbin][ibin][type[i]] += nbins*nbins/vol bin[jbin][ibin][type[i]] += nbins*nbins/vol
nsnaps += 1 nsnaps += 1
print time, print(time, end=' ')
print print()
print "Printing %s-mapped density distribution for %s-slice [%.2f,%.2f] in mol/L to %s" %(bidirect, direction, zmin, zmax, outfile) print("Printing %s-mapped density distribution for %s-slice [%.2f,%.2f] in mol/L to %s" %(bidirect, direction, zmin, zmax, outfile))
conversion = 1660.53873 # convert from atoms/Angs^3 to mol/L conversion = 1660.53873 # convert from atoms/Angs^3 to mol/L
fp = open(outfile,"w") fp = open(outfile,"w")
@ -129,10 +129,10 @@ fp = open(outfile,"w")
# for k in xrange(ntypes): # for k in xrange(ntypes):
# print >>fp, " %8s " %(k), # print >>fp, " %8s " %(k),
# print >>fp # print >>fp
for i in xrange(nbins): for i in range(nbins):
for j in xrange(nbins): for j in range(nbins):
print >>fp, " %8.3f %8.3f " %(float(i)/float(nbins)*float(dx)+float(x0), float(j)/float(nbins)*float(dy)+float(y0)), print(" %8.3f %8.3f " %(float(i)/float(nbins)*float(dx)+float(x0), float(j)/float(nbins)*float(dy)+float(y0)), end=' ', file=fp)
for k in xrange(ntypes): for k in range(ntypes):
print >>fp, " %8.3f " % (conversion*bin[j][i][k]/nsnaps), print(" %8.3f " % (conversion*bin[j][i][k]/nsnaps), end=' ', file=fp)
print >>fp print(file=fp)
fp.close() fp.close()

View File

@ -16,12 +16,12 @@
import sys import sys
from dump import dump from dump import dump
if not globals().has_key("argv"): argv = sys.argv if "argv" not in globals(): argv = sys.argv
# main script # main script
if len(argv) < 5: if len(argv) < 5:
raise StandardError, "Syntax: density.py x/y/z nbin outfile files ..." raise Exception("Syntax: density.py x/y/z nbin outfile files ...")
direction = argv[1] direction = argv[1]
nbins = int(argv[2]) nbins = int(argv[2])
@ -44,7 +44,7 @@ while 1:
tmp,ntypes = d.minmax("type") tmp,ntypes = d.minmax("type")
ntypes = int(ntypes) ntypes = int(ntypes)
bin = nbins * [0] bin = nbins * [0]
for i in xrange(nbins): bin[i] = ntypes * [0] for i in range(nbins): bin[i] = ntypes * [0]
first = 0 first = 0
box = (d.snaps[-1].xlo,d.snaps[-1].ylo,d.snaps[-1].zlo, box = (d.snaps[-1].xlo,d.snaps[-1].ylo,d.snaps[-1].zlo,
@ -55,21 +55,21 @@ while 1:
elif direction == "y": type,x = d.vecs(time,"type","y") elif direction == "y": type,x = d.vecs(time,"type","y")
elif direction == "z": type,x = d.vecs(time,"type","z") elif direction == "z": type,x = d.vecs(time,"type","z")
type = map(int,type) type = list(map(int,type))
natoms = len(type) natoms = len(type)
for i in xrange(natoms): type[i] -= 1 for i in range(natoms): type[i] -= 1
for i in xrange(natoms): for i in range(natoms):
ibin = int(nbins*x[i] + 0.5) ibin = int(nbins*x[i] + 0.5)
if (ibin < 0): ibin += nbins if (ibin < 0): ibin += nbins
if (ibin > nbins-1): ibin -= nbins if (ibin > nbins-1): ibin -= nbins
bin[ibin][type[i]] += nbins/vol bin[ibin][type[i]] += nbins/vol
nsnaps += 1 nsnaps += 1
print time, print(time, end=' ')
print print()
print "Printing ",direction,"-directional density distribution in mol/L to", \ print("Printing ",direction,"-directional density distribution in mol/L to", \
outfile outfile)
conversion = 1660.53873 # convert from atoms/Angs^3 to mol/L conversion = 1660.53873 # convert from atoms/Angs^3 to mol/L
# Output as x, density_1, area_1, ... # Output as x, density_1, area_1, ...
@ -78,20 +78,20 @@ fp = open(outfile,"w")
first = 1 first = 1
xden = nbins * [0] xden = nbins * [0]
yden = nbins * [0] yden = nbins * [0]
for i in xrange(nbins): yden[i] = ntypes * [0] for i in range(nbins): yden[i] = ntypes * [0]
sum = ntypes * [0] sum = ntypes * [0]
for i in xrange(nbins): for i in range(nbins):
xden[i] = float(i)/float(nbins) xden[i] = float(i)/float(nbins)
print >>fp, xden[i], print(xden[i], end=' ', file=fp)
if first: if first:
for j in xrange(ntypes): for j in range(ntypes):
yden[i][j] = conversion*bin[i][j]/nsnaps yden[i][j] = conversion*bin[i][j]/nsnaps
print >>fp, yden[i][j], sum[j], print(yden[i][j], sum[j], end=' ', file=fp)
first = 0 first = 0
else: else:
for j in xrange(ntypes): for j in range(ntypes):
yden[i][j] = conversion*bin[i][j]/nsnaps yden[i][j] = conversion*bin[i][j]/nsnaps
sum[j] += 0.5 * (xden[i] - xden[i-1]) * (yden[i][j] + yden[i-1][j]) sum[j] += 0.5 * (xden[i] - xden[i-1]) * (yden[i][j] + yden[i-1][j])
print >>fp, yden[i][j], sum[j], print(yden[i][j], sum[j], end=' ', file=fp)
print >>fp print(file=fp)
fp.close() fp.close()

View File

@ -12,12 +12,12 @@
from math import sqrt from math import sqrt
if len(argv) < 3: if len(argv) < 3:
raise StandardError,"distance.py maxcut dump.file1 dump.file2 ..." raise Exception("distance.py maxcut dump.file1 dump.file2 ...")
maxcut = float(argv[1]) maxcut = float(argv[1])
maxcut_sq = maxcut*maxcut maxcut_sq = maxcut*maxcut
files = ' '.join(argv[2:]) # dump files files = ' '.join(argv[2:]) # dump files
d = dump(files,0) d = dump(files,0)
d.map(1,"id",2,"type",3,"x",4,"y",5,"z") d.map(1,"id",2,"type",3,"x",4,"y",5,"z")
@ -36,8 +36,8 @@ while 1:
yprd = box[4] - box[1] yprd = box[4] - box[1]
zprd = box[5] - box[2] zprd = box[5] - box[2]
for i in xrange(n): for i in range(n):
for j in xrange(i+1,n): for j in range(i+1,n):
delx = x[j] - x[i] delx = x[j] - x[i]
if abs(delx) > 0.5*xprd: if abs(delx) > 0.5*xprd:
@ -65,11 +65,11 @@ while 1:
rsq = delx*delx + dely*dely + delz*delz rsq = delx*delx + dely*dely + delz*delz
if rsq < maxcut_sq: if rsq < maxcut_sq:
print "time = %d, id[i] = %d, id[j] = %d," \ print("time = %d, id[i] = %d, id[j] = %d," \
" type[i] = %d, type[j] = %d, distance = %g" % \ " type[i] = %d, type[j] = %d, distance = %g" % \
(time, id[i], id[j], type[i], type[j], sqrt(rsq)) (time, id[i], id[j], type[i], type[j], sqrt(rsq)))
d.tselect.none() d.tselect.none()
d.tselect.one(time) d.tselect.one(time)
print "timestep = ", time print("timestep = ", time)
d.delete() d.delete()

View File

@ -10,7 +10,7 @@
# main script # main script
if len(argv) < 2: if len(argv) < 2:
raise StandardError, "Syntax: dview.py dump.1 ..." raise Exception("Syntax: dview.py dump.1 ...")
files = ' '.join(argv[1:]) files = ' '.join(argv[1:])

View File

@ -13,18 +13,18 @@ import sys
from dump import dump from dump import dump
# w/out Pizza.py these lines need to come before import of gl tool # w/out Pizza.py these lines need to come before import of gl tool
import Tkinter import tkinter
tkroot = Tkinter.Tk() tkroot = tkinter.Tk()
tkroot.withdraw() tkroot.withdraw()
from gl import gl from gl import gl
from vcr import vcr from vcr import vcr
if not globals().has_key("argv"): argv = sys.argv if "argv" not in globals(): argv = sys.argv
# main script # main script
if len(argv) < 2: if len(argv) < 2:
raise StandardError, "Syntax: dview.py dump.1 ..." raise Exception("Syntax: dview.py dump.1 ...")
files = ' '.join(argv[1:]) files = ' '.join(argv[1:])

View File

@ -14,12 +14,12 @@
import sys import sys
from dump import dump from dump import dump
if not globals().has_key("argv"): argv = sys.argv if "argv" not in globals(): argv = sys.argv
# main script # main script
if len(argv) < 5: if len(argv) < 5:
raise StandardError, "Syntax: flux.py x/y/z plane outfile files ..." raise Exception("Syntax: flux.py x/y/z plane outfile files ...")
direction = argv[1] direction = argv[1]
scaled_plane = float(argv[2]) scaled_plane = float(argv[2])
@ -58,7 +58,7 @@ while 1:
prd = hi - lo prd = hi - lo
plane = lo + scaled_plane*prd plane = lo + scaled_plane*prd
print time, print(time, end=' ')
sys.stdout.flush() sys.stdout.flush()
natoms = len(x) natoms = len(x)
@ -67,7 +67,7 @@ while 1:
typeflux = ntypes * [0] typeflux = ntypes * [0]
for i in xrange(natoms): for i in range(natoms):
id[i] = int(id[i]) id[i] = int(id[i])
type[i] = int(type[i]) type[i] = int(type[i])
if jconfig == 1: x_initial[id[i]] = x[i] if jconfig == 1: x_initial[id[i]] = x[i]
@ -78,10 +78,10 @@ while 1:
crossings = int((plane - x[i])/prd) + 1 crossings = int((plane - x[i])/prd) + 1
typeflux[type[i]] -= crossings typeflux[type[i]] -= crossings
print >>f,time, print(time, end=' ', file=f)
for j in xrange(ntypes-1): for j in range(ntypes-1):
print >>f,typeflux[j+1], print(typeflux[j+1], end=' ', file=f)
print >>f print(file=f)
print print()
f.close() f.close()

View File

@ -11,10 +11,10 @@
import sys import sys
from animate import animate from animate import animate
if not globals().has_key("argv"): argv = sys.argv if "argv" not in globals(): argv = sys.argv
# main script # main script
# this could be done with one-line alias in shell start-up file # this could be done with one-line alias in shell start-up file
if len(argv) < 2: raise StandardError, "Syntax: iview.py files ..." if len(argv) < 2: raise Exception("Syntax: iview.py files ...")
a = animate(' '.join(argv[1:])) a = animate(' '.join(argv[1:]))

View File

@ -15,17 +15,17 @@ from log import log
from plotview import plotview from plotview import plotview
from gnu import gnu from gnu import gnu
from matlab import matlab from matlab import matlab
if not globals().has_key("argv"): argv = sys.argv if "argv" not in globals(): argv = sys.argv
# main script # main script
if len(argv) < 3: if len(argv) < 3:
raise StandardError, "Syntax: logview.py gnu/matlab files ..." raise Exception("Syntax: logview.py gnu/matlab files ...")
style = argv[1] style = argv[1]
files = ' '.join(argv[2:]) files = ' '.join(argv[2:])
lg = log(files) lg = log(files)
exec "plot = %s()" % style exec("plot = %s()" % style)
p = plotview(lg,plot) p = plotview(lg,plot)

View File

@ -4,7 +4,7 @@
# Purpose: create images from LAMMPS dump snapshots # Purpose: create images from LAMMPS dump snapshots
# Syntax: movie.py raster/svg theta phi dump.1 dump.2 ... # Syntax: movie.py raster/svg theta phi dump.1 dump.2 ...
# raster/svg = style of image to create # raster/svg = style of image to create
# theta/phi = vertical (z) and azimuthal angle to view from # theta/phi = vertical (z) and azimuthal angle to view from
# files = one or more dump files # files = one or more dump files
# Example: movie.py svg 60 130 dump.* # Example: movie.py svg 60 130 dump.*
# Author: Steve Plimpton (Sandia) # Author: Steve Plimpton (Sandia)
@ -15,12 +15,12 @@ import sys
from dump import dump from dump import dump
from raster import raster from raster import raster
from svg import svg from svg import svg
if not globals().has_key("argv"): argv = sys.argv if "argv" not in globals(): argv = sys.argv
# main script # main script
if len(argv) < 5: if len(argv) < 5:
raise StandardError, "Syntax: movie.py raster/svg theta phi dump.1 ..." raise Exception("Syntax: movie.py raster/svg theta phi dump.1 ...")
style = argv[1] style = argv[1]
theta = float(argv[2]) theta = float(argv[2])
@ -28,6 +28,6 @@ phi = float(argv[3])
files = ' '.join(argv[4:]) files = ' '.join(argv[4:])
d = dump(files) d = dump(files)
exec "viz = %s(d)" % style exec("viz = %s(d)" % style)
viz.rotate(theta,phi) viz.rotate(theta,phi)
viz.all() viz.all()

View File

@ -14,17 +14,17 @@ import sys
from plotview import plotview from plotview import plotview
from gnu import gnu from gnu import gnu
from matlab import matlab from matlab import matlab
if not globals().has_key("argv"): argv = sys.argv if "argv" not in globals(): argv = sys.argv
# main script # main script
if len(argv) != 3: if len(argv) != 3:
raise StandardError, "Syntax: plot.py gnu/matlab file" raise Exception("Syntax: plot.py gnu/matlab file")
style = argv[1] style = argv[1]
file = argv[2] file = argv[2]
v = vec(file) v = vec(file)
exec "plot = %s()" % style exec("plot = %s()" % style)
p = plotview(v,plot) p = plotview(v,plot)

View File

@ -8,23 +8,33 @@
# animate tool # animate tool
# Imports and external programs
from __future__ import print_function, absolute_import
import sys, os, re, glob
try:
from Tkinter import *
except ImportError:
from tkinter import *
oneline = "Animate a series of image files" oneline = "Animate a series of image files"
docstr = """ docstr = """
a = animate("image*.png") create GUI to animate set of image files 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): Actions (same as GUI widgets):
a.first() go to first frame a.first() go to first frame
a.prev() go to previous frame a.prev() go to previous frame
a.back() play backwards from current frame to start a.back() play backwards from current frame to start
a.stop() stop on current frame a.stop() stop on current frame
a.play() play from current frame to end a.play() play from current frame to end
a.next() go to next frame a.next() go to next frame
a.last() go to last frame a.last() go to last frame
a.frame(31) set frame slider a.frame(31) set frame slider
a.delay(0.4) set delay slider a.delay(0.4) set delay slider
""" """
# History # History
@ -45,11 +55,6 @@ a.delay(0.4) set delay slider
# delay_value = delay between frames (secs) # delay_value = delay between frames (secs)
# delay_msec = delay in millisec # delay_msec = delay in millisec
# Imports and external programs
import sys, os, commands, re, glob
from Tkinter import *
from ImageTk import PhotoImage
# Class definition # Class definition
@ -57,23 +62,24 @@ class animate:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def __init__(self,filestr): def __init__(self,filestr,sortflag=1):
self.loop_flag = 0 self.loop_flag = 0
self.delay_value = 0.0 self.delay_value = 0.0
self.delay_msec = 0 self.delay_msec = 0
# convert filestr into full list of files # convert filestr into full list of files
list = str.split(filestr) flist = str.split(filestr)
self.files = [] 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) 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 # load all images
self.images = [] self.images = []
for i in xrange(self.nframes): for i in range(self.nframes):
self.images.append(PhotoImage(file=self.files[i])) self.images.append(PhotoImage(file=self.files[i]))
# grab Tk instance from main # grab Tk instance from main

View File

@ -8,18 +8,25 @@
# bdump tool # bdump tool
# Imports and external programs
from __future__ import print_function, absolute_import
import sys, re, glob, types
import functools
from os import popen
oneline = "Read dump files with bond info" oneline = "Read dump files with bond info"
docstr = """ docstr = """
b = bdump("dump.one") read in one or more dump files b = bdump("dump.one") read in one or more dump files
b = bdump("dump.1 dump.2.gz") can be gzipped b = bdump("dump.1 dump.2.gz") can be gzipped
b = bdump("dump.*") wildcard expands to multiple files b = bdump("dump.*") wildcard expands to multiple files
b = bdump("dump.*",0) two args = store filenames, but don't read b = bdump("dump.*",0) two args = store filenames, but don't read
incomplete and duplicate snapshots are deleted incomplete and duplicate snapshots are deleted
no column name assignment is performed no column name assignment is performed
time = b.next() read next snapshot from dump files time = b.next() read next snapshot from dump files
used with 2-argument constructor to allow reading snapshots one-at-a-time used with 2-argument constructor to allow reading snapshots one-at-a-time
snapshot will be skipped only if another snapshot has same time stamp snapshot will be skipped only if another snapshot has same time stamp
@ -60,11 +67,6 @@ time,box,atoms,bonds,tris,lines = b.viz(index) return list of viz objects
# natoms = # of atoms # natoms = # of atoms
# atoms[i][j] = 2d array of floats, i = 0 to natoms-1, j = 0 to ncols-1 # 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: try:
import numpy as np import numpy as np
oldnumeric = False oldnumeric = False
@ -92,7 +94,7 @@ class bdump:
self.flist = [] self.flist = []
for word in words: self.flist += glob.glob(word) for word in words: self.flist += glob.glob(word)
if len(self.flist) == 0 and len(list) == 1: 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: if len(list) == 1:
self.increment = 0 self.increment = 0
@ -117,26 +119,26 @@ class bdump:
snap = self.read_snapshot(f) snap = self.read_snapshot(f)
while snap: while snap:
self.snaps.append(snap) self.snaps.append(snap)
print snap.time, print(snap.time, end=' ')
sys.stdout.flush() sys.stdout.flush()
snap = self.read_snapshot(f) snap = self.read_snapshot(f)
f.close() f.close()
print print()
# sort entries by timestep, cull duplicates # 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.cull()
self.nsnaps = len(self.snaps) self.nsnaps = len(self.snaps)
print "read %d snapshots" % self.nsnaps print("read %d snapshots" % self.nsnaps)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# read next snapshot from list of files # read next snapshot from list of files
def next(self): 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 # read next snapshot in current file using eof as pointer
# if fail, try next file # if fail, try next file
@ -148,15 +150,15 @@ class bdump:
snap = self.read_snapshot(f) snap = self.read_snapshot(f)
if not snap: if not snap:
self.nextfile += 1 self.nextfile += 1
if self.nextfile == len(self.flist): return -1 if self.nextfile == len(self.flist): return -1
f.close() f.close()
self.eof = 0 self.eof = 0
continue continue
self.eof = f.tell() self.eof = f.tell()
f.close() f.close()
try: try:
self.findtime(snap.time) self.findtime(snap.time)
continue continue
except: break except: break
self.snaps.append(snap) self.snaps.append(snap)
@ -183,14 +185,14 @@ class bdump:
if snap.natoms: if snap.natoms:
words = f.readline().split() words = f.readline().split()
ncol = len(words) ncol = len(words)
for i in xrange(1,snap.natoms): for i in range(1,snap.natoms):
words += f.readline().split() words += f.readline().split()
floats = map(float,words) floats = list(map(float,words))
if oldnumeric: atoms = np.zeros((snap.natoms,ncol),np.Float) if oldnumeric: atoms = np.zeros((snap.natoms,ncol),np.Float)
else: atoms = np.zeros((snap.natoms,ncol),np.float) else: atoms = np.zeros((snap.natoms,ncol),np.float)
start = 0 start = 0
stop = ncol stop = ncol
for i in xrange(snap.natoms): for i in range(snap.natoms):
atoms[i] = floats[start:stop] atoms[i] = floats[start:stop]
start = stop start = stop
stop += ncol stop += ncol
@ -205,7 +207,7 @@ class bdump:
def map(self,*pairs): def map(self,*pairs):
if len(pairs) % 2 != 0: 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): for i in range(0,len(pairs),2):
j = i + 1 j = i + 1
self.names[pairs[j]] = pairs[i]-1 self.names[pairs[j]] = pairs[i]-1
@ -269,7 +271,7 @@ class bdump:
# abs() of type since could be negative # abs() of type since could be negative
bonds = [] bonds = []
for i in xrange(snap.natoms): for i in range(snap.natoms):
atom = snap.atoms[i] atom = snap.atoms[i]
bonds.append([int(atom[id]),abs(int(atom[type])), bonds.append([int(atom[id]),abs(int(atom[type])),
int(atom[atom1]),int(atom[atom2])]) int(atom[atom1]),int(atom[atom2])])

File diff suppressed because it is too large Load Diff

View File

@ -8,10 +8,15 @@
# cfg tool # cfg tool
# Imports and external programs
from __future__ import print_function, absolute_import
import sys
oneline = "Convert LAMMPS snapshots to AtomEye CFG format" oneline = "Convert LAMMPS snapshots to AtomEye CFG format"
docstr = """ docstr = """
c = cfg(d) d = object containing atom coords (dump, data) c = cfg(d) d = object containing atom coords (dump, data)
c.one() write all snapshots to tmp.cfg c.one() write all snapshots to tmp.cfg
c.one("new") write all snapshots to new.cfg c.one("new") write all snapshots to new.cfg
@ -34,10 +39,6 @@ c.single(N,"file") write snapshot for timestep N to file.cfg
# Variables # Variables
# data = data file to read from # data = data file to read from
# Imports and external programs
import sys
# Class definition # Class definition
class cfg: class cfg:
@ -65,18 +66,18 @@ class cfg:
ylen = box[4]-box[1] ylen = box[4]-box[1]
zlen = box[5]-box[2] zlen = box[5]-box[2]
print >>f,"Number of particles = %d " % len(atoms) print("Number of particles = %d " % len(atoms), file=f)
print >>f,"# Timestep %d \n#\nA = 1.0 Angstrom" % time print("# Timestep %d \n#\nA = 1.0 Angstrom" % time, file=f)
print >>f,"H0(1,1) = %20.10f A " % xlen print("H0(1,1) = %20.10f A " % xlen, file=f)
print >>f,"H0(1,2) = 0.0 A " print("H0(1,2) = 0.0 A ", file=f)
print >>f,"H0(1,3) = 0.0 A " print("H0(1,3) = 0.0 A ", file=f)
print >>f,"H0(2,1) = 0.0 A " print("H0(2,1) = 0.0 A ", file=f)
print >>f,"H0(2,2) = %20.10f A " % ylen print("H0(2,2) = %20.10f A " % ylen, file=f)
print >>f,"H0(2,3) = 0.0 A " print("H0(2,3) = 0.0 A ", file=f)
print >>f,"H0(3,1) = 0.0 A " print("H0(3,1) = 0.0 A ", file=f)
print >>f,"H0(3,2) = 0.0 A " print("H0(3,2) = 0.0 A ", file=f)
print >>f,"H0(3,3) = %20.10f A " % zlen print("H0(3,3) = %20.10f A " % zlen, file=f)
print >>f,"#" print("#", file=f)
for atom in atoms: for atom in atoms:
itype = int(atom[1]) itype = int(atom[1])
@ -84,14 +85,14 @@ class cfg:
yfrac = (atom[3]-box[1])/ylen yfrac = (atom[3]-box[1])/ylen
zfrac = (atom[4]-box[2])/zlen 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 %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() sys.stdout.flush()
n += 1 n += 1
f.close() 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] ylen = box[4]-box[1]
zlen = box[5]-box[2] zlen = box[5]-box[2]
print >>f,"Number of particles = %d " % len(atoms) print("Number of particles = %d " % len(atoms), file=f)
print >>f,"# Timestep %d \n#\nA = 1.0 Angstrom" % time print("# Timestep %d \n#\nA = 1.0 Angstrom" % time, file=f)
print >>f,"H0(1,1) = %20.10f A " % xlen print("H0(1,1) = %20.10f A " % xlen, file=f)
print >>f,"H0(1,2) = 0.0 A " print("H0(1,2) = 0.0 A ", file=f)
print >>f,"H0(1,3) = 0.0 A " print("H0(1,3) = 0.0 A ", file=f)
print >>f,"H0(2,1) = 0.0 A " print("H0(2,1) = 0.0 A ", file=f)
print >>f,"H0(2,2) = %20.10f A " % ylen print("H0(2,2) = %20.10f A " % ylen, file=f)
print >>f,"H0(2,3) = 0.0 A " print("H0(2,3) = 0.0 A ", file=f)
print >>f,"H0(3,1) = 0.0 A " print("H0(3,1) = 0.0 A ", file=f)
print >>f,"H0(3,2) = 0.0 A " print("H0(3,2) = 0.0 A ", file=f)
print >>f,"H0(3,3) = %20.10f A " % zlen print("H0(3,3) = %20.10f A " % zlen, file=f)
print >>f,"#" print("#", file=f)
for atom in atoms: for atom in atoms:
itype = int(atom[1]) itype = int(atom[1])
@ -139,14 +140,14 @@ class cfg:
yfrac = (atom[3]-box[1])/ylen yfrac = (atom[3]-box[1])/ylen
zfrac = (atom[4]-box[2])/zlen 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 %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() sys.stdout.flush()
f.close() f.close()
n += 1 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] ylen = box[4]-box[1]
zlen = box[5]-box[2] zlen = box[5]-box[2]
print >>f,"Number of particles = %d " % len(atoms) print("Number of particles = %d " % len(atoms), file=f)
print >>f,"# Timestep %d \n#\nA = 1.0 Angstrom" % time print("# Timestep %d \n#\nA = 1.0 Angstrom" % time, file=f)
print >>f,"H0(1,1) = %20.10f A " % xlen print("H0(1,1) = %20.10f A " % xlen, file=f)
print >>f,"H0(1,2) = 0.0 A " print("H0(1,2) = 0.0 A ", file=f)
print >>f,"H0(1,3) = 0.0 A " print("H0(1,3) = 0.0 A ", file=f)
print >>f,"H0(2,1) = 0.0 A " print("H0(2,1) = 0.0 A ", file=f)
print >>f,"H0(2,2) = %20.10f A " % ylen print("H0(2,2) = %20.10f A " % ylen, file=f)
print >>f,"H0(2,3) = 0.0 A " print("H0(2,3) = 0.0 A ", file=f)
print >>f,"H0(3,1) = 0.0 A " print("H0(3,1) = 0.0 A ", file=f)
print >>f,"H0(3,2) = 0.0 A " print("H0(3,2) = 0.0 A ", file=f)
print >>f,"H0(3,3) = %20.10f A " % zlen print("H0(3,3) = %20.10f A " % zlen, file=f)
print >>f,"#" print("#", file=f)
for atom in atoms: for atom in atoms:
itype = int(atom[1]) itype = int(atom[1])
@ -182,6 +183,6 @@ class cfg:
yfrac = (atom[3]-box[1])/ylen yfrac = (atom[3]-box[1])/ylen
zfrac = (atom[4]-box[2])/zlen 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 %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() f.close()

View File

@ -8,15 +8,21 @@
# chain tool # 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" oneline = "Create bead-spring chains for LAMMPS input"
docstr = """ docstr = """
c = chain(N,rho) setup box with N monomers at reduced density rho c = chain(N,rho) setup box with N monomers at reduced density rho
c = chain(N,rho,1,1,2) x,y,z = aspect ratio of box (def = 1,1,1) c = chain(N,rho,1,1,2) x,y,z = aspect ratio of box (def = 1,1,1)
c.seed = 48379 set random # seed (def = 12345) c.seed = 48379 set random # seed (def = 12345)
c.mtype = 2 set type of monomers (def = 1) c.mtype = 2 set type of monomers (def = 1)
c.btype = 1 set type of bonds (def = 1) c.btype = 1 set type of bonds (def = 1)
c.blen = 0.97 set length of bonds (def = 0.97) c.blen = 0.97 set length of bonds (def = 0.97)
c.dmin = 1.02 set min dist from i-1 to i+1 site (def = 1.02) c.dmin = 1.02 set min dist from i-1 to i+1 site (def = 1.02)
@ -24,7 +30,7 @@ c.id = "chain" set molecule ID to chain # (default)
c.id = "end1" set molecule ID to count from one end of chain c.id = "end1" set molecule ID to count from one end of chain
c.id = "end2" set molecule ID to count from either end of chain c.id = "end2" set molecule ID to count from either end of chain
c.build(100,10) create 100 chains, each of length 10 c.build(100,10) create 100 chains, each of length 10
can be invoked multiple times interleaved with different settings can be invoked multiple times interleaved with different settings
must fill box with total of N monomers must fill box with total of N monomers
@ -52,11 +58,6 @@ c.write("data.file") write out all built chains to LAMMPS data file
# xlo,ylo,zlo = -xyz prd / 2 # xlo,ylo,zlo = -xyz prd / 2
# xhi,yhi,zhi = x,y,zprd /2 # xhi,yhi,zhi = x,y,zprd /2
# Imports and external programs
import math
from data import data
# Class definition # Class definition
class chain: class chain:
@ -92,12 +93,12 @@ class chain:
self.zlo = -self.zprd/2.0 self.zlo = -self.zprd/2.0
self.zhi = 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): def build(self,n,nper):
for ichain in xrange(n): for ichain in range(n):
atoms = [] atoms = []
bonds = [] bonds = []
id_atom_prev = id_mol_prev = id_bond_prev = 0 id_atom_prev = id_mol_prev = id_bond_prev = 0
@ -107,12 +108,12 @@ class chain:
if len(self.bonds): if len(self.bonds):
id_bond_prev = self.bonds[-1][0] id_bond_prev = self.bonds[-1][0]
for imonomer in xrange(nper): for imonomer in range(nper):
if imonomer == 0: if imonomer == 0:
x = self.xlo + self.random()*self.xprd x = self.xlo + self.random()*self.xprd
y = self.ylo + self.random()*self.yprd y = self.ylo + self.random()*self.yprd
z = self.zlo + self.random()*self.zprd z = self.zlo + self.random()*self.zprd
ix = iy = iz = 0 ix = iy = iz = 0
else: else:
restriction = True restriction = True
while restriction: while restriction:
@ -143,14 +144,14 @@ class chain:
idmol = imonomer + 1 idmol = imonomer + 1
elif self.id == "end2": elif self.id == "end2":
idmol = imonomer + 1 idmol = imonomer + 1
if idmol > nper/2: if idmol > nper//2:
idmol = nper - imonomer idmol = nper - imonomer
else: 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]) atoms.append([idatom,idmol,self.mtype,x,y,z,ix,iy,iz])
if imonomer: if imonomer:
bondid = id_bond_prev + imonomer bondid = id_bond_prev + imonomer
bonds.append([bondid,self.btype,idatom-1,idatom]) bonds.append([bondid,self.btype,idatom-1,idatom])
self.atoms += atoms self.atoms += atoms
@ -160,16 +161,16 @@ class chain:
def write(self,file): def write(self,file):
if len(self.atoms) != self.n: if len(self.atoms) != self.n:
raise StandardError,"%d monomers instead of requested %d" % \ raise Exception("%d monomers instead of requested %d" % \
(len(self.atoms),self.n) (len(self.atoms),self.n))
list = [atom[2] for atom in self.atoms] atlist = [atom[2] for atom in self.atoms]
atypes = max(list) atypes = max(atlist)
btypes = 0 btypes = 0
if len(self.bonds): if len(self.bonds):
list = [bond[1] for bond in self.bonds] btlist = [bond[1] for bond in self.bonds]
btypes = max(list) btypes = max(btlist)
# create the data file # create the data file
@ -229,7 +230,7 @@ class chain:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def random(self): def random(self):
k = self.seed/IQ k = self.seed//IQ
self.seed = IA*(self.seed-k*IQ) - IR*k self.seed = IA*(self.seed-k*IQ) - IR*k
if self.seed < 0: if self.seed < 0:
self.seed += IM self.seed += IM

View File

@ -8,6 +8,12 @@
# clog tool # clog tool
# Imports and external programs
from __future__ import print_function, absolute_import
import sys, re, glob
from os import popen
oneline = "Read ChemCell and SPPARKS log files and extract time-series data" oneline = "Read ChemCell and SPPARKS log files and extract time-series data"
docstr = """ docstr = """
@ -26,7 +32,7 @@ nvec = c.nvec # of vectors of thermo info
nlen = c.nlen length of each vectors nlen = c.nlen length of each vectors
names = c.names list of vector names names = c.names list of vector names
a,b,... = c.get("A","B",...) return one or more vectors of values a,b,... = c.get("A","B",...) return one or more vectors of values
c.write("file.txt") write all vectors to a file c.write("file.txt") write all vectors to a file
c.write("file.txt","A","B",...) write listed vectors to a file c.write("file.txt","A","B",...) write listed vectors to a file
get and write allow abbreviated (uniquely) vector names get and write allow abbreviated (uniquely) vector names
@ -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 # 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 # 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 try: tmp = PIZZA_GUNZIP
except: PIZZA_GUNZIP = "gunzip" except: PIZZA_GUNZIP = "gunzip"
@ -74,7 +75,7 @@ class clog:
self.flist = [] self.flist = []
for word in words: self.flist += glob.glob(word) for word in words: self.flist += glob.glob(word)
if len(self.flist) == 0 and len(list) == 1: 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) > 1 and len(list[1]): self.firststr = list[1]
if len(list) == 3: self.ave = 1 if len(list) == 3: self.ave = 1
@ -86,12 +87,12 @@ class clog:
def read_all(self): def read_all(self):
self.read_header(self.flist[0]) 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 # read all files
for file in self.flist: self.read_one(file) for file in self.flist: self.read_one(file)
print print()
# if no average, sort entries by timestep, cull duplicates # if no average, sort entries by timestep, cull duplicates
# if average, call self.average() # if average, call self.average()
@ -102,33 +103,33 @@ class clog:
else: self.average() else: self.average()
self.nlen = len(self.data) self.nlen = len(self.data)
print "read %d log entries" % self.nlen print("read %d log entries" % self.nlen)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def get(self,*keys): def get(self,*keys):
if len(keys) == 0: if len(keys) == 0:
raise StandardError, "no log vectors specified" raise Exception("no log vectors specified")
map = [] map = []
for key in keys: for key in keys:
if self.ptr.has_key(key): if key in self.ptr:
map.append(self.ptr[key]) map.append(self.ptr[key])
else: else:
count = 0 count = 0
for i in range(self.nvec): for i in range(self.nvec):
if self.names[i].find(key) == 0: if self.names[i].find(key) == 0:
count += 1 count += 1
index = i index = i
if count == 1: if count == 1:
map.append(index) map.append(index)
else: else:
raise StandardError, "unique log vector %s not found" % key raise Exception("unique log vector %s not found" % key)
vecs = [] vecs = []
for i in range(len(keys)): for i in range(len(keys)):
vecs.append(self.nlen * [0]) 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]] vecs[i][j] = self.data[j][map[i]]
if len(keys) == 1: return vecs[0] if len(keys) == 1: return vecs[0]
@ -140,26 +141,26 @@ class clog:
if len(keys): if len(keys):
map = [] map = []
for key in keys: for key in keys:
if self.ptr.has_key(key): if key in self.ptr:
map.append(self.ptr[key]) map.append(self.ptr[key])
else: else:
count = 0 count = 0
for i in range(self.nvec): for i in range(self.nvec):
if self.names[i].find(key) == 0: if self.names[i].find(key) == 0:
count += 1 count += 1
index = i index = i
if count == 1: if count == 1:
map.append(index) map.append(index)
else: else:
raise StandardError, "unique log vector %s not found" % key raise Exception("unique log vector %s not found" % key)
else: else:
map = range(self.nvec) map = list(range(self.nvec))
f = open(filename,"w") f = open(filename,"w")
for i in xrange(self.nlen): for i in range(self.nlen):
for j in xrange(len(map)): for j in range(len(map)):
print >>f,self.data[i][map[j]], print(self.data[i][map[j]], end=' ', file=f)
print >>f print(file=f)
f.close() f.close()
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -195,12 +196,12 @@ class clog:
data.append(self.nvec*[0]) data.append(self.nvec*[0])
nlen += 1 nlen += 1
counts[j] += 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 j += 1
i += 1 i += 1
for i in xrange(nlen): for i in range(nlen):
for j in xrange(self.nvec): for j in range(self.nvec):
data[i][j] /= counts[j] data[i][j] /= counts[j]
self.nlen = nlen self.nlen = nlen
@ -261,26 +262,26 @@ class clog:
elif s1 >= 0 and s2 >= 0 and s2 < s1: # found s1,s2 with s2 before s1 elif s1 >= 0 and s2 >= 0 and s2 < s1: # found s1,s2 with s2 before s1
s1 = 0 s1 = 0
elif s1 == -1 and s2 >= 0: # found s2, but no s1 elif s1 == -1 and s2 >= 0: # found s2, but no s1
last = 1 last = 1
s1 = 0 s1 = 0
elif s1 >= 0 and s2 == -1: # found s1, but no s2 elif s1 >= 0 and s2 == -1: # found s1, but no s2
last = 1 last = 1
s1 = txt.find("\n",s1) + 1 s1 = txt.find("\n",s1) + 1
s2 = txt.rfind("\n",s1) + 1 s2 = txt.rfind("\n",s1) + 1
eof -= len(txt) - s2 eof -= len(txt) - s2
elif s1 == -1 and s2 == -1: # found neither elif s1 == -1 and s2 == -1: # found neither
# could be end-of-file section # could be end-of-file section
# or entire read was one chunk # or entire read was one chunk
if txt.find("Loop time of",start) == start: # end of file, so exit if txt.find("Loop time of",start) == start: # end of file, so exit
eof -= len(txt) - start # reset eof to "Loop" eof -= len(txt) - start # reset eof to "Loop"
break break
last = 1 # entire read is a chunk last = 1 # entire read is a chunk
s1 = 0 s1 = 0
s2 = txt.rfind("\n",s1) + 1 s2 = txt.rfind("\n",s1) + 1
eof -= len(txt) - s2 eof -= len(txt) - s2
if s1 == s2: break if s1 == s2: break
chunk = txt[s1:s2-1] chunk = txt[s1:s2-1]
start = s2 start = s2
@ -291,11 +292,11 @@ class clog:
lines = chunk.split("\n") lines = chunk.split("\n")
for line in lines: for line in lines:
words = line.split() words = line.split()
self.data.append(map(float,words)) self.data.append(list(map(float,words)))
# print last timestep of chunk # 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() sys.stdout.flush()
return eof return eof

View File

@ -8,11 +8,16 @@
# data tool # data tool
# Imports and external programs
from __future__ import print_function, absolute_import
from os import popen
oneline = "Read, write, manipulate LAMMPS data files" oneline = "Read, write, manipulate LAMMPS data files"
docstr = """ docstr = """
d = data("data.poly") read a LAMMPS data file, can be gzipped d = data("data.poly") read a LAMMPS data file, can be gzipped
d = data() create an empty data file d = data() create an empty data file
d.map(1,"id",3,"x") assign names to atom columns (1-N) d.map(1,"id",3,"x") assign names to atom columns (1-N)
@ -26,13 +31,13 @@ d.reorder("Atoms",1,3,2,4,5) reorder columns (1-N) in a data file section
1,3,2,4,5 = new order of previous columns, can delete columns this way 1,3,2,4,5 = new order of previous columns, can delete columns this way
d.title = "My LAMMPS data file" set title of the data file d.title = "My LAMMPS data file" set title of the data file
d.headers["atoms"] = 1500 set a header value d.headers["atoms"] = 1500 set a header value
d.sections["Bonds"] = lines set a section to list of lines (with newlines) d.sections["Bonds"] = lines set a section to list of lines (with newlines)
d.delete("bonds") delete a keyword or section of data file d.delete("bonds") delete a keyword or section of data file
d.delete("Bonds") d.delete("Bonds")
d.replace("Atoms",5,vec) replace Nth column of section with vector d.replace("Atoms",5,vec) replace Nth column of section with vector
d.newxyz(dmp,1000) replace xyz in Atoms with xyz of snapshot N d.newxyz(dmp,1000) replace xyz in Atoms with xyz of snapshot N
newxyz assumes id,x,y,z are defined in both data and dump files newxyz assumes id,x,y,z are defined in both data and dump files
also replaces ix,iy,iz if they are defined also replaces ix,iy,iz if they are defined
@ -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 # sections = dictionary with section name as key, array of lines as values
# nselect = 1 = # of snapshots # nselect = 1 = # of snapshots
# Imports and external programs
from os import popen
try: tmp = PIZZA_GUNZIP try: tmp = PIZZA_GUNZIP
except: PIZZA_GUNZIP = "gunzip" except: PIZZA_GUNZIP = "gunzip"
@ -109,16 +110,16 @@ class data:
found = 0 found = 0
for keyword in hkeywords: for keyword in hkeywords:
if line.find(keyword) >= 0: if line.find(keyword) >= 0:
found = 1 found = 1
words = line.split() words = line.split()
if keyword == "xlo xhi" or keyword == "ylo yhi" or \ if keyword == "xlo xhi" or keyword == "ylo yhi" or \
keyword == "zlo zhi": keyword == "zlo zhi":
headers[keyword] = (float(words[0]),float(words[1])) headers[keyword] = (float(words[0]),float(words[1]))
elif keyword == "xy xz yz": elif keyword == "xy xz yz":
headers[keyword] = \ headers[keyword] = \
(float(words[0]),float(words[1]),float(words[2])) (float(words[0]),float(words[1]),float(words[2]))
else: else:
headers[keyword] = int(words[0]) headers[keyword] = int(words[0])
if not found: if not found:
break break
@ -128,16 +129,15 @@ class data:
for pair in skeywords: for pair in skeywords:
keyword,length = pair[0],pair[1] keyword,length = pair[0],pair[1]
if keyword == line: if keyword == line:
found = 1 found = 1
if not headers.has_key(length): if length not in headers:
raise StandardError, \ raise Exception("data section %s has no matching header value" % line)
"data section %s has no matching header value" % line f.readline()
f.readline()
list = [] list = []
for i in xrange(headers[length]): list.append(f.readline()) for i in range(headers[length]): list.append(f.readline())
sections[keyword] = list sections[keyword] = list
if not found: if not found:
raise StandardError,"invalid section %s in data file" % line raise Exception("invalid section %s in data file" % line)
f.readline() f.readline()
line = f.readline() line = f.readline()
if not line: if not line:
@ -153,7 +153,7 @@ class data:
def map(self,*pairs): def map(self,*pairs):
if len(pairs) % 2 != 0: 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): for i in range(0,len(pairs),2):
j = i + 1 j = i + 1
self.names[pairs[j]] = pairs[i]-1 self.names[pairs[j]] = pairs[i]-1
@ -161,19 +161,19 @@ class data:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# extract info from data file fields # extract info from data file fields
def get(self,*list): def get(self,*flist):
if len(list) == 1: if len(flist) == 1:
field = list[0] field = flist[0]
array = [] array = []
lines = self.sections[field] lines = self.sections[field]
for line in lines: for line in lines:
words = line.split() words = line.split()
values = map(float,words) values = list(map(float,words))
array.append(values) array.append(values)
return array return array
elif len(list) == 2: elif len(flist) == 2:
field = list[0] field = flist[0]
n = list[1] - 1 n = flist[1] - 1
vec = [] vec = []
lines = self.sections[field] lines = self.sections[field]
for line in lines: for line in lines:
@ -181,7 +181,7 @@ class data:
vec.append(float(words[n])) vec.append(float(words[n]))
return vec return vec
else: else:
raise StandardError, "invalid arguments for data.get()" raise Exception("invalid arguments for data.get()")
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# reorder columns in a data file field # reorder columns in a data file field
@ -192,10 +192,10 @@ class data:
oldlines = self.sections[name] oldlines = self.sections[name]
newlines = natoms*[""] newlines = natoms*[""]
for index in order: for index in order:
for i in xrange(len(newlines)): for i in range(len(newlines)):
words = oldlines[i].split() words = oldlines[i].split()
newlines[i] += words[index-1] + " " newlines[i] += words[index-1] + " "
for i in xrange(len(newlines)): for i in range(len(newlines)):
newlines[i] += "\n" newlines[i] += "\n"
self.sections[name] = newlines self.sections[name] = newlines
@ -206,7 +206,7 @@ class data:
lines = self.sections[name] lines = self.sections[name]
newlines = [] newlines = []
j = icol - 1 j = icol - 1
for i in xrange(len(lines)): for i in range(len(lines)):
line = lines[i] line = lines[i]
words = line.split() words = line.split()
words[j] = str(vector[i]) words[j] = str(vector[i])
@ -222,19 +222,15 @@ class data:
def newxyz(self,dm,ntime): def newxyz(self,dm,ntime):
nsnap = dm.findtime(ntime) nsnap = dm.findtime(ntime)
if dm.scaled(nsnap): scaleflag = 1
else: scaleflag = 0
dm.sort(ntime) dm.sort(ntime)
if scaleflag: dm.unscale(ntime)
x,y,z = dm.vecs(ntime,"x","y","z") 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['x']+1,x)
self.replace("Atoms",self.names['y']+1,y) self.replace("Atoms",self.names['y']+1,y)
self.replace("Atoms",self.names['z']+1,z) 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") ix,iy,iz = dm.vecs(ntime,"ix","iy","iz")
self.replace("Atoms",self.names['ix']+1,ix) self.replace("Atoms",self.names['ix']+1,ix)
self.replace("Atoms",self.names['iy']+1,iy) self.replace("Atoms",self.names['iy']+1,iy)
@ -245,33 +241,33 @@ class data:
def delete(self,keyword): def delete(self,keyword):
if self.headers.has_key(keyword): del self.headers[keyword] if keyword in self.headers: del self.headers[keyword]
elif self.sections.has_key(keyword): del self.sections[keyword] elif keyword in self.sections: del self.sections[keyword]
else: raise StandardError, "keyword not found in data object" else: raise Exception("keyword not found in data object")
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# write out a LAMMPS data file # write out a LAMMPS data file
def write(self,file): def write(self,file):
f = open(file,"w") f = open(file,"w")
print >>f,self.title print(self.title, file=f)
for keyword in hkeywords: for keyword in hkeywords:
if self.headers.has_key(keyword): if keyword in self.headers:
if keyword == "xlo xhi" or keyword == "ylo yhi" or \ if keyword == "xlo xhi" or keyword == "ylo yhi" or \
keyword == "zlo zhi": keyword == "zlo zhi":
pair = self.headers[keyword] pair = self.headers[keyword]
print >>f,pair[0],pair[1],keyword print(pair[0],pair[1],keyword, file=f)
elif keyword == "xy xz yz": elif keyword == "xy xz yz":
triple = self.headers[keyword] triple = self.headers[keyword]
print >>f,triple[0],triple[1],triple[2],keyword print(triple[0],triple[1],triple[2],keyword, file=f)
else: else:
print >>f,self.headers[keyword],keyword print(self.headers[keyword],keyword, file=f)
for pair in skeywords: for pair in skeywords:
keyword = pair[0] keyword = pair[0]
if self.sections.has_key(keyword): if keyword in self.sections:
print >>f,"\n%s\n" % keyword print("\n%s\n" % keyword, file=f)
for line in self.sections[keyword]: for line in self.sections[keyword]:
print >>f,line, print(line, end=' ', file=f)
f.close() f.close()
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -286,13 +282,13 @@ class data:
def findtime(self,n): def findtime(self,n):
if n == 0: return 0 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 # return list of atoms and bonds to viz for data object
def viz(self,isnap): 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"] id = self.names["id"]
type = self.names["type"] type = self.names["type"]
@ -318,7 +314,7 @@ class data:
# assumes atoms are sorted so can lookup up the 2 atoms in each bond # assumes atoms are sorted so can lookup up the 2 atoms in each bond
bonds = [] bonds = []
if self.sections.has_key("Bonds"): if "Bonds" in self.sections:
bondlines = self.sections["Bonds"] bondlines = self.sections["Bonds"]
for line in bondlines: for line in bondlines:
words = line.split() words = line.split()
@ -331,7 +327,7 @@ class data:
float(atom1words[z]), float(atom1words[z]),
float(atom2words[x]),float(atom2words[y]), float(atom2words[x]),float(atom2words[y]),
float(atom2words[z]), float(atom2words[z]),
float(atom1words[type]),float(atom2words[type])]) float(atom1words[type]),float(atom2words[type])])
tris = [] tris = []
lines = [] lines = []
@ -357,18 +353,18 @@ class data:
hkeywords = ["atoms","lines","tris", hkeywords = ["atoms","lines","tris",
"bonds","angles","dihedrals","impropers", "bonds","angles","dihedrals","impropers",
"atom types","bond types","angle types","dihedral types", "atom types","bond types","angle types","dihedral types",
"improper types","xlo xhi","ylo yhi","zlo zhi","xy xz yz"] "improper types","xlo xhi","ylo yhi","zlo zhi","xy xz yz"]
skeywords = [["Masses","atom types"], skeywords = [["Masses","atom types"],
["Atoms","atoms"],["Lines","lines"],["Triangles","tris"], ["Atoms","atoms"],["Lines","lines"],["Triangles","tris"],
["Bonds","bonds"], ["Bonds","bonds"],
["Angles","angles"],["Dihedrals","dihedrals"], ["Angles","angles"],["Dihedrals","dihedrals"],
["Impropers","impropers"],["Velocities","atoms"], ["Impropers","impropers"],["Velocities","atoms"],
["Pair Coeffs","atom types"], ["Pair Coeffs","atom types"],
["Bond Coeffs","bond types"],["Angle Coeffs","angle types"], ["Bond Coeffs","bond types"],["Angle Coeffs","angle types"],
["Dihedral Coeffs","dihedral types"], ["Dihedral Coeffs","dihedral types"],
["Improper Coeffs","improper types"], ["Improper Coeffs","improper types"],
["BondBond Coeffs","angle types"], ["BondBond Coeffs","angle types"],
["BondAngle Coeffs","angle types"], ["BondAngle Coeffs","angle types"],
["MiddleBondTorsion Coeffs","dihedral types"], ["MiddleBondTorsion Coeffs","dihedral types"],

View File

@ -8,19 +8,28 @@
# dump tool # dump tool
# Imports and external programs
from __future__ import print_function, absolute_import
import sys, 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" oneline = "Read, write, manipulate dump files and particle attributes"
docstr = """ docstr = """
d = dump("dump.one") read in one or more dump files d = dump("dump.one") read in one or more dump files
d = dump("dump.1 dump.2.gz") can be gzipped d = dump("dump.1 dump.2.gz") can be gzipped
d = dump("dump.*") wildcard expands to multiple files d = dump("dump.*") wildcard expands to multiple files
d = dump("dump.*",0) two args = store filenames, but don't read d = dump("dump.*",0) two args = store filenames, but don't read
incomplete and duplicate snapshots are deleted incomplete and duplicate snapshots are deleted
if atoms have 5 or 8 columns, assign id,type,x,y,z (ix,iy,iz) if atoms have 5 or 8 columns, assign id,type,x,y,z (ix,iy,iz)
atoms will be unscaled if stored in files as scaled atoms will be unscaled if stored in files as scaled
time = d.next() read next snapshot from dump files time = d.next() read next snapshot from dump files
used with 2-argument constructor to allow reading snapshots one-at-a-time used with 2-argument constructor to allow reading snapshots one-at-a-time
snapshot will be skipped only if another snapshot has same time stamp snapshot will be skipped only if another snapshot has same time stamp
@ -32,20 +41,20 @@ d.map(1,"id",3,"x") assign names to atom columns (1-N)
not needed if dump file is self-describing not needed if dump file is self-describing
d.tselect.all() select all timesteps d.tselect.all() select all timesteps
d.tselect.one(N) select only timestep N d.tselect.one(N) select only timestep N
d.tselect.none() deselect all timesteps d.tselect.none() deselect all timesteps
d.tselect.skip(M) select every Mth step d.tselect.skip(M) select every Mth step
d.tselect.test("$t >= 100 and $t < 10000") select matching timesteps d.tselect.test("$t >= 100 and $t < 10000") select matching timesteps
d.delete() delete non-selected timesteps d.delete() delete non-selected timesteps
selecting a timestep also selects all atoms in the timestep selecting a timestep also selects all atoms in the timestep
skip() and test() only select from currently selected timesteps skip() and test() only select from currently selected timesteps
test() uses a Python Boolean expression with $t for timestep value test() uses a Python Boolean expression with $t for timestep value
Python comparison syntax: == != < > <= >= and or Python comparison syntax: == != < > <= >= and or
d.aselect.all() select all atoms in all steps d.aselect.all() select all atoms in all steps
d.aselect.all(N) select all atoms in one step d.aselect.all(N) select all atoms in one step
d.aselect.test("$id > 100 and $type == 2") select match atoms in all steps d.aselect.test("$id > 100 and $type == 2") select match atoms in all steps
d.aselect.test("$id > 100 and $type == 2",N) select matching atoms in one step d.aselect.test("$id > 100 and $type == 2",N) select matching atoms in one step
@ -56,24 +65,24 @@ d.aselect.test("$id > 100 and $type == 2",N) select matching atoms in one step
Python comparison syntax: == != < > <= >= and or Python comparison syntax: == != < > <= >= and or
$name must end with a space $name must end with a space
d.write("file") write selected steps/atoms to dump file d.write("file") write selected steps/atoms to dump file
d.write("file",head,app) write selected steps/atoms to dump file d.write("file",head,app) write selected steps/atoms to dump file
d.scatter("tmp") write selected steps/atoms to multiple files d.scatter("tmp") write selected steps/atoms to multiple files
write() can be specified with 2 additional flags write() can be specified with 2 additional flags
headd = 0/1 for no/yes snapshot header, app = 0/1 for write vs append head = 0/1 for no/yes snapshot header, app = 0/1 for write vs append
scatter() files are given timestep suffix: e.g. tmp.0, tmp.100, etc scatter() files are given timestep suffix: e.g. tmp.0, tmp.100, etc
d.scale() scale x,y,z to 0-1 for all timesteps d.scale() scale x,y,z to 0-1 for all timesteps
d.scale(100) scale atom coords for timestep N d.scale(100) scale atom coords for timestep N
d.unscale() unscale x,y,z to box size to all timesteps d.unscale() unscale x,y,z to box size to all timesteps
d.unscale(1000) unscale atom coords for timestep N d.unscale(1000) unscale atom coords for timestep N
d.wrap() wrap x,y,z into periodic box via ix,iy,iz d.wrap() wrap x,y,z into periodic box via ix,iy,iz
d.unwrap() unwrap x,y,z out of box via ix,iy,iz d.unwrap() unwrap x,y,z out of box via ix,iy,iz
d.owrap("other") wrap x,y,z to same image as another atom d.owrap("other") wrap x,y,z to same image as another atom
d.sort() sort atoms by atom ID in all selected steps d.sort() sort atoms by atom ID in all selected steps
d.sort("x") sort atoms by column value in all steps d.sort("x") sort atoms by column value in all steps
d.sort(1000) sort atoms in timestep N d.sort(1000) sort atoms in timestep N
scale(), unscale(), wrap(), unwrap(), owrap() operate on all steps and atoms scale(), unscale(), wrap(), unwrap(), owrap() operate on all steps and atoms
wrap(), unwrap(), owrap() require ix,iy,iz be defined wrap(), unwrap(), owrap() require ix,iy,iz be defined
@ -85,8 +94,8 @@ d.sort(1000) sort atoms in timestep N
m1,m2 = d.minmax("type") find min/max values for a column m1,m2 = d.minmax("type") find min/max values for a column
d.set("$ke = $vx * $vx + $vy * $vy") set a column to a computed value d.set("$ke = $vx * $vx + $vy * $vy") set a column to a computed value
d.setv("type",vector) set a column to a vector of values d.setv("type",vector) set a column to a vector of values
d.spread("ke",N,"color") 2nd col = N ints spread over 1st col d.spread("ke",N,"color") 2nd col = N ints spread over 1st col
d.clone(1000,"color") clone timestep N values to other steps d.clone(1000,"color") clone timestep N values to other steps
minmax() operates on selected timesteps and atoms minmax() operates on selected timesteps and atoms
set() operates on selected timesteps and atoms set() operates on selected timesteps and atoms
@ -107,7 +116,7 @@ d.clone(1000,"color") clone timestep N values to other steps
values at every timestep are set to value at timestep N for that atom ID values at every timestep are set to value at timestep N for that atom ID
useful for propagating a color map useful for propagating a color map
t = d.time() return vector of selected timestep values t = d.time() return vector of selected timestep values
fx,fy,... = d.atom(100,"fx","fy",...) return vector(s) for atom ID N fx,fy,... = d.atom(100,"fx","fy",...) return vector(s) for atom ID N
fx,fy,... = d.vecs(1000,"fx","fy",...) return vector(s) for timestep N fx,fy,... = d.vecs(1000,"fx","fy",...) return vector(s) for timestep N
@ -117,7 +126,7 @@ fx,fy,... = d.vecs(1000,"fx","fy",...) return vector(s) for timestep N
index,time,flag = d.iterator(0/1) loop over dump snapshots index,time,flag = d.iterator(0/1) loop over dump snapshots
time,box,atoms,bonds,tris,lines = d.viz(index) return list of viz objects time,box,atoms,bonds,tris,lines = d.viz(index) return list of viz objects
d.atype = "color" set column returned as "type" by viz d.atype = "color" set column returned as "type" by viz
d.extra(obj) extract bond/tri/line info from obj d.extra(obj) extract bond/tri/line info from obj
iterator() loops over selected timesteps iterator() loops over selected timesteps
iterator() called with arg = 0 first time, with arg = 1 on subsequent calls iterator() called with arg = 0 first time, with arg = 1 on subsequent calls
@ -180,19 +189,12 @@ d.extra(obj) extract bond/tri/line info from obj
# xlo,xhi,ylo,yhi,zlo,zhi = box bounds (float) # 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 # 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: try:
import numpy as np import numpy as np
oldnumeric = False oldnumeric = False
except: except:
import Numeric as np import Numeric as np
oldnumeric = True oldnumeric = True
try: from DEFAULTS import PIZZA_GUNZIP try: from DEFAULTS import PIZZA_GUNZIP
except: PIZZA_GUNZIP = "gunzip" except: PIZZA_GUNZIP = "gunzip"
@ -228,7 +230,7 @@ class dump:
# check whether to output or not # check whether to output or not
if "debugMode" in dictionary: outputfl = dictionary["debugMode"] 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.flist = dictionary["filelist"]
self.multiprocflag = 1 self.multiprocflag = 1
@ -240,7 +242,7 @@ class dump:
self.flist = [] self.flist = []
for word in words: self.flist += glob.glob(word) for word in words: self.flist += glob.glob(word)
if len(self.flist) == 0 and len(input) == 1: 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: if len(input) == 1:
self.increment = 0 self.increment = 0
@ -261,31 +263,32 @@ class dump:
outputfl = True outputfl = True
if "output" in kwargs: outputfl = kwargs["output"] 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): for i, file in enumerate(self.flist):
if file[-3:] == ".gz": if file[-3:] == ".gz":
f = popen("%s -c %s" % (PIZZA_GUNZIP,file),'r') f = popen("%s -c %s" % (PIZZA_GUNZIP,file),'r')
else: f = open(file) else:
f = open(file)
snap = self.read_snapshot(f) snap = self.read_snapshot(f)
while snap: while snap:
self.snaps.append(snap) self.snaps.append(snap)
if outputfl: print snap.time, if outputfl: print(snap.time,end=' ')
self.fileNums.append(snap.time) self.fileNums.append(snap.time)
sys.stdout.flush() sys.stdout.flush()
snap = self.read_snapshot(f) snap = self.read_snapshot(f)
f.close() f.close()
if outputfl: print if outputfl: print()
# sort entries by timestep, cull duplicates # 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.fileNums.sort()
self.cull() self.cull()
self.nsnaps = len(self.snaps) self.nsnaps = len(self.snaps)
#print "read %d snapshots" % self.nsnaps #print("read %d snapshots" % self.nsnaps)
# select all timesteps and atoms # select all timesteps and atoms
@ -294,32 +297,32 @@ class dump:
# set default names for atom columns if file wasn't self-describing # set default names for atom columns if file wasn't self-describing
if len(self.snaps) == 0: if len(self.snaps) == 0:
if outputfl: print "no column assignments made" if outputfl: print("no column assignments made")
elif len(self.names): elif len(self.names):
if outputfl: print "assigned columns:",self.names2str() if outputfl: print("assigned columns:",self.names2str())
else: else:
if outputfl: print "no column assignments made" if outputfl: print("no column assignments made")
pass pass
# if snapshots are scaled, unscale them # if snapshots are scaled, unscale them
if (not self.names.has_key("x")) or \ if ("x" not in self.names) or \
(not self.names.has_key("y")) or \ ("y" not in self.names) or \
(not self.names.has_key("z")): ("z" not in self.names):
print "dump scaling status is unknown" print("dump scaling status is unknown")
elif self.nsnaps > 0: elif self.nsnaps > 0:
if self.scale_original == 1: self.unscale() if self.scale_original == 1: self.unscale()
elif self.scale_original == 0: elif self.scale_original == 0:
if outputfl: print "dump is already unscaled" if outputfl: print("dump is already unscaled")
else: else:
if outputfl: print "dump scaling status is unknown" if outputfl: print("dump scaling status is unknown")
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# read next snapshot from list of files # read next snapshot from list of files
def next(self): 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 # read next snapshot in current file using eof as pointer
# if fail, try next file # if fail, try next file
@ -331,24 +334,25 @@ class dump:
snap = self.read_snapshot(f) snap = self.read_snapshot(f)
if not snap: if not snap:
self.nextfile += 1 self.nextfile += 1
if self.nextfile == len(self.flist): return -1 if self.nextfile == len(self.flist): return -1
f.close() f.close()
self.eof = 0 self.eof = 0
continue continue
self.eof = f.tell() self.eof = f.tell()
f.close() f.close()
try: try:
self.findtime(snap.time) self.findtime(snap.time)
continue continue
except: break except: break
# select the new snapshot with all its atoms # select the new snapshot with all its atoms
self.snaps.append(snap) self.snaps.append(snap)
self.fileNums.append(snap.time)
snap = self.snaps[self.nsnaps] snap = self.snaps[self.nsnaps]
snap.tselect = 1 snap.tselect = 1
snap.nselect = snap.natoms 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.nsnaps += 1
self.nselect += 1 self.nselect += 1
@ -411,14 +415,14 @@ class dump:
if snap.natoms: if snap.natoms:
words = f.readline().split() words = f.readline().split()
ncol = len(words) ncol = len(words)
for i in xrange(1,snap.natoms): for i in range(1,snap.natoms):
words += f.readline().split() words += f.readline().split()
floats = map(float,words) floats = list(map(float,words))
if oldnumeric: atoms = np.zeros((snap.natoms,ncol),np.Float) if oldnumeric: atoms = np.zeros((snap.natoms,ncol),np.Float)
else: atoms = np.zeros((snap.natoms,ncol),np.float) else: atoms = np.zeros((snap.natoms,ncol),np.float)
start = 0 start = 0
stop = ncol stop = ncol
for i in xrange(snap.natoms): for i in range(snap.natoms):
atoms[i] = floats[start:stop] atoms[i] = floats[start:stop]
start = stop start = stop
stop += ncol stop += ncol
@ -433,7 +437,7 @@ class dump:
def map(self,*pairs): def map(self,*pairs):
if len(pairs) % 2 != 0: 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): for i in range(0,len(pairs),2):
j = i + 1 j = i + 1
self.names[pairs[j]] = pairs[i]-1 self.names[pairs[j]] = pairs[i]-1
@ -445,25 +449,26 @@ class dump:
ndel = i = 0 ndel = i = 0
while i < self.nsnaps: while i < self.nsnaps:
if not self.snaps[i].tselect: if not self.snaps[i].tselect:
del self.fileNums[i]
del self.snaps[i] del self.snaps[i]
self.nsnaps -= 1 self.nsnaps -= 1
ndel += 1 ndel += 1
else: i += 1 else: i += 1
print "%d snapshots deleted" % ndel print("%d snapshots deleted" % ndel)
print "%d snapshots remaining" % self.nsnaps print("%d snapshots remaining" % self.nsnaps)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# scale coords to 0-1 for all snapshots or just one # scale coords to 0-1 for all snapshots or just one
def scale(self,*list): def scale(self,*dumplist):
if len(list) == 0: if len(dumplist) == 0:
print "Scaling dump ..." print("Scaling dump ...")
x = self.names["x"] x = self.names["x"]
y = self.names["y"] y = self.names["y"]
z = self.names["z"] z = self.names["z"]
for snap in self.snaps: self.scale_one(snap,x,y,z) for snap in self.snaps: self.scale_one(snap,x,y,z)
else: else:
i = self.findtime(list[0]) i = self.findtime(dumplist[0])
x = self.names["x"] x = self.names["x"]
y = self.names["y"] y = self.names["y"]
z = self.names["z"] z = self.names["z"]
@ -483,15 +488,15 @@ class dump:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# unscale coords from 0-1 to box size for all snapshots or just one # unscale coords from 0-1 to box size for all snapshots or just one
def unscale(self,*list): def unscale(self,*dumplist):
if len(list) == 0: if len(dumplist) == 0:
print "Unscaling dump ..." print("Unscaling dump ...")
x = self.names["x"] x = self.names["x"]
y = self.names["y"] y = self.names["y"]
z = self.names["z"] z = self.names["z"]
for snap in self.snaps: self.unscale_one(snap,x,y,z) for snap in self.snaps: self.unscale_one(snap,x,y,z)
else: else:
i = self.findtime(list[0]) i = self.findtime(dumplist[0])
x = self.names["x"] x = self.names["x"]
y = self.names["y"] y = self.names["y"]
z = self.names["z"] z = self.names["z"]
@ -512,7 +517,7 @@ class dump:
# wrap coords from outside box to inside # wrap coords from outside box to inside
def wrap(self): def wrap(self):
print "Wrapping dump ..." print("Wrapping dump ...")
x = self.names["x"] x = self.names["x"]
y = self.names["y"] y = self.names["y"]
@ -534,7 +539,7 @@ class dump:
# unwrap coords from inside box to outside # unwrap coords from inside box to outside
def unwrap(self): def unwrap(self):
print "Unwrapping dump ..." print("Unwrapping dump ...")
x = self.names["x"] x = self.names["x"]
y = self.names["y"] y = self.names["y"]
@ -557,7 +562,7 @@ class dump:
# if dynamic extra lines or triangles defined, owrap them as well # if dynamic extra lines or triangles defined, owrap them as well
def owrap(self,other): def owrap(self,other):
print "Wrapping to other ..." print("Wrapping to other ...")
id = self.names["id"] id = self.names["id"]
x = self.names["x"] x = self.names["x"]
@ -574,9 +579,9 @@ class dump:
zprd = snap.zhi - snap.zlo zprd = snap.zhi - snap.zlo
atoms = snap.atoms atoms = snap.atoms
ids = {} ids = {}
for i in xrange(snap.natoms): for i in range(snap.natoms):
ids[atoms[i][id]] = i ids[atoms[i][id]] = i
for i in xrange(snap.natoms): for i in range(snap.natoms):
j = ids[atoms[i][iother]] j = ids[atoms[i][iother]]
atoms[i][x] += (atoms[i][ix]-atoms[j][ix])*xprd atoms[i][x] += (atoms[i][ix]-atoms[j][ix])*xprd
atoms[i][y] += (atoms[i][iy]-atoms[j][iy])*yprd atoms[i][y] += (atoms[i][iy]-atoms[j][iy])*yprd
@ -589,11 +594,11 @@ class dump:
# convert column names assignment to a string, in column order # convert column names assignment to a string, in column order
def names2str(self): def names2str(self):
ncol = max(self.names.values()) #len(self.snaps[0].atoms[0]) pairs = list(self.names.items())
pairs = self.names.items() values = list(self.names.values())
values = self.names.values() ncol = len(pairs)
str = "" str = ""
for i in xrange(ncol): for i in range(ncol):
if i in values: str += pairs[values.index(i)][0] + ' ' if i in values: str += pairs[values.index(i)][0] + ' '
return str return str
@ -602,24 +607,24 @@ class dump:
# if arg = string, sort all steps by that column # if arg = string, sort all steps by that column
# if arg = numeric, sort atoms in single step # if arg = numeric, sort atoms in single step
def sort(self,*list, **kwargs): def sort(self,*tslist, **kwargs):
# check whether to output or not # check whether to output or not
outputfl = True outputfl = True
if "output" in kwargs: outputfl = kwargs["output"] if "output" in kwargs: outputfl = kwargs["output"]
if len(list) == 0: if len(tslist) == 0:
if outputfl: print "Sorting selected snapshots ..." if outputfl: print("Sorting selected snapshots ...")
id = self.names["id"] id = self.names["id"]
for snap in self.snaps: for snap in self.snaps:
if snap.tselect: self.sort_one(snap,id) if snap.tselect: self.sort_one(snap,id)
elif type(list[0]) is types.StringType: elif isinstance(tslist[0], str):
if outputfl: print "Sorting selected snapshots by %s ..." % list[0] if outputfl: print("Sorting selected snapshots by %s ..." % tslist[0])
id = self.names[list[0]] id = self.names[tslist[0]]
for snap in self.snaps: for snap in self.snaps:
if snap.tselect: self.sort_one(snap,id) if snap.tselect: self.sort_one(snap,id)
else: else:
i = self.findtime(list[0]) i = self.findtime(tslist[0])
id = self.names["id"] id = self.names["id"]
self.sort_one(self.snaps[i],id) self.sort_one(self.snaps[i],id)
@ -630,7 +635,7 @@ class dump:
atoms = snap.atoms atoms = snap.atoms
ids = atoms[:,id] ids = atoms[:,id]
ordering = np.argsort(ids) 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) atoms[:,i] = np.take(atoms[:,i],ordering)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -642,33 +647,33 @@ class dump:
else: f = open(file,"a") else: f = open(file,"a")
for snap in self.snaps: for snap in self.snaps:
if not snap.tselect: continue if not snap.tselect: continue
print snap.time, print(snap.time, end=' ')
sys.stdout.flush() sys.stdout.flush()
if header: if header:
print >>f,"ITEM: TIMESTEP" print("ITEM: TIMESTEP", file=f)
print >>f,snap.time print(snap.time, file=f)
print >>f,"ITEM: NUMBER OF ATOMS" print("ITEM: NUMBER OF ATOMS", file=f)
print >>f,snap.nselect print(snap.nselect, file=f)
print >>f,"ITEM: BOX BOUNDS" print("ITEM: BOX BOUNDS", file=f)
print >>f,snap.xlo,snap.xhi print(snap.xlo,snap.xhi, file=f)
print >>f,snap.ylo,snap.yhi print(snap.ylo,snap.yhi, file=f)
print >>f,snap.zlo,snap.zhi print(snap.zlo,snap.zhi, file=f)
print >>f,"ITEM: ATOMS",namestr print("ITEM: ATOMS",namestr, file=f)
atoms = snap.atoms atoms = snap.atoms
nvalues = len(atoms[0]) nvalues = len(atoms[0])
for i in xrange(snap.natoms): for i in range(snap.natoms):
if not snap.aselect[i]: continue if not snap.aselect[i]: continue
line = "" line = ""
for j in xrange(nvalues): for j in range(nvalues):
if (j < 2): if (j < 2):
line += str(int(atoms[i][j])) + " " line += str(int(atoms[i][j])) + " "
else: else:
line += str(atoms[i][j]) + " " line += str(atoms[i][j]) + " "
print >>f,line print(line, file=f)
f.close() f.close()
print "\n%d snapshots" % self.nselect print("\n%d snapshots" % self.nselect)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# write one dump file per snapshot from current selection # write one dump file per snapshot from current selection
@ -677,34 +682,34 @@ class dump:
if len(self.snaps): namestr = self.names2str() if len(self.snaps): namestr = self.names2str()
for snap in self.snaps: for snap in self.snaps:
if not snap.tselect: continue if not snap.tselect: continue
print snap.time, print(snap.time, end=' ')
sys.stdout.flush() sys.stdout.flush()
file = root + "." + str(snap.time) file = root + "." + str(snap.time)
f = open(file,"w") f = open(file,"w")
print >>f,"ITEM: TIMESTEP" print("ITEM: TIMESTEP", file=f)
print >>f,snap.time print(snap.time, file=f)
print >>f,"ITEM: NUMBER OF ATOMS" print("ITEM: NUMBER OF ATOMS", file=f)
print >>f,snap.nselect print(snap.nselect, file=f)
print >>f,"ITEM: BOX BOUNDS" print("ITEM: BOX BOUNDS", file=f)
print >>f,snap.xlo,snap.xhi print(snap.xlo,snap.xhi, file=f)
print >>f,snap.ylo,snap.yhi print(snap.ylo,snap.yhi, file=f)
print >>f,snap.zlo,snap.zhi print(snap.zlo,snap.zhi, file=f)
print >>f,"ITEM: ATOMS",namestr print("ITEM: ATOMS",namestr, file=f)
atoms = snap.atoms atoms = snap.atoms
nvalues = len(atoms[0]) nvalues = len(atoms[0])
for i in xrange(snap.natoms): for i in range(snap.natoms):
if not snap.aselect[i]: continue if not snap.aselect[i]: continue
line = "" line = ""
for j in xrange(nvalues): for j in range(nvalues):
if (j < 2): if (j < 2):
line += str(int(atoms[i][j])) + " " line += str(int(atoms[i][j])) + " "
else: else:
line += str(atoms[i][j]) + " " line += str(atoms[i][j]) + " "
print >>f,line print(line, file=f)
f.close() 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 # find min/max across all selected snapshots/atoms for a particular column
@ -716,7 +721,7 @@ class dump:
for snap in self.snaps: for snap in self.snaps:
if not snap.tselect: continue if not snap.tselect: continue
atoms = snap.atoms atoms = snap.atoms
for i in xrange(snap.natoms): for i in range(snap.natoms):
if not snap.aselect[i]: continue if not snap.aselect[i]: continue
if atoms[i][icol] < min: min = atoms[i][icol] if atoms[i][icol] < min: min = atoms[i][icol]
if atoms[i][icol] > max: max = atoms[i][icol] if atoms[i][icol] > max: max = atoms[i][icol]
@ -726,15 +731,15 @@ class dump:
# set a column value via an equation for all selected snapshots # set a column value via an equation for all selected snapshots
def set(self,eq): def set(self,eq):
print "Setting ..." print("Setting ...")
pattern = "\$\w*" pattern = "\$\w*"
list = re.findall(pattern,eq) eqlist = re.findall(pattern,eq)
lhs = list[0][1:] lhs = eqlist[0][1:]
if not self.names.has_key(lhs): if lhs not in self.names:
self.newcolumn(lhs) self.newcolumn(lhs)
for item in list: for item in eqlist:
name = item[1:] name = item[1:]
column = self.names[name] column = self.names[name]
insert = "snap.atoms[i][%d]" % (column) insert = "snap.atoms[i][%d]" % (column)
@ -743,25 +748,25 @@ class dump:
for snap in self.snaps: for snap in self.snaps:
if not snap.tselect: continue if not snap.tselect: continue
for i in xrange(snap.natoms): for i in range(snap.natoms):
if snap.aselect[i]: exec ceq if snap.aselect[i]: exec(ceq)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# set a column value via an input vec for all selected snapshots/atoms # set a column value via an input vec for all selected snapshots/atoms
def setv(self,colname,vec): def setv(self,colname,vec):
print "Setting ..." print("Setting ...")
if not self.names.has_key(colname): if colname not in self.names:
self.newcolumn(colname) self.newcolumn(colname)
icol = self.names[colname] icol = self.names[colname]
for snap in self.snaps: for snap in self.snaps:
if not snap.tselect: continue if not snap.tselect: continue
if snap.nselect != len(vec): 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 atoms = snap.atoms
m = 0 m = 0
for i in xrange(snap.natoms): for i in range(snap.natoms):
if snap.aselect[i]: if snap.aselect[i]:
atoms[i][icol] = vec[m] atoms[i][icol] = vec[m]
m += 1 m += 1
@ -774,12 +779,12 @@ class dump:
icol = self.names[col] icol = self.names[col]
id = self.names["id"] id = self.names["id"]
ids = {} 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 ids[self.snaps[istep].atoms[i][id]] = i
for snap in self.snaps: for snap in self.snaps:
if not snap.tselect: continue if not snap.tselect: continue
atoms = snap.atoms atoms = snap.atoms
for i in xrange(snap.natoms): for i in range(snap.natoms):
if not snap.aselect[i]: continue if not snap.aselect[i]: continue
j = ids[atoms[i][id]] j = ids[atoms[i][id]]
atoms[i][icol] = self.snaps[istep].atoms[j][icol] atoms[i][icol] = self.snaps[istep].atoms[j][icol]
@ -789,18 +794,18 @@ class dump:
def spread(self,old,n,new): def spread(self,old,n,new):
iold = self.names[old] 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] inew = self.names[new]
min,max = self.minmax(old) min,max = self.minmax(old)
print "min/max = ",min,max print("min/max = ",min,max)
gap = max - min gap = max - min
invdelta = n/gap invdelta = n/gap
for snap in self.snaps: for snap in self.snaps:
if not snap.tselect: continue if not snap.tselect: continue
atoms = snap.atoms atoms = snap.atoms
for i in xrange(snap.natoms): for i in range(snap.natoms):
if not snap.aselect[i]: continue if not snap.aselect[i]: continue
ivalue = int((atoms[i][iold] - min) * invdelta) + 1 ivalue = int((atoms[i][iold] - min) * invdelta) + 1
if ivalue > n: ivalue = n if ivalue > n: ivalue = n
@ -822,12 +827,12 @@ class dump:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# extract vector(s) of values for atom ID n at each selected timestep # extract vector(s) of values for atom ID n at each selected timestep
def atom(self,n,*list): def atom(self,n,*tslist):
if len(list) == 0: if len(tslist) == 0:
raise StandardError, "no columns specified" raise Exception("no columns specified")
columns = [] columns = []
values = [] values = []
for name in list: for name in tslist:
columns.append(self.names[name]) columns.append(self.names[name])
values.append(self.nselect * [0]) values.append(self.nselect * [0])
ncol = len(columns) ncol = len(columns)
@ -837,40 +842,40 @@ class dump:
for snap in self.snaps: for snap in self.snaps:
if not snap.tselect: continue if not snap.tselect: continue
atoms = snap.atoms 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: break
if atoms[i][id] != n: if atoms[i][id] != n:
raise StandardError, "could not find atom ID in snapshot" raise Exception("could not find atom ID in snapshot")
for j in xrange(ncol): for j in range(ncol):
values[j][m] = atoms[i][columns[j]] values[j][m] = atoms[i][columns[j]]
m += 1 m += 1
if len(list) == 1: return values[0] if len(tslist) == 1: return values[0]
else: return values else: return values
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# extract vector(s) of values for selected atoms at chosen timestep # 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)] snap = self.snaps[self.findtime(n)]
if len(list) == 0: if len(tslist) == 0:
raise StandardError, "no columns specified" raise Exception("no columns specified")
columns = [] columns = []
values = [] values = []
for name in list: for name in tslist:
columns.append(self.names[name]) columns.append(self.names[name])
values.append(snap.nselect * [0]) values.append(snap.nselect * [0])
ncol = len(columns) ncol = len(columns)
m = 0 m = 0
for i in xrange(snap.natoms): for i in range(snap.natoms):
if not snap.aselect[i]: continue if not snap.aselect[i]: continue
for j in xrange(ncol): for j in range(ncol):
values[j][m] = snap.atoms[i][columns[j]] values[j][m] = snap.atoms[i][columns[j]]
m += 1 m += 1
if len(list) == 1: return values[0] if len(tslist) == 1: return values[0]
else: return values else: return values
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -915,7 +920,7 @@ class dump:
def iterator(self,flag): def iterator(self,flag):
start = 0 start = 0
if flag: start = self.iterate + 1 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: if self.snaps[i].tselect:
self.iterate = i self.iterate = i
return i,self.snaps[i].time,1 return i,self.snaps[i].time,1
@ -951,7 +956,7 @@ class dump:
# need Numeric/Numpy mode here # need Numeric/Numpy mode here
atoms = [] atoms = []
for i in xrange(snap.natoms): for i in range(snap.natoms):
if not snap.aselect[i]: continue if not snap.aselect[i]: continue
atom = snap.atoms[i] atom = snap.atoms[i]
atoms.append([atom[id],atom[type],atom[x],atom[y],atom[z]]) atoms.append([atom[id],atom[type],atom[x],atom[y],atom[z]])
@ -970,7 +975,7 @@ class dump:
elif self.bondflag == 2: elif self.bondflag == 2:
tmp1,tmp2,tmp3,bondlist,tmp4,tmp5 = self.objextra.viz(time,1) tmp1,tmp2,tmp3,bondlist,tmp4,tmp5 = self.objextra.viz(time,1)
alist = {} 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: for bond in bondlist:
try: try:
i = alist[bond[2]] i = alist[bond[2]]
@ -1004,9 +1009,9 @@ class dump:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def findtime(self,n): def findtime(self,n):
for i in xrange(self.nsnaps): for i in range(self.nsnaps):
if self.snaps[i].time == n: return i 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 # return maximum box size across all selected snapshots
@ -1033,7 +1038,7 @@ class dump:
for snap in self.snaps: for snap in self.snaps:
if not snap.tselect: continue if not snap.tselect: continue
atoms = snap.atoms atoms = snap.atoms
for i in xrange(snap.natoms): for i in range(snap.natoms):
if not snap.aselect[i]: continue if not snap.aselect[i]: continue
if atoms[i][icol] > max: max = atoms[i][icol] if atoms[i][icol] > max: max = atoms[i][icol]
return int(max) return int(max)
@ -1046,7 +1051,7 @@ class dump:
# data object, grab bonds statically # 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 self.bondflag = 0
try: try:
bondlist = [] bondlist = []
@ -1059,11 +1064,11 @@ class dump:
self.bondflag = 1 self.bondflag = 1
self.bondlist = bondlist self.bondlist = bondlist
except: 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 # 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 self.triflag = self.lineflag = 0
try: try:
tmp,tmp,tmp,tmp,tris,lines = arg.viz(0) tmp,tmp,tmp,tmp,tris,lines = arg.viz(0)
@ -1074,34 +1079,34 @@ class dump:
self.lineflag = 1 self.lineflag = 1
self.linelist = lines self.linelist = lines
except: 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 # 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.triflag = 2
self.objextra = arg self.objextra = arg
# bdump object, grab bonds dynamically # 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.bondflag = 2
self.objextra = arg self.objextra = arg
# ldump object, grab tris dynamically # 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.lineflag = 2
self.objextra = arg self.objextra = arg
# tdump object, grab tris dynamically # 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.triflag = 2
self.objextra = arg self.objextra = arg
else: else:
raise StandardError,"unrecognized argument to dump.extra()" raise Exception("unrecognized argument to dump.extra()")
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -1140,7 +1145,7 @@ class tselect:
snap.tselect = 1 snap.tselect = 1
data.nselect = len(data.snaps) data.nselect = len(data.snaps)
data.aselect.all() 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 +1157,7 @@ class tselect:
data.snaps[i].tselect = 1 data.snaps[i].tselect = 1
data.nselect = 1 data.nselect = 1
data.aselect.all() 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 +1166,7 @@ class tselect:
for snap in data.snaps: for snap in data.snaps:
snap.tselect = 0 snap.tselect = 0
data.nselect = 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 +1182,7 @@ class tselect:
snap.tselect = 0 snap.tselect = 0
data.nselect -= 1 data.nselect -= 1
data.aselect.all() 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 +1191,16 @@ class tselect:
snaps = data.snaps snaps = data.snaps
cmd = "flag = " + teststr.replace("$t","snaps[i].time") cmd = "flag = " + teststr.replace("$t","snaps[i].time")
ccmd = compile(cmd,'','single') ccmd = compile(cmd,'','single')
for i in xrange(data.nsnaps): for i in range(data.nsnaps):
if not snaps[i].tselect: continue 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: if not flag:
snaps[i].tselect = 0 snaps[i].tselect = 0
data.nselect -= 1 data.nselect -= 1
data.aselect.all() 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 # atom selection class
@ -1210,12 +1217,12 @@ class aselect:
if len(args) == 0: # all selected timesteps if len(args) == 0: # all selected timesteps
for snap in data.snaps: for snap in data.snaps:
if not snap.tselect: continue 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 snap.nselect = snap.natoms
else: # one timestep else: # one timestep
n = data.findtime(args[0]) n = data.findtime(args[0])
snap = data.snaps[n] 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 snap.nselect = snap.natoms
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -1226,8 +1233,8 @@ class aselect:
# replace all $var with snap.atoms references and compile test string # replace all $var with snap.atoms references and compile test string
pattern = "\$\w*" pattern = "\$\w*"
list = re.findall(pattern,teststr) testlist = re.findall(pattern,teststr)
for item in list: for item in testlist:
name = item[1:] name = item[1:]
column = data.names[name] column = data.names[name]
insert = "snap.atoms[i][%d]" % column insert = "snap.atoms[i][%d]" % column
@ -1238,29 +1245,33 @@ class aselect:
if len(args) == 0: # all selected timesteps if len(args) == 0: # all selected timesteps
for snap in data.snaps: for snap in data.snaps:
if not snap.tselect: continue if not snap.tselect: continue
for i in xrange(snap.natoms): for i in range(snap.natoms):
if not snap.aselect[i]: continue if not snap.aselect[i]: continue
exec ccmd ldict = {'snap':snap,'i':i}
exec(ccmd,globals(),ldict)
flag = ldict['flag']
if not flag: if not flag:
snap.aselect[i] = 0 snap.aselect[i] = 0
snap.nselect -= 1 snap.nselect -= 1
for i in xrange(data.nsnaps): for i in range(data.nsnaps):
if data.snaps[i].tselect: if data.snaps[i].tselect:
print "%d atoms of %d selected in first step %d" % \ print("%d atoms of %d selected in first step %d" % \
(data.snaps[i].nselect,data.snaps[i].natoms,data.snaps[i].time) (data.snaps[i].nselect,data.snaps[i].natoms,data.snaps[i].time))
break break
for i in xrange(data.nsnaps-1,-1,-1): for i in range(data.nsnaps-1,-1,-1):
if data.snaps[i].tselect: if data.snaps[i].tselect:
print "%d atoms of %d selected in last step %d" % \ print("%d atoms of %d selected in last step %d" % \
(data.snaps[i].nselect,data.snaps[i].natoms,data.snaps[i].time) (data.snaps[i].nselect,data.snaps[i].natoms,data.snaps[i].time))
break break
else: # one timestep else: # one timestep
n = data.findtime(args[0]) n = data.findtime(args[0])
snap = data.snaps[n] snap = data.snaps[n]
for i in xrange(snap.natoms): for i in range(snap.natoms):
if not snap.aselect[i]: continue if not snap.aselect[i]: continue
exec ccmd ldict = {'snap':snap,'i':i}
exec(ccmd,globals(),ldict)
flag = ldict['flag']
if not flag: if not flag:
snap.aselect[i] = 0 snap.aselect[i] = 0
snap.nselect -= 1 snap.nselect -= 1

View File

@ -27,6 +27,7 @@ and dump match the format here - this will be checked in future!
""" """
from __future__ import print_function, absolute_import
from evtk.vtk import VtkFile, VtkGroup, VtkUnstructuredGrid from evtk.vtk import VtkFile, VtkGroup, VtkUnstructuredGrid
from bdump import bdump from bdump import bdump
import numpy as np 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... # 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: 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() sys.exit()
# loop through available timesteps # loop through available timesteps
@ -104,7 +105,7 @@ while timestep >= 0:
if forcedata.snaps[fileindex].natoms == 0: if forcedata.snaps[fileindex].natoms == 0:
vtufile = fileprefix+'_'+str(timestep)+'.vtu' vtufile = fileprefix+'_'+str(timestep)+'.vtu'
vtufile = os.path.join(outputdir,vtufile) vtufile = os.path.join(outputdir,vtufile)
vtuwrite = file(vtufile,'w') vtuwrite = open(vtufile,'w')
vtuwrite.write("""<?xml version="1.0"?> vtuwrite.write("""<?xml version="1.0"?>
<VTKFile byte_order="LittleEndian" version="0.1" type="UnstructuredGrid"> <VTKFile byte_order="LittleEndian" version="0.1" type="UnstructuredGrid">
<UnstructuredGrid> <UnstructuredGrid>
@ -134,8 +135,8 @@ while timestep >= 0:
nconnex = ncells - nperiodic nconnex = ncells - nperiodic
# extract the IDs as an array of integers # extract the IDs as an array of integers
id1 = np.array(forcedata.snaps[fileindex].atoms[:,forcedata.names["id1"]],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=long) id2 = np.array(forcedata.snaps[fileindex].atoms[:,forcedata.names["id2"]],dtype=int)
# and convert to lists # and convert to lists
id1 = id1.tolist() id1 = id1.tolist()
@ -153,7 +154,7 @@ while timestep >= 0:
# number of points = number of unique IDs (particles) # number of points = number of unique IDs (particles)
npoints = len(ids) 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))
# ****************************************** # ******************************************

View File

@ -8,10 +8,15 @@
# ensight tool # ensight tool
# Imports and external programs
from __future__ import print_function, absolute_import
import sys, types
oneline = "Convert LAMMPS snapshots or meshes to Ensight format" oneline = "Convert LAMMPS snapshots or meshes to Ensight format"
docstr = """ docstr = """
e = ensight(d) d = object with atoms or elements (dump,data,mdump) e = ensight(d) d = object with atoms or elements (dump,data,mdump)
e.change = 1 set to 1 if element nodal xyz change with time (def = 0) e.change = 1 set to 1 if element nodal xyz change with time (def = 0)
e.maxtype = 10 max particle type, set if query to data will be bad e.maxtype = 10 max particle type, set if query to data will be bad
@ -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 # which = 0 for particles, 1 for elements
# change = 0 for unchanging mesh coords, 1 for changing mesh coords (def = 0) # change = 0 for unchanging mesh coords, 1 for changing mesh coords (def = 0)
# Imports and external programs
import sys, types
# Class definition # Class definition
class ensight: class ensight:
@ -64,16 +65,16 @@ class ensight:
self.change = 0 self.change = 0
self.maxtype = 0 self.maxtype = 0
self.data = data 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 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 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 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 self.which = 1
else: 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 flag == -1: break
if self.which == 0: 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) time,box,atoms,bonds,tris,lines = self.data.viz(which)
self.coord_file_atoms(f,box,atoms) self.coord_file_atoms(f,box,atoms)
print >>f,"END TIME STEP" print("END TIME STEP", file=f)
elif self.change == 0 and first: 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) time,box,nodes,elements,nvalues,evalues = self.data.mviz(which)
self.coord_file_elements(f,box,nodes,elements) self.coord_file_elements(f,box,nodes,elements)
etype = len(elements[0]) etype = len(elements[0])
first = 0 first = 0
print >>f,"END TIME STEP" print("END TIME STEP", file=f)
elif self.change: elif self.change:
print >>f,"BEGIN TIME STEP" print("BEGIN TIME STEP", file=f)
time,box,nodes,elements,nvalues,evalues = self.data.mviz(which) time,box,nodes,elements,nvalues,evalues = self.data.mviz(which)
self.coord_file_elements(f,box,nodes,elements) self.coord_file_elements(f,box,nodes,elements)
etype = len(elements[0]) etype = len(elements[0])
print >>f,"END TIME STEP" print("END TIME STEP", file=f)
for i in range(len(pairs)): 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]) values = self.data.vecs(time,pairs[i][0])
if self.which == 0: if self.which == 0:
self.variable_file_atoms(vfiles[i],pairs[i][1],atoms,values) self.variable_file_atoms(vfiles[i],pairs[i][1],atoms,values)
else: else:
self.variable_file_elements(vfiles[i],pairs[i][1],etype,values) 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() sys.stdout.flush()
n += 1 n += 1
@ -150,7 +151,7 @@ class ensight:
f.close() f.close()
for f in vfiles: 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 first = 1
n = etype = 0 n = etype = 0
while 1: while 1:
time = self.data.next() time = next(self.data)
if time == -1: break if time == -1: break
times.append(time) times.append(time)
self.data.tselect.one(time) self.data.tselect.one(time)
self.data.delete() self.data.delete()
if self.which == 0: 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) time,box,atoms,bonds,tris,lines = self.data.viz(0)
self.coord_file_atoms(f,box,atoms) self.coord_file_atoms(f,box,atoms)
print >>f,"END TIME STEP" print("END TIME STEP", file=f)
elif self.change == 0 and first: 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) time,box,nodes,elements,nvalues,evalues = self.data.mviz(0)
self.coord_file_elements(f,box,nodes,elements) self.coord_file_elements(f,box,nodes,elements)
etype = len(elements[0]) etype = len(elements[0])
first = 0 first = 0
print >>f,"END TIME STEP" print("END TIME STEP", file=f)
elif self.change: elif self.change:
print >>f,"BEGIN TIME STEP" print("BEGIN TIME STEP", file=f)
time,box,nodes,elements,nvalues,evalues = self.data.mviz(0) time,box,nodes,elements,nvalues,evalues = self.data.mviz(0)
self.coord_file_elements(f,box,nodes,elements) self.coord_file_elements(f,box,nodes,elements)
etype = len(elements[0]) etype = len(elements[0])
print >>f,"END TIME STEP" print("END TIME STEP", file=f)
for i in range(len(pairs)): 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]) values = self.data.vecs(time,pairs[i][0])
if self.which == 0: if self.which == 0:
self.variable_file_atoms(vfiles[i],pairs[i][1],atoms,values) self.variable_file_atoms(vfiles[i],pairs[i][1],atoms,values)
else: else:
self.variable_file_elements(vfiles[i],pairs[i][1],etype,values) 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() sys.stdout.flush()
n += 1 n += 1
@ -230,7 +231,7 @@ class ensight:
self.case_file(f,root,pairs,0,len(times),times) self.case_file(f,root,pairs,0,len(times),times)
f.close() f.close()
print "\nwrote %s snapshots in Ensight format" % n print("\nwrote %s snapshots in Ensight format" % n)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -268,20 +269,20 @@ class ensight:
files = [] files = []
if n < 10: if n < 10:
file = root + "000" + str(n) + ".xyz" file = root + "000" + str(n) + ".xyz"
for pair in pairs: for pair in pairs:
files.append(root + "000" + str(n) + "." + pair[0]) files.append(root + "000" + str(n) + "." + pair[0])
elif n < 100: elif n < 100:
file = root + "00" + str(n) + ".xyz" file = root + "00" + str(n) + ".xyz"
for pair in pairs: for pair in pairs:
files.append(root + "00" + str(n) + "." + pair[0]) files.append(root + "00" + str(n) + "." + pair[0])
elif n < 1000: elif n < 1000:
file = root + "0" + str(n) + ".xyz" file = root + "0" + str(n) + ".xyz"
for pair in pairs: for pair in pairs:
files.append(root + "0" + str(n) + "." + pair[0]) files.append(root + "0" + str(n) + "." + pair[0])
else: else:
file = root + str(n) + ".xyz" file = root + str(n) + ".xyz"
for pair in pairs: for pair in pairs:
files.append(root + str(n) + "." + pair[0]) files.append(root + str(n) + "." + pair[0])
if self.which == 0: if self.which == 0:
f = open(file,"w") f = open(file,"w")
@ -309,13 +310,13 @@ class ensight:
self.variable_file_atoms(f,pairs[i][1],atoms,values) self.variable_file_atoms(f,pairs[i][1],atoms,values)
else: else:
self.variable_file_elements(f,pairs[i][1],etype,values) self.variable_file_elements(f,pairs[i][1],etype,values)
f.close() f.close()
print time, print(time, end=' ')
sys.stdout.flush() sys.stdout.flush()
n += 1 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 # write Ensight case file
def case_file(self,f,root,pairs,multifile,nsnaps,times): def case_file(self,f,root,pairs,multifile,nsnaps,times):
print >>f,"# Ensight case file\n" print("# Ensight case file\n", file=f)
print >>f,"FORMAT\ntype: ensight gold\n" print("FORMAT\ntype: ensight gold\n", file=f)
if self.which == 0: if self.which == 0:
if multifile: if multifile:
# print >>f,"GEOMETRY\nmodel: %s****.xyz change_coords_only\n" % root # 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: else:
# print >>f,"GEOMETRY\nmodel: 1 1 %s.xyz change_coords_only\n" % root # 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: else:
if self.change == 0: if self.change == 0:
print >>f,"GEOMETRY\nmodel: %s.xyz\n" % root print("GEOMETRY\nmodel: %s.xyz\n" % root, file=f)
elif multifile: elif multifile:
print >>f,"GEOMETRY\nmodel: %s****.xyz\n" % root print("GEOMETRY\nmodel: %s****.xyz\n" % root, file=f)
else: 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): if len(pairs):
print >>f,"VARIABLE" print("VARIABLE", file=f)
for pair in pairs: for pair in pairs:
if self.which == 0: if self.which == 0:
if multifile: 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: 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: else:
if multifile: 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: else:
print >>f,"scalar per element: 1 1 %s %s.%s" % (pair[1],root,pair[0]) print("scalar per element: 1 1 %s %s.%s" % (pair[1],root,pair[0]), file=f)
print >>f print(file=f)
print >>f,"TIME" print("TIME", file=f)
print >>f,"time set: 1" print("time set: 1", file=f)
print >>f,"number of steps:",nsnaps print("number of steps:",nsnaps, file=f)
print >>f,"filename start number: 0" print("filename start number: 0", file=f)
print >>f,"filename increment: 1" print("filename increment: 1", file=f)
print >>f,"time values:" print("time values:", file=f)
for i in range(nsnaps): for i in range(nsnaps):
print >>f,times[i], print(times[i], end=' ', file=f)
if i % 10 == 9: print >>f if i % 10 == 9: print(file=f)
print >>f print(file=f)
print >>f print(file=f)
if not multifile: if not multifile:
print >>f,"FILE" print("FILE", file=f)
print >>f,"file set: 1" print("file set: 1", file=f)
print >>f,"number of steps:",nsnaps print("number of steps:",nsnaps, file=f)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# write Ensight coordinates for atoms # write Ensight coordinates for atoms
@ -423,65 +424,65 @@ class ensight:
# one part = coords for all atoms of a single type # one part = coords for all atoms of a single type
def coord_file_atoms(self,f,box,atoms): def coord_file_atoms(self,f,box,atoms):
print >>f,"Particle geometry\nfor a collection of atoms" print("Particle geometry\nfor a collection of atoms", file=f)
print >>f,"node id given" print("node id given", file=f)
print >>f,"element id off" print("element id off", file=f)
print >>f,"extents" print("extents", file=f)
print >>f,"%12.5e%12.5e" % (box[0],box[3]) print("%12.5e%12.5e" % (box[0],box[3]), file=f)
print >>f,"%12.5e%12.5e" % (box[1],box[4]) print("%12.5e%12.5e" % (box[1],box[4]), file=f)
print >>f,"%12.5e%12.5e" % (box[2],box[5]) print("%12.5e%12.5e" % (box[2],box[5]), file=f)
for type in xrange(1,self.maxtype+1): for type in range(1,self.maxtype+1):
print >>f,"part" print("part", file=f)
print >>f,"%10d" % type print("%10d" % type, file=f)
print >>f,"type",type print("type",type, file=f)
print >>f,"coordinates" print("coordinates", file=f)
group = [atom for atom in atoms if int(atom[1]) == type] group = [atom for atom in atoms if int(atom[1]) == type]
print >>f,"%10d" % len(group) print("%10d" % len(group), file=f)
for atom in group: print >>f,"%10d" % int(atom[0]) for atom in group: print("%10d" % int(atom[0]), file=f)
for atom in group: print >>f,"%12.5e" % atom[2] for atom in group: print("%12.5e" % atom[2], file=f)
for atom in group: print >>f,"%12.5e" % atom[3] for atom in group: print("%12.5e" % atom[3], file=f)
for atom in group: print >>f,"%12.5e" % atom[4] for atom in group: print("%12.5e" % atom[4], file=f)
print >>f,"point" print("point", file=f)
print >>f,"%10d" % len(group) print("%10d" % len(group), file=f)
for i in xrange(1,len(group)+1): print >>f,"%10d" % i for i in range(1,len(group)+1): print("%10d" % i, file=f)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# write Ensight coordinates for elements # write Ensight coordinates for elements
def coord_file_elements(self,f,box,nodes,elements): def coord_file_elements(self,f,box,nodes,elements):
print >>f,"Element geometry\nfor a collection of elements" print("Element geometry\nfor a collection of elements", file=f)
print >>f,"node id given" print("node id given", file=f)
print >>f,"element id given" print("element id given", file=f)
print >>f,"extents" print("extents", file=f)
print >>f,"%12.5e%12.5e" % (box[0],box[3]) print("%12.5e%12.5e" % (box[0],box[3]), file=f)
print >>f,"%12.5e%12.5e" % (box[1],box[4]) print("%12.5e%12.5e" % (box[1],box[4]), file=f)
print >>f,"%12.5e%12.5e" % (box[2],box[5]) print("%12.5e%12.5e" % (box[2],box[5]), file=f)
print >>f,"part" print("part", file=f)
print >>f,"%10d" % 1 print("%10d" % 1, file=f)
print >>f,"all elements" print("all elements", file=f)
print >>f,"coordinates" print("coordinates", file=f)
print >>f,"%10d" % len(nodes) print("%10d" % len(nodes), file=f)
for node in nodes: print >>f,"%10d" % int(node[0]) for node in nodes: print("%10d" % int(node[0]), file=f)
for node in nodes: print >>f,"%12.5e" % node[2] for node in nodes: print("%12.5e" % node[2], file=f)
for node in nodes: print >>f,"%12.5e" % node[3] for node in nodes: print("%12.5e" % node[3], file=f)
for node in nodes: print >>f,"%12.5e" % node[4] for node in nodes: print("%12.5e" % node[4], file=f)
if len(elements[0]) == 5: print >>f,"tria3" if len(elements[0]) == 5: print("tria3", file=f)
elif len(elements[0]) == 6: print >>f,"tetra4" elif len(elements[0]) == 6: print("tetra4", file=f)
else: raise StandardError,"unrecognized element type" else: raise Exception("unrecognized element type")
print >>f,"%10d" % len(elements) 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: if len(elements[0]) == 5:
for element in elements: for element in elements:
print >>f,"%10d%10d%10d" % \ print("%10d%10d%10d" % \
(int(element[2]),int(element[3]),int(element[4])) (int(element[2]),int(element[3]),int(element[4])), file=f)
elif len(elements[0]) == 6: elif len(elements[0]) == 6:
for element in elements: for element in elements:
print >>f,"%10d%10d%10d%10d" % \ print("%10d%10d%10d%10d" % \
(int(element[2]),int(element[3]),int(element[4]),int(element[5])) (int(element[2]),int(element[3]),int(element[4]),int(element[5])), file=f)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# write Ensight variable values for atoms # write Ensight variable values for atoms
@ -489,22 +490,22 @@ class ensight:
# one part = values for all atoms of a single type # one part = values for all atoms of a single type
def variable_file_atoms(self,f,name,atoms,values): def variable_file_atoms(self,f,name,atoms,values):
print >>f,"Particle %s" % name print("Particle %s" % name, file=f)
for type in xrange(1,self.maxtype+1): for type in range(1,self.maxtype+1):
print >>f,"part" print("part", file=f)
print >>f,"%10d" % type print("%10d" % type, file=f)
print >>f,"coordinates" print("coordinates", file=f)
group = [values[i] for i in xrange(len(atoms)) group = [values[i] for i in range(len(atoms))
if int(atoms[i][1]) == type] 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 # write Ensight variable values for elements
def variable_file_elements(self,f,name,etype,values): def variable_file_elements(self,f,name,etype,values):
print >>f,"Element %s" % name print("Element %s" % name, file=f)
print >>f,"part" print("part", file=f)
print >>f,"%10d" % 1 print("%10d" % 1, file=f)
if etype == 5: print >>f,"tria3" if etype == 5: print("tria3", file=f)
elif etype == 6: print >>f,"tetra4" elif etype == 6: print("tetra4", file=f)
for value in values: print >>f,"%12.5e" % value for value in values: print("%12.5e" % value, file=f)

100
src/gl.py
View File

@ -8,6 +8,16 @@
# gl tool # gl tool
# Imports and external programs
from __future__ import print_function, absolute_import
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" oneline = "3d interactive visualization via OpenGL"
docstr = """ docstr = """
@ -16,8 +26,8 @@ g = gl(d) create OpenGL display for data in d
d = atom snapshot object (dump, data) d = atom snapshot object (dump, data)
g.bg("black") set background color (def = "black") g.bg("black") set background color (def = "black")
g.size(N) set image size to NxN g.size(N) set image size to NxN
g.size(N,M) set image size to NxM g.size(N,M) set image size to NxM
g.rotate(60,135) view from z theta and azimuthal phi (def = 60,30) g.rotate(60,135) view from z theta and azimuthal phi (def = 60,30)
g.shift(x,y) translate by x,y pixels in view window (def = 0,0) g.shift(x,y) translate by x,y pixels in view window (def = 0,0)
g.zoom(0.5) scale image by factor (def = 1) g.zoom(0.5) scale image by factor (def = 1)
@ -43,9 +53,9 @@ g.select = "" no extra aselect (default)
%g varies from 0.0 to 1.0 from beginning to end of all() %g varies from 0.0 to 1.0 from beginning to end of all()
g.acol(2,"green") set atom colors by atom type (1-N) g.acol(2,"green") set atom colors by atom type (1-N)
g.acol([2,4],["red","blue"]) 1st arg = one type or list of types g.acol([2,4],["red","blue"]) 1st arg = one type or list of types
g.acol(0,"blue") 2nd arg = one color or list of colors g.acol(0,"blue") 2nd arg = one color or list of colors
g.acol(range(20),["red","blue"]) if list lengths unequal, interpolate g.acol(range(20),["red","blue"]) if list lengths unequal, interpolate
g.acol(range(10),"loop") assign colors in loop, randomly ordered g.acol(range(10),"loop") assign colors in loop, randomly ordered
@ -55,19 +65,19 @@ g.acol(range(10),"loop") assign colors in loop, randomly ordered
g.arad([1,2],[0.5,0.3]) set atom radii, same rules as acol() g.arad([1,2],[0.5,0.3]) set atom radii, same rules as acol()
g.bcol() set bond color, same args as acol() g.bcol() set bond color, same args as acol()
g.brad() set bond thickness, same args as arad() g.brad() set bond thickness, same args as arad()
g.tcol() set triangle color, same args as acol() g.tcol() set triangle color, same args as acol()
g.tfill() set triangle fill, 0 fill, 1 line, 2 both g.tfill() set triangle fill, 0 fill, 1 line, 2 both
g.lcol() set line color, same args as acol() g.lcol() set line color, same args as acol()
g.lrad() set line thickness, same args as arad() g.lrad() set line thickness, same args as arad()
g.adef() set atom/bond/tri/line properties to default g.adef() set atom/bond/tri/line properties to default
g.bdef() default = "loop" for colors, 0.45 for radii g.bdef() default = "loop" for colors, 0.45 for radii
g.tdef() default = 0.25 for bond/line thickness g.tdef() default = 0.25 for bond/line thickness
g.ldef() default = 0 fill g.ldef() default = 0 fill
by default 100 types are assigned by default 100 types are assigned
if atom/bond/tri/line has type > # defined properties, is an error if atom/bond/tri/line has type > # defined properties, is an error
@ -122,14 +132,6 @@ g.sview(theta,phi,x,y,scale,up) set all view parameters
# up[3] = screen up direction in simulation box (unit vector) # up[3] = screen up direction in simulation box (unit vector)
# right[3] = screen right 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 definition
class gl: class gl:
@ -312,7 +314,7 @@ class gl:
self.up[1] = sin(pi*self.azphi/180) self.up[1] = sin(pi*self.azphi/180)
self.up[2] = 0.0 self.up[2] = 0.0
else: else:
dot = self.view[2] # dot = (0,0,1) . view dot = self.view[2] # dot = (0,0,1) . view
self.up[0] = -dot*self.view[0] # up projected onto v = dot * v self.up[0] = -dot*self.view[0] # up projected onto v = dot * v
self.up[1] = -dot*self.view[1] # up perp to v = up - dot * v self.up[1] = -dot*self.view[1] # up perp to v = up - dot * v
self.up[2] = 1.0 - dot*self.view[2] self.up[2] = 1.0 - dot*self.view[2]
@ -442,8 +444,8 @@ class gl:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def shift(self,x,y): def shift(self,x,y):
self.xshift = x; self.xshift = x
self.yshift = y; self.yshift = y
self.setview() self.setview()
self.w.tkRedraw() self.w.tkRedraw()
@ -500,7 +502,7 @@ class gl:
# add GL-specific info to each bond # add GL-specific info to each bond
def reload(self): def reload(self):
print "Loading data into gl tool ..." print("Loading data into gl tool ...")
data = self.data data = self.data
self.timeframes = [] self.timeframes = []
@ -528,9 +530,9 @@ class gl:
self.triframes.append(tris) self.triframes.append(tris)
self.lineframes.append(lines) self.lineframes.append(lines)
print time, print(time, end=' ')
sys.stdout.flush() sys.stdout.flush()
print print()
self.nframes = len(self.timeframes) self.nframes = len(self.timeframes)
self.distance = compute_distance(self.boxframes[0]) self.distance = compute_distance(self.boxframes[0])
@ -636,7 +638,7 @@ class gl:
fraction*(self.scale_stop - self.scale_start) fraction*(self.scale_stop - self.scale_start)
self.viewupright() self.viewupright()
if n == nstart or self.panflag: self.center = compute_center(box) if n == nstart or self.panflag: self.center = compute_center(box)
if bonds: self.bonds_augment(bonds) if bonds: self.bonds_augment(bonds)
@ -652,7 +654,7 @@ class gl:
self.w.tkRedraw() self.w.tkRedraw()
self.save(file) self.save(file)
print time, print(time, end=' ')
sys.stdout.flush() sys.stdout.flush()
i += 1 i += 1
n += 1 n += 1
@ -691,7 +693,7 @@ class gl:
fraction*(self.scale_stop - self.scale_start) fraction*(self.scale_stop - self.scale_start)
self.viewupright() self.viewupright()
if n == nstart or self.panflag: self.center = compute_center(box) if n == nstart or self.panflag: self.center = compute_center(box)
if bonds: self.bonds_augment(bonds) if bonds: self.bonds_augment(bonds)
@ -707,11 +709,11 @@ class gl:
self.w.tkRedraw() self.w.tkRedraw()
self.save(file) self.save(file)
print n, print(n, end=' ')
sys.stdout.flush() sys.stdout.flush()
n += 1 n += 1
print "\n%d images" % ncount print("\n%d images" % ncount)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -777,11 +779,11 @@ class gl:
ncolor = self.vizinfo.nlcolor ncolor = self.vizinfo.nlcolor
for line in self.linedraw: for line in self.linedraw:
itype = int(line[1]) 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] red,green,blue = self.vizinfo.lcolor[itype]
glColor3f(red,green,blue) glColor3f(red,green,blue)
thick = self.vizinfo.lrad[itype] thick = self.vizinfo.lrad[itype]
glLineWidth(thick) glLineWidth(thick)
glBegin(GL_LINES) glBegin(GL_LINES)
glVertex3f(line[2],line[3],line[4]) glVertex3f(line[2],line[3],line[4])
glVertex3f(line[5],line[6],line[7]) glVertex3f(line[5],line[6],line[7])
@ -826,7 +828,7 @@ class gl:
for bond in self.bonddraw: for bond in self.bonddraw:
if bond[10] > bound: continue if bond[10] > bound: continue
itype = int(bond[1]) 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] red,green,blue = self.vizinfo.bcolor[itype]
rad = self.vizinfo.brad[itype] rad = self.vizinfo.brad[itype]
glPushMatrix() glPushMatrix()
@ -849,7 +851,7 @@ class gl:
ncolor = self.vizinfo.ntcolor ncolor = self.vizinfo.ntcolor
for tri in self.tridraw: for tri in self.tridraw:
itype = int(tri[1]) 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] red,green,blue = self.vizinfo.tcolor[itype]
glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION,[red,green,blue,1.0]); glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION,[red,green,blue,1.0]);
glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,self.shiny); glMaterialf(GL_FRONT_AND_BACK,GL_SHININESS,self.shiny);
@ -907,7 +909,7 @@ class gl:
ymin >= ylo and ymax <= yhi and zmin >= zlo and zmax <= zhi: ymin >= ylo and ymax <= yhi and zmin >= zlo and zmax <= zhi:
if bond[10] > bound: continue if bond[10] > bound: continue
itype = int(bond[1]) 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] red,green,blue = self.vizinfo.bcolor[itype]
rad = self.vizinfo.brad[itype] rad = self.vizinfo.brad[itype]
glPushMatrix() glPushMatrix()
@ -939,7 +941,7 @@ class gl:
ymin >= ylo and ymax <= yhi and \ ymin >= ylo and ymax <= yhi and \
zmin >= zlo and zmax <= zhi: zmin >= zlo and zmax <= zhi:
itype = int(tri[1]) 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] red,green,blue = self.vizinfo.tcolor[itype]
glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION, glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION,
[red,green,blue,1.0]); [red,green,blue,1.0]);
@ -991,7 +993,7 @@ class gl:
# create new calllist for each atom type # 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) if self.calllist[itype]: glDeleteLists(self.calllist[itype],1)
ilist = glGenLists(1) ilist = glGenLists(1)
self.calllist[itype] = ilist self.calllist[itype] = ilist
@ -1101,7 +1103,8 @@ class gl:
pstring = glReadPixels(0,0,self.xpixels,self.ypixels, pstring = glReadPixels(0,0,self.xpixels,self.ypixels,
GL_RGBA,GL_UNSIGNED_BYTE) 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) snapshot = snapshot.transpose(Image.FLIP_TOP_BOTTOM)
if not file: file = self.file if not file: file = self.file
@ -1110,8 +1113,11 @@ class gl:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def adef(self): def adef(self):
self.vizinfo.setcolors("atom",range(100),"loop") rlist = list(range(100))
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)
self.vizinfo.setcolors("atom",rlist,"loop")
self.vizinfo.setradii("atom",rlist,0.45)
self.make_atom_calllist() self.make_atom_calllist()
self.cachelist = -self.cachelist self.cachelist = -self.cachelist
self.w.tkRedraw() self.w.tkRedraw()
@ -1119,24 +1125,24 @@ class gl:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def bdef(self): def bdef(self):
self.vizinfo.setcolors("bond",range(100),"loop") self.vizinfo.setcolors("bond",list(range(100)),"loop")
self.vizinfo.setradii("bond",range(100),0.25) self.vizinfo.setradii("bond",list(range(100)),0.25)
self.cachelist = -self.cachelist self.cachelist = -self.cachelist
self.w.tkRedraw() self.w.tkRedraw()
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def tdef(self): def tdef(self):
self.vizinfo.setcolors("tri",range(100),"loop") self.vizinfo.setcolors("tri",list(range(100)),"loop")
self.vizinfo.setfills("tri",range(100),0) self.vizinfo.setfills("tri",list(range(100)),0)
self.cachelist = -self.cachelist self.cachelist = -self.cachelist
self.w.tkRedraw() self.w.tkRedraw()
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def ldef(self): def ldef(self):
self.vizinfo.setcolors("line",range(100),"loop") self.vizinfo.setcolors("line",list(range(100)),"loop")
self.vizinfo.setradii("line",range(100),0.25) self.vizinfo.setradii("line",list(range(100)),0.25)
self.cachelist = -self.cachelist self.cachelist = -self.cachelist
self.w.tkRedraw() self.w.tkRedraw()

View File

@ -8,15 +8,20 @@
# gnu tool # gnu tool
# Imports and external programs
from __future__ import print_function, division, absolute_import
import types, os
oneline = "Create plots via GnuPlot plotting program" oneline = "Create plots via GnuPlot plotting program"
docstr = """ docstr = """
g = gnu() start up GnuPlot g = gnu() start up GnuPlot
g.stop() shut down GnuPlot process g.stop() shut down GnuPlot process
g.plot(a) plot vector A against linear index g.plot(a) plot vector A against linear index
g.plot(a,b) plot B against A g.plot(a,b) plot B against A
g.plot(a,b,c,d,...) plot B against A, D against C, etc g.plot(a,b,c,d,...) plot B against A, D against C, etc
g.mplot(M,N,S,"file",a,b,...) multiple plots saved to file0000.eps, etc g.mplot(M,N,S,"file",a,b,...) multiple plots saved to file0000.eps, etc
each plot argument can be a tuple, list, or Numeric/NumPy vector each plot argument can be a tuple, list, or Numeric/NumPy vector
@ -29,21 +34,21 @@ g.mplot(M,N,S,"file",a,b,...) multiple plots saved to file0000.eps, etc
g("plot 'file.dat' using 2:3 with lines") execute string in GnuPlot g("plot 'file.dat' using 2:3 with lines") execute string in GnuPlot
g.enter() enter GnuPlot shell g.enter() enter GnuPlot shell
gnuplot> plot sin(x) with lines type commands directly to GnuPlot gnuplot> plot sin(x) with lines type commands directly to GnuPlot
gnuplot> exit, quit exit GnuPlot shell gnuplot> exit, quit exit GnuPlot shell
g.export("data",range(100),a,...) create file with columns of numbers g.export("data",range(100),a,...) create file with columns of numbers
all vectors must be of equal length all vectors must be of equal length
could plot from file with GnuPlot command: plot 'data' using 1:2 with lines could plot from file with GnuPlot command: plot 'data' using 1:2 with lines
g.select(N) figure N becomes the current plot g.select(N) figure N becomes the current plot
subsequent commands apply to this plot subsequent commands apply to this plot
g.hide(N) delete window for figure N g.hide(N) delete window for figure N
g.save("file") save current plot as file.eps g.save("file") save current plot as file.eps
Set attributes for current plot: Set attributes for current plot:
@ -82,10 +87,6 @@ g.curve(N,'r') set color of curve N
# figures = list of figure objects with each plot's attributes # figures = list of figure objects with each plot's attributes
# so they aren't lost between replots # so they aren't lost between replots
# Imports and external programs
import types, os
try: from DEFAULTS import PIZZA_GNUPLOT try: from DEFAULTS import PIZZA_GNUPLOT
except: PIZZA_GNUPLOT = "gnuplot" except: PIZZA_GNUPLOT = "gnuplot"
try: from DEFAULTS import PIZZA_GNUTERM try: from DEFAULTS import PIZZA_GNUTERM
@ -119,7 +120,7 @@ class gnu:
def enter(self): def enter(self):
while 1: while 1:
command = raw_input("gnuplot> ") command = input("gnuplot> ")
if command == "quit" or command == "exit": return if command == "quit" or command == "exit": return
self.__call__(command) self.__call__(command)
@ -129,15 +130,15 @@ class gnu:
def plot(self,*vectors): def plot(self,*vectors):
if len(vectors) == 1: if len(vectors) == 1:
file = self.file + ".%d.1" % self.current 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.export(file,linear,vectors[0])
self.figures[self.current-1].ncurves = 1 self.figures[self.current-1].ncurves = 1
else: 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): 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.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() self.draw()
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -167,13 +168,13 @@ class gnu:
def export(self,filename,*vectors): def export(self,filename,*vectors):
n = len(vectors[0]) n = len(vectors[0])
for vector in vectors: 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') f = open(filename,'w')
nvec = len(vectors) nvec = len(vectors)
for i in xrange(n): for i in range(n):
for j in xrange(nvec): for j in range(nvec):
print >>f,vectors[j][i], print(vectors[j][i], end=' ', file=f)
print >>f print(file=f)
f.close() f.close()
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -353,7 +354,7 @@ class gnu:
for i in range(fig.ncurves): for i in range(fig.ncurves):
file = self.file + ".%d.%d" % (self.current,i+1) file = self.file + ".%d.%d" % (self.current,i+1)
if len(fig.colors) > i and fig.colors[i]: 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: else:
cmd += "'" + file + "' using 1:2 with lines, " cmd += "'" + file + "' using 1:2 with lines, "
self.__call__(cmd[:-2]) self.__call__(cmd[:-2])

View File

@ -43,7 +43,7 @@ class histo:
if dim == 'x': idim = 2 if dim == 'x': idim = 2
elif dim == 'y': idim = 3 elif dim == 'y': idim = 3
elif dim == 'z': idim = 4 elif dim == 'z': idim = 4
else: raise StandardError,"illegal dim value" else: raise Exception("illegal dim value")
y = nbins*[0] y = nbins*[0]
@ -78,9 +78,9 @@ class histo:
n += 1 n += 1
x = nbins*[0] 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 snapshots = ",n)
print "histogram counts (per snap) = %d (%g)" % (count,float(count)/n) print("histogram counts (per snap) = %d (%g)" % (count,float(count)/n))
print "histogram bounds = ",lo,hi print("histogram bounds = ",lo,hi)
return x,y return x,y

View File

@ -8,19 +8,35 @@
# image tool # image tool
# Imports and external programs
from __future__ import print_function, absolute_import
import sys, os, re, glob
try:
import commands
except ImportError:
import subprocess as commands
from math import *
try:
from Tkinter import *
except ImportError:
from tkinter import *
import Pmw
from PIL import Image
oneline = "View and manipulate images" oneline = "View and manipulate images"
docstr = """ docstr = """
i = image("my1.gif my2.gif") display thumbnails of matching images i = image("my1.gif my2.gif") display thumbnails of matching images
i = image("*.png *.gif") wildcards allowed i = image("*.png *.gif") wildcards allowed
i = image("") blank string matches all image suffixes i = image("") blank string matches all image suffixes
i = image() no display window opened if no arg i = image() no display window opened if no arg
image suffixes for blank string = *.png, *.bmp, *.gif, *.tiff, *.tif image suffixes for blank string = *.png, *.bmp, *.gif, *.tiff, *.tif
click on a thumbnail to view it full-size click on a thumbnail to view it full-size
click on thumbnail again to remove full-sized version click on thumbnail again to remove full-sized version
i.view("*.png *.gif") display thumbnails of matching images i.view("*.png *.gif") display thumbnails of matching images
view arg is same as constructor arg view arg is same as constructor arg
@ -46,14 +62,6 @@ i.montage("-geometry 512x512","i*.png","new.png") 1st arg is switch
# Variables # 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 try: from DEFAULTS import PIZZA_CONVERT
except: PIZZA_CONVERT = "convert" except: PIZZA_CONVERT = "convert"
try: from DEFAULTS import PIZZA_MONTAGE try: from DEFAULTS import PIZZA_MONTAGE
@ -77,7 +85,7 @@ class image:
list = str.split(filestr) list = str.split(filestr)
files = [] files = []
for file in list: files += glob.glob(file) 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 # grab Tk instance from main
@ -93,7 +101,7 @@ class image:
pane = scroll.interior() pane = scroll.interior()
ncolumns = 4 ncolumns = 4
for i in xrange(len(files)): for i in range(len(files)):
# create new row frame if 1st in column # create new row frame if 1st in column
@ -107,7 +115,7 @@ class image:
imt.thumbnail((60,60),Image.ANTIALIAS) imt.thumbnail((60,60),Image.ANTIALIAS)
basename = os.path.basename(files[i]) basename = os.path.basename(files[i])
imt.save("tmp." + basename) imt.save("tmp." + basename)
thumbnail = ImageTk.PhotoImage(file = "tmp." + basename) thumbnail = PhotoImage(file = "tmp." + basename)
os.remove("tmp." + basename) os.remove("tmp." + basename)
# read in full size image # read in full size image
@ -115,7 +123,7 @@ class image:
# create button that calls the thumbnail, label with filename # create button that calls the thumbnail, label with filename
# buttton needs to store thumbnail else it is garbage collected # 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) obj = thumbnails(gui,files[i],big,thumbnail)
Button(oneframe,image=thumbnail,command=obj.display).pack(side=TOP) Button(oneframe,image=thumbnail,command=obj.display).pack(side=TOP)
Label(oneframe,text=basename).pack(side=BOTTOM) Label(oneframe,text=basename).pack(side=BOTTOM)
@ -150,17 +158,17 @@ class image:
middle = re.search(expr,file1).group(1) middle = re.search(expr,file1).group(1)
file2 = "%s%s%s" % (pre2,middle,post2) file2 = "%s%s%s" % (pre2,middle,post2)
cmd = "%s %s %s %s" % (PIZZA_CONVERT,switch,file1,file2) cmd = "%s %s %s %s" % (PIZZA_CONVERT,switch,file1,file2)
print middle, print(middle, end=' ')
sys.stdout.flush() sys.stdout.flush()
commands.getoutput(cmd) commands.getoutput(cmd)
print print()
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# wrapper on ImageMagick montage command # wrapper on ImageMagick montage command
def montage(self,switch,*fileargs): def montage(self,switch,*fileargs):
nsets = len(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): for i in range(nsets):
if fileargs[i].find('*') < 0: if fileargs[i].find('*') < 0:
@ -174,7 +182,7 @@ class image:
for i in range(nsets-1): for i in range(nsets-1):
filesets.append(glob.glob(fileargs[i])) filesets.append(glob.glob(fileargs[i]))
if len(filesets[-1]) != nfiles: 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('*') index = fileargs[0].index('*')
pre1 = fileargs[0][:index] pre1 = fileargs[0][:index]
@ -191,9 +199,9 @@ class image:
fileN = "%s%s%s" % (preN,middle,postN) fileN = "%s%s%s" % (preN,middle,postN)
cmd += " %s" % fileN cmd += " %s" % fileN
commands.getoutput(cmd) commands.getoutput(cmd)
print middle, print(middle, end=' ')
sys.stdout.flush() sys.stdout.flush()
print print()
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# thumbnail class # thumbnail class
@ -216,7 +224,7 @@ class thumbnails:
self.bigexist = 0 self.bigexist = 0
if self.window: if self.window:
self.window.destroy() self.window.destroy()
self.window = None self.window = None
# create a new window with the big image # create a new window with the big image

View File

@ -8,18 +8,25 @@
# ldump tool # ldump tool
# Imports and external programs
from __future__ import print_function, absolute_import
import sys, re, glob, types
import functools
from os import popen
oneline = "Read dump files with line segment info" oneline = "Read dump files with line segment info"
docstr = """ docstr = """
l = ldump("dump.one") read in one or more dump files l = ldump("dump.one") read in one or more dump files
l = ldump("dump.1 dump.2.gz") can be gzipped l = ldump("dump.1 dump.2.gz") can be gzipped
l = ldump("dump.*") wildcard expands to multiple files l = ldump("dump.*") wildcard expands to multiple files
l = ldump("dump.*",0) two args = store filenames, but don't read l = ldump("dump.*",0) two args = store filenames, but don't read
incomplete and duplicate snapshots are deleted incomplete and duplicate snapshots are deleted
no column name assignment is performed no column name assignment is performed
time = l.next() read next snapshot from dump files time = l.next() read next snapshot from dump files
used with 2-argument constructor to allow reading snapshots one-at-a-time used with 2-argument constructor to allow reading snapshots one-at-a-time
snapshot will be skipped only if another snapshot has same time stamp snapshot will be skipped only if another snapshot has same time stamp
@ -43,7 +50,7 @@ time,box,atoms,bonds,tris,lines = l.viz(index) return list of viz objects
lines = id,type,x1,y1,z1,x2,y2,z2 for each line as 2d array lines = id,type,x1,y1,z1,x2,y2,z2 for each line as 2d array
id,type are from associated atom id,type are from associated atom
l.owrap(...) wrap lines to same image as their atoms l.owrap(...) wrap lines to same image as their atoms
owrap() is called by dump tool's owrap() owrap() is called by dump tool's owrap()
useful for wrapping all molecule's atoms/lines the same so it is contiguous useful for wrapping all molecule's atoms/lines the same so it is contiguous
@ -67,11 +74,6 @@ l.owrap(...) wrap lines to same image as their atoms
# xlo,xhi,ylo,yhi,zlo,zhi = box bounds (float) # 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 # 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: try:
import numpy as np import numpy as np
oldnumeric = False oldnumeric = False
@ -99,7 +101,7 @@ class ldump:
self.flist = [] self.flist = []
for word in words: self.flist += glob.glob(word) for word in words: self.flist += glob.glob(word)
if len(self.flist) == 0 and len(list) == 1: 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: if len(list) == 1:
self.increment = 0 self.increment = 0
@ -124,26 +126,26 @@ class ldump:
snap = self.read_snapshot(f) snap = self.read_snapshot(f)
while snap: while snap:
self.snaps.append(snap) self.snaps.append(snap)
print snap.time, print(snap.time, end=' ')
sys.stdout.flush() sys.stdout.flush()
snap = self.read_snapshot(f) snap = self.read_snapshot(f)
f.close() f.close()
print print()
# sort entries by timestep, cull duplicates # 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.cull()
self.nsnaps = len(self.snaps) self.nsnaps = len(self.snaps)
print "read %d snapshots" % self.nsnaps print("read %d snapshots" % self.nsnaps)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# read next snapshot from list of files # read next snapshot from list of files
def next(self): 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 # read next snapshot in current file using eof as pointer
# if fail, try next file # if fail, try next file
@ -155,15 +157,15 @@ class ldump:
snap = self.read_snapshot(f) snap = self.read_snapshot(f)
if not snap: if not snap:
self.nextfile += 1 self.nextfile += 1
if self.nextfile == len(self.flist): return -1 if self.nextfile == len(self.flist): return -1
f.close() f.close()
self.eof = 0 self.eof = 0
continue continue
self.eof = f.tell() self.eof = f.tell()
f.close() f.close()
try: try:
self.findtime(snap.time) self.findtime(snap.time)
continue continue
except: break except: break
self.snaps.append(snap) self.snaps.append(snap)
@ -197,14 +199,14 @@ class ldump:
if snap.natoms: if snap.natoms:
words = f.readline().split() words = f.readline().split()
ncol = len(words) ncol = len(words)
for i in xrange(1,snap.natoms): for i in range(1,snap.natoms):
words += f.readline().split() words += f.readline().split()
floats = map(float,words) floats = list(map(float,words))
if oldnumeric: atoms = np.zeros((snap.natoms,ncol),np.Float) if oldnumeric: atoms = np.zeros((snap.natoms,ncol),np.Float)
else: atoms = np.zeros((snap.natoms,ncol),np.float) else: atoms = np.zeros((snap.natoms,ncol),np.float)
start = 0 start = 0
stop = ncol stop = ncol
for i in xrange(snap.natoms): for i in range(snap.natoms):
atoms[i] = floats[start:stop] atoms[i] = floats[start:stop]
start = stop start = stop
stop += ncol stop += ncol
@ -219,7 +221,7 @@ class ldump:
def map(self,*pairs): def map(self,*pairs):
if len(pairs) % 2 != 0: 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): for i in range(0,len(pairs),2):
j = i + 1 j = i + 1
self.names[pairs[j]] = pairs[i]-1 self.names[pairs[j]] = pairs[i]-1
@ -249,9 +251,9 @@ class ldump:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def findtime(self,n): def findtime(self,n):
for i in xrange(self.nsnaps): for i in range(self.nsnaps):
if self.snaps[i].time == n: return i 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 # 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 # don't add line if all 4 values are 0 since not a line
lines = [] lines = []
for i in xrange(snap.natoms): for i in range(snap.natoms):
atom = snap.atoms[i] atom = snap.atoms[i]
e1x = atom[end1x] e1x = atom[end1x]
e1y = atom[end1y] e1y = atom[end1y]
@ -323,7 +325,7 @@ class ldump:
# jdump = atom J in dump's atoms that atom I was owrapped on # 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 # 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] tag = atoms[i][id]
idump = idsdump[tag] idump = idsdump[tag]
jdump = idsdump[atomsdump[idump][iother]] jdump = idsdump[atomsdump[idump][iother]]

View File

@ -8,6 +8,13 @@
# log tool # log tool
# Imports and external programs
from __future__ import print_function, absolute_import
import sys, re, glob
import functools
from os import popen
oneline = "Read LAMMPS log files and extract thermodynamic data" oneline = "Read LAMMPS log files and extract thermodynamic data"
docstr = """ docstr = """
@ -28,7 +35,7 @@ nvec = l.nvec # of vectors of thermo info
nlen = l.nlen length of each vectors nlen = l.nlen length of each vectors
names = l.names list of vector names names = l.names list of vector names
t,pe,... = l.get("Time","KE",...) return one or more vectors of values t,pe,... = l.get("Time","KE",...) return one or more vectors of values
l.write("file.txt") write all vectors to a file l.write("file.txt") write all vectors to a file
l.write("file.txt","Time","PE",...) write listed vectors to a file l.write("file.txt","Time","PE",...) write listed vectors to a file
get and write allow abbreviated (uniquely) vector names get and write allow abbreviated (uniquely) vector names
@ -50,11 +57,6 @@ l.write("file.txt","Time","PE",...) write listed vectors to a file
# increment = 1 if log file being read incrementally # increment = 1 if log file being read incrementally
# eof = ptr into incremental file for where to start next read # 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 try: tmp = PIZZA_GUNZIP
except: PIZZA_GUNZIP = "gunzip" except: PIZZA_GUNZIP = "gunzip"
@ -76,14 +78,14 @@ class log:
self.flist = [] self.flist = []
for word in words: self.flist += glob.glob(word) for word in words: self.flist += glob.glob(word)
if len(self.flist) == 0 and len(list) == 1: 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: if len(list) == 1:
self.increment = 0 self.increment = 0
self.read_all() self.read_all()
else: else:
if len(self.flist) > 1: 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.increment = 1
self.eof = 0 self.eof = 0
@ -92,24 +94,24 @@ class log:
def read_all(self): def read_all(self):
self.read_header(self.flist[0]) 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 # read all files
for file in self.flist: self.read_one(file) for file in self.flist: self.read_one(file)
print print()
# sort entries by timestep, cull duplicates # sort entries by timestep, cull duplicates
self.data.sort(self.compare) self.data.sort(key = functools.cmp_to_key(self.compare))
self.cull() self.cull()
self.nlen = len(self.data) self.nlen = len(self.data)
print "read %d log entries" % self.nlen print("read %d log entries" % self.nlen)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def next(self): 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: if self.nvec == 0:
try: open(self.flist[0],'r') try: open(self.flist[0],'r')
@ -124,27 +126,27 @@ class log:
def get(self,*keys): def get(self,*keys):
if len(keys) == 0: if len(keys) == 0:
raise StandardError, "no log vectors specified" raise Exception("no log vectors specified")
map = [] map = []
for key in keys: for key in keys:
if self.ptr.has_key(key): if key in self.ptr:
map.append(self.ptr[key]) map.append(self.ptr[key])
else: else:
count = 0 count = 0
for i in range(self.nvec): for i in range(self.nvec):
if self.names[i].find(key) == 0: if self.names[i].find(key) == 0:
count += 1 count += 1
index = i index = i
if count == 1: if count == 1:
map.append(index) map.append(index)
else: else:
raise StandardError, "unique log vector %s not found" % key raise Exception("unique log vector %s not found" % key)
vecs = [] vecs = []
for i in range(len(keys)): for i in range(len(keys)):
vecs.append(self.nlen * [0]) 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]] vecs[i][j] = self.data[j][map[i]]
if len(keys) == 1: return vecs[0] if len(keys) == 1: return vecs[0]
@ -156,26 +158,26 @@ class log:
if len(keys): if len(keys):
map = [] map = []
for key in keys: for key in keys:
if self.ptr.has_key(key): if key in self.ptr:
map.append(self.ptr[key]) map.append(self.ptr[key])
else: else:
count = 0 count = 0
for i in range(self.nvec): for i in range(self.nvec):
if self.names[i].find(key) == 0: if self.names[i].find(key) == 0:
count += 1 count += 1
index = i index = i
if count == 1: if count == 1:
map.append(index) map.append(index)
else: else:
raise StandardError, "unique log vector %s not found" % key raise Exception("unique log vector %s not found" % key)
else: else:
map = range(self.nvec) map = list(range(self.nvec))
f = open(filename,"w") f = open(filename,"w")
for i in xrange(self.nlen): for i in range(self.nlen):
for j in xrange(len(map)): for j in range(len(map)):
print >>f,self.data[i][map[j]], print(self.data[i][map[j]], end=' ', file=f)
print >>f print(file=f)
f.close() f.close()
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -224,7 +226,7 @@ class log:
keywords.insert(0,"Step") keywords.insert(0,"Step")
i = 0 i = 0
for keyword in keywords: for keyword in keywords:
self.names.append(keyword) self.names.append(keyword)
self.ptr[keyword] = i self.ptr[keyword] = i
i += 1 i += 1
@ -234,25 +236,25 @@ class log:
line = txt[s1:s2] line = txt[s1:s2]
words = line.split() words = line.split()
for i in range(len(words)): for i in range(len(words)):
self.names.append(words[i]) self.names.append(words[i])
self.ptr[words[i]] = i self.ptr[words[i]] = i
self.nvec = len(self.names) self.nvec = len(self.names)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def read_one(self,*list): def read_one(self,*flist):
# if 2nd arg exists set file ptr to that value # if 2nd arg exists set file ptr to that value
# read entire (rest of) file into txt # read entire (rest of) file into txt
file = list[0] file = flist[0]
if file[-3:] == ".gz": if file[-3:] == ".gz":
f = popen("%s -c %s" % (PIZZA_GUNZIP,file),'rb') f = popen("%s -c %s" % (PIZZA_GUNZIP,file),'r')
else: 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() txt = f.read()
if file[-3:] == ".gz": eof = 0 if file[-3:] == ".gz": eof = 0
else: eof = f.tell() else: eof = f.tell()
@ -273,36 +275,36 @@ class log:
if s1 >= 0 and s2 >= 0 and s1 < s2: # found s1,s2 with s1 before s2 if s1 >= 0 and s2 >= 0 and s1 < s2: # found s1,s2 with s1 before s2
if self.style == 2: if self.style == 2:
s1 = txt.find("\n",s1) + 1 s1 = txt.find("\n",s1) + 1
elif s1 >= 0 and s2 >= 0 and s2 < s1: # found s1,s2 with s2 before s1 elif s1 >= 0 and s2 >= 0 and s2 < s1: # found s1,s2 with s2 before s1
s1 = 0 s1 = 0
elif s1 == -1 and s2 >= 0: # found s2, but no s1 elif s1 == -1 and s2 >= 0: # found s2, but no s1
last = 1 last = 1
s1 = 0 s1 = 0
elif s1 >= 0 and s2 == -1: # found s1, but no s2 elif s1 >= 0 and s2 == -1: # found s1, but no s2
last = 1 last = 1
if self.style == 1: if self.style == 1:
s2 = txt.rfind("\n--",s1) + 1 s2 = txt.rfind("\n--",s1) + 1
else: else:
s1 = txt.find("\n",s1) + 1 s1 = txt.find("\n",s1) + 1
s2 = txt.rfind("\n",s1) + 1 s2 = txt.rfind("\n",s1) + 1
eof -= len(txt) - s2 eof -= len(txt) - s2
elif s1 == -1 and s2 == -1: # found neither elif s1 == -1 and s2 == -1: # found neither
# could be end-of-file section # could be end-of-file section
# or entire read was one chunk # or entire read was one chunk
if txt.find("Loop time of",start) == start: # end of file, so exit if txt.find("Loop time of",start) == start: # end of file, so exit
eof -= len(txt) - start # reset eof to "Loop" eof -= len(txt) - start # reset eof to "Loop"
break break
last = 1 # entire read is a chunk last = 1 # entire read is a chunk
s1 = 0 s1 = 0
if self.style == 1: if self.style == 1:
s2 = txt.rfind("\n--",s1) + 1 s2 = txt.rfind("\n--",s1) + 1
else: else:
s2 = txt.rfind("\n",s1) + 1 s2 = txt.rfind("\n",s1) + 1
eof -= len(txt) - s2 eof -= len(txt) - s2
if s1 == s2: break if s1 == s2: break
chunk = txt[s1:s2-1] chunk = txt[s1:s2-1]
start = s2 start = s2
@ -318,17 +320,17 @@ class log:
word1 = [re.search(pat1,section).group(1)] word1 = [re.search(pat1,section).group(1)]
word2 = re.findall(pat2,section) word2 = re.findall(pat2,section)
words = word1 + word2 words = word1 + word2
self.data.append(map(float,words)) self.data.append(list(map(float,words)))
else: else:
lines = chunk.split("\n") lines = chunk.split("\n")
for line in lines: for line in lines:
words = line.split() words = line.split()
self.data.append(map(float,words)) self.data.append(list(map(float,words)))
# print last timestep of chunk # 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() sys.stdout.flush()
return eof return eof

View File

@ -1,32 +1,33 @@
#!/usr/bin/env python #!/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" oneline = "writing pp-data in vtk format automatically, saving memory"
docstr = """this is the docstr of LIGGGHTSPostProcessing""" 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 # changes py p.s. - include a few command line options
import getopt
class lpp: class lpp:
#============================================================================= # =============================================================================
# creates a filelist, seperates it to sublists # creates a filelist, seperates it to sublists
# creates multiple processes # creates multiple processes
# calls lppWorker for each sublist # calls lppWorker for each sublist
# lppWorker # lppWorker
# calls dump, vtk and manyGran for the given list of files # calls dump, vtk and manyGran for the given list of files
# returns 0 # returns 0
#============================================================================= # =============================================================================
def __init__(self, *list, **kwargs): def __init__(self, *list, **kwargs):
# do argument parsing, raise errors if non-integers were given # do argument parsing, raise errors if non-integers were given
@ -35,43 +36,66 @@ class lpp:
self.cpunum = multiprocessing.cpu_count() self.cpunum = multiprocessing.cpu_count()
self.chunksize = 8 self.chunksize = 8
self.overwrite = True self.overwrite = True
self.Nth = 1
self.timesteps = "all"
if "--chunksize" in kwargs: if "--chunksize" in kwargs:
try: try:
if int(kwargs["--chunksize"]) > 0: if int(kwargs["--chunksize"]) > 0:
self.chunksize = int(kwargs["--chunksize"]) self.chunksize = int(kwargs["--chunksize"])
else: raise ValueError else:
raise ValueError
except 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: if "--cpunum" in kwargs:
try: try:
if int(kwargs["--cpunum"]) > 0 and int(kwargs["--cpunum"]) <= self.cpunum: if int(kwargs["--cpunum"]) > 0 and int(kwargs["--cpunum"]) <= self.cpunum:
self.cpunum = int(kwargs["--cpunum"]) self.cpunum = int(kwargs["--cpunum"])
else: raise ValueError else:
raise ValueError
except 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 # do not overwrite existing files
if "--no-overwrite" in kwargs: if "--no-overwrite" in kwargs:
self.overwrite = False self.overwrite = False
# suppress output with 'False' # suppress output with 'False'
if "--debug" in kwargs: self.debugMode = True if "--debug" in kwargs:
else: self.debugMode = False self.debugMode = True
else:
self.debugMode = False
if "--quiet" in kwargs: if "--quiet" in kwargs:
self.output = False self.output = False
self.debugMode = False self.debugMode = False
else: self.output = True else:
self.output = True
if self.output: if self.output:
print "starting LIGGGHTS memory optimized parallel post processing" print("starting LIGGGHTS memory optimized parallel post processing")
print "chunksize:", self.chunksize, "-->",self.chunksize,\ print("chunksize:", self.chunksize, "-->",self.chunksize,\
"files are processed per chunk. If you run out of memory reduce chunksize." "files are processed per chunk. If you run out of memory reduce chunksize.")
starttime = time.time() 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 # check whether file-list is nonempty
self.flist = [] self.flist = []
@ -86,42 +110,47 @@ class lpp:
self.flist = list[0] self.flist = list[0]
listlen = len(self.flist) listlen = len(self.flist)
if listlen == 0 and len(list) == 1: 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: 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: if self.output:
print "Working with", self.cpunum, "processes..." print("Working with", self.cpunum, "processes...")
# seperate list in pieces+rest # seperate list in pieces+rest
self.slices = [] self.slices = []
residualPresent = int(bool(listlen-floor(listlen/self.chunksize)*self.chunksize)) 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] slice = self.flist[i*self.chunksize:(i+1)*self.chunksize]
self.slices.append(slice) self.slices.append(slice)
self.flist = [] self.flist = []
output = "" output = ""
if "-o" in kwargs: output = kwargs["-o"] if "-o" in kwargs:
output = kwargs["-o"]
# generate input for lppWorker # generate input for lppWorker
dumpInput = [{"filelist":self.slices[i],\ dumpInput = [{"filelist":self.slices[i],\
"debugMode":self.debugMode,\ "debugMode":self.debugMode,\
"output":output,\ "output":output,\
"overwrite":self.overwrite} \ "overwrite":self.overwrite,\
for i in xrange(len(self.slices))] "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) numberOfRuns = len(dumpInput)
i = 0 i = 0
while i < len(dumpInput): while i < len(dumpInput):
if self.output: 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 # create job_server
job_server = multiprocessing.Pool(processes = self.cpunum) job_server = multiprocessing.Pool(processes = self.cpunum)
@ -136,14 +165,16 @@ class lpp:
endtime = time.time() endtime = time.time()
if self.output: if self.output:
print "wrote", listlen,"granular snapshots in VTK format" print("wrote", listlen,"granular snapshots in VTK format")
print "time needed:",endtime-starttime,"sec" print("time needed:",endtime-starttime,"sec")
def lppWorker(input): def lppWorker(input):
flist = input["filelist"] flist = input["filelist"]
debugMode = input["debugMode"] debugMode = input["debugMode"]
outfileName = input["output"] outfileName = input["output"]
overwrite = input["overwrite"] overwrite = input["overwrite"]
Nth = input["Nth"]
timesteps = input["timesteps"]
flistlen = len(flist) flistlen = len(flist)
# generate name of manyGran # generate name of manyGran
@ -184,8 +215,25 @@ def lppWorker(input):
# call dump, vtk, manyGran on shortFlist # call dump, vtk, manyGran on shortFlist
try: try:
d = dump({"filelist":shortFlist, "debugMode":debugMode}) 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) 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) v.manyGran(granName,fileNos=d.fileNums,output=debugMode)
except KeyboardInterrupt: except KeyboardInterrupt:
raise raise
@ -193,21 +241,24 @@ def lppWorker(input):
return 0 return 0
def printHelp(): def printHelp():
print "usage: pizza [options] dump.example\n where dump.example is a filename",\ print("usage: pizza [options] dump.example\n where dump.example is a filename",\
"or regular expression passing all relevant dump files to pizza." "or regular expression passing all relevant dump files to pizza.")
print "Important command line options:" print("Important command line options:")
print "-o fname : define output file name (default is liggghts + timestep number)" print("-o fname : define output file name (default is liggghts + timestep number)")
print "--chunksize : sets the chunksize, default: 8" print("--chunksize : sets the chunksize, default: 8")
print "--cpunum : sets the number of processes to start, default (and maximum)",\ print("--cpunum : sets the number of processes to start, default (and maximum)",\
"is the amout of cpu cores avaliable at your system" "is the amout of cpu cores avaliable at your system")
print "--help : writes this help message and exits" print("--help : writes this help message and exits")
print "--no-overwrite: disables overwriting of already post-processed files." print("--no-overwrite: disables overwriting of already post-processed files.")
print "For details, read README_GRANULAR.txt" 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 __name__ == "__main__":
if len(sys.argv) > 1: if len(sys.argv) > 1:
# parse options # 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) optdict = dict(optlist)
if "--help" in optdict: if "--help" in optdict:
printHelp() printHelp()
@ -215,17 +266,17 @@ if __name__ == "__main__":
try: try:
lpp(args,**optdict) lpp(args,**optdict)
except KeyboardInterrupt: except KeyboardInterrupt:
print "aborted by user" print("aborted by user")
except BaseException, e: except BaseException as e:
print "aborting due to errors:", e print("aborting due to errors:", e)
#=========================================================================== # ===========================================================================
# except: # except:
# if sys.exc_type == exceptions.SystemExit: # if sys.exc_type == exceptions.SystemExit:
# pass # pass
# else: # else:
# print sys.exc_info() # print(sys.exc_info())
#=========================================================================== # ===========================================================================
else: else:
printHelp() printHelp()

View File

@ -8,15 +8,20 @@
# matlab tool # 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" oneline = "Create plots via MatLab numerical analysis program"
docstr = """ docstr = """
m = matlab() start up MatLab m = matlab() start up MatLab
m.stop() shut down MatLab process m.stop() shut down MatLab process
m.plot(a) plot vector A against linear index m.plot(a) plot vector A against linear index
m.plot(a,b) plot B against A m.plot(a,b) plot B against A
m.plot(a,b,c,d,...) plot B against A, D against C, etc m.plot(a,b,c,d,...) plot B against A, D against C, etc
m.mplot(M,N,S,"file",a,b,...) multiple plots saved to file0000.eps, etc m.mplot(M,N,S,"file",a,b,...) multiple plots saved to file0000.eps, etc
each plot argument can be a tuple, list, or Numeric/NumPy vector each plot argument can be a tuple, list, or Numeric/NumPy vector
@ -29,9 +34,9 @@ m.mplot(M,N,S,"file",a,b,...) multiple plots saved to file0000.eps, etc
m("c = a + b") execute string in MatLab m("c = a + b") execute string in MatLab
m.enter() enter MatLab shell m.enter() enter MatLab shell
matlab> c = a + b type commands directly to MatLab matlab> c = a + b type commands directly to MatLab
matlab> exit, quit exit MatLab shell matlab> exit, quit exit MatLab shell
m.export("data",range(100),a,...) create file with columns of numbers m.export("data",range(100),a,...) create file with columns of numbers
@ -40,12 +45,12 @@ m.export("data",range(100),a,...) create file with columns of numbers
cols = importdata('data') cols = importdata('data')
plot(cols(:,1),cols(:,2)) plot(cols(:,1),cols(:,2))
m.select(N) figure N becomes the current plot m.select(N) figure N becomes the current plot
subsequent commands apply to this plot subsequent commands apply to this plot
m.hide(N) delete window for figure N m.hide(N) delete window for figure N
m.save("file") save current plot as file.eps m.save("file") save current plot as file.eps
Set attributes for current plot: Set attributes for current plot:
@ -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 # allow for alternate export command to name the variables from Python
# in MatLab and vice versa # in MatLab and vice versa
# Imports and external programs
import types, os
try: from DEFAULTS import PIZZA_MATLAB try: from DEFAULTS import PIZZA_MATLAB
except: PIZZA_MATLAB = "matlab -nosplash -nodesktop -nojvm" except: PIZZA_MATLAB = "matlab -nosplash -nodesktop -nojvm"
@ -126,7 +127,7 @@ class matlab:
def enter(self): def enter(self):
while 1: while 1:
command = raw_input("matlab> ") command = input("matlab> ")
if command == "quit" or command == "exit": return if command == "quit" or command == "exit": return
self.__call__(command) self.__call__(command)
@ -136,15 +137,15 @@ class matlab:
def plot(self,*vectors): def plot(self,*vectors):
if len(vectors) == 1: if len(vectors) == 1:
file = self.file + ".%d.1" % self.current 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.export(file,linear,vectors[0])
self.figures[self.current-1].ncurves = 1 self.figures[self.current-1].ncurves = 1
else: 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): 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.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() self.draw()
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -174,13 +175,13 @@ class matlab:
def export(self,filename,*vectors): def export(self,filename,*vectors):
n = len(vectors[0]) n = len(vectors[0])
for vector in vectors: 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') f = open(filename,'w')
nvec = len(vectors) nvec = len(vectors)
for i in xrange(n): for i in range(n):
for j in xrange(nvec): for j in range(nvec):
print >>f,vectors[j][i], print(vectors[j][i], end=' ', file=f)
print >>f print(file=f)
f.close() f.close()
# -------------------------------------------------------------------- # --------------------------------------------------------------------

View File

@ -8,17 +8,25 @@
# mdump tool # mdump tool
# Imports and external programs
from __future__ import print_function, absolute_import
import sys, 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" oneline = "Read, write, manipulate mesh dump files"
docstr = """ docstr = """
m = mdump("mesh.one") read in one or more mesh dump files m = mdump("mesh.one") read in one or more mesh dump files
m = mdump("mesh.1 mesh.2.gz") can be gzipped m = mdump("mesh.1 mesh.2.gz") can be gzipped
m = mdump("mesh.*") wildcard expands to multiple files m = mdump("mesh.*") wildcard expands to multiple files
m = mdump("mesh.*",0) two args = store filenames, but don't read m = mdump("mesh.*",0) two args = store filenames, but don't read
incomplete and duplicate snapshots are deleted incomplete and duplicate snapshots are deleted
time = m.next() read next snapshot from dump files time = m.next() read next snapshot from dump files
used with 2-argument constructor to allow reading snapshots one-at-a-time used with 2-argument constructor to allow reading snapshots one-at-a-time
snapshot will be skipped only if another snapshot has same time stamp snapshot will be skipped only if another snapshot has same time stamp
@ -28,20 +36,20 @@ time = m.next() read next snapshot from dump files
m.map(2,"temperature") assign names to element value columns (1-N) m.map(2,"temperature") assign names to element value columns (1-N)
m.tselect.all() select all timesteps m.tselect.all() select all timesteps
m.tselect.one(N) select only timestep N m.tselect.one(N) select only timestep N
m.tselect.none() deselect all timesteps m.tselect.none() deselect all timesteps
m.tselect.skip(M) select every Mth step m.tselect.skip(M) select every Mth step
m.tselect.test("$t >= 100 and $t < 10000") select matching timesteps m.tselect.test("$t >= 100 and $t < 10000") select matching timesteps
m.delete() delete non-selected timesteps m.delete() delete non-selected timesteps
selecting a timestep also selects all elements in the timestep selecting a timestep also selects all elements in the timestep
skip() and test() only select from currently selected timesteps skip() and test() only select from currently selected timesteps
test() uses a Python Boolean expression with $t for timestep value test() uses a Python Boolean expression with $t for timestep value
Python comparison syntax: == != < > <= >= and or Python comparison syntax: == != < > <= >= and or
m.eselect.all() select all elems in all steps m.eselect.all() select all elems in all steps
m.eselect.all(N) select all elems in one step m.eselect.all(N) select all elems in one step
m.eselect.test("$id > 100 and $type == 2") select match elems in all steps m.eselect.test("$id > 100 and $type == 2") select match elems in all steps
m.eselect.test("$id > 100 and $type == 2",N) select matching elems in one step m.eselect.test("$id > 100 and $type == 2",N) select matching elems in one step
@ -52,7 +60,7 @@ m.eselect.test("$id > 100 and $type == 2",N) select matching elems in one step
Python comparison syntax: == != < > <= >= and or Python comparison syntax: == != < > <= >= and or
$name must end with a space $name must end with a space
t = m.time() return vector of selected timestep values t = m.time() return vector of selected timestep values
fx,fy,... = m.vecs(1000,"fx","fy",...) return vector(s) for timestep N fx,fy,... = m.vecs(1000,"fx","fy",...) return vector(s) for timestep N
vecs() returns vectors with one value for each selected elem in the timestep vecs() returns vectors with one value for each selected elem in the timestep
@ -124,12 +132,6 @@ m.etype = "color" set column returned as "type" by viz
# nevalues = # of node values # nevalues = # of node values
# evalues[i][j] = 2d array of floats, i = 0 to Nel-1, j = 0 to Ncol # 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: try:
import numpy as np import numpy as np
oldnumeric = False oldnumeric = False
@ -160,7 +162,7 @@ class mdump:
self.flist = [] self.flist = []
for word in words: self.flist += glob.glob(word) for word in words: self.flist += glob.glob(word)
if len(self.flist) == 0 and len(list) == 1: 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: if len(list) == 1:
self.increment = 0 self.increment = 0
@ -185,16 +187,16 @@ class mdump:
snap = self.read_snapshot(f) snap = self.read_snapshot(f)
while snap: while snap:
self.snaps.append(snap) self.snaps.append(snap)
print snap.time, print(snap.time, end=' ')
sys.stdout.flush() sys.stdout.flush()
snap = self.read_snapshot(f) snap = self.read_snapshot(f)
f.close() f.close()
print print()
# sort entries by timestep, cull and combine duplicates # 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() self.cull()
# sort all node, element, nvalue, evalue arrays by ID # sort all node, element, nvalue, evalue arrays by ID
@ -204,25 +206,25 @@ class mdump:
array = snap.nodes array = snap.nodes
ids = array[:,0] ids = array[:,0]
ordering = np.argsort(ids) 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) array[:,i] = np.take(array[:,i],ordering)
if snap.eflag: if snap.eflag:
array = snap.elements array = snap.elements
ids = array[:,0] ids = array[:,0]
ordering = np.argsort(ids) 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) array[:,i] = np.take(array[:,i],ordering)
if snap.nvalueflag: if snap.nvalueflag:
array = snap.nvalues array = snap.nvalues
ids = array[:,0] ids = array[:,0]
ordering = np.argsort(ids) 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) array[:,i] = np.take(array[:,i],ordering)
if snap.evalueflag: if snap.evalueflag:
array = snap.evalues array = snap.evalues
ids = array[:,0] ids = array[:,0]
ordering = np.argsort(ids) 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) array[:,i] = np.take(array[:,i],ordering)
# reference definitions of nodes and elements in previous timesteps # reference definitions of nodes and elements in previous timesteps
@ -230,7 +232,7 @@ class mdump:
self.reference() self.reference()
self.nsnaps = len(self.snaps) self.nsnaps = len(self.snaps)
print "read %d snapshots" % self.nsnaps print("read %d snapshots" % self.nsnaps)
# select all timesteps and elements # select all timesteps and elements
@ -241,7 +243,7 @@ class mdump:
def next(self): 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 # read next snapshot in current file using eof as pointer
# if fail, try next file # if fail, try next file
@ -253,15 +255,15 @@ class mdump:
snap = self.read_snapshot(f) snap = self.read_snapshot(f)
if not snap: if not snap:
self.nextfile += 1 self.nextfile += 1
if self.nextfile == len(self.flist): return -1 if self.nextfile == len(self.flist): return -1
f.close() f.close()
self.eof = 0 self.eof = 0
continue continue
self.eof = f.tell() self.eof = f.tell()
f.close() f.close()
try: try:
self.findtime(snap.time) self.findtime(snap.time)
continue continue
except: break except: break
# select the new snapshot with all its elements # select the new snapshot with all its elements
@ -271,7 +273,7 @@ class mdump:
snap.tselect = 1 snap.tselect = 1
snap.nselect = snap.nelements snap.nselect = snap.nelements
if snap.eflag: 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.nsnaps += 1
self.nselect += 1 self.nselect += 1
@ -295,7 +297,7 @@ class mdump:
elif "NUMBER OF CUBES" in str: snap.eflag = 4 elif "NUMBER OF CUBES" in str: snap.eflag = 4
elif "NUMBER OF NODE VALUES" in str: snap.nvalueflag = 1 elif "NUMBER OF NODE VALUES" in str: snap.nvalueflag = 1
elif "NUMBER OF ELEMENT VALUES" in str: snap.evalueflag = 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()) n = int(f.readline())
if snap.eflag: snap.eselect = np.zeros(n) if snap.eflag: snap.eselect = np.zeros(n)
@ -313,14 +315,14 @@ class mdump:
if n: if n:
words = f.readline().split() words = f.readline().split()
ncol = len(words) ncol = len(words)
for i in xrange(1,n): for i in range(1,n):
words += f.readline().split() words += f.readline().split()
floats = map(float,words) floats = list(map(float,words))
if oldnumeric: values = np.zeros((n,ncol),np.Float) if oldnumeric: values = np.zeros((n,ncol),np.Float)
else: values = np.zeros((n,ncol),np.float) else: values = np.zeros((n,ncol),np.float)
start = 0 start = 0
stop = ncol stop = ncol
for i in xrange(n): for i in range(n):
values[i] = floats[start:stop] values[i] = floats[start:stop]
start = stop start = stop
stop += ncol stop += ncol
@ -343,7 +345,7 @@ class mdump:
def map(self,*pairs): def map(self,*pairs):
if len(pairs) % 2 != 0: 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): for i in range(0,len(pairs),2):
j = i + 1 j = i + 1
self.names[pairs[j]] = pairs[i]-1 self.names[pairs[j]] = pairs[i]-1
@ -360,15 +362,15 @@ class mdump:
self.nsnaps -= 1 self.nsnaps -= 1
ndel += 1 ndel += 1
else: i += 1 else: i += 1
print "%d snapshots deleted" % ndel print("%d snapshots deleted" % ndel)
print "%d snapshots remaining" % self.nsnaps print("%d snapshots remaining" % self.nsnaps)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# sort elements by ID in all selected timesteps or one timestep # sort elements by ID in all selected timesteps or one timestep
def sort(self,*list): def sort(self,*list):
if len(list) == 0: if len(list) == 0:
print "Sorting selected snapshots ..." print("Sorting selected snapshots ...")
id = self.names["id"] id = self.names["id"]
for snap in self.snaps: for snap in self.snaps:
if snap.tselect: self.sort_one(snap,id) if snap.tselect: self.sort_one(snap,id)
@ -385,7 +387,7 @@ class mdump:
atoms = snap.atoms atoms = snap.atoms
ids = atoms[:,id] ids = atoms[:,id]
ordering = np.argsort(ids) 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) atoms[:,i] = np.take(atoms[:,i],ordering)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -406,10 +408,10 @@ class mdump:
def vecs(self,n,*list): def vecs(self,n,*list):
snap = self.snaps[self.findtime(n)] snap = self.snaps[self.findtime(n)]
if not snap.evalues: if not snap.evalues:
raise StandardError, "snapshot has no element values" raise Exception("snapshot has no element values")
if len(list) == 0: if len(list) == 0:
raise StandardError, "no columns specified" raise Exception("no columns specified")
columns = [] columns = []
values = [] values = []
for name in list: for name in list:
@ -418,9 +420,9 @@ class mdump:
ncol = len(columns) ncol = len(columns)
m = 0 m = 0
for i in xrange(len(snap.evalues)): for i in range(len(snap.evalues)):
if not snap.eselect[i]: continue if not snap.eselect[i]: continue
for j in xrange(ncol): for j in range(ncol):
values[j][m] = snap.evalues[i][columns[j]] values[j][m] = snap.evalues[i][columns[j]]
m += 1 m += 1
@ -482,9 +484,9 @@ class mdump:
# if not, point it at most recent shapshot that does # if not, point it at most recent shapshot that does
def reference(self): def reference(self):
for i in xrange(len(self.snaps)): for i in range(len(self.snaps)):
if not self.snaps[i].nflag: 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: if self.snaps[j].nflag:
self.snaps[i].nflag = self.snaps[j].nflag self.snaps[i].nflag = self.snaps[j].nflag
self.snaps[i].nnodes = self.snaps[j].nnodes self.snaps[i].nnodes = self.snaps[j].nnodes
@ -497,9 +499,9 @@ class mdump:
self.snaps[i].zhi = self.snaps[j].zhi self.snaps[i].zhi = self.snaps[j].zhi
break break
if not self.snaps[i].nflag: 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: 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: if self.snaps[j].eflag:
self.snaps[i].eflag = self.snaps[j].eflag self.snaps[i].eflag = self.snaps[j].eflag
self.snaps[i].nelements = self.snaps[j].nelements self.snaps[i].nelements = self.snaps[j].nelements
@ -507,7 +509,7 @@ class mdump:
self.snaps[i].eselect = self.snaps[j].eselect self.snaps[i].eselect = self.snaps[j].eselect
break break
if not self.snaps[i].eflag: 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 # iterate over selected snapshots
@ -515,7 +517,7 @@ class mdump:
def iterator(self,flag): def iterator(self,flag):
start = 0 start = 0
if flag: start = self.iterate + 1 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: if self.snaps[i].tselect:
self.iterate = i self.iterate = i
return i,self.snaps[i].time,1 return i,self.snaps[i].time,1
@ -550,7 +552,7 @@ class mdump:
tris = [] tris = []
nodes = snap.nodes nodes = snap.nodes
for i in xrange(snap.nelements): for i in range(snap.nelements):
if not snap.eselect[i]: continue if not snap.eselect[i]: continue
element = snap.elements[i] element = snap.elements[i]
if snap.evalueflag: evalue = snap.evalues[i] if snap.evalueflag: evalue = snap.evalues[i]
@ -699,9 +701,9 @@ class mdump:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def findtime(self,n): def findtime(self,n):
for i in xrange(self.nsnaps): for i in range(self.nsnaps):
if self.snaps[i].time == n: return i 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 # return maximum box size across all selected snapshots
@ -751,7 +753,7 @@ class tselect:
snap.tselect = 1 snap.tselect = 1
data.nselect = len(data.snaps) data.nselect = len(data.snaps)
data.eselect.all() 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.snaps[i].tselect = 1
data.nselect = 1 data.nselect = 1
data.eselect.all() 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: for snap in data.snaps:
snap.tselect = 0 snap.tselect = 0
data.nselect = 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 snap.tselect = 0
data.nselect -= 1 data.nselect -= 1
data.eselect.all() 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 snaps = data.snaps
cmd = "flag = " + teststr.replace("$t","snaps[i].time") cmd = "flag = " + teststr.replace("$t","snaps[i].time")
ccmd = compile(cmd,'','single') ccmd = compile(cmd,'','single')
for i in xrange(data.nsnaps): for i in range(data.nsnaps):
if not snaps[i].tselect: continue 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: if not flag:
snaps[i].tselect = 0 snaps[i].tselect = 0
data.nselect -= 1 data.nselect -= 1
data.eselect.all() 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 # element selection class
@ -821,12 +825,12 @@ class eselect:
if len(args) == 0: # all selected timesteps if len(args) == 0: # all selected timesteps
for snap in data.snaps: for snap in data.snaps:
if not snap.tselect: continue 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 snap.nselect = snap.nelements
else: # one timestep else: # one timestep
n = data.findtime(args[0]) n = data.findtime(args[0])
snap = data.snaps[n] 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 snap.nselect = snap.nelements
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -849,29 +853,29 @@ class eselect:
if len(args) == 0: # all selected timesteps if len(args) == 0: # all selected timesteps
for snap in data.snaps: for snap in data.snaps:
if not snap.tselect: continue if not snap.tselect: continue
for i in xrange(snap.nelements): for i in range(snap.nelements):
if not snap.eselect[i]: continue if not snap.eselect[i]: continue
exec ccmd exec(ccmd)
if not flag: if not flag:
snap.eselect[i] = 0 snap.eselect[i] = 0
snap.nselect -= 1 snap.nselect -= 1
for i in xrange(data.nsnaps): for i in range(data.nsnaps):
if data.snaps[i].tselect: if data.snaps[i].tselect:
print "%d atoms of %d selected in first step %d" % \ print("%d atoms of %d selected in first step %d" % \
(data.snaps[i].nselect,data.snaps[i].nelements,data.snaps[i].time) (data.snaps[i].nselect,data.snaps[i].nelements,data.snaps[i].time))
break break
for i in xrange(data.nsnaps-1,-1,-1): for i in range(data.nsnaps-1,-1,-1):
if data.snaps[i].tselect: if data.snaps[i].tselect:
print "%d atoms of %d selected in last step %d" % \ print("%d atoms of %d selected in last step %d" % \
(data.snaps[i].nselect,data.snaps[i].nelements,data.snaps[i].time) (data.snaps[i].nselect,data.snaps[i].nelements,data.snaps[i].time))
break break
else: # one timestep else: # one timestep
n = data.findtime(args[0]) n = data.findtime(args[0])
snap = data.snaps[n] snap = data.snaps[n]
for i in xrange(snap.nelements): for i in range(snap.nelements):
if not snap.eselect[i]: continue if not snap.eselect[i]: continue
exec ccmd exec(ccmd)
if not flag: if not flag:
snap.eselect[i] = 0 snap.eselect[i] = 0
snap.nselect -= 1 snap.nselect -= 1

View File

@ -8,6 +8,11 @@
# pair tool # pair tool
# Imports and external programs
from __future__ import print_function, absolute_import
from math import sqrt
oneline = "Compute LAMMPS pairwise energies" oneline = "Compute LAMMPS pairwise energies"
docstr = """ docstr = """
@ -15,8 +20,8 @@ p = pair("lj/charmm/coul/charmm") create pair object for specific pair style
available styles: lj/cut, lj/cut/coul/cut, lj/charmm/coul/charmm available styles: lj/cut, lj/cut/coul/cut, lj/charmm/coul/charmm
p.coeff(d) extract pairwise coeffs from data object p.coeff(d) extract pairwise coeffs from data object
p.init(cut1,cut2,...) setup based on coeffs and cutoffs p.init(cut1,cut2,...) setup based on coeffs and cutoffs
init args are specific to pair style: init args are specific to pair style:
lj/cut = cutlj lj/cut = cutlj
@ -41,10 +46,6 @@ e_vdwl,e_coul = p.single(rsq,itype,jtype,q1,q2,...) compute LJ/Coul energy
# Variables # Variables
# Imports and external programs
from math import sqrt
# Class definition # Class definition
class pair: class pair:
@ -68,7 +69,7 @@ class pair:
self.init_func = self.init_lj_charmm_coul_charmm self.init_func = self.init_lj_charmm_coul_charmm
self.single_func = self.single_lj_charmm_coul_charmm self.single_func = self.single_lj_charmm_coul_charmm
else: else:
raise StandardError, "this pair style not yet supported" raise Exception("this pair style not yet supported")
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# generic coeff method # generic coeff method
@ -99,10 +100,10 @@ class pair:
self.lj3 = [] self.lj3 = []
self.lj4 = [] self.lj4 = []
for i in xrange(ntypes): for i in range(ntypes):
self.lj3.append(ntypes * [0]) self.lj3.append(ntypes * [0])
self.lj4.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]) epsilon_ij = sqrt(epsilon[i]*epsilon[j])
sigma_ij = sqrt(sigma[i]*sigma[j]) sigma_ij = sqrt(sigma[i]*sigma[j])
self.lj3[i][j] = 4.0 * epsilon_ij * pow(sigma_ij,12.0); self.lj3[i][j] = 4.0 * epsilon_ij * pow(sigma_ij,12.0);
@ -143,10 +144,10 @@ class pair:
self.lj3 = [] self.lj3 = []
self.lj4 = [] self.lj4 = []
for i in xrange(ntypes): for i in range(ntypes):
self.lj3.append(ntypes * [0]) self.lj3.append(ntypes * [0])
self.lj4.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]) epsilon_ij = sqrt(epsilon[i]*epsilon[j])
sigma_ij = sqrt(sigma[i]*sigma[j]) sigma_ij = sqrt(sigma[i]*sigma[j])
self.lj3[i][j] = 4.0 * epsilon_ij * pow(sigma_ij,12.0); self.lj3[i][j] = 4.0 * epsilon_ij * pow(sigma_ij,12.0);
@ -156,7 +157,7 @@ class pair:
# args = cutlj, cut_coul (cut_coul optional) # args = cutlj, cut_coul (cut_coul optional)
def init_lj_cut_coul_cut(self,list): def init_lj_cut_coul_cut(self,list):
self.qqr2e = 332.0636 # convert energy to kcal/mol self.qqr2e = 332.0636 # convert energy to kcal/mol
cut_lj = list[0] cut_lj = list[0]
self.cut_ljsq = cut_lj*cut_lj self.cut_ljsq = cut_lj*cut_lj
@ -197,10 +198,10 @@ class pair:
self.lj3 = [] self.lj3 = []
self.lj4 = [] self.lj4 = []
for i in xrange(ntypes): for i in range(ntypes):
self.lj3.append(ntypes * [0]) self.lj3.append(ntypes * [0])
self.lj4.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]) epsilon_ij = sqrt(epsilon[i]*epsilon[j])
sigma_ij = 0.5 * (sigma[i] + sigma[j]) sigma_ij = 0.5 * (sigma[i] + sigma[j])
self.lj3[i][j] = 4.0 * epsilon_ij * pow(sigma_ij,12.0); self.lj3[i][j] = 4.0 * epsilon_ij * pow(sigma_ij,12.0);
@ -210,7 +211,7 @@ class pair:
# args = cutlj_inner,cutlj,cutcoul_inner,cut_coul (last 2 optional) # args = cutlj_inner,cutlj,cutcoul_inner,cut_coul (last 2 optional)
def init_lj_charmm_coul_charmm(self,list): def init_lj_charmm_coul_charmm(self,list):
self.qqr2e = 332.0636 # convert energy to kcal/mol self.qqr2e = 332.0636 # convert energy to kcal/mol
cut_lj_inner = list[0] cut_lj_inner = list[0]
cut_lj = list[1] cut_lj = list[1]

View File

@ -8,15 +8,21 @@
# patch tool # patch tool
# Imports and external programs
from __future__ import print_function, absolute_import
from math import sqrt,pi,cos,sin
from data import data
oneline = "Create patchy Lennard-Jones particles for LAMMPS input" oneline = "Create patchy Lennard-Jones particles for LAMMPS input"
docstr = """ docstr = """
p = patch(vfrac) setup box with a specified volume fraction p = patch(vfrac) setup box with a specified volume fraction
p = patch(vfrac,1,1,2) x,y,z = aspect ratio of box (def = 1,1,1) p = patch(vfrac,1,1,2) x,y,z = aspect ratio of box (def = 1,1,1)
p.seed = 48379 set random # seed (def = 12345) p.seed = 48379 set random # seed (def = 12345)
p.randomized = 0 1 = choose next particle randomly, 0 = as generated p.randomized = 0 1 = choose next particle randomly, 0 = as generated
p.dim = 2 set dimension of created box (def = 3) p.dim = 2 set dimension of created box (def = 3)
p.blen = 0.97 set length of tether bonds (def = 0.97) p.blen = 0.97 set length of tether bonds (def = 0.97)
p.dmin = 1.02 set min r from i-1 to i+1 tether site (def = 1.02) p.dmin = 1.02 set min r from i-1 to i+1 tether site (def = 1.02)
p.lattice = [Nx,Ny,Nz] generate Nx by Ny by Nz lattice of particles p.lattice = [Nx,Ny,Nz] generate Nx by Ny by Nz lattice of particles
@ -61,11 +67,6 @@ p.write("data.patch") write out system to LAMMPS data file
# seed = random seed # seed = random seed
# molecules = list of atoms, grouped by molecule # 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 definition
class patch: class patch:
@ -98,8 +99,14 @@ class patch:
if style == "linebox" or style == "linetri": self.style = "line" if style == "linebox" or style == "linetri": self.style = "line"
if style == "tritet" or style == "tribox": self.style = "tri" if style == "tritet" or style == "tribox": self.style = "tri"
cmd = "atoms,bonds,tris,segments,volume = self.%s(*types)" % style cmd = "atoms,bonds,tris,segments,volume = self.%s(*types)" % style
for i in xrange(n): for i in range(n):
exec cmd 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.molecules.append([atoms,bonds,tris,segments])
self.volume += volume self.volume += volume
@ -131,7 +138,7 @@ class patch:
latflag = 1 latflag = 1
if self.lattice[0]*self.lattice[1]*self.lattice[2] != \ if self.lattice[0]*self.lattice[1]*self.lattice[2] != \
len(self.molecules): len(self.molecules):
raise StandardError,"lattice inconsistent with # of molecules" raise Exception("lattice inconsistent with # of molecules")
else: latflag = 0 else: latflag = 0
idatom = idbond = idtri = idmol = 0 idatom = idbond = idtri = idmol = 0
@ -343,7 +350,7 @@ class patch:
if self.lattice[0] or self.lattice[1]: if self.lattice[0] or self.lattice[1]:
latflag = 1 latflag = 1
if self.lattice[0]*self.lattice[1] != len(self.molecules): 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 else: latflag = 0
idatom = idbond = idmol = 0 idatom = idbond = idmol = 0
@ -885,7 +892,7 @@ class patch:
sep = params[1] sep = params[1]
type = params[2] type = params[2]
if n % 2 == 0: 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 middle = n/2
atoms = [] atoms = []
@ -1131,7 +1138,7 @@ class patch:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def random(self): def random(self):
k = self.seed/IQ k = self.seed//IQ
self.seed = IA*(self.seed-k*IQ) - IR*k self.seed = IA*(self.seed-k*IQ) - IR*k
if self.seed < 0: if self.seed < 0:
self.seed += IM self.seed += IM

View File

@ -8,6 +8,15 @@
# pdb tool # pdb tool
# Imports and external programs
from __future__ import print_function, absolute_import
import sys, types, glob
try:
import urllib.request, urllib.parse, urllib.error
except ImportError:
import urllib
oneline = "Read, write PDB files in combo with LAMMPS snapshots" oneline = "Read, write PDB files in combo with LAMMPS snapshots"
docstr = """ docstr = """
@ -62,10 +71,6 @@ index,time,flag = p.iterator(1)
# atomlines = dict of ATOM lines in original PDB file # atomlines = dict of ATOM lines in original PDB file
# key = atom id, value = tuple of (beginning,end) of line # key = atom id, value = tuple of (beginning,end) of line
# Imports and external programs
import sys, types, glob, urllib
# Class definition # Class definition
class pdbfile: class pdbfile:
@ -74,7 +79,7 @@ class pdbfile:
def __init__(self,*args): def __init__(self,*args):
if len(args) == 1: if len(args) == 1:
if type(args[0]) is types.StringType: if type(args[0]) is bytes:
filestr = args[0] filestr = args[0]
self.data = None self.data = None
else: else:
@ -83,7 +88,7 @@ class pdbfile:
elif len(args) == 2: elif len(args) == 2:
filestr = args[0] filestr = args[0]
self.data = args[1] 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 # flist = full list of all PDB input file names
# append .pdb if needed # append .pdb if needed
@ -94,17 +99,17 @@ class pdbfile:
for file in list: for file in list:
if '*' in file: flist += glob.glob(file) if '*' in file: flist += glob.glob(file)
else: flist.append(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 flist[i][-4:] != ".pdb": flist[i] += ".pdb"
if len(flist) == 0: if len(flist) == 0:
raise StandardError,"no PDB file specified" raise Exception("no PDB file specified")
self.files = flist self.files = flist
else: self.files = [] else: self.files = []
if len(self.files) > 1 and self.data: 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: 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 # grab PDB file from http://rcsb.org if not a local file
@ -112,9 +117,9 @@ class pdbfile:
try: try:
open(self.files[0],'r').close() open(self.files[0],'r').close()
except: 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] 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]) if self.data and len(self.files): self.read_template(self.files[0])
@ -142,20 +147,20 @@ class pdbfile:
which,time,flag = self.data.iterator(flag) which,time,flag = self.data.iterator(flag)
if flag == -1: break if flag == -1: break
self.convert(f,which) self.convert(f,which)
print >>f,"END" print("END", file=f)
print time, print(time, end=' ')
sys.stdout.flush() sys.stdout.flush()
n += 1 n += 1
else: else:
for file in self.files: for file in self.files:
f.write(open(file,'r').read()) f.write(open(file,'r').read())
print >>f,"END" print("END", file=f)
print file, print(file, end=' ')
sys.stdout.flush() sys.stdout.flush()
f.close() 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 # write series of numbered PDB files
@ -190,7 +195,7 @@ class pdbfile:
self.convert(f,which) self.convert(f,which)
f.close() f.close()
print time, print(time, end=' ')
sys.stdout.flush() sys.stdout.flush()
n += 1 n += 1
@ -210,12 +215,12 @@ class pdbfile:
f = open(file,'w') f = open(file,'w')
f.write(open(infile,'r').read()) f.write(open(infile,'r').read())
f.close() f.close()
print file, print(file, end=' ')
sys.stdout.flush() sys.stdout.flush()
n += 1 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 # write a single PDB file
@ -277,13 +282,13 @@ class pdbfile:
if len(self.files): if len(self.files):
for atom in atoms: for atom in atoms:
id = atom[0] id = atom[0]
if self.atomlines.has_key(id): if id in self.atomlines:
(begin,end) = self.atomlines[id] (begin,end) = self.atomlines[id]
line = "%s%8.3f%8.3f%8.3f%s" % (begin,atom[2],atom[3],atom[4],end) 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: else:
for atom in atoms: for atom in atoms:
begin = "ATOM %6d %2d R00 1 " % (atom[0],atom[1]) begin = "ATOM %6d %2d R00 1 " % (atom[0],atom[1])
middle = "%8.3f%8.3f%8.3f" % (atom[2],atom[3],atom[4]) middle = "%8.3f%8.3f%8.3f" % (atom[2],atom[3],atom[4])
end = " 1.00 0.00 NONE" end = " 1.00 0.00 NONE"
print >>f,begin+middle+end print(begin+middle+end, file=f)

View File

@ -15,6 +15,12 @@
# ToDo list: # ToDo list:
# modules needed by pizza.py
from __future__ import print_function, absolute_import
import sys, os, string, glob, re
import time
# Help strings: # Help strings:
version = "LPP 1.0 based on pizza - 7 Oct 2011" version = "LPP 1.0 based on pizza - 7 Oct 2011"
@ -26,12 +32,12 @@ type ? for help, CTRL-D to quit
help = """ help = """
pizza.py switch arg(s) switch arg(s) ... pizza.py switch arg(s) switch arg(s) ...
-s silent (else print start-up help) -s silent (else print start-up help)
-t log dump raster load only these tools -t log dump raster load only these tools
-x raster rasmol load all tools except these -x raster rasmol load all tools except these
-f mine.py arg1 arg2 run script file with args -f mine.py arg1 arg2 run script file with args
-c "vec = range(100)" run Python command -c "vec = range(100)" run Python command
-q quit (else interactive) -q quit (else interactive)
Everything typed at the ">" prompt is a Python command Everything typed at the ">" prompt is a Python command
@ -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 # readline not available in all Pythons
try: try:
import readline import readline
readline_flag = 1 readline_flag = 1
except ImportError, exception: except ImportError as exception:
print "readline option not available" print("readline option not available")
readline_flag = 0 readline_flag = 0
# create global Tk root if Tkinter is loaded # create global Tk root if Tkinter is loaded
@ -72,10 +73,12 @@ try:
import Tkinter import Tkinter
tkroot = Tkinter.Tk() tkroot = Tkinter.Tk()
tkroot.withdraw() tkroot.withdraw()
except ImportError, exception: except ImportError as exception:
nodisplay = True import tkinter
tkroot = tkinter.Tk()
tkroot.withdraw()
pass pass
except Exception, exception: except Exception as exception:
nodisplay = True nodisplay = True
pass pass
@ -107,22 +110,22 @@ def trap(type,value,tback):
words = value.text.split() words = value.text.split()
if len(words) == 1 and words[0] == "?": if len(words) == 1 and words[0] == "?":
print intro[1:] % version print(intro[1:] % version)
print help[1:]," ", print(help[1:]," ", end=' ')
for tool in tools: print tool, for tool in tools: print(tool, end=' ')
print print()
elif len(words) == 1 and words[0] == "??": elif len(words) == 1 and words[0] == "??":
for tool in tools: for tool in tools:
exec "oneline = oneline_%s" % tool exec("oneline = oneline_%s" % tool)
print "%-11s%s" % (tool,oneline) print("%-11s%s" % (tool,oneline))
print print()
scripts = [] scripts = []
for dir in PIZZA_SCRIPTS[1:]: for dir in PIZZA_SCRIPTS[1:]:
list = glob.glob("%s/*.py" % dir) flist = glob.glob("%s/*.py" % dir)
list.sort() flist.sort()
scripts += list scripts += flist
for script in scripts: for script in scripts:
filename = os.path.basename(script) filename = os.path.basename(script)
lines = open(script,'r').readlines() lines = open(script,'r').readlines()
@ -133,7 +136,7 @@ def trap(type,value,tback):
break break
if flag: doc = line[line.find("Purpose:")+8:] if flag: doc = line[line.find("Purpose:")+8:]
else: doc = " not available\n" else: doc = " not available\n"
print "%-20s%s" % (filename,doc), print("%-20s%s" % (filename,doc), end=' ')
elif len(words) == 2 and words[0] == "?": elif len(words) == 2 and words[0] == "?":
if words[1][-3:] == ".py": if words[1][-3:] == ".py":
@ -145,25 +148,25 @@ def trap(type,value,tback):
lineflag = 0 lineflag = 0
lines = open(filename,'r').readlines() lines = open(filename,'r').readlines()
for line in lines: 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: if line.find("# Syntax:") >= 0:
lineflag = 1 lineflag = 1
break break
if not lineflag: print "%s has no Syntax line" % words[1] if not lineflag: print("%s has no Syntax line" % words[1])
else: print line[2:], else: print(line[2:], end=' ')
break break
if not fileflag: if not fileflag:
print "%s is not a recognized script" % words[1] print("%s is not a recognized script" % words[1])
else: else:
if words[1] in tools: 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\s*\n","\n",txt)
txt = re.sub("\n .*","",txt) txt = re.sub("\n .*","",txt)
exec "print oneline_%s" % words[1] exec("print oneline_%s" % words[1])
print txt print(txt)
else: 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] == "??": elif len(words) == 2 and words[0] == "??":
if words[1][-3:] == ".py": if words[1][-3:] == ".py":
@ -175,18 +178,18 @@ def trap(type,value,tback):
lines = open(filename,'r').readlines() lines = open(filename,'r').readlines()
for line in lines: for line in lines:
if len(line.strip()) == 0: continue if len(line.strip()) == 0: continue
if line[0] == '#': print line, if line[0] == '#': print(line, end=' ')
else: break else: break
break break
if not fileflag: if not fileflag:
print "%s is not a recognized script" % words[1] print("%s is not a recognized script" % words[1])
else: else:
if words[1] in tools: if words[1] in tools:
exec "print oneline_%s" % words[1] exec("print oneline_%s" % words[1])
exec "print docstr_%s" % words[1] exec("print docstr_%s" % words[1])
else: else:
print "%s is not a recognized class" % words[1] print("%s is not a recognized class" % words[1])
return return
@ -208,13 +211,13 @@ def trap(type,value,tback):
return return
elif words[0][1:] == "log": elif words[0][1:] == "log":
if readline_flag == 0: if readline_flag == 0:
print "cannot use @log without readline module" print("cannot use @log without readline module")
return return
f = open(words[1],"w") 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() nlines = readline.get_current_history_length()
for i in xrange(1,nlines): for i in range(1,nlines):
print >>f,readline.get_history_item(i) print(readline.get_history_item(i), file=f)
f.close() f.close()
return return
elif words[0][1:] == "run": elif words[0][1:] == "run":
@ -225,17 +228,17 @@ def trap(type,value,tback):
fullfile = dir + '/' + file fullfile = dir + '/' + file
if os.path.exists(fullfile): if os.path.exists(fullfile):
flag = 1 flag = 1
print "Executing file:",fullfile print("Executing file:",fullfile)
execfile(fullfile,namespace) exec(compile(open(fullfile).read(), fullfile, 'exec'),namespace)
break break
if not flag: print "Could not find file",file if not flag: print("Could not find file",file)
return return
elif words[0][1:] == "time": elif words[0][1:] == "time":
cmd = string.join(words[1:]) cmd = string.join(words[1:])
t1 = clock() t1 = clock()
exec cmd in namespace exec(cmd, namespace)
t2 = clock() t2 = clock()
print "CPU time = ",t2-t1 print("CPU time = ",t2-t1)
return return
# unrecognized command, let system handle error # unrecognized command, let system handle error
@ -255,7 +258,7 @@ quitflag = 0
iarg = 1 iarg = 1
while (iarg < len(sys.argv)): while (iarg < len(sys.argv)):
if (sys.argv[iarg][0] != '-'): 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() sys.exit()
if (sys.argv[iarg] == "-s"): if (sys.argv[iarg] == "-s"):
silent = 1 silent = 1
@ -274,37 +277,37 @@ while (iarg < len(sys.argv)):
iarg = jarg iarg = jarg
elif (sys.argv[iarg] == "-f"): elif (sys.argv[iarg] == "-f"):
jarg = iarg + 1 jarg = iarg + 1
list = [] flist = []
while (jarg < len(sys.argv) and sys.argv[jarg][0] != '-'): while (jarg < len(sys.argv) and sys.argv[jarg][0] != '-'):
list.append(sys.argv[jarg]) flist.append(sys.argv[jarg])
jarg += 1 jarg += 1
task = ("script",list) task = ("script",flist)
tasks.append(task) tasks.append(task)
iarg = jarg iarg = jarg
elif (sys.argv[iarg] == "-c"): elif (sys.argv[iarg] == "-c"):
jarg = iarg + 1 jarg = iarg + 1
list = [] clist = []
while (jarg < len(sys.argv) and sys.argv[jarg][0] != '-'): while (jarg < len(sys.argv) and sys.argv[jarg][0] != '-'):
list.append(sys.argv[jarg]) clist.append(sys.argv[jarg])
jarg += 1 jarg += 1
task = ("command",list) task = ("command",clist)
tasks.append(task) tasks.append(task)
iarg = jarg iarg = jarg
elif (sys.argv[iarg] == "-q"): elif (sys.argv[iarg] == "-q"):
quitflag = 1 quitflag = 1
iarg += 1 iarg += 1
else: else:
print "ERROR: unknown switch: %s" % (sys.argv[iarg]) print("ERROR: unknown switch: %s" % (sys.argv[iarg]))
sys.exit() sys.exit()
# print intro message # 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 # error test on m,x command-line switches
if len(yes_tools) > 0 and len(no_tools) > 0: 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() sys.exit()
# ------------------------------------------------------------------------- # -------------------------------------------------------------------------
@ -313,12 +316,12 @@ if len(yes_tools) > 0 and len(no_tools) > 0:
# else scan for *.py files in all dirs in PIZZA_TOOLS list # else scan for *.py files in all dirs in PIZZA_TOOLS list
# and then Pizza.py src dir (sys.path[0]) # and then Pizza.py src dir (sys.path[0])
if not silent: print "Loading tools ..." if not silent: print("Loading tools ...")
if not silent and nodisplay: print "Display not available ... no GUIs" if not silent and nodisplay: print("Display not available ... no GUIs")
try: from DEFAULTS import PIZZA_TOOLS try: from DEFAULTS import PIZZA_TOOLS
except: 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]) PIZZA_TOOLS.append(sys.path[0])
if len(yes_tools) > 0: tools = yes_tools if len(yes_tools) > 0: tools = yes_tools
@ -359,12 +362,12 @@ for tool in tools:
failed.append(tool) failed.append(tool)
continue continue
try: try:
exec "from %s import %s" % (tool,tool) exec("from %s import %s" % (tool,tool))
exec "from %s import oneline as oneline_%s" % (tool,tool) exec("from %s import oneline as oneline_%s" % (tool,tool))
exec "from %s import docstr as docstr_%s" % (tool,tool) exec("from %s import docstr as docstr_%s" % (tool,tool))
except Exception, exception: except Exception as exception:
print "%s tool did not load:" % tool print("%s tool did not load:" % tool)
print " ",exception print(" ",exception)
failed.append(tool) failed.append(tool)
for dir in PIZZA_TOOLS: sys.path = sys.path[1:] for dir in PIZZA_TOOLS: sys.path = sys.path[1:]
@ -384,7 +387,7 @@ sys.path.insert(0,'')
try: from DEFAULTS import PIZZA_SCRIPTS try: from DEFAULTS import PIZZA_SCRIPTS
except: 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.insert(0,'.')
PIZZA_SCRIPTS.append(sys.path[1][:-3] + "scripts") # path for pizza.py PIZZA_SCRIPTS.append(sys.path[1][:-3] + "scripts") # path for pizza.py
@ -403,27 +406,27 @@ for task in tasks:
for dir in PIZZA_SCRIPTS: for dir in PIZZA_SCRIPTS:
fullfile = dir + '/' + file fullfile = dir + '/' + file
if os.path.exists(fullfile): if os.path.exists(fullfile):
print "Executing file:",fullfile print("Executing file:",fullfile)
execfile(fullfile) exec(compile(open(fullfile).read(), fullfile, 'exec'))
flag = 1 flag = 1
break break
if not flag: print "Could not find file",file if not flag: print("Could not find file",file)
except StandardError, exception: except Exception as exception:
(type,value,tback) = sys.exc_info() (type,value,tback) = sys.exc_info()
print type,value,tback print(type,value,tback)
type = str(type) type = str(type)
type = type[type.find(".")+1:] type = type[type.find(".")+1:]
print "%s with value: %s" % (type,value) print("%s with value: %s" % (type,value))
tback = tback.tb_next tback = tback.tb_next
while tback: while tback:
print "error on line %d of file %s" % \ print("error on line %d of file %s" % \
(tback.tb_lineno,tback.tb_frame.f_code.co_filename) (tback.tb_lineno,tback.tb_frame.f_code.co_filename))
tback = tback.tb_next tback = tback.tb_next
elif task[0] == "command": elif task[0] == "command":
argv = task[1] argv = task[1]
cmd = "" cmd = ""
for arg in argv: cmd += arg + " " for arg in argv: cmd += arg + " "
exec cmd exec(cmd)
# ------------------------------------------------------------------------- # -------------------------------------------------------------------------
# store global namespace # store global namespace

View File

@ -8,6 +8,15 @@
# plotview tool # plotview tool
# Imports and external programs
from __future__ import print_function, absolute_import
import sys, re, glob, time
try:
from Tkinter import *
except ImportError:
from tkinter import *
oneline = "Plot multiple vectors from a data set" oneline = "Plot multiple vectors from a data set"
docstr = """ docstr = """
@ -46,11 +55,6 @@ p.save() save currently selected plot to file.eps
# checkvars = list of status of check buttons # checkvars = list of status of check buttons
# checkold = list of status of check buttons before click # checkold = list of status of check buttons before click
# Imports and external programs
import sys, re, glob, time
from Tkinter import *
# Class definition # Class definition
class plotview: class plotview:
@ -148,7 +152,7 @@ class plotview:
def save(self): def save(self):
n = self.radiovar.get() n = self.radiovar.get()
if n == 0: raise StandardError,"no plot selected" if n == 0: raise Exception("no plot selected")
name = self.entry.get() name = self.entry.get()
self.plot.save(name) self.plot.save(name)

View File

@ -8,6 +8,16 @@
# rasmol tool # rasmol tool
# Imports and external programs
from __future__ import print_function, absolute_import
import sys, os, re, types
try:
import commands
except ImportError:
import subprocess as commands
from pdbfile import pdbfile
oneline = "3d visualization via RasMol program" oneline = "3d visualization via RasMol program"
docstr = """ docstr = """
@ -38,11 +48,6 @@ r.run(N,"new.rasmol","old.rasmol") type quit to save RasMol script file
# Variables # Variables
# Imports and external programs
import sys, os, commands, re, types
from pdbfile import pdbfile
try: from DEFAULTS import PIZZA_RASMOL try: from DEFAULTS import PIZZA_RASMOL
except: PIZZA_RASMOL = "rasmol" except: PIZZA_RASMOL = "rasmol"
try: from DEFAULTS import PIZZA_DISPLAY try: from DEFAULTS import PIZZA_DISPLAY
@ -67,7 +72,7 @@ class rasmol:
def enter(self): def enter(self):
while 1: while 1:
command = raw_input("rasmol> ") command = input("rasmol> ")
if command == "quit" or command == "exit": return if command == "quit" or command == "exit": return
self.__call__(command) self.__call__(command)
@ -85,19 +90,19 @@ class rasmol:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def show(self,*list): def show(self,*arglist):
# create tmp.pdb with atom data # create tmp.pdb with atom data
n = list[0] n = arglist[0]
self.pdb.single(n,"tmp.pdb") self.pdb.single(n,"tmp.pdb")
# if RasMol input script specified, read it # if RasMol input script specified, read it
# replace load pdb "file" with load pdb "%s" # replace load pdb "file" with load pdb "%s"
# if no RasMol input script specified, use rasmol_template # if no RasMol input script specified, use rasmol_template
if len(list) == 2: if len(arglist) == 2:
rasmol_text = open(list[1],"r").read() rasmol_text = open(arglist[1],"r").read()
rasmol_text = re.sub('load pdb ".*"','load pdb "%s"',rasmol_text) rasmol_text = re.sub('load pdb ".*"','load pdb "%s"',rasmol_text)
else: else:
rasmol_text = rasmol_template rasmol_text = rasmol_template
@ -106,7 +111,7 @@ class rasmol:
f = open("tmp.rasmol","w") f = open("tmp.rasmol","w")
text = rasmol_text % "tmp.pdb" text = rasmol_text % "tmp.pdb"
print >>f,text print(text, file=f)
f.close() f.close()
# run RasMol to create image in tmp.gif # run RasMol to create image in tmp.gif
@ -123,14 +128,14 @@ class rasmol:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def all(self,*list): def all(self,*arglist):
# if RasMol script specified, read it # if RasMol script specified, read it
# replace load pdb "file" with load pdb "%s" # replace load pdb "file" with load pdb "%s"
# if no RasMol script specified, just use rasmol_template # if no RasMol script specified, just use rasmol_template
if len(list) == 1: if len(arglist) == 1:
rasmol_text = open(list[0],"r").read() rasmol_text = open(arglist[0],"r").read()
rasmol_text = re.sub('load pdb ".*"','load pdb "%s"',rasmol_text) rasmol_text = re.sub('load pdb ".*"','load pdb "%s"',rasmol_text)
else: else:
rasmol_text = rasmol_template rasmol_text = rasmol_template
@ -160,10 +165,10 @@ class rasmol:
text = rasmol_text % file_pdb text = rasmol_text % file_pdb
file_rasmol = "tmp%s.rasmol" % ncount file_rasmol = "tmp%s.rasmol" % ncount
f = open(file_rasmol,"w") f = open(file_rasmol,"w")
print >>f,text print(text, file=f)
f.close() f.close()
print time, print(time, end=' ')
sys.stdout.flush() sys.stdout.flush()
n += 1 n += 1
@ -172,7 +177,7 @@ class rasmol:
self.start() self.start()
loop = n loop = n
for n in xrange(loop): for n in range(loop):
if n < 10: if n < 10:
ncount = "000" + str(n) ncount = "000" + str(n)
elif n < 100: elif n < 100:
@ -196,19 +201,19 @@ class rasmol:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def run(self,*list): def run(self,*arglist):
# create tmp.pdb with atom data # create tmp.pdb with atom data
n = list[0] n = arglist[0]
self.pdb.single(n,"tmp.pdb") self.pdb.single(n,"tmp.pdb")
# if RasMol script specified, read it # if RasMol script specified, read it
# replace load pdb "file" with load pdb "%s" # replace load pdb "file" with load pdb "%s"
# if no RasMol script specified, just use rasmol_template # if no RasMol script specified, just use rasmol_template
if len(list) == 3: if len(arglist) == 3:
rasmol_text = open(list[2],"r").read() rasmol_text = open(arglist[2],"r").read()
rasmol_text = re.sub('load pdb ".*"','load pdb "%s"',rasmol_text) rasmol_text = re.sub('load pdb ".*"','load pdb "%s"',rasmol_text)
else: else:
rasmol_text = rasmol_template rasmol_text = rasmol_template
@ -217,7 +222,7 @@ class rasmol:
f = open("tmp.rasmol","w") f = open("tmp.rasmol","w")
text = rasmol_template % "tmp.pdb" text = rasmol_template % "tmp.pdb"
print >>f,text print(text, file=f)
f.close() f.close()
# run RasMol to create image in tmp.gif # run RasMol to create image in tmp.gif
@ -226,7 +231,7 @@ class rasmol:
self.__call__("source tmp.rasmol") self.__call__("source tmp.rasmol")
self.enter() self.enter()
if len(list) > 1: newfile = list[1] if len(arglist) > 1: newfile = arglist[1]
else: newfile = "tmp.rasmol" else: newfile = "tmp.rasmol"
self.__call__("write script %s" % newfile) self.__call__("write script %s" % newfile)
self.stop() self.stop()

View File

@ -8,6 +8,17 @@
# raster tool # raster tool
# Imports and external programs
from __future__ import print_function, absolute_import
import sys, os, re
try:
import commands
except ImportError:
import subprocess as commands
from vizinfo import vizinfo
from math import fabs,atan,cos,sin
oneline = "3d visualization via Raster3d program" oneline = "3d visualization via Raster3d program"
docstr = """ docstr = """
@ -16,8 +27,8 @@ r = raster(d) create Raster3d wrapper for data in d
d = atom snapshot object (dump, data) d = atom snapshot object (dump, data)
r.bg("black") set background color (def = "black") r.bg("black") set background color (def = "black")
r.size(N) set image size to NxN r.size(N) set image size to NxN
r.size(N,M) set image size to NxM r.size(N,M) set image size to NxM
r.rotate(60,135) view from z theta and azimuthal phi (def = 60,30) r.rotate(60,135) view from z theta and azimuthal phi (def = 60,30)
r.shift(x,y) translate by x,y pixels in view window (def = 0,0) r.shift(x,y) translate by x,y pixels in view window (def = 0,0)
r.zoom(0.5) scale image by factor (def = 1) r.zoom(0.5) scale image by factor (def = 1)
@ -49,9 +60,9 @@ r.nolabel() delete all labels
x,y coords = -0.5 to 0.5, "h" or "t" for Helvetica or Times font x,y coords = -0.5 to 0.5, "h" or "t" for Helvetica or Times font
size = fontsize (e.g. 10), "red" = color of text size = fontsize (e.g. 10), "red" = color of text
r.acol(2,"green") set atom colors by atom type (1-N) r.acol(2,"green") set atom colors by atom type (1-N)
r.acol([2,4],["red","blue"]) 1st arg = one type or list of types r.acol([2,4],["red","blue"]) 1st arg = one type or list of types
r.acol(0,"blue") 2nd arg = one color or list of colors r.acol(0,"blue") 2nd arg = one color or list of colors
r.acol(range(20),["red","blue"]) if list lengths unequal, interpolate r.acol(range(20),["red","blue"]) if list lengths unequal, interpolate
r.acol(range(10),"loop") assign colors in loop, randomly ordered r.acol(range(10),"loop") assign colors in loop, randomly ordered
@ -61,19 +72,19 @@ r.acol(range(10),"loop") assign colors in loop, randomly ordered
r.arad([1,2],[0.5,0.3]) set atom radii, same rules as acol() r.arad([1,2],[0.5,0.3]) set atom radii, same rules as acol()
r.bcol() set bond color, same args as acol() r.bcol() set bond color, same args as acol()
r.brad() set bond thickness, same args as arad() r.brad() set bond thickness, same args as arad()
r.tcol() set triangle color, same args as acol() r.tcol() set triangle color, same args as acol()
r.tfill() set triangle fill, 0 fill, 1 line, 2 both r.tfill() set triangle fill, 0 fill, 1 line, 2 both
r.lcol() set line color, same args as acol() r.lcol() set line color, same args as acol()
r.lrad() set line thickness, same args as arad() r.lrad() set line thickness, same args as arad()
r.adef() set atom/bond/tri/line properties to default r.adef() set atom/bond/tri/line properties to default
r.bdef() default = "loop" for colors, 0.45 for radii r.bdef() default = "loop" for colors, 0.45 for radii
r.tdef() default = 0.25 for bond/line thickness r.tdef() default = 0.25 for bond/line thickness
r.ldef() default = 0 fill r.ldef() default = 0 fill
by default 100 types are assigned by default 100 types are assigned
if atom/bond/tri/line has type > # defined properties, is an error if atom/bond/tri/line has type > # defined properties, is an error
@ -108,16 +119,10 @@ colors["nickname"] = [R,G,B] set new RGB values from 0 to 255
# vizinfo = scene attributes # vizinfo = scene attributes
# xtrans,ytrans,ztrans = translation factors computed by Raster3d # 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 try: from DEFAULTS import PIZZA_RENDER
except: PIZZA_RENDER = "render" except: PIZZA_RENDER = "render"
try: from DEFAULTS import PIZZA_LABEL3D try: from DEFAULTS import PIZZA_LABEL3D
except: PIZZA_LABEL3D = "label3d" except: PIZZA_LABEL3D = "render -labels"
try: from DEFAULTS import PIZZA_DISPLAY try: from DEFAULTS import PIZZA_DISPLAY
except: PIZZA_DISPLAY = "display" except: PIZZA_DISPLAY = "display"
@ -152,6 +157,8 @@ class raster:
self.tdef() self.tdef()
self.ldef() self.ldef()
os.environ["TMPDIR"] = "/tmp"
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def bg(self,color): def bg(self,color):
@ -222,7 +229,7 @@ class raster:
self.xtrans = self.ytrans = self.ztrans = 0.0 self.xtrans = self.ytrans = self.ztrans = 0.0
output = self.single(1,self.file,box,atoms,bonds,tris,lines) 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) nums = re.findall("translation to:\s*(\S*)\s*(\S*)\s*(\S*)\s",output)
self.xtrans = float(nums[0][0]) self.xtrans = float(nums[0][0])
self.ytrans = float(nums[0][1]) self.ytrans = float(nums[0][1])
@ -297,16 +304,16 @@ class raster:
self.scale = self.scale_start + \ self.scale = self.scale_start + \
fraction*(self.scale_stop - self.scale_start) fraction*(self.scale_stop - self.scale_start)
if n == nstart or self.panflag: if n == nstart or self.panflag:
self.xtrans = self.ytrans = self.ztrans = 0.0 self.xtrans = self.ytrans = self.ztrans = 0.0
output = self.single(1,file,box,atoms,bonds,tris,lines) output = self.single(1,file,box,atoms,bonds,tris,lines)
nums = re.findall("translation to:\s*(\S*)\s*(\S*)\s*(\S*)\s",output) nums = re.findall("translation to:\s*(\S*)\s*(\S*)\s*(\S*)\s",output)
self.xtrans = float(nums[0][0]) self.xtrans = float(nums[0][0])
self.ytrans = float(nums[0][1]) self.ytrans = float(nums[0][1])
self.ztrans = float(nums[0][2]) self.ztrans = float(nums[0][2])
self.single(0,file,box,atoms,bonds,tris,lines) self.single(0,file,box,atoms,bonds,tris,lines)
print time, print(time, end=' ')
sys.stdout.flush() sys.stdout.flush()
i += 1 i += 1
n += 1 n += 1
@ -344,20 +351,20 @@ class raster:
self.scale = self.scale_start + \ self.scale = self.scale_start + \
fraction*(self.scale_stop - self.scale_start) fraction*(self.scale_stop - self.scale_start)
if n == nstart or self.panflag: if n == nstart or self.panflag:
self.xtrans = self.ytrans = self.ztrans = 0.0 self.xtrans = self.ytrans = self.ztrans = 0.0
output = self.single(1,file,box,atoms,bonds,tris,lines) output = self.single(1,file,box,atoms,bonds,tris,lines)
nums = re.findall("translation to:\s*(\S*)\s*(\S*)\s*(\S*)\s",output) nums = re.findall("translation to:\s*(\S*)\s*(\S*)\s*(\S*)\s",output)
self.xtrans = float(nums[0][0]) self.xtrans = float(nums[0][0])
self.ytrans = float(nums[0][1]) self.ytrans = float(nums[0][1])
self.ztrans = float(nums[0][2]) self.ztrans = float(nums[0][2])
self.single(0,file,box,atoms,bonds,tris,lines) self.single(0,file,box,atoms,bonds,tris,lines)
print n, print(n, end=' ')
sys.stdout.flush() sys.stdout.flush()
n += 1 n += 1
print "\n%d images" % ncount print("\n%d images" % ncount)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -374,7 +381,7 @@ class raster:
(self.xpixels,self.ypixels,color[0],color[1],color[2], (self.xpixels,self.ypixels,color[0],color[1],color[2],
self.eye,matrix,self.xtrans+xshift,self.ytrans+yshift, self.eye,matrix,self.xtrans+xshift,self.ytrans+yshift,
self.ztrans,1.6*self.distance/self.scale) self.ztrans,1.6*self.distance/self.scale)
print >>f,header, print(header, end=' ', file=f)
# draw box if boxflag or flag is set # draw box if boxflag or flag is set
# flag = 1 is a pre-call of single to set frame size correctly # flag = 1 is a pre-call of single to set frame size correctly
@ -385,53 +392,53 @@ class raster:
ncolor = self.vizinfo.nacolor ncolor = self.vizinfo.nacolor
for atom in atoms: for atom in atoms:
itype = int(atom[1]) 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] color = self.vizinfo.acolor[itype]
rad = self.vizinfo.arad[itype] rad = self.vizinfo.arad[itype]
print >>f,2 print(2, file=f)
print >>f,atom[2],atom[3],atom[4],rad,color[0],color[1],color[2] print(atom[2],atom[3],atom[4],rad,color[0],color[1],color[2], file=f)
# need to include vizinfo.tfill options # need to include vizinfo.tfill options
ncolor = self.vizinfo.ntcolor ncolor = self.vizinfo.ntcolor
for tri in tris: for tri in tris:
itype = int(tri[1]) 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] color = self.vizinfo.tcolor[itype]
print >>f,1 print(1, file=f)
print >>f,tri[2],tri[3],tri[4],tri[5],tri[6],tri[7], \ 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] tri[8],tri[9],tri[10],color[0],color[1],color[2], file=f)
bound = 0.25 * self.distance bound = 0.25 * self.distance
ncolor = self.vizinfo.nbcolor ncolor = self.vizinfo.nbcolor
for bond in bonds: for bond in bonds:
itype = int(bond[1]) 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] color = self.vizinfo.bcolor[itype]
rad = self.vizinfo.brad[itype] rad = self.vizinfo.brad[itype]
if fabs(bond[2]-bond[5]) > bound or fabs(bond[3]-bond[6]) > bound: if fabs(bond[2]-bond[5]) > bound or fabs(bond[3]-bond[6]) > bound:
continue continue
print >>f,5 print(5, file=f)
print >>f,bond[2],bond[3],bond[4],rad, \ print(bond[2],bond[3],bond[4],rad, \
bond[5],bond[6],bond[7],0.0,color[0],color[1],color[2] bond[5],bond[6],bond[7],0.0,color[0],color[1],color[2], file=f)
ncolor = self.vizinfo.nlcolor ncolor = self.vizinfo.nlcolor
for line in lines: for line in lines:
itype = int(line[1]) 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] color = self.vizinfo.lcolor[itype]
thick = self.vizinfo.lrad[itype] thick = self.vizinfo.lrad[itype]
print >>f,3 print(3, file=f)
print >>f,line[2],line[3],line[4],thick, \ print(line[2],line[3],line[4],thick, \
line[5],line[6],line[7],thick,color[0],color[1],color[2] line[5],line[6],line[7],thick,color[0],color[1],color[2], file=f)
for label in self.labels: for label in self.labels:
print >>f,15 print(15, file=f)
print >>f,10 print(10, file=f)
print >>f,label[2],label[3],label[4] print(label[2],label[3],label[4], file=f)
print >>f,11 print(11, file=f)
print >>f,label[0],label[1],0.0,label[5][0],label[5][1],label[5][2] print(label[0],label[1],0.0,label[5][0],label[5][1],label[5][2], file=f)
print >>f,label[6] print(label[6], file=f)
f.close() f.close()
@ -446,26 +453,26 @@ class raster:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def adef(self): def adef(self):
self.vizinfo.setcolors("atom",range(100),"loop") self.vizinfo.setcolors("atom",list(range(100)),"loop")
self.vizinfo.setradii("atom",range(100),0.45) self.vizinfo.setradii("atom",list(range(100)),0.45)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def bdef(self): def bdef(self):
self.vizinfo.setcolors("bond",range(100),"loop") self.vizinfo.setcolors("bond",list(range(100)),"loop")
self.vizinfo.setradii("bond",range(100),0.25) self.vizinfo.setradii("bond",list(range(100)),0.25)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def tdef(self): def tdef(self):
self.vizinfo.setcolors("tri",range(100),"loop") self.vizinfo.setcolors("tri",list(range(100)),"loop")
self.vizinfo.setfills("tri",range(100),0) self.vizinfo.setfills("tri",list(range(100)),0)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def ldef(self): def ldef(self):
self.vizinfo.setcolors("line",range(100),"loop") self.vizinfo.setcolors("line",list(range(100)),"loop")
self.vizinfo.setradii("line",range(100),0.25) self.vizinfo.setradii("line",list(range(100)),0.25)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -526,32 +533,32 @@ def box_write(f,box,color,thick):
green = color[1] green = color[1]
blue = color[2] blue = color[2]
print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ 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) (xlo,ylo,zlo,thick,xhi,ylo,zlo,thick,red,green,blue), file=f)
print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ 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) (xlo,yhi,zlo,thick,xhi,yhi,zlo,thick,red,green,blue), file=f)
print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ 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) (xlo,ylo,zhi,thick,xhi,ylo,zhi,thick,red,green,blue), file=f)
print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ 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) (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" % \ 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) (xlo,ylo,zlo,thick,xlo,yhi,zlo,thick,red,green,blue), file=f)
print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ 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) (xhi,ylo,zlo,thick,xhi,yhi,zlo,thick,red,green,blue), file=f)
print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ 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) (xlo,ylo,zhi,thick,xlo,yhi,zhi,thick,red,green,blue), file=f)
print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ 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) (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" % \ 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) (xlo,ylo,zlo,thick,xlo,ylo,zhi,thick,red,green,blue), file=f)
print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ 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) (xhi,ylo,zlo,thick,xhi,ylo,zhi,thick,red,green,blue), file=f)
print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ 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) (xlo,yhi,zlo,thick,xlo,yhi,zhi,thick,red,green,blue), file=f)
print >>f,"3\n%g %g %g %g %g %g %g %g %g %g %g" % \ 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) (xhi,yhi,zlo,thick,xhi,yhi,zhi,thick,red,green,blue), file=f)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# compute 3x3 rotation matrix for viewing angle # compute 3x3 rotation matrix for viewing angle
@ -634,7 +641,7 @@ def rotation_matrix(coord1,angle1,coord2,angle2):
# each line padded with 0.0 for 4x4 raster3d matrix # each line padded with 0.0 for 4x4 raster3d matrix
matrix = "%g %g %g 0.0\n%g %g %g 0.0\n%g %g %g 0.0" % \ matrix = "%g %g %g 0.0\n%g %g %g 0.0\n%g %g %g 0.0" % \
(c11,c12,c13,c21,c22,c23,c31,c32,c33) (c11,c12,c13,c21,c22,c23,c31,c32,c33)
return matrix return matrix
# -------------------------------------------------------------------- # --------------------------------------------------------------------

View File

@ -8,6 +8,18 @@
# svg tool # svg tool
# Imports and external programs
from __future__ import print_function, absolute_import
import sys, os, re
try:
import commands
except ImportError:
import subprocess as commands
import functools
from vizinfo import vizinfo
from math import sqrt,atan,cos,sin,fabs
oneline = "3d visualization via SVG files" oneline = "3d visualization via SVG files"
docstr = """ docstr = """
@ -16,8 +28,8 @@ s = svg(d) create SVG object for data in d
d = atom snapshot object (dump, data) d = atom snapshot object (dump, data)
s.bg("black") set background color (def = "black") s.bg("black") set background color (def = "black")
s.size(N) set image size to NxN s.size(N) set image size to NxN
s.size(N,M) set image size to NxM s.size(N,M) set image size to NxM
s.rotate(60,135) view from z theta and azimuthal phi (def = 60,30) s.rotate(60,135) view from z theta and azimuthal phi (def = 60,30)
s.shift(x,y) translate by x,y pixels in view window (def = 0,0) s.shift(x,y) translate by x,y pixels in view window (def = 0,0)
s.zoom(0.5) scale image by factor (def = 1) s.zoom(0.5) scale image by factor (def = 1)
@ -49,9 +61,9 @@ s.nolabel() delete all labels
x,y coords = -0.5 to 0.5, "h" or "t" for Helvetica or Times font x,y coords = -0.5 to 0.5, "h" or "t" for Helvetica or Times font
size = fontsize (e.g. 10), "red" = color of text size = fontsize (e.g. 10), "red" = color of text
s.acol(2,"green") set atom colors by atom type (1-N) s.acol(2,"green") set atom colors by atom type (1-N)
s.acol([2,4],["red","blue"]) 1st arg = one type or list of types s.acol([2,4],["red","blue"]) 1st arg = one type or list of types
s.acol(0,"blue") 2nd arg = one color or list of colors s.acol(0,"blue") 2nd arg = one color or list of colors
s.acol(range(20),["red","blue"]) if list lengths unequal, interpolate s.acol(range(20),["red","blue"]) if list lengths unequal, interpolate
s.acol(range(10),"loop") assign colors in loop, randomly ordered s.acol(range(10),"loop") assign colors in loop, randomly ordered
@ -61,19 +73,19 @@ s.acol(range(10),"loop") assign colors in loop, randomly ordered
s.arad([1,2],[0.5,0.3]) set atom radii, same rules as acol() s.arad([1,2],[0.5,0.3]) set atom radii, same rules as acol()
s.bcol() set bond color, same args as acol() s.bcol() set bond color, same args as acol()
s.brad() set bond thickness, same args as arad() s.brad() set bond thickness, same args as arad()
s.tcol() set triangle color, same args as acol() s.tcol() set triangle color, same args as acol()
s.tfill() set triangle fill, 0 fill, 1 line, 2 both s.tfill() set triangle fill, 0 fill, 1 line, 2 both
s.lcol() set line color, same args as acol() s.lcol() set line color, same args as acol()
s.lrad() set line thickness, same args as arad() s.lrad() set line thickness, same args as arad()
s.adef() set atom/bond/tri/line properties to default s.adef() set atom/bond/tri/line properties to default
s.bdef() default = "loop" for colors, 0.45 for radii s.bdef() default = "loop" for colors, 0.45 for radii
s.tdef() default = 0.25 for bond/line thickness s.tdef() default = 0.25 for bond/line thickness
s.ldef() default = 0 fill s.ldef() default = 0 fill
by default 100 types are assigned by default 100 types are assigned
if atom/bond/tri/line has type > # defined properties, is an error if atom/bond/tri/line has type > # defined properties, is an error
@ -110,12 +122,6 @@ s.thick = 2.0 pixel thickness of black atom border
# bgcol = color of background # bgcol = color of background
# vizinfo = scene attributes # 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 try: from DEFAULTS import PIZZA_DISPLAY
except: PIZZA_DISPLAY = "display" except: PIZZA_DISPLAY = "display"
@ -248,10 +254,10 @@ class svg:
fraction = float(i) / (ncount-1) fraction = float(i) / (ncount-1)
if self.select != "": if self.select != "":
newstr = self.select % fraction newstr = self.select % fraction
data.aselect.test(newstr,time) data.aselect.test(newstr,time)
time,boxone,atoms,bonds,tris,lines = data.viz(which) time,boxone,atoms,bonds,tris,lines = data.viz(which)
if self.boxflag < 2: box = boxone if self.boxflag < 2: box = boxone
if n == nstart: self.distance = compute_distance(box) if n == nstart: self.distance = compute_distance(box)
@ -261,7 +267,7 @@ class svg:
elif n < 1000: file = self.file + "0" + str(n) elif n < 1000: file = self.file + "0" + str(n)
else: file = self.file + str(n) else: file = self.file + str(n)
if self.panflag: if self.panflag:
self.ztheta = self.ztheta_start + \ self.ztheta = self.ztheta_start + \
fraction*(self.ztheta_stop - self.ztheta_start) fraction*(self.ztheta_stop - self.ztheta_start)
self.azphi = self.azphi_start + \ self.azphi = self.azphi_start + \
@ -270,10 +276,10 @@ class svg:
fraction*(self.scale_stop - self.scale_start) fraction*(self.scale_stop - self.scale_start)
scaleflag = 0 scaleflag = 0
if n == nstart or self.panflag: scaleflag = 1 if n == nstart or self.panflag: scaleflag = 1
self.single(file,box,atoms,bonds,tris,lines,scaleflag) self.single(file,box,atoms,bonds,tris,lines,scaleflag)
print time, print(time, end=' ')
sys.stdout.flush() sys.stdout.flush()
i += 1 i += 1
n += 1 n += 1
@ -290,7 +296,7 @@ class svg:
for i in range(ncount): for i in range(ncount):
fraction = float(i) / (ncount-1) fraction = float(i) / (ncount-1)
if self.select != "": if self.select != "":
newstr = self.select % fraction newstr = self.select % fraction
data.aselect.test(newstr,ntime) data.aselect.test(newstr,ntime)
time,boxone,atoms,bonds,tris,lines = data.viz(which) time,boxone,atoms,bonds,tris,lines = data.viz(which)
@ -303,23 +309,23 @@ class svg:
elif n < 1000: file = self.file + "0" + str(n) elif n < 1000: file = self.file + "0" + str(n)
else: file = self.file + str(n) else: file = self.file + str(n)
if self.panflag: if self.panflag:
self.ztheta = self.ztheta_start + \ self.ztheta = self.ztheta_start + \
fraction*(self.ztheta_stop - self.ztheta_start) fraction*(self.ztheta_stop - self.ztheta_start)
self.azphi = self.azphi_start + \ self.azphi = self.azphi_start + \
fraction*(self.azphi_stop - self.azphi_start) fraction*(self.azphi_stop - self.azphi_start)
self.scale = self.scale_start + \ self.scale = self.scale_start + \
fraction*(self.scale_stop - self.scale_start) fraction*(self.scale_stop - self.scale_start)
scaleflag = 0 scaleflag = 0
if n == nstart or self.panflag: scaleflag = 1 if n == nstart or self.panflag: scaleflag = 1
self.single(file,box,atoms,bonds,tris,lines,scaleflag) self.single(file,box,atoms,bonds,tris,lines,scaleflag)
print n, print(n, end=' ')
sys.stdout.flush() sys.stdout.flush()
n += 1 n += 1
print "\n%d images" % ncount print("\n%d images" % ncount)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -420,7 +426,7 @@ class svg:
# convert objects by factor/offset and sort by z-depth # convert objects by factor/offset and sort by z-depth
self.convert(olist) self.convert(olist)
olist.sort(cmprz) olist.sort(key = functools.cmp_to_key(cmprz))
# write SVG file # write SVG file
@ -430,19 +436,19 @@ class svg:
header = '<?xml version="1.0"?> <svg height="%s" width="%s" >' % \ header = '<?xml version="1.0"?> <svg height="%s" width="%s" >' % \
(self.ypixels,self.xpixels) (self.ypixels,self.xpixels)
header += '<g style="fill-opacity:1.0; stroke:black; stroke-width:0.001;">' header += '<g style="fill-opacity:1.0; stroke:black; stroke-width:0.001;">'
print >>f,header print(header, file=f)
color = '<rect x="0" y="0" height="%s" width="%s" ' % \ color = '<rect x="0" y="0" height="%s" width="%s" ' % \
(self.ypixels,self.xpixels) (self.ypixels,self.xpixels)
color += 'fill="rgb(%s,%s,%s)"/>' % \ color += 'fill="rgb(%s,%s,%s)"/>' % \
(self.bgcol[0]*255,self.bgcol[1]*255,self.bgcol[2]*255) (self.bgcol[0]*255,self.bgcol[1]*255,self.bgcol[2]*255)
print >>f,color print(color, file=f)
for element in olist: self.write(f,0,element) for element in olist: self.write(f,0,element)
for label in self.labels: self.write(f,1,label) for label in self.labels: self.write(f,1,label)
footer = "</g></svg>" footer = "</g></svg>"
print >> f,footer print(footer, file=f)
f.close() f.close()
@ -512,82 +518,82 @@ class svg:
if flag == 0: if flag == 0:
if obj[0] == 0: # atom with its color and radius if obj[0] == 0: # atom with its color and radius
itype = int(obj[1]) itype = int(obj[1])
if itype > self.vizinfo.nacolor: if itype > self.vizinfo.nacolor:
raise StandardError,"atom type too big" raise Exception("atom type too big")
color = self.vizinfo.acolor[itype] color = self.vizinfo.acolor[itype]
rad = self.vizinfo.arad[itype] rad = self.vizinfo.arad[itype]
print >>f,'<circle cx="%s" cy="%s" r="%s" fill="rgb(%s,%s,%s)" stroke-width="%s" />' % \ print('<circle cx="%s" cy="%s" r="%s" fill="rgb(%s,%s,%s)" stroke-width="%s" />' % \
(obj[2],obj[3],rad*self.factor, (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) elif obj[0] == 1: # tri with its color (need to add fill type)
itype = int(obj[1]) itype = int(obj[1])
if itype > self.vizinfo.ntcolor: if itype > self.vizinfo.ntcolor:
raise StandardError,"tri type too big" raise Exception("tri type too big")
color = self.vizinfo.tcolor[itype] color = self.vizinfo.tcolor[itype]
print >>f,'<polygon points= "%s,%s %s,%s %s,%s" fill="rgb(%s,%s,%s)" stroke="black" stroke-width="0.01" />' % \ print('<polygon points= "%s,%s %s,%s %s,%s" fill="rgb(%s,%s,%s)" stroke="black" stroke-width="0.01" />' % \
(obj[2],obj[3],obj[5],obj[6],obj[8],obj[9], (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 elif obj[0] == 2: # bond with its color and thickness
itype = int(obj[1]) itype = int(obj[1])
if itype > self.vizinfo.nbcolor: if itype > self.vizinfo.nbcolor:
raise StandardError,"bond type too big" raise Exception("bond type too big")
color = self.vizinfo.bcolor[itype] color = self.vizinfo.bcolor[itype]
thick = self.vizinfo.brad[itype] thick = self.vizinfo.brad[itype]
print >>f,'<line x1="%s" y1="%s" x2="%s" y2="%s" stroke="rgb(%s,%s,%s)" stroke-width="%s" />' % \ print('<line x1="%s" y1="%s" x2="%s" y2="%s" stroke="rgb(%s,%s,%s)" stroke-width="%s" />' % \
(obj[2],obj[3],obj[5],obj[6], (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 elif obj[0] == 3: # line with its color and thickness
itype = int(obj[1]) itype = int(obj[1])
if itype > self.vizinfo.nlcolor: if itype > self.vizinfo.nlcolor:
raise StandardError,"line type too big" raise Exception("line type too big")
color = self.vizinfo.lcolor[itype] color = self.vizinfo.lcolor[itype]
thick = self.vizinfo.lrad[itype] thick = self.vizinfo.lrad[itype]
print >>f,'<line x1="%s" y1="%s" x2="%s" y2="%s" stroke="rgb(%s,%s,%s)" stroke-width="%s" />' % \ print('<line x1="%s" y1="%s" x2="%s" y2="%s" stroke="rgb(%s,%s,%s)" stroke-width="%s" />' % \
(obj[2],obj[3],obj[5],obj[6], (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 elif obj[0] == 4: # box line with built-in color and thickness
color = self.bxcol color = self.bxcol
thick = self.bxthick thick = self.bxthick
print >>f,'<line x1="%s" y1="%s" x2="%s" y2="%s" stroke="rgb(%s,%s,%s)" stroke-width="%s" />' % \ print('<line x1="%s" y1="%s" x2="%s" y2="%s" stroke="rgb(%s,%s,%s)" stroke-width="%s" />' % \
(obj[2],obj[3],obj[5],obj[6], (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: elif flag == 1:
x = (obj[0]*self.xpixels) + (self.xpixels/2.0) x = (obj[0]*self.xpixels) + (self.xpixels/2.0)
y = (self.ypixels/2.0) - (obj[1]*self.ypixels) y = (self.ypixels/2.0) - (obj[1]*self.ypixels)
color = obj[4] color = obj[4]
print >>f,'<text x="%s" y="%s" font-size="%s" font-family="%s" stroke="rgb(%s,%s,%s)" fill="rgb(%s,%s,%s"> %s </text>' % \ print('<text x="%s" y="%s" font-size="%s" font-family="%s" stroke="rgb(%s,%s,%s)" fill="rgb(%s,%s,%s"> %s </text>' % \
(x,y,obj[3],obj[2],color[0]*255,color[1]*255,color[2]*255, (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): def adef(self):
self.vizinfo.setcolors("atom",range(100),"loop") self.vizinfo.setcolors("atom",list(range(100)),"loop")
self.vizinfo.setradii("atom",range(100),0.45) self.vizinfo.setradii("atom",list(range(100)),0.45)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def bdef(self): def bdef(self):
self.vizinfo.setcolors("bond",range(100),"loop") self.vizinfo.setcolors("bond",list(range(100)),"loop")
self.vizinfo.setradii("bond",range(100),0.25) self.vizinfo.setradii("bond",list(range(100)),0.25)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def tdef(self): def tdef(self):
self.vizinfo.setcolors("tri",range(100),"loop") self.vizinfo.setcolors("tri",list(range(100)),"loop")
self.vizinfo.setfills("tri",range(100),0) self.vizinfo.setfills("tri",list(range(100)),0)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def ldef(self): def ldef(self):
self.vizinfo.setcolors("line",range(100),"loop") self.vizinfo.setcolors("line",list(range(100)),"loop")
self.vizinfo.setradii("line",range(100),0.25) self.vizinfo.setradii("line",list(range(100)),0.25)
# -------------------------------------------------------------------- # --------------------------------------------------------------------

View File

@ -8,18 +8,26 @@
# tdump tool # tdump tool
# Imports and external programs
from __future__ import print_function, absolute_import
import sys, re, glob, types
import functools
from math import sqrt
from os import popen
oneline = "Read dump files with triangle info" oneline = "Read dump files with triangle info"
docstr = """ docstr = """
t = tdump("dump.one") read in one or more dump files t = tdump("dump.one") read in one or more dump files
t = tdump("dump.1 dump.2.gz") can be gzipped t = tdump("dump.1 dump.2.gz") can be gzipped
t = tdump("dump.*") wildcard expands to multiple files t = tdump("dump.*") wildcard expands to multiple files
t = tdump("dump.*",0) two args = store filenames, but don't read t = tdump("dump.*",0) two args = store filenames, but don't read
incomplete and duplicate snapshots are deleted incomplete and duplicate snapshots are deleted
no column name assignment is performed no column name assignment is performed
time = t.next() read next snapshot from dump files time = t.next() read next snapshot from dump files
used with 2-argument constructor to allow reading snapshots one-at-a-time used with 2-argument constructor to allow reading snapshots one-at-a-time
snapshot will be skipped only if another snapshot has same time stamp snapshot will be skipped only if another snapshot has same time stamp
@ -43,7 +51,7 @@ time,box,atoms,bonds,tris,lines = t.viz(index) return list of viz objects
id,type are from associated atom id,type are from associated atom
lines = NULL lines = NULL
t.owrap(...) wrap tris to same image as their atoms t.owrap(...) wrap tris to same image as their atoms
owrap() is called by dump tool's owrap() owrap() is called by dump tool's owrap()
useful for wrapping all molecule's atoms/tris the same so it is contiguous useful for wrapping all molecule's atoms/tris the same so it is contiguous
@ -67,12 +75,6 @@ t.owrap(...) wrap tris to same image as their atoms
# xlo,xhi,ylo,yhi,zlo,zhi = box bounds (float) # 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 # 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: try:
import numpy as np import numpy as np
oldnumeric = False oldnumeric = False
@ -100,7 +102,7 @@ class tdump:
self.flist = [] self.flist = []
for word in words: self.flist += glob.glob(word) for word in words: self.flist += glob.glob(word)
if len(self.flist) == 0 and len(list) == 1: 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: if len(list) == 1:
self.increment = 0 self.increment = 0
@ -125,26 +127,26 @@ class tdump:
snap = self.read_snapshot(f) snap = self.read_snapshot(f)
while snap: while snap:
self.snaps.append(snap) self.snaps.append(snap)
print snap.time, print(snap.time, end=' ')
sys.stdout.flush() sys.stdout.flush()
snap = self.read_snapshot(f) snap = self.read_snapshot(f)
f.close() f.close()
print print()
# sort entries by timestep, cull duplicates # 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.cull()
self.nsnaps = len(self.snaps) self.nsnaps = len(self.snaps)
print "read %d snapshots" % self.nsnaps print("read %d snapshots" % self.nsnaps)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# read next snapshot from list of files # read next snapshot from list of files
def next(self): 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 # read next snapshot in current file using eof as pointer
# if fail, try next file # if fail, try next file
@ -156,15 +158,15 @@ class tdump:
snap = self.read_snapshot(f) snap = self.read_snapshot(f)
if not snap: if not snap:
self.nextfile += 1 self.nextfile += 1
if self.nextfile == len(self.flist): return -1 if self.nextfile == len(self.flist): return -1
f.close() f.close()
self.eof = 0 self.eof = 0
continue continue
self.eof = f.tell() self.eof = f.tell()
f.close() f.close()
try: try:
self.findtime(snap.time) self.findtime(snap.time)
continue continue
except: break except: break
self.snaps.append(snap) self.snaps.append(snap)
@ -198,14 +200,14 @@ class tdump:
if snap.natoms: if snap.natoms:
words = f.readline().split() words = f.readline().split()
ncol = len(words) ncol = len(words)
for i in xrange(1,snap.natoms): for i in range(1,snap.natoms):
words += f.readline().split() words += f.readline().split()
floats = map(float,words) floats = list(map(float,words))
if oldnumeric: atoms = np.zeros((snap.natoms,ncol),np.Float) if oldnumeric: atoms = np.zeros((snap.natoms,ncol),np.Float)
else: atoms = np.zeros((snap.natoms,ncol),np.float) else: atoms = np.zeros((snap.natoms,ncol),np.float)
start = 0 start = 0
stop = ncol stop = ncol
for i in xrange(snap.natoms): for i in range(snap.natoms):
atoms[i] = floats[start:stop] atoms[i] = floats[start:stop]
start = stop start = stop
stop += ncol stop += ncol
@ -220,7 +222,7 @@ class tdump:
def map(self,*pairs): def map(self,*pairs):
if len(pairs) % 2 != 0: 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): for i in range(0,len(pairs),2):
j = i + 1 j = i + 1
self.names[pairs[j]] = pairs[i]-1 self.names[pairs[j]] = pairs[i]-1
@ -250,9 +252,9 @@ class tdump:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def findtime(self,n): def findtime(self,n):
for i in xrange(self.nsnaps): for i in range(self.nsnaps):
if self.snaps[i].time == n: return i 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 # delete successive snapshots with duplicate time stamp
@ -295,11 +297,11 @@ class tdump:
corner3y = self.names["corner3y"] corner3y = self.names["corner3y"]
corner3z = self.names["corner3z"] corner3z = self.names["corner3z"]
# create line list from id,type,corner1x,...corner3z # create tris list from id,type,corner1x,...corner3z
# don't add line if all 4 values are 0 since not a line # don't add tri if all 4 values are 0 since not a line
tris = [] tris = []
for i in xrange(snap.natoms): for i in range(snap.natoms):
atom = snap.atoms[i] atom = snap.atoms[i]
c1 = [atom[corner1x],atom[corner1y],atom[corner1z]] c1 = [atom[corner1x],atom[corner1y],atom[corner1z]]
c2 = [atom[corner2x],atom[corner2y],atom[corner2z]] 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 # 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 # 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] tag = atoms[i][id]
idump = idsdump[tag] idump = idsdump[tag]
jdump = idsdump[atomsdump[idump][iother]] jdump = idsdump[atomsdump[idump][iother]]

View File

@ -8,6 +8,15 @@
# vcr tool # vcr tool
# Imports and external programs
from __future__ import print_function, absolute_import
try:
from Tkinter import *
except ImportError:
from tkinter import *
import types
oneline = "VCR-style GUI for 3d interactive OpenGL visualization" oneline = "VCR-style GUI for 3d interactive OpenGL visualization"
docstr = """ docstr = """
@ -16,26 +25,26 @@ v.add(gl) add a gl window to vcr GUI
Actions (same as GUI widgets): Actions (same as GUI widgets):
v.first() go to first frame v.first() go to first frame
v.prev() go to previous frame v.prev() go to previous frame
v.back() play backwards from current frame to start v.back() play backwards from current frame to start
v.stop() stop on current frame v.stop() stop on current frame
v.play() play from current frame to end v.play() play from current frame to end
v.next() go to next frame v.next() go to next frame
v.last() go to last frame v.last() go to last frame
v.frame(31) set frame slider v.frame(31) set frame slider
v.delay(0.4) set delay slider v.delay(0.4) set delay slider
v.q(5) set quality slider v.q(5) set quality slider
v.xaxis() view scene from x axis v.xaxis() view scene from x axis
v.yaxis() view scene from y axis v.yaxis() view scene from y axis
v.zaxis() view scene from z axis v.zaxis() view scene from z axis
v.box() toggle bounding box v.box() toggle bounding box
v.axis() toggle display of xyz axes v.axis() toggle display of xyz axes
v.norm() recenter and resize the view v.norm() recenter and resize the view
v.ortho() toggle ortho/perspective button v.ortho() toggle ortho/perspective button
v.reload() reload all frames from gl viewer data files v.reload() reload all frames from gl viewer data files
v.clipxlo(0.2) clip scene at x lo fraction of box v.clipxlo(0.2) clip scene at x lo fraction of box
v.clipxhi(1.0) clip at x hi v.clipxhi(1.0) clip at x hi
@ -44,9 +53,9 @@ v.clipyhi(1.0)
v.clipzlo(0.2) clip in z v.clipzlo(0.2) clip in z
v.clipzhi(1.0) v.clipzhi(1.0)
v.save() save current scene to file.png v.save() save current scene to file.png
v.file("image") set filename v.file("image") set filename
v.saveall() toggle save-all checkbox v.saveall() toggle save-all checkbox
""" """
# History # History
@ -64,11 +73,6 @@ v.saveall() toggle save-all checkbox
# delay_value = delay between frames (secs) # delay_value = delay between frames (secs)
# delay_msec = delay in millisec # delay_msec = delay in millisec
# Imports and external programs
from Tkinter import *
import types
# Class definition # Class definition
class vcr: class vcr:
@ -88,7 +92,7 @@ class vcr:
# load data for each viewer # load data for each viewer
# if each viewer has different data set, nframes is for 1st 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 = [] self.viewlist = []
for view in views: self.viewlist.append(view) for view in views: self.viewlist.append(view)
for view in self.viewlist: view.reload() for view in self.viewlist: view.reload()
@ -320,7 +324,7 @@ class vcr:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def q(self,value): 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) self.slider_quality.set(value)
for view in self.viewlist: view.q(value) for view in self.viewlist: view.q(value)

View File

@ -8,6 +8,11 @@
# vec tool # vec tool
# Imports and external programs
from __future__ import print_function, absolute_import
import types
oneline = "Create numeric vectors from columns in file or list of vecs" oneline = "Create numeric vectors from columns in file or list of vecs"
docstr = """ docstr = """
@ -19,10 +24,10 @@ v = vec(array) array = list of numeric vectors
assigns names = "col1", "col2", etc assigns names = "col1", "col2", etc
nvec = v.nvec # of vectors nvec = v.nvec # of vectors
nlen = v.nlen lengths of vectors nlen = v.nlen lengths of vectors
names = v.names list of vector names names = v.names list of vector names
x,y,... = l.get(1,"col2",...) return one or more vectors of values x,y,... = l.get(1,"col2",...) return one or more vectors of values
l.write("file.txt") write all vectors to a file l.write("file.txt") write all vectors to a file
l.write("file.txt","col1",7,...) write listed vectors to a file l.write("file.txt","col1",7,...) write listed vectors to a file
get and write allow abbreviated (uniquely) vector names or digits (1-Nvec) get and write allow abbreviated (uniquely) vector names or digits (1-Nvec)
@ -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 # 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 # 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 definition
class vec: class vec:
@ -53,22 +54,22 @@ class vec:
def __init__(self,data): def __init__(self,data):
self.data = [] self.data = []
if type(data) == types.StringType: if isinstance(data,str):
lines = open(data,'r').readlines() lines = open(data,'r').readlines()
for line in lines: for line in lines:
words = line.split() words = line.split()
if len(words) and words[0][0] in "0123456789.-": if len(words) and words[0][0] in "0123456789.-":
self.data.append(map(float,words)) self.data.append(list(map(float,words)))
elif type(data) == types.ListType: elif isinstance(data, list):
nlen = len(data[0]) nlen = len(data[0])
for list in data[1:]: for dlist in data[1:]:
if len(list) != nlen: if len(dlist) != nlen:
raise StandardError,"lists are not all same length" raise Exception("lists are not all same length")
for i in xrange(nlen): for i in range(nlen):
values = [list[i] for list in data] values = [dlist[i] for dlist in data]
self.data.append(map(float,values)) self.data.append(list(map(float,values)))
else: else:
raise StandardError,"invalid argument to vec" raise Exception("invalid argument to vec")
if len(self.data) == 0: if len(self.data) == 0:
self.nlen = self.nvec = 0 self.nlen = self.nvec = 0
@ -77,40 +78,40 @@ class vec:
self.nvec = len(self.data[0]) self.nvec = len(self.data[0])
self.names = [] self.names = []
for i in xrange(self.nvec): for i in range(self.nvec):
self.names.append(str("col%d" % (i+1))) self.names.append(str("col%d" % (i+1)))
self.ptr = {} self.ptr = {}
for i in xrange(self.nvec): for i in range(self.nvec):
self.ptr[self.names[i]] = i 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): def get(self,*keys):
if len(keys) == 0: if len(keys) == 0:
raise StandardError, "no vectors specified" raise Exception("no vectors specified")
map = [] map = []
for key in keys: for key in keys:
if type(key) == types.IntType: map.append(key-1) if type(key) == int: map.append(key-1)
elif self.ptr.has_key(key): map.append(self.ptr[key]) elif key in self.ptr: map.append(self.ptr[key])
else: else:
count = 0 count = 0
for i in range(self.nvec): for i in range(self.nvec):
if self.names[i].find(key) == 0: if self.names[i].find(key) == 0:
count += 1 count += 1
index = i index = i
if count == 1: if count == 1:
map.append(index) map.append(index)
else: else:
raise StandardError, "unique vector %s not found" % key raise Exception("unique vector %s not found" % key)
vecs = [] vecs = []
for i in range(len(keys)): for i in range(len(keys)):
vecs.append(self.nlen * [0]) 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]] vecs[i][j] = self.data[j][map[i]]
if len(keys) == 1: return vecs[0] if len(keys) == 1: return vecs[0]
@ -122,24 +123,24 @@ class vec:
if len(keys): if len(keys):
map = [] map = []
for key in keys: for key in keys:
if type(key) == types.IntType: map.append(key-1) if type(key) == int: map.append(key-1)
elif self.ptr.has_key(key): map.append(self.ptr[key]) elif key in self.ptr: map.append(self.ptr[key])
else: else:
count = 0 count = 0
for i in range(self.nvec): for i in range(self.nvec):
if self.names[i].find(key) == 0: if self.names[i].find(key) == 0:
count += 1 count += 1
index = i index = i
if count == 1: if count == 1:
map.append(index) map.append(index)
else: else:
raise StandardError, "unique vector %s not found" % key raise Exception("unique vector %s not found" % key)
else: else:
map = range(self.nvec) map = list(range(self.nvec))
f = open(filename,"w") f = open(filename,"w")
for i in xrange(self.nlen): for i in range(self.nlen):
for j in xrange(len(map)): for j in range(len(map)):
print >>f,self.data[i][map[j]], print(self.data[i][map[j]], end=' ', file=f)
print >>f print(file=f)
f.close() f.close()

View File

@ -18,6 +18,7 @@
# Imports and external programs # Imports and external programs
from __future__ import print_function, absolute_import
import types import types
# Class definition # Class definition
@ -66,20 +67,20 @@ class vizinfo:
# convert args into lists if single values # convert args into lists if single values
# if arg = 0, convert to full-range list # if arg = 0, convert to full-range list
if type(ids) is types.IntType and ids == 0: if type(ids) is int and ids == 0:
if which == "atom": ids = range(self.nacolor) if which == "atom": ids = list(range(self.nacolor))
if which == "bond": ids = range(self.nbcolor) if which == "bond": ids = list(range(self.nbcolor))
if which == "tri": ids = range(self.ntcolor) if which == "tri": ids = list(range(self.ntcolor))
if which == "line": ids = range(self.nlcolor) if which == "line": ids = list(range(self.nlcolor))
if type(ids) is not types.ListType and type(ids) is not types.TupleType: if type(ids) is not list and type(ids) is not tuple:
ids = [ids] 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] rgbs = [rgbs]
# if list of types has a 0, increment each type value # if list of types has a 0, increment each type value
if 0 in ids: 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 storage list if necessary
# extend other arrays for same "which" so that gl::make_atom_calllist # extend other arrays for same "which" so that gl::make_atom_calllist
@ -109,12 +110,12 @@ class vizinfo:
ntypes = len(ids) ntypes = len(ids)
nrgbs = len(rgbs) nrgbs = len(rgbs)
for i in xrange(ntypes): for i in range(ntypes):
id = ids[i] id = ids[i]
if rgbs[0] == "loop": if rgbs[0] == "loop":
list = colors.keys() colorlist = list(colors.keys())
red,green,blue = colors[list[i % len(colors)]] red,green,blue = colors[colorlist[i % len(colors)]]
elif ntypes == nrgbs: elif ntypes == nrgbs:
red,green,blue = colors[rgbs[i]] red,green,blue = colors[rgbs[i]]
else: else:
@ -144,20 +145,20 @@ class vizinfo:
# convert args into lists if single values # convert args into lists if single values
# if arg = 0, convert to full-range list # if arg = 0, convert to full-range list
if type(ids) is types.IntType and ids == 0: if type(ids) is int and ids == 0:
if which == "atom": ids = range(self.narad) if which == "atom": ids = list(range(self.narad))
if which == "bond": ids = range(self.nbrad) if which == "bond": ids = list(range(self.nbrad))
if which == "line": ids = range(self.nlrad) if which == "line": ids = list(range(self.nlrad))
if type(ids) is not types.ListType and type(ids) is not types.TupleType: if type(ids) is not list and type(ids) is not tuple:
ids = [ids] ids = [ids]
if type(radii) is not types.ListType and \ if type(radii) is not list and \
type(radii) is not types.TupleType: type(radii) is not tuple:
radii = [radii] radii = [radii]
# if list of types has a 0, increment each type value # if list of types has a 0, increment each type value
if 0 in ids: 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 storage list if necessary
# extend other arrays for same "which" so that gl::make_atom_calllist # 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 # convert args into lists if single values
# if arg = 0, convert to full-range list # if arg = 0, convert to full-range list
if type(ids) is types.IntType and ids == 0: if type(ids) is int and ids == 0:
ids = range(self.ntfill) ids = list(range(self.ntfill))
if type(ids) is not types.ListType and type(ids) is not types.TupleType: if type(ids) is not list and type(ids) is not tuple:
ids = [ids] ids = [ids]
if type(fills) is not types.ListType and \ if type(fills) is not list and \
type(fills) is not types.TupleType: type(fills) is not tuple:
fills = [fills] fills = [fills]
# if list of types has a 0, increment each type value # if list of types has a 0, increment each type value
if 0 in ids: 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 storage list if necessary
# extend other arrays for same "which" so that gl::make_atom_calllist # 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 list lengths match, set directly, else set types to 1st fill value
if len(fills) == len(ids): 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: else:
for id in ids: self.tfill[id] = int(fills[0]) for id in ids: self.tfill[id] = int(fills[0])

View File

@ -14,37 +14,38 @@
# open a pipe to the executable, # open a pipe to the executable,
# and feed it Tcl command lines one at a time # and feed it Tcl command lines one at a time
# Imports and external programs
from __future__ import print_function, absolute_import
import types, os
import numpy
oneline = "Control VMD from python" oneline = "Control VMD from python"
docstr = """ docstr = """
v = vmd() start up VMD v = vmd() start up VMD
v.stop() shut down VMD instance v.stop() shut down VMD instance
v.clear() delete all visualizations v.clear() delete all visualizations
v.rep(style) set default representation style. One of v.rep(style) set default representation style. One of
(Lines|VDW|Licorice|DynamicBonds|Points|CPK) (Lines|VDW|Licorice|DynamicBonds|Points|CPK)
v.new(file[,type]) load new file (default file type 'lammpstrj') v.new(file[,type]) load new file (default file type 'lammpstrj')
v.data(file[,atomstyle]) load new data file (default atom style 'full') v.data(file[,atomstyle]) load new data file (default atom style 'full')
v.replace(file[,type]) replace current frames with new file v.replace(file[,type]) replace current frames with new file
v.append(file[,type]) append file to current frame(s) v.append(file[,type]) append file to current frame(s)
v.set(snap,x,y,z,(True|False)) set coordinates from a pizza.py snapshot to new or current frame v.set(snap,x,y,z,(True|False)) set coordinates from a pizza.py snapshot to new or current frame
v.frame(frame) set current frame v.frame(frame) set current frame
v.flush() flush pending input to VMD and update GUI v.flush() flush pending input to VMD and update GUI
v.read(file) read Tcl script file (e.g. saved state) v.read(file) read Tcl script file (e.g. saved state)
v.enter() enter interactive shell v.enter() enter interactive shell
v.debug([True|False]) display generated VMD script commands? v.debug([True|False]) display generated VMD script commands?
""" """
# History # History
# 11/10, Axel Kohlmeyer (Temple U): original version # 11/10, Axel Kohlmeyer (Temple U): original version
# Imports and external programs
import types, os
import numpy
try: from DEFAULTS import PIZZA_VMDNAME try: from DEFAULTS import PIZZA_VMDNAME
except: PIZZA_VMDNAME = "vmd" except: PIZZA_VMDNAME = "vmd"
try: from DEFAULTS import PIZZA_VMDDIR try: from DEFAULTS import PIZZA_VMDDIR
@ -56,8 +57,8 @@ except: PIZZA_VMDARCH = "LINUX"
try: import pexpect try: import pexpect
except: except:
print "pexpect from http://pypi.python.org/pypi/pexpect", \ print("pexpect from http://pypi.python.org/pypi/pexpect", \
"is required for vmd tool" "is required for vmd tool")
raise raise
# Class definition # Class definition
@ -103,7 +104,7 @@ class vmd:
self.VMD.sendline(command) self.VMD.sendline(command)
self.VMD.expect('vmd >') self.VMD.expect('vmd >')
if self.debugme: if self.debugme:
print "call+result:"+self.VMD.before print("call+result:"+self.VMD.before)
return return
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -121,9 +122,9 @@ class vmd:
# turn on debugging info # turn on debugging info
def debug(self,status=True): def debug(self,status=True):
if status and not self.debugme: if status and not self.debugme:
print 'Turning vmd.py debugging ON.' print('Turning vmd.py debugging ON.')
if not status and self.debugme: if not status and self.debugme:
print 'Turning vmd.py debugging OFF.' print('Turning vmd.py debugging OFF.')
self.debugme = status self.debugme = status
# -------------------------------------------------------------------- # --------------------------------------------------------------------
@ -133,16 +134,16 @@ class vmd:
self.__call__('menu main on') self.__call__('menu main on')
while 1: while 1:
try: try:
command = raw_input("vmd > ") command = input("vmd > ")
except EOFError: except EOFError:
print "(EOF)" print("(EOF)")
self.__call__('menu main off') self.__call__('menu main off')
return return
if command == "quit" or command == "exit": if command == "quit" or command == "exit":
self.__call__('menu main off') self.__call__('menu main off')
return return
if command == "gopython": if command == "gopython":
print "gopython not supported here" print("gopython not supported here")
continue continue
self.__call__(command) self.__call__(command)

View File

@ -8,10 +8,13 @@
# vtk tool # vtk tool
from __future__ import print_function, absolute_import
import sys, re
oneline = "Convert LAMMPS snapshots to VTK format" oneline = "Convert LAMMPS snapshots to VTK format"
docstr = """ docstr = """
v = vtk(d) d = object containing atom coords (dump, data) v = vtk(d) d = object containing atom coords (dump, data)
v.one() write all snapshots to tmp.vtk v.one() write all snapshots to tmp.vtk
v.one("new") write all snapshots to new.vtk v.one("new") write all snapshots to new.vtk
@ -34,8 +37,6 @@ v.single(N,"file") write snapshot for timestep N to file.vtk
# Imports and external programs # Imports and external programs
import sys, re
# Class definition # Class definition
class vtk: class vtk:
@ -55,7 +56,7 @@ class vtk:
n = flag = 0 n = flag = 0
which,time,flag = self.data.iterator(flag) which,time,flag = self.data.iterator(flag)
time,box,atoms,bonds,tris,lines = self.data.viz(which) time,box,atoms,bonds,tris,lines = self.data.viz(which)
print time, print(time, end=' ')
sys.stdout.flush() sys.stdout.flush()
if len(tris): surface(tris) if len(tris): surface(tris)
@ -70,12 +71,12 @@ class vtk:
time,box,atoms,bonds,tris,lines = self.data.viz(which) time,box,atoms,bonds,tris,lines = self.data.viz(which)
for atom in atoms: allatoms.append(atom) for atom in atoms: allatoms.append(atom)
print time, print(time, end=' ')
sys.stdout.flush() sys.stdout.flush()
n += 1 n += 1
particle(file,allatoms) 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 +106,11 @@ class vtk:
particle(file,atoms) particle(file,atoms)
print time, print(time, end=' ')
sys.stdout.flush() sys.stdout.flush()
n += 1 n += 1
print "\nwrote %s snapshots in VTK format" % n print("\nwrote %s snapshots in VTK format" % n)
# -------------------------------------------------------------------- # --------------------------------------------------------------------
def manyGran(self,*args,**kwargs): def manyGran(self,*args,**kwargs):
@ -159,11 +160,11 @@ class vtk:
except: nvalues = 0 except: nvalues = 0
particleGran(file,atoms,names,nvalues) particleGran(file,atoms,names,nvalues)
if outputfl: print time, if outputfl: print(time, end=' ')
if outputfl: sys.stdout.flush() if outputfl: sys.stdout.flush()
n += 1 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): def single(self,time,*args):
@ -210,7 +211,7 @@ def generateFilename(root,fileNos,n):
def surface(tris): def surface(tris):
ntypes = tris[-1][1] ntypes = tris[-1][1]
for i in xrange(ntypes): for i in range(ntypes):
itype = i+1 itype = i+1
v = {} v = {}
nvert = ntri = 0 nvert = ntri = 0
@ -218,19 +219,19 @@ def surface(tris):
if tri[1] == itype: if tri[1] == itype:
ntri += 1 ntri += 1
vert = (tri[2],tri[3],tri[4]) vert = (tri[2],tri[3],tri[4])
if not v.has_key(vert): if vert not in v:
v[vert] = nvert v[vert] = nvert
nvert += 1 nvert += 1
vert = (tri[5],tri[6],tri[7]) vert = (tri[5],tri[6],tri[7])
if not v.has_key(vert): if vert not in v:
v[vert] = nvert v[vert] = nvert
nvert += 1 nvert += 1
vert = (tri[8],tri[9],tri[10]) vert = (tri[8],tri[9],tri[10])
if not v.has_key(vert): if vert not in v:
v[vert] = nvert v[vert] = nvert
nvert += 1 nvert += 1
keys = v.keys() keys = list(v.keys())
vinverse = {} vinverse = {}
for key in keys: for key in keys:
vinverse[v[key]] = key vinverse[v[key]] = key
@ -238,15 +239,15 @@ def surface(tris):
filename = "SURF" + str(itype) + ".vtk" filename = "SURF" + str(itype) + ".vtk"
f = open(filename,"w") f = open(filename,"w")
print >>f,"# vtk DataFile Version 3.0" print("# vtk DataFile Version 3.0", file=f)
print >>f,"Generated by pizza.py" print("Generated by pizza.py", file=f)
print >>f,"ASCII" print("ASCII", file=f)
print >>f,"DATASET POLYDATA" print("DATASET POLYDATA", file=f)
print >>f,"POINTS %d float" % nvert print("POINTS %d float" % nvert, file=f)
for i in xrange(nvert): for i in range(nvert):
tuple = vinverse[i] tuple = vinverse[i]
print >>f,tuple[0],tuple[1],tuple[2] print(tuple[0],tuple[1],tuple[2], file=f)
print >>f,"POLYGONS",ntri,4*ntri print("POLYGONS",ntri,4*ntri, file=f)
for tri in tris: for tri in tris:
if tri[1] == itype: if tri[1] == itype:
vert = (tri[2],tri[3],tri[4]) vert = (tri[2],tri[3],tri[4])
@ -255,10 +256,10 @@ def surface(tris):
ivert2 = v[vert] ivert2 = v[vert]
vert = (tri[8],tri[9],tri[10]) vert = (tri[8],tri[9],tri[10])
ivert3 = v[vert] ivert3 = v[vert]
print >>f,3,ivert1,ivert2,ivert3 print(3,ivert1,ivert2,ivert3, file=f)
print >>f print(file=f)
print >>f,"CELL_DATA",ntri print("CELL_DATA",ntri, file=f)
print >>f,"POINT_DATA",nvert print("POINT_DATA",nvert, file=f)
f.close() f.close()
@ -268,23 +269,23 @@ def surface(tris):
def particle(file,atoms): def particle(file,atoms):
f = open(file,"w") f = open(file,"w")
print >>f,"# vtk DataFile Version 2.0" print("# vtk DataFile Version 2.0", file=f)
print >>f,"Generated by pizza.py" print("Generated by pizza.py", file=f)
print >>f,"ASCII" print("ASCII", file=f)
print >>f,"DATASET POLYDATA" print("DATASET POLYDATA", file=f)
print >>f,"POINTS %d float" % len(atoms) print("POINTS %d float" % len(atoms), file=f)
for atom in atoms: for atom in atoms:
print >>f,atom[2],atom[3],atom[4] print(atom[2],atom[3],atom[4], file=f)
print >>f,"VERTICES",len(atoms),2*len(atoms) print("VERTICES",len(atoms),2*len(atoms), file=f)
for i in xrange(len(atoms)): for i in range(len(atoms)):
print >>f,1,i print(1,i, file=f)
print >>f,"POINT_DATA",len(atoms) print("POINT_DATA",len(atoms), file=f)
print >>f,"SCALARS atom_type int 1" print("SCALARS atom_type int 1", file=f)
print >>f,"LOOKUP_TABLE default" print("LOOKUP_TABLE default", file=f)
for atom in atoms: for atom in atoms:
itype = int(atom[1]) itype = int(atom[1])
print >>f,itype, print(itype, end=' ', file=f)
print >>f print(file=f)
f.close() f.close()
@ -292,17 +293,17 @@ def particle(file,atoms):
def boundingBox(file,xlo,xhi,ylo,yhi,zlo,zhi): def boundingBox(file,xlo,xhi,ylo,yhi,zlo,zhi):
f = open(file,"w") f = open(file,"w")
print >>f,"# vtk DataFile Version 2.0" print("# vtk DataFile Version 2.0", file=f)
print >>f,"Generated by pizza.py" print("Generated by pizza.py", file=f)
print >>f,"ASCII" print("ASCII", file=f)
print >>f,"DATASET RECTILINEAR_GRID" print("DATASET RECTILINEAR_GRID", file=f)
print >>f,"DIMENSIONS 2 2 2" print("DIMENSIONS 2 2 2", file=f)
print >>f,"X_COORDINATES 2 float" print("X_COORDINATES 2 float", file=f)
print >>f,xlo,xhi print(xlo,xhi, file=f)
print >>f,"Y_COORDINATES 2 float" print("Y_COORDINATES 2 float", file=f)
print >>f,ylo,yhi print(ylo,yhi, file=f)
print >>f,"Z_COORDINATES 2 float" print("Z_COORDINATES 2 float", file=f)
print >>f,zlo,zhi print(zlo,zhi, file=f)
def typestr(o): def typestr(o):
string = str(type(o)) string = str(type(o))
@ -320,20 +321,20 @@ def particleGran(file,atoms,names,n_values):
scalars, vectors = findScalarsAndVectors(names) scalars, vectors = findScalarsAndVectors(names)
# print head # print head
print >>f,"# vtk DataFile Version 2.0" print("# vtk DataFile Version 2.0", file=f)
print >>f,"Generated by lpp.py" print("Generated by lpp.py", file=f)
print >>f,"ASCII" print("ASCII", file=f)
print >>f,"DATASET POLYDATA" print("DATASET POLYDATA", file=f)
print >>f,"POINTS %d float" % len(atoms) print("POINTS %d float" % len(atoms), file=f)
for atom in atoms: 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(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 >>f,"VERTICES",len(atoms),2*len(atoms) print("VERTICES", len(atoms), 2*len(atoms), file=f)
for i in xrange(len(atoms)): for i in range(len(atoms)):
print >>f,1,i print(1,i, file=f)
print >>f,"POINT_DATA",len(atoms) print("POINT_DATA",len(atoms), file=f)
if len(atoms) == 0: if len(atoms) == 0:
print >> f print('', file=f)
f.close() f.close()
return return
@ -353,9 +354,9 @@ def particleGran(file,atoms,names,n_values):
else: # if no atoms are present else: # if no atoms are present
pass pass
print >>f,"VECTORS",key,vectortype print("VECTORS",key,vectortype, file=f)
for atom in atoms: 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 # print SCALARS
for key in scalars.keys(): for key in scalars.keys():
@ -368,12 +369,12 @@ def particleGran(file,atoms,names,n_values):
else: # if no atoms are present else: # if no atoms are present
pass pass
print >>f,"SCALARS",key,scalartype,1 print("SCALARS",key,scalartype,1, file=f)
print >>f,"LOOKUP_TABLE default" print("LOOKUP_TABLE default", file=f)
for atom in atoms: for atom in atoms:
print >>f, atom[scalars[key]] print(atom[scalars[key]], file=f)
print >>f print('', file=f)
f.close() f.close()
def findScalarsAndVectors(names): def findScalarsAndVectors(names):
@ -387,7 +388,7 @@ def findScalarsAndVectors(names):
indices[names[name]]=name indices[names[name]]=name
# fill missing indices (occurrs e.g. if output is like vx vy vz fx fy fz vx vy vz) # 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: if i not in indices:
indices[i]="" indices[i]=""
@ -441,7 +442,7 @@ def findScalarsAndVectors(names):
i+=1 i+=1
if 'x' not in vectors.keys(): 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() exit()
return scalars, vectors return scalars, vectors

View File

@ -8,10 +8,14 @@
# xyz tool # xyz tool
# Imports and external programs
from __future__ import print_function, absolute_import
import sys
oneline = "Convert LAMMPS snapshots to XYZ format" oneline = "Convert LAMMPS snapshots to XYZ format"
docstr = """ docstr = """
x = xyz(d) d = object containing atom coords (dump, data) x = xyz(d) d = object containing atom coords (dump, data)
x.one() write all snapshots to tmp.xyz x.one() write all snapshots to tmp.xyz
x.one("new") write all snapshots to new.xyz x.one("new") write all snapshots to new.xyz
@ -29,9 +33,6 @@ x.single(N,"file") write snapshot for timestep N to file.xyz
# Variables # Variables
# data = data file to read from # data = data file to read from
# Imports and external programs
import sys
# Class definition # Class definition
@ -56,18 +57,18 @@ class xyz:
if flag == -1: break if flag == -1: break
time,box,atoms,bonds,tris,lines = self.data.viz(which) time,box,atoms,bonds,tris,lines = self.data.viz(which)
print >>f,len(atoms) print(len(atoms), file=f)
print >>f,"Atoms" print("Atoms", file=f)
for atom in atoms: for atom in atoms:
itype = int(atom[1]) 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() sys.stdout.flush()
n += 1 n += 1
f.close() 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 = root + str(n)
file += ".xyz" file += ".xyz"
f = open(file,"w") f = open(file,"w")
print >>f,len(atoms) print(len(atoms), file=f)
print >>f,"Atoms" print("Atoms", file=f)
for atom in atoms: for atom in atoms:
itype = int(atom[1]) 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() sys.stdout.flush()
f.close() f.close()
n += 1 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) which = self.data.findtime(time)
time,box,atoms,bonds,tris,lines = self.data.viz(which) time,box,atoms,bonds,tris,lines = self.data.viz(which)
f = open(file,"w") f = open(file,"w")
print >>f,len(atoms) print(len(atoms), file=f)
print >>f,"Atoms" print("Atoms", file=f)
for atom in atoms: for atom in atoms:
itype = int(atom[1]) 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() f.close()