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 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
|
'''
Plugable pyqtgraph mcplot frontend.
'''
import os
import sys
import math
import subprocess
import numpy as np
import qtpy
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui, QtWidgets
from . import utils
from . import mccode_config
from .mcplotloader import McCodeDataLoader, test_decfuncs, PlotGraphPrint
from .plotgraph import PNSingle, PNMultiple
from .mcplotloader import Data2D
def get_help_string():
if sys.platform == 'darwin':
modifier = 'Meta'
elif sys.platform == 'win32':
modifier = 'alt'
else:
modifier = 'ctrl'
helplines = []
helplines.append('')
helplines.append('q - quit')
helplines.append('p - save png')
if not os.name == 'nt':
helplines.append('s - save svg')
helplines.append('l - log toggle')
helplines.append('t - textinfo toggle')
helplines.append('c - cycle colormap')
helplines.append('F1/h - help')
helplines.append('F5 - replot')
helplines.append('click - display subplot')
helplines.append('right-click/b - back')
helplines.append('%s + click - sweep monitors' % modifier)
helplines.append('x - expand subplots')
return '\n'.join(helplines)
class ViewModel():
'''
It is a kind of viewmodel, originally a log logstate housekeeping object,
extended by various other logstate variables as well.
'''
def __init__(self, log=False, legend=True, sourcedir=None):
self.log = log
self.icolormap = 0
self.legend = legend
self.sourcedir = sourcedir
def flip_log(self):
self.log = not self.log
return self.log
def inc_colormap(self):
self.icolormap += 1
def flip_legend(self):
self.legend = not self.legend
return self.legend
def logstate(self):
return self.log
def legendstate(self):
return self.legend
def cmapindex(self):
return self.icolormap
def get_sourcedir(self):
return self.sourcedir
class McPyqtgraphPlotter():
'''
PyQtGraph-based plotter class.
'''
def __init__(self, plotgraph, sourcedir, plot_func, invcanvas):
'''
plotgraph: plotgraph root node
sourcedir: data files source directory
plot_funct: the user-specified matching user data.
Signature:
node - plotgraph node
i - int
plt - pqtg plot object
opts - (dict, see code)))
returns:
view_box - the click-able view box of the constructed plot object
plt - the plot object to be added to the pqtg window
inv_canvas: inverts background from black to white
'''
self.graph = plotgraph
self.sourcedir = sourcedir
self.plot_func = plot_func
self.isQt6 = None
# Qt app
self.app = QtWidgets.QApplication(sys.argv)
# start
if hasattr(self.app, "exec_"):
try:
import PySide6
self.isQt6 = False
except:
self.isQt6 = False
else:
self.isQt6 = False
if invcanvas:
# switch to using white background and black foreground
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
def runplot(self):
node = self.graph
self.create_plotwindow(title=self.sourcedir)
# create the logflipper
self.viewmodel = ViewModel(sourcedir=self.sourcedir)
# initiate event driven plot recursion
self.plot_node(node)
self.update_statusbar(None, node, None)
# start
if (not self.isQt6):
sys.exit(self.app.exec_()) # Qt5
else:
sys.exit(self.app.exec()) # Qt6
def create_plotwindow(self, title):
''' set up and return a plotlayout "window" '''
helpmessage = QtWidgets.QLabel()
helpmessage.setText("Press 'h' for app shortcuts.")
self.statusmessage = QtWidgets.QLabel()
statusbar = QtWidgets.QStatusBar()
statusbar.addWidget(helpmessage)
statusbar.addPermanentWidget(self.statusmessage)
self.main_window = QtWidgets.QMainWindow()
self.graphics_view = pg.GraphicsView(self.main_window)
self.main_window.setCentralWidget(self.graphics_view)
self.main_window.setStatusBar(statusbar)
self.main_window.setWindowTitle(title)
self.main_window.setMouseTracking(True)
# window size
if hasattr(QtWidgets.QApplication,"primaryScreen"): # Qt6 and late Qt5
rect = QtWidgets.QApplication.primaryScreen().size()
else: # earlier Qt5
rect = QtWidgets.QApplication.desktop().screenGeometry()
#
w = int(0.7 * rect.width())
h = int(0.7 * rect.height())
self.main_window.resize(w, h)
self.plot_layout = pg.GraphicsLayout(border=None)
self.graphics_view.setCentralItem(self.plot_layout)
self.plot_layout.setContentsMargins(2, 2, 2, 2) # outermost margin
self.main_window.show()
self.main_window.raise_()
self.main_window.activateWindow()
def plot_node(self, node, sync_zoom_obj_ids=[]):
'''
Event driven recursive plot function. Click events are registered with each recursion.
'''
# First check if we have been called with a meaningful node
if node == None:
return
def get_modifiers(modname):
''' Get int codes for keyboardmodifiers. WARNING: String codes may be used directly in code. '''
if (self.isQt6): # Qt6
k = QtCore.Qt.KeyboardModifier
else: # Qt5
k = QtCore.Qt
if modname == "none":
return 0
if modname == "ctrl":
return k.ControlModifier
if modname == "shft":
return k.ShiftModifier
if modname == "ctrl-shft":
return k.ControlModifier | k.ShiftModifier
if modname == "alt":
return k.AltModifier
# init
self.clear_window_and_handlers()
# get references from node
parent = node.parent
prim_lst = node.primaries
sec_lst = node.secondaries
# add plot instances and record viewbox results
n = node.getnumdata()
self.viewbox_list = []
self.plot_list = []
for i in range(n):
viewbox, plt = self.add_plot(node, i, n)
self.viewbox_list.append(viewbox)
self.plot_list.append(plt)
if id(node) in sync_zoom_obj_ids:
self.sync_views_zooming()
# set up viewbox - node correspondences for each action (click, right-click, ctrl-click, ...)
node_list_click = []
node_list_rclick = []
node_list_ctrlclick = []
# tag sync-zoom node id's (secondaries)
sync_zoom_obj_ids = sync_zoom_obj_ids + [id(n) for n in sec_lst]
# for each primary node, a click is registered to it
node_list_click = prim_lst
# if parent exists, all right-clicks are registered to it
if parent:
for i in range(n):
node_list_rclick.append(parent)
# for each secondary node, a ctrl-click is registered to it
node_list_ctrlclick = sec_lst
# set mouse click handlers on the window
plot_node_cb = lambda node: self.plot_node(
node, sync_zoom_obj_ids=sync_zoom_obj_ids)
self.set_handler(node_list_click, plot_node_cb, "click", get_modifiers("none"))
self.set_handler(node_list_rclick, plot_node_cb, "rclick", get_modifiers("none"))
# set modifiers "alt" and "ctrl" for all platforms, since some may not work on win, darwin etc.
self.set_handler(node_list_ctrlclick, plot_node_cb, "click", get_modifiers("alt"))
self.set_handler(node_list_ctrlclick, plot_node_cb, "click", get_modifiers("ctrl"))
# set keypress handlers
replot_cb = lambda: self.plot_node(node)
back_cb = lambda: self.plot_node(parent)
self.set_keyhandler(replot_cb, back_cb, 'l', get_modifiers("none"))
def show_help(self):
if mccode_config.configuration["MCCODE"] == "mcstas":
prefix = "mc"
else:
prefix = "mx"
QtWidgets.QMessageBox.about(self.main_window, prefix+'plot-pyqtgraph', get_help_string())
def set_keyhandler(self, replot_cb, back_cb, key, modifier):
''' sets a clickhadler according to input '''
def key_handler(ev, replot_cb, back_cb, savefile_cb, flip_log, flip_legend, inc_cmap, expand_sp, debug=False):
''' global keypress handler, replot_cb is a function of log '''
if hasattr(QtCore.Qt, "Key"):
k = QtCore.Qt.Key
else:
k = QtCore.Qt
if ev.key() == k.Key_Q: # q
QtWidgets.QApplication.quit()
elif ev.key() == k.Key_L: # l
flip_log()
replot_cb()
elif ev.key() == k.Key_P: # p
savefile_cb(format='png')
elif ev.key() == 83: # s
if not os.name == 'nt':
savefile_cb(format='svg')
elif ev.key() == k.Key_T: # t
print("Toggle legend visibility")
flip_legend()
replot_cb()
elif ev.key() == k.Key_C: # c
inc_cmap()
replot_cb()
elif ev.key() == k.Key_F5: # F5
replot_cb()
elif ev.key() == k.Key_X: # x
expand_sp()
elif ev.key() == k.Key_F1 or ev.key() == k.Key_H: # F1 or h
self.show_help()
elif ev.key() == k.Key_B: # b
back_cb()
# print debug info
if debug:
print("key code: %s" % str(ev.key()))
savefile_cb = lambda format: utils.dumpfile_pqtg(scene=self.plot_layout.scene(), format=format)
expand_sp = lambda : self.expand_subplots(sourcedir=self.viewmodel.get_sourcedir())
self.plot_layout.scene().keyPressEvent = \
lambda ev: key_handler(ev = ev,
replot_cb = replot_cb,
savefile_cb = savefile_cb,
back_cb = back_cb,
flip_log = self.viewmodel.flip_log,
flip_legend = self.viewmodel.flip_legend,
inc_cmap = self.viewmodel.inc_colormap,
expand_sp = expand_sp)
def expand_subplots(self, sourcedir):
''' opens a new process of mcplot-pyqtgraph on each subdir '''
# stolen from stack overflow:
def get_immediate_subdirectories(a_dir):
return [name for name in os.listdir(a_dir)
if os.path.isdir(os.path.join(a_dir, name))]
def sortalpha(data):
return sorted(data, key =
lambda item: (
int(item.partition(' ')[0])
if item[0].isdigit() else float('inf'), item))
subdirs = sortalpha(get_immediate_subdirectories(sourcedir))
if len(subdirs) == 0:
print("no subdirs to plot")
return
for s in subdirs:
if mccode_config.configuration["MCCODE"] == "mcstas":
prefix = "mc"
else:
prefix = "mx"
subprocess.Popen(prefix+'plot-pyqtgraph %s' %
os.path.join(sourcedir, s), shell=True, cwd=os.getcwd())
def clear_window_and_handlers(self):
''' clears all click handlers on "rootui" '''
self.plot_layout.clear()
try:
self.plot_layout.scene().sigMouseClicked.disconnect()
self.plot_layout.scene().sigMouseMoved.disconnect()
except TypeError:
pass
def set_handler(self, node_list, node_cb, click, modifier):
''' sets a clickhandler according to input '''
def click_handler(event, node_list, node_cb, click, mod, debug=False):
''' generic conditional-branch-tree, catch-all, mouse click event handler '''
posItem = None
posScene = None
plotIdx = -1
try:
posItem = event.pos()
posScene = event.scenePos()
plotIdx = self.get_plot_index(posScene)
except AttributeError:
pass
# print debug info
if debug:
print("click modifier: %s" % str(event.modifiers()))
# prevent action for modifiers mismatch
if (self.isQt6 and hasattr(QtCore.Qt,"KeyboardModifier")): # Qt6
if not isinstance(mod, int):
if event.modifiers() != mod: # Qt5: int(event.modifiers()) != mod fails in Qt6
return
# prevent action for mouse button mismatch
if click == "rclick" and (str(event.button()) != 'MouseButton.RightButton'):
return
if click == "click" and (str(event.button()) != 'MouseButton.LeftButton'):
return
else: # Qt5
if int(event.modifiers()) != mod:
return
# prevent action for mouse button mismatch
if click == "rclick" and event.button() != 2:
return
if click == "click" and event.button() != 1:
return
if plotIdx >= 0 and plotIdx < len(node_list):
node = node_list[plotIdx]
# replot
node_cb(node)
# update status message
self.update_statusbar(None, node, posItem)
if len(list(node_list)) == 0:
return
self.plot_layout.scene().sigMouseClicked.connect(
lambda event: click_handler(
event, node_list=node_list, node_cb=node_cb, click=click, mod=modifier))
def get_plot_func_opts(self, log, legend, icolormap, verbose, fontsize, cbmin=None, cbmax=None):
''' returns a dict for holding the plot options relevant for this plotting frontend '''
d = {}
d['log'] = log
d['legend'] = legend
d['icolormap'] = icolormap
d['verbose'] = verbose
d['fontsize'] = fontsize
if cbmin != None and cbmax != None:
d['cbmin'] = cbmin
d['cbmax'] = cbmax
return d
def get_sweep_multiplot_colorbar_limits(self, node):
if type(node) == PNMultiple:
cbmin = float("inf")
cbmax = float("-inf")
monname = None
for data in node.getdata_lst():
if type(data) != Data2D:
continue
# make sure all nodes in the multiplot have the same component name
# (indicating comparable (sweep) data)
if monname == None:
monname = data.component
else:
if data.component != monname:
return None, None
# update min/max values
if type(data) == Data2D:
localmin = np.min(np.array(data.zvals))
localmax = np.max(np.array(data.zvals))
cbmin = min(cbmin, localmin)
cbmax = max(cbmax, localmax)
return cbmin, cbmax
return None, None
def add_plot(self, node, i, n):
''' constructs a plot from data and adds this to layout '''
def get_golden_rowlen(n):
''' find rowlength by golden ratio '''
return int(math.sqrt(n*1.61803398875))
plt = pg.PlotItem()
rowlen = get_golden_rowlen(n)
verbose = n<=4
fontsize = (4, 10, 14)[int(n<=2) + int(n<12)]
if self.viewmodel.logstate():
cbmin = cbmax = None
else:
cbmin, cbmax = self.get_sweep_multiplot_colorbar_limits(node)
options = self.get_plot_func_opts(
self.viewmodel.logstate(), self.viewmodel.legendstate(), self.viewmodel.cmapindex(),
verbose, fontsize, cbmin, cbmax)
view_box, plt_itm = self.plot_func(node, i, plt, options)
if view_box:
self.plot_layout.addItem(plt_itm, i // rowlen, i % rowlen)
# disconnect any old mouse handlers
try:
self.plot_layout.scene().sigMouseMoved.disconnect()
except TypeError:
pass
mouse_func = lambda pos: self.update_statusbar(plt, node, pos)
self.plot_layout.scene().sigMouseMoved.connect(mouse_func)
return view_box, plt
def update_statusbar(self, plot, node, pos):
# if a single plot is visible, show the coordinates
if isinstance(node, PNSingle):
if plot == None and len(self.plot_list) == 1:
plot = self.plot_list[0]
self.single_plot_mouse_moved(plot, node, pos)
# else show infos about the plots
elif isinstance(node, PNMultiple):
self.multi_plot_mouse_moved(node, pos)
def single_plot_mouse_moved(self, plot, node, pos):
''' shows the mouse coordinates for single plots '''
if plot!=None and pos!=None:
pos = plot.getViewBox().mapSceneToView(pos)
# get axis labels
xlabel = ""
ylabel = ""
if node != None:
xlabel = node.getdata_idx(0).xlabel
ylabel = node.getdata_idx(0).ylabel
if xlabel == "":
xlabel = "x"
if ylabel == "":
ylabel = "y"
if pos != None:
x = pos.x()
y = pos.y()
logstr = ""
if self.viewmodel.log:
# TODO: do this for non-colourplots:
#y = np.power(10., y)
logstr = " (log)"
posstr = "%.24s=%g, %.24s=%g%s." % (xlabel, x, ylabel, y, logstr)
else:
posstr = ""
self.statusmessage.setText(posstr)
def multi_plot_mouse_moved(self, node, pos):
''' shows information on multi-plots '''
prim = node.primaries
num_plots = node.getnumdata()
statustext = ""
# find the plot under the cursor
idx = self.get_plot_index(pos)
if idx >= 0:
# plot found?
statustext = "Plot %d/%d" % (idx+1, num_plots)
if prim != None:
title = prim[idx].getdata_idx(0).title
# truncate the tile string if it's too long
if len(title) > 64:
title = title[0:64] + "..."
statustext += ": " + title
statustext += "."
else:
if num_plots == 1:
statustext = "Showing 1 plot."
else:
statustext = "Showing %d plots." % num_plots
if self.viewmodel.log:
statustext = "Mode: log. " + statustext
else:
statustext = "Mode: lin. " + statustext
self.statusmessage.setText(statustext)
def get_plot_index(self, pos):
''' get the plot index at (cursor) position pos '''
if self.viewbox_list == None or pos == None:
return -1
for idx in range(len(self.viewbox_list)):
viewbox = self.viewbox_list[idx]
topRight = viewbox.mapViewToScene(viewbox.viewRect().topRight())
bottomLeft = viewbox.mapViewToScene(viewbox.viewRect().bottomLeft())
rect = QtCore.QRectF()
rect.setTopRight(topRight)
rect.setBottomLeft(bottomLeft)
# plot found?
if rect.contains(pos):
return idx
# plot not found
return -1
def sync_views_zooming(self):
''' replace individual viewbox wheel events with a new, global wheel event which calls all of them '''
org_wheel_events = [vb.wheelEvent for vb in self.viewbox_list]
def modded_wheel_event(ev, axis = None):
for vb in self.viewbox_list:
org_wheel_events[self.viewbox_list.index(vb)](ev, axis=axis)
for vb in self.viewbox_list:
vb.wheelEvent = modded_wheel_event
|