Skip to content

Commit 482be92

Browse files
committed
Working copy of 30 May, 2016
1 parent 731d481 commit 482be92

12 files changed

+1808
-269
lines changed

Diff for: contours.py

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
import numpy as np
2+

Diff for: getAxyDistributions.py

+112
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Wed Mar 20 10:59:08 2013
4+
5+
@author: gf
6+
"""
7+
8+
import os
9+
import pickle
10+
import numpy as np
11+
import itertools
12+
import getLogDistributions as gLD
13+
reload(gLD)
14+
import matplotlib.pyplot as plt
15+
import tables
16+
17+
NN = {1:(1,1),
18+
2:(2,1),
19+
3:(3,1),
20+
4:(2,2),
21+
5:(3,2),
22+
6:(3,2),
23+
7:(3,3),
24+
8:(3,3),
25+
9:(3,3),
26+
10:(5,2),
27+
11:(4,3),
28+
12:(4,3),
29+
13:(4,4),
30+
14:(4,4),
31+
15:(5,3),
32+
16:(4,4)
33+
}
34+
35+
mainDir = "/run/media/gf/DATA/meas/Barkh/Films/NiO_Fe/"
36+
f5filename = os.path.join(mainDir, "NiO_Fe_results.h5")
37+
38+
f5 = tables.openFile(f5filename, mode="r")
39+
40+
runNode = f5.root.NiO80.M10x.run21
41+
42+
area = 1000.*1000.
43+
log_step = 1./10
44+
45+
Axy_labels = []
46+
# Collect Axy labels first
47+
#for seqNode in f5.listNodes(runNode):
48+
#AxyNode = seqNode.clus
49+
#for label in f5.listNodes(AxyNode):
50+
#Axy_labels.append(label.name)
51+
#Axy_labels = set(Axy_labels)
52+
53+
aval_clus = 'clus'
54+
Axy = {}
55+
Axy[aval_clus] = {}
56+
57+
for seqNode in f5.listNodes(runNode):
58+
clusNode = f5.getNode(seqNode, aval_clus)
59+
for lb in f5.listNodes(clusNode):
60+
Axy[aval_clus][lb.name] = np.concatenate((
61+
Axy[aval_clus].get(lb,np.array([])),lb.read()))
62+
f5.close()
63+
64+
fig = plt.figure()
65+
fig.set_size_inches((20,10),forward=True)
66+
rows, cols = NN[len(Axy[aval_clus])]
67+
for n, key in enumerate(Axy[aval_clus]):
68+
selected_Axy = Axy[aval_clus][key]
69+
print "==============="
70+
print "Cluster of type %s" % key
71+
N_S, bins = np.histogram(selected_Axy, np.arange(1, max(selected_Axy)+2),
72+
normed=False)
73+
S = bins[:-1]
74+
# Compress the data to non-zero values
75+
#cond = N_S!=0
76+
#N_S = np.compress(cond, N_S)
77+
#S = np.compress(cond, S)i
78+
yAverage = []
79+
# Get log bins
80+
SlogBins, logBins = gLD.getLogBins(bins[0], bins[-1], log_step)
81+
for i, j in zip(logBins[:-1],logBins[1:]):
82+
q1, q2 = np.greater_equal(S, i), np.less(S, j)
83+
q = np.logical_and(q1, q2)
84+
if sum(q) == 0:
85+
averageValue = np.NaN
86+
else:
87+
#allElements = [val for val in itertools.chain(*A_S[q])]
88+
averageValue = np.sum(S[q]*N_S[q])/area/(j-i)
89+
yAverage.append(averageValue)
90+
yAverage = np.asanyarray(yAverage)
91+
# Check if there are NaN values
92+
iNan = np.isnan(yAverage)
93+
x = SlogBins[~iNan]
94+
y = yAverage[~iNan]
95+
96+
plt.subplot(rows, cols, n+1)
97+
plt.loglog(x, y, 'o', label=key)
98+
# Plot the fit
99+
q = np.logical_and(np.greater_equal(x, 10), np.less(x, 1000))
100+
if sum(q)!=0:
101+
X, Y = np.log10(x[q]), np.log10(y[q])
102+
m, k = np.polyfit(X, Y, 1)
103+
lin_x = np.linspace(10,1000)
104+
new_y = 10**k*lin_x**m
105+
plt.plot(lin_x, new_y, '-')
106+
print "exponent: %f" % m
107+
x, PS, PSerror = gLD.logDistribution(selected_Axy, log_step, normed=False)
108+
plt.loglog(x, x*PS/area, '^')
109+
plt.loglog(x, PS, 'v', label="P(S)")
110+
plt.errorbar(x, PS, PSerror,fmt=None)
111+
plt.legend()
112+
plt.show()

Diff for: getAxyLabels.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def getAxyLabels(labels, imageDir="Left_to_right", edgeThickness=1, fraction=Non
4747
elif imageDir == "Top_to_bottom":
4848
lrbt = top, bottom, left, right
4949
else:
50-
raise ValueError, "avalanche direction not defined"
50+
raise ValueError("avalanche direction not defined")
5151
# Find the sets
5252
# Select the labels contained in the edges
5353
#setLrbt = set(left+right+bottom+top)
@@ -82,7 +82,7 @@ def getAxyLabels(labels, imageDir="Left_to_right", edgeThickness=1, fraction=Non
8282
#a = a.repeat(100,axis=0)
8383
#a = a.repeat(66,axis=1)
8484
labels, n = nd.label(a, structure)
85-
print labels
85+
print(labels)
8686
list_sizes = nd.sum(a, labels, range(1,n+1))
8787
array_sizes = scipy.array(list_sizes,dtype='int16')
8888
array_Axy = getAxyLabels(labels,'Bottom_to_top', edgeThickness=1, fraction=0.5)
@@ -91,5 +91,5 @@ def getAxyLabels(labels, imageDir="Left_to_right", edgeThickness=1, fraction=Non
9191
d[Axy] = scipy.concatenate((d.get(Axy,a0),sizes))
9292

9393
for i, results in enumerate(zip(array_sizes,array_Axy)):
94-
print i+1, results
95-
print "Done in %.3f s" % (time.time()-startTime)
94+
print(i+1, results)
95+
print("Done in %.3f s" % (time.time()-startTime))

Diff for: getLogDistributions.py

+15-6
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,11 @@ def logDistribution(listValues, log_step=0.2, first_point=None,
4848
last_point=None, normed=True):
4949
"""
5050
Calculate the distribution in log scale from a list of values
51+
Returns:
52+
--------------
53+
X : array of the x values at the center (in log-scale) of the bin
54+
Y : array of the y values at the center (in log-scale) of the bin
55+
Yerr : array of the y errors, calculated by a binomial distribution
5156
"""
5257
# Check the list of Values
5358
if not checkIfVoid(listValues):
@@ -56,13 +61,17 @@ def logDistribution(listValues, log_step=0.2, first_point=None,
5661
first_point = scipy.amin(listValues)
5762
if not last_point:
5863
last_point = scipy.amax(listValues)
59-
xbins, bins = getLogBins(first_point, last_point, log_step)
60-
yhist = scipy.stats.stats.histogram2(listValues, bins)
61-
deltas = bins[1:]-bins[:-1]
62-
yhist = yhist[:-1]/deltas
64+
X, Xbins = getLogBins(first_point, last_point, log_step)
65+
Y = scipy.stats.stats.histogram2(listValues, Xbins)
66+
deltas = Xbins[1:]-Xbins[:-1] # Check if zeros occurs
67+
bool0 = Y!=0
68+
for ary in [X,Y,deltas]:
69+
ary = scipy.compress(bool0, ary)
70+
Y = Y[:-1]/deltas
71+
Yerr = (Y * (1. - Y/sum(Y)))**0.5 / (deltas*sum(Y))
6372
if normed:
64-
yhist = yhist/scipy.sum(yhist)
65-
return xbins, yhist
73+
Y = Y/scipy.sum(Y)
74+
return X, Y, Yerr
6675

6776
def averageLogDistribution(values, log_step=0.2, density=False,
6877
first_point=None, last_point=None):

Diff for: getRofImages.py

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Tue Mar 19 09:06:32 2013
4+
5+
@author: gf
6+
"""
7+
8+
import os, re, glob, sys
9+
import rof
10+
import numpy as np
11+
import Image
12+
import scipy.misc as misc
13+
14+
def denoise(im):
15+
U,T = rof.denoise(im,im)
16+
return np.asarray(U, dtype='int32')
17+
18+
19+
import skimage.io as im_io
20+
21+
class Imread_convert():
22+
23+
def __call__(self, f):
24+
im = np.array(Image.open(f), dtype='int32')
25+
# imageList = list(im.getdata())
26+
# sizeX, sizeY = im.size
27+
# return np.asanyarray(imageList).reshape(sizeY, sizeX)
28+
return im
29+
30+
31+
def natural_key(string_):
32+
"""See http://www.codinghorror.com/blog/archives/001018.html"""
33+
return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_)]
34+
35+
mainDir, pattern = "/media/DATA/meas/Barkh/Films/NiO-Fe/NiO80/NiO80 run19 10x pinLin 10iter/", "Data1-*.tif"
36+
37+
s = "(%s|%s)" % tuple(pattern.split("*"))
38+
patternCompiled = re.compile(s)
39+
# Load all the image filenames
40+
imageFileNames = glob.glob1(mainDir, pattern)
41+
# Sort it with natural keys
42+
imageFileNames.sort(key=natural_key)
43+
44+
if not len(imageFileNames):
45+
print "ERROR, no images in %s" % mainDir
46+
sys.exit()
47+
else:
48+
print "Found %d images in %s" % (len(imageFileNames), mainDir)
49+
50+
# Prepare the rof subdir
51+
rofDir = os.path.join(mainDir, 'rof')
52+
if not os.path.exists(rofDir):
53+
os.mkdir(rofDir)
54+
55+
56+
imread_convert = Imread_convert()
57+
# Load the images
58+
print "Loading images: "
59+
load_pattern = [os.path.join(mainDir,ifn) for ifn in imageFileNames]
60+
61+
imageCollection = im_io.ImageCollection(load_pattern, load_func=imread_convert)
62+
63+
for i, im in enumerate(imageCollection):
64+
print "Image n. %i" % i
65+
U = denoise(im)
66+
fileName = imageFileNames[i]
67+
fileName = os.path.join(mainDir, 'rof', fileName)
68+
q = misc.toimage(U)
69+
q.save(fileName)
70+

