Skip to content

Commit 587210b

Browse files
author
LAKESIDE\LindaT18
committed
code cleanup and documentation
1 parent 1a56a6b commit 587210b

File tree

10 files changed

+356
-370
lines changed

10 files changed

+356
-370
lines changed

PythonGUI_apps/FLIM_analysis/FLIM_plot.py

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,6 @@
1212
import customplotting.mscope as cpm
1313
# local modules
1414

15-
16-
1715
pg.mkQApp()
1816
pg.setConfigOption('background', 'w')
1917
pg.setConfigOption('imageAxisOrder', 'row-major')
@@ -34,27 +32,29 @@ def __init__(self):
3432
self.ui = WindowTemplate()
3533
self.ui.setupUi(self)
3634

35+
#set up ui signals
3736
self.ui.load_scan_pushButton.clicked.connect(self.open_pkl_file)
3837
self.ui.plot_intensity_sums_pushButton.clicked.connect(self.plot_intensity_sums)
3938
self.ui.plot_raw_hist_data_pushButton.clicked.connect(self.plot_raw_scan)
4039
self.ui.save_intensities_image_pushButton.clicked.connect(self.save_intensities_image)
4140
self.ui.save_intensities_array_pushButton.clicked.connect(self.save_intensities_array)
4241
self.ui.compare_checkBox.stateChanged.connect(self.switch_compare)
4342
self.ui.intensity_sums_viewBox.roi.sigRegionChanged.connect(self.line_profile_update_plot)
44-
4543
self.ui.import_pkl_pushButton.clicked.connect(self.import_pkl_to_convert)
4644
self.ui.pkl_to_h5_pushButton.clicked.connect(self.pkl_to_h5)
45+
4746
self.show()
4847

49-
"""Open Scan Files"""
5048
def open_pkl_file(self):
49+
""" Open FLIM scan file """
5150
try:
5251
self.filename = QtWidgets.QFileDialog.getOpenFileName(self)
5352
self.pkl_file = pickle.load(open(self.filename[0], 'rb'))
5453
except Exception as err:
5554
print(format(err))
5655

5756
def import_pkl_to_convert(self):
57+
""" Open pkl file to convert to h5 """
5858
try:
5959
self.pkl_to_convert = QtWidgets.QFileDialog.getOpenFileName(self)
6060
self.ui.result_textBrowser.append("Done Loading - .pkl to convert")
@@ -70,11 +70,10 @@ def plot_intensity_sums(self):
7070
self.x_scan_size = float(data['Scan Parameters']['X scan size (um)'])
7171
self.y_step_size = float(data['Scan Parameters']['Y step size (um)'])
7272
self.y_scan_size = float(data['Scan Parameters']['Y scan size (um)'])
73-
# TODO test line scan plots
7473

