summaryrefslogtreecommitdiff
path: root/PyMca5/PyMcaGui/pymca/ScanWindow.py
blob: 37ea2587c5e22618ab36d5621f4c3d3bf38e8693 (plain)
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
#/*##########################################################################
# Copyright (C) 2004-2018 V.A. Sole, European Synchrotron Radiation Facility
#
# This file is part of the PyMca X-ray Fluorescence Toolkit developed at
# the ESRF by the Software group.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#############################################################################*/
"""This module defines a :class:`ScanWindow` inheriting a *silx*
:class:`PlotWindow` with additional tools and actions.
The main addition is a :class:`PluginsToolButton` button added to the toolbar,
to open a menu with plugins."""

import os
import copy
import logging
import numpy
import sys

from silx.gui.plot import PlotWindow
from silx.gui.plot.PrintPreviewToolButton import SingletonPrintPreviewToolButton

import PyMca5
from PyMca5.PyMcaGui.pymca import ScanWindowInfoWidget
from PyMca5.PyMcaGui import PyMcaQt as qt
from PyMca5.PyMcaGui.PluginsToolButton import PluginsToolButton
from PyMca5.PyMcaGui.math import SimpleActions
from PyMca5.PyMcaGui.pymca import ScanFit
from PyMca5.PyMcaGui.pymca.ScanFitToolButton import ScanFitToolButton
from PyMca5.PyMcaCore import DataObject
from PyMca5.PyMcaGui.pymca import QPyMcaMatplotlibSave1D
from PyMca5.PyMcaGui.plotting.PyMca_Icons import change_icons

if hasattr(qt, 'QString'):
    QString = qt.QString
else:
    QString = qt.safe_str

PLUGINS_DIR = None

if os.path.exists(os.path.join(os.path.dirname(PyMca5.__file__), "PyMcaPlugins")):
    from PyMca5 import PyMcaPlugins
    PLUGINS_DIR = os.path.dirname(PyMcaPlugins.__file__)
else:
    directory = os.path.dirname(__file__)
    while True:
        if os.path.exists(os.path.join(directory, "PyMcaPlugins")):
            PLUGINS_DIR = os.path.join(directory, "PyMcaPlugins")
            break
        directory = os.path.dirname(directory)
        if len(directory) < 5:
            break
userPluginsDirectory = PyMca5.getDefaultUserPluginsDirectory()
if userPluginsDirectory is not None:
    if PLUGINS_DIR is None:
        PLUGINS_DIR = userPluginsDirectory
    else:
        PLUGINS_DIR = [PLUGINS_DIR, userPluginsDirectory]


_logger = logging.getLogger(__name__)
# _logger.setLevel(logging.DEBUG)


