-
Notifications
You must be signed in to change notification settings - Fork 1
/
interactive2.py
422 lines (373 loc) · 17.6 KB
/
interactive2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
print("Loading modules...")
from os import remove, environ, path
#print(environ["DISPLAY"])
environ["DISPLAY"] = ":1" # this line may or may not be needed depending on the system
from concurrent.futures import ProcessPoolExecutor
from csv import writer
from ctypes import c_double
from hyperspy.api import load
from math import ceil
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib import cm
from matplotlib import colors
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from matplotlib.ticker import LinearLocator
from multiprocessing import Array
from numpy import sqrt, array, ndenumerate, arange, min, max, percentile, linspace, nonzero, zeros, around, unravel_index, argmax, mean
from numpy.ctypeslib import as_array
from pandas import DataFrame
from PIL import Image, ImageTk
from pixstem.api import PixelatedSTEM
from seaborn import heatmap
import tkinter as tk
from tkinter import font
from scipy.signal.signaltools import wiener
from skimage.feature import match_template
from scipy.ndimage import gaussian_filter
from skimage.restoration import denoise_nl_means, estimate_sigma
print("Modules loaded.")
file = None
distances = None
singleValues = None
currFunc = None
def setCurrFunc(funcName):
global currFunc, file, singleValues
currFunc = str(funcName)
entry.delete(0, tk.END)
if currFunc is "loadFile":
entry.bind("<Return>", getEntry)
label1['text'] = label1['text'] + "Please enter the path of the input file in the text box provided then press Enter.\n"
elif currFunc is "toCSV":
if file is None:
label1['text'] = label1['text'] + "Please load a file before saving data.\n"
elif singleValues is None:
label1['text'] = label1['text'] + "Please analyze the file before saving data.\n"
else:
entry.bind("<Return>", getEntry)
label1['text'] = label1['text'] + "Please enter the path of the file you want to save to in the text box provided then press Enter.\n"
elif currFunc is "analysis":
if file is None:
label1['text'] = label1['text'] + "Please load a file before starting analysis.\n"
else :
entry.bind("<Return>", getEntry)
label1['text'] = label1['text'] + "Please enter the number of rows and columns you would like to analyze, as integers, seperated by spaces. Press Enter when ready.\n"
def getEntry(event):
global currFunc
if currFunc is "loadFile":
entry.unbind("<Return>")
loadFile(entry.get())
elif currFunc is "analysis":
entry.unbind("<Return>")
startAnalysis(entry.get())
elif currFunc is "toCSV":
entry.unbind("<Return>")
toCSV(entry.get())
def loadFile(filename = None):
global file
label1['text'] = label1['text'] + "Loading file...\n"
root.update()
try:
file = load(filename)
label1['text'] = label1['text'] + "File loaded.\n"
except:
label1['text'] = label1['text'] + "Error loading. Please check path and try again.\n"
entry.delete(0, tk.END)
#entry.unbind("<Return>")
def distance(x1, y1, x2, y2):
return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2))
def intensity(values):
s = PixelatedSTEM(file.inav[values[0], values[1]])
imarray = array(s)
singleValues[values[1]][values[0]] = imarray[values[3]][values[2]]
def findCenter(im, peak):
center = (0,0)
minimum = 144
for (x,y) in ndenumerate(peak):
for (a, b) in y:
length = len(im)
d = distance(length / 2, length / 2, b, a)
if (int(a) < length and int(b) < length and d < minimum):
minimum = d
center = (b, a)
return center
def multiprocessing_func(values):
global singleValues, distances
s = PixelatedSTEM(file.inav[values[0], values[1]])
original = array(s)
############################################################################################################################
# # FILTERS
# sigma_est = mean(estimate_sigma(original, ))
# # patch_size for 580 - 1, patch_size for 144 = 3
# nlm = denoise_nl_means(original, h=1.15*sigma_est, fast_mode=True, patch_size=3, patch_distance=6, )
# gaussian = gaussian_filter(original, 1.15*sigma_est)
# wien = wiener(original, 5, 3)
# s = PixelatedSTEM(gaussian) # Change this to whatever filter you want to use
############################################################################################################################
# # PIXSTEM
# s = s.rotate_diffraction(0,show_progressbar=False)
# st = s.template_match_disk(disk_r=5, lazy_result=False, show_progressbar=False)
# peak_array = st.find_peaks(lazy_result=False, show_progressbar=False)
# peak_array_com = s.peak_position_refinement_com(peak_array, lazy_result=False, show_progressbar=False)
# s_rem = s.subtract_diffraction_background(lazy_result=False, show_progressbar=False)
# peak_array_rem_com = s_rem.peak_position_refinement_com(peak_array_com, lazy_result=False, show_progressbar=False)
############################################################################################################################
# MY METHOD
# defines template and templates matches
# spot for 580 - [265:320, 265:320]
# spot for 144 - [65:80, 65:80]
template = original[65:80, 65:80]
result = match_template(original, template, pad_input=True)
# only takes points greater than the threshold r-value
tempList = []
for i in range(len(result)):
for j in range(len(result[i])):
if (result[i][j] > 0.7): # change correlation value
tempList.append((i, j))
# removes duplicate spots that are too close to each other
i = 0
l = []
while i < len(tempList):
j = 0
temp = []
point = tempList[i]
while j < len(tempList):
if distance(point[0], point[1], tempList[j][0], tempList[j][1]) < 15: # change minimum center distance
temp.append(tempList[j])
tempList.pop(j)
else:
j = j + 1
max = 0
pnt = temp[0]
for j in range(len(temp)):
if (result[pnt[0]][pnt[1]] < result[temp[j][0]][temp[j][1]]):
max = result[temp[j][0]][temp[j][1]]
pnt = temp[j]
l.append(pnt)
peak_array_rem_com = [[], l]
############################################################################################################################
closestPoint = None
closestPoint1 = None
length = len(original)
for (x,y) in ndenumerate(peak_array_rem_com):
minimum = 999999
minimum1 = 999999
for (a, b) in y:
dis = distance(values[2], values[3], b, a)
dis1 = distance(values[4], values[5], b, a)
if dis < minimum and dis < length / 10:
minimum = dis
closestPoint = (b, a)
if dis1 < minimum1 and dis1 < length / 10:
minimum1 = dis1
closestPoint1 = (b, a)
print(closestPoint, closestPoint1, values[4], values[5])
posDistance = distance(closestPoint[0], closestPoint[1], closestPoint1[0], closestPoint1[1])
singleValues[values[1]][values[0]] = round(posDistance, 2)
def startAnalysis(values = None):
global file, currFunc
methodOfAnalysis = ""
def assignMethod(method):
global methodOfAnalysis
methodOfAnalysis = method
def mousecoords(event):
global methodOfAnalysis
s = PixelatedSTEM(file.inav[0, 0])
length = len(array(s))
pointxy = (-1, -1)
while pointxy is (-1, -1):
pointxy = (int(event.x * length / 400), int(event.y * length / 400)) # get the mouse position from event
l['text'] = l['text'] + str(pointxy[0]) + " " + str(pointxy[1]) + "\n"
r.update()
c2.unbind('<Button-1>')
c2.bind('<Button-1>', lambda event : mousecoords1(event,pointxy))
def mousecoords1(event, pointxy):
global methodOfAnalysis
pointxy1 = None
s = PixelatedSTEM(file.inav[0, 0])
length = len(array(s))
while pointxy1 is None:
pointxy1 = (int(event.x * length / 400), int(event.y * length / 400)) # get the mouse position from event
print("pointxy1", pointxy1, "\n", "pointxy", pointxy)
l['text'] = l['text'] + str(pointxy1[0]) + " " + str(pointxy1[1]) + "\n"
l['text'] = l['text'] + "Starting analysis...\n"
analysis(pointxy, pointxy1, values, methodOfAnalysis)
r.update()
remove("temp.png")
c2.unbind('<Button-1>')
r.destroy()
label1['text'] = label1['text'] + "Analysis complete.\n"
s = PixelatedSTEM(file.inav[60, 60])
s.save("temp.png")
img = Image.open("temp.png")
img = img.resize((400,400), Image.ANTIALIAS)
img.save('temp.png')
r = tk.Toplevel(root)
c = tk.Canvas(r, height=720, width=1080)
c.pack()
f = tk.Frame(r, bg='#333333')
f.place(relwidth=1, relheight=1)
l = tk.Message(f, bg='#999999', font=('Calibri', 15), anchor='nw', justify='left', highlightthickness = 0, bd=0, width = 1000)
l.place(relx=0.05, rely=0.7, relwidth=0.9, relheight=0.2)
b1 = tk.Button(f, text='Intensity Mapping', bg='#620000', font=('Calibri', 15), highlightthickness = 0, bd=0, activebackground='#800000', activeforeground='#ffffff', command=lambda: assignMethod("intensity"), pady=0.02, fg='#ffffff')
b1.place(relx=0.2, rely=0.6, relwidth=0.2, relheight=0.05)
b2 = tk.Button(f, text='Strain Mapping', bg='#620000', font=('Calibri', 15), highlightthickness = 0, bd=0, activebackground='#800000', activeforeground='#ffffff', command=lambda: assignMethod("strain"), pady=0.02, fg='#ffffff')
b2.place(relx=0.6, rely=0.6, relwidth=0.2, relheight=0.05)
c2 = tk.Canvas(r, width=400, height=400)
c2.place(relx=0.3)
img = ImageTk.PhotoImage(Image.open("temp.png"))
c2.create_image(0, 0, anchor='nw', image=img)
c2.bind('<Button-1>', mousecoords)
l['text'] = l['text'] + "Please click on the method of analysis and then the point you would like to analyze from the diffraction pattern above.\n"
r.mainloop()
if path.exists("temp.png"):
remove("temp.png")
def analysis(pointxy, pointxy1, values, methodOfAnalysis=""):
global file, singleValues, distances
t = values.split(" ")
COL = int(t[1])
ROW = int(t[0])
list = []
for r in range(ROW):
for c in range(COL):
list.append((r, c, pointxy[0], pointxy[1], pointxy1[0], pointxy1[1]))
shared_array_base = Array(c_double, ROW*COL)
singleValues = as_array(shared_array_base.get_obj())
singleValues = singleValues.reshape(COL, ROW)
shared_array = Array(c_double, ROW*COL*50)
distances = as_array(shared_array.get_obj())
distances = distances.reshape(COL, ROW, 50)
with ProcessPoolExecutor() as executor:
if methodOfAnalysis is "strain":
executor.map(multiprocessing_func, list)
else:
executor.map(intensity, list)
entry.delete(0, tk.END)
def toCSV(filename = None):
global singleValues
f = open(filename, "w")
w = writer(f)
for i in singleValues:
w.writerow(i)
f.close()
label1['text'] = label1['text'] + "File saved.\n"
entry.delete(0, tk.END)
#entry.unbind("<Return>")
def heatMapMaker(minimum, maximum, parity = 0):
global singleValues, distances
if parity == 0:
data = singleValues.copy()
df = DataFrame(data, columns=arange(len(data[0])), index=arange(len(data)))
_, a = plt.subplots(figsize=(6,5.5))
chart1 = heatmap(df, cmap=cm.get_cmap("rainbow"),ax=a, vmin = minimum, vmax = maximum, square=True)
return chart1.get_figure()
else:
data = zeros((len(singleValues), len(singleValues[0])), dtype=float)
for i in range(len(distances)):
for j in range(len(distances[i])):
sum = 0
num = 0
for k in distances[i][j]:
if minimum < k < maximum:
sum += k
num += 1
if num > 0:
data[i][j] = round(sum / num, 1)
df = DataFrame(data, columns=arange(len(data[0])), index=arange(len(data)))
_, a = plt.subplots(figsize=(6,5.5))
gray = cm.get_cmap('gray', 512)
newcolors = gray(linspace(0.15, 0.85, 2048))
white = array([255/256, 255/256, 255/256, 1])
newcolors[:1, :] = white
newcolors[2047:, :] = white
newcmp = colors.ListedColormap(newcolors)
chart = heatmap(df, cmap=newcmp, vmin = minimum, vmax = maximum, square=True)
return chart.get_figure()
def barChart(INTERVAL = 0.1):
global distances
if file is None:
label1['text'] = label1['text'] + "Please load a file before creating a bar chart.\n"
elif distances is None:
label1['text'] = label1['text'] + "Please analyze the file before creating a bar chart.\n"
else:
label1['text'] = label1['text'] + "Creating bar chart. This might take several minutes depending on the size of data.\n"
root.update()
dist = singleValues.flatten()
fig, a = plt.subplots(figsize=(6,5.5))
plt.xlabel('Distance from center peek', fontsize = 10)
plt.ylabel('Counts', fontsize = 10)
plt.title('Distance Counts', fontsize = 10)
#plt.bar(y_pos, counts, align='center', alpha=0.95) # creates the bar plot
plt.hist(dist, bins=500)
def scopeHeatMap(event):
values = e.get().split(" ")
minimum = float(values[0])
maximum = float(values[1])
f = heatMapMaker(minimum, maximum, 1)
chart_type = FigureCanvasTkAgg(f, barChartWindow)
chart_type.draw()
chart_type.get_tk_widget().place(relx=0.51, rely=0.2)
barChartWindow = tk.Toplevel(root)
barChartWindow.geometry('1920x1080')
chart_type = FigureCanvasTkAgg(plt.gcf(), barChartWindow)
chart_type.draw()
chart_type.get_tk_widget().place(relx=0.0, rely=0.2, relwidth=0.5)
m = tk.Message(barChartWindow, font=('Calibri', 15), highlightthickness = 0, bd=0, width=1000, justify='center')
m['text'] = "Enter the minimum value and the maximum value (exclusive) seperated by a space. Press Enter to create the heatmap with these specifications"
m.place(relx = 0.25, rely=0.05)
e = tk.Entry(barChartWindow, font=('Calibri', 15))
e.place(relx=0.44, rely=0.1)
e.bind("<Return>", scopeHeatMap)
def outlier(data):
data = data.flatten()
q1 = percentile(data, 25)
q3 = percentile(data, 75)
iqr = q3 - q1
minimum = q1 - (1.5 * iqr)
maximum = q3 + (1.5 * iqr)
return minimum, maximum
def heatMap():
global singleValues
if file is None:
label1['text'] = label1['text'] + "Please load a file before creating a heat map.\n"
elif singleValues is None:
label1['text'] = label1['text'] + "Please analyze the file before creating a heat map.\n"
else:
minimum, maximum = outlier(singleValues)
fig = heatMapMaker(minimum, maximum, 0)
heatMapWindow = tk.Toplevel(root)
heatMapWindow.geometry('1280x720')
chart_type = FigureCanvasTkAgg(fig, heatMapWindow)
chart_type.draw()
chart_type.get_tk_widget().pack()
if __name__ == "__main__":
HEIGHT = 1080
WIDTH = 1920
root = tk.Tk()
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()
frame = tk.Frame(root, bg='#450000')
frame.place(relwidth=1, relheight=1)
# Menu Label
label = tk.Label(frame, text='Menu', bg='#450000', font=('Times New Roman', 50), fg='#ffffff')
label.place(relx=0.40, rely=0.05, relwidth=0.2, relheight=0.05)
# Text Output box
label1 = tk.Message(frame, bg='#ffffff', font=('Calibri', 15), anchor='nw', justify='left', highlightthickness = 0, bd=0, width = 1500)
label1.place(relx=0.1, rely=0.5, relwidth=0.8, relheight=0.35)
# Entry box
entry = tk.Entry(frame, font=('Calibri', 15))
entry.place(relx=0.1, rely=0.9, relwidth=0.8, relheight=0.05)
# Buttons
button = tk.Button(frame, text='Load File', bg='#620000', font=('Calibri', 30), highlightthickness = 0, bd=0, activebackground='#800000', activeforeground='#ffffff', command=lambda: setCurrFunc("loadFile"), pady=0.02, fg='#ffffff')
button.place(relx=0.42, rely=0.15, relwidth=0.16, relheight=0.05)
button1 = tk.Button(frame, text='Start Analysis', bg='#620000', font=('Calibri', 30), highlightthickness = 0, bd=0, activebackground='#800000', activeforeground='#ffffff', command=lambda: setCurrFunc("analysis"), pady=0.02, fg='#ffffff')
button1.place(relx=0.39, rely=0.22, relwidth=0.22, relheight=0.05)
button2 = tk.Button(frame, text='Create Bar Chart', bg='#620000', font=('Calibri', 30), highlightthickness = 0, bd=0, activebackground='#800000', activeforeground='#ffffff', command=lambda: barChart(), pady=0.02, fg='#ffffff')
button2.place(relx=0.375, rely=0.29, relwidth=0.25, relheight=0.05)
button3 = tk.Button(frame, text='Create Heat Map', bg='#620000', font=('Calibri', 30), highlightthickness = 0, bd=0, activebackground='#800000', activeforeground='#ffffff', command=lambda: heatMap(), pady=0.02, fg='#ffffff')
button3.place(relx=0.38, rely=0.36, relwidth=0.24, relheight=0.05)
button4 = tk.Button(frame, text='Transfer Data to .csv', bg='#620000', font=('Calibri', 30), highlightthickness = 0, bd=0, activebackground='#800000', activeforeground='#ffffff', command=lambda: setCurrFunc("toCSV"), pady=0.02, fg='#ffffff')
button4.place(relx=0.34, rely=0.43, relwidth=0.32, relheight=0.05)
root.mainloop()
if path.exists("temp.png"):
remove("temp.png")