summaryrefslogtreecommitdiff
path: root/silx/gui/plot/items/roi.py
blob: 65831bef2b1a424a3c4d7b31b6e51caebf04ad79 (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
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2018 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 ROI item for the :class:`~silx.gui.plot.PlotWidget`.
"""

__authors__ = ["T. Vincent"]
__license__ = "MIT"
__date__ = "28/06/2018"


import functools
import itertools
import logging
import collections
import numpy

from ....utils.weakref import WeakList
from ... import qt
from .. import items
from ...colors import rgba


logger = logging.getLogger(__name__)


class RegionOfInterest(qt.QObject):
    """Object describing a region of interest in a plot.

    :param QObject parent:
        The RegionOfInterestManager that created this object
    """

    _kind = None
    """Label for this kind of ROI.

    Should be setted by inherited classes to custom the ROI manager widget.
    """

    sigRegionChanged = qt.Signal()
    """Signal emitted everytime the shape or position of the ROI changes"""

    def __init__(self, parent=None):
        # Avoid circular dependancy
        from ..tools import roi as roi_tools
        assert parent is None or isinstance(parent, roi_tools.RegionOfInterestManager)
        qt.QObject.__init__(self, parent)
        self._color = rgba('red')
        self._items = WeakList()
        self._editAnchors = WeakList()
        self._points = None
        self._label = ''
        self._labelItem = None
        self._editable = False
        self._visible = True

    def __del__(self):
        # Clean-up plot items
        self._removePlotItems()

    def setParent(self, parent):
        """Set the parent of the RegionOfInterest

        :param Union[None,RegionOfInterestManager] parent:
        """
        # Avoid circular dependancy
        from ..tools import roi as roi_tools
        if (parent is not None and not isinstance(parent, roi_tools.RegionOfInterestManager)):
            raise ValueError('Unsupported parent')

        self._removePlotItems()
        super(RegionOfInterest, self).setParent(parent)
        self._createPlotItems()

    @classmethod
    def _getKind(cls):
        """Return an human readable kind of ROI

        :rtype: str
        """
        return cls._kind

    def getColor(self):
        """Returns the color of this ROI

        :rtype: QColor
        """
        return qt.QColor.fromRgbF(*self._color)

    def _getAnchorColor(self, color):
        """Returns the anchor color from the base ROI color

        :param Union[numpy.array,Tuple,List]: color
        :rtype: Union[numpy.array,Tuple,List]
        """
        return color[:3] + (0.5,)

    def setColor(self, color):
        """Set the color used for this ROI.

        :param color: The color to use for ROI shape as
           either a color name, a QColor, a list of uint8 or float in [0, 1].
        """
        color = rgba(color)
        if color != self._color:
            self._color = color

            # Update color of shape items in the plot
            rgbaColor = rgba(color)
            for item in list(self._items):
                if isinstance(item, items.ColorMixIn):
                    item.setColor(rgbaColor)
            item = self._getLabelItem()
            if isinstance(item, items.ColorMixIn):
                item.setColor(rgbaColor)

            rgbaColor = self._getAnchorColor(rgbaColor)
            for item in list(self._editAnchors):
                if isinstance(item, items.ColorMixIn):
                    item.setColor(rgbaColor)

    def getLabel(self):
        """Returns the label displayed for this ROI.

        :rtype: str
        """
        return self._label

    def setLabel(self, label):
        """Set the label displayed with this ROI.

        :param str label: The text label to display
        """
        label = str(label)
        if label != self._label:
            self._label = label
            self._updateLabelItem(label)

    def isEditable(self):
        """Returns whether the ROI is editable by the user or not.

        :rtype: bool
        """
        return self._editable

    def setEditable(self, editable):
        """Set whether the ROI can be changed interactively.

        :param bool editable: True to allow edition by the user,
           False to disable.
        """
        editable = bool(editable)
        if self._editable != editable:
            self._editable = editable
            # Recreate plot items
            # This can be avoided once marker.setDraggable is public
            self._createPlotItems()

    def isVisible(self):
        """Returns whether the ROI is visible in the plot.

        .. note::
            This does not take into account whether or not the plot
            widget itself is visible (unlike :meth:`QWidget.isVisible` which
            checks the visibility of all its parent widgets up to the window)

        :rtype: bool
        """
        return self._visible

    def setVisible(self, visible):
        """Set whether the plot items associated with this ROI are
        visible in the plot.

        :param bool visible: True to show the ROI in the plot, False to
            hide it.
        """
        visible = bool(visible)
        if self._visible == visible:
            return
        self._visible = visible
        if self._labelItem is not None:
            self._labelItem.setVisible(visible)
        for item in self._items + self._editAnchors:
            item.setVisible(visible)

    def _getControlPoints(self):
        """Returns the current ROI control points.

        It returns an empty tuple if there is currently no ROI.

        :return: Array of (x, y) position in plot coordinates
        :rtype: numpy.ndarray
        """
        return None if self._points is None else numpy.array(self._points)

    @classmethod
    def showFirstInteractionShape(cls):
        """Returns True if the shape created by the first interaction and
        managed by the plot have to be visible.

        :rtype: bool
        """
        return True

    @classmethod
    def getFirstInteractionShape(cls):
        """Returns the shape kind which will be used by the very first
        interaction with the plot.

        This interactions are hardcoded inside the plot

        :rtype: str
        """
        return cls._plotShape

    def setFirstShapePoints(self, points):
        """"Initialize the ROI using the points from the first interaction.

        This interaction is constrained by the plot API and only supports few
        shapes.
        """
        points = self._createControlPointsFromFirstShape(points)
        self._setControlPoints(points)

    def _createControlPointsFromFirstShape(self, points):
        """Returns the list of control points from the very first shape
        provided.

        This shape is provided by the plot interaction and constained by the
        class of the ROI itself.
        """
        return points

    def _setControlPoints(self, points):
        """Set this ROI control points.

        :param points: Iterable of (x, y) control points
        """
        points = numpy.array(points)

        nbPointsChanged = (self._points is None or
                           points.shape != self._points.shape)

        if nbPointsChanged or not numpy.all(numpy.equal(points, self._points)):
            self._points = points

            self._updateShape()
            if self._items and not nbPointsChanged:  # Update plot items
                item = self._getLabelItem()
                if item is not None:
                    markerPos = self._getLabelPosition()
                    item.setPosition(*markerPos)

                if self._editAnchors:  # Update anchors
                    for anchor, point in zip(self._editAnchors, points):
                        old = anchor.blockSignals(True)
                        anchor.setPosition(*point)
                        anchor.blockSignals(old)

            else:  # No items or new point added
                # re-create plot items
                self._createPlotItems()

            self.sigRegionChanged.emit()

    def _updateShape(self):
        """Called when shape must be updated.

        Must be reimplemented if a shape item have to be updated.
        """
        return

    def _getLabelPosition(self):
        """Compute position of the label

        :return: (x, y) position of the marker
        """
        return None

    def _createPlotItems(self):
        """Create items displaying the ROI in the plot.

        It first removes any existing plot items.
        """
        roiManager = self.parent()
        if roiManager is None:
            return
        plot = roiManager.parent()

        self._removePlotItems()

        legendPrefix = "__RegionOfInterest-%d__" % id(self)
        itemIndex = 0

        controlPoints = self._getControlPoints()

        if self._labelItem is None:
            self._labelItem = self._createLabelItem()
            if self._labelItem is not None:
                self._labelItem._setLegend(legendPrefix + "label")
                plot._add(self._labelItem)
                self._labelItem.setVisible(self.isVisible())

        self._items = WeakList()
        plotItems = self._createShapeItems(controlPoints)
        for item in plotItems:
            item._setLegend(legendPrefix + str(itemIndex))
            plot._add(item)
            item.setVisible(self.isVisible())
            self._items.append(item)
            itemIndex += 1

        self._editAnchors = WeakList()
        if self.isEditable():
            plotItems = self._createAnchorItems(controlPoints)
            color = rgba(self.getColor())
            color = self._getAnchorColor(color)
            for index, item in enumerate(plotItems):
                item._setLegend(legendPrefix + str(itemIndex))
                item.setColor(color)
                item.setVisible(self.isVisible())
                plot._add(item)
                item.sigItemChanged.connect(functools.partial(
                    self._controlPointAnchorChanged, index))
                self._editAnchors.append(item)
                itemIndex += 1

    def _updateLabelItem(self, label):
        """Update the marker displaying the label.

        Inherite this method to custom the way the ROI display the label.

        :param str label: The new label to use
        """
        item = self._getLabelItem()
        if item is not None:
            item.setText(label)

    def _createLabelItem(self):
        """Returns a created marker which will be used to dipslay the label of
        this ROI.

        Inherite this method to return nothing if no new items have to be
        created, or your own marker.

        :rtype: Union[None,Marker]
        """
        # Add label marker
        markerPos = self._getLabelPosition()
        marker = items.Marker()
        marker.setPosition(*markerPos)
        marker.setText(self.getLabel())
        marker.setColor(rgba(self.getColor()))
        marker.setSymbol('')
        marker._setDraggable(False)
        return marker

    def _getLabelItem(self):
        """Returns the marker displaying the label of this ROI.

        Inherite this method to choose your own item. In case this item is also
        a control point.
        """
        return self._labelItem

    def _createShapeItems(self, points):
        """Create shape items from the current control points.

        :rtype: List[PlotItem]
        """
        return []

    def _createAnchorItems(self, points):
        """Create anchor items from the current control points.

        :rtype: List[Marker]
        """
        return []

    def _controlPointAnchorChanged(self, index, event):
        """Handle update of position of an edition anchor

        :param int index: Index of the anchor
        :param ItemChangedType event: Event type
        """
        if event == items.ItemChangedType.POSITION:
            anchor = self._editAnchors[index]
            previous = self._points[index].copy()
            current = anchor.getPosition()
            self._controlPointAnchorPositionChanged(index, current, previous)

    def _controlPointAnchorPositionChanged(self, index, current, previous):
        """Called when an anchor is manually edited.

        This function have to be inherited to change the behaviours of the
        control points. This function have to call :meth:`_getControlPoints` to
        reach the previous state of the control points. Updated the positions
        of the changed control points. Then call :meth:`_setControlPoints` to
        update the anchors and send signals.
        """
        points = self._getControlPoints()
        points[index] = current
        self._setControlPoints(points)

    def _removePlotItems(self):
        """Remove items from their plot."""
        for item in itertools.chain(list(self._items),
                                    list(self._editAnchors)):

            plot = item.getPlot()
            if plot is not None:
                plot._remove(item)
        self._items = WeakList()
        self._editAnchors = WeakList()

        if self._labelItem is not None:
            item = self._labelItem
            plot = item.getPlot()
            if plot is not None:
                plot._remove(item)
        self._labelItem = None

    def _updated(self, event=None, checkVisibility=True):
        """Implement Item mix-in update method by updating the plot items

        See :class:`~silx.gui.plot.items.Item._updated`
        """
        self._createPlotItems()

    def __str__(self):
        """Returns parameters of the ROI as a string."""
        points = self._getControlPoints()
        params = '; '.join('(%f; %f)' % (pt[0], pt[1]) for pt in points)
        return "%s(%s)" % (self.__class__.__name__, params)


class PointROI(RegionOfInterest, items.SymbolMixIn):
    """A ROI identifying a point in a 2D plot."""

    _kind = "Point"
    """Label for this kind of ROI"""

    _plotShape = "point"
    """Plot shape which is used for the first interaction"""

    def __init__(self, parent=None):
        items.SymbolMixIn.__init__(self)
        RegionOfInterest.__init__(self, parent=parent)

    def getPosition(self):
        """Returns the position of this ROI

        :rtype: numpy.ndarray
        """
        return self._points[0].copy()

    def setPosition(self, pos):
        """Set the position of this ROI

        :param numpy.ndarray pos: 2d-coordinate of this point
        """
        controlPoints = numpy.array([pos])
        self._setControlPoints(controlPoints)

    def _createLabelItem(self):
        return None

    def _updateLabelItem(self, label):
        if self.isEditable():
            item = self._editAnchors[0]
        else:
            item = self._items[0]
        item.setText(label)

    def _createShapeItems(self, points):
        if self.isEditable():
            return []
        marker = items.Marker()
        marker.setPosition(points[0][0], points[0][1])
        marker.setText(self.getLabel())
        marker.setColor(rgba(self.getColor()))
        marker.setSymbol(self.getSymbol())
        marker.setSymbolSize(self.getSymbolSize())
        marker._setDraggable(False)
        return [marker]

    def _createAnchorItems(self, points):
        marker = items.Marker()
        marker.setPosition(points[0][0], points[0][1])
        marker.setText(self.getLabel())
        marker._setDraggable(self.isEditable())
        marker.setSymbol(self.getSymbol())
        marker.setSymbolSize(self.getSymbolSize())
        return [marker]

    def __str__(self):
        points = self._getControlPoints()
        params = '%f %f' % (points[0, 0], points[0, 1])
        return "%s(%s)" % (self.__class__.__name__, params)


class LineROI(RegionOfInterest, items.LineMixIn):
    """A ROI identifying a line in a 2D plot.

    This ROI provides 1 anchor for each boundary of the line, plus an center
    in the center to translate the full ROI.
    """

    _kind = "Line"
    """Label for this kind of ROI"""

    _plotShape = "line"
    """Plot shape which is used for the first interaction"""

    def __init__(self, parent=None):
        items.LineMixIn.__init__(self)
        RegionOfInterest.__init__(self, parent=parent)

    def _createControlPointsFromFirstShape(self, points):
        center = numpy.mean(points, axis=0)
        controlPoints = numpy.array([points[0], points[1], center])
        return controlPoints

    def setEndPoints(self, startPoint, endPoint):
        """Set this line location using the ending points

        :param numpy.ndarray startPoint: Staring bounding point of the line
        :param numpy.ndarray endPoint: Ending bounding point of the line
        """
        assert(startPoint.shape == (2,) and endPoint.shape == (2,))
        shapePoints = numpy.array([startPoint, endPoint])
        controlPoints = self._createControlPointsFromFirstShape(shapePoints)
        self._setControlPoints(controlPoints)

    def getEndPoints(self):
        """Returns bounding points of this ROI.

        :rtype: Tuple(numpy.ndarray,numpy.ndarray)
        """
        startPoint = self._points[0].copy()
        endPoint = self._points[1].copy()
        return (startPoint, endPoint)

    def _getLabelPosition(self):
        points = self._getControlPoints()
        return points[-1]

    def _updateShape(self):
        if len(self._items) == 0:
            return
        shape = self._items[0]
        points = self._getControlPoints()
        points = self._getShapeFromControlPoints(points)
        shape.setPoints(points)

    def _getShapeFromControlPoints(self, points):
        # Remove the center from the control points
        return points[0:2]

    def _createShapeItems(self, points):
        shapePoints = self._getShapeFromControlPoints(points)
        item = items.Shape("polylines")
        item.setPoints(shapePoints)
        item.setColor(rgba(self.getColor()))
        item.setFill(False)
        item.setOverlay(True)
        item.setLineStyle(self.getLineStyle())
        item.setLineWidth(self.getLineWidth())
        return [item]

    def _createAnchorItems(self, points):
        anchors = []
        for point in points[0:-1]:
            anchor = items.Marker()
            anchor.setPosition(*point)
            anchor.setText('')
            anchor.setSymbol('s')
            anchor._setDraggable(True)
            anchors.append(anchor)

        # Add an anchor to the center of the rectangle
        center = numpy.mean(points, axis=0)
        anchor = items.Marker()
        anchor.setPosition(*center)
        anchor.setText('')
        anchor.setSymbol('+')
        anchor._setDraggable(True)
        anchors.append(anchor)

        return anchors

    def _controlPointAnchorPositionChanged(self, index, current, previous):
        if index == len(self._editAnchors) - 1:
            # It is the center anchor
            points = self._getControlPoints()
            center = numpy.mean(points[0:-1], axis=0)
            offset = current - previous
            points[-1] = current
            points[0:-1] = points[0:-1] + offset
            self._setControlPoints(points)
        else:
            # Update the center
            points = self._getControlPoints()
            points[index] = current
            center = numpy.mean(points[0:-1], axis=0)
            points[-1] = center
            self._setControlPoints(points)

    def __str__(self):
        points = self._getControlPoints()
        params = points[0][0], points[0][1], points[1][0], points[1][1]
        params = 'start: %f %f; end: %f %f' % params
        return "%s(%s)" % (self.__class__.__name__, params)


class HorizontalLineROI(RegionOfInterest, items.LineMixIn):
    """A ROI identifying an horizontal line in a 2D plot."""

    _kind = "HLine"
    """Label for this kind of ROI"""

    _plotShape = "hline"
    """Plot shape which is used for the first interaction"""

    def __init__(self, parent=None):
        items.LineMixIn.__init__(self)
        RegionOfInterest.__init__(self, parent=parent)

    def _createControlPointsFromFirstShape(self, points):
        points = numpy.array([(float('nan'), points[0, 1])],
                             dtype=numpy.float64)
        return points

    def getPosition(self):
        """Returns the position of this line if the horizontal axis

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

    def setPosition(self, pos):
        """Set the position of this ROI

        :param float pos: Horizontal position of this line
        """
        controlPoints = numpy.array([[float('nan'), pos]])
        self._setControlPoints(controlPoints)

    def _createLabelItem(self):
        return None

    def _updateLabelItem(self, label):
        if self.isEditable():
            item = self._editAnchors[0]
        else:
            item = self._items[0]
        item.setText(label)

    def _updateShape(self):
        if not self.isEditable():
            if len(self._items) > 0:
                controlPoints = self._getControlPoints()
                item = self._items[0]
                item.setPosition(*controlPoints[0])

    def _createShapeItems(self, points):
        if self.isEditable():
            return []
        marker = items.YMarker()
        marker.setPosition(points[0][0], points[0][1])
        marker.setText(self.getLabel())
        marker.setColor(rgba(self.getColor()))
        marker._setDraggable(False)
        marker.setLineWidth(self.getLineWidth())
        marker.setLineStyle(self.getLineStyle())
        return [marker]

    def _createAnchorItems(self, points):
        marker = items.YMarker()
        marker.setPosition(points[0][0], points[0][1])
        marker.setText(self.getLabel())
        marker._setDraggable(self.isEditable())
        marker.setLineWidth(self.getLineWidth())
        marker.setLineStyle(self.getLineStyle())
        return [marker]

    def __str__(self):
        points = self._getControlPoints()
        params = 'y: %f' % points[0, 1]
        return "%s(%s)" % (self.__class__.__name__, params)


class VerticalLineROI(RegionOfInterest, items.LineMixIn):
    """A ROI identifying a vertical line in a 2D plot."""

    _kind = "VLine"
    """Label for this kind of ROI"""

    _plotShape = "vline"
    """Plot shape which is used for the first interaction"""

    def __init__(self, parent=None):
        items.LineMixIn.__init__(self)
        RegionOfInterest.__init__(self, parent=parent)

    def _createControlPointsFromFirstShape(self, points):
        points = numpy.array([(points[0, 0], float('nan'))],
                             dtype=numpy.float64)
        return points

    def getPosition(self):
        """Returns the position of this line if the horizontal axis

        :rtype: float
        """
        return self._points[0, 0]

    def setPosition(self, pos):
        """Set the position of this ROI

        :param float pos: Horizontal position of this line
        """
        controlPoints = numpy.array([[pos, float('nan')]])
        self._setControlPoints(controlPoints)

    def _createLabelItem(self):
        return None

    def _updateLabelItem(self, label):
        if self.isEditable():
            item = self._editAnchors[0]
        else:
            item = self._items[0]
        item.setText(label)

    def _updateShape(self):
        if not self.isEditable():
            if len(self._items) > 0:
                controlPoints = self._getControlPoints()
                item = self._items[0]
                item.setPosition(*controlPoints[0])

    def _createShapeItems(self, points):
        if self.isEditable():
            return []
        marker = items.XMarker()
        marker.setPosition(points[0][0], points[0][1])
        marker.setText(self.getLabel())
        marker.setColor(rgba(self.getColor()))
        marker._setDraggable(False)
        marker.setLineWidth(self.getLineWidth())
        marker.setLineStyle(self.getLineStyle())
        return [marker]

    def _createAnchorItems(self, points):
        marker = items.XMarker()
        marker.setPosition(points[0][0], points[0][1])
        marker.setText(self.getLabel())
        marker._setDraggable(self.isEditable())
        marker.setLineWidth(self.getLineWidth())
        marker.setLineStyle(self.getLineStyle())
        return [marker]

    def __str__(self):
        points = self._getControlPoints()
        params = 'x: %f' % points[0, 0]
        return "%s(%s)" % (self.__class__.__name__, params)


class RectangleROI(RegionOfInterest, items.LineMixIn):
    """A ROI identifying a rectangle in a 2D plot.

    This ROI provides 1 anchor for each corner, plus an anchor in the
    center to translate the full ROI.
    """

    _kind = "Rectangle"
    """Label for this kind of ROI"""

    _plotShape = "rectangle"
    """Plot shape which is used for the first interaction"""

    def __init__(self, parent=None):
        items.LineMixIn.__init__(self)
        RegionOfInterest.__init__(self, parent=parent)

    def _createControlPointsFromFirstShape(self, points):
        point0 = points[0]
        point1 = points[1]

        # 4 corners
        controlPoints = numpy.array([
            point0[0], point0[1],
            point0[0], point1[1],
            point1[0], point1[1],
            point1[0], point0[1],
        ])
        # Central
        center = numpy.mean(points, axis=0)
        controlPoints = numpy.append(controlPoints, center)
        controlPoints.shape = -1, 2
        return controlPoints

    def getCenter(self):
        """Returns the central point of this rectangle

        :rtype: numpy.ndarray([float,float])
        """
        return numpy.mean(self._points, axis=0)

    def getOrigin(self):
        """Returns the corner point with the smaller coordinates

        :rtype: numpy.ndarray([float,float])
        """
        return numpy.min(self._points, axis=0)

    def getSize(self):
        """Returns the size of this rectangle

        :rtype: numpy.ndarray([float,float])
        """
        minPoint = numpy.min(self._points, axis=0)
        maxPoint = numpy.max(self._points, axis=0)
        return maxPoint - minPoint

    def setOrigin(self, position):
        """Set the origin position of this ROI

        :param numpy.ndarray position: Location of the smaller corner of the ROI
        """
        size = self.getSize()
        self.setGeometry(origin=position, size=size)

    def setSize(self, size):
        """Set the size of this ROI

        :param numpy.ndarray size: Size of the center of the ROI
        """
        origin = self.getOrigin()
        self.setGeometry(origin=origin, size=size)

    def setCenter(self, position):
        """Set the size of this ROI

        :param numpy.ndarray position: Location of the center of the ROI
        """
        size = self.getSize()
        self.setGeometry(center=position, size=size)

    def setGeometry(self, origin=None, size=None, center=None):
        """Set the geometry of the ROI
        """
        if origin is not None:
            origin = numpy.array(origin)
            size = numpy.array(size)
            points = numpy.array([origin, origin + size])
            controlPoints = self._createControlPointsFromFirstShape(points)
        elif center is not None:
            center = numpy.array(center)
            size = numpy.array(size)
            points = numpy.array([center - size * 0.5, center + size * 0.5])
            controlPoints = self._createControlPointsFromFirstShape(points)
        else:
            raise ValueError("Origin or cengter expected")
        self._setControlPoints(controlPoints)

    def _getLabelPosition(self):
        points = self._getControlPoints()
        return points.min(axis=0)

    def _updateShape(self):
        if len(self._items) == 0:
            return
        shape = self._items[0]
        points = self._getControlPoints()
        points = self._getShapeFromControlPoints(points)
        shape.setPoints(points)

    def _getShapeFromControlPoints(self, points):
        minPoint = points.min(axis=0)
        maxPoint = points.max(axis=0)
        return numpy.array([minPoint, maxPoint])

    def _createShapeItems(self, points):
        shapePoints = self._getShapeFromControlPoints(points)
        item = items.Shape("rectangle")
        item.setPoints(shapePoints)
        item.setColor(rgba(self.getColor()))
        item.setFill(False)
        item.setOverlay(True)
        item.setLineStyle(self.getLineStyle())
        item.setLineWidth(self.getLineWidth())
        return [item]

    def _createAnchorItems(self, points):
        # Remove the center control point
        points = points[0:-1]

        anchors = []
        for point in points:
            anchor = items.Marker()
            anchor.setPosition(*point)
            anchor.setText('')
            anchor.setSymbol('s')
            anchor._setDraggable(True)
            anchors.append(anchor)

        # Add an anchor to the center of the rectangle
        center = numpy.mean(points, axis=0)
        anchor = items.Marker()
        anchor.setPosition(*center)
        anchor.setText('')
        anchor.setSymbol('+')
        anchor._setDraggable(True)
        anchors.append(anchor)

        return anchors

    def _controlPointAnchorPositionChanged(self, index, current, previous):
        if index == len(self._editAnchors) - 1:
            # It is the center anchor
            points = self._getControlPoints()
            center = numpy.mean(points[0:-1], axis=0)
            offset = current - previous
            points[-1] = current
            points[0:-1] = points[0:-1] + offset
            self._setControlPoints(points)
        else:
            # Fix other corners
            constrains = [(1, 3), (0, 2), (3, 1), (2, 0)]
            constrains = constrains[index]
            points = self._getControlPoints()
            points[index] = current
            points[constrains[0]][0] = current[0]
            points[constrains[1]][1] = current[1]
            # Update the center
            center = numpy.mean(points[0:-1], axis=0)
            points[-1] = center
            self._setControlPoints(points)

    def __str__(self):
        origin = self.getOrigin()
        w, h = self.getSize()
        params = origin[0], origin[1], w, h
        params = 'origin: %f %f; width: %f; height: %f' % params
        return "%s(%s)" % (self.__class__.__name__, params)


class PolygonROI(RegionOfInterest, items.LineMixIn):
    """A ROI identifying a closed polygon in a 2D plot.

    This ROI provides 1 anchor for each point of the polygon.
    """

    _kind = "Polygon"
    """Label for this kind of ROI"""

    _plotShape = "polygon"
    """Plot shape which is used for the first interaction"""

    def __init__(self, parent=None):
        items.LineMixIn.__init__(self)
        RegionOfInterest.__init__(self, parent=parent)

    def getPoints(self):
        """Returns the list of the points of this polygon.

        :rtype: numpy.ndarray
        """
        return self._points.copy()

    def setPoints(self, points):
        """Set the position of this ROI

        :param numpy.ndarray pos: 2d-coordinate of this point
        """
        assert(len(points.shape) == 2 and points.shape[1] == 2)
        if len(points) > 0:
            controlPoints = numpy.array(points)
        else:
            controlPoints = numpy.empty((0, 2))
        self._setControlPoints(controlPoints)

    def _getLabelPosition(self):
        points = self._getControlPoints()
        if len(points) == 0:
            # FIXME: we should return none, this polygon have no location
            return numpy.array([0, 0])
        return points[numpy.argmin(points[:, 1])]

    def _updateShape(self):
        if len(self._items) == 0:
            return
        shape = self._items[0]
        points = self._getControlPoints()
        shape.setPoints(points)

    def _createShapeItems(self, points):
        if len(points) == 0:
            return []
        else:
            item = items.Shape("polygon")
            item.setPoints(points)
            item.setColor(rgba(self.getColor()))
            item.setFill(False)
            item.setOverlay(True)
            item.setLineStyle(self.getLineStyle())
            item.setLineWidth(self.getLineWidth())
            return [item]

    def _createAnchorItems(self, points):
        anchors = []
        for point in points:
            anchor = items.Marker()
            anchor.setPosition(*point)
            anchor.setText('')
            anchor.setSymbol('s')
            anchor._setDraggable(True)
            anchors.append(anchor)
        return anchors

    def __str__(self):
        points = self._getControlPoints()
        params = '; '.join('%f %f' % (pt[0], pt[1]) for pt in points)
        return "%s(%s)" % (self.__class__.__name__, params)


class ArcROI(RegionOfInterest, items.LineMixIn):
    """A ROI identifying an arc of a circle with a width.

    This ROI provides 3 anchors to control the curvature, 1 anchor to control
    the weigth, and 1 anchor to translate the shape.
    """

    _kind = "Arc"
    """Label for this kind of ROI"""

    _plotShape = "line"
    """Plot shape which is used for the first interaction"""

    _ArcGeometry = collections.namedtuple('ArcGeometry', ['center',
                                                          'startPoint', 'endPoint',
                                                          'radius', 'weight',
                                                          'startAngle', 'endAngle'])

    def __init__(self, parent=None):
        items.LineMixIn.__init__(self)
        RegionOfInterest.__init__(self, parent=parent)
        self._geometry = None

    def _getInternalGeometry(self):
        """Returns the object storing the internal geometry of this ROI.

        This geometry is derived from the control points and cached for
        efficiency. Calling :meth:`_setControlPoints` invalidate the cache.
        """
        if self._geometry is None:
            controlPoints = self._getControlPoints()
            self._geometry = self._createGeometryFromControlPoint(controlPoints)
        return self._geometry

    @classmethod
    def showFirstInteractionShape(cls):
        return False

    def _getLabelPosition(self):
        points = self._getControlPoints()
        return points.min(axis=0)

    def _updateShape(self):
        if len(self._items) == 0:
            return
        shape = self._items[0]
        points = self._getControlPoints()
        points = self._getShapeFromControlPoints(points)
        shape.setPoints(points)

    def _controlPointAnchorPositionChanged(self, index, current, previous):
        controlPoints = self._getControlPoints()
        currentWeigth = numpy.linalg.norm(controlPoints[3] - controlPoints[1]) * 2

        if index in [0, 2]:
            # Moving start or end will maintain the same curvature
            # Then we have to custom the curvature control point
            startPoint = controlPoints[0]
            endPoint = controlPoints[2]
            center = (startPoint + endPoint) * 0.5
            normal = (endPoint - startPoint)
            normal = numpy.array((normal[1], -normal[0]))
            distance = numpy.linalg.norm(normal)
            # Compute the coeficient which have to be constrained
            if distance != 0:
                normal /= distance
                midVector = controlPoints[1] - center
                constainedCoef = numpy.dot(midVector, normal) / distance
            else:
                constainedCoef = 1.0

            # Compute the location of the curvature point
            controlPoints[index] = current
            startPoint = controlPoints[0]
            endPoint = controlPoints[2]
            center = (startPoint + endPoint) * 0.5
            normal = (endPoint - startPoint)
            normal = numpy.array((normal[1], -normal[0]))
            distance = numpy.linalg.norm(normal)
            if distance != 0:
                # BTW we dont need to divide by the distance here
                # Cause we compute normal * distance after all
                normal /= distance
            midPoint = center + normal * constainedCoef * distance
            controlPoints[1] = midPoint

            # The weight have to be fixed
            self._updateWeightControlPoint(controlPoints, currentWeigth)
            self._setControlPoints(controlPoints)

        elif index == 1:
            # The weight have to be fixed
            controlPoints[index] = current
            self._updateWeightControlPoint(controlPoints, currentWeigth)
            self._setControlPoints(controlPoints)
        else:
            super(ArcROI, self)._controlPointAnchorPositionChanged(index, current, previous)

    def _updateWeightControlPoint(self, controlPoints, weigth):
        startPoint = controlPoints[0]
        midPoint = controlPoints[1]
        endPoint = controlPoints[2]
        normal = (endPoint - startPoint)
        normal = numpy.array((normal[1], -normal[0]))
        distance = numpy.linalg.norm(normal)
        if distance != 0:
            normal /= distance
        controlPoints[3] = midPoint + normal * weigth * 0.5

    def _createGeometryFromControlPoint(self, controlPoints):
        """Returns the geometry of the object"""
        weigth = numpy.linalg.norm(controlPoints[3] - controlPoints[1]) * 2
        if numpy.allclose(controlPoints[0], controlPoints[2]):
            # Special arc: It's a closed circle
            center = (controlPoints[0] + controlPoints[1]) * 0.5
            radius = numpy.linalg.norm(controlPoints[0] - center)
            v = controlPoints[0] - center
            startAngle = numpy.angle(complex(v[0], v[1]))
            endAngle = startAngle + numpy.pi * 2.0
            return self._ArcGeometry(center, controlPoints[0], controlPoints[2],
                                     radius, weigth, startAngle, endAngle)

        elif numpy.linalg.norm(
            numpy.cross(controlPoints[1] - controlPoints[0],
                        controlPoints[2] - controlPoints[0])) < 1e-5:
            # Degenerated arc, it's a rectangle
            return self._ArcGeometry(None, controlPoints[0], controlPoints[2],
                                     None, weigth, None, None)
        else:
            center, radius = self._circleEquation(*controlPoints[:3])
            v = controlPoints[0] - center
            startAngle = numpy.angle(complex(v[0], v[1]))
            v = controlPoints[1] - center
            midAngle = numpy.angle(complex(v[0], v[1]))
            v = controlPoints[2] - center
            endAngle = numpy.angle(complex(v[0], v[1]))
            # Is it clockwise or anticlockwise
            if (midAngle - startAngle + 2 * numpy.pi) % (2 * numpy.pi) <= numpy.pi:
                if endAngle < startAngle:
                    endAngle += 2 * numpy.pi
            else:
                if endAngle > startAngle:
                    endAngle -= 2 * numpy.pi

            return self._ArcGeometry(center, controlPoints[0], controlPoints[2],
                                     radius, weigth, startAngle, endAngle)

    def _isCircle(self, geometry):
        """Returns True if the geometry is a closed circle"""
        delta = numpy.abs(geometry.endAngle - geometry.startAngle)
        return numpy.isclose(delta, numpy.pi * 2)

    def _getShapeFromControlPoints(self, controlPoints):
        geometry = self._createGeometryFromControlPoint(controlPoints)
        if geometry.center is None:
            # It is not an arc
            # but we can display it as an the intermediat shape
            normal = (geometry.endPoint - geometry.startPoint)
            normal = numpy.array((normal[1], -normal[0]))
            distance = numpy.linalg.norm(normal)
            if distance != 0:
                normal /= distance
            points = numpy.array([
                geometry.startPoint + normal * geometry.weight * 0.5,
                geometry.endPoint + normal * geometry.weight * 0.5,
                geometry.endPoint - normal * geometry.weight * 0.5,
                geometry.startPoint - normal * geometry.weight * 0.5])
        else:
            innerRadius = geometry.radius - geometry.weight * 0.5
            outerRadius = geometry.radius + geometry.weight * 0.5

            if numpy.isnan(geometry.startAngle):
                # Degenerated, it's a point
                # At least 2 points are expected
                return numpy.array([geometry.startPoint, geometry.startPoint])

            delta = 0.1 if geometry.endAngle >= geometry.startAngle else -0.1
            if geometry.startAngle == geometry.endAngle:
                # Degenerated, it's a line (single radius)
                angle = geometry.startAngle
                direction = numpy.array([numpy.cos(angle), numpy.sin(angle)])
                points = []
                points.append(geometry.center + direction * innerRadius)
                points.append(geometry.center + direction * outerRadius)
                return numpy.array(points)

            angles = numpy.arange(geometry.startAngle, geometry.endAngle, delta)
            if angles[-1] != geometry.endAngle:
                angles = numpy.append(angles, geometry.endAngle)

            isCircle = self._isCircle(geometry)

            if isCircle:
                if innerRadius <= 0:
                    # It's a circle
                    points = []
                    numpy.append(angles, angles[-1])
                    for angle in angles:
                        direction = numpy.array([numpy.cos(angle), numpy.sin(angle)])
                        points.append(geometry.center + direction * outerRadius)
                else:
                    # It's a donut
                    points = []
                    # NOTE: NaN value allow to create 2 separated circle shapes
                    # using a single plot item. It's a kind of cheat
                    points.append(numpy.array([float("nan"), float("nan")]))
                    for angle in angles:
                        direction = numpy.array([numpy.cos(angle), numpy.sin(angle)])
                        points.insert(0, geometry.center + direction * innerRadius)
                        points.append(geometry.center + direction * outerRadius)
                    points.append(numpy.array([float("nan"), float("nan")]))
            else:
                if innerRadius <= 0:
                    # It's a part of camembert
                    points = []
                    points.append(geometry.center)
                    points.append(geometry.startPoint)
                    delta = 0.1 if geometry.endAngle >= geometry.startAngle else -0.1
                    for angle in angles:
                        direction = numpy.array([numpy.cos(angle), numpy.sin(angle)])
                        points.append(geometry.center + direction * outerRadius)
                    points.append(geometry.endPoint)
                    points.append(geometry.center)
                else:
                    # It's a part of donut
                    points = []
                    points.append(geometry.startPoint)
                    for angle in angles:
                        direction = numpy.array([numpy.cos(angle), numpy.sin(angle)])
                        points.insert(0, geometry.center + direction * innerRadius)
                        points.append(geometry.center + direction * outerRadius)
                    points.insert(0, geometry.endPoint)
                    points.append(geometry.endPoint)
            points = numpy.array(points)

        return points

    def _setControlPoints(self, points):
        # Invalidate the geometry
        self._geometry = None
        RegionOfInterest._setControlPoints(self, points)

    def getGeometry(self):
        """Returns a tuple containing the geometry of this ROI

        It is a symmetric function of :meth:`setGeometry`.

        If `startAngle` is smaller than `endAngle` the rotation is clockwise,
        else the rotation is anticlockwise.

        :rtype: Tuple[numpy.ndarray,float,float,float,float]
        :raise ValueError: In case the ROI can't be represented as section of
            a circle
        """
        geometry = self._getInternalGeometry()
        if geometry.center is None:
            raise ValueError("This ROI can't be represented as a section of circle")
        return geometry.center, self.getInnerRadius(), self.getOuterRadius(), geometry.startAngle, geometry.endAngle

    def isClosed(self):
        """Returns true if the arc is a closed shape, like a circle or a donut.

        :rtype: bool
        """
        geometry = self._getInternalGeometry()
        return self._isCircle(geometry)

    def getCenter(self):
        """Returns the center of the circle used to draw arcs of this ROI.

        This center is usually outside the the shape itself.

        :rtype: numpy.ndarray
        """
        geometry = self._getInternalGeometry()
        return geometry.center

    def getStartAngle(self):
        """Returns the angle of the start of the section of this ROI (in radian).

        If `startAngle` is smaller than `endAngle` the rotation is clockwise,
        else the rotation is anticlockwise.

        :rtype: float
        """
        geometry = self._getInternalGeometry()
        return geometry.startAngle

    def getEndAngle(self):
        """Returns the angle of the end of the section of this ROI (in radian).

        If `startAngle` is smaller than `endAngle` the rotation is clockwise,
        else the rotation is anticlockwise.

        :rtype: float
        """
        geometry = self._getInternalGeometry()
        return geometry.endAngle

    def getInnerRadius(self):
        """Returns the radius of the smaller arc used to draw this ROI.

        :rtype: float
        """
        geometry = self._getInternalGeometry()
        radius = geometry.radius - geometry.weight * 0.5
        if radius < 0:
            radius = 0
        return radius

    def getOuterRadius(self):
        """Returns the radius of the bigger arc used to draw this ROI.

        :rtype: float
        """
        geometry = self._getInternalGeometry()
        radius = geometry.radius + geometry.weight * 0.5
        return radius

    def setGeometry(self, center, innerRadius, outerRadius, startAngle, endAngle):
        """
        Set the geometry of this arc.

        :param numpy.ndarray center: Center of the circle.
        :param float innerRadius: Radius of the smaller arc of the section.
        :param float outerRadius: Weight of the bigger arc of the section.
            It have to be bigger than `innerRadius`
        :param float startAngle: Location of the start of the section (in radian)
        :param float endAngle: Location of the end of the section (in radian).
            If `startAngle` is smaller than `endAngle` the rotation is clockwise,
            else the rotation is anticlockwise.
        """
        assert(innerRadius <= outerRadius)
        assert(numpy.abs(startAngle - endAngle) <= 2 * numpy.pi)
        center = numpy.array(center)
        radius = (innerRadius + outerRadius) * 0.5
        weight = outerRadius - innerRadius
        geometry = self._ArcGeometry(center, None, None, radius, weight, startAngle, endAngle)
        controlPoints = self._createControlPointsFromGeometry(geometry)
        self._setControlPoints(controlPoints)

    def _createControlPointsFromGeometry(self, geometry):
        if geometry.startPoint or geometry.endPoint:
            # Duplication with the angles
            raise NotImplementedError("This general case is not implemented")

        angle = geometry.startAngle
        direction = numpy.array([numpy.cos(angle), numpy.sin(angle)])
        startPoint = geometry.center + direction * geometry.radius

        angle = geometry.endAngle
        direction = numpy.array([numpy.cos(angle), numpy.sin(angle)])
        endPoint = geometry.center + direction * geometry.radius

        angle = (geometry.startAngle + geometry.endAngle) * 0.5
        direction = numpy.array([numpy.cos(angle), numpy.sin(angle)])
        curvaturePoint = geometry.center + direction * geometry.radius
        weightPoint = curvaturePoint + direction * geometry.weight * 0.5

        return numpy.array([startPoint, curvaturePoint, endPoint, weightPoint])

    def _createControlPointsFromFirstShape(self, points):
        # The first shape is a line
        point0 = points[0]
        point1 = points[1]

        # Compute a non colineate point for the curvature
        center = (point1 + point0) * 0.5
        normal = point1 - center
        normal = numpy.array((normal[1], -normal[0]))
        defaultCurvature = numpy.pi / 5.0
        defaultWeight = 0.20  # percentage
        curvaturePoint = center - normal * defaultCurvature
        weightPoint = center - normal * defaultCurvature * (1.0 + defaultWeight)

        # 3 corners
        controlPoints = numpy.array([
            point0,
            curvaturePoint,
            point1,
            weightPoint
        ])
        return controlPoints

    def _createShapeItems(self, points):
        shapePoints = self._getShapeFromControlPoints(points)
        item = items.Shape("polygon")
        item.setPoints(shapePoints)
        item.setColor(rgba(self.getColor()))
        item.setFill(False)
        item.setOverlay(True)
        item.setLineStyle(self.getLineStyle())
        item.setLineWidth(self.getLineWidth())
        return [item]

    def _createAnchorItems(self, points):
        anchors = []
        symbols = ['o', 'o', 'o', 's']

        for index, point in enumerate(points):
            if index in [1, 3]:
                constraint = self._arcCurvatureMarkerConstraint
            else:
                constraint = None
            anchor = items.Marker()
            anchor.setPosition(*point)
            anchor.setText('')
            anchor.setSymbol(symbols[index])
            anchor._setDraggable(True)
            if constraint is not None:
                anchor._setConstraint(constraint)
            anchors.append(anchor)

        return anchors

    def _arcCurvatureMarkerConstraint(self, x, y):
        """Curvature marker remains on "mediatrice" """
        start = self._points[0]
        end = self._points[2]
        midPoint = (start + end) / 2.
        normal = (end - start)
        normal = numpy.array((normal[1], -normal[0]))
        distance = numpy.linalg.norm(normal)
        if distance != 0:
            normal /= distance
        v = numpy.dot(normal, (numpy.array((x, y)) - midPoint))
        x, y = midPoint + v * normal
        return x, y

    @staticmethod
    def _circleEquation(pt1, pt2, pt3):
        """Circle equation from 3 (x, y) points

        :return: Position of the center of the circle and the radius
        :rtype: Tuple[Tuple[float,float],float]
        """
        x, y, z = complex(*pt1), complex(*pt2), complex(*pt3)
        w = z - x
        w /= y - x
        c = (x - y) * (w - abs(w) ** 2) / 2j / w.imag - x
        return ((-c.real, -c.imag), abs(c + x))

    def __str__(self):
        try:
            center, innerRadius, outerRadius, startAngle, endAngle = self.getGeometry()
            params = center[0], center[1], innerRadius, outerRadius, startAngle, endAngle
            params = 'center: %f %f; radius: %f %f; angles: %f %f' % params
        except ValueError:
            params = "invalid"
        return "%s(%s)" % (self.__class__.__name__, params)