class BaseScanWindow(PlotWindow):
    """:class:`PlotWindow` augmented with plugins, fitting actions,
    a widget for displaying scan metadata and simple curve processing actions.
    """
    def __init__(self, parent=None, name="Scan Window", fit=True, backend=None,
                 plugins=True, control=True, position=True, roi=True,
                 specfit=None, info=False, save=True):
        super(BaseScanWindow, self).__init__(parent,
                                             backend=backend,
                                             roi=roi,
                                             control=control,
                                             position=position,
                                             save=save,
                                             mask=False,
                                             colormap=False,
                                             aspectRatio=False,
                                             yInverted=False,
                                             copy=True,
                                             print_=False)
        self.setDataMargins(0, 0, 0.025, 0.025)

        self.setPanWithArrowKeys(True)
        self._plotType = "SCAN"     # needed by legacy plugins

        self.setWindowTitle(name)

        # No context menu by default, execute zoomBack on right click
        plotArea = self.getWidgetHandle()
        plotArea.setContextMenuPolicy(qt.Qt.CustomContextMenu)
        plotArea.customContextMenuRequested.connect(self._zoomBack)

        # Toolbar:
        # hide interactive toolbar (zoom and pan mode buttons)
        self.getInteractiveModeToolBar().setVisible(False)

        # additional buttons
        self._mathToolBar = qt.QToolBar(self)

        self.addToolBar(self._mathToolBar)

        self.fitToolButton = None
        self.scanFit = None
        if fit:
            self.scanFit = ScanFit.ScanFit(specfit=specfit)
            self.fitToolButton = ScanFitToolButton(self)
            self.toolBar().insertWidget(self.getMaskAction(),  # before MaskAction (hidden)
                                        self.fitToolButton)

        self.avgAction = SimpleActions.AverageAction(plot=self)
        self.derivativeAction = SimpleActions.DerivativeAction(plot=self)
        self.smoothAction = SimpleActions.SmoothAction(plot=self)
        self.swapSignAction = SimpleActions.SwapSignAction(plot=self)
        self.yMinToZero = SimpleActions.YMinToZeroAction(plot=self)
        self.subtractAction = SimpleActions.SubtractAction(plot=self)

        self._mathToolBar.addAction(self.avgAction)
        self._mathToolBar.addAction(self.derivativeAction)
        self._mathToolBar.addAction(self.smoothAction)
        self._mathToolBar.addAction(self.swapSignAction)
        self._mathToolBar.addAction(self.yMinToZero)
        self._mathToolBar.addAction(self.subtractAction)

        self.pluginsToolButton = None
        """Plugins tool button, used to load and call plugins.
        It inherits the PluginLoader API:

            - getPlugins
            - getPluginDirectoryList
            - setPluginDirectoryList

        It can be None, if plugins are disabled when initializing
        the ScanWindow.
        """

        if plugins:
            self.pluginsToolButton = PluginsToolButton(plot=self)

            if PLUGINS_DIR is not None:
                if isinstance(PLUGINS_DIR, list):
                    pluginDir = PLUGINS_DIR
                else:
                    pluginDir = [PLUGINS_DIR]
                self.pluginsToolButton.getPlugins(
                        method="getPlugin1DInstance",
                        directoryList=pluginDir)
            self.pluginsAction = self._mathToolBar.addWidget(self.pluginsToolButton)

        self._printPreviewToolBar = qt.QToolBar(self)
        self._printPreviewToolBar.setMovable(False)
        self._printPreviewToolBar.setFloatable(False)
        self.addToolBar(self._printPreviewToolBar)
        self._printPreviewToolBar.addWidget(qt.HorizontalSpacer(self._printPreviewToolBar))
        self.printPreview = SingletonPrintPreviewToolButton(parent=self._printPreviewToolBar,
                                                            plot=self)
        self.printPreviewAction = self._printPreviewToolBar.addWidget(self.printPreview)

        self.scanWindowInfoWidget = None
        self.infoDockWidget = None
        if info:
            self.scanWindowInfoWidget = ScanWindowInfoWidget.\
                                            ScanWindowInfoWidget()
            self.infoDockWidget = qt.QDockWidget(self)
            self.infoDockWidget.layout().setContentsMargins(0, 0, 0, 0)
            self.infoDockWidget.setWidget(self.scanWindowInfoWidget)
            self.infoDockWidget.setWindowTitle("Scan Info")
            self.addDockWidget(qt.Qt.BottomDockWidgetArea,
                               self.infoDockWidget)

            self.sigActiveCurveChanged.connect(self.__updateInfoWidget)

        self.sigActiveCurveChanged.connect(self.__updateGraphTitle)
        self.matplotlibDialog = None

        saveAction = self.getOutputToolBar().getSaveAction()
        for ext in ["png", "eps", "svg"]:
            name_filter = 'Customized graphics (*.%s)' % ext
            # if silx-kit/silx#2013 is merged, the following line can be removed for silx 0.9
            saveAction.setFileFilter(dataKind='curve',  # single curve case
                                     nameFilter=name_filter,
                                     func=self._graphicsSave)
            saveAction.setFileFilter(dataKind='curves',
                                     nameFilter=name_filter,
                                     func=self._graphicsSave)

        change_icons(self)

    def _customControlButtonMenu(self):
        """Display Options button sub-menu. Overloaded to add
        _toggleInfoAction"""
        # overloaded from PlotWindow to add "Show/Hide Info"
        controlMenu = self.controlButton.menu()
        controlMenu.clear()
        controlMenu.addAction(self.getLegendsDockWidget().toggleViewAction())

        if self.infoDockWidget is not None:
            controlMenu.addAction(self.infoDockWidget.toggleViewAction())
        controlMenu.addAction(self.getRoiAction())
        controlMenu.addAction(self.getMaskAction())
        controlMenu.addAction(self.getConsoleAction())

        controlMenu.addSeparator()
        controlMenu.addAction(self.getCrosshairAction())
        controlMenu.addAction(self.getPanWithArrowKeysAction())

    def __updateInfoWidget(self, previous_legend, legend):
        """Called on active curve changed, to update the info widget"""
        x, y, legend, info, params = self.getCurve(legend)
        self.scanWindowInfoWidget.updateFromXYInfo(x, y, info)

    def __updateGraphTitle(self, previous_legend, legend):
        """Called on active curve changed, to update the graph title"""
        if legend is None and previous_legend is not None:
            self.setGraphTitle()
        elif legend is not None:
            self.setGraphTitle(legend)

    def setWindowType(self, wtype=None):
        if wtype not in [None, "SCAN", "MCA"]:
            raise AttributeError("Unsupported window type %s." % wtype)
        self._plotType = wtype

    def _zoomBack(self, pos):
        self.getLimitsHistory().pop()

    def _graphicsSave(self, plot, filename, nameFilter=""):
        # note: the method's signature must conform to
        #       saveAction.setFileFilter requirements
        x, y, legend, info = plot.getActiveCurve()[:4]
        curveList = plot.getAllCurves()
        size = (6, 3)  # in inches
        legends = len(curveList) > 1
        if self.matplotlibDialog is None:
            self.matplotlibDialog = QPyMcaMatplotlibSave1D.\
                                    QPyMcaMatplotlibSaveDialog(size=size,
                                                        logx=plot.isXAxisLogarithmic(),
                                                        logy=plot.isYAxisLogarithmic(),
                                                        legends=legends,
                                                        bw=False)

        mtplt = self.matplotlibDialog.plot

        mtplt.setParameters({'logy': plot.isXAxisLogarithmic(),
                             'logx': plot.isYAxisLogarithmic(),
                             'legends': legends,
                             'bw': False})
        xmin, xmax = plot.getGraphXLimits()
        ymin, ymax = plot.getGraphYLimits()
        mtplt.setLimits(xmin, xmax, ymin, ymax)

        legend0 = legend
        dataCounter = 1
        alias = "%c" % (96 + dataCounter)
        mtplt.addDataToPlot(x, y, legend=legend0, alias=alias)
        for curve in curveList:
            x, y, legend, info = curve[0:4]
            if legend == legend0:
                continue
            dataCounter += 1
            alias = "%c" % (96 + dataCounter)
            mtplt.addDataToPlot(x, y, legend=legend, alias=alias)

        self.matplotlibDialog.setXLabel(plot.getGraphXLabel())
        self.matplotlibDialog.setYLabel(plot.getGraphYLabel())

        if legends:
            mtplt.plotLegends()
        ret = self.matplotlibDialog.exec_()
        if ret == qt.QDialog.Accepted:
            mtplt.saveFile(filename)
        return


