-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgui.py
550 lines (425 loc) · 21.3 KB
/
gui.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'draft.ui'
#
# Created by: PyQt5 UI code generator 5.15.1
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtWidgets import QFileDialog, QTextEdit, QSizePolicy
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import pyqtgraph as pg
from pyqtgraph import PlotWidget
# from ..dev.receptive_fields import get_rfs
# from ..dev.utils import load_data
from .utils import get_rfs
from .utils import load_neural_data, process_neural_data, process_stim_data
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import cm
import pickle
import numpy as np
from scipy.io import loadmat
import sys
import signal
class Ui_MainWindow(object):
def __init__(self):
self.spks = None
self.lastClicked = []
self.varexp = None
self.currentPoint = []
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1792, 1098)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)
brush = QtGui.QBrush(QtGui.QColor(127, 127, 127))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)
MainWindow.setPalette(palette)
font = QtGui.QFont()
font.setFamily("Arial")
MainWindow.setFont(font)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
font = QtGui.QFont()
font.setPointSize(18)
self.buttonRun = QtWidgets.QPushButton(self.centralwidget)
self.buttonRun.setGeometry(QtCore.QRect(300, 850, 81, 41))
self.buttonRun.setObjectName("buttonRun")
self.loadReceptiveFieldsHeader = QtWidgets.QLabel(self.centralwidget)
self.loadReceptiveFieldsHeader.setFont(font)
self.loadReceptiveFieldsHeader.setGeometry(QtCore.QRect(300, 900, 201, 41))
self.loadReceptiveFieldsHeader.setObjectName("loadReceptiveFieldsHeader")
self.buttonLoad = QtWidgets.QPushButton(self.centralwidget)
self.buttonLoad.setGeometry(QtCore.QRect(300, 1000, 81, 41))
self.buttonLoad.setObjectName("buttonLoad")
self.comboboxRF = QtWidgets.QComboBox(self.centralwidget)
self.comboboxRF.setGeometry(QtCore.QRect(300, 810, 181, 41))
self.comboboxRF.setObjectName("comboboxRF")
self.comboboxRF.addItem("")
self.comboboxRF.addItem("")
self.comboboxRF.addItem("")
# self.displayRFs = pg.PlotWidget(self.centralwidget)
self.displayRFs = pg.GraphicsLayoutWidget(self.centralwidget)
self.displayRFs.setGeometry(QtCore.QRect(10, 20, 1071, 711))
self.displayRFs.setObjectName("displayRFs")
self.chooseNeuralDataButton = QtWidgets.QPushButton(self.centralwidget)
self.chooseNeuralDataButton.setGeometry(QtCore.QRect(20, 810, 181, 31))
self.chooseNeuralDataButton.setObjectName("chooseNeuralDataButton")
self.runReceptiveFieldsHeader = QtWidgets.QLabel(self.centralwidget)
self.runReceptiveFieldsHeader.setGeometry(QtCore.QRect(300, 770, 171, 41))
self.runReceptiveFieldsHeader.setFont(font)
self.runReceptiveFieldsHeader.setObjectName("runReceptiveFieldsHeader")
self.chooseRFDataButton = QtWidgets.QPushButton(self.centralwidget)
self.chooseRFDataButton.setGeometry(QtCore.QRect(300, 940, 181, 31))
self.chooseRFDataButton.setObjectName("chooseRFDataButton")
self.rf_data_file = QtWidgets.QLabel(self.centralwidget)
self.rf_data_file.setGeometry(QtCore.QRect(310, 970, 141, 21))
self.rf_data_file.setObjectName("rf_data_file")
self.chooseFileHeader = QtWidgets.QLabel(self.centralwidget)
self.chooseFileHeader.setGeometry(QtCore.QRect(30, 770, 171, 41))
self.chooseFileHeader.setFont(font)
self.chooseFileHeader.setObjectName("chooseFileHeader")
self.neural_data_file = QtWidgets.QLabel(self.centralwidget)
self.neural_data_file.setGeometry(QtCore.QRect(30, 840, 121, 21))
self.neural_data_file.setObjectName("neural_data_file")
self.load_neural_data_button = QtWidgets.QPushButton(self.centralwidget)
self.load_neural_data_button.setGeometry(QtCore.QRect(20, 870, 81, 41))
self.load_neural_data_button.setObjectName("load_neural_data_button")
self.load_stim_data_button = QtWidgets.QPushButton(self.centralwidget)
self.load_stim_data_button.setGeometry(QtCore.QRect(20, 1000, 81, 41))
self.load_stim_data_button.setObjectName("load_stim_data_button")
self.downsample_checkbox = QtWidgets.QLabel(self.centralwidget)
self.downsample_checkbox.setGeometry(QtCore.QRect(30, 980, 111, 21))
self.downsample_checkbox.setObjectName("downsample_checkbox")
# self.downsample_checkbox.setChecked(False)
self.height_input = QtWidgets.QLineEdit(self.centralwidget)
self.height_input.setGeometry(QtCore.QRect(140, 980, 41, 21))
self.height_input.setObjectName("height_input")
self.height_input.setStyleSheet('''
QLineEdit {
background-color: rgb(255, 255, 255);
}
''')
self.height_input.setText('18')
self.width_input = QtWidgets.QLineEdit(self.centralwidget)
self.width_input.setGeometry(QtCore.QRect(190, 980, 41, 21))
self.width_input.setObjectName("width_input")
self.width_input.setStyleSheet('''
QLineEdit {
background-color: rgb(255, 255, 255);
}
''')
self.width_input.setText('48')
self.H_label = QtWidgets.QLabel(self.centralwidget)
self.H_label.setGeometry(QtCore.QRect(150, 961, 16, 16))
self.H_label.setObjectName("H_label")
self.W_label = QtWidgets.QLabel(self.centralwidget)
self.W_label.setGeometry(QtCore.QRect(200, 961, 16, 16))
self.W_label.setObjectName("W_label")
self.chooseStimuliDataButton = QtWidgets.QPushButton(self.centralwidget)
self.chooseStimuliDataButton.setGeometry(QtCore.QRect(20, 920, 181, 31))
self.chooseStimuliDataButton.setObjectName("chooseStimuliDataButton")
self.stimuli_data_file = QtWidgets.QLabel(self.centralwidget)
self.stimuli_data_file.setGeometry(QtCore.QRect(30, 950, 121, 21))
self.stimuli_data_file.setObjectName("stimuli_data_file")
# Retinotopy
self.retinotopy = pg.PlotWidget(self.centralwidget)
self.retinotopy.setGeometry(QtCore.QRect(1090, 20, 611, 701))
self.retinotopy.setObjectName("retinotopy")
# Go to neuron
self.gotoNeuronForm = QtWidgets.QLineEdit(self.centralwidget)
self.gotoNeuronForm.returnPressed.connect(self.gotoNeuron)
self.gotoNeuronForm.setGeometry(QtCore.QRect(1580, 740, 113, 21))
self.gotoNeuronForm.setObjectName("gotoNeuronForm")
self.gotoNeuronForm.setStyleSheet('''
QLineEdit {
background-color: rgb(255, 255, 255);
}
''')
self.gotoNeuronLabel = QtWidgets.QLabel(self.centralwidget)
self.gotoNeuronLabel.setGeometry(QtCore.QRect(1490, 740, 91, 21))
self.gotoNeuronLabel.setObjectName("gotoNeuronLabel")
# Stimuli
self.stimuliPreview = pg.GraphicsLayoutWidget(self.centralwidget)
self.stimuliPreview.setGeometry(QtCore.QRect(560, 820, 1151, 221))
self.stimuliPreview.setObjectName("stimuliPreview")
self.stimuliPreviewHeader = QtWidgets.QLabel(self.centralwidget)
self.stimuliPreviewHeader.setFont(font)
self.stimuliPreviewHeader.setGeometry(QtCore.QRect(560, 768, 171, 41))
self.stimuliPreviewHeader.setObjectName("stimuliPreviewHeader")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1792, 22))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.menubar.addAction(self.menuFile.menuAction())
self.neuron_filename = QtWidgets.QLabel(self.centralwidget)
self.neuron_filename.setGeometry(QtCore.QRect(30, 180, 121, 21))
self.neuron_filename.setObjectName("label_filename")
# Make clickable
self.chooseNeuralDataButton.clicked.connect(lambda: self.get_neural_path())
self.chooseStimuliDataButton.clicked.connect(lambda: self.get_stim_path())
self.load_neural_data_button.clicked.connect(lambda: self.get_file("neural"))
self.load_stim_data_button.clicked.connect(lambda: self.get_file("stimuli"))
self.chooseRFDataButton.clicked.connect(lambda: self.get_file("RF"))
self.buttonRun.clicked.connect(self.run_rf)
self.buttonLoad.clicked.connect(self.load_preprocessed_rfs)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Approxineuro - RF Fitting"))
self.buttonRun.setText(_translate("MainWindow", "Run"))
self.buttonLoad.setText(_translate("MainWindow", "Load"))
self.gotoNeuronForm.setText(_translate("MainWindow", ""))
self.rf_data_file.setText(_translate("MainWindow", "Upload a file [optional]"))
self.comboboxRF.setItemText(0, _translate("MainWindow", "Linear Regression"))
self.comboboxRF.setItemText(1, _translate("MainWindow", "Reduced Rank Regression"))
self.chooseNeuralDataButton.setText(_translate("MainWindow", "Select Neural Data File"))
self.runReceptiveFieldsHeader.setText(_translate("MainWindow", "Run Receptive Fields"))
self.loadReceptiveFieldsHeader.setText(_translate("MainWindow", "Load Receptive Fields"))
self.chooseFileHeader.setText(_translate("MainWindow", "Choose Files"))
self.neural_data_file.setText(_translate("MainWindow", "Upload a file"))
self.load_neural_data_button.setText(_translate("MainWindow", "Load"))
self.load_stim_data_button.setText(_translate("MainWindow", "Load"))
self.downsample_checkbox.setText(_translate("MainWindow", "Downsample:"))
self.H_label.setText(_translate("MainWindow", "H"))
self.W_label.setText(_translate("MainWindow", "W"))
self.chooseStimuliDataButton.setText(_translate("MainWindow", "Select Stimulus Data File"))
self.chooseRFDataButton.setText(_translate("MainWindow", "Select RF Data File"))
self.stimuli_data_file.setText(_translate("MainWindow", "Upload a file"))
self.gotoNeuronLabel.setText(_translate("MainWindow", "Go to neuron"))
self.stimuliPreviewHeader.setText(_translate("MainWindow", "Preview Stimuli"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
def get_neural_path(self):
"""
Open file dialog box to get path to neural data.
Neural data should be in specified format (see README.md)
"""
self.neural_path, _ = QFileDialog.getOpenFileName()
url = QUrl.fromLocalFile(self.neural_path)
if url.fileName() == "":
pass
else:
self.neural_data_file.setText(str(url.fileName()))
self.neural_data_file.adjustSize()
self.neural_data_file.repaint()
def get_stim_path(self):
"""
Open file dialog box to get stimuli data.
Stimuli data should be in specified format (see README.md)
"""
self.stim_path, _ = QFileDialog.getOpenFileName()
url = QUrl.fromLocalFile(self.stim_path)
if url.fileName() == "":
pass
else:
self.stimuli_data_file.setText(str(url.fileName()))
self.stimuli_data_file.adjustSize()
self.stimuli_data_file.repaint()
def get_file(self, file_type, process=True):
'''
Get file.
file_type (string): "neural", "stimuli", or "RF"
process (boolean): True - process;
'''
if file_type == "neural":
print("Loading neural data...")
if not hasattr(self, 'neural_path'):
error = QtWidgets.QErrorMessage()
error.showMessage("Please select a stimuli data file first.")
# Process data
if process:
self.spks, self.istim, self.xpos, self.ypos = process_neural_data(self.neural_path)
else:
self.spks, self.istim, self.xpos, self.ypos = load_neural_data(self.neural_path)
# Retinotopy
self.graph_retinotopy()
elif file_type == "stimuli":
print("Loading stimuli data...")
# Error reporting
if not hasattr(self, 'stim_path'):
error = QtWidgets.QErrorMessage()
error.showMessage("Please load a neural data and stimuli data file first.")
if not hasattr(self, 'istim'):
error = QtWidgets.QErrorMessage()
error.showMessage("Please load neural data file that contains istim before loading stimuli data")
# Load stimulus data
self.Lyd, self.Lxd = int(self.height_input.text()), int(self.width_input.text())
self.Z = process_stim_data(self.stim_path, self.istim, Lyd=self.Lyd, Lxd=self.Lxd)
# Display stimuli
self.display_stimuli(self.Z)
elif file_type == "RF":
self.rf_path, _ = QFileDialog.getOpenFileName()
url = QUrl.fromLocalFile(self.rf_path)
self.rf_data_file.setText(str(url.fileName()))
self.rf_data_file.adjustSize()
self.rf_data_file.repaint()
def load_preprocessed_rfs(self, file_path):
"""
Load preprocessed RF data in matrix form of h x w x number of RFs
file_path (str): Path to receptive field dictionary. Dictionary has keys B0 containing
receptive field matrix and Spred containing predicted spikes.
"""
print("Loading RF data...")
dat = pickle.load(open(file_path, 'rb'))
self.B0, self.Spred = dat['B0'], dat['Spred']
del dat
print("RF data loaded!")
self.graph_RFs(Spred_run=True)
def display_stimuli(self, Z):
self.stimuliPreview.clear()
n = 18
row = 6
for i in range(n):
if i % row == 0:
self.stimuliPreview.nextRow()
img_data = Z[i].reshape(self.Lyd,self.Lxd)
img = pg.ImageItem(img_data.T)
vb = self.stimuliPreview.addPlot()
vb.setAspectLocked()
vb.invertY()
vb.addItem(img)
vb.hideAxis("bottom")
vb.hideAxis("left")
def graph_RFs(self, index=None, Spred_run=False, n = 36):
"""
Graph receptive fields.
Args:
index (list): Order of RFs.
Spred_run (bool): Graph RFs based on variance explained of predicted spikes.
n (int): Number of RFs to graph.
"""
print("Graphing receptive fields.")
# Clear old graph
self.displayRFs.clear()
# Get variances
if Spred_run:
self.varexp = 1.0 - (self.Spred**2).mean(axis=-1)
index = np.argsort(self.varexp)[::-1]
n = np.minimum(n, len(index))
row = int(np.sqrt(n))
for i in range(n):
if i % row == 0:
self.displayRFs.nextRow()
img_data = self.B0[:,:,index[i]]
img = pg.ImageItem(img_data.T)
vb = self.displayRFs.addPlot(title="idx =" + str(index[i]))
vb.setAspectLocked()
vb.invertY()
vb.addItem(img)
vb.hideAxis("bottom")
vb.hideAxis("left")
def update_ROI(self,imga, imgb, roi):
imgb.setImage(roi.getArrayRegion(arr, imga), levels=(0, arr.max()))
def graph_retinotopy(self):
print("Graphing retinotopy...")
self.retinotopy.clear()
global scatter
scatter = pg.ScatterPlotItem(symbol='o', size=3, pen=None, brush='r')
scatter.setZValue(0)
# inconspiciously make dots bigger to be selected more easily
scatter_shadow = pg.ScatterPlotItem(symbol='o', pen=None, size=30, brush=None)
scatter_shadow.setZValue(1)
self.retinotopy.addItem(scatter)
self.retinotopy.addItem(scatter_shadow)
pos = [{'pos': (self.xpos[n], -self.ypos[n])} for n in range(len(self.xpos))]
scatter.setData(pos)
scatter_shadow.setData(pos)
scatter_shadow.sigClicked.connect(self.pointsClicked)
print("Retintopy graphed!")
def pointsClicked(self, plot, points):
modifiers = QtGui.QApplication.keyboardModifiers()
if (modifiers & QtCore.Qt.ControlModifier):
pass
else:
print("Control key not pressed")
for p in self.lastClicked:
p.resetPen()
for p in points:
p.setPen(width=.5, color='w')
if (modifiers & QtCore.Qt.ControlModifier):
self.lastClicked.extend(points)
print("Control key pressed.")
else:
self.lastClicked = points
# Get index to display RFs
data_list = plot.data.tolist()
# find faster way to do this
all_points = [tup for tup in data_list for pt in points if pt in tup]
mypoint_index = [data_list.index(pt) for pt in all_points]
self.graph_RFs(index=mypoint_index)
def gotoNeuron(self):
neuron_index = int(self.gotoNeuronForm.text())
print("Going to neuron ", neuron_index)
self.highlightPoint(neuron_index)
self.graph_RFs(index=[neuron_index])
def highlightPoint(self, index):
# reset previous point
for p in self.lastClicked:
p.resetPen()
# color new point
highlighted_pt = scatter.pointsAt(QPoint(self.xpos[index], -self.ypos[index]))[0]
highlighted_pt.setPen('w', width=50)
self.lastClicked = [highlighted_pt]
def run_rf(self):
# error messages
if not hasattr(self, 'Z') or not hasattr(self, 'spks'):
error = QtWidgets.QErrorMessage()
error.showMessage("Please load a neural data and stimuli data file first.")
fit_type = self.comboboxRF.currentText()
if fit_type == "Linear Regression":
print("Running linear regression")
self.B0, self.Spred = get_rfs(self.Z, self.spks, (self.Lyd, self.Lxd), regression_type="linear")
print("Linear regression has been run.")
elif fit_type == "Reduced Rank Regression":
print("Running reduced rank regression")
self.B0, self.Spred = get_rfs(self.Z, self.spks, (self.Lyd, self.Lxd), regression_type="reduced_rank")
print("Reduced rank regression has been run.")
self.graph_RFs(Spred_run=True)
def run():
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()