-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmmApp.py
506 lines (399 loc) · 18.2 KB
/
mmApp.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
"""
Main PyMapManager application interface using PyQt interface library.
Instantiate mmApplicationWindow to open the main window
Example::
from PyQt4 import QtGui
from pymapmanager.interface.mmApp import mmApplicationWindow
qApp = QtGui.QApplication(sys.argv)
aw = mmApplicationWindow()
aw.show()
sys.exit(qApp.exec_())
"""
import os
import sys # to make menus on osx, sys.platform == 'darwin'
import functools
from errno import ENOENT
from PyQt5 import QtWidgets, QtGui, QtCore
from pymapmanager.mmMap import mmMap
from mmWindow import mmStackWindow, mmMapPlotWindow, mmStackPlotWindow
from pymapmanager.mmUtil import newplotdict
class mmApplicationWindow(QtWidgets.QMainWindow):
"""
Main PyMapManager applicaiton window.
This holds list widgets to display: maps, sessions, segments, and stats
"""
def __init__(self, parent=None):
#QtWidgets.QMainWindow.__init__(self)
super(mmApplicationWindow, self).__init__(parent)
self.maps = [] # List of open pymapmanager.map
self._windows = [] # list of open windows (use this to propogate selections)
# set location of the window
ag = QtWidgets.QDesktopWidget().availableGeometry()
sg = QtWidgets.QDesktopWidget().screenGeometry()
widget = self.geometry()
x = ag.width() - widget.width()
y = 2 * ag.height() - sg.height() - widget.height()
self.move(x, y)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.setWindowTitle("PyQt-MapManager")
self._lastMap = None
# build the gui
self._buildMenus()
self._buildGui()
def _buildMenus(self):
"""
if sys.platform.startswith('darwin') :
self.myMenuBar = QtGui.QMenuBar() # parentless menu bar for Mac OS
else :
self.myMenuBar = self.menuBar() # refer to the default one
self.file_menu = QtGui.QMenu('&File', self)
self.file_menu.addAction('&Quit', self.fileQuit,
QtCore.Qt.CTRL + QtCore.Qt.Key_Q)
#self.menuBar().addMenu(self.file_menu)
self.myMenuBar.addMenu(self.file_menu)
self.help_menu = QtGui.QMenu('&Help', self)
self.myMenuBar.addSeparator()
self.myMenuBar.addMenu(self.help_menu)
self.help_menu.addAction('&About', self.about)
"""
if sys.platform.startswith('darwin') :
self.myMenuBar = QtWidgets.QMenuBar()
else:
self.myMenuBar = self.menuBar() # refer to the default one
#self.myMenuBar.setNativeMenuBar(True)
self.file_menu = QtWidgets.QMenu('&File', self)
self.file_menu.addAction('&Load Map', self.loadMap)
self.file_menu.addSeparator()
self.file_menu.addAction('&Close Map', self.about)
# can't add a quit menu, it is reserved on osx
#self.file_menu.addSeparator()
#self.file_menu.addAction('&Quit', self.fileQuit) #, QtCore.Qt.CTRL + QtCore.Qt.Key_Q)
self.view_menu = QtWidgets.QMenu('&View', self)
self.view_menu.addAction('&Segments', self.about)
self.view_menu.addAction('&Annotations', self.about)
self.myMenuBar.addMenu(self.file_menu)
self.myMenuBar.addMenu(self.view_menu)
def _buildGui(self):
self.main_widget = QtWidgets.QWidget(self)
mainToolbar = self.addToolBar('myToolbar')
# loadMapAction = QtGui.QAction(QtGui.QIcon("open.bmp"), "Load", self)
# loadMapAction = QtGui.QAction("Load", self)
self.loadMapButton = QtWidgets.QPushButton("Load Map", self)
#self.loadMapButton.clicked.connect(lambda: self.toolbarButton_callback(loadMapButton))
self.loadMapButton.clicked.connect(functools.partial(self.toolbarButton_callback, 'loadMapButton'))
self.loadMapDirButton = QtWidgets.QPushButton("Load Directory", self)
#self.loadMapDirButton.clicked.connect(lambda: self.toolbarButton_callback(loadMapDirButton))
self.loadMapDirButton.clicked.connect(functools.partial(self.toolbarButton_callback, 'loadMapDirButton'))
self.defaultRoiType = QtWidgets.QComboBox(self)
self.defaultRoiType.addItems(['spineROI', 'otherROI'])
self.defaultRoiType.activated[str].connect(self.setDefaultRoiType)
mainToolbar.addWidget(self.loadMapButton)
mainToolbar.addWidget(self.loadMapDirButton)
mainToolbar.addWidget(self.defaultRoiType)
# mainToolbar.addAction(loadMapAction)
# mainToolbar.actionTriggered[QtGui.QAction].connect(self.mainToolbar_callback)
#
gridLayout1 = QtWidgets.QGridLayout()
# list of map
mapLabel = QtWidgets.QLabel("Maps")
self.mapListWidget = QtWidgets.QListWidget()
self.mapListWidget.setMaximumWidth(150)
self.mapListWidget.currentItemChanged.connect(self.map_list_changed)
self.mapListWidget.doubleClicked.connect(self.plotmap0)
# list of session
sessLabel = QtWidgets.QLabel("Sessions")
self.sessListWidget = QtWidgets.QListWidget()
self.sessListWidget.setMaximumWidth(100)
self.sessListWidget.currentItemChanged.connect(self.sess_list_changed)
# list of segment
segLabel = QtWidgets.QLabel("Segments")
self.segListWidget = QtWidgets.QListWidget()
self.segListWidget.setMaximumWidth(100)
self.segListWidget.currentItemChanged.connect(self.seg_list_changed)
gridLayout1.addWidget(mapLabel, 0, 0)
gridLayout1.addWidget(self.mapListWidget, 1, 0)
gridLayout1.addWidget(sessLabel, 0, 1)
gridLayout1.addWidget(self.sessListWidget, 1, 1)
gridLayout1.addWidget(segLabel, 0, 2)
gridLayout1.addWidget(self.segListWidget, 1, 2)
gridLayout1.setRowMinimumHeight(1, 200)
#
gridLayout2 = QtWidgets.QGridLayout()
# list of y stat
yStatLabel = QtWidgets.QLabel("Y Stat")
self.ystatListWidget = QtWidgets.QListWidget()
self.ystatListWidget.setMaximumWidth(200)
for i in range(10):
item = QtWidgets.QListWidgetItem("%i\tystat" % i)
self.ystatListWidget.addItem(item)
# self.segListWidget.currentItemChanged.connect(self.seg_list_changed)
# list of x stat
xStatLabel = QtWidgets.QLabel("X Stat")
self.xstatListWidget = QtWidgets.QListWidget()
self.xstatListWidget.setMaximumWidth(200)
for i in range(10):
item = QtWidgets.QListWidgetItem("%i\txstat" % i)
self.xstatListWidget.addItem(item)
# self.segListWidget.currentItemChanged.connect(self.seg_list_changed)
gridLayout2.addWidget(yStatLabel, 0, 0)
gridLayout2.addWidget(self.ystatListWidget, 1, 0)
gridLayout2.addWidget(xStatLabel, 0, 1)
gridLayout2.addWidget(self.xstatListWidget, 1, 1)
gridLayout2.setRowMinimumHeight(1, 200)
# main vertical layout
l = QtWidgets.QVBoxLayout(self.main_widget)
# sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100)
# dc = MyDynamicMplCanvas(self.main_widget, width=5, height=4, dpi=100)
plotStackButton = QtWidgets.QPushButton("Plot Stack Stats")
plotStackButton.clicked.connect(self.plotStackButton_callback)
plotMapButton = QtWidgets.QPushButton("Plot Map Stats")
plotMapButton.clicked.connect(self.plotMapButton_callback)
plotStackImageButton = QtWidgets.QPushButton("Plot Stack Image")
plotStackImageButton.clicked.connect(self.plotStackImageButton_callback)
l.addLayout(gridLayout1)
l.addLayout(gridLayout2)
# l.addWidget(sc)
# l.addWidget(dc)
l.addWidget(plotStackButton)
l.addWidget(plotMapButton)
l.addWidget(plotStackImageButton)
self.main_widget.setFocus()
self.setCentralWidget(self.main_widget)
self.statusBar().showMessage("All hail matplotlib!", 2000)
"""
#show a table widget
tmp_df = self.maps[0].stacks[0].stackdb
self.tableWidget = QtGui.QTableWidget(self)
self.tableWidget.setRowCount(len(tmp_df.index))
self.tableWidget.setColumnCount(len(tmp_df.columns))
self.tableWidget.setHorizontalHeaderLabels(tmp_df.columns.values)
for i in range(len(tmp_df.index)):
for j in range(len(tmp_df.columns)):
pass
#used to work
# #self.tableWidget.setItem(i, j, QtGui.QTableWidgetItem(str(tmp_df.iget_value(i, j))))
# slow?
# self.tableWidget.setItem(i, j, QtGui.QTableWidgetItem(str(tmp_df.iloc[i, j])))
l.addWidget(self.tableWidget)
"""
#
# qtpandas
'''
from qtpandas.models.DataFrameModel import DataFrameModel
from qtpandas.views.DataTableView import DataTableWidget
model = DataFrameModel()
widget = DataTableWidget()
widget.resize(800, 600)
widget.show()
widget.setViewModel(model)
model.setDataFrame(self.maps[0].stacks[0].stackdb)
'''
#
#
self.setAcceptDrops(True)
def setDefaultRoiType(self, text):
"""Respond to roiType popup/QComboBox"""
d = self.getState()
if d['map']:
d['map'].defaultRoiType = str(text)
def broadcastevent(self, event):
"""
Broadcast an event to all open application windows (self._windows) and call receiveevent(event)
TODO: implement this as signal/slot
"""
# if we don;t get a runMapRow but have a spine selection from a map then fill it in
if event.type == 'spine selection':
if not event.runMapRow >= 0:
if event.map and event.mapSession>=0 and event.stackdbIdx>=0:
runMapIdx = 6
event.runMapRow = event.map.objMap[runMapIdx,event.stackdbIdx,event.mapSession]
event.runMapRow = int(event.runMapRow)
for window in self._windows:
window.receiveevent(event)
def dragEnterEvent(self, event):
"""Changes the look of the main window when a file/folder is dragged over the window."""
print(event.mimeData())
if event.mimeData().hasFormat("text/uri-list"):
event.acceptProposedAction()
event.acceptProposedAction()
def dropEvent(self, event):
"""Handles opening a map, stack, or folder of maps/stacks when they are dropped on the main window."""
urls = event.mimeData().urls()
if urls:
filename = urls[0].toLocalFile()
if filename:
print('todo: implement drag and drop of folders, maps, and stacks, filename:', filename)
# def mainToolbar_callback(self, a):
# print('mainToolbar_callback:', a
def loadMap(self, path=None, urlmap=None):
"""Load a mmMap into application. Application keeps 'maps', a list of maps."""
if urlmap is not None:
serverurl = ''
username = 'cudmore'
elif path is None:
# ask user for file
# this is returning a tuple??? (path, file types)
aFolder = '/'
if self._lastMap is not None:
aFolder = self._lastMap
path = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File',
directory=aFolder,
filter="Text files (*.txt)")
path = path[0]
print(f'path: "{path}"')
if not path:
return
m = mmMap(filePath=path, urlmap=urlmap)
self.maps.append(m)
self.mapListWidget.clear()
for i in range(len(self.maps)):
item = QtWidgets.QListWidgetItem("%i\t%s" % (i, self.maps[i].name))
self.mapListWidget.addItem(item)
self.selectMap(0)
self._lastMap = path
def selectMap(self, idx):
"""Update the interface when user selects a different map or a new map is loaded"""
self.statList = self.maps[idx].stacks[0].stackdb.columns.values
# map
self.mapListWidget.setCurrentRow(idx)
# sess
self.sessListWidget.clear()
for i in range(self.maps[idx].numSessions):
item = QtWidgets.QListWidgetItem("%i" % i)
self.sessListWidget.addItem(item)
self.sessListWidget.setCurrentRow(0)
# seg
self.segListWidget.clear()
item = QtWidgets.QListWidgetItem('All')
self.segListWidget.addItem(item)
for i in range(self.maps[idx].numMapSegments):
item = QtWidgets.QListWidgetItem("%i" % i)
self.segListWidget.addItem(item)
self.segListWidget.setCurrentRow(0)
# ystat
self.ystatListWidget.clear()
self.xstatListWidget.clear()
# todo: prepend map type (session, date, days, hours, minutes, zdays, zhours, zminutes)
for i in range(len(self.statList)):
statStr = self.statList[i]
typeStr = 'stackdb'
spaces = ' '
if i < 10:
spaces = ' '
elif i < 100:
spaces = ' '
else:
spaces = ' '
spaces2 = ' '
if statStr.endswith('_int1'):
typeStr = 'int1'
spaces2 = ' '
elif statStr.endswith('_int2'):
typeStr = 'int2'
spaces2 = ' '
item = QtWidgets.QListWidgetItem("%i%s%s%s%s" % (i, spaces, typeStr, spaces2, statStr))
self.ystatListWidget.addItem(item)
item = QtWidgets.QListWidgetItem("%i%s%s%s%s" % (i, spaces, typeStr, spaces2, statStr))
self.xstatListWidget.addItem(item)
self.ystatListWidget.setCurrentRow(3)
self.xstatListWidget.setCurrentRow(2)
def toolbarButton_callback(self, buttonID):
print('toolbarButton_callback:', buttonID)
if buttonID == 'loadMapButton':
self.loadMap()
def map_list_changed(self, curr, prev):
# (curr,prev) are QListWidgetItem
print('ApplicationWindow.map_list_changed', curr)
print(' currentRow:', self.mapListWidget.currentRow())
print(' ', self.mapListWidget.currentItem().text())
def sess_list_changed(self, curr, prev):
# (curr,prev) are QListWidgetItem
print('ApplicationWindow.sess_list_changed', curr)
print(' currentRow:', self.sessListWidget.currentRow())
print(' ', self.sessListWidget.currentItem().text())
def seg_list_changed(self, curr, prev):
# (curr,prev) are QListWidgetItem
print('ApplicationWindow.seg_list_changed', curr)
print(' currentRow:', self.segListWidget.currentRow())
print(' ', self.segListWidget.currentItem().text())
def getState(self):
"""Capture the full state of the interface including selected: map, session, segment, ystat, xstat."""
plotDict = newplotdict()
# map
mapIdx = self.mapListWidget.currentRow()
plotDict['map'] = self.maps[mapIdx]
plotDict['mapname'] = self.mapListWidget.currentItem().text()
plotDict['mapidx'] = mapIdx # index into the list we are displaying
# session
sessIdx = self.sessListWidget.currentRow()
plotDict['sessidx'] = sessIdx
plotDict['stack'] = self.maps[mapIdx].stacks[sessIdx]
# segment
segStr = self.segListWidget.currentItem().text()
if segStr == 'All':
plotDict['segmentid'] = []
else:
plotDict['segmentid'] = [int(segStr)]
# stat
plotDict['ystat'] = self.statList[self.ystatListWidget.currentRow()]
plotDict['xstat'] = self.statList[self.xstatListWidget.currentRow()]
plotDict['roitype'] = ['spineROI']
if plotDict['map'] is not None:
#plotDict['roitype'] = [plotDict['map'].defaultRoiType]
plotDict['roitype'] = [plotDict['map'].defaultAnnotation]
return plotDict
def closechildwindow(self, windowPtr):
"""called when we close a PlotWindow"""
self._windows.remove(windowPtr)
"""
for window in self._windows:
if window == windowPtr:
self._windows.remove(windowPtr)
"""
def plotStackButton_callback(self):
print('ApplicationWindow.plotStackButton_callback()')
# todo: add to list of open windows self._windows
plotwindow = mmStackPlotWindow(self)
self._windows.append(plotwindow)
stateDict = self.getState()
plotwindow.myCanvas.plot(stateDict)
plotwindow.show()
def plotMapButton_callback(self):
print('ApplicationWindow.plotMapButton_callback()')
# todo: add to list of open windows self._windows
plotwindow = mmMapPlotWindow(self)
self._windows.append(plotwindow)
stateDict = self.getState()
#plotwindow.myCanvas.plot(stateDict)
plotwindow.myCanvas.plot2(stateDict)
plotwindow.show()
def plotmap0(self):
"""Plot a session versus pDist map. This responds to double-click of a map in the map list."""
# todo: add to list of open windows self._windows
plotwindow = mmMapPlotWindow(self)
self._windows.append(plotwindow)
stateDict = self.getState()
if stateDict['roitype'] == 'spineROI':
stateDict['segmentid'] = [0]
stateDict['ystat'] = 'pDist'
elif stateDict['roitype'] == 'otherROI':
stateDict['segmentid'] = []
stateDict['ystat'] = 'runIdx'
stateDict['xstat'] = 'mapSession'
plotwindow.myCanvas.plotMap0(stateDict)
plotwindow.show()
def plotStackImageButton_callback(self):
print('ApplicationWindow.plotStackImageButton_callback()')
# todo: add to list of open windows self._windows
stateDict = self.getState()
plotwindow = mmStackWindow(stateDict=stateDict, parent=self)
self._windows.append(plotwindow)
stateDict = self.getState()
plotwindow.myCanvas.plot(stateDict)
plotwindow.show()
def fileQuit(self):
self.close()
def closeEvent(self, ce):
self.fileQuit()
def about(self):
QtWidgets.QMessageBox.about(self, "About", """Made by Robert H Cudmore.""")