class ScanWindow(BaseScanWindow):
    """ScanWindow, adding dataObject management to BaseScanWindow
    """

    def __init__(self, parent=None, name="Scan Window", fit=True, backend=None,
                 plugins=True, control=True, position=True, roi=True,
                 specfit=None, info=False, save=True):
        BaseScanWindow.__init__(self,
                                parent, name, fit, backend,
                                plugins, control, position, roi,
                                specfit, info, save)

        self.dataObjectsDict = {}

        self.sigContentChanged.connect(self._handleContentChanged)

    @property
    def dataObjectsList(self):
        return self.getAllCurves(just_legend=True)

    @property
    def _curveList(self):
        return self.getAllCurves(just_legend=True)

    def _handleContentChanged(self, action, kind, legend):
        if action == 'remove' and kind == "curve":
            self.removeCurves([legend])

    def setDispatcher(self, w):
        w.sigAddSelection.connect(self._addSelection)
        w.sigRemoveSelection.connect(self._removeSelection)
        w.sigReplaceSelection.connect(self._replaceSelection)

    def _addSelection(self, selectionlist, resetzoom=True, replot=None):
        """Add curves to plot and data objects to :attr:`dataObjectsDict`
        """
        _logger.debug("_addSelection(self, selectionlist) " +
                      str(selectionlist))
        if replot is not None:
            _logger.warning(
                    'deprecated replot argument, use resetzoom instead')
            resetzoom = replot and resetzoom

        sellist = selectionlist if isinstance(selectionlist, list) else \
            [selectionlist]

        if len(self.getAllCurves(just_legend=True)):
            activeCurve = self.getActiveCurve(just_legend=True)
        else:
            activeCurve = None
        nSelection = len(sellist)
        for selectionIndex in range(nSelection):
            sel = sellist[selectionIndex]
            key = sel['Key']
            legend = sel['legend']  # expected form sourcename + scan key
            if "scanselection" not in sel or not sel["scanselection"] or \
                            sel['scanselection'] == "MCA":
                continue
            if len(key.split(".")) > 2:
                continue
            dataObject = sel['dataobject']
            # only one-dimensional selections considered
            if dataObject.info["selectiontype"] != "1D":
                continue

            # there must be something to plot
            if not hasattr(dataObject, 'y'):
                continue

            if len(dataObject.y) == 0:
                # nothing to be plot
                continue
            else:
                for i in range(len(dataObject.y)):
                    if numpy.isscalar(dataObject.y[i]):
                        dataObject.y[i] = numpy.array([dataObject.y[i]])
            if not hasattr(dataObject, 'x'):
                ylen = len(dataObject.y[0])
                if ylen:
                    xdata = numpy.arange(ylen).astype(numpy.float)
                else:
                    #nothing to be plot
                    continue
            if getattr(dataObject, 'x', None) is None:
                ylen = len(dataObject.y[0])
                if not ylen:
                    # nothing to be plot
                    continue
                xdata = numpy.arange(ylen).astype(numpy.float)
            elif len(dataObject.x) > 1:
                # mesh plot
                continue
            else:
                if numpy.isscalar(dataObject.x[0]):
                    dataObject.x[0] = numpy.array([dataObject.x[0]])    
                xdata = dataObject.x[0]

            if sel.get('SourceType') == "SPS":
                ycounter = -1
                if 'selection' not in dataObject.info:
                    dataObject.info['selection'] = copy.deepcopy(sel['selection'])
                for ydata in dataObject.y:
                    xlabel = None
                    ylabel = None
                    ycounter += 1
                    # normalize ydata with monitor
                    if dataObject.m is not None and len(dataObject.m[0]) > 0:
                        if len(dataObject.m[0]) != len(ydata):
                            raise ValueError("Monitor data length different than counter data")
                        index = numpy.nonzero(dataObject.m[0])[0]
                        if not len(index):
                            continue
                        xdata = numpy.take(xdata, index)
                        ydata = numpy.take(ydata, index)
                        mdata = numpy.take(dataObject.m[0], index)
                        # A priori the graph only knows about plots
                        ydata = ydata / mdata
                    ylegend = 'y%d' % ycounter
                    if isinstance(dataObject.info['selection'], dict):
                        if 'x' in dataObject.info['selection']:
                            # proper scan selection
                            ilabel = dataObject.info['selection']['y'][ycounter]
                            ylegend = dataObject.info['LabelNames'][ilabel]
                            ylabel = ylegend
                            if sel['selection']['x'] is not None:
                                if len(dataObject.info['selection']['x']):
                                    xlabel = dataObject.info['LabelNames'] \
                                        [dataObject.info['selection']['x'][0]]
                    dataObject.info["xlabel"] = xlabel
                    dataObject.info["ylabel"] = ylabel
                    newLegend = legend + " " + ylegend
                    self.dataObjectsDict[newLegend] = dataObject
                    self.addCurve(xdata, ydata, legend=newLegend, info=dataObject.info,
                                  xlabel=xlabel, ylabel=ylabel, resetzoom=False)
                    if self.scanWindowInfoWidget is not None:
                        if not self.infoDockWidget.isHidden():
                            activeLegend = self.getActiveCurve(just_legend=True)
                            if activeLegend == newLegend:
                                self.scanWindowInfoWidget.updateFromDataObject \
                                    (dataObject)
                            else:
                                # TODO: better to implement scanWindowInfoWidget.clear
                                dummyDataObject = DataObject.DataObject()
                                dummyDataObject.y = [numpy.array([])]
                                dummyDataObject.x = [numpy.array([])]
                                self.scanWindowInfoWidget.updateFromDataObject(dummyDataObject)
            else:
                # we have to loop for all y values
                ycounter = -1
                for ydata in dataObject.y:
                    ylen = len(ydata)
                    if ylen == 1 and len(xdata) > 1:
                        ydata = ydata[0] * numpy.ones(len(xdata)).astype(numpy.float)
                    elif len(xdata) == 1:
                        xdata = xdata[0] * numpy.ones(ylen).astype(numpy.float)
                    ycounter += 1
                    newDataObject = DataObject.DataObject()
                    newDataObject.info = copy.deepcopy(dataObject.info)

                    if dataObject.m is not None:
                        for imon in range(len(dataObject.m)):
                            if numpy.isscalar(dataObject.m[imon]):
                                dataObject.m[imon] = \
                                             numpy.array([dataObject.m[imon]])
                    if dataObject.m is None:
                        mdata = numpy.ones(len(ydata)).astype(numpy.float)
                    elif len(dataObject.m[0]) == len(ydata):
                        index = numpy.nonzero(dataObject.m[0])[0]
                        if not len(index):
                            continue
                        xdata = numpy.take(xdata, index)
                        ydata = numpy.take(ydata, index)
                        mdata = numpy.take(dataObject.m[0], index)
                        # A priori the graph only knows about plots
                        ydata = ydata / mdata
                    elif len(dataObject.m[0]) == 1:
                        mdata = numpy.ones(len(ydata)).astype(numpy.float)
                        mdata *= dataObject.m[0][0]
                        index = numpy.nonzero(dataObject.m[0])[0]
                        if not len(index):
                            continue
                        xdata = numpy.take(xdata, index)
                        ydata = numpy.take(ydata, index)
                        mdata = numpy.take(dataObject.m[0], index)
                        # A priori the graph only knows about plots
                        ydata = ydata / mdata
                    else:
                        raise ValueError("Monitor data length different than counter data")

                    newDataObject.x = [xdata]
                    newDataObject.y = [ydata]
                    newDataObject.m = [mdata]
                    newDataObject.info['selection'] = copy.deepcopy(sel['selection'])
                    ylegend = 'y%d' % ycounter
                    xlabel = None
                    ylabel = None
                    if isinstance(sel['selection'], dict) and 'x' in sel['selection']:
                        # proper scan selection
                        newDataObject.info['selection']['x'] = sel['selection']['x']
                        newDataObject.info['selection']['y'] = [sel['selection']['y'][ycounter]]
                        newDataObject.info['selection']['m'] = sel['selection']['m']
                        ilabel = newDataObject.info['selection']['y'][0]
                        ylegend = newDataObject.info['LabelNames'][ilabel]
                        ylabel = ylegend
                        if len(newDataObject.info['selection']['x']):
                            ilabel = newDataObject.info['selection']['x'][0]
                            xlabel = newDataObject.info['LabelNames'][ilabel]
                        else:
                            xlabel = "Point number"
                    if ('operations' in dataObject.info) and len(dataObject.y) == 1:
                        newDataObject.info['legend'] = legend
                        symbol = 'x'
                    else:
                        symbol = None
                        newDataObject.info['legend'] = legend + " " + ylegend
                        newDataObject.info['selectionlegend'] = legend
                    yaxis = None
                    if "plot_yaxis" in dataObject.info:
                        yaxis = dataObject.info["plot_yaxis"]
                    elif 'operations' in dataObject.info:
                        if dataObject.info['operations'][-1] == 'derivate':
                            yaxis = 'right'
                    self.dataObjectsDict[newDataObject.info['legend']] = newDataObject
                    self.addCurve(xdata, ydata, legend=newDataObject.info['legend'],
                                  info=newDataObject.info,
                                  symbol=symbol,
                                  yaxis=yaxis,
                                  xlabel=xlabel,
                                  ylabel=ylabel,
                                  resetzoom=False)
        try:
            if activeCurve is None and self._curveList:
                self.setActiveCurve(self._curveList[0])
        finally:
            if resetzoom:
                self.resetZoom()

    def _removeSelection(self, selectionlist):
        _logger.debug("_removeSelection(self, selectionlist) " +
                      str(selectionlist))

        sellist = selectionlist if isinstance(selectionlist, list) else \
            [selectionlist]

        removelist = []
        for sel in sellist:
            key = sel['Key']
            if "scanselection" not in sel or not sel["scanselection"]:
                continue
            if sel['scanselection'] == "MCA":
                continue
            if len(key.split(".")) > 2:
                continue

            legend = sel['legend']  # expected form sourcename + scan key
            if isinstance(sel['selection'], dict) and 'y' in sel['selection']:
                for lName in ['cntlist', 'LabelNames']:
                    if lName in sel['selection']:
                        for index in sel['selection']['y']:
                            removelist.append(legend + " " +
                                              sel['selection'][lName][index])

        if len(removelist):
            self.removeCurves(removelist)

    def _replaceSelection(self, selectionlist):
        """Delete existing curves and data objects, then add new selection.
        """
        _logger.debug("_replaceSelection(self, selectionlist) " +
                      str(selectionlist))

        sellist = selectionlist if isinstance(selectionlist, list) else \
            [selectionlist]

        doit = False
        for sel in sellist:
            if "scanselection" not in sel or not sel["scanselection"]:
                continue
            if sel['scanselection'] == "MCA":
                continue
            if len(sel["Key"].split(".")) > 2:
                continue
            dataObject = sel['dataobject']
            if dataObject.info["selectiontype"] == "1D":
                if hasattr(dataObject, 'y'):
                    doit = True
                    break
        if not doit:
            return
        self.clearCurves()
        self.dataObjectsDict = {}
        self._addSelection(selectionlist, resetzoom=True)

    def removeCurves(self, removeList):
        for legend in removeList:
            self.removeCurve(legend)
            if legend in self.dataObjectsDict:
                del self.dataObjectsDict[legend]

    def addCurve(self, x, y, legend=None, info=None, replace=False,
                 resetzoom=True, color=None, symbol=None,
                 linestyle=None, xlabel=None, ylabel=None, yaxis=None,
                 xerror=None, yerror=None, **kw):
        """Add a curve. If a curve with the same legend already exists,
        the unspecified parameters (color, symbol, linestyle, yaxis) are
        assumed to be identical to the parameters of the existing curve."""
        if "replot" in kw:
            _logger.warning("addCurve deprecated replot argument, "
                            "use resetzoom instead")
            resetzoom = kw["replot"] and resetzoom
        if legend in self._curveList:
            if info is None:
                info = {}
            oldStuff = self.getCurve(legend)
            if oldStuff is not None:
                oldX, oldY, oldLegend, oldInfo, oldParams = oldStuff
            else:
                oldInfo = {}
            if color is None:
                color = info.get("plot_color",
                                 oldInfo.get("plot_color", None))
            if symbol is None:
                symbol = info.get("plot_symbol",
                                  oldInfo.get("plot_symbol", None))
            if linestyle is None:
                linestyle = info.get("plot_linestyle",
                                     oldInfo.get("plot_linestyle", None))
            if yaxis is None:
                yaxis = info.get("plot_yaxis",
                                 oldInfo.get("plot_yaxis", None))
        else:
            if info is None:
                info = {}
            if color is None:
                color = info.get("plot_color", None)
            if symbol is None:
                symbol = info.get("plot_symbol", None)
            if linestyle is None:
                linestyle = info.get("plot_linestyle", None)
            if yaxis is None:
                yaxis = info.get("plot_yaxis", None)
        if legend in self.dataObjectsDict:
            # the info is changing
            super(ScanWindow, self).addCurve(
                    x, y, legend=legend, info=info,
                    replace=replace, color=color, symbol=symbol,
                    linestyle=linestyle, xlabel=xlabel, ylabel=ylabel,
                    yaxis=yaxis, xerror=xerror, yerror=yerror,
                    resetzoom=resetzoom, **kw)
        else:
            # create the data object
            self.newCurve(
                    x, y, legend=legend, info=info,
                    replace=replace, color=color, symbol=symbol,
                    linestyle=linestyle, xlabel=xlabel, ylabel=ylabel,
                    yaxis=yaxis, xerror=xerror, yerror=yerror,
                    resetzoom=resetzoom, **kw)

    def newCurve(self, x, y, legend=None, info=None, replace=False,
                 resetzoom=True, color=None, symbol=None,
                 linestyle=None, xlabel=None, ylabel=None, yaxis=None,
                 xerror=None, yerror=None, **kw):
        """
        Create and add a data object to :attr:`dataObjectsDict`
        """
        if "replot" in kw:
            _logger.warning("addCurve deprecated replot argument, "
                            "use resetzoom instead")
            resetzoom = kw["replot"] and resetzoom
        if legend is None:
            legend = "Unnamed curve 1.1"
        if xlabel is None:
            xlabel = "X"
        if ylabel is None:
            ylabel = "Y"
        if info is None:
            info = {}
        if color is not None:
            info["plot_color"] = color
        if symbol is not None:
            info["plot_symbol"] = symbol
        if linestyle is not None:
            info["plot_linestyle"] = linestyle
        if yaxis is not None:
            info["plot_yaxis"] = yaxis

        newDataObject = DataObject.DataObject()
        newDataObject.x = [x]
        newDataObject.y = [y]
        newDataObject.m = None
        newDataObject.info = copy.deepcopy(info)
        newDataObject.info['legend'] = legend
        newDataObject.info['SourceName'] = legend
        newDataObject.info['Key'] = ""
        newDataObject.info['selectiontype'] = "1D"
        newDataObject.info['LabelNames'] = [xlabel, ylabel]
        newDataObject.info['selection'] = {'x': [0], 'y': [1]}

        sel = {'SourceType': "Operation",
               'SourceName': legend,
               'Key': "",
               'legend': legend,
               'dataobject': newDataObject,
               'scanselection': True,
               'selection': {'x': [0], 'y': [1], 'm': [],
                             'cntlist': [xlabel, ylabel]},
               'selectiontype': "1D"}
        sel_list = [sel]
        if replace:
            self._replaceSelection(sel_list)
        else:
            self._addSelection(sel_list, resetzoom=resetzoom)


def test():
    import numpy
    app = qt.QApplication([])
    w = ScanWindow(info=True)
    x = numpy.arange(1000.)
    y1 = 10 * x + 10000. * numpy.exp(-0.5*(x-500)*(x-500)/400)
    y2 = y1 + 5000. * numpy.exp(-0.5*(x-700)*(x-700)/200)
    y3 = y1 + 7000. * numpy.exp(-0.5*(x-200)*(x-200)/1000)
    w.addCurve(x, y1, legend="dummy1",
               info={"SourceName": "Synthetic data 1 (linear+gaussian)",
                     "hkl": [1.1, 1.2, 1.3],
                     "Header": ["#S 1 toto"]})
    w.addCurve(x, y2, legend="dummy2",
               info={"SourceName": "Synthetic data 2",
                     "hkl": [2.1, 2.2, 2.3],
                     "Header": ["#S 2"]})
    w.addCurve(x, y3, legend="dummy3",
               info={"SourceName": "Synthetic data 3",
                     "hkl": ["3.1", 3.2, 3.3],
                     "Header": ["#S 3"]})
    w.resetZoom()
    app.lastWindowClosed.connect(app.quit)
    w.show()
    app.exec_()


if __name__ == "__main__":
    test()