Skip to content

Commit

Permalink
more 2to3
Browse files Browse the repository at this point in the history
  • Loading branch information
jonwright committed Sep 29, 2017
1 parent 55512ec commit 115bd97
Show file tree
Hide file tree
Showing 32 changed files with 286 additions and 177 deletions.
48 changes: 48 additions & 0 deletions fixprint.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@


import glob, shutil


def got_future(lines):
for line in lines:
if line.find("from __future__ import print_function")==0:
return True
return False

def got_print(lines):
for line in lines:
if line.find("print") > -1:
return True
return False

def got_input(lines):
for line in lines:
if line.find("input") > -1:
return True
return False

fl = glob.glob("*.py")

def fix(fname, lines):
shutil.move(fname, fname+".bak2")
g = open(fname,"w")
g.write("\nfrom __future__ import print_function\n")
if got_input(lines):
g.write("from six.moves import input\n")
for line in lines:
g.write(line)
g.close()


for fname in fl:
lines = open(fname).readlines()
p = got_print(lines)
f = got_future(lines)
if p and f:
print "OK",fname
continue
if p:
print "Need to fix",fname
fix(fname, lines)


2 changes: 1 addition & 1 deletion sandbox/allflips.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
splinefile = sys.argv[2]
dims = (2048,2048)
sf = c.s_raw.copy(), c.f_raw.copy()
for name in flippers.keys():
for name in list(flippers.keys()):
newname = sys.argv[1].replace(".flt",name)+".flt"
newsf = np.dot( flippers[name], sf )
origin = np.dot( flippers[name], dims ).clip(-np.inf, 0 )
Expand Down
16 changes: 9 additions & 7 deletions sandbox/art.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@

from __future__ import print_function


