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
|
#!/usr/bin/env python
# /*##########################################################################
#
# Copyright (c) 2016-2024 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 is a simple example of how to add your own statistic to a
:class:`~silx.gui.plot.statsWidget.StatsWidget` from customs
:class:`~silx.gui.plot.stats.Stats` and display it.
On this example we will:
- show sum of values for each type
- compute curve integrals (only for 'curve').
- compute center of mass for all possible items
.. note:: stats are available for 1D and 2D at the time being
"""
__authors__ = ["H. Payno"]
__license__ = "MIT"
__date__ = "23/07/2019"
from silx.gui import qt
from silx.gui.colors import Colormap
from silx.gui.plot import Plot1D
from silx.gui.plot.stats.stats import StatBase
from silx.gui.utils import concurrent
import random
import threading
import argparse
import numpy
import time
try:
from numpy import trapezoid
except ImportError: # numpy v1 compatibility
from numpy import trapz as trapezoid
class UpdateThread(threading.Thread):
"""Thread updating the curve of a :class:`~silx.gui.plot.Plot1D`
:param plot1d: The Plot1D to update."""
def __init__(self, plot1d):
self.plot1d = plot1d
self.running = False
super(UpdateThread, self).__init__()
def start(self):
"""Start the update thread"""
self.running = True
super(UpdateThread, self).start()
def run(self):
"""Method implementing thread loop that updates the plot"""
while self.running:
time.sleep(1)
# Run plot update asynchronously
concurrent.submitToQtMainThread(
self.plot1d.addCurve,
numpy.arange(1000),
numpy.random.random(1000),
resetzoom=False,
legend=random.choice(("mycurve0", "mycurve1")),
)
def stop(self):
"""Stop the update thread"""
self.running = False
self.join(2)
class Integral(StatBase):
"""
Simple calculation of the line integral
"""
def __init__(self):
StatBase.__init__(self, name="integral", compatibleKinds=("curve",))
def calculate(self, context):
xData, yData = context.data
return trapezoid(x=xData, y=yData)
class COM(StatBase):
"""
Compute data center of mass
"""
def __init__(self):
StatBase.__init__(self, name="COM", description="Center of mass")
def calculate(self, context):
if context.kind in ("curve", "histogram"):
xData, yData = context.data
deno = numpy.sum(yData).astype(numpy.float32)
if deno == 0.0:
return 0.0
else:
return numpy.sum(xData * yData).astype(numpy.float32) / deno
elif context.kind == "scatter":
xData, yData, values = context.data
values = values.astype(numpy.float64)
deno = numpy.sum(values)
if deno == 0.0:
return float("inf"), float("inf")
else:
comX = numpy.sum(xData * values) / deno
comY = numpy.sum(yData * values) / deno
return comX, comY
def main(argv):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--update-mode", default="auto", help="update mode to display (manual or auto)"
)
options = parser.parse_args(argv[1:])
app = qt.QApplication([])
plot = Plot1D()
# Create the thread that calls submitToQtMainThread
updateThread = UpdateThread(plot)
updateThread.start() # Start updating the plot
plot.addScatter(
x=[0, 2, 5, 5, 12, 20],
y=[2, 3, 4, 20, 15, 6],
value=[5, 6, 7, 10, 90, 20],
colormap=Colormap("viridis"),
legend="myScatter",
)
stats = [
("sum", numpy.sum),
Integral(),
(COM(), "{0:.2f}"),
]
plot.getStatsWidget().setStats(stats)
plot.getStatsWidget().setUpdateMode(options.update_mode)
plot.getStatsWidget().setDisplayOnlyActiveItem(False)
plot.getStatsWidget().parent().setVisible(True)
plot.show()
app.exec()
updateThread.stop() # Stop updating the plot
if __name__ == "__main__":
import sys
main(sys.argv)
|