summaryrefslogtreecommitdiff
path: root/silx/gui/plot/items/core.py
blob: 9426a130b9deb9103c8560882bf09a2f3529e1c4 (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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2017-2020 European Synchrotron Radiation Facility
#
# 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 provides the base class for items of the :class:`Plot`.
"""

__authors__ = ["T. Vincent"]
__license__ = "MIT"
__date__ = "29/01/2019"

import collections
try:
    from collections import abc
except ImportError:  # Python2 support
    import collections as abc
from copy import deepcopy
import logging
import enum
import warnings
import weakref

import numpy
import six

from ....utils.deprecation import deprecated
from ....utils.enum import Enum as _Enum
from ... import qt
from ... import colors
from ...colors import Colormap
from ._pick import PickingResult

from silx import config

_logger = logging.getLogger(__name__)


@enum.unique
class ItemChangedType(enum.Enum):
    """Type of modification provided by :attr:`Item.sigItemChanged` signal."""
    # Private setters and setInfo are not emitting sigItemChanged signal.
    # Signals to consider:
    # COLORMAP_SET emitted when setColormap is called but not forward colormap object signal
    # CURRENT_COLOR_CHANGED emitted current color changed because highlight changed,
    # highlighted color changed or color changed depending on hightlight state.

    VISIBLE = 'visibleChanged'
    """Item's visibility changed flag."""

    ZVALUE = 'zValueChanged'
    """Item's Z value changed flag."""

    COLORMAP = 'colormapChanged'  # Emitted when set + forward events from the colormap object
    """Item's colormap changed flag.

    This is emitted both when setting a new colormap and
    when the current colormap object is updated.
    """

    SYMBOL = 'symbolChanged'
    """Item's symbol changed flag."""

    SYMBOL_SIZE = 'symbolSizeChanged'
    """Item's symbol size changed flag."""

    LINE_WIDTH = 'lineWidthChanged'
    """Item's line width changed flag."""

    LINE_STYLE = 'lineStyleChanged'
    """Item's line style changed flag."""

    COLOR = 'colorChanged'
    """Item's color changed flag."""

    LINE_BG_COLOR = 'lineBgColorChanged'
    """Item's line background color changed flag."""

    YAXIS = 'yAxisChanged'
    """Item's Y axis binding changed flag."""

    FILL = 'fillChanged'
    """Item's fill changed flag."""

    ALPHA = 'alphaChanged'
    """Item's transparency alpha changed flag."""

    DATA = 'dataChanged'
    """Item's data changed flag"""

    HIGHLIGHTED = 'highlightedChanged'
    """Item's highlight state changed flag."""

    HIGHLIGHTED_COLOR = 'highlightedColorChanged'
    """Deprecated, use HIGHLIGHTED_STYLE instead."""

    HIGHLIGHTED_STYLE = 'highlightedStyleChanged'
    """Item's highlighted style changed flag."""

    SCALE = 'scaleChanged'
    """Item's scale changed flag."""

    TEXT = 'textChanged'
    """Item's text changed flag."""

    POSITION = 'positionChanged'
    """Item's position changed flag.

    This is emitted when a marker position changed and
    when an image origin changed.
    """

    OVERLAY = 'overlayChanged'
    """Item's overlay state changed flag."""

    VISUALIZATION_MODE = 'visualizationModeChanged'
    """Item's visualization mode changed flag."""

    COMPLEX_MODE = 'complexModeChanged'
    """Item's complex data visualization mode changed flag."""

    NAME = 'nameChanged'
    """Item's name changed flag."""

    EDITABLE = 'editableChanged'
    """Item's editable state changed flags."""

    SELECTABLE = 'selectableChanged'
    """Item's selectable state changed flags."""


class Item(qt.QObject):
    """Description of an item of the plot"""

    _DEFAULT_Z_LAYER = 0
    """Default layer for overlay rendering"""

    _DEFAULT_SELECTABLE = False
    """Default selectable state of items"""

    sigItemChanged = qt.Signal(object)
    """Signal emitted when the item has changed.

    It provides a flag describing which property of the item has changed.
    See :class:`ItemChangedType` for flags description.
    """

    def __init__(self):
        qt.QObject.__init__(self)
        self._dirty = True
        self._plotRef = None
        self._visible = True
        self._selectable = self._DEFAULT_SELECTABLE
        self._z = self._DEFAULT_Z_LAYER
        self._info = None
        self._xlabel = None
        self._ylabel = None
        self.__name = ''

        self._backendRenderer = None

    def getPlot(self):
        """Returns the ~silx.gui.plot.PlotWidget this item belongs to.

        :rtype: Union[~silx.gui.plot.PlotWidget,None]
        """
        return None if self._plotRef is None else self._plotRef()

    def _setPlot(self, plot):
        """Set the plot this item belongs to.

        WARNING: This should only be called from the Plot.

        :param Union[~silx.gui.plot.PlotWidget,None] plot: The Plot instance.
        """
        if plot is not None and self._plotRef is not None:
            raise RuntimeError('Trying to add a node at two places.')
        self._plotRef = None if plot is None else weakref.ref(plot)
        self._updated()

    def getBounds(self):  # TODO return a Bounds object rather than a tuple
        """Returns the bounding box of this item in data coordinates

        :returns: (xmin, xmax, ymin, ymax) or None
        :rtype: 4-tuple of float or None
        """
        return self._getBounds()

    def _getBounds(self):
        """:meth:`getBounds` implementation to override by sub-class"""
        return None

    def isVisible(self):
        """True if item is visible, False otherwise

        :rtype: bool
        """
        return self._visible

    def setVisible(self, visible):
        """Set visibility of item.

        :param bool visible: True to display it, False otherwise
        """
        visible = bool(visible)
        if visible != self._visible:
            self._visible = visible
            # When visibility has changed, always mark as dirty
            self._updated(ItemChangedType.VISIBLE,
                          checkVisibility=False)

    def isOverlay(self):
        """Return true if item is drawn as an overlay.

        :rtype: bool
        """
        return False

    def getName(self):
        """Returns the name of the item which is used as legend.

        :rtype: str
        """
        return self.__name

    def setName(self, name):
        """Set the name of the item which is used as legend.

        :param str name: New name of the item
        :raises RuntimeError: If item belongs to a PlotWidget.
        """
        name = str(name)
        if self.__name != name:
            if self.getPlot() is not None:
                raise RuntimeError(
                    "Cannot change name while item is in a PlotWidget")

            self.__name = name
            self._updated(ItemChangedType.NAME)

    def getLegend(self):  # Replaced by getName for API consistency
        return self.getName()

    @deprecated(replacement='setName', since_version='0.13')
    def _setLegend(self, legend):
        legend = str(legend) if legend is not None else ''
        self.setName(legend)

    def isSelectable(self):
        """Returns true if item is selectable (bool)"""
        return self._selectable

    def _setSelectable(self, selectable):  # TODO support update
        """Set whether item is selectable or not.

        This is private for now as change is not handled.

        :param bool selectable: True to make item selectable
        """
        self._selectable = bool(selectable)

    def getZValue(self):
        """Returns the layer on which to draw this item (int)"""
        return self._z

    def setZValue(self, z):
        z = int(z) if z is not None else self._DEFAULT_Z_LAYER
        if z != self._z:
            self._z = z
            self._updated(ItemChangedType.ZVALUE)

    def getInfo(self, copy=True):
        """Returns the info associated to this item

        :param bool copy: True to get a deepcopy, False otherwise.
        """
        return deepcopy(self._info) if copy else self._info

    def setInfo(self, info, copy=True):
        if copy:
            info = deepcopy(info)
        self._info = info

    def _updated(self, event=None, checkVisibility=True):
        """Mark the item as dirty (i.e., needing update).

        This also triggers Plot.replot.

        :param event: The event to send to :attr:`sigItemChanged` signal.
        :param bool checkVisibility: True to only mark as dirty if visible,
                                     False to always mark as dirty.
        """
        if not checkVisibility or self.isVisible():
            if not self._dirty:
                self._dirty = True
                # TODO: send event instead of explicit call
                plot = self.getPlot()
                if plot is not None:
                    plot._itemRequiresUpdate(self)
        if event is not None:
            self.sigItemChanged.emit(event)

    def _update(self, backend):
        """Called by Plot to update the backend for this item.

        This is meant to be called asynchronously from _updated.
        This optimizes the number of call to _update.

        :param backend: The backend to update
        """
        if self._dirty:
            # Remove previous renderer from backend if any
            self._removeBackendRenderer(backend)

            # If not visible, do not add renderer to backend
            if self.isVisible():
                self._backendRenderer = self._addBackendRenderer(backend)

            self._dirty = False

    def _addBackendRenderer(self, backend):
        """Override in subclass to add specific backend renderer.

        :param BackendBase backend: The backend to update
        :return: The renderer handle to store or None if no renderer in backend
        """
        return None

    def _removeBackendRenderer(self, backend):
        """Override in subclass to remove specific backend renderer.

        :param BackendBase backend: The backend to update
        """
        if self._backendRenderer is not None:
            backend.remove(self._backendRenderer)
            self._backendRenderer = None

    def pick(self, x, y):
        """Run picking test on this item

        :param float x: The x pixel coord where to pick.
        :param float y: The y pixel coord where to pick.
        :return: None if not picked, else the picked position information
        :rtype: Union[None,PickingResult]
        """
        if not self.isVisible() or self._backendRenderer is None:
            return None
        plot = self.getPlot()
        if plot is None:
            return None

        indices = plot._backend.pickItem(x, y, self._backendRenderer)
        if indices is None:
            return None
        else:
            return PickingResult(self, indices)


# Mix-in classes ##############################################################

class ItemMixInBase(object):
    """Base class for Item mix-in"""

    def _updated(self, event=None, checkVisibility=True):
        """This is implemented in :class:`Item`.

        Mark the item as dirty (i.e., needing update).
        This also triggers Plot.replot.

        :param event: The event to send to :attr:`sigItemChanged` signal.
        :param bool checkVisibility: True to only mark as dirty if visible,
                                     False to always mark as dirty.
        """
        raise RuntimeError(
            "Issue with Mix-In class inheritance order")


class LabelsMixIn(ItemMixInBase):
    """Mix-in class for items with x and y labels

    Setters are private, otherwise it needs to check the plot
    current active curve and access the internal current labels.
    """

    def __init__(self):
        self._xlabel = None
        self._ylabel = None

    def getXLabel(self):
        """Return the X axis label associated to this curve

        :rtype: str or None
        """
        return self._xlabel

    def _setXLabel(self, label):
        """Set the X axis label associated with this curve

        :param str label: The X axis label
        """
        self._xlabel = str(label)

    def getYLabel(self):
        """Return the Y axis label associated to this curve

        :rtype: str or None
        """
        return self._ylabel

    def _setYLabel(self, label):
        """Set the Y axis label associated with this curve

        :param str label: The Y axis label
        """
        self._ylabel = str(label)


class DraggableMixIn(ItemMixInBase):
    """Mix-in class for draggable items"""

    def __init__(self):
        self._draggable = False

    def isDraggable(self):
        """Returns true if image is draggable

        :rtype: bool
        """
        return self._draggable

    def _setDraggable(self, draggable):  # TODO support update
        """Set if image is draggable or not.

        This is private for not as it does not support update.

        :param bool draggable:
        """
        self._draggable = bool(draggable)

    def drag(self, from_, to):
        """Perform a drag of the item.

        :param List[float] from_: (x, y) previous position in data coordinates
        :param List[float] to: (x, y) current position in data coordinates
        """
        raise NotImplementedError("Must be implemented in subclass")


class ColormapMixIn(ItemMixInBase):
    """Mix-in class for items with colormap"""

    def __init__(self):
        self._colormap = Colormap()
        self._colormap.sigChanged.connect(self._colormapChanged)
        self.__data = None
        self.__cacheColormapRange = {}  # Store {normalization: range}

    def getColormap(self):
        """Return the used colormap"""
        return self._colormap

    def setColormap(self, colormap):
        """Set the colormap of this item

        :param silx.gui.colors.Colormap colormap: colormap description
        """
        if self._colormap is colormap:
            return
        if isinstance(colormap, dict):
            colormap = Colormap._fromDict(colormap)

        if self._colormap is not None:
            self._colormap.sigChanged.disconnect(self._colormapChanged)
        self._colormap = colormap
        if self._colormap is not None:
            self._colormap.sigChanged.connect(self._colormapChanged)
        self._colormapChanged()

    def _colormapChanged(self):
        """Handle updates of the colormap"""
        self._updated(ItemChangedType.COLORMAP)

    def _setColormappedData(self, data, copy=True,
                            min_=None, minPositive=None, max_=None):
        """Set the data used to compute the colormapped display.

        It also resets the cache of data ranges.

        This method MUST be called by inheriting classes when data is updated.

        :param Union[None,numpy.ndarray] data:
        :param Union[None,float] min_: Minimum value of the data
        :param Union[None,float] minPositive:
            Minimum of strictly positive values of the data
        :param Union[None,float] max_: Maximum value of the data
        """
        self.__data = None if data is None else numpy.array(data, copy=copy)
        self.__cacheColormapRange = {}  # Reset cache

        # Fill-up colormap range cache if values are provided
        if max_ is not None and numpy.isfinite(max_):
            if min_ is not None and numpy.isfinite(min_):
                self.__cacheColormapRange[Colormap.LINEAR, Colormap.MINMAX] = min_, max_
            if minPositive is not None and numpy.isfinite(minPositive):
                self.__cacheColormapRange[Colormap.LOGARITHM, Colormap.MINMAX] = minPositive, max_

        colormap = self.getColormap()
        if None in (colormap.getVMin(), colormap.getVMax()):
            self._colormapChanged()

    def getColormappedData(self, copy=True):
        """Returns the data used to compute the displayed colors

        :param bool copy: True to get a copy,
            False to get internal data (do not modify!).
        :rtype: Union[None,numpy.ndarray]
        """
        if self.__data is None:
            return None
        else:
            return numpy.array(self.__data, copy=copy)

    def _getColormapAutoscaleRange(self, colormap=None):
        """Returns the autoscale range for current data and colormap.

        :param Union[None,~silx.gui.colors.Colormap] colormap:
           The colormap for which to compute the autoscale range.
           If None, the default, the colormap of the item is used
        :return: (vmin, vmax) range (vmin and /or vmax might be `None`)
        """
        if colormap is None:
            colormap = self.getColormap()

        data = self.getColormappedData(copy=False)
        if colormap is None or data is None:
            return None, None

        normalization = colormap.getNormalization()
        autoscaleMode = colormap.getAutoscaleMode()
        key = normalization, autoscaleMode
        vRange = self.__cacheColormapRange.get(key, None)
        if vRange is None:
            vRange = colormap._computeAutoscaleRange(data)
            self.__cacheColormapRange[key] = vRange
        return vRange


class SymbolMixIn(ItemMixInBase):
    """Mix-in class for items with symbol type"""

    _DEFAULT_SYMBOL = None
    """Default marker of the item"""

    _DEFAULT_SYMBOL_SIZE = config.DEFAULT_PLOT_SYMBOL_SIZE
    """Default marker size of the item"""

    _SUPPORTED_SYMBOLS = collections.OrderedDict((
        ('o', 'Circle'),
        ('d', 'Diamond'),
        ('s', 'Square'),
        ('+', 'Plus'),
        ('x', 'Cross'),
        ('.', 'Point'),
        (',', 'Pixel'),
        ('|', 'Vertical line'),
        ('_', 'Horizontal line'),
        ('tickleft', 'Tick left'),
        ('tickright', 'Tick right'),
        ('tickup', 'Tick up'),
        ('tickdown', 'Tick down'),
        ('caretleft', 'Caret left'),
        ('caretright', 'Caret right'),
        ('caretup', 'Caret up'),
        ('caretdown', 'Caret down'),
        (u'\u2665', 'Heart'),
        ('', 'None')))
    """Dict of supported symbols"""

    def __init__(self):
        if self._DEFAULT_SYMBOL is None:  # Use default from config
            self._symbol = config.DEFAULT_PLOT_SYMBOL
        else:
            self._symbol = self._DEFAULT_SYMBOL

        if self._DEFAULT_SYMBOL_SIZE is None:  # Use default from config
            self._symbol_size = config.DEFAULT_PLOT_SYMBOL_SIZE
        else:
            self._symbol_size = self._DEFAULT_SYMBOL_SIZE

    @classmethod
    def getSupportedSymbols(cls):
        """Returns the list of supported symbol names.

        :rtype: tuple of str
        """
        return tuple(cls._SUPPORTED_SYMBOLS.keys())

    @classmethod
    def getSupportedSymbolNames(cls):
        """Returns the list of supported symbol human-readable names.

        :rtype: tuple of str
        """
        return tuple(cls._SUPPORTED_SYMBOLS.values())

    def getSymbolName(self, symbol=None):
        """Returns human-readable name for a symbol.

        :param str symbol: The symbol from which to get the name.
                           Default: current symbol.
        :rtype: str
        :raise KeyError: if symbol is not in :meth:`getSupportedSymbols`.
        """
        if symbol is None:
            symbol = self.getSymbol()
        return self._SUPPORTED_SYMBOLS[symbol]

    def getSymbol(self):
        """Return the point marker type.

        Marker type::

            - 'o' circle
            - '.' point
            - ',' pixel
            - '+' cross
            - 'x' x-cross
            - 'd' diamond
            - 's' square

        :rtype: str
        """
        return self._symbol

    def setSymbol(self, symbol):
        """Set the marker type

        See :meth:`getSymbol`.

        :param str symbol: Marker type or marker name
        """
        if symbol is None:
            symbol = self._DEFAULT_SYMBOL

        elif symbol not in self.getSupportedSymbols():
            for symbolCode, name in self._SUPPORTED_SYMBOLS.items():
                if name.lower() == symbol.lower():
                    symbol = symbolCode
                    break
            else:
                raise ValueError('Unsupported symbol %s' % str(symbol))

        if symbol != self._symbol:
            self._symbol = symbol
            self._updated(ItemChangedType.SYMBOL)

    def getSymbolSize(self):
        """Return the point marker size in points.

        :rtype: float
        """
        return self._symbol_size

    def setSymbolSize(self, size):
        """Set the point marker size in points.

        See :meth:`getSymbolSize`.

        :param str symbol: Marker type
        """
        if size is None:
            size = self._DEFAULT_SYMBOL_SIZE
        if size != self._symbol_size:
            self._symbol_size = size
            self._updated(ItemChangedType.SYMBOL_SIZE)


class LineMixIn(ItemMixInBase):
    """Mix-in class for item with line"""

    _DEFAULT_LINEWIDTH = 1.
    """Default line width"""

    _DEFAULT_LINESTYLE = '-'
    """Default line style"""

    _SUPPORTED_LINESTYLE = '', ' ', '-', '--', '-.', ':', None
    """Supported line styles"""

    def __init__(self):
        self._linewidth = self._DEFAULT_LINEWIDTH
        self._linestyle = self._DEFAULT_LINESTYLE

    @classmethod
    def getSupportedLineStyles(cls):
        """Returns list of supported line styles.

        :rtype: List[str,None]
        """
        return cls._SUPPORTED_LINESTYLE

    def getLineWidth(self):
        """Return the curve line width in pixels

        :rtype: float
        """
        return self._linewidth

    def setLineWidth(self, width):
        """Set the width in pixel of the curve line

        See :meth:`getLineWidth`.

        :param float width: Width in pixels
        """
        width = float(width)
        if width != self._linewidth:
            self._linewidth = width
            self._updated(ItemChangedType.LINE_WIDTH)

    def getLineStyle(self):
        """Return the type of the line

        Type of line::

            - ' '  no line
            - '-'  solid line
            - '--' dashed line
            - '-.' dash-dot line
            - ':'  dotted line

        :rtype: str
        """
        return self._linestyle

    def setLineStyle(self, style):
        """Set the style of the curve line.

        See :meth:`getLineStyle`.

        :param str style: Line style
        """
        style = str(style)
        assert style in self.getSupportedLineStyles()
        if style is None:
            style = self._DEFAULT_LINESTYLE
        if style != self._linestyle:
            self._linestyle = style
            self._updated(ItemChangedType.LINE_STYLE)


class ColorMixIn(ItemMixInBase):
    """Mix-in class for item with color"""

    _DEFAULT_COLOR = (0., 0., 0., 1.)
    """Default color of the item"""

    def __init__(self):
        self._color = self._DEFAULT_COLOR

    def getColor(self):
        """Returns the RGBA color of the item

        :rtype: 4-tuple of float in [0, 1] or array of colors
        """
        return self._color

    def setColor(self, color, copy=True):
        """Set item color

        :param color: color(s) to be used
        :type color: str ("#RRGGBB") or (npoints, 4) unsigned byte array or
                     one of the predefined color names defined in colors.py
        :param bool copy: True (Default) to get a copy,
                         False to use internal representation (do not modify!)
        """
        if isinstance(color, six.string_types):
            color = colors.rgba(color)
        elif isinstance(color, qt.QColor):
            color = colors.rgba(color)
        else:
            color = numpy.array(color, copy=copy)
            # TODO more checks + improve color array support
            if color.ndim == 1:  # Single RGBA color
                color = colors.rgba(color)
            else:  # Array of colors
                assert color.ndim == 2

        self._color = color
        self._updated(ItemChangedType.COLOR)


class YAxisMixIn(ItemMixInBase):
    """Mix-in class for item with yaxis"""

    _DEFAULT_YAXIS = 'left'
    """Default Y axis the item belongs to"""

    def __init__(self):
        self._yaxis = self._DEFAULT_YAXIS

    def getYAxis(self):
        """Returns the Y axis this curve belongs to.

        Either 'left' or 'right'.

        :rtype: str
        """
        return self._yaxis

    def setYAxis(self, yaxis):
        """Set the Y axis this curve belongs to.

        :param str yaxis: 'left' or 'right'
        """
        yaxis = str(yaxis)
        assert yaxis in ('left', 'right')
        if yaxis != self._yaxis:
            self._yaxis = yaxis
            self._updated(ItemChangedType.YAXIS)


class FillMixIn(ItemMixInBase):
    """Mix-in class for item with fill"""

    def __init__(self):
        self._fill = False

    def isFill(self):
        """Returns whether the item is filled or not.

        :rtype: bool
        """
        return self._fill

    def setFill(self, fill):
        """Set whether to fill the item or not.

        :param bool fill:
        """
        fill = bool(fill)
        if fill != self._fill:
            self._fill = fill
            self._updated(ItemChangedType.FILL)


class AlphaMixIn(ItemMixInBase):
    """Mix-in class for item with opacity"""

    def __init__(self):
        self._alpha = 1.

    def getAlpha(self):
        """Returns the opacity of the item

        :rtype: float in [0, 1.]
        """
        return self._alpha

    def setAlpha(self, alpha):
        """Set the opacity of the item

        .. note::

            If the colormap already has some transparency, this alpha
            adds additional transparency. The alpha channel of the colormap
            is multiplied by this value.

        :param alpha: Opacity of the item, between 0 (full transparency)
            and 1. (full opacity)
        :type alpha: float
        """
        alpha = float(alpha)
        alpha = max(0., min(alpha, 1.))  # Clip alpha to [0., 1.] range
        if alpha != self._alpha:
            self._alpha = alpha
            self._updated(ItemChangedType.ALPHA)


class ComplexMixIn(ItemMixInBase):
    """Mix-in class for complex data mode"""

    _SUPPORTED_COMPLEX_MODES = None
    """Override to only support a subset of all ComplexMode"""

    class ComplexMode(_Enum):
        """Identify available display mode for complex"""
        NONE = 'none'
        ABSOLUTE = 'amplitude'
        PHASE = 'phase'
        REAL = 'real'
        IMAGINARY = 'imaginary'
        AMPLITUDE_PHASE = 'amplitude_phase'
        LOG10_AMPLITUDE_PHASE = 'log10_amplitude_phase'
        SQUARE_AMPLITUDE = 'square_amplitude'

    def __init__(self):
        self.__complex_mode = self.ComplexMode.ABSOLUTE

    def getComplexMode(self):
        """Returns the current complex visualization mode.

        :rtype: ComplexMode
        """
        return self.__complex_mode

    def setComplexMode(self, mode):
        """Set the complex visualization mode.

        :param ComplexMode mode: The visualization mode in:
            'real', 'imaginary', 'phase', 'amplitude'
        :return: True if value was set, False if is was already set
        :rtype: bool
        """
        mode = self.ComplexMode.from_value(mode)
        assert mode in self.supportedComplexModes()

        if mode != self.__complex_mode:
            self.__complex_mode = mode
            self._updated(ItemChangedType.COMPLEX_MODE)
            return True
        else:
            return False

    def _convertComplexData(self, data, mode=None):
        """Convert complex data to the specific mode.

        :param Union[ComplexMode,None] mode:
            The kind of value to compute.
            If None (the default), the current complex mode is used.
        :return: The converted dataset
        :rtype: Union[numpy.ndarray[float],None]
        """
        if data is None:
            return None

        if mode is None:
            mode = self.getComplexMode()

        if mode is self.ComplexMode.REAL:
            return numpy.real(data)
        elif mode is self.ComplexMode.IMAGINARY:
            return numpy.imag(data)
        elif mode is self.ComplexMode.ABSOLUTE:
            return numpy.absolute(data)
        elif mode is self.ComplexMode.PHASE:
            return numpy.angle(data)
        elif mode is self.ComplexMode.SQUARE_AMPLITUDE:
            return numpy.absolute(data) ** 2
        else:
            raise ValueError('Unsupported conversion mode: %s', str(mode))

    @classmethod
    def supportedComplexModes(cls):
        """Returns the list of supported complex visualization modes.

        See :class:`ComplexMode` and :meth:`setComplexMode`.

        :rtype: List[ComplexMode]
        """
        if cls._SUPPORTED_COMPLEX_MODES is None:
            return cls.ComplexMode.members()
        else:
            return cls._SUPPORTED_COMPLEX_MODES


class ScatterVisualizationMixIn(ItemMixInBase):
    """Mix-in class for scatter plot visualization modes"""

    _SUPPORTED_SCATTER_VISUALIZATION = None
    """Allows to override supported Visualizations"""

    @enum.unique
    class Visualization(_Enum):
        """Different modes of scatter plot visualizations"""

        POINTS = 'points'
        """Display scatter plot as a point cloud"""

        LINES = 'lines'
        """Display scatter plot as a wireframe.

        This is based on Delaunay triangulation
        """

        SOLID = 'solid'
        """Display scatter plot as a set of filled triangles.

        This is based on Delaunay triangulation
        """

        REGULAR_GRID = 'regular_grid'
        """Display scatter plot as an image.

        It expects the points to be the intersection of a regular grid,
        and the order of points following that of an image.
        First line, then second one, and always in the same direction
        (either all lines from left to right or all from right to left).
        """

        IRREGULAR_GRID = 'irregular_grid'
        """Display scatter plot as contiguous quadrilaterals.

        It expects the points to be the intersection of an irregular grid,
        and the order of points following that of an image.
        First line, then second one, and always in the same direction
        (either all lines from left to right or all from right to left).
        """

        BINNED_STATISTIC = 'binned_statistic'
        """Display scatter plot as 2D binned statistic (i.e., generalized histogram).
        """

    @enum.unique
    class VisualizationParameter(_Enum):
        """Different parameter names for scatter plot visualizations"""

        GRID_MAJOR_ORDER = 'grid_major_order'
        """The major order of points in the regular grid.

        Either 'row' (row-major, fast X) or 'column' (column-major, fast Y).
        """

        GRID_BOUNDS = 'grid_bounds'
        """The expected range in data coordinates of the regular grid.

        A 2-tuple of 2-tuple: (begin (x, y), end (x, y)).
        This provides the data coordinates of the first point and the expected
        last on.
        As for `GRID_SHAPE`, this can be wider than the current data.
        """

        GRID_SHAPE = 'grid_shape'
        """The expected size of the regular grid (height, width).

        The given shape can be wider than the number of points,
        in which case the grid is not fully filled.
        """

        BINNED_STATISTIC_SHAPE = 'binned_statistic_shape'
        """The number of bins in each dimension (height, width).
        """

        BINNED_STATISTIC_FUNCTION = 'binned_statistic_function'
        """The reduction function to apply to each bin (str).

        Available reduction functions are: 'mean' (default), 'count', 'sum'.
        """

    _SUPPORTED_VISUALIZATION_PARAMETER_VALUES = {
        VisualizationParameter.GRID_MAJOR_ORDER: ('row', 'column'),
        VisualizationParameter.BINNED_STATISTIC_FUNCTION: ('mean', 'count', 'sum'),
    }
    """Supported visualization parameter values.

    Defined for parameters with a set of acceptable values.
    """

    def __init__(self):
        self.__visualization = self.Visualization.POINTS
        self.__parameters = dict(  # Init parameters to None
            (parameter, None) for parameter in self.VisualizationParameter)
        self.__parameters[self.VisualizationParameter.BINNED_STATISTIC_FUNCTION] = 'mean'

    @classmethod
    def supportedVisualizations(cls):
        """Returns the list of supported scatter visualization modes.

        See :meth:`setVisualization`

        :rtype: List[Visualization]
        """
        if cls._SUPPORTED_SCATTER_VISUALIZATION is None:
            return cls.Visualization.members()
        else:
            return cls._SUPPORTED_SCATTER_VISUALIZATION

    @classmethod
    def supportedVisualizationParameterValues(cls, parameter):
        """Returns the list of supported scatter visualization modes.

        See :meth:`VisualizationParameters`

        :param VisualizationParameter parameter:
            This parameter for which to retrieve the supported values.
        :returns: tuple of supported of values or None if not defined.
        """
        parameter = cls.VisualizationParameter(parameter)
        return cls._SUPPORTED_VISUALIZATION_PARAMETER_VALUES.get(
            parameter, None)

    def setVisualization(self, mode):
        """Set the scatter plot visualization mode to use.

        See :class:`Visualization` for all possible values,
        and :meth:`supportedVisualizations` for supported ones.

        :param Union[str,Visualization] mode:
            The visualization mode to use.
        :return: True if value was set, False if is was already set
        :rtype: bool
        """
        mode = self.Visualization.from_value(mode)
        assert mode in self.supportedVisualizations()

        if mode != self.__visualization:
            self.__visualization = mode

            self._updated(ItemChangedType.VISUALIZATION_MODE)
            return True
        else:
            return False

    def getVisualization(self):
        """Returns the scatter plot visualization mode in use.

        :rtype: Visualization
        """
        return self.__visualization

    def setVisualizationParameter(self, parameter, value=None):
        """Set the given visualization parameter.

        :param Union[str,VisualizationParameter] parameter:
            The name of the parameter to set
        :param value: The value to use for this parameter
            Set to None to automatically set the parameter
        :raises ValueError: If parameter is not supported
        :return: True if parameter was set, False if is was already set
        :rtype: bool
        :raise ValueError: If value is not supported
        """
        parameter = self.VisualizationParameter.from_value(parameter)

        if self.__parameters[parameter] != value:
            validValues = self.supportedVisualizationParameterValues(parameter)
            if validValues is not None and value not in validValues:
                raise ValueError("Unsupported parameter value: %s" % str(value))

            self.__parameters[parameter] = value
            self._updated(ItemChangedType.VISUALIZATION_MODE)
            return True
        return False

    def getVisualizationParameter(self, parameter):
        """Returns the value of the given visualization parameter.

        This method returns the parameter as set by
        :meth:`setVisualizationParameter`.

        :param parameter: The name of the parameter to retrieve
        :returns: The value previously set or None if automatically set
        :raises ValueError: If parameter is not supported
        """
        if parameter not in self.VisualizationParameter:
            raise ValueError("parameter not supported: %s", parameter)

        return self.__parameters[parameter]

    def getCurrentVisualizationParameter(self, parameter):
        """Returns the current value of the given visualization parameter.

        If the parameter was set by :meth:`setVisualizationParameter` to
        a value that is not None, this value is returned;
        else the current value that is automatically computed is returned.

        :param parameter: The name of the parameter to retrieve
        :returns: The current value (either set or automatically computed)
        :raises ValueError: If parameter is not supported
        """
        # Override in subclass to provide automatically computed parameters
        return self.getVisualizationParameter(parameter)


class PointsBase(Item, SymbolMixIn, AlphaMixIn):
    """Base class for :class:`Curve` and :class:`Scatter`"""
    # note: _logFilterData must be overloaded if you overload
    #       getData to change its signature

    _DEFAULT_Z_LAYER = 1
    """Default overlay layer for points,
    on top of images."""

    def __init__(self):
        Item.__init__(self)
        SymbolMixIn.__init__(self)
        AlphaMixIn.__init__(self)
        self._x = ()
        self._y = ()
        self._xerror = None
        self._yerror = None

        # Store filtered data for x > 0 and/or y > 0
        self._filteredCache = {}
        self._clippedCache = {}

        # Store bounds depending on axes filtering >0:
        # key is (isXPositiveFilter, isYPositiveFilter)
        self._boundsCache = {}

    @staticmethod
    def _logFilterError(value, error):
        """Filter/convert error values if they go <= 0.

        Replace error leading to negative values by nan

        :param numpy.ndarray value: 1D array of values
        :param numpy.ndarray error:
            Array of errors: scalar, N, Nx1 or 2xN or None.
        :return: Filtered error so error bars are never negative
        """
        if error is not None:
            # Convert Nx1 to N
            if error.ndim == 2 and error.shape[1] == 1 and len(value) != 1:
                error = numpy.ravel(error)

            # Supports error being scalar, N or 2xN array
            valueMinusError = value - numpy.atleast_2d(error)[0]
            errorClipped = numpy.isnan(valueMinusError)
            mask = numpy.logical_not(errorClipped)
            errorClipped[mask] = valueMinusError[mask] <= 0

            if numpy.any(errorClipped):  # Need filtering

                # expand errorbars to 2xN
                if error.size == 1:  # Scalar
                    error = numpy.full(
                        (2, len(value)), error, dtype=numpy.float)

                elif error.ndim == 1:  # N array
                    newError = numpy.empty((2, len(value)),
                                           dtype=numpy.float)
                    newError[0, :] = error
                    newError[1, :] = error
                    error = newError

                elif error.size == 2 * len(value):  # 2xN array
                    error = numpy.array(
                        error, copy=True, dtype=numpy.float)

                else:
                    _logger.error("Unhandled error array")
                    return error

                error[0, errorClipped] = numpy.nan

        return error

    def _getClippingBoolArray(self, xPositive, yPositive):
        """Compute a boolean array to filter out points with negative
        coordinates on log axes.

        :param bool xPositive: True to filter arrays according to X coords.
        :param bool yPositive: True to filter arrays according to Y coords.
        :rtype: boolean numpy.ndarray
        """
        assert xPositive or yPositive
        if (xPositive, yPositive) not in self._clippedCache:
            xclipped, yclipped = False, False

            if xPositive:
                x = self.getXData(copy=False)
                with numpy.errstate(invalid='ignore'):  # Ignore NaN warnings
                    xclipped = x <= 0

            if yPositive:
                y = self.getYData(copy=False)
                with numpy.errstate(invalid='ignore'):  # Ignore NaN warnings
                    yclipped = y <= 0

            self._clippedCache[(xPositive, yPositive)] = \
                numpy.logical_or(xclipped, yclipped)
        return self._clippedCache[(xPositive, yPositive)]

    def _logFilterData(self, xPositive, yPositive):
        """Filter out values with x or y <= 0 on log axes

        :param bool xPositive: True to filter arrays according to X coords.
        :param bool yPositive: True to filter arrays according to Y coords.
        :return: The filter arrays or unchanged object if filtering not needed
        :rtype: (x, y, xerror, yerror)
        """
        x = self.getXData(copy=False)
        y = self.getYData(copy=False)
        xerror = self.getXErrorData(copy=False)
        yerror = self.getYErrorData(copy=False)

        if xPositive or yPositive:
            clipped = self._getClippingBoolArray(xPositive, yPositive)

            if numpy.any(clipped):
                # copy to keep original array and convert to float
                x = numpy.array(x, copy=True, dtype=numpy.float)
                x[clipped] = numpy.nan
                y = numpy.array(y, copy=True, dtype=numpy.float)
                y[clipped] = numpy.nan

                if xPositive and xerror is not None:
                    xerror = self._logFilterError(x, xerror)

                if yPositive and yerror is not None:
                    yerror = self._logFilterError(y, yerror)

        return x, y, xerror, yerror

    def _getBounds(self):
        if self.getXData(copy=False).size == 0:  # Empty data
            return None

        plot = self.getPlot()
        if plot is not None:
            xPositive = plot.getXAxis()._isLogarithmic()
            yPositive = plot.getYAxis()._isLogarithmic()
        else:
            xPositive = False
            yPositive = False

        # TODO bounds do not take error bars into account
        if (xPositive, yPositive) not in self._boundsCache:
            # use the getData class method because instance method can be
            # overloaded to return additional arrays
            data = PointsBase.getData(self, copy=False, displayed=True)
            if len(data) == 5:
                # hack to avoid duplicating caching mechanism in Scatter
                # (happens when cached data is used, caching done using
                # Scatter._logFilterData)
                x, y, _xerror, _yerror = data[0], data[1], data[3], data[4]
            else:
                x, y, _xerror, _yerror = data

            with warnings.catch_warnings():
                warnings.simplefilter('ignore', category=RuntimeWarning)
                # Ignore All-NaN slice encountered
                self._boundsCache[(xPositive, yPositive)] = (
                    numpy.nanmin(x),
                    numpy.nanmax(x),
                    numpy.nanmin(y),
                    numpy.nanmax(y)
                )
        return self._boundsCache[(xPositive, yPositive)]

    def _getCachedData(self):
        """Return cached filtered data if applicable,
        i.e. if any axis is in log scale.
        Return None if caching is not applicable."""
        plot = self.getPlot()
        if plot is not None:
            xPositive = plot.getXAxis()._isLogarithmic()
            yPositive = plot.getYAxis()._isLogarithmic()
            if xPositive or yPositive:
                # At least one axis has log scale, filter data
                if (xPositive, yPositive) not in self._filteredCache:
                    self._filteredCache[(xPositive, yPositive)] = \
                        self._logFilterData(xPositive, yPositive)
                return self._filteredCache[(xPositive, yPositive)]
        return None

    def getData(self, copy=True, displayed=False):
        """Returns the x, y values of the curve points and xerror, yerror

        :param bool copy: True (Default) to get a copy,
                         False to use internal representation (do not modify!)
        :param bool displayed: True to only get curve points that are displayed
                               in the plot. Default: False
                               Note: If plot has log scale, negative points
                               are not displayed.
        :returns: (x, y, xerror, yerror)
        :rtype: 4-tuple of numpy.ndarray
        """
        if displayed:  # filter data according to plot state
            cached_data = self._getCachedData()
            if cached_data is not None:
                return cached_data

        return (self.getXData(copy),
                self.getYData(copy),
                self.getXErrorData(copy),
                self.getYErrorData(copy))

    def getXData(self, copy=True):
        """Returns the x coordinates of the data points

        :param copy: True (Default) to get a copy,
                     False to use internal representation (do not modify!)
        :rtype: numpy.ndarray
        """
        return numpy.array(self._x, copy=copy)

    def getYData(self, copy=True):
        """Returns the y coordinates of the data points

        :param copy: True (Default) to get a copy,
                     False to use internal representation (do not modify!)
        :rtype: numpy.ndarray
        """
        return numpy.array(self._y, copy=copy)

    def getXErrorData(self, copy=True):
        """Returns the x error of the points

        :param copy: True (Default) to get a copy,
                     False to use internal representation (do not modify!)
        :rtype: numpy.ndarray, float or None
        """
        if isinstance(self._xerror, numpy.ndarray):
            return numpy.array(self._xerror, copy=copy)
        else:
            return self._xerror  # float or None

    def getYErrorData(self, copy=True):
        """Returns the y error of the points

        :param copy: True (Default) to get a copy,
                     False to use internal representation (do not modify!)
        :rtype: numpy.ndarray, float or None
        """
        if isinstance(self._yerror, numpy.ndarray):
            return numpy.array(self._yerror, copy=copy)
        else:
            return self._yerror  # float or None

    def setData(self, x, y, xerror=None, yerror=None, copy=True):
        """Set the data of the curve.

        :param numpy.ndarray x: The data corresponding to the x coordinates.
        :param numpy.ndarray y: The data corresponding to the y coordinates.
        :param xerror: Values with the uncertainties on the x values
        :type xerror: A float, or a numpy.ndarray of float32.
                      If it is an array, it can either be a 1D array of
                      same length as the data or a 2D array with 2 rows
                      of same length as the data: row 0 for positive errors,
                      row 1 for negative errors.
        :param yerror: Values with the uncertainties on the y values.
        :type yerror: A float, or a numpy.ndarray of float32. See xerror.
        :param bool copy: True make a copy of the data (default),
                          False to use provided arrays.
        """
        x = numpy.array(x, copy=copy)
        y = numpy.array(y, copy=copy)
        assert len(x) == len(y)
        assert x.ndim == y.ndim == 1

        if xerror is not None:
            if isinstance(xerror, abc.Iterable):
                xerror = numpy.array(xerror, copy=copy)
            else:
                xerror = float(xerror)
        if yerror is not None:
            if isinstance(yerror, abc.Iterable):
                yerror = numpy.array(yerror, copy=copy)
            else:
                yerror = float(yerror)
        # TODO checks on xerror, yerror
        self._x, self._y = x, y
        self._xerror, self._yerror = xerror, yerror

        self._boundsCache = {}  # Reset cached bounds
        self._filteredCache = {}  # Reset cached filtered data
        self._clippedCache = {}  # Reset cached clipped bool array

        # TODO hackish data range implementation
        if self.isVisible():
            plot = self.getPlot()
            if plot is not None:
                plot._invalidateDataRange()
        self._updated(ItemChangedType.DATA)


class BaselineMixIn(object):
    """Base class for Baseline mix-in"""
    def __init__(self, baseline=None):
        self._baseline = baseline

    def _setBaseline(self, baseline):
        """
        Set baseline value

        :param baseline: baseline value(s)
        :type: Union[None,float,numpy.ndarray]
        """
        if (isinstance(baseline, abc.Iterable)):
            baseline = numpy.array(baseline)
        self._baseline = baseline

    def getBaseline(self, copy=True):
        """

        :param bool copy:
        :return: histogram baseline
        :rtype: Union[None,float,numpy.ndarray]
        """
        if isinstance(self._baseline, numpy.ndarray):
            return numpy.array(self._baseline, copy=True)
        else:
            return self._baseline


class _Style:
    """Object which store styles"""


class HighlightedMixIn(ItemMixInBase):

    def __init__(self):
        self._highlightStyle = self._DEFAULT_HIGHLIGHT_STYLE
        self._highlighted = False

    def isHighlighted(self):
        """Returns True if curve is highlighted.

        :rtype: bool
        """
        return self._highlighted

    def setHighlighted(self, highlighted):
        """Set the highlight state of the curve

        :param bool highlighted:
        """
        highlighted = bool(highlighted)
        if highlighted != self._highlighted:
            self._highlighted = highlighted
            # TODO inefficient: better to use backend's setCurveColor
            self._updated(ItemChangedType.HIGHLIGHTED)

    def getHighlightedStyle(self):
        """Returns the highlighted style in use

        :rtype: CurveStyle
        """
        return self._highlightStyle

    def setHighlightedStyle(self, style):
        """Set the style to use for highlighting

        :param CurveStyle style: New style to use
        """
        previous = self.getHighlightedStyle()
        if style != previous:
            assert isinstance(style, _Style)
            self._highlightStyle = style
            self._updated(ItemChangedType.HIGHLIGHTED_STYLE)

            # Backward compatibility event
            if previous.getColor() != style.getColor():
                self._updated(ItemChangedType.HIGHLIGHTED_COLOR)