Commit d52a5c31 authored by Damien Naudet's avatar Damien Naudet
Browse files

FitView refactoring.

Delayed display of plots.
parent a1ddd730
......@@ -33,308 +33,23 @@ __date__ = "15/09/2016"
import numpy as np
from silx.gui import qt as Qt
from silx.gui.plot import PlotWindow, PlotWidget
from matplotlib import cm
from kmap.gui.model.Model import Model, RootNode
from kmap.gui.project.Hdf5Nodes import H5File
from kmap.gui.model.ModelDef import ModelRoles, ModelColumns
from kmap.gui.project.XsocsH5Factory import h5NodeToProjectItem
from kmap.gui.widgets.Containers import GroupBox
from kmap.io.FitH5 import FitH5
from ...widgets.XsocsPlot2D import XsocsPlot2D
from ..widgets.XsocsPlot2D import XsocsPlot2D
from kmap.gui.model.TreeView import TreeView
from kmap.gui.model.NodeEditor import EditorMixin
from kmap.gui.project.Hdf5Nodes import H5Base, H5NodeClassDef
@H5NodeClassDef('FitH5')
class FitH5Node(H5File):
# TODO : check the file format (make sure that all required
# groups/datasets are there)
def _loadChildren(self):
base = self.h5Path.rstrip('/')
children = []
with FitH5(self.h5File, mode='r') as h5f:
entries = h5f.entries()
for entry in entries:
child = FitEntryNode(self.h5File, base + '/' + entry)
children.append(child)
return children
@H5NodeClassDef('FitEntry')
class FitEntryNode(H5Base):
entry = property(lambda self: self.h5Path.lstrip('/').split('/')[0])
def _loadChildren(self):
base = self.h5Path.rstrip('/')
entry = self.entry
children = []
with FitH5(self.h5File, mode='r') as h5f:
processes = h5f.processes(entry)
for process in processes:
child = FitProcessNode(self.h5File, base + '/' + process)
children.append(child)
return children
class FitProcessNode(FitEntryNode):
process = property(lambda self: self.h5Path.split('/')[1])
def _loadChildren(self):
base = self.h5Path.rstrip('/')
entry = self.entry
process = self.process
children = []
with FitH5(self.h5File, mode='r') as h5f:
results = h5f.results(entry, process)
for result in results:
child = FitResultNode(self.h5File, base + '/' + result)
children.append(child)
return children
class FitResultNode(FitProcessNode):
result = property(lambda self: self.h5Path.split('/')[-1])
def __init__(self, *args, **kwargs):
self.dragEnabledColumns = [False, True, True, True]
super(FitResultNode, self).__init__(*args, **kwargs)
def _setupNode(self):
self.setData(1, 'Qx', Qt.Qt.DisplayRole)
self.setData(1, Qt.Qt.AlignCenter, Qt.Qt.TextAlignmentRole)
self.setData(2, 'Qy', Qt.Qt.DisplayRole)
self.setData(2, Qt.Qt.AlignCenter, Qt.Qt.TextAlignmentRole)
self.setData(3, 'Qz', Qt.Qt.DisplayRole)
self.setData(3, Qt.Qt.AlignCenter, Qt.Qt.TextAlignmentRole)
def _loadChildren(self):
return [FitThumbnailNode(self.h5File, self.h5Path)]
class FitResultEditor(EditorMixin, PlotWidget):
persistent = True
def __init__(self, *args, **kwargs):
super(FitResultEditor, self).__init__(*args, **kwargs)
self._backend._enableAxis('left', False)
self._backend._enableAxis('right', False)
self._backend.ax.get_xaxis().set_visible(False)
self._backend.ax.set_xmargin(0)
self._backend.ax.set_ymargin(0)
self.setActiveCurveHandling(False)
self.setKeepDataAspectRatio(True)
self.setDataMargins(0, 0, 0, 0)
def setEditorData(self, index):
node = index.data(ModelRoles.InternalDataRole)
if node and not node.setEditorData(self, index.column()):
value = index.data(Qt.Qt.EditRole)
return self.setModelValue(value)
return True
def setModelValue(self, value):
return False
def getEditorData(self):
pass
def sizeHint(self):
return Qt.QSize(100, 100)
def minimumSizeHint(self):
return Qt.QSize(100, 100)
def maximumSize(self):
return Qt.QSize(100, 100)
class FitThumbnailNode(FitResultNode):
editors = [None, FitResultEditor, FitResultEditor, FitResultEditor]
def __init__(self, *args, **kwargs):
self.dragEnabledColumns = [False, True, True, True]
super(FitThumbnailNode, self).__init__(*args, **kwargs)
def _setupNode(self):
self.setData(ModelColumns.NameColumn, None, Qt.Qt.DisplayRole)
def _loadChildren(self):
return []
def sizeHint(self, column):
if column == ModelColumns.ValueColumn:
return Qt.QSize(100, 100)
return super(FitResultNode, self).sizeHint(column)
def setEditorData(self, editor, column):
if not isinstance(editor, FitResultEditor):
return False
with FitH5(self.h5File) as fitH5:
x = fitH5.scan_x(self.entry)
y = fitH5.scan_y(self.entry)
if column == 1:
data = fitH5.get_qx_result(self.entry,
self.process,
self.result)
elif column == 2:
data = fitH5.get_qy_result(self.entry,
self.process,
self.result)
else:
data = fitH5.get_qz_result(self.entry,
self.process,
self.result)
min_, max_ = data.min(), data.max()
colormap = cm.jet
colors = colormap(
(data.astype(np.float64) - min_) / (max_ - min_))
editor.addCurve(x,
y,
color=colors,
symbol='s',
linestyle='')
return True
def _setModelData(self, editor, column):
"""
This is called by the View's delegate just before the editor is closed,
it allows this item to update itself with data from the editor.
:param editor:
:return:
"""
return False
def _openedEditorEvent(self, editor, column, args=None, kwargs=None):
"""
This is called by custom editors while they're opened in the view.
See ItemDelegate.__notifyView. Defqult implementation calls
_setModelData on this node.
:param editor:
:param column:
:param args: event's args
:param kwargs: event's kwargs
:return:
"""
return self._setModelData(editor, column)
class FitRootNode(RootNode):
ColumnNames = ['Param', 'Qx', 'Qy', 'Qz']
class FitModel(Model):
RootNode = FitRootNode
ColumnsWithDelegates = [1, 2, 3]
def mimeData(self, indexes):
if len(indexes) > 1:
raise ValueError('Drag&Drop of more than one item is not'
'supported yet.')
index = indexes[0]
node = index.data(ModelRoles.InternalDataRole)
if not isinstance(node, FitResultNode):
return super(Model, self).mimeData(indexes)
if index.column() == 1:
q_axis = FitH5.qx_axis
elif index.column() == 2:
q_axis = FitH5.qy_axis
elif index.column() == 3:
q_axis = FitH5.qz_axis
else:
raise ValueError('Unexpected column.')
h5file = node.h5File
entry = node.entry
process = node.process
result = node.result
data = Qt.QByteArray()
stream = Qt.QDataStream(data, Qt.QIODevice.WriteOnly)
stream.writeString(h5file)
stream.writeString(entry)
stream.writeString(process)
stream.writeString(result)
stream.writeInt(q_axis)
mimeData = Qt.QMimeData()
mimeData.setData('application/FitModel', data)
return mimeData
class DropPlotWidget(XsocsPlot2D):
sigSelected = Qt.Signal(object)
def __init__(self, *args, **kwargs):
super(DropPlotWidget, self).__init__(*args, **kwargs)
self.__legend = None
self.setActiveCurveHandling(False)
self.setKeepDataAspectRatio(True)
self.setAcceptDrops(True)
self.setPointSelectionEnabled(True)
self.setShowMousePosition(True)
self.setShowSelectedCoordinates(True)
def dropEvent(self, event):
mimeData = event.mimeData()
if not mimeData.hasFormat('application/FitModel'):
return super(DropPlotWidget, self).dropEvent(event)
qByteArray = mimeData.data('application/FitModel')
stream = Qt.QDataStream(qByteArray, Qt.QIODevice.ReadOnly)
h5File = stream.readString()
entry = stream.readString()
process = stream.readString()
result = stream.readString()
q_axis = stream.readInt()
self.plotFitResult(h5File, entry, process, result, q_axis)
def dragEnterEvent(self, event):
# super(DropWidget, self).dragEnterEvent(event)
if event.mimeData().hasFormat('application/FitModel'):
event.acceptProposedAction()
def dragLeaveEvent(self, event):
super(DropPlotWidget, self).dragLeaveEvent(event)
def dragMoveEvent(self, event):
super(DropPlotWidget, self).dragMoveEvent(event)
def plotFitResult(self, fitH5Name, entry, process, result, q_axis):
with FitH5(fitH5Name) as h5f:
data = h5f.get_axis_result(entry, process, result, q_axis)
scan_x = h5f.scan_x(entry)
scan_y = h5f.scan_y(entry)
self.__legend = self.setPlotData(scan_x, scan_y, data)
self.setGraphTitle(result + '/' + FitH5.axis_names[q_axis])
from .fitview.FitModel import FitModel, FitH5Node
from .fitview.DropPlotWidget import DropPlotWidget
class FitView(Qt.QMainWindow):
sigPointSelected = Qt.Signal(object)
__sigStartModel = Qt.Signal()
__sigInitPlots = Qt.Signal()
def __init__(self,
parent,
model,
......@@ -367,7 +82,7 @@ class FitView(Qt.QMainWindow):
treeDock = Qt.QDockWidget()
self.__model = FitModel()
self.__model.startModel()
# self.__model.startModel()
rootNode = FitH5Node(item.fitFile)
self.__model.appendGroup(rootNode)
......@@ -392,6 +107,7 @@ class FitView(Qt.QMainWindow):
mask=False,
yInverted=False)
grpLayout.addWidget(plot)
plot.setVisible(False)
self.__plots.append(plot)
plot.sigPointSelected.connect(self.__plotSignal)
......@@ -402,6 +118,7 @@ class FitView(Qt.QMainWindow):
mask=False,
yInverted=False)
grpLayout.addWidget(plot)
plot.setVisible(False)
self.__plots.append(plot)
plot.sigPointSelected.connect(self.__plotSignal)
......@@ -412,6 +129,7 @@ class FitView(Qt.QMainWindow):
mask=False,
yInverted=False)
grpLayout.addWidget(plot)
plot.setVisible(False)
self.__plots.append(plot)
plot.sigPointSelected.connect(self.__plotSignal)
......@@ -428,7 +146,7 @@ class FitView(Qt.QMainWindow):
self.__fitPlots.append(plot)
plot.setGraphTitle('Qx fit')
plot.setShowMousePosition(True)
plot.setShowSelectedCoordinates(True)
# plot.setPointSelectionEnabled(True)
plot = XsocsPlot2D()
plot.setKeepDataAspectRatio(False)
......@@ -436,7 +154,7 @@ class FitView(Qt.QMainWindow):
self.__fitPlots.append(plot)
plot.setGraphTitle('Qy fit')
plot.setShowMousePosition(True)
plot.setShowSelectedCoordinates(True)
# plot.setPointSelectionEnabled(True)
plot = XsocsPlot2D()
plot.setKeepDataAspectRatio(False)
......@@ -444,7 +162,7 @@ class FitView(Qt.QMainWindow):
self.__fitPlots.append(plot)
plot.setGraphTitle('Qz fit')
plot.setShowMousePosition(True)
plot.setShowSelectedCoordinates(True)
# plot.setPointSelectionEnabled(True)
layout.addWidget(grpBox, 0, 2)
......@@ -453,17 +171,40 @@ class FitView(Qt.QMainWindow):
self.setCentralWidget(centralWid)
self.__sigInitPlots.connect(self.__firstInit, Qt.Qt.QueuedConnection)
# self.__sigStartModel.connect(self.__startModel, Qt.Qt.QueuedConnection)
def showEvent(self, event):
"""
Overloard method from Qt.QWidget.showEvent to set up the widget the
first time it is shown. Also starts the model in a queued slot, so that
the window is shown right away, and the thumbmails are drawn
afterwards.
:param event:
:return:
"""
# TODO : this is a workaround to the fact that
# plot ranges aren't set correctly when adding data when the plot
# widget hasn't been shown yet.
Qt.QCoreApplication.processEvents()
super(FitView, self).showEvent(event)
if self.__firstShow:
self.__firstShow = False
self.__initPlots()
self.__sigInitPlots.emit()
# self.__sigStartModel.emit()
def __initPlots(self):
def __firstInit(self):
self.__initPlots()
self.__startModel()
def __startModel(self):
"""
Starts the model (in this case draws the thumbnails
:return:
"""
self.__model.startModel()
def __initPlots(self):
fitH5 = self.__fitH5
entry = None
......@@ -482,6 +223,10 @@ class FitView(Qt.QMainWindow):
_initCentroid(self.__plots, fitH5.filename, entry, process)
def __plotSignal(self, point):
sender = self.sender()
for plot in self.__plots:
if plot != sender:
plot.selectPoint(point.x, point.y)
self.__plotFitResults(point.xIdx)
self.sigPointSelected.emit(point)
......@@ -649,12 +394,20 @@ def _initLeastSq(plots, fitH5Name, entry, process):
"""
# hard coded result name, this isn't satisfactory but I can't think
# of any other way right now.
qApp = Qt.qApp
qApp.processEvents()
plots[0].plotFitResult(fitH5Name, entry, process,
'position', FitH5.qx_axis)
plots[0].setVisible(True)
qApp.processEvents()
plots[1].plotFitResult(fitH5Name, entry, process,
'position', FitH5.qy_axis)
plots[1].setVisible(True)
qApp.processEvents()
plots[2].plotFitResult(fitH5Name, entry, process,
'position', FitH5.qz_axis)
plots[2].setVisible(True)
def _initCentroid(plots, fitH5Name, entry, process):
......@@ -668,9 +421,16 @@ def _initCentroid(plots, fitH5Name, entry, process):
"""
# hard coded result name, this isn't satisfactory but I can't think
# of any other way right now.
qApp = Qt.qApp
qApp.processEvents()
plots[0].plotFitResult(fitH5Name, entry, process, 'position', FitH5.qx_axis)
plots[0].setVisible(True)
qApp.processEvents()
plots[1].plotFitResult(fitH5Name, entry, process, 'position', FitH5.qy_axis)
plots[1].setVisible(True)
qApp.processEvents()
plots[2].plotFitResult(fitH5Name, entry, process, 'position', FitH5.qz_axis)
plots[2].setVisible(True)
if __name__ == '__main__':
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment