File: compareBackends.py

package info (click to toggle)
silx 2.2.1%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 31,696 kB
  • sloc: python: 119,829; ansic: 5,062; lisp: 4,454; cpp: 883; sh: 286; makefile: 90; xml: 46
file content (375 lines) | stat: -rw-r--r-- 12,679 bytes parent folder | download | duplicates (2)
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
# /*##########################################################################
#
# Copyright (c) 2017-2021 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 script compares the rendering of PlotWidget's matplotlib and OpenGL backends.
"""

from __future__ import annotations

__license__ = "MIT"

import numpy
import sys
import functools

from silx.gui import qt

from silx.gui.plot import PlotWidget
from silx.gui.plot import items
from silx.gui.plot.items.marker import Marker
from silx.gui.plot.utils.axis import SyncAxes


_DESCRIPTIONS = {}


class MyPlotWindow(qt.QMainWindow):
    """QMainWindow with selected tools"""

    def __init__(self, parent=None):
        super(MyPlotWindow, self).__init__(parent)

        # Create a PlotWidget
        self._plot1 = PlotWidget(parent=self, backend="mpl")
        self._plot1.setGraphTitle("matplotlib")
        self._plot2 = PlotWidget(parent=self, backend="opengl")
        self._plot2.setGraphTitle("opengl")

        self.constraintX = SyncAxes(
            [
                self._plot1.getXAxis(),
                self._plot2.getXAxis(),
            ]
        )
        self.constraintY = SyncAxes(
            [
                self._plot1.getYAxis(),
                self._plot2.getYAxis(),
            ]
        )

        plotWidget = qt.QWidget(self)
        plotLayout = qt.QHBoxLayout(plotWidget)
        plotLayout.addWidget(self._plot1)
        plotLayout.addWidget(self._plot2)
        plotLayout.setContentsMargins(0, 0, 0, 0)
        plotLayout.setContentsMargins(0, 0, 0, 0)

        options = self.createOptions(self)
        centralWidget = qt.QWidget(self)
        layout = qt.QHBoxLayout(centralWidget)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(options)
        layout.addWidget(plotWidget)

        self.setCentralWidget(centralWidget)

        self._state = {}

    def clear(self):
        self._state = {}

    def createOptions(self, parent):
        options = qt.QWidget(parent)
        layout = qt.QVBoxLayout(options)
        for id, description in _DESCRIPTIONS.items():
            label, _func = description
            button = qt.QPushButton(label, self)
            button.clicked.connect(functools.partial(self.showUseCase, id))
            layout.addWidget(button)
        layout.addStretch()
        return options

    def showUseCase(self, name: str):
        description = _DESCRIPTIONS.get(name)
        if description is None:
            raise ValueError(f"Unknown use case '{name}'")
        setupFunc = description[1]
        self.clear()
        for p in [self._plot1, self._plot2]:
            p.clear()
            setupFunc(self, p)
            p.resetZoom()

    def _register(name, label):
        def decorator(func):
            _DESCRIPTIONS[name] = (label, func)
            return func

        return decorator

    def _addLine(
        self,
        plot,
        lineWidth: float,
        lineStyle: str,
        color: str,
        gapColor: str | None,
        curve: bool,
    ):
        state = self._state.setdefault(plot, {})
        x = state.get("x", 0)
        y = state.get("y", 0)
        x += 10
        state["x"] = x
        state["y"] = y

        start = (x - 20, y + 0)
        stop = (x + 40, y + 100)

        def createShape():
            shape = items.Shape("polylines")
            shape.setPoints(numpy.array((start, stop)))
            shape.setLineWidth(lineWidth)
            shape.setLineStyle(lineStyle)
            shape.setColor(color)
            if gapColor is not None:
                shape.setLineGapColor(gapColor)
            return shape

        def createCurve():
            curve = items.Curve()
            array = numpy.array((start, stop)).T
            curve.setData(array[0], array[1])
            curve.setLineWidth(lineWidth)
            curve.setLineStyle(lineStyle)
            curve.setColor(color)
            curve.setSymbol("")
            if gapColor is not None:
                curve.setLineGapColor(gapColor)
            return curve

        if curve:
            plot.addItem(createCurve())
        else:
            plot.addItem(createShape())

    @_register("linewidth", "Line width")
    def _setupLineStyle(self, plot: PlotWidget):
        self._addLine(plot, 0.5, "-", "#0000FF", None, curve=False)
        self._addLine(plot, 1.0, "-", "#0000FF", None, curve=False)
        self._addLine(plot, 2.0, "-", "#0000FF", None, curve=False)
        self._addLine(plot, 4.0, "-", "#0000FF", None, curve=False)
        self._addLine(plot, 0.5, "-", "#00FFFF", None, curve=True)
        self._addLine(plot, 1.0, "-", "#00FFFF", None, curve=True)
        self._addLine(plot, 2.0, "-", "#00FFFF", None, curve=True)
        self._addLine(plot, 4.0, "-", "#00FFFF", None, curve=True)

    @_register("linestyle", "Line style")
    def _setupLineStyle(self, plot: PlotWidget):
        self._addLine(plot, 1.0, "--", "#0000FF", None, curve=False)
        self._addLine(plot, 1.0, "-.", "#0000FF", None, curve=False)
        self._addLine(plot, 1.0, ":", "#0000FF", None, curve=False)
        self._addLine(plot, 2.0, "--", "#00FFFF", None, curve=True)
        self._addLine(plot, 2.0, "-.", "#00FFFF", None, curve=True)
        self._addLine(plot, 2.0, ":", "#00FFFF", None, curve=True)

    @_register("gapcolor", "LineStyle Gap Color")
    def _setupLineStyleGapColor(self, plot):
        self._addLine(plot, 1.0, "-", "#FF00FF", "black", curve=False)
        self._addLine(plot, 1.0, "-.", "#FF00FF", "black", curve=False)
        self._addLine(plot, 1.0, "--", "#FF00FF", "black", curve=False)
        self._addLine(plot, 0.5, "--", "#FF00FF", "black", curve=False)
        self._addLine(plot, 1.5, "--", "#FF00FF", "black", curve=False)
        self._addLine(plot, 2.0, "--", "#FF00FF", "black", curve=False)
        plot.setGraphXLimits(0, 100)
        plot.setGraphYLimits(0, 100)

    @_register("curveshape", "Curve vs Shape")
    def _setupLineStyleCurveShape(self, plot):
        self._addLine(plot, 1.0, (0, (5, 5)), "#00FF00", None, curve=False)
        self._addLine(plot, 4.0, (0, (3, 3)), "#00FF00", None, curve=False)
        self._addLine(plot, 4.0, (0, (5, 5)), "#00FF00", None, curve=False)
        self._addLine(plot, 4.0, (0, (7, 7)), "#00FF00", None, curve=False)
        self._addLine(plot, 1.0, (0, (5, 5)), "#00FFFF", None, curve=True)
        self._addLine(plot, 4.0, (0, (3, 3)), "#00FFFF", None, curve=True)
        self._addLine(plot, 4.0, (0, (5, 5)), "#00FFFF", None, curve=True)
        self._addLine(plot, 4.0, (0, (7, 7)), "#00FFFF", None, curve=True)
        plot.setGraphXLimits(0, 100)
        plot.setGraphYLimits(0, 100)

    @_register("text", "Text")
    def _setupText(self, plot):
        plot.getDefaultColormap().setName("viridis")

        # Add an image to the plot
        x = numpy.outer(numpy.linspace(-10, 10, 200), numpy.linspace(-10, 5, 150))
        image = numpy.sin(x) / x
        plot.addImage(image)

        label = Marker()
        label.setPosition(40, 150)
        label.setText("No background")
        plot.addItem(label)

        label = Marker()
        label.setPosition(50, 50)
        label.setText("Foo bar\nmmmmmmmmmmmmmmmmmmmm")
        label.setBackgroundColor("#FFFFFF44")
        plot.addItem(label)

        label2 = Marker()
        label2.setPosition(70, 70)
        label2.setText("Foo bar")
        label2.setColor("red")
        label2.setBackgroundColor("#00000044")
        plot.addItem(label2)

        label3 = Marker()
        label3.setPosition(10, 70)
        label3.setText("Pioupiou")
        label3.setColor("yellow")
        label3.setBackgroundColor("#000000")
        plot.addItem(label3)

    @_register("marker", "Marker")
    def _setupMarker(self, plot):
        plot.getDefaultColormap().setName("viridis")

        # Add an image to the plot
        x = numpy.outer(numpy.linspace(-10, 10, 200), numpy.linspace(-10, 5, 150))
        image = numpy.sin(x) / x
        plot.addImage(image)

        label = Marker()
        label.setSymbol("o")
        label.setPosition(30, 30)
        label.setColor("white")
        plot.addItem(label)

        label = Marker()
        label.setSymbol(".")
        label.setPosition(50, 30)
        label.setColor("white")
        plot.addItem(label)

        label = Marker()
        label.setSymbol(",")
        label.setPosition(70, 30)
        label.setColor("white")
        plot.addItem(label)

        label = Marker()
        label.setSymbol("+")
        # label.setSymbolSize(100)
        label.setPosition(30, 50)
        label.setColor("white")
        plot.addItem(label)

        label = Marker()
        label.setSymbol("x")
        label.setPosition(50, 50)
        label.setColor("white")
        plot.addItem(label)

        label = Marker()
        label.setSymbol("d")
        label.setPosition(70, 50)
        label.setColor("white")
        plot.addItem(label)

        label = Marker()
        label.setSymbol("s")
        label.setPosition(30, 70)
        label.setColor("white")
        plot.addItem(label)

        label = Marker()
        label.setSymbol("|")
        label.setPosition(50, 70)
        label.setColor("white")
        plot.addItem(label)

        label = Marker()
        label.setSymbol("_")
        label.setPosition(70, 70)
        label.setColor("white")
        plot.addItem(label)

    @_register("arrows", "Arrows")
    def _setupArrows(self, plot):
        """Display few lines with markers."""
        plot.setDataMargins(0.1, 0.1, 0.1, 0.1)

        plot.addCurve(
            x=[-10, 0, 0, -10, -10], y=[90, 90, 10, 10, 90], legend="box1", color="gray"
        )
        plot.addCurve(
            x=[110, 100, 100, 110, 110],
            y=[90, 90, 10, 10, 90],
            legend="box2",
            color="gray",
        )
        plot.addCurve(
            y=[-10, 0, 0, -10, -10], x=[90, 90, 10, 10, 90], legend="box3", color="gray"
        )
        plot.addCurve(
            y=[110, 100, 100, 110, 110],
            x=[90, 90, 10, 10, 90],
            legend="box4",
            color="gray",
        )

        def addCompositeLine(
            source, destination, symbolSource, symbolDestination, legend, color
        ):
            line = numpy.array([source, destination]).T
            plot.addCurve(x=line[0, :], y=line[1, :], color=color, legend=legend)
            plot.addMarker(x=source[0], y=source[1], symbol=symbolSource, color=color)
            plot.addMarker(
                x=destination[0],
                y=destination[1],
                symbol=symbolDestination,
                color=color,
            )

        addCompositeLine([0, 50], [100, 50], "caretleft", "caretright", "l1", "red")
        addCompositeLine([0, 30], [100, 30], "tickup", "tickdown", "l2", "blue")
        addCompositeLine([0, 70], [100, 70], "|", "|", "l3", "black")

        addCompositeLine([50, 0], [50, 100], "caretdown", "caretup", "l4", "red")
        addCompositeLine([30, 0], [30, 100], "tickleft", "tickright", "l5", "blue")
        addCompositeLine([70, 0], [70, 100], "_", "_", "l6", "black")


def main():
    global app
    app = qt.QApplication([])

    # Create the ad hoc window containing a PlotWidget and associated tools
    window = MyPlotWindow()
    window.setAttribute(qt.Qt.WA_DeleteOnClose)
    window.show()
    if len(sys.argv) == 1:
        useCase = "linestyle"
    else:
        useCase = sys.argv[1]
    window.showUseCase(useCase)
    app.exec()


if __name__ == "__main__":
    main()