Diff for: gpuSwitchtime.py

+7-8
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ def get_gpuSwitchTime(stackImages, kernel, device=0):
193193
dim_z = 80
194194
a = np.random.randn(dim_z,dim_y,dim_x)
195195
a = a.astype(np.int32)
196-
print "Loading %.2f MB of data" % (a.nbytes/1e6)
196+
print("Loading %.2f MB of data" % (a.nbytes/1e6))
197197
# Call the GPU kernel
198198
kernel = np.array([-1]*5+[1]*5)
199199
t0 = time.time()
@@ -203,16 +203,15 @@ def get_gpuSwitchTime(stackImages, kernel, device=0):
203203
step = kernel
204204
cpuswitch=np.zeros((dim_y,dim_x),dtype=np.int32)
205205
cpulevels=np.zeros((dim_y,dim_x),dtype=np.int32)
206-
print "Loading %.2f MB of data" % (2*cpuswitch.nbytes/1e6)
206+
print("Loading %.2f MB of data" % (2*cpuswitch.nbytes/1e6))
207207
t3=time.time()
208208
for i in range(0,dim_x):
209209
for j in range(0,dim_y):
210210
indice=(nd.convolve1d(a[:,j,i],step,mode='reflect')).argmin()
211211
cpuswitch[j,i]=indice
212212
timeCpu = time.time()-t3
213-
print ("GPU calculus done = %.4f s" %timeGpu)
214-
print ("CPU calculus done = %.4f s" %timeCpu)
215-
print "Difference on switch : \n"
216-
print gpuswitch-cpuswitch
217-
218-
print ("\nGPU is %d times faster than CPU " %(timeCpu/timeGpu))
213+
print("GPU calculus done = %.4f s" %timeGpu)
214+
print("CPU calculus done = %.4f s" %timeCpu)
215+
print("Difference on switch : \n")
216+
print(gpuswitch-cpuswitch)
217+
print("\nGPU is %d times faster than CPU " %(timeCpu/timeGpu))

0 commit comments

Comments
 (0)