7574
hist_data = data["Histogram data"]
7675
hist_data = np.reshape(hist_data, newshape=(hist_data.shape[0], self.numb_pixels_X*self.numb_pixels_Y))
77-
self.intensity_sums = np.sum(hist_data, axis=0)
76+
self.intensity_sums = np.sum(hist_data, axis=0) #sum intensities for each pixel
7877
self.intensity_sums = np.reshape(self.intensity_sums, newshape=(self.numb_pixels_X, self.numb_pixels_Y))
7978
self.ui.intensity_sums_viewBox.view.invertY(False) # stop y axis invert
8079
self.ui.intensity_sums_viewBox.setImage(self.intensity_sums, scale=
@@ -88,6 +87,7 @@ def plot_intensity_sums(self):
8887
print(format(err))
8988

9089
def line_profile_update_plot(self):
90+
""" Handle line profile for intensity sum viewbox """
9191
if hasattr(self, "intensity_sums"):
9292
roiPlot = self.ui.intensity_sums_viewBox.getRoiPlot()
9393
roiPlot.clear()
@@ -144,10 +144,10 @@ def plot_raw_scan(self):
144144

145145
def switch_compare(self):
146146
"""
147-
Handles compare checkbox. If checked, show second ROI that user can use for comparison to first ROI.
147+
Handles compare checkbox. If checked, show second ROI on raw histogram data that user can use for comparison to first ROI.
148148
"""
149149
if self.ui.compare_checkBox.isChecked() and hasattr(self, "hist_image"):
150-
if not hasattr(self, "roi2"):
150+
if not hasattr(self, "roi2"): #create roi if doesn't exist yet
151151
self.roi2 = pg.ROI(pos=[0,0], size=[int(self.x_scan_size/2), int(self.y_scan_size/2)], movable=True, pen='r')
152152
self.roi2.addScaleHandle([1, 1], [0, 0])
153153
self.roi2.addRotateHandle([0, 0], [1, 1])
@@ -162,12 +162,13 @@ def switch_compare(self):
162162
else:
163163
self.roi2.hide()
164164
self.roi2_plot.hide()
165-
else:
165+
else: #if not checked, hide roi
166166
if hasattr(self, "roi2"):
167167
self.roi2.hide()
168168
self.roi2_plot.hide()
169169

170170
def update_roi2_plot(self):
171+
""" Update plot corresponding to second roi """
171172
#Adapted from pyqtgraph imageview sourcecode
172173

173174
image = self.ui.raw_hist_data_viewBox.getProcessedImage()
@@ -177,6 +178,7 @@ def update_roi2_plot(self):
177178
data, coords = self.roi2.getArrayRegion(image.view(np.ndarray), self.ui.raw_hist_data_viewBox.imageItem, axes, returnMappedCoords=True)
178179
if data is None:
179180
return
181+
180182
# Average data within entire ROI for each frame
181183
data = data.mean(axis=max(axes)).mean(axis=min(axes))
182184
xvals = self.ui.raw_hist_data_viewBox.tVals
@@ -199,7 +201,7 @@ def save_intensities_array(self):
199201
filename_ext = os.path.basename(self.filename[0])
200202
filename = os.path.splitext(filename_ext)[0] #get filename without extension
201203
save_to = os.getcwd() + "\\" + filename + "_intensity_sums.txt"
202-
np.savetxt(save_to, self.intensity_sums.T, fmt='%f') #save transpoed intensity sums, as original array handles x in cols and y in rows
204+
np.savetxt(save_to, self.intensity_sums.T, fmt='%f') #save transposed intensity sums, as original array handles x in cols and y in rows
203205
except:
204206
pass
205207

@@ -220,15 +222,15 @@ def pkl_to_h5(self):
220222
def traverse_dict_into_h5(self, dictionary, h5_output):
221223
#Create an h5 file using .pkl with scan data and params
222224
for key in dictionary:
223-
if type(dictionary[key]) == dict:
225+
if type(dictionary[key]) == dict: #if subdictionary, create a group
224226
group = h5_output.create_group(key)
225227
previous_dict = dictionary[key]
226-
self.traverse_dict_into_h5(dictionary[key], group)
228+
self.traverse_dict_into_h5(dictionary[key], group) #traverse subdictionary
227229
else:
228230
if key == "Histogram data" or key == "Time data":
229231
h5_output.create_dataset(key, data=dictionary[key])
230232
else:
231-
h5_output.attrs[key] = dictionary[key]
233+
h5_output.attrs[key] = dictionary[key] #if not dataset, create attribute
232234

233235
def close_application(self):
234236
choice = QtGui.QMessageBox.question(self, 'EXIT!',

PythonGUI_apps/H5_Pkl/h5_tree.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
from qtpy import QtWidgets
33
import h5py
44

5-
65
class H5TreeSearchView(DataBrowserView):
76

87
name = 'h5_tree_search'
@@ -29,6 +28,7 @@ def setup(self):
2928
self.search_lineEdit.textChanged.connect(self.on_new_search_text)
3029

3130
def on_change_data_filename(self, fname=None):
31+
""" Handle file change """
3232
self.tree_textEdit.setText("loading {}".format(fname))
3333
try:
3434
#if using h5_plot_and_view
@@ -65,7 +65,6 @@ def on_new_search_text(self, x=None):
6565
self.tree_textEdit.verticalScrollBar().setValue(old_scroll_pos)
6666

6767
def _visitfunc(self, name, node):
68-
6968
level = len(name.split('/'))
7069
indent = ' '*4*(level-1)
7170

@@ -74,7 +73,7 @@ def _visitfunc(self, name, node):
7473

7574
#search_text = self.settings['search_text'].lower()
7675
search_text = self.search_text
77-
if search_text and (search_text in localname.lower()):
76+
if search_text and (search_text in localname.lower()): #highlight terms that contain search text
7877
localname = """<span style="color: red;">{}</span>""".format(localname)
7978

8079
if isinstance(node, h5py.Group):
@@ -91,7 +90,7 @@ def _visitfunc(self, name, node):
9190
self.dataset_dict[item_name] = node
9291

9392

94-
for key, val in node.attrs.items():
93+
for key, val in node.attrs.items(): #highlight terms that contain search text
9594
if search_text:
9695
if search_text in str(key).lower():
9796
key = """<span style="color: red;">{}</span>""".format(key)

PythonGUI_apps/H5_Pkl/h5_view_and_plot.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def setup(self):
6868
self.ui.show()
6969

7070
def on_change_data_filename(self):
71-
#Handle file change
71+
""" Handle file change """
7272
try:
7373
fname = self.settings.data_filename.val
7474
if os.path.isfile(fname):
@@ -79,7 +79,7 @@ def on_change_data_filename(self):
7979
pass
8080

8181
def plot_dataset(self):
82-
#Plot data set depending on dataset shape and plot type option.
82+
""" Plot data set depending on dataset shape and plot type option. """
8383
self.plot = self.ui.data_plotWidget.getPlotItem()
8484
self.plot.clear()
8585

@@ -102,7 +102,7 @@ def plot_dataset(self):
102102
self.ui.data_imageView.setImage(data, xvals=x_values)
103103

104104
def on_data_selection(self):
105-
#Handle dataset selection
105+
""" Handle dataset selection """
106106
try:
107107
dataset_name = self.ui.dataset_listWidget.currentItem().text()
108108
self.dataset = self.h5treeview.dataset_dict[dataset_name]
@@ -120,7 +120,7 @@ def on_data_selection(self):
120120
pass
121121

122122
def update_data_widget(self):
123-
#Decide which widget to display based on dataset shape and plot type option.
123+
""" Decide which widget to display based on dataset shape and plot type option. """
124124
if self.dataset_shape == 1:
125125
self.ui.data_stackedWidget.setCurrentIndex(0)
126126
elif self.dataset_shape == 2 and self.ui.plot_radioButton.isChecked():

PythonGUI_apps/H5_Pkl/pkl_tree.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ def setup(self):
3030
self.search_lineEdit.textChanged.connect(self.on_new_search_text)
3131

3232
def on_change_data_filename(self, fname=None):
33+
""" Handle file change """
3334
self.tree_textEdit.setText("loading {}".format(fname))
3435
try:
3536
self.fname = fname
@@ -64,6 +65,13 @@ def on_new_search_text(self, x=None):
6465
self.tree_textEdit.verticalScrollBar().setValue(old_scroll_pos)
6566

6667
def traverse_dict(self, dictionary, previous_dict, level):
68+
"""
69+
Visit all values in the dictionary and its subdictionaries.
70+
71+
dictionary -- dictionary to traverse
72+
previous_dict -- dictionary one level up
73+
level -- track how far to indent
74+
"""
6775
for key in dictionary:
6876
if key not in previous_dict:
6977
level -=1

PythonGUI_apps/Lifetime_analysis/Fit_functions_with_irf.py

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@ def array_zeropad_pos(array, pad_length):
4040
#
4141
# return np.pad(array, (pad_length, 0), 'symmetric')
4242

43-
4443
def signal_and_resp_forconv(signal_array, response_array):
4544
resp_pad_negtime = array_zeropad_neg(normalize_response(response_array, t_array), len(response_array) - 1)
4645
sig_pad_negtime = array_zeropad_neg(signal_array, len(signal_array) - 1)
@@ -52,8 +51,6 @@ def signal_and_resp_forconv(signal_array, response_array):
5251

5352
return convolution[len(signal_array) - 1 : (2*len(signal_array)) - 1]
5453

55-
56-
5754
def convolution_plusnoise(signal_array, response_array, t_array, tstep, noiselevel):
5855
return convolve_sig_resp(signal_array, response_array, t_array, tstep) + noiselevel
5956

@@ -147,8 +144,6 @@ def bestfit_decay(params):
147144
# plt.legend(loc = 'best')
148145
return bestfit_params, bestfit_model, data_array, time_array, irf
149146

150-
151-
152147
def multi_exp(t, params, num_exp):
153148
exp_array = np.empty((len(t), num_exp))
154149

@@ -242,9 +237,7 @@ def bestfit_decay(params):
242237
# plt.semilogy(time_array, data_array,'b', label = 'Data')
243238
# plt.semilogy(time_array, bestfit_model, 'r', label = 'Fit')
244239
# plt.legend(loc = 'best')
245-
return bestfit_params, t_avg, bestfit_model, data_array, time_array, irf
246-
247-
240+
return bestfit_params, t_avg, bestfit_model, data_array, time_array, irf
248241

249242
def fit_multi_exp_fmin_tnc(t, tstep, data, irf, init_params, bounds, n):
250243
time_array = t
@@ -290,7 +283,6 @@ def bestfit_decay(params):
290283
# plt.legend(loc = 'best')
291284
return bestfit_params, bestfit_model, data_array, time_array, irf
292285

293-
294286
def fit_multi_exp_diffev(t, tstep, data, irf, bounds, n):
295287
time_array = t
296288
data_array = data

PythonGUI_apps/Lifetime_analysis/Lifetime_analysis_gui_layout.ui

Lines changed: 0 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -73,21 +73,6 @@
7373
<pointsize>10</pointsize>
7474
</font>
7575
</property>
76-
<item>
77-
<property name="text">
78-
<string>Stretched Exponential</string>
79-
</property>
80-
</item>
81-
<item>
82-
<property name="text">
83-
<string>Double Exponential</string>
84-
</property>
85-
</item>
86-
<item>
87-
<property name="text">
88-
<string>Single Exponential</string>
89-
</property>
90-
</item>
9176
</widget>
9277
</item>
9378
<item row="2" column="0">
@@ -112,16 +97,6 @@
11297
<pointsize>10</pointsize>
11398
</font>
11499
</property>
115-
<item>
116-
<property name="text">
117-
<string>diff_ev</string>
118-
</property>
119-
</item>
120-
<item>
121-
<property name="text">
122-
<string>fmin_tnc</string>
123-
</property>
124-
</item>
125100
</widget>
126101
</item>
127102
<item row="0" column="1">

0 commit comments

Comments
 (0)