Commit 2a291c74 authored by Germain Clavier's avatar Germain Clavier
Browse files

Some more modifications of the libs from python2 to python3

parent ac7c9d11
Loading
Loading
Loading
Loading
+8 −1
Changes for src/Notes.md: 8 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -8,11 +8,18 @@
    from PIL import Image, ImageTk
```
   retrocompatibility must be checked.
* Check Pmw compatibility with python3.4+
* Check Pmw compatibility with python3.4+ (seems ok)
* Togl support has been dropped by PyopenGL devs. Is it still relevant?
* Globally installation advices should be rewritten using pip or conda
* Is the use of some tools such as MatLab, Gnuplot or Raster3d still
  necessary given the existence of python libs (numpy, scipy, matplotlib...)
* In installing glumpy, we also need python3-devel lib compared to what
  is mentioned in the doc. This lib is installed through package managers.

## Changes

* Well if everything goes well, I'll write a new vizualization tool...
  - It might be better to start off a new project and make it simply dependent on the pizza tools
  - And also make it dependent on glumpy and PyQt, that looks more reasonable
  - This imply dropping several libs actually. Inclugind gl.
* The whole matlab.py and gnu.py could be replaced by matplotlib.
+38 −28
Changes for src/histo.py: 38 added lines, 28 removed lines.
Original line number Diff line number Diff line
@@ -5,31 +5,32 @@
# DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
# certain rights in this software.  This software is distributed under
# the GNU General Public License.

#
# histo tool
#
# History
#   12/05, Steve Plimpton (SNL): original version
#
# ToDo list
#
# Variables
#   data = dump object

oneline = "Particle density histogram from a dump"

docstr = """
"""
Particle density histogram from a dump
h = histo(d)                        d = dump/cdump object

x,y = h.compute('x',N,lo,hi)        compute histogram in dim with N bins

  lo/hi are optional, if not used histo will be over entire box
"""

# History
#   12/05, Steve Plimpton (SNL): original version

# ToDo list

# Variables
#   data = dump object

# Imports and external programs

import sys

# Class definition


class histo:

    # --------------------------------------------------------------------
@@ -40,10 +41,14 @@ class histo:
    # --------------------------------------------------------------------

    def compute(self, dim, nbins, lo=None, hi=None):
    if dim == 'x': idim = 2
    elif dim == 'y': idim = 3
    elif dim == 'z': idim = 4
    else: raise StandardError,"illegal dim value"
        if dim == "x":
            idim = 2
        elif dim == "y":
            idim = 3
        elif dim == "z":
            idim = 4
        else:
            sys.exit("illegal dim value")

        y = nbins * [0]

@@ -51,36 +56,41 @@ class histo:
        n = flag = 0
        while 1:
            which, time, flag = self.data.iterator(flag)
      if flag == -1: break
            if flag == -1:
                break
            time, box, atoms, bonds, tris, lines = self.data.viz(which)

            if not lo:
        if dim == 'x':
                if dim == "x":
                    lo = box[0]
                    hi = box[3]
        elif dim == 'y':
                elif dim == "y":
                    lo = box[1]
                    hi = box[4]
        elif dim == 'z':
                elif dim == "z":
                    lo = box[2]
                    hi = box[5]

      delta = (hi-lo) / nbins;
            delta = (hi - lo) / nbins
            invdelta = 1.0 / delta

            for atom in atoms:
                coord = atom[idim]
                ibin = int((coord - lo) * invdelta)
        if ibin < 0 or ibin >= nbins: continue
                if ibin < 0 or ibin >= nbins:
                    continue
                y[ibin] += 1
                count += 1

            n += 1

        x = nbins * [0]
    for i in xrange(nbins): x[i] = (i+0.5)*delta
      
    print "histogram snapshots = ",n
    print "histogram counts (per snap) = %d (%g)" % (count,float(count)/n)
    print "histogram bounds = ",lo,hi
        for i in range(nbins):
            x[i] = (i + 0.5) * delta

        print("histogram snapshots = ", n)
        print("histogram counts (per snap) = %d (%g)" %
              (count, float(count) / n)
              )
        print("histogram bounds = ", lo, hi)
        return x, y
+88 −60
Changes for src/image.py: 88 added lines, 60 removed lines.
Original line number Diff line number Diff line
#!/usr/bin/env python3

# Pizza.py toolkit, www.cs.sandia.gov/~sjplimp/pizza.html
# Steve Plimpton, sjplimp@sandia.gov, Sandia National Laboratories
#
@@ -5,12 +7,18 @@
# DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
# certain rights in this software.  This software is distributed under
# the GNU General Public License.

#
# image tool
#
#
# History
#   8/05, Matt Jones (BYU): original version
#   9/05, Steve Plimpton: added convert() and montage() methods

oneline = "View and manipulate images"
# ToDo list

docstr = """
"""
View and manipulate images
i = image("my1.gif my2.gif")    display thumbnails of matching images
i = image("*.png *.gif")        wildcards allowed
i = image("*.png *.gif",0)      2nd arg = sort filenames, 0 = no sort, def = 1
@@ -39,68 +47,80 @@ i.montage("-geometry 512x512","i*.png","new.png") 1st arg is switch
  montage with not all wildcard args will issue single montage command
"""

# History
#   8/05, Matt Jones (BYU): original version
#   9/05, Steve Plimpton: added convert() and montage() methods

# ToDo list

# Variables

# Imports and external programs

import sys, os, commands, re, glob
from math import *
from Tkinter import *
import sys
import os
import re
import glob
import subprocess
# import numpy as np
import tkinter as tk
import Pmw
import Image,ImageTk
from PIL import Image, ImageTk

try: from DEFAULTS import PIZZA_CONVERT
except: PIZZA_CONVERT = "convert"
try: from DEFAULTS import PIZZA_MONTAGE
except: PIZZA_MONTAGE = "montage"
try:
    from DEFAULTS import PIZZA_CONVERT
except (ModuleNotFoundError, ImportError):
    PIZZA_CONVERT = "convert"
try:
    from DEFAULTS import PIZZA_MONTAGE
except (ModuleNotFoundError, ImportError):
    PIZZA_MONTAGE = "montage"

# Class definition


class image:

    # --------------------------------------------------------------------

    def __init__(self, filestr=None, sortflag=1):
    if filestr == None: return
        if filestr is None:
            return
        self.view(filestr, sortflag)

    def view(self, filestr, sortflag=0):

        # convert filestr into full list of files

    if filestr == "": filestr = ' '.join(extensions)
        if filestr == "":
            filestr = " ".join(extensions)
        list = str.split(filestr)
        files = []
    for file in list: files += glob.glob(file)
    if len(files) == 0: raise StandardError, "no image files to load"
    if sortflag: files.sort()
        for file in list:
            files += glob.glob(file)
        if len(files) == 0:
            sys.exit("no image files to load")
        if sortflag:
            files.sort()

        # grab Tk instance from main

    from __main__ import tkroot
        # from __main__ import tkroot

        # GUI control window

    gui = Toplevel(tkroot)
    gui.title('Pizza.py image tool')
        tkroot = tk.Tk()
        gui = tk.Toplevel(tkroot)
        gui.title("Pizza.py image tool")

    scroll = \
      Pmw.ScrolledFrame(gui,usehullsize=1,hull_width=420,hull_height=500)
        scroll = Pmw.ScrolledFrame(
                gui,
                usehullsize=1,
                hull_width=420,
                hull_height=500
                )
        pane = scroll.interior()

        ncolumns = 4
    for i in xrange(len(files)):
        for i, file in enumerate(files):

            # create new row frame if 1st in column

      if i % ncolumns == 0: rowframe = Frame(pane)
      oneframe = Frame(rowframe)
            if i % ncolumns == 0:
                rowframe = tk.Frame(pane)
            oneframe = tk.Frame(rowframe)

            # create a thumbnail of image

@@ -119,30 +139,33 @@ class image:

            big = ImageTk.PhotoImage(file=files[i])
            obj = thumbnails(gui, files[i], big, thumbnail)
      Button(oneframe,image=thumbnail,command=obj.display).pack(side=TOP)
      Label(oneframe,text=basename).pack(side=BOTTOM)
            tk.Button(oneframe, image=thumbnail,
                      command=obj.display).pack(side=tk.TOP)
            tk.Label(oneframe, text=basename).pack(side=tk.BOTTOM)

            # pack into row frame

      oneframe.pack(side=LEFT)
      if (i+1) % ncolumns == 0: rowframe.pack(side=TOP)
            oneframe.pack(side=tk.LEFT)
            if (i + 1) % ncolumns == 0:
                rowframe.pack(side=tk.TOP)

    if len(files) % ncolumns != 0: rowframe.pack(side=TOP)
    scroll.pack(side=LEFT)     
        if len(files) % ncolumns != 0:
            rowframe.pack(side=tk.TOP)
        scroll.pack(side=tk.LEFT)

    # --------------------------------------------------------------------
    # wrapper on ImageMagick convert command

    def convert(self, file1, file2, switch=""):
    if file1.find('*') < 0 or file2.find('*') < 0:
        if file1.find("*") < 0 or file2.find("*") < 0:
            cmd = "%s %s %s %s" % (PIZZA_CONVERT, switch, file1, file2)
      commands.getoutput(cmd)
            subprocess.check_output(cmd)
            return

    index = file1.index('*')
        index = file1.index("*")
        pre1 = file1[:index]
        post1 = file1[index + 1:]
    index = file2.index('*')
        index = file2.index("*")
        pre2 = file2[:index]
        post2 = file2[index + 1:]
        expr = "%s(.*)%s" % (pre1, post1)
@@ -152,23 +175,25 @@ class image:
            middle = re.search(expr, file1).group(1)
            file2 = "%s%s%s" % (pre2, middle, post2)
            cmd = "%s %s %s %s" % (PIZZA_CONVERT, switch, file1, file2)
      print middle,
            print(middle)
            sys.stdout.flush()
      commands.getoutput(cmd)
    print
            subprocess.check_output(cmd)
        print()

    # --------------------------------------------------------------------
    # wrapper on ImageMagick montage command

    def montage(self, switch, *fileargs):
        nsets = len(fileargs)
    if nsets < 2: raise StandardError,"montage requires 2 or more file args"
        if nsets < 2:
            sys.exit("montage requires 2 or more file args")

        for i in range(nsets):
      if fileargs[i].find('*') < 0:
            if fileargs[i].find("*") < 0:
                cmd = "%s %s" % (PIZZA_MONTAGE, switch)
        for j in range(nsets): cmd += " %s" % fileargs[j]
        commands.getoutput(cmd)
                for j in range(nsets):
                    cmd += " %s" % fileargs[j]
                subprocess.check_output(cmd)
                return

        nfiles = len(glob.glob(fileargs[0]))
@@ -176,32 +201,34 @@ class image:
        for i in range(nsets - 1):
            filesets.append(glob.glob(fileargs[i]))
            if len(filesets[-1]) != nfiles:
        raise StandardError,"each montage arg must represent equal # of files"
                sys.exit("each montage arg must represent equal # of files")

    index = fileargs[0].index('*')
        index = fileargs[0].index("*")
        pre1 = fileargs[0][:index]
        post1 = fileargs[0][index + 1:]
    index = fileargs[-1].index('*')
        index = fileargs[-1].index("*")
        preN = fileargs[-1][:index]
        postN = fileargs[-1][index + 1:]
        expr = "%s(.*)%s" % (pre1, post1)

        for i in range(nfiles):
            cmd = "%s %s" % (PIZZA_MONTAGE, switch)
      for j in range(nsets-1): cmd += " %s" % filesets[j][i]
            for j in range(nsets - 1):
                cmd += " %s" % filesets[j][i]
            middle = re.search(expr, filesets[0][i]).group(1)
            fileN = "%s%s%s" % (preN, middle, postN)
            cmd += " %s" % fileN
      commands.getoutput(cmd)
      print middle,
            subprocess.check_output(cmd)
            print(middle)
            sys.stdout.flush()
    print
        print()


# --------------------------------------------------------------------
# thumbnail class

class thumbnails:

class thumbnails:
    def __init__(self, root, name, bigimage, thumbimage):
        self.root = root
        self.big = bigimage
@@ -224,12 +251,13 @@ class thumbnails:

        else:
            self.bigexist = 1
      self.window = Toplevel(self.root)
      Label(self.window,text=self.name).pack(side=TOP)
      Label(self.window,image=self.big).pack(side=BOTTOM)
            self.window = tk.Toplevel(self.root)
            tk.Label(self.window, text=self.name).pack(side=tk.TOP)
            tk.Label(self.window, image=self.big).pack(side=tk.BOTTOM)

# --------------------------------------------------------------------
# list of file extensions to test for
# could add any extensions that PIL recognizes


extensions = ["*.png", "*.bmp", "*.gif", "*.tiff", "*.tif"]
+98 −69
Changes for src/ldump.py: 98 added lines, 69 removed lines.
Original line number Diff line number Diff line
@@ -5,12 +5,30 @@
# DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
# certain rights in this software.  This software is distributed under
# the GNU General Public License.

#
# ldump tool
#
#
# History
#   11/10, Steve Plimpton (SNL): original version
#
# Variables
#   flist = list of dump file names
#   increment = 1 if reading snapshots one-at-a-time
#   nextfile = which file to read from via next()
#   eof = ptr into current file for where to read via next()
#   nsnaps = # of snapshots
#   snaps = list of snapshots
#   names = dictionary of column names:
#     key = "id", value = column # (0 to M-1)
#   Snap = one snapshot
#     time = time stamp
#     natoms = # of atoms
#     xlo,xhi,ylo,yhi,zlo,zhi = box bounds (float)
#     atoms[i][j] = 2d array of floats, i = 0 to natoms-1, j = 0 to ncols-1

oneline = "Read dump files with line segment info"

docstr = """
"""
Read dump files with line segment info
l = ldump("dump.one")             read in one or more dump files
l = ldump("dump.1 dump.2.gz")	  can be gzipped
l = ldump("dump.*")		  wildcard expands to multiple files
@@ -36,7 +54,7 @@ time,box,atoms,bonds,tris,lines = l.viz(index) return list of viz objects
  viz() returns line info for specified timestep index
    can also call as viz(time,1) and will find index of preceding snapshot
    time = timestep value
    box = \[xlo,ylo,zlo,xhi,yhi,zhi\]
    box = [xlo,ylo,zlo,xhi,yhi,zhi]
    atoms = NULL
    bonds = NULL
    tris = NULL
@@ -49,41 +67,21 @@ l.owrap(...) wrap lines to same image as their atoms
  useful for wrapping all molecule's atoms/lines the same so it is contiguous
"""

# History
#   11/10, Steve Plimpton (SNL): original version

# Variables
#   flist = list of dump file names
#   increment = 1 if reading snapshots one-at-a-time
#   nextfile = which file to read from via next()
#   eof = ptr into current file for where to read via next()
#   nsnaps = # of snapshots
#   snaps = list of snapshots
#   names = dictionary of column names:
#     key = "id", value = column # (0 to M-1)
#   Snap = one snapshot
#     time = time stamp
#     natoms = # of atoms
#     xlo,xhi,ylo,yhi,zlo,zhi = box bounds (float)
#     atoms[i][j] = 2d array of floats, i = 0 to natoms-1, j = 0 to ncols-1

# Imports and external programs

import sys, commands, re, glob, types
from os import popen

try:
import sys
import glob
import os
import numpy as np
    oldnumeric = False
except:
    import Numeric as np
    oldnumeric = True

try: from DEFAULTS import PIZZA_GUNZIP
except: PIZZA_GUNZIP = "gunzip"
try:
    from DEFAULTS import PIZZA_GUNZIP
except (ModuleNotFoundError, ImportError):
    PIZZA_GUNZIP = "gunzip"

# Class definition


class ldump:

    # --------------------------------------------------------------------
@@ -97,9 +95,10 @@ class ldump:

        words = list[0].split()
        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:
      raise StandardError,"no ldump file specified"
            sys.exit("no ldump file specified")

        if len(list) == 1:
            self.increment = 0
@@ -118,44 +117,47 @@ class ldump:

        for file in self.flist:
            if file[-3:] == ".gz":
        f = popen("%s -c %s" % (PIZZA_GUNZIP,file),'r')
      else: f = open(file)
                f = os.popen("%s -c %s" % (PIZZA_GUNZIP, file), "r")
            else:
                f = open(file)

            snap = self.read_snapshot(f)
            while snap:
                self.snaps.append(snap)
        print snap.time,
                print(snap.time)
                sys.stdout.flush()
                snap = self.read_snapshot(f)

            f.close()
    print
        print()

        # sort entries by timestep, cull duplicates

        self.snaps.sort(self.compare_time)
        self.cull()
        self.nsnaps = len(self.snaps)
    print "read %d snapshots" % self.nsnaps
        print("read %d snapshots" % self.nsnaps)

    # --------------------------------------------------------------------
    # read next snapshot from list of files

    def next(self):

    if not self.increment: raise StandardError,"cannot read incrementally"
        if not self.increment:
            sys.exit("cannot read incrementally")

        # read next snapshot in current file using eof as pointer
        # if fail, try next file
        # if new snapshot time stamp already exists, read next snapshot

        while 1:
      f = open(self.flist[self.nextfile],'rb')
            f = open(self.flist[self.nextfile], "rb")
            f.seek(self.eof)
            snap = self.read_snapshot(f)
            if not snap:
                self.nextfile += 1
	if self.nextfile == len(self.flist): return -1
                if self.nextfile == len(self.flist):
                    return -1
                f.close()
                self.eof = 0
                continue
@@ -164,7 +166,9 @@ class ldump:
            try:
                self.findtime(snap.time)
                continue
      except: break
            except Exception as e:
                print(e)
                break

        self.snaps.append(snap)
        snap = self.snaps[self.nsnaps]
@@ -179,12 +183,12 @@ class ldump:
    def read_snapshot(self, f):
        try:
            snap = Snap()
      item = f.readline()
            f.readline()
            snap.time = int(f.readline().split()[0])  # just grab 1st field
      item = f.readline()
            f.readline()
            snap.natoms = int(f.readline())

      item = f.readline()
            f.readline()
            words = f.readline().split()
            snap.xlo, snap.xhi = float(words[0]), float(words[1])
            words = f.readline().split()
@@ -192,26 +196,26 @@ class ldump:
            words = f.readline().split()
            snap.zlo, snap.zhi = float(words[0]), float(words[1])

      item = f.readline()
            f.readline()

            if snap.natoms:
                words = f.readline().split()
                ncol = len(words)
        for i in xrange(1,snap.natoms):
                for i in range(1, snap.natoms):
                    words += f.readline().split()
                floats = map(float, words)
        if oldnumeric: atoms = np.zeros((snap.natoms,ncol),np.Float)
        else: atoms = np.zeros((snap.natoms,ncol),np.float)
                atoms = np.zeros((snap.natoms, ncol), np.float)
                start = 0
                stop = ncol
        for i in xrange(snap.natoms):
                for i in range(snap.natoms):
                    atoms[i] = floats[start:stop]
                    start = stop
                    stop += ncol
      else: atoms = None
            else:
                atoms = None
            snap.atoms = atoms
            return snap
    except:
        except Exception:
            return 0

    # --------------------------------------------------------------------
@@ -219,7 +223,7 @@ class ldump:

    def map(self, *pairs):
        if len(pairs) % 2 != 0:
      raise StandardError, "ldump map() requires pairs of mappings"
            sys.exit("ldump map() requires pairs of mappings")
        for i in range(0, len(pairs), 2):
            j = i + 1
            self.names[pairs[j]] = pairs[i] - 1
@@ -249,9 +253,10 @@ class ldump:
    # --------------------------------------------------------------------

    def findtime(self, n):
    for i in xrange(self.nsnaps):
      if self.snaps[i].time == n: return i
    raise StandardError, "no step %d exists" % n
        for i in range(self.nsnaps):
            if self.snaps[i].time == n:
                return i
        sys.exit("no step %d exists" % n)

    # --------------------------------------------------------------------
    # delete successive snapshots with duplicate time stamp
@@ -269,21 +274,23 @@ class ldump:
    # if called with flag, then index is timestep, so convert to snapshot index

    def viz(self, index, flag=0):
    if not flag: isnap = index
        if not flag:
            isnap = index
        else:
            times = self.time()
            n = len(times)
            i = 0
            while i < n:
        if times[i] > index: break
                if times[i] > index:
                    break
                i += 1
            isnap = i - 1
        snap = self.snaps[isnap]

        time = snap.time
        box = [snap.xlo, snap.ylo, snap.zlo, snap.xhi, snap.yhi, snap.zhi]
    id = self.names["id"]
    type = self.names["type"]
        liid = self.names["id"]
        litype = self.names["type"]
        end1x = self.names["end1x"]
        end1y = self.names["end1y"]
        end2x = self.names["end2x"]
@@ -293,14 +300,24 @@ class ldump:
        # don't add line if all 4 values are 0 since not a line

        lines = []
    for i in xrange(snap.natoms):
        for i in range(snap.natoms):
            atom = snap.atoms[i]
            e1x = atom[end1x]
            e1y = atom[end1y]
            e2x = atom[end2x]
            e2y = atom[end2y]
      if e1x == 0.0 and e1y == 0.0 and e2x == 0.0 and e2y == 0.0: continue
      lines.append([atom[id],atom[type],e1x,e1y,0.0,e2x,e2y,0.0])
            if e1x == 0.0 and e1y == 0.0 and e2x == 0.0 and e2y == 0.0:
                continue
            lines.append([
                atom[liid],
                atom[litype],
                e1x,
                e1y,
                0.0,
                e2x,
                e2y,
                0.0
                ])

        return time, box, None, None, None, lines

@@ -308,8 +325,18 @@ class ldump:
    # wrap line end points associated with atoms thru periodic boundaries
    # invoked by dump() when it does an owrap() on its atoms

  def owrap(self,time,xprd,yprd,zprd,idsdump,atomsdump,iother,ix,iy,iz):
    id = self.names["id"]
    def owrap(self,
              time,
              xprd,
              yprd,
              zprd,
              idsdump,
              atomsdump,
              iother,
              ix,
              iy,
              iz):
        liid = self.names["id"]
        end1x = self.names["end1x"]
        end1y = self.names["end1y"]
        end2x = self.names["end2x"]
@@ -323,8 +350,8 @@ class ldump:
        # jdump = atom J in dump's atoms that atom I was owrapped on
        # delx,dely = offset applied to atom I and thus to line I

    for i in xrange(snap.natoms):
      tag = atoms[i][id]
        for i in range(snap.natoms):
            tag = atoms[i][liid]
            idump = idsdump[tag]
            jdump = idsdump[atomsdump[idump][iother]]
            delx = (atomsdump[idump][ix] - atomsdump[jdump][ix]) * xprd
@@ -334,8 +361,10 @@ class ldump:
            atoms[i][end2x] += delx
            atoms[i][end2y] += dely


# --------------------------------------------------------------------
# one snapshot


class Snap:
    pass
+6 −6
Changes for src/todo.txt: 6 added lines, 6 removed lines.
Original line number Diff line number Diff line
@@ -7,13 +7,13 @@ chain.py TODO/Done?
data.py         TODO/Done?
dump.py         TODO/Done?
ensight.py      TODO/Done?
gl.py           TODO
gl.py           TODO/To wipe?
gnu.py          TODO/Done?
histo.py        TODO
image.py        TODO
ldump.py        TODO
log.py          TODO
matlab.py       TODO
histo.py        TODO/Done?
image.py        TODO/Done?
ldump.py        TODO/Done?
log.py          TODO/Done?
matlab.py       TODO/to wipe?
mdump.py        TODO
olog.py         TODO
pair.py         TODO