"""
Some simplistic ART algorithms
Expand Down Expand Up @@ -78,7 +80,7 @@ def update_wtd( recon, proj, angle, msk, dbg=True ):

update = update
update.shape = recon.shape
print update.sum(),error.sum(),
print(update.sum(),error.sum(), end=' ')
if dbg:
pl.figure()
pl.imshow( np.reshape(update, recon.shape) )
Expand All @@ -92,7 +94,7 @@ def make_data():
import rad, Image
im = Image.open("phantom3.gif")
a = np.asarray(im).astype(np.float32)
print a.min(),a.max()
print(a.min(),a.max())
# 70 random projection
np.random.seed(42)
theta = np.random.random(70)*180.
Expand Down Expand Up @@ -120,7 +122,7 @@ def test_u_n():
pl.ion()
for j in range(3):
for proj, angle in zip(projections, theta):
print j, angle,
print(j, angle, end=' ')
start = time.clock()
update = update_wtd( recon, proj, angle, msk, dbg=False)
recon = recon + update*0.9
Expand All @@ -137,14 +139,14 @@ def test_u_n():
sumtime += end-start
ncalc +=1
# print err.sum()
print
print()
# print "Waiting"
# raw_input()
# recon = recon.clip( 0, 10)
print sumtime/ncalc
print(sumtime/ncalc)
np.save("recon.npy",recon)
end = time.time()
print "Time take",realstart - end
print("Time take",realstart - end)
pl.figure(1)
pl.clf()
pl.subplot(221)
Expand All @@ -159,7 +161,7 @@ def test_u_n():
# pl.title("difference")
# pl.imshow(ideal-recon)
# pl.colorbar()
print len(theta),"projections"
print(len(theta),"projections")
pl.show()


Expand Down
22 changes: 12 additions & 10 deletions sandbox/clean_data.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@

from __future__ import print_function
from six.moves import input
from ImageD11 import peakmerge, indexing, transformer
from ImageD11 import grain
import sys, os, numpy as np
Expand All @@ -7,7 +9,7 @@
#
# Your work starts here:
#
print "select only peaks of certain rings "
print("select only peaks of certain rings ")

mytransformer.loadfiltered( sys.argv[1] )
mytransformer.loadfileparameters( sys.argv[2] )
Expand All @@ -26,34 +28,34 @@
mytransformer.addcellpeaks()

rh = mytransformer.unitcell.ringhkls
peaks = rh.keys()
peaks = list(rh.keys())
peaks.sort()
m = 0
print "Ring ds tth (h k l) mult npks npks/mult"
print("Ring ds tth (h k l) mult npks npks/mult")
for i,d in enumerate(peaks):
thistth = mytransformer.theorytth[i]
mult = len(rh[d])
print "Ring %3d %2.4f %8.4f"%(i,d,thistth),"(%2d %2d %2d)"%rh[d][0],"%2d"%(mult),
print("Ring %3d %2.4f %8.4f"%(i,d,thistth),"(%2d %2d %2d)"%rh[d][0],"%2d"%(mult), end=' ')
msk = ((thistth+0.2) > tth)&(tth > (thistth-0.2))
npk = msk.sum()
print "%8d %8d"%(npk,1.0*npk/mult)
print("%8d %8d"%(npk,1.0*npk/mult))
m += msk.sum()
print m, tth.shape
print(m, tth.shape)

figure(2)
plot(tth,np.log(mytransformer.colfile.sum_intensity), ",")
show()

if 1:
while 1:
rings_to_use = raw_input("Enter comma separated list of rings to use")
rings_to_use = input("Enter comma separated list of rings to use")
try:
rs = [int(v) for v in rings_to_use.split(',')]
except:
print "I don't understand, please try again"
print("I don't understand, please try again")
continue
print "You entered"," ".join([str(r) for r in rs])
if raw_input("OK?") in ['Y','y']:
print("You entered"," ".join([str(r) for r in rs]))
if input("OK?") in ['Y','y']:
break
else:
rs = [ 0, 2, 6, 10]
Expand Down
20 changes: 11 additions & 9 deletions sandbox/cleanbg.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@

from __future__ import print_function
#!/usr/bin/python2.7

import numpy as np, fabio
Expand Down Expand Up @@ -38,12 +40,12 @@ def cleanbg( stem, nimages, newstem ):
o.name = name
buffy[i] = o.data.copy()
buffo.append( o )
print i,name
print(i,name)
bg = np.clip( buffy.min( axis = 0 ), 90, 65535 ) - 90
# Deal with images up to bufsize/2
for i in range(bufsize/2):
outname = newstem + "%04d.edf"%(i)
print "write",outname, buffo[i].name
print("write",outname, buffo[i].name)
np.subtract( buffo[i].data , bg, buffo[i].data )
buffo[i].write( outname )

Expand All @@ -52,7 +54,7 @@ def cleanbg( stem, nimages, newstem ):
if i < bufsize :
continue
bp = i%bufsize
print "open",name,bp
print("open",name,bp)
o = fabio.open( name )
o.header["Omega"] = omega
o.header["OmegaStep"] = omegastep
Expand All @@ -65,13 +67,13 @@ def cleanbg( stem, nimages, newstem ):
op = (i-bufsize/2-1)%bufsize
np.subtract( buffo[op].data , bg, buffo[op].data )
outname = newstem + "%04d.edf"%(i-bufsize/2-1)
print i,outname, buffo[op].name
print(i,outname, buffo[op].name)
buffo[op].write( outname )
n=i
for i in range(bufsize/2):
outname = newstem + "%04d.edf"%(n+i-bufsize/2)
bp = (n+i-bufsize/2)%bufsize
print "write",outname, buffo[bp].name
print("write",outname, buffo[bp].name)
np.subtract( buffo[bp].data , bg, buffo[bp].data )
buffo[bp].write( outname )

Expand All @@ -87,24 +89,24 @@ def cleanbg( stem, nimages, newstem ):
for indir in glob.glob( "rubydiff*"):
# dirs =[ sys.argv[1] , ]
# for indir in dirs:
print indir
print(indir)
if not os.path.isdir(indir):

continue

outdir = os.path.join("diffproc", indir)
if not os.path.exists(outdir):
print "mkdir",outdir
print("mkdir",outdir)
os.mkdir(outdir)

# check if last image exists for input:
lastin = os.path.join(indir,indir+"1_0720.edf")
lastout = os.path.join(outdir,indir+"1438.edf")
if not os.path.exists( lastin ):
print "Missing image",lastin,"skip"
print("Missing image",lastin,"skip")
continue
if not os.path.exists( lastout ):
print "Missing result",lastout
print("Missing result",lastout)
cleanbg( os.path.join(indir, indir),
720,
os.path.join(outdir,indir) )
Expand Down
10 changes: 6 additions & 4 deletions sandbox/compute_fazit.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@

from __future__ import print_function


"""
Try to compute the radius/arc images required for the
Expand Down Expand Up @@ -47,7 +49,7 @@ def __init__(self, splinefile = None,
self.pars.loadparameters( parfile )
for key in self.required_pars:

if not self.pars.parameters.has_key( key ):
if key not in self.pars.parameters:
raise Exception("Missing parameter "+str(par))

def compute_tth_eta(self, dims):
Expand Down Expand Up @@ -172,15 +174,15 @@ def main():
raise
except:
parser.print_help()
print "\nSorry, there was a problem interpreting your command line"
print("\nSorry, there was a problem interpreting your command line")
raise


if options.pars is None:
print "Failed: You must supply a parameters file, -p option"
print("Failed: You must supply a parameters file, -p option")
sys.exit()
if not os.path.exists( options.pars ):
print "Cannot find your file",options.pars
print("Cannot find your file",options.pars)
sys.exit()

worker = xydisp(
Expand Down
22 changes: 12 additions & 10 deletions sandbox/factors.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@

from __future__ import print_function
# ImageD11_v0.4 Software for beamline ID11
# Copyright (C) 2005 Jon Wright
#
Expand Down Expand Up @@ -72,7 +74,7 @@ def savesvd(self,filename):
s.shape[0],
r.shape[0],
r.shape[1]))
print len(l.astype(np.float).tostring())
print(len(l.astype(np.float).tostring()))
out.write(l.astype(np.float).tostring())
out.write(s.astype(np.float).tostring())
out.write(r.astype(np.float).tostring())
Expand All @@ -84,11 +86,11 @@ def loadsvd(self,filename):
"""
out=open(filename,"rb")
dims=struct.unpack("lllll",out.read(struct.calcsize("lllll")))
print dims,8*dims[0]*8*dims[1]
print(dims,8*dims[0]*8*dims[1])
l=np.fromstring(out.read(8*dims[0]*dims[1]),np.float)
s=np.fromstring(out.read(8*dims[2]),np.float)
r=np.fromstring(out.read(8*dims[3]*dims[4]),np.float)
print l.shape,s.shape,r.shape,dims
print(l.shape,s.shape,r.shape,dims)
l=np.reshape(l,(dims[0],dims[1]))
r=np.reshape(r,(dims[3],dims[4]))
self.svd=(l,s,r)
Expand All @@ -98,19 +100,19 @@ def loadsvd(self,filename):
def setnfactors(self,n):
"""Decide on the number of factors in the data"""
self.nfactors=n
print "Number of factors set to",self.nfactors
print("Number of factors set to",self.nfactors)

def loadchis(self,filename):
"""
Glob for filenames
"""
fl=glob.glob(filename[:-8]+"????"+".chi")
fl.sort()
print "Number of chi files is:",len(fl)
print("Number of chi files is:",len(fl))
dl=[opendata.openchi(f).data[:,1] for f in fl]
self.obsdata=np.array(dl)
self.x=opendata.openchi(fl[0]).data[:,0]
print self.x.shape,self.obsdata.shape
print(self.x.shape,self.obsdata.shape)

def saveobsdata(self,filename):
"""
Expand All @@ -129,12 +131,12 @@ def readobsdata(self,filename):
infile=open(filename,"rb")
sizes=struct.unpack("lll",infile.read(struct.calcsize("lll")))
# Type is Float therefore 8 bytes per item
print sizes
print(sizes)
self.x=np.fromstring(infile.read(sizes[0]*8),np.float)
self.obsdata=np.fromstring(infile.read(8*sizes[1]*sizes[2]),np.float)
print self.obsdata.shape
print(self.obsdata.shape)
self.obsdata=np.reshape(self.obsdata,(sizes[1],sizes[2]))
print self.x.shape,self.obsdata.shape
print(self.x.shape,self.obsdata.shape)


if __name__=="__main__":
Expand All @@ -144,7 +146,7 @@ def readobsdata(self,filename):
o.loadchis(sys.argv[1])
else:
o.readobsdata(sys.argv[1])
print dir(o)
print(dir(o))
o.setnfactors(int(sys.argv[2]))
o.factorsvd()
o.generatedata()
Loading

0 comments on commit 115bd97

Please sign in to comment.