mirror of
https://github.com/bec-project/bec_widgets.git
synced 2026-04-08 01:37:53 +02:00
Compare commits
3 Commits
v0.43.0
...
94-bec-fig
| Author | SHA1 | Date | |
|---|---|---|---|
| d996ff9284 | |||
| 8b43eba282 | |||
| 9c822ec480 |
@@ -1,7 +1,7 @@
|
||||
# This file is a template, and might need editing before it works on your project.
|
||||
# Official language image. Look for the different tagged releases at:
|
||||
# https://hub.docker.com/r/library/python/tags/
|
||||
image: $CI_DOCKER_REGISTRY/python:3.10
|
||||
image: $CI_DOCKER_REGISTRY/python:3.9
|
||||
#commands to run in the Docker container before starting each job.
|
||||
variables:
|
||||
DOCKER_TLS_CERTDIR: ""
|
||||
@@ -91,16 +91,23 @@ tests:
|
||||
coverage_format: cobertura
|
||||
path: coverage.xml
|
||||
|
||||
#tests-3.10-pyqt5: #todo enable when we decide what qt distributions we want to support
|
||||
#tests-3.9-pyqt5: #todo enable when we decide what qt distributions we want to support
|
||||
# extends: "tests"
|
||||
# stage: AdditionalTests
|
||||
# image: $CI_DOCKER_REGISTRY/python:3.10
|
||||
# image: $CI_DOCKER_REGISTRY/python:3.9
|
||||
# script:
|
||||
# - apt-get update
|
||||
# - apt-get install -y libgl1-mesa-glx libegl1-mesa x11-utils libxkbcommon-x11-0 libdbus-1-3
|
||||
# - pip install .[dev,pyqt5]
|
||||
# - pytest -v --random-order ./tests
|
||||
|
||||
tests-3.10:
|
||||
extends: "tests"
|
||||
stage: AdditionalTests
|
||||
image: $CI_DOCKER_REGISTRY/python:3.10
|
||||
allow_failure: true
|
||||
|
||||
|
||||
tests-3.11:
|
||||
extends: "tests"
|
||||
stage: AdditionalTests
|
||||
@@ -134,9 +141,9 @@ semver:
|
||||
- export REPOSITORY_USERNAME=__token__
|
||||
- export REPOSITORY_PASSWORD=$CI_PYPI_TOKEN
|
||||
- >
|
||||
semantic-release publish -v DEBUG
|
||||
-D version_variable=./setup.py:__version__
|
||||
-D hvcs=gitlab
|
||||
semantic-release publish -v DEBUG
|
||||
-D version_variable=./setup.py:__version__
|
||||
-D hvcs=gitlab
|
||||
|
||||
allow_failure: false
|
||||
rules:
|
||||
|
||||
@@ -52,7 +52,7 @@ persistent=yes
|
||||
|
||||
# Minimum Python version to use for version dependent checks. Will default to
|
||||
# the version used to run pylint.
|
||||
py-version=3.10
|
||||
py-version=3.9
|
||||
|
||||
# When enabled, pylint would attempt to guess common misconfiguration and emit
|
||||
# user-friendly hints instead of false-positive error messages.
|
||||
|
||||
@@ -9,7 +9,7 @@ version: 2
|
||||
build:
|
||||
os: ubuntu-20.04
|
||||
tools:
|
||||
python: "3.10"
|
||||
python: "3.9"
|
||||
|
||||
# Build documentation in the docs/ directory with Sphinx
|
||||
sphinx:
|
||||
|
||||
46
CHANGELOG.md
46
CHANGELOG.md
@@ -2,52 +2,6 @@
|
||||
|
||||
<!--next-version-placeholder-->
|
||||
|
||||
## v0.43.0 (2024-03-14)
|
||||
|
||||
### Feature
|
||||
|
||||
* **plots/image:** Image processor can run in threaded or non-threaded version ([`4865b10`](https://gitlab.psi.ch/bec/bec-widgets/-/commit/4865b10ced6b321974e7b4b4db12786fe21fd916))
|
||||
* **plots/image:** Change stream processor to QThread with connector.get_last; cleanup method for BECFigure to kill all threads if App is closed during acquisition ([`7ffedd9`](https://gitlab.psi.ch/bec/bec-widgets/-/commit/7ffedd9cebb382fc22f24a6b0b46823db6378d89))
|
||||
* **plots/image:** Basic image visualisation, getting data are based on stream_connector (deprecated) ([`9ad0055`](https://gitlab.psi.ch/bec/bec-widgets/-/commit/9ad0055336dba50886504a616db6f9f63b23beb3))
|
||||
|
||||
### Fix
|
||||
|
||||
* **plots/waveform1d:** Curves_data access disabled ([`598479b`](https://gitlab.psi.ch/bec/bec-widgets/-/commit/598479bb555a6cd077d5a137052d91314e5af6b7))
|
||||
* **cli:** Find_widget_by_id for BECImageShow changed to be compatible with RPC logic ([`4ef6ae9`](https://gitlab.psi.ch/bec/bec-widgets/-/commit/4ef6ae90f2afd5e2442465c11ce5165517cd4218))
|
||||
* **plots/image:** Access pattern for ImageItems in BECImageShow ([`3362fab`](https://gitlab.psi.ch/bec/bec-widgets/-/commit/3362fabed7ccd611b35f524c1970aeefbf3a9faf))
|
||||
* **cli:** Fix cli connector.send to set_and_publish for gui_instruction_response ([`4076698`](https://gitlab.psi.ch/bec/bec-widgets/-/commit/407669853097b40e6fba7d43da001f083140ad74))
|
||||
|
||||
## v0.42.1 (2024-03-10)
|
||||
|
||||
### Fix
|
||||
|
||||
* **various:** Repo cleanup, removed - [plot_app, one_plot, scan_plot, scan2d_plot, crosshair_example, qtplugins], tests adjusted ([`f3b3c2f`](https://gitlab.psi.ch/bec/bec-widgets/-/commit/f3b3c2f526d66687b3cc596a5877921953dd0803))
|
||||
|
||||
## v0.42.0 (2024-03-07)
|
||||
|
||||
### Feature
|
||||
|
||||
* **utils/bec_dispatcher:** BECDispatcher can register redis stream ([`4c0a7bb`](https://gitlab.psi.ch/bec/bec-widgets/-/commit/4c0a7bbec7abafc7d04a8aaf10dabd7e668fa908))
|
||||
|
||||
## v0.41.4 (2024-03-07)
|
||||
|
||||
### Fix
|
||||
|
||||
* **utils/bec_dispatcher:** BECDispatcher can accept new EndpointInfo dataclass. ([`c319dac`](https://gitlab.psi.ch/bec/bec-widgets/-/commit/c319dacb24e64930af258a81484feeadcb1bc341))
|
||||
|
||||
## v0.41.3 (2024-03-01)
|
||||
|
||||
### Fix
|
||||
|
||||
* **cli/generate_cli:** Typing.get_overloads are only used if the python version is higher than 3.11 ([`f386563`](https://gitlab.psi.ch/bec/bec-widgets/-/commit/f386563aa162eaca9202af16574860bf3eb5a092))
|
||||
* **cli/generate_cli:** Added automatic black formatting; added black as a dependency ([`d89f596`](https://gitlab.psi.ch/bec/bec-widgets/-/commit/d89f596a5d0f0674b1ef3268a9cfee5e32b64ba5))
|
||||
|
||||
## v0.41.2 (2024-02-28)
|
||||
|
||||
### Fix
|
||||
|
||||
* **utils/bec_dispatcher:** Msg is unp[acked from dict before accessing .content ([`bb1f066`](https://gitlab.psi.ch/bec/bec-widgets/-/commit/bb1f066c3c5e5076a8906e309030cfb47a6cad12))
|
||||
|
||||
## v0.41.1 (2024-02-26)
|
||||
|
||||
### Fix
|
||||
|
||||
@@ -101,15 +101,7 @@ class BECPlotBase(RPCBase):
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def lock_aspect_ratio(self, lock):
|
||||
"""
|
||||
Lock aspect ratio.
|
||||
Args:
|
||||
lock(bool): True to lock, False to unlock.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def plot(self, data_x: "list | np.ndarray", data_y: "list | np.ndarray", **kwargs):
|
||||
def plot_data(self, data_x: "list | np.ndarray", data_y: "list | np.ndarray", **kwargs):
|
||||
"""
|
||||
Plot custom data on the plot widget. These data are not saved in config.
|
||||
Args:
|
||||
@@ -202,6 +194,15 @@ class BECWaveform1D(RPCBase):
|
||||
list: List of curves.
|
||||
"""
|
||||
|
||||
@property
|
||||
@rpc_call
|
||||
def curves_data(self) -> "dict":
|
||||
"""
|
||||
Get the curves data of the plot widget as a dictionary
|
||||
Returns:
|
||||
dict: Dictionary of curves data.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def get_curve(self, identifier) -> "BECCurve":
|
||||
"""
|
||||
@@ -262,78 +263,6 @@ class BECFigure(RPCBase, BECFigureClientMixin):
|
||||
**axis_kwargs(dict): Additional axis properties to set on the widget after creation.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def add_image(
|
||||
self,
|
||||
widget_id: "str" = None,
|
||||
row: "int" = None,
|
||||
col: "int" = None,
|
||||
config=None,
|
||||
color_map: "str" = "magma",
|
||||
color_bar: "Literal['simple', 'full']" = "full",
|
||||
vrange: "tuple[float, float]" = None,
|
||||
**axis_kwargs
|
||||
) -> "BECImageShow":
|
||||
"""
|
||||
None
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def plot(
|
||||
self,
|
||||
x_name: "str" = None,
|
||||
y_name: "str" = None,
|
||||
x_entry: "str" = None,
|
||||
y_entry: "str" = None,
|
||||
x: "list | np.ndarray" = None,
|
||||
y: "list | np.ndarray" = None,
|
||||
color: "Optional[str]" = None,
|
||||
label: "Optional[str]" = None,
|
||||
validate: "bool" = True,
|
||||
**axis_kwargs
|
||||
) -> "BECWaveform1D":
|
||||
"""
|
||||
Add a 1D waveform plot to the figure.
|
||||
Args:
|
||||
x_name(str): The name of the device for the x-axis.
|
||||
y_name(str): The name of the device for the y-axis.
|
||||
x_entry(str): The name of the entry for the x-axis.
|
||||
y_entry(str): The name of the entry for the y-axis.
|
||||
x(list | np.ndarray): Custom x data to plot.
|
||||
y(list | np.ndarray): Custom y data to plot.
|
||||
color(str): The color of the curve.
|
||||
label(str): The label of the curve.
|
||||
validate(bool): If True, validate the device names and entries.
|
||||
**axis_kwargs: Additional axis properties to set on the widget after creation.
|
||||
|
||||
Returns:
|
||||
BECWaveform1D: The waveform plot widget.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def image(
|
||||
self,
|
||||
monitor: "str" = None,
|
||||
color_bar: "Literal['simple', 'full']" = "full",
|
||||
color_map: "str" = "magma",
|
||||
data: "np.ndarray" = None,
|
||||
vrange: "tuple[float, float]" = None,
|
||||
**axis_kwargs
|
||||
) -> "BECImageShow":
|
||||
"""
|
||||
Add an image to the figure.
|
||||
Args:
|
||||
monitor(str): The name of the monitor to display.
|
||||
color_bar(Literal["simple","full"]): The type of color bar to display.
|
||||
color_map(str): The color map to use for the image.
|
||||
data(np.ndarray): Custom data to display.
|
||||
vrange(tuple[float, float]): The range of values to display.
|
||||
**axis_kwargs: Additional axis properties to set on the widget after creation.
|
||||
|
||||
Returns:
|
||||
BECImageShow: The image widget.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def remove(
|
||||
self,
|
||||
@@ -376,16 +305,6 @@ class BECFigure(RPCBase, BECFigureClientMixin):
|
||||
Clear all widgets from the figure and reset to default state
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def get_config(self, dict_output: "bool" = True) -> "dict | BaseModel":
|
||||
"""
|
||||
Get the configuration of the widget.
|
||||
Args:
|
||||
dict_output(bool): If True, return the configuration as a dictionary. If False, return the configuration as a pydantic model.
|
||||
Returns:
|
||||
dict: The configuration of the plot widget.
|
||||
"""
|
||||
|
||||
|
||||
class BECCurve(RPCBase):
|
||||
@rpc_call
|
||||
@@ -465,211 +384,3 @@ class BECCurve(RPCBase):
|
||||
Returns:
|
||||
tuple[np.ndarray,np.ndarray]: X and Y data of the curve.
|
||||
"""
|
||||
|
||||
|
||||
class BECImageShow(RPCBase):
|
||||
@rpc_call
|
||||
def add_image_by_config(self, config: "ImageItemConfig | dict") -> "BECImageItem":
|
||||
"""
|
||||
Add an image to the widget by configuration.
|
||||
Args:
|
||||
config(ImageItemConfig|dict): The configuration of the image.
|
||||
|
||||
Returns:
|
||||
BECImageItem: The image object.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def get_image_config(self, image_id, dict_output: "bool" = True) -> "ImageItemConfig | dict":
|
||||
"""
|
||||
Get the configuration of the image.
|
||||
Args:
|
||||
image_id(str): The ID of the image.
|
||||
dict_output(bool): Whether to return the configuration as a dictionary. Defaults to True.
|
||||
|
||||
Returns:
|
||||
ImageItemConfig|dict: The configuration of the image.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def get_image_list(self) -> "list[BECImageItem]":
|
||||
"""
|
||||
Get the list of images.
|
||||
Returns:
|
||||
list[BECImageItem]: The list of images.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def get_image_dict(self) -> "dict[str, dict[str, BECImageItem]]":
|
||||
"""
|
||||
Get all images.
|
||||
Returns:
|
||||
dict[str, dict[str, BECImageItem]]: The dictionary of images.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def add_monitor_image(
|
||||
self,
|
||||
monitor: "str",
|
||||
color_map: "Optional[str]" = "magma",
|
||||
color_bar: "Optional[Literal['simple', 'full']]" = "simple",
|
||||
downsample: "Optional[bool]" = True,
|
||||
opacity: "Optional[float]" = 1.0,
|
||||
vrange: "Optional[tuple[int, int]]" = None,
|
||||
**kwargs
|
||||
) -> "BECImageItem":
|
||||
"""
|
||||
None
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def add_custom_image(
|
||||
self,
|
||||
name: "str",
|
||||
data: "Optional[np.ndarray]" = None,
|
||||
color_map: "Optional[str]" = "magma",
|
||||
color_bar: "Optional[Literal['simple', 'full']]" = "simple",
|
||||
downsample: "Optional[bool]" = True,
|
||||
opacity: "Optional[float]" = 1.0,
|
||||
vrange: "Optional[tuple[int, int]]" = None,
|
||||
**kwargs
|
||||
):
|
||||
"""
|
||||
None
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def set_vrange(self, vmin: "float", vmax: "float", name: "str" = None):
|
||||
"""
|
||||
Set the range of the color bar.
|
||||
If name is not specified, then set vrange for all images.
|
||||
Args:
|
||||
vmin(float): Minimum value of the color bar.
|
||||
vmax(float): Maximum value of the color bar.
|
||||
name(str): The name of the image. If None, apply to all images.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def set_color_map(self, cmap: "str", name: "str" = None):
|
||||
"""
|
||||
Set the color map of the image.
|
||||
If name is not specified, then set color map for all images.
|
||||
Args:
|
||||
cmap(str): The color map of the image.
|
||||
name(str): The name of the image. If None, apply to all images.
|
||||
"""
|
||||
|
||||
|
||||
class BECConnector(RPCBase):
|
||||
@rpc_call
|
||||
def get_config(self, dict_output: "bool" = True) -> "dict | BaseModel":
|
||||
"""
|
||||
Get the configuration of the widget.
|
||||
Args:
|
||||
dict_output(bool): If True, return the configuration as a dictionary. If False, return the configuration as a pydantic model.
|
||||
Returns:
|
||||
dict: The configuration of the plot widget.
|
||||
"""
|
||||
|
||||
|
||||
class BECImageItem(RPCBase):
|
||||
@rpc_call
|
||||
def set(self, **kwargs):
|
||||
"""
|
||||
Set the properties of the image.
|
||||
Args:
|
||||
**kwargs: Keyword arguments for the properties to be set.
|
||||
Possible properties:
|
||||
- downsample
|
||||
- color_map
|
||||
- monitor
|
||||
- opacity
|
||||
- vrange
|
||||
- fft
|
||||
- log
|
||||
- rot
|
||||
- transpose
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def set_fft(self, enable: "bool" = False):
|
||||
"""
|
||||
Set the FFT of the image.
|
||||
Args:
|
||||
enable(bool): Whether to perform FFT on the monitor data.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def set_log(self, enable: "bool" = False):
|
||||
"""
|
||||
Set the log of the image.
|
||||
Args:
|
||||
enable(bool): Whether to perform log on the monitor data.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def set_rotation(self, deg_90: "int" = 0):
|
||||
"""
|
||||
Set the rotation of the image.
|
||||
Args:
|
||||
deg_90(int): The rotation angle of the monitor data before displaying.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def set_transpose(self, enable: "bool" = False):
|
||||
"""
|
||||
Set the transpose of the image.
|
||||
Args:
|
||||
enable(bool): Whether to transpose the image.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def set_opacity(self, opacity: "float" = 1.0):
|
||||
"""
|
||||
Set the opacity of the image.
|
||||
Args:
|
||||
opacity(float): The opacity of the image.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def set_autorange(self, autorange: "bool" = True):
|
||||
"""
|
||||
Set the autorange of the color bar.
|
||||
Args:
|
||||
autorange(bool): Whether to autorange the color bar.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def set_color_map(self, cmap: "str" = "magma"):
|
||||
"""
|
||||
Set the color map of the image.
|
||||
Args:
|
||||
cmap(str): The color map of the image.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def set_auto_downsample(self, auto: "bool" = True):
|
||||
"""
|
||||
Set the auto downsample of the image.
|
||||
Args:
|
||||
auto(bool): Whether to downsample the image.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def set_monitor(self, monitor: "str"):
|
||||
"""
|
||||
Set the monitor of the image.
|
||||
Args:
|
||||
monitor(str): The name of the monitor.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def set_vrange(
|
||||
self, vmin: "float" = None, vmax: "float" = None, vrange: "tuple[int, int]" = None
|
||||
):
|
||||
"""
|
||||
Set the range of the color bar.
|
||||
Args:
|
||||
vmin(float): Minimum value of the color bar.
|
||||
vmax(float): Maximum value of the color bar.
|
||||
"""
|
||||
|
||||
@@ -132,7 +132,7 @@ class RPCBase:
|
||||
print(f"RPCBase: {rpc_msg}")
|
||||
# pylint: disable=protected-access
|
||||
receiver = self._root._gui_id
|
||||
self._client.connector.set_and_publish(MessageEndpoints.gui_instructions(receiver), rpc_msg)
|
||||
self._client.connector.send(MessageEndpoints.gui_instructions(receiver), rpc_msg)
|
||||
|
||||
if not wait_for_rpc_response:
|
||||
return None
|
||||
|
||||
@@ -1,21 +1,5 @@
|
||||
# pylint: disable=missing-module-docstring
|
||||
from __future__ import annotations
|
||||
import inspect
|
||||
import black
|
||||
import sys
|
||||
|
||||
|
||||
if sys.version_info >= (3, 11):
|
||||
from typing import get_overloads
|
||||
else:
|
||||
print(
|
||||
"Python version is less than 3.11, using dummy function for get_overloads. "
|
||||
"If you want to use the real function 'typing.get_overloads()', please use Python 3.11 or later."
|
||||
)
|
||||
|
||||
def get_overloads(obj):
|
||||
# Dummy function for Python versions before 3.11
|
||||
return []
|
||||
import typing
|
||||
|
||||
|
||||
class ClientGenerator:
|
||||
@@ -69,7 +53,7 @@ class {class_name}(RPCBase):"""
|
||||
else:
|
||||
sig = str(inspect.signature(obj))
|
||||
doc = inspect.getdoc(obj)
|
||||
overloads = get_overloads(obj)
|
||||
overloads = typing.get_overloads(obj)
|
||||
for overload in overloads:
|
||||
sig_overload = str(inspect.signature(overload))
|
||||
self.content += f"""
|
||||
@@ -87,42 +71,26 @@ class {class_name}(RPCBase):"""
|
||||
|
||||
def write(self, file_name: str):
|
||||
"""
|
||||
Write the content to a file, automatically formatted with black.
|
||||
Write the content to a file.
|
||||
|
||||
Args:
|
||||
file_name(str): The name of the file to write to.
|
||||
"""
|
||||
# Combine header and content, then format with black
|
||||
full_content = self.header + "\n" + self.content
|
||||
try:
|
||||
formatted_content = black.format_str(full_content, mode=black.FileMode(line_length=100))
|
||||
except black.NothingChanged:
|
||||
formatted_content = full_content
|
||||
|
||||
with open(file_name, "w", encoding="utf-8") as file:
|
||||
file.write(formatted_content)
|
||||
file.write(self.header)
|
||||
file.write(self.content)
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
if __name__ == "__main__":
|
||||
import os
|
||||
|
||||
from bec_widgets.widgets.figure import BECFigure
|
||||
from bec_widgets.widgets.plots import BECPlotBase, BECWaveform1D, BECImageShow
|
||||
from bec_widgets.widgets.plots import BECPlotBase, BECWaveform1D # ,BECCurve
|
||||
from bec_widgets.widgets.plots.waveform1d import BECCurve
|
||||
from bec_widgets.widgets.plots.image import BECImageItem
|
||||
from bec_widgets.utils import BECConnector
|
||||
|
||||
current_path = os.path.dirname(__file__)
|
||||
client_path = os.path.join(current_path, "client.py")
|
||||
clss = [
|
||||
BECPlotBase,
|
||||
BECWaveform1D,
|
||||
BECFigure,
|
||||
BECCurve,
|
||||
BECImageShow,
|
||||
BECConnector,
|
||||
BECImageItem,
|
||||
]
|
||||
clss = [BECPlotBase, BECWaveform1D, BECFigure, BECCurve]
|
||||
generator = ClientGenerator()
|
||||
generator.generate_client(clss)
|
||||
generator.write(client_path)
|
||||
|
||||
@@ -5,11 +5,11 @@ from bec_lib import MessageEndpoints, messages
|
||||
from bec_widgets.utils import BECDispatcher
|
||||
from bec_widgets.utils.bec_connector import BECConnector
|
||||
from bec_widgets.widgets.figure import BECFigure
|
||||
from bec_widgets.widgets.plots import BECCurve, BECWaveform1D, BECImageShow
|
||||
from bec_widgets.widgets.plots import BECCurve, BECWaveform1D
|
||||
|
||||
|
||||
class BECWidgetsCLIServer:
|
||||
WIDGETS = [BECWaveform1D, BECFigure, BECCurve, BECImageShow]
|
||||
WIDGETS = [BECWaveform1D, BECFigure, BECCurve]
|
||||
|
||||
def __init__(self, gui_id: str = None, dispatcher: BECDispatcher = None) -> None:
|
||||
self.dispatcher = BECDispatcher() if dispatcher is None else dispatcher
|
||||
@@ -42,7 +42,7 @@ class BECWidgetsCLIServer:
|
||||
self.send_response(request_id, True, {"result": res})
|
||||
|
||||
def send_response(self, request_id: str, accepted: bool, msg: dict):
|
||||
self.client.connector.set_and_publish(
|
||||
self.client.connector.set(
|
||||
MessageEndpoints.gui_instruction_response(request_id),
|
||||
messages.RequestResponseMessage(accepted=accepted, message=msg),
|
||||
expire=60,
|
||||
@@ -62,9 +62,9 @@ class BECWidgetsCLIServer:
|
||||
item = widget.find_widget_by_id(gui_id)
|
||||
if item:
|
||||
return item
|
||||
# raise NotImplementedError(
|
||||
# f"gui_id lookup for widget of type {widget.__class__.__name__} not implemented"
|
||||
# )
|
||||
raise NotImplementedError(
|
||||
f"gui_id lookup for widget of type {widget.__class__.__name__} not implemented"
|
||||
)
|
||||
|
||||
raise ValueError(f"Object with gui_id {gui_id} not found")
|
||||
|
||||
@@ -97,7 +97,7 @@ class BECWidgetsCLIServer:
|
||||
return obj
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description="BEC Widgets CLI Server")
|
||||
|
||||
0
bec_widgets/examples/crosshair_example/__init__.py
Normal file
0
bec_widgets/examples/crosshair_example/__init__.py
Normal file
168
bec_widgets/examples/crosshair_example/crosshair_example.py
Normal file
168
bec_widgets/examples/crosshair_example/crosshair_example.py
Normal file
@@ -0,0 +1,168 @@
|
||||
import numpy as np
|
||||
import pyqtgraph as pg
|
||||
from qtpy.QtWidgets import (
|
||||
QApplication,
|
||||
QVBoxLayout,
|
||||
QLabel,
|
||||
QWidget,
|
||||
QHBoxLayout,
|
||||
QTableWidget,
|
||||
QTableWidgetItem,
|
||||
QSpinBox,
|
||||
)
|
||||
from pyqtgraph import mkPen
|
||||
from pyqtgraph.Qt import QtCore
|
||||
from bec_widgets.utils import Crosshair
|
||||
|
||||
|
||||
class ExampleApp(QWidget):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
# Layout
|
||||
self.layout = QHBoxLayout()
|
||||
self.setLayout(self.layout)
|
||||
|
||||
##########################
|
||||
# 1D Plot
|
||||
##########################
|
||||
|
||||
# PlotWidget
|
||||
self.plot_widget_1d = pg.PlotWidget(title="1D PlotWidget with multiple curves")
|
||||
self.plot_item_1d = self.plot_widget_1d.getPlotItem()
|
||||
self.plot_item_1d.setLogMode(True, True)
|
||||
|
||||
# 1D Datasets
|
||||
self.x_data = np.linspace(0, 10, 1000)
|
||||
|
||||
def gauss(x, mu, sigma):
|
||||
return (1 / (sigma * np.sqrt(2 * np.pi))) * np.exp(-0.5 * ((x - mu) / sigma) ** 2)
|
||||
|
||||
# same convention as in line_plot.py
|
||||
self.y_value_list = [
|
||||
gauss(self.x_data, 1, 1),
|
||||
gauss(self.x_data, 1.5, 3),
|
||||
abs(np.sin(self.x_data)),
|
||||
abs(np.cos(self.x_data)),
|
||||
abs(np.sin(2 * self.x_data)),
|
||||
] # List of y-values for multiple curves
|
||||
|
||||
self.curve_names = ["Gauss(1,1)", "Gauss(1.5,3)", "Abs(Sine)", "Abs(Cosine)", "Abs(Sine2x)"]
|
||||
self.curves = []
|
||||
|
||||
##########################
|
||||
# 2D Plot
|
||||
##########################
|
||||
self.plot_widget_2d = pg.PlotWidget(title="2D plot with crosshair and ROI square")
|
||||
self.data_2D = np.random.random((100, 200))
|
||||
self.plot_item_2d = self.plot_widget_2d.getPlotItem()
|
||||
self.image_item = pg.ImageItem(self.data_2D)
|
||||
self.plot_item_2d.addItem(self.image_item)
|
||||
|
||||
##########################
|
||||
# Table
|
||||
##########################
|
||||
self.table = QTableWidget(len(self.curve_names), 2)
|
||||
self.table.setHorizontalHeaderLabels(["(X, Y) - Moved", "(X, Y) - Clicked"])
|
||||
self.table.setVerticalHeaderLabels(self.curve_names)
|
||||
self.table.resizeColumnsToContents()
|
||||
|
||||
##########################
|
||||
# Spinbox for N curves
|
||||
##########################
|
||||
self.spin_box = QSpinBox()
|
||||
self.spin_box.setMinimum(0)
|
||||
self.spin_box.setMaximum(len(self.y_value_list))
|
||||
self.spin_box.setValue(2)
|
||||
self.spin_box.valueChanged.connect(lambda: self.update_curves(self.spin_box.value()))
|
||||
|
||||
##########################
|
||||
# Adding widgets to layout
|
||||
##########################
|
||||
|
||||
##### left side #####
|
||||
self.column1 = QVBoxLayout()
|
||||
self.layout.addLayout(self.column1)
|
||||
|
||||
# SpinBox
|
||||
self.spin_row = QHBoxLayout()
|
||||
self.column1.addLayout(self.spin_row)
|
||||
self.spin_row.addWidget(QLabel("Number of curves:"))
|
||||
self.spin_row.addWidget(self.spin_box)
|
||||
|
||||
# label
|
||||
self.clicked_label_1d = QLabel("Clicked Coordinates (1D):")
|
||||
self.column1.addWidget(self.clicked_label_1d)
|
||||
|
||||
# table
|
||||
self.column1.addWidget(self.table)
|
||||
|
||||
# 1D plot
|
||||
self.column1.addWidget(self.plot_widget_1d)
|
||||
|
||||
##### left side #####
|
||||
self.column2 = QVBoxLayout()
|
||||
self.layout.addLayout(self.column2)
|
||||
|
||||
# labels
|
||||
self.clicked_label_2d = QLabel("Clicked Coordinates (2D):")
|
||||
self.moved_label_2d = QLabel("Moved Coordinates (2D):")
|
||||
self.column2.addWidget(self.clicked_label_2d)
|
||||
self.column2.addWidget(self.moved_label_2d)
|
||||
|
||||
# 2D plot
|
||||
self.column2.addWidget(self.plot_widget_2d)
|
||||
|
||||
self.update_curves(2) # just Gaussian curves
|
||||
|
||||
def hook_crosshair(self):
|
||||
self.crosshair_1d = Crosshair(self.plot_item_1d, precision=10)
|
||||
self.crosshair_1d.coordinatesChanged1D.connect(
|
||||
lambda x, y: self.update_table(self.table, x, y, column=0)
|
||||
)
|
||||
self.crosshair_1d.coordinatesClicked1D.connect(
|
||||
lambda x, y: self.update_table(self.table, x, y, column=1)
|
||||
)
|
||||
# 2D
|
||||
self.crosshair_2d = Crosshair(self.plot_item_2d)
|
||||
self.crosshair_2d.coordinatesChanged2D.connect(
|
||||
lambda x, y: self.moved_label_2d.setText(f"Mouse Moved Coordinates (2D): x={x}, y={y}")
|
||||
)
|
||||
self.crosshair_2d.coordinatesClicked2D.connect(
|
||||
lambda x, y: self.clicked_label_2d.setText(f"Clicked Coordinates (2D): x={x}, y={y}")
|
||||
)
|
||||
|
||||
def update_table(self, table_widget, x, y_values, column):
|
||||
"""Update the table with the new coordinates"""
|
||||
for i, y in enumerate(y_values):
|
||||
table_widget.setItem(i, column, QTableWidgetItem(f"({x}, {y})"))
|
||||
table_widget.resizeColumnsToContents()
|
||||
|
||||
def update_curves(self, num_curves):
|
||||
"""Update the number of curves"""
|
||||
|
||||
self.plot_item_1d.clear()
|
||||
|
||||
# Curves
|
||||
color_list = ["#384c6b", "#e28a2b", "#5E3023", "#e41a1c", "#984e83", "#4daf4a"]
|
||||
self.plot_item_1d.addLegend()
|
||||
self.curves = []
|
||||
|
||||
y_value_list = self.y_value_list[:num_curves]
|
||||
|
||||
for ii, y_value in enumerate(y_value_list):
|
||||
pen = mkPen(color=color_list[ii], width=2, style=QtCore.Qt.DashLine)
|
||||
curve = pg.PlotDataItem(
|
||||
self.x_data, y_value, pen=pen, skipFiniteCheck=True, name=self.curve_names[ii]
|
||||
)
|
||||
self.plot_item_1d.addItem(curve)
|
||||
self.curves.append(curve)
|
||||
|
||||
self.hook_crosshair()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app = QApplication([])
|
||||
window = ExampleApp()
|
||||
window.show()
|
||||
app.exec()
|
||||
@@ -2,7 +2,6 @@ from bec_lib import messages, MessageEndpoints, RedisConnector
|
||||
import time
|
||||
|
||||
connector = RedisConnector("localhost:6379")
|
||||
producer = connector.producer()
|
||||
metadata = {}
|
||||
|
||||
scanID = "ScanID1"
|
||||
@@ -20,9 +19,7 @@ for ii in range(20):
|
||||
metadata=metadata,
|
||||
).dumps()
|
||||
|
||||
# producer.send(topic=MessageEndpoints.device_status(device="mca"), msg=msg)
|
||||
|
||||
producer.xadd(
|
||||
connector.xadd(
|
||||
topic=MessageEndpoints.device_async_readback(
|
||||
scanID=scanID, device="mca"
|
||||
), # scanID will be different for each scan
|
||||
|
||||
0
bec_widgets/examples/oneplot/__init__.py
Normal file
0
bec_widgets/examples/oneplot/__init__.py
Normal file
3
bec_widgets/examples/oneplot/config_gaussworker.yaml
Normal file
3
bec_widgets/examples/oneplot/config_gaussworker.yaml
Normal file
@@ -0,0 +1,3 @@
|
||||
x_value: "samx"
|
||||
y_values: ["gauss_bpm", "gauss_adc1", "gauss_adc2"]
|
||||
dap_worker: "gaussian_fit_worker_3"
|
||||
3
bec_widgets/examples/oneplot/config_noworker.yaml
Normal file
3
bec_widgets/examples/oneplot/config_noworker.yaml
Normal file
@@ -0,0 +1,3 @@
|
||||
x_value: "samx"
|
||||
y_values: ["gauss_bpm", "gauss_adc1", "gauss_adc2"]
|
||||
dap_worker: None
|
||||
271
bec_widgets/examples/oneplot/oneplot.py
Normal file
271
bec_widgets/examples/oneplot/oneplot.py
Normal file
@@ -0,0 +1,271 @@
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import qtpy.QtWidgets
|
||||
import pyqtgraph as pg
|
||||
from bec_lib import MessageEndpoints
|
||||
from qtpy.QtCore import Signal as pyqtSignal, Slot as pyqtSlot
|
||||
from qtpy.QtWidgets import QApplication, QTableWidgetItem, QWidget
|
||||
from pyqtgraph import mkBrush, mkColor, mkPen
|
||||
from pyqtgraph.Qt import QtCore, uic
|
||||
|
||||
from bec_widgets.utils import Crosshair, ctrl_c
|
||||
from bec_widgets.utils.bec_dispatcher import BECDispatcher
|
||||
|
||||
|
||||
# TODO implement:
|
||||
# - implement scanID database for visualizing previous scans
|
||||
# - multiple signals for different monitors
|
||||
# - change how dap is handled in bec_dispatcher to handle more workers
|
||||
|
||||
|
||||
class PlotApp(QWidget):
|
||||
"""
|
||||
Main class for the PlotApp used to plot two signals from the BEC.
|
||||
|
||||
Attributes:
|
||||
update_signal (pyqtSignal): Signal to trigger plot updates.
|
||||
update_dap_signal (pyqtSignal): Signal to trigger DAP updates.
|
||||
|
||||
Args:
|
||||
x_value (str): The x device/signal for plotting.
|
||||
y_values (list of str): List of y device/signals for plotting.
|
||||
dap_worker (str, optional): DAP process to specify. Set to None to disable.
|
||||
parent (QWidget, optional): Parent widget.
|
||||
"""
|
||||
|
||||
update_signal = pyqtSignal()
|
||||
update_dap_signal = pyqtSignal()
|
||||
|
||||
def __init__(self, x_value, y_values, dap_worker=None, parent=None):
|
||||
super(PlotApp, self).__init__(parent)
|
||||
current_path = os.path.dirname(__file__)
|
||||
uic.loadUi(os.path.join(current_path, "oneplot.ui"), self)
|
||||
|
||||
self.x_value = x_value
|
||||
self.y_values = y_values
|
||||
self.dap_worker = dap_worker
|
||||
|
||||
self.scanID = None
|
||||
self.data_x = []
|
||||
self.data_y = []
|
||||
|
||||
self.dap_x = np.array([])
|
||||
self.dap_y = np.array([])
|
||||
|
||||
self.fit = None
|
||||
|
||||
self.init_ui()
|
||||
self.init_curves()
|
||||
self.hook_crosshair()
|
||||
|
||||
self.proxy_update_plot = pg.SignalProxy(
|
||||
self.update_signal, rateLimit=25, slot=self.update_plot
|
||||
)
|
||||
self.proxy_update_fit = pg.SignalProxy(
|
||||
self.update_dap_signal, rateLimit=25, slot=self.update_fit_table
|
||||
)
|
||||
|
||||
def init_ui(self) -> None:
|
||||
"""Initialize the UI components."""
|
||||
self.plot = pg.PlotItem()
|
||||
self.glw.addItem(self.plot)
|
||||
self.plot.setLabel("bottom", self.x_value)
|
||||
self.plot.setLabel("left", ", ".join(self.y_values))
|
||||
self.plot.addLegend()
|
||||
|
||||
def init_curves(self) -> None:
|
||||
"""Initialize curve data and properties."""
|
||||
self.plot.clear()
|
||||
|
||||
self.curves_data = []
|
||||
self.curves_dap = []
|
||||
|
||||
colors_y_values = PlotApp.golden_angle_color(colormap="CET-R2", num=len(self.y_values))
|
||||
# colors_y_daps = PlotApp.golden_angle_color(
|
||||
# colormap="CET-I2", num=len(self.dap_worker)
|
||||
# ) # TODO adapt for multiple dap_workers
|
||||
|
||||
# Initialize curves for y_values
|
||||
for ii, (signal, color) in enumerate(zip(self.y_values, colors_y_values)):
|
||||
pen_curve = mkPen(color=color, width=2, style=QtCore.Qt.DashLine)
|
||||
brush_curve = mkBrush(color=color)
|
||||
curve_data = pg.PlotDataItem(
|
||||
symbolSize=5,
|
||||
symbolBrush=brush_curve,
|
||||
pen=pen_curve,
|
||||
skipFiniteCheck=True,
|
||||
name=f"{signal}",
|
||||
)
|
||||
self.curves_data.append(curve_data)
|
||||
self.plot.addItem(curve_data)
|
||||
|
||||
# Initialize curves for DAP if dap_worker is not None
|
||||
if self.dap_worker is not None:
|
||||
# for ii, (monitor, color) in enumerate(zip(self.dap_worker, colors_y_daps)):#TODO adapt for multiple dap_workers
|
||||
pen_dap = mkPen(color="#3b5998", width=2, style=QtCore.Qt.DashLine)
|
||||
curve_dap = pg.PlotDataItem(
|
||||
pen=pen_dap, skipFiniteCheck=True, symbolSize=5, name=f"{self.dap_worker}"
|
||||
)
|
||||
self.curves_dap.append(curve_dap)
|
||||
self.plot.addItem(curve_dap)
|
||||
|
||||
self.tableWidget_crosshair.setRowCount(len(self.y_values))
|
||||
self.tableWidget_crosshair.setVerticalHeaderLabels(self.y_values)
|
||||
self.hook_crosshair()
|
||||
|
||||
def hook_crosshair(self) -> None:
|
||||
"""Attach the crosshair to the plot."""
|
||||
self.crosshair_1d = Crosshair(self.plot, precision=3)
|
||||
self.crosshair_1d.coordinatesChanged1D.connect(
|
||||
lambda x, y: self.update_table(self.tableWidget_crosshair, x, y, column=0)
|
||||
)
|
||||
self.crosshair_1d.coordinatesClicked1D.connect(
|
||||
lambda x, y: self.update_table(self.tableWidget_crosshair, x, y, column=1)
|
||||
)
|
||||
|
||||
def update_table(
|
||||
self, table_widget: qtpy.QtWidgets.QTableWidget, x: float, y_values: list, column: int
|
||||
) -> None:
|
||||
for i, y in enumerate(y_values):
|
||||
table_widget.setItem(i, column, QTableWidgetItem(f"({x}, {y})"))
|
||||
table_widget.resizeColumnsToContents()
|
||||
|
||||
def update_plot(self) -> None:
|
||||
"""Update the plot data."""
|
||||
for ii, curve in enumerate(self.curves_data):
|
||||
curve.setData(self.data_x, self.data_y[ii])
|
||||
|
||||
if self.dap_worker is not None:
|
||||
# for ii, curve in enumerate(self.curves_dap): #TODO adapt for multiple dap_workers
|
||||
# curve.setData(self.dap_x, self.dap_y[ii])
|
||||
self.curves_dap[0].setData(self.dap_x, self.dap_y)
|
||||
|
||||
def update_fit_table(self):
|
||||
"""Update the table for fit data."""
|
||||
|
||||
self.tableWidget_fit.setData(self.fit)
|
||||
|
||||
@pyqtSlot(dict, dict)
|
||||
def on_dap_update(self, msg: dict, metadata: dict) -> None:
|
||||
"""
|
||||
Update DAP related data.
|
||||
|
||||
Args:
|
||||
msg (dict): Message received with data.
|
||||
metadata (dict): Metadata of the DAP.
|
||||
"""
|
||||
|
||||
# TODO adapt for multiple dap_workers
|
||||
self.dap_x = msg[self.dap_worker]["x"]
|
||||
self.dap_y = msg[self.dap_worker]["y"]
|
||||
|
||||
self.fit = metadata["fit_parameters"]
|
||||
|
||||
self.update_dap_signal.emit()
|
||||
|
||||
@pyqtSlot(dict, dict)
|
||||
def on_scan_segment(self, msg: dict, metadata: dict):
|
||||
"""
|
||||
Handle new scan segments.
|
||||
|
||||
Args:
|
||||
msg (dict): Message received with scan data.
|
||||
metadata (dict): Metadata of the scan.
|
||||
"""
|
||||
current_scanID = msg["scanID"]
|
||||
|
||||
if current_scanID != self.scanID:
|
||||
self.scanID = current_scanID
|
||||
self.data_x = []
|
||||
self.data_y = [[] for _ in self.y_values]
|
||||
self.init_curves()
|
||||
|
||||
dev_x = self.x_value
|
||||
data_x = msg["data"][dev_x][dev[dev_x]._hints[0]]["value"]
|
||||
self.data_x.append(data_x)
|
||||
|
||||
for ii, dev_y in enumerate(self.y_values):
|
||||
data_y = msg["data"][dev_y][dev[dev_y]._hints[0]]["value"]
|
||||
self.data_y[ii].append(data_y)
|
||||
|
||||
self.update_signal.emit()
|
||||
|
||||
@staticmethod
|
||||
def golden_ratio(num: int) -> list:
|
||||
"""Calculate the golden ratio for a given number of angles.
|
||||
|
||||
Args:
|
||||
num (int): Number of angles
|
||||
"""
|
||||
phi = 2 * np.pi * ((1 + np.sqrt(5)) / 2)
|
||||
angles = []
|
||||
for ii in range(num):
|
||||
x = np.cos(ii * phi)
|
||||
y = np.sin(ii * phi)
|
||||
angle = np.arctan2(y, x)
|
||||
angles.append(angle)
|
||||
return angles
|
||||
|
||||
@staticmethod
|
||||
def golden_angle_color(colormap: str, num: int) -> list:
|
||||
"""
|
||||
Extract num colors for from the specified colormap following golden angle distribution.
|
||||
|
||||
Args:
|
||||
colormap (str): Name of the colormap
|
||||
num (int): Number of requested colors
|
||||
|
||||
Returns:
|
||||
list: List of colors with length <num>
|
||||
|
||||
Raises:
|
||||
ValueError: If the number of requested colors is greater than the number of colors in the colormap.
|
||||
"""
|
||||
|
||||
cmap = pg.colormap.get(colormap)
|
||||
cmap_colors = cmap.color
|
||||
if num > len(cmap_colors):
|
||||
raise ValueError(
|
||||
f"Number of colors requested ({num}) is greater than the number of colors in the colormap ({len(cmap_colors)})"
|
||||
)
|
||||
angles = PlotApp.golden_ratio(len(cmap_colors))
|
||||
color_selection = np.round(np.interp(angles, (-np.pi, np.pi), (0, len(cmap_colors))))
|
||||
colors = [
|
||||
mkColor(tuple((cmap_colors[int(ii)] * 255).astype(int))) for ii in color_selection[:num]
|
||||
]
|
||||
return colors
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import yaml
|
||||
|
||||
with open("config_noworker.yaml", "r") as file:
|
||||
config = yaml.safe_load(file)
|
||||
|
||||
x_value = config["x_value"]
|
||||
y_values = config["y_values"]
|
||||
dap_worker = config["dap_worker"]
|
||||
|
||||
dap_worker = None if dap_worker == "None" else dap_worker
|
||||
|
||||
# BECclient global variables
|
||||
bec_dispatcher = BECDispatcher()
|
||||
client = bec_dispatcher.client
|
||||
client.start()
|
||||
|
||||
dev = client.device_manager.devices
|
||||
scans = client.scans
|
||||
queue = client.queue
|
||||
|
||||
app = QApplication([])
|
||||
plotApp = PlotApp(x_value=x_value, y_values=y_values, dap_worker=dap_worker)
|
||||
|
||||
# Connecting signals from bec_dispatcher
|
||||
bec_dispatcher.connect_slot(plotApp.on_dap_update, MessageEndpoints.processed_data(dap_worker))
|
||||
bec_dispatcher.connect_slot(plotApp.on_scan_segment, MessageEndpoints.scan_segment())
|
||||
ctrl_c.setup(app)
|
||||
|
||||
window = plotApp
|
||||
window.show()
|
||||
app.exec()
|
||||
75
bec_widgets/examples/oneplot/oneplot.ui
Normal file
75
bec_widgets/examples/oneplot/oneplot.ui
Normal file
@@ -0,0 +1,75 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ui version="4.0">
|
||||
<class>Form</class>
|
||||
<widget class="QWidget" name="Form">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>547</width>
|
||||
<height>653</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>Form</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="verticalLayout" stretch="1,2">
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="horizontalLayout" stretch="2,1">
|
||||
<item>
|
||||
<widget class="QGroupBox" name="groupBox">
|
||||
<property name="title">
|
||||
<string>Cursor</string>
|
||||
</property>
|
||||
<layout class="QGridLayout" name="gridLayout">
|
||||
<item row="0" column="0">
|
||||
<widget class="QTableWidget" name="tableWidget_crosshair">
|
||||
<column>
|
||||
<property name="text">
|
||||
<string>Moved</string>
|
||||
</property>
|
||||
</column>
|
||||
<column>
|
||||
<property name="text">
|
||||
<string>Clicked</string>
|
||||
</property>
|
||||
</column>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QGroupBox" name="groupBox_2">
|
||||
<property name="title">
|
||||
<string>Fit</string>
|
||||
</property>
|
||||
<layout class="QGridLayout" name="gridLayout_2">
|
||||
<item row="0" column="0">
|
||||
<widget class="TableWidget" name="tableWidget_fit"/>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="GraphicsLayoutWidget" name="glw"/>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<customwidgets>
|
||||
<customwidget>
|
||||
<class>GraphicsLayoutWidget</class>
|
||||
<extends>QGraphicsView</extends>
|
||||
<header>pyqtgraph.h</header>
|
||||
</customwidget>
|
||||
<customwidget>
|
||||
<class>TableWidget</class>
|
||||
<extends>QTableWidget</extends>
|
||||
<header>pyqtgraph.h</header>
|
||||
</customwidget>
|
||||
</customwidgets>
|
||||
<resources/>
|
||||
<connections/>
|
||||
</ui>
|
||||
0
bec_widgets/examples/plot_app/__init__.py
Normal file
0
bec_widgets/examples/plot_app/__init__.py
Normal file
130
bec_widgets/examples/plot_app/config_example.yaml
Normal file
130
bec_widgets/examples/plot_app/config_example.yaml
Normal file
@@ -0,0 +1,130 @@
|
||||
plot_settings:
|
||||
background_color: "black"
|
||||
num_columns: 2
|
||||
colormap: "plasma"
|
||||
scan_types: False # True to show scan types
|
||||
|
||||
# example to use without scan_type -> only one general configuration
|
||||
plot_data:
|
||||
- plot_name: "BPM4i plots vs samy"
|
||||
x:
|
||||
label: 'Motor Y'
|
||||
signals:
|
||||
- name: "samy"
|
||||
# entry: "samy" # here I also forgot to specify entry
|
||||
y:
|
||||
label: 'bpm4i'
|
||||
signals:
|
||||
- name: "bpm4i"
|
||||
entry: "bpm4i"
|
||||
# I will not specify entry, because I want to take hint from gauss_adc2
|
||||
- plot_name: "BPM4i plots vs samx"
|
||||
x:
|
||||
label: 'Motor Y'
|
||||
signals:
|
||||
- name: "samy"
|
||||
# entry: "samy" # here I also forgot to specify entry
|
||||
y:
|
||||
label: 'bpm4i'
|
||||
signals:
|
||||
- name: "bpm4i"
|
||||
entry: "bpm4i"
|
||||
# I will not specify entry, because I want to take hint from gauss_adc2
|
||||
- plot_name: "MCS Channel 4 (Cyberstar) vs samx"
|
||||
x:
|
||||
label: 'Motor X'
|
||||
signals:
|
||||
- name: "samx"
|
||||
entry: "samx"
|
||||
y:
|
||||
label: 'mcs4 cyberstar'
|
||||
signals:
|
||||
- name: "mcs"
|
||||
entry: "mca4"
|
||||
- plot_name: "MCS Channel 4 (Cyberstar) vs samy"
|
||||
x:
|
||||
label: 'Motor X'
|
||||
signals:
|
||||
- name: "samy"
|
||||
entry: "samy"
|
||||
y:
|
||||
label: 'mcs4 cyberstar'
|
||||
signals:
|
||||
- name: "mcs"
|
||||
entry: "mca4"
|
||||
|
||||
|
||||
|
||||
# example to use with scan_type -> different configuration for different scan types
|
||||
#plot_data:
|
||||
# line_scan:
|
||||
# - plot_name: "BPM plot"
|
||||
# x:
|
||||
# label: 'Motor X'
|
||||
# signals:
|
||||
# - name: "samx"
|
||||
# # entry: "samx"
|
||||
# y:
|
||||
# label: 'BPM'
|
||||
# signals:
|
||||
# - name: "gauss_bpm"
|
||||
# entry: "gauss_bpm"
|
||||
# - name: "gauss_adc1"
|
||||
# entry: "gauss_adc1"
|
||||
# - name: "gauss_adc2"
|
||||
# entry: "gauss_adc2"
|
||||
#
|
||||
# - plot_name: "Multi"
|
||||
# x:
|
||||
# label: 'Motor X'
|
||||
# signals:
|
||||
# - name: "samx"
|
||||
# entry: "samx"
|
||||
# y:
|
||||
# label: 'Multi'
|
||||
# signals:
|
||||
# - name: "gauss_bpm"
|
||||
# entry: "gauss_bpm"
|
||||
# - name: "samx"
|
||||
# entry: ["samx", "samx_setpoint"]
|
||||
#
|
||||
# grid_scan:
|
||||
# - plot_name: "Grid plot 1"
|
||||
# x:
|
||||
# label: 'Motor X'
|
||||
# signals:
|
||||
# - name: "samx"
|
||||
# entry: "samx"
|
||||
# y:
|
||||
# label: 'BPM'
|
||||
# signals:
|
||||
# - name: "gauss_bpm"
|
||||
# entry: "gauss_bpm"
|
||||
# - name: "gauss_adc1"
|
||||
# entry: "gauss_adc1"
|
||||
# - plot_name: "Grid plot 2"
|
||||
# x:
|
||||
# label: 'Motor X'
|
||||
# signals:
|
||||
# - name: "samx"
|
||||
# entry: "samx"
|
||||
# y:
|
||||
# label: 'BPM'
|
||||
# signals:
|
||||
# - name: "gauss_bpm"
|
||||
# entry: "gauss_bpm"
|
||||
# - name: "gauss_adc1"
|
||||
# entry: "gauss_adc1"
|
||||
#
|
||||
# - plot_name: "Grid plot 3"
|
||||
# x:
|
||||
# label: 'Motor Y'
|
||||
# signals:
|
||||
# - name: "samy"
|
||||
# entry: "samy"
|
||||
# y:
|
||||
# label: 'BPM'
|
||||
# signals:
|
||||
# - name: "gauss_bpm"
|
||||
# entry: "gauss_bpm"
|
||||
|
||||
91
bec_widgets/examples/plot_app/config_scans_example.yaml
Normal file
91
bec_widgets/examples/plot_app/config_scans_example.yaml
Normal file
@@ -0,0 +1,91 @@
|
||||
plot_settings:
|
||||
background_color: "black"
|
||||
num_columns: 2
|
||||
colormap: "plasma"
|
||||
scan_types: True # True to show scan types
|
||||
|
||||
# example to use with scan_type -> different configuration for different scan types
|
||||
plot_data:
|
||||
line_scan:
|
||||
- plot_name: "BPM plot"
|
||||
x:
|
||||
label: 'Motor X'
|
||||
signals:
|
||||
- name: "samx"
|
||||
# entry: "samx"
|
||||
y:
|
||||
label: 'BPM'
|
||||
signals:
|
||||
- name: "gauss_bpm"
|
||||
entry: "gauss_bpm"
|
||||
- name: "gauss_adc1"
|
||||
entry: "gauss_adc1"
|
||||
- name: "gauss_adc2"
|
||||
entry: "gauss_adc2"
|
||||
|
||||
- plot_name: "Multi"
|
||||
x:
|
||||
label: 'Motor X'
|
||||
signals:
|
||||
- name: "samx"
|
||||
entry: "samx"
|
||||
y:
|
||||
label: 'Multi'
|
||||
signals:
|
||||
- name: "gauss_bpm"
|
||||
entry: "gauss_bpm"
|
||||
- name: "samx"
|
||||
entry: ["samx", "samx_setpoint"]
|
||||
|
||||
grid_scan:
|
||||
- plot_name: "Grid plot 1"
|
||||
x:
|
||||
label: 'Motor X'
|
||||
signals:
|
||||
- name: "samx"
|
||||
entry: "samx"
|
||||
y:
|
||||
label: 'BPM'
|
||||
signals:
|
||||
- name: "gauss_bpm"
|
||||
entry: "gauss_bpm"
|
||||
- name: "gauss_adc1"
|
||||
entry: "gauss_adc1"
|
||||
- plot_name: "Grid plot 2"
|
||||
x:
|
||||
label: 'Motor X'
|
||||
signals:
|
||||
- name: "samx"
|
||||
entry: "samx"
|
||||
y:
|
||||
label: 'BPM'
|
||||
signals:
|
||||
- name: "gauss_bpm"
|
||||
entry: "gauss_bpm"
|
||||
- name: "gauss_adc1"
|
||||
entry: "gauss_adc1"
|
||||
|
||||
- plot_name: "Grid plot 3"
|
||||
x:
|
||||
label: 'Motor Y'
|
||||
signals:
|
||||
- name: "samy"
|
||||
entry: "samy"
|
||||
y:
|
||||
label: 'BPM'
|
||||
signals:
|
||||
- name: "gauss_bpm"
|
||||
entry: "gauss_bpm"
|
||||
|
||||
- plot_name: "Grid plot 4"
|
||||
x:
|
||||
label: 'Motor Y'
|
||||
signals:
|
||||
- name: "samy"
|
||||
entry: "samy"
|
||||
y:
|
||||
label: 'BPM'
|
||||
signals:
|
||||
- name: "gauss_adc3"
|
||||
entry: "gauss_adc3"
|
||||
|
||||
730
bec_widgets/examples/plot_app/plot_app.py
Normal file
730
bec_widgets/examples/plot_app/plot_app.py
Normal file
@@ -0,0 +1,730 @@
|
||||
import logging
|
||||
import os
|
||||
|
||||
# import traceback
|
||||
|
||||
import pyqtgraph
|
||||
import pyqtgraph as pg
|
||||
|
||||
from qtpy.QtCore import Signal as pyqtSignal, Slot as pyqtSlot
|
||||
|
||||
from qtpy.QtWidgets import (
|
||||
QApplication,
|
||||
QWidget,
|
||||
QTableWidgetItem,
|
||||
QTableWidget,
|
||||
QFileDialog,
|
||||
QMessageBox,
|
||||
)
|
||||
from pyqtgraph import ColorButton
|
||||
from pyqtgraph import mkBrush, mkPen
|
||||
from pyqtgraph.Qt import QtCore, uic
|
||||
from pyqtgraph.Qt import QtWidgets
|
||||
|
||||
from bec_lib import MessageEndpoints
|
||||
from bec_widgets.utils import Crosshair, Colors
|
||||
from bec_widgets.utils.bec_dispatcher import BECDispatcher
|
||||
|
||||
|
||||
# TODO implement:
|
||||
# - implement scanID database for visualizing previous scans
|
||||
|
||||
|
||||
class PlotApp(QWidget):
|
||||
"""
|
||||
Main class for PlotApp, designed to plot multiple signals in a grid layout
|
||||
based on a flexible YAML configuration.
|
||||
|
||||
Attributes:
|
||||
update_signal (pyqtSignal): Signal to trigger plot updates.
|
||||
plot_data (list of dict): List of dictionaries containing plot configurations.
|
||||
Each dictionary specifies x and y signals, including their
|
||||
name and entry, for a particular plot.
|
||||
|
||||
Args:
|
||||
config (dict): Configuration dictionary containing all settings for the plotting app.
|
||||
It should include the following keys:
|
||||
- 'plot_settings': Dictionary containing global plot settings.
|
||||
- 'plot_data': List of dictionaries specifying the signals to plot.
|
||||
parent (QWidget, optional): Parent widget.
|
||||
|
||||
Example:
|
||||
General Plot Configuration:
|
||||
{
|
||||
'plot_settings': {'background_color': 'black', 'num_columns': 2, 'colormap': 'plasma', 'scan_types': False},
|
||||
'plot_data': [
|
||||
{
|
||||
'plot_name': 'Plot A',
|
||||
'x': {'label': 'X-axis', 'signals': [{'name': 'device_x', 'entry': 'entry_x'}]},
|
||||
'y': {'label': 'Y-axis', 'signals': [{'name': 'device_y', 'entry': 'entry_y'}]}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Different Scans Mode Configuration:
|
||||
{
|
||||
'plot_settings': {'background_color': 'black', 'num_columns': 2, 'colormap': 'plasma', 'scan_types': True},
|
||||
'plot_data': {
|
||||
'scan_type_1': [
|
||||
{
|
||||
'plot_name': 'Plot 1',
|
||||
'x': {'label': 'X-axis', 'signals': [{'name': 'device_x1', 'entry': 'entry_x1'}]},
|
||||
'y': {'label': 'Y-axis', 'signals': [{'name': 'device_y1', 'entry': 'entry_y1'}]}
|
||||
}
|
||||
],
|
||||
'scan_type_2': [
|
||||
{
|
||||
'plot_name': 'Plot 2',
|
||||
'x': {'label': 'X-axis', 'signals': [{'name': 'device_x2', 'entry': 'entry_x2'}]},
|
||||
'y': {'label': 'Y-axis', 'signals': [{'name': 'device_y2', 'entry': 'entry_y2'}]}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
update_signal = pyqtSignal()
|
||||
update_dap_signal = pyqtSignal()
|
||||
|
||||
def __init__(self, config: dict, client=None, parent=None):
|
||||
super(PlotApp, self).__init__(parent)
|
||||
|
||||
# Error handler
|
||||
self.error_handler = ErrorHandler(parent=self)
|
||||
|
||||
# Client and device manager from BEC
|
||||
self.client = BECDispatcher().client if client is None else client
|
||||
self.dev = self.client.device_manager.devices
|
||||
|
||||
# Loading UI
|
||||
current_path = os.path.dirname(__file__)
|
||||
uic.loadUi(os.path.join(current_path, "plot_app.ui"), self)
|
||||
|
||||
self.data = {}
|
||||
|
||||
self.crosshairs = None
|
||||
self.plots = None
|
||||
self.curves_data = None
|
||||
self.grid_coordinates = None
|
||||
self.scanID = None
|
||||
|
||||
self.user_colors = {} # key: (plot_name, y_name, y_entry), value: color
|
||||
|
||||
# Default config
|
||||
self.config = config
|
||||
|
||||
# Validate the configuration before proceeding
|
||||
self.load_config(self.config)
|
||||
|
||||
# Default splitter size
|
||||
self.splitter.setSizes([400, 100])
|
||||
|
||||
# Buttons
|
||||
self.pushButton_save.clicked.connect(self.save_settings_to_yaml)
|
||||
self.pushButton_load.clicked.connect(self.load_settings_from_yaml)
|
||||
|
||||
# Connect the update signal to the update plot method
|
||||
self.proxy_update_plot = pg.SignalProxy(
|
||||
self.update_signal, rateLimit=25, slot=self.update_plot
|
||||
)
|
||||
|
||||
# Change layout of plots when the number of columns is changed in GUI
|
||||
self.spinBox_N_columns.valueChanged.connect(lambda x: self.init_ui(x))
|
||||
|
||||
def load_config(self, config: dict) -> None:
|
||||
"""
|
||||
Load and validate the configuration, retrying until a valid configuration is provided or the user cancels.
|
||||
Args:
|
||||
config (dict): Configuration dictionary form .yaml file.
|
||||
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
valid_config = False
|
||||
self.error_handler.set_retry_action(self.load_settings_from_yaml)
|
||||
while not valid_config:
|
||||
if config is None:
|
||||
self.config = (
|
||||
self.load_settings_from_yaml()
|
||||
) # Load config if it hasn't been loaded yet
|
||||
try: # Validate loaded config file
|
||||
self.error_handler.validate_config_file(config)
|
||||
valid_config = True
|
||||
except ValueError as e:
|
||||
self.config = None # Reset config_to_test to force reloading configuration
|
||||
self.config = self.error_handler.handle_error(str(e))
|
||||
if valid_config is True: # Initialize config if validation succeeds
|
||||
self.init_config(self.config)
|
||||
|
||||
def init_config(self, config: dict) -> None:
|
||||
"""
|
||||
Initializes or update the configuration settings for the PlotApp.
|
||||
|
||||
Args:
|
||||
config (dict): Dictionary containing plot settings and data configurations.
|
||||
"""
|
||||
|
||||
# YAML config
|
||||
self.plot_settings = config.get("plot_settings", {})
|
||||
self.plot_data_config = config.get("plot_data", {})
|
||||
self.scan_types = self.plot_settings.get("scan_types", False)
|
||||
|
||||
if self.scan_types is False: # Device tracking mode
|
||||
self.plot_data = self.plot_data_config # TODO logic has to be improved
|
||||
else: # setup first line scan as default, then changed with different scan type
|
||||
self.plot_data = self.plot_data_config[list(self.plot_data_config.keys())[0]]
|
||||
|
||||
# Setting global plot settings
|
||||
self.init_plot_background(self.plot_settings["background_color"])
|
||||
|
||||
# Initialize the UI
|
||||
self.init_ui(self.plot_settings["num_columns"])
|
||||
self.spinBox_N_columns.setValue(
|
||||
self.plot_settings["num_columns"]
|
||||
) # TODO has to be checked if it will not setup more columns than plots
|
||||
self.spinBox_N_columns.setMaximum(len(self.plot_data))
|
||||
|
||||
def init_plot_background(self, background_color: str) -> None:
|
||||
"""
|
||||
Initialize plot settings based on the background color.
|
||||
|
||||
Args:
|
||||
background_color (str): The background color ('white' or 'black').
|
||||
|
||||
This method sets the background and foreground colors for pyqtgraph.
|
||||
If the background is dark ('black'), the foreground will be set to 'white',
|
||||
and vice versa.
|
||||
"""
|
||||
if background_color.lower() == "black":
|
||||
pg.setConfigOption("background", "k")
|
||||
pg.setConfigOption("foreground", "w")
|
||||
elif background_color.lower() == "white":
|
||||
pg.setConfigOption("background", "w")
|
||||
pg.setConfigOption("foreground", "k")
|
||||
else:
|
||||
raise ValueError(
|
||||
f"Invalid background color {background_color}. Allowed values are 'white' or 'black'."
|
||||
)
|
||||
|
||||
# TODO simplify -> find way how to setup also foreground color
|
||||
# if background_color.lower() not in ["black", "white"]:
|
||||
# raise ValueError(
|
||||
# f"Invalid background color {background_color}. Allowed values are 'white' or 'black'."
|
||||
# )
|
||||
# self.glw.setBackground(background_color.lower())
|
||||
|
||||
def init_ui(self, num_columns: int = 3) -> None:
|
||||
"""
|
||||
Initialize the UI components, create plots and store their grid positions.
|
||||
|
||||
Args:
|
||||
num_columns (int): Number of columns to wrap the layout.
|
||||
|
||||
This method initializes a dictionary `self.plots` to store the plot objects
|
||||
along with their corresponding x and y signal names. It dynamically arranges
|
||||
the plots in a grid layout based on the given number of columns and dynamically
|
||||
stretches the last plots to fit the remaining space.
|
||||
"""
|
||||
self.glw.clear()
|
||||
self.plots = {}
|
||||
self.grid_coordinates = []
|
||||
|
||||
num_plots = len(self.plot_data)
|
||||
|
||||
# Check if num_columns exceeds the number of plots
|
||||
if num_columns >= num_plots:
|
||||
num_columns = num_plots
|
||||
self.plot_settings["num_columns"] = num_columns # Update the settings
|
||||
print(
|
||||
f"Warning: num_columns in the YAML file was greater than the number of plots. Resetting num_columns to number of plots:{num_columns}."
|
||||
)
|
||||
else:
|
||||
self.plot_settings["num_columns"] = num_columns # Update the settings
|
||||
|
||||
num_rows = num_plots // num_columns
|
||||
last_row_cols = num_plots % num_columns
|
||||
remaining_space = num_columns - last_row_cols
|
||||
|
||||
for i, plot_config in enumerate(self.plot_data):
|
||||
row, col = i // num_columns, i % num_columns
|
||||
colspan = 1
|
||||
|
||||
if row == num_rows and remaining_space > 0:
|
||||
if last_row_cols == 1:
|
||||
colspan = num_columns
|
||||
else:
|
||||
colspan = remaining_space // last_row_cols + 1
|
||||
remaining_space -= colspan - 1
|
||||
last_row_cols -= 1
|
||||
|
||||
plot_name = plot_config.get("plot_name", "")
|
||||
x_label = plot_config["x"].get("label", "")
|
||||
y_label = plot_config["y"].get("label", "")
|
||||
|
||||
plot = self.glw.addPlot(row=row, col=col, colspan=colspan, title=plot_name)
|
||||
plot.setLabel("bottom", x_label)
|
||||
plot.setLabel("left", y_label)
|
||||
plot.addLegend()
|
||||
|
||||
self.plots[plot_name] = plot
|
||||
self.grid_coordinates.append((row, col))
|
||||
|
||||
self.init_curves()
|
||||
|
||||
def init_curves(self) -> None:
|
||||
"""
|
||||
Initialize curve data and properties, and update table row labels.
|
||||
|
||||
This method initializes a nested dictionary `self.curves_data` to store
|
||||
the curve objects for each x and y signal pair. It also updates the row labels
|
||||
in `self.tableWidget_crosshair` to include the grid position for each y-value.
|
||||
"""
|
||||
self.curves_data = {}
|
||||
row_labels = []
|
||||
|
||||
for idx, plot_config in enumerate(self.plot_data):
|
||||
plot_name = plot_config.get("plot_name", "")
|
||||
plot = self.plots[plot_name]
|
||||
plot.clear()
|
||||
|
||||
y_configs = plot_config["y"]["signals"]
|
||||
colors_ys = Colors.golden_angle_color(
|
||||
colormap=self.plot_settings["colormap"], num=len(y_configs)
|
||||
)
|
||||
|
||||
curve_list = []
|
||||
for i, (y_config, color) in enumerate(zip(y_configs, colors_ys)):
|
||||
# print(y_config)
|
||||
y_name = y_config["name"]
|
||||
y_entries = y_config.get("entry", [y_name])
|
||||
|
||||
if not isinstance(y_entries, list):
|
||||
y_entries = [y_entries]
|
||||
|
||||
for y_entry in y_entries:
|
||||
user_color = self.user_colors.get((plot_name, y_name, y_entry), None)
|
||||
color_to_use = user_color if user_color else color
|
||||
|
||||
pen_curve = mkPen(color=color_to_use, width=2, style=QtCore.Qt.DashLine)
|
||||
brush_curve = mkBrush(color=color_to_use)
|
||||
|
||||
curve_data = pg.PlotDataItem(
|
||||
symbolSize=5,
|
||||
symbolBrush=brush_curve,
|
||||
pen=pen_curve,
|
||||
skipFiniteCheck=True,
|
||||
name=f"{y_name} ({y_entry})",
|
||||
)
|
||||
|
||||
curve_list.append((y_name, y_entry, curve_data))
|
||||
plot.addItem(curve_data)
|
||||
row_labels.append(f"{y_name} ({y_entry}) - {plot_name}")
|
||||
|
||||
# Create a ColorButton and set its color
|
||||
color_btn = ColorButton()
|
||||
color_btn.setColor(color_to_use)
|
||||
color_btn.sigColorChanged.connect(
|
||||
lambda btn=color_btn, plot=plot_name, yname=y_name, yentry=y_entry, curve=curve_data: self.change_curve_color(
|
||||
btn, plot, yname, yentry, curve
|
||||
)
|
||||
)
|
||||
|
||||
# Add the ColorButton as a QWidget to the table
|
||||
color_widget = QtWidgets.QWidget()
|
||||
layout = QtWidgets.QHBoxLayout()
|
||||
layout.addWidget(color_btn)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
color_widget.setLayout(layout)
|
||||
|
||||
row = len(row_labels) - 1 # The row index in the table
|
||||
self.tableWidget_crosshair.setCellWidget(row, 2, color_widget)
|
||||
|
||||
self.curves_data[plot_name] = curve_list
|
||||
|
||||
self.tableWidget_crosshair.setRowCount(len(row_labels))
|
||||
self.tableWidget_crosshair.setVerticalHeaderLabels(row_labels)
|
||||
self.hook_crosshair()
|
||||
|
||||
def change_curve_color(
|
||||
self,
|
||||
btn: pyqtgraph.ColorButton,
|
||||
plot_name: str,
|
||||
y_name: str,
|
||||
y_entry: str,
|
||||
curve: pyqtgraph.PlotDataItem,
|
||||
) -> None:
|
||||
"""
|
||||
Change the color of a curve and update the corresponding ColorButton.
|
||||
|
||||
Args:
|
||||
btn (ColorButton): The ColorButton that was clicked.
|
||||
plot_name (str): The name of the plot where the curve belongs.
|
||||
y_name (str): The name of the y signal.
|
||||
y_entry (str): The entry of the y signal.
|
||||
curve (PlotDataItem): The curve to be changed.
|
||||
"""
|
||||
color = btn.color()
|
||||
pen_curve = mkPen(color=color, width=2, style=QtCore.Qt.DashLine)
|
||||
brush_curve = mkBrush(color=color)
|
||||
curve.setPen(pen_curve)
|
||||
curve.setSymbolBrush(brush_curve)
|
||||
self.user_colors[(plot_name, y_name, y_entry)] = color
|
||||
|
||||
def hook_crosshair(self) -> None:
|
||||
"""Attach crosshairs to each plot and connect them to the update_table method."""
|
||||
self.crosshairs = {}
|
||||
for plot_name, plot in self.plots.items():
|
||||
crosshair = Crosshair(plot, precision=3)
|
||||
crosshair.coordinatesChanged1D.connect(
|
||||
lambda x, y, plot=plot: self.update_table(
|
||||
self.tableWidget_crosshair, x, y, column=0, plot=plot
|
||||
)
|
||||
)
|
||||
crosshair.coordinatesClicked1D.connect(
|
||||
lambda x, y, plot=plot: self.update_table(
|
||||
self.tableWidget_crosshair, x, y, column=1, plot=plot
|
||||
)
|
||||
)
|
||||
self.crosshairs[plot_name] = crosshair
|
||||
|
||||
def update_table(
|
||||
self, table_widget: QTableWidget, x: float, y_values: list, column: int, plot: pg.PlotItem
|
||||
) -> None:
|
||||
"""
|
||||
Update the table with coordinates based on cursor movements and clicks.
|
||||
|
||||
Args:
|
||||
table_widget (QTableWidget): The table to be updated.
|
||||
x (float): The x-coordinate from the plot.
|
||||
y_values (list): The y-coordinates from the plot.
|
||||
column (int): The column in the table to be updated.
|
||||
plot (PlotItem): The plot from which the coordinates are taken.
|
||||
|
||||
This method calculates the correct row in the table for each y-value
|
||||
and updates the cell at (row, column) with the new x and y coordinates.
|
||||
"""
|
||||
plot_name = [name for name, value in self.plots.items() if value == plot][0]
|
||||
|
||||
starting_row = 0
|
||||
for plot_config in self.plot_data:
|
||||
if plot_config.get("plot_name", "") == plot_name:
|
||||
break
|
||||
for y_config in plot_config.get("y", {}).get("signals", []):
|
||||
y_entries = y_config.get("entry", [y_config.get("name", "")])
|
||||
if not isinstance(y_entries, list):
|
||||
y_entries = [y_entries]
|
||||
starting_row += len(y_entries)
|
||||
|
||||
for i, y in enumerate(y_values):
|
||||
row = starting_row + i
|
||||
table_widget.setItem(row, column, QTableWidgetItem(f"({x}, {y})"))
|
||||
table_widget.resizeColumnsToContents()
|
||||
|
||||
def update_plot(self) -> None:
|
||||
"""Update the plot data based on the stored data dictionary."""
|
||||
for plot_name, curve_list in self.curves_data.items():
|
||||
for y_name, y_entry, curve in curve_list:
|
||||
x_config = next(
|
||||
(pc["x"] for pc in self.plot_data if pc.get("plot_name") == plot_name), {}
|
||||
)
|
||||
x_signal_config = x_config["signals"][0]
|
||||
x_name = x_signal_config.get("name", "")
|
||||
x_entry = x_signal_config.get("entry", x_name)
|
||||
|
||||
key = (x_name, x_entry, y_name, y_entry)
|
||||
data_x = self.data.get(key, {}).get("x", [])
|
||||
data_y = self.data.get(key, {}).get("y", [])
|
||||
|
||||
curve.setData(data_x, data_y)
|
||||
|
||||
@pyqtSlot(dict, dict)
|
||||
def on_scan_segment(
|
||||
self, msg, metadata
|
||||
) -> None: # TODO the logic should be separated from GUI operation
|
||||
"""
|
||||
Handle new scan segments and saves data to a dictionary. Linked through bec_dispatcher.
|
||||
|
||||
Args:
|
||||
msg (dict): Message received with scan data.
|
||||
metadata (dict): Metadata of the scan.
|
||||
"""
|
||||
|
||||
current_scanID = msg.get("scanID", None)
|
||||
if current_scanID is None:
|
||||
return
|
||||
|
||||
if current_scanID != self.scanID:
|
||||
if self.scan_types is False:
|
||||
self.plot_data = self.plot_data_config
|
||||
elif self.scan_types is True:
|
||||
currentName = metadata.get("scan_name")
|
||||
if currentName is None:
|
||||
raise ValueError(
|
||||
f"Scan name not found in metadata. Please check the scan_name in the YAML config or in bec "
|
||||
f"configuration."
|
||||
)
|
||||
self.plot_data = self.plot_data_config.get(currentName, [])
|
||||
if self.plot_data == []:
|
||||
raise ValueError(
|
||||
f"Scan name {currentName} not found in the YAML config. Please check the scan_name in the "
|
||||
f"YAML config or in bec configuration."
|
||||
)
|
||||
|
||||
# Init UI
|
||||
self.init_ui(self.plot_settings["num_columns"])
|
||||
self.spinBox_N_columns.setValue(
|
||||
self.plot_settings["num_columns"]
|
||||
) # TODO has to be checked if it will not setup more columns than plots
|
||||
self.spinBox_N_columns.setMaximum(len(self.plot_data))
|
||||
|
||||
self.scanID = current_scanID
|
||||
self.data = {}
|
||||
self.init_curves()
|
||||
|
||||
for plot_config in self.plot_data:
|
||||
plot_name = plot_config.get("plot_name", "Unnamed Plot")
|
||||
x_config = plot_config["x"]
|
||||
x_signal_config = x_config["signals"][0] # Assuming there's at least one signal for x
|
||||
|
||||
x_name = x_signal_config.get("name", "")
|
||||
if not x_name:
|
||||
raise ValueError(f"Name for x signal must be specified in plot: {plot_name}.")
|
||||
|
||||
x_entry_list = x_signal_config.get("entry", [])
|
||||
if not x_entry_list:
|
||||
x_entry_list = (
|
||||
self.dev[x_name]._hints if hasattr(self.dev[x_name], "_hints") else [x_name]
|
||||
)
|
||||
|
||||
if not isinstance(x_entry_list, list):
|
||||
x_entry_list = [x_entry_list]
|
||||
|
||||
y_configs = plot_config["y"]["signals"]
|
||||
|
||||
for x_entry in x_entry_list:
|
||||
for y_config in y_configs:
|
||||
y_name = y_config.get("name", "")
|
||||
if not y_name:
|
||||
raise ValueError(
|
||||
f"Name for y signal must be specified in plot: {plot_name}."
|
||||
)
|
||||
|
||||
y_entry_list = y_config.get("entry", [])
|
||||
if not y_entry_list:
|
||||
y_entry_list = (
|
||||
self.dev[y_name]._hints
|
||||
if hasattr(self.dev[y_name], "_hints")
|
||||
else [y_name]
|
||||
)
|
||||
|
||||
if not isinstance(y_entry_list, list):
|
||||
y_entry_list = [y_entry_list]
|
||||
|
||||
for y_entry in y_entry_list:
|
||||
key = (x_name, x_entry, y_name, y_entry)
|
||||
|
||||
data_x = msg["data"].get(x_name, {}).get(x_entry, {}).get("value", None)
|
||||
data_y = msg["data"].get(y_name, {}).get(y_entry, {}).get("value", None)
|
||||
|
||||
if data_x is None:
|
||||
raise ValueError(
|
||||
f"Incorrect entry '{x_entry}' specified for x in plot: {plot_name}, x name: {x_name}"
|
||||
)
|
||||
|
||||
if data_y is None:
|
||||
if hasattr(self.dev[y_name], "_hints"):
|
||||
raise ValueError(
|
||||
f"Incorrect entry '{y_entry}' specified for y in plot: {plot_name}, y name: {y_name}"
|
||||
)
|
||||
else:
|
||||
raise ValueError(
|
||||
f"No hints available for y in plot: {plot_name}, and name '{y_name}' did not work as entry"
|
||||
)
|
||||
|
||||
if data_x is not None:
|
||||
self.data.setdefault(key, {}).setdefault("x", []).append(data_x)
|
||||
|
||||
if data_y is not None:
|
||||
self.data.setdefault(key, {}).setdefault("y", []).append(data_y)
|
||||
|
||||
self.update_signal.emit()
|
||||
|
||||
def save_settings_to_yaml(self):
|
||||
"""Save the current settings to a .yaml file using a file dialog."""
|
||||
options = QFileDialog.Options()
|
||||
options |= QFileDialog.DontUseNativeDialog
|
||||
file_path, _ = QFileDialog.getSaveFileName(
|
||||
self, "Save Settings", "", "YAML Files (*.yaml);;All Files (*)", options=options
|
||||
)
|
||||
|
||||
if file_path:
|
||||
try:
|
||||
if not file_path.endswith(".yaml"):
|
||||
file_path += ".yaml"
|
||||
|
||||
with open(file_path, "w") as file:
|
||||
yaml.dump(
|
||||
{"plot_settings": self.plot_settings, "plot_data": self.plot_data_config},
|
||||
file,
|
||||
)
|
||||
print(f"Settings saved to {file_path}")
|
||||
except Exception as e:
|
||||
print(f"An error occurred while saving the settings to {file_path}: {e}")
|
||||
|
||||
def load_settings_from_yaml(self) -> dict: # TODO can be replace by the utils function
|
||||
"""Load settings from a .yaml file using a file dialog and update the current settings."""
|
||||
options = QFileDialog.Options()
|
||||
options |= QFileDialog.DontUseNativeDialog
|
||||
file_path, _ = QFileDialog.getOpenFileName(
|
||||
self, "Load Settings", "", "YAML Files (*.yaml);;All Files (*)", options=options
|
||||
)
|
||||
|
||||
if file_path:
|
||||
try:
|
||||
with open(file_path, "r") as file:
|
||||
self.config = yaml.safe_load(file)
|
||||
self.load_config(self.config) # validate new config
|
||||
return config
|
||||
except FileNotFoundError:
|
||||
print(f"The file {file_path} was not found.")
|
||||
except Exception as e:
|
||||
print(f"An error occurred while loading the settings from {file_path}: {e}")
|
||||
return None # Return None on exception to indicate failure
|
||||
|
||||
|
||||
class ErrorHandler:
|
||||
def __init__(self, parent=None):
|
||||
self.parent = parent
|
||||
self.errors = []
|
||||
self.retry_action = None
|
||||
logging.basicConfig(level=logging.ERROR) # Configure logging
|
||||
|
||||
def set_retry_action(self, action):
|
||||
self.retry_action = action # Store a reference to the retry action
|
||||
|
||||
def handle_error(self, error_message: str):
|
||||
# logging.error(f"{error_message}\n{traceback.format_exc()}") #TODO decide if useful
|
||||
|
||||
choice = QMessageBox.critical(
|
||||
self.parent,
|
||||
"Error",
|
||||
f"{error_message}\n\nWould you like to retry?",
|
||||
QMessageBox.Retry | QMessageBox.Cancel,
|
||||
)
|
||||
if choice == QMessageBox.Retry and self.retry_action is not None:
|
||||
return self.retry_action()
|
||||
else:
|
||||
exit(1) # Exit the program if the user selects Cancel or if no retry_action is provided
|
||||
|
||||
def validate_config_file(self, config: dict) -> None:
|
||||
"""
|
||||
Validate the configuration dictionary.
|
||||
Args:
|
||||
config (dict): Configuration dictionary form .yaml file.
|
||||
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
self.errors = []
|
||||
|
||||
# Validate common keys
|
||||
required_top_level_keys = ["plot_settings", "plot_data"]
|
||||
for key in required_top_level_keys:
|
||||
if key not in config:
|
||||
self.errors.append(f"Missing required key: {key}")
|
||||
|
||||
# Only continue if no errors so far
|
||||
if not self.errors:
|
||||
# Determine the configuration mode (device or scan)
|
||||
plot_settings = config.get("plot_settings", {})
|
||||
scan_types = plot_settings.get("scan_types", False)
|
||||
|
||||
plot_data = config.get("plot_data", [])
|
||||
|
||||
if scan_types:
|
||||
# Validate scan mode configuration
|
||||
for scan_type, plots in plot_data.items():
|
||||
for i, plot_config in enumerate(plots):
|
||||
self.validate_plot_config(plot_config, i)
|
||||
else:
|
||||
# Validate device mode configuration
|
||||
for i, plot_config in enumerate(plot_data):
|
||||
self.validate_plot_config(plot_config, i)
|
||||
|
||||
if self.errors != []:
|
||||
self.handle_error("\n".join(self.errors))
|
||||
|
||||
def validate_plot_config(self, plot_config: dict, i: int):
|
||||
"""
|
||||
Validate individual plot configuration.
|
||||
Args:
|
||||
plot_config (dict): Individual plot configuration.
|
||||
i (int): Index of the plot configuration.
|
||||
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
for axis in ["x", "y"]:
|
||||
axis_config = plot_config.get(axis)
|
||||
plot_name = plot_config.get("plot_name", "")
|
||||
if axis_config is None:
|
||||
error_msg = f"Missing '{axis}' configuration in plot {i} - {plot_name}"
|
||||
logging.error(error_msg) # Log the error
|
||||
self.errors.append(error_msg)
|
||||
|
||||
signals_config = axis_config.get("signals")
|
||||
if signals_config is None:
|
||||
error_msg = (
|
||||
f"Missing 'signals' configuration for {axis} axis in plot {i} - '{plot_name}'"
|
||||
)
|
||||
logging.error(error_msg) # Log the error
|
||||
self.errors.append(error_msg)
|
||||
elif not isinstance(signals_config, list) or len(signals_config) == 0:
|
||||
error_msg = (
|
||||
f"'signals' configuration for {axis} axis in plot {i} must be a non-empty list"
|
||||
)
|
||||
logging.error(error_msg) # Log the error
|
||||
self.errors.append(error_msg)
|
||||
# TODO add condition for name and entry
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import yaml
|
||||
import argparse
|
||||
|
||||
# from bec_widgets import ctrl_c
|
||||
parser = argparse.ArgumentParser(description="Plotting App")
|
||||
parser.add_argument(
|
||||
"--config",
|
||||
"-c",
|
||||
help="Path to the .yaml configuration file",
|
||||
default="config_example.yaml",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
with open(args.config, "r") as file:
|
||||
config = yaml.safe_load(file)
|
||||
|
||||
except FileNotFoundError:
|
||||
print(f"The file {args.config} was not found.")
|
||||
exit(1)
|
||||
except Exception as e:
|
||||
print(f"An error occurred while loading the config file: {e}")
|
||||
exit(1)
|
||||
|
||||
# BECclient global variables
|
||||
bec_dispatcher = BECDispatcher()
|
||||
client = bec_dispatcher.client
|
||||
client.start()
|
||||
|
||||
app = QApplication([])
|
||||
plotApp = PlotApp(config=config, client=client)
|
||||
|
||||
# Connecting signals from bec_dispatcher
|
||||
bec_dispatcher.connect_slot(plotApp.on_scan_segment, MessageEndpoints.scan_segment())
|
||||
# ctrl_c.setup(app)
|
||||
|
||||
window = plotApp
|
||||
window.show()
|
||||
app.exec()
|
||||
115
bec_widgets/examples/plot_app/plot_app.ui
Normal file
115
bec_widgets/examples/plot_app/plot_app.ui
Normal file
@@ -0,0 +1,115 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ui version="4.0">
|
||||
<class>MultiWindow</class>
|
||||
<widget class="QWidget" name="MultiWindow">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>1248</width>
|
||||
<height>564</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>MultiWindow</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="verticalLayout">
|
||||
<item>
|
||||
<widget class="QSplitter" name="splitter">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Horizontal</enum>
|
||||
</property>
|
||||
<widget class="GraphicsLayoutWidget" name="glw"/>
|
||||
<widget class="QWidget" name="">
|
||||
<layout class="QGridLayout" name="gridLayout_2">
|
||||
<item row="1" column="0">
|
||||
<spacer name="horizontalSpacer">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Horizontal</enum>
|
||||
</property>
|
||||
<property name="sizeHint" stdset="0">
|
||||
<size>
|
||||
<width>40</width>
|
||||
<height>20</height>
|
||||
</size>
|
||||
</property>
|
||||
</spacer>
|
||||
</item>
|
||||
<item row="2" column="0" colspan="3">
|
||||
<widget class="QGroupBox" name="groupBox">
|
||||
<property name="title">
|
||||
<string>Cursor</string>
|
||||
</property>
|
||||
<layout class="QGridLayout" name="gridLayout">
|
||||
<item row="0" column="0">
|
||||
<widget class="QTableWidget" name="tableWidget_crosshair">
|
||||
<column>
|
||||
<property name="text">
|
||||
<string>Moved</string>
|
||||
</property>
|
||||
</column>
|
||||
<column>
|
||||
<property name="text">
|
||||
<string>Clicked</string>
|
||||
</property>
|
||||
</column>
|
||||
<column>
|
||||
<property name="text">
|
||||
<string>Color</string>
|
||||
</property>
|
||||
</column>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="1" column="1">
|
||||
<widget class="QLabel" name="label">
|
||||
<property name="text">
|
||||
<string>Number of Columns:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="1" column="2">
|
||||
<widget class="QSpinBox" name="spinBox_N_columns">
|
||||
<property name="minimum">
|
||||
<number>1</number>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<number>10</number>
|
||||
</property>
|
||||
<property name="value">
|
||||
<number>3</number>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="0" column="1">
|
||||
<widget class="QPushButton" name="pushButton_load">
|
||||
<property name="text">
|
||||
<string>Load Config</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item row="0" column="2">
|
||||
<widget class="QPushButton" name="pushButton_save">
|
||||
<property name="text">
|
||||
<string>Save Config</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<customwidgets>
|
||||
<customwidget>
|
||||
<class>GraphicsLayoutWidget</class>
|
||||
<extends>QGraphicsView</extends>
|
||||
<header>pyqtgraph.h</header>
|
||||
</customwidget>
|
||||
</customwidgets>
|
||||
<resources/>
|
||||
<connections/>
|
||||
</ui>
|
||||
@@ -40,7 +40,7 @@ class StreamPlot(QtWidgets.QWidget):
|
||||
uic.loadUi(os.path.join(current_path, "line_plot.ui"), self)
|
||||
|
||||
self._idle_time = 100
|
||||
self.producer = RedisConnector(["localhost:6379"]).producer()
|
||||
self.connector = RedisConnector(["localhost:6379"])
|
||||
|
||||
self.y_value_list = y_value_list
|
||||
self.previous_y_value_list = None
|
||||
@@ -214,7 +214,7 @@ class StreamPlot(QtWidgets.QWidget):
|
||||
]
|
||||
}
|
||||
msg = messages.DeviceMessage(signals=return_dict).dumps()
|
||||
self.producer.set_and_publish("px_stream/gui_event", msg=msg)
|
||||
self.connector.set_and_publish("px_stream/gui_event", msg=msg)
|
||||
self.roi_signal.emit(region)
|
||||
|
||||
def init_table(self):
|
||||
@@ -270,7 +270,7 @@ class StreamPlot(QtWidgets.QWidget):
|
||||
time.sleep(0.1)
|
||||
continue
|
||||
endpoint = f"px_stream/projection_{self._current_proj}/data"
|
||||
msgs = self.client.producer.lrange(topic=endpoint, start=-1, end=-1)
|
||||
msgs = self.client.connector.lrange(topic=endpoint, start=-1, end=-1)
|
||||
data = msgs
|
||||
if not data:
|
||||
continue
|
||||
@@ -295,7 +295,7 @@ class StreamPlot(QtWidgets.QWidget):
|
||||
def new_proj(self, content: dict, _metadata: dict):
|
||||
proj_nr = content["signals"]["proj_nr"]
|
||||
endpoint = f"px_stream/projection_{proj_nr}/metadata"
|
||||
msg_raw = self.client.producer.get(topic=endpoint)
|
||||
msg_raw = self.client.connector.get(topic=endpoint)
|
||||
msg = messages.DeviceMessage.loads(msg_raw)
|
||||
self._current_q = msg.content["signals"]["q"]
|
||||
self._current_norm = msg.content["signals"]["norm_sum"]
|
||||
|
||||
0
bec_widgets/qtdesigner_plugins/__init__.py
Normal file
0
bec_widgets/qtdesigner_plugins/__init__.py
Normal file
56
bec_widgets/qtdesigner_plugins/scan2d_plot_plugin.py
Normal file
56
bec_widgets/qtdesigner_plugins/scan2d_plot_plugin.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from qtpy.QtDesigner import QPyDesignerCustomWidgetPlugin
|
||||
from qtpy.QtGui import QIcon
|
||||
|
||||
from bec_widgets.widgets.scan_plot.scan2d_plot import BECScanPlot2D
|
||||
|
||||
|
||||
class BECScanPlot2DPlugin(QPyDesignerCustomWidgetPlugin):
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
|
||||
self._initialized = False
|
||||
|
||||
def initialize(self, formEditor):
|
||||
if self._initialized:
|
||||
return
|
||||
|
||||
self._initialized = True
|
||||
|
||||
def isInitialized(self):
|
||||
return self._initialized
|
||||
|
||||
def createWidget(self, parent):
|
||||
return BECScanPlot2D(parent)
|
||||
|
||||
def name(self):
|
||||
return "BECScanPlot2D"
|
||||
|
||||
def group(self):
|
||||
return "BEC widgets"
|
||||
|
||||
def icon(self):
|
||||
return QIcon()
|
||||
|
||||
def toolTip(self):
|
||||
return "BEC plot for 2D scans"
|
||||
|
||||
def whatsThis(self):
|
||||
return "BEC plot for 2D scans"
|
||||
|
||||
def isContainer(self):
|
||||
return False
|
||||
|
||||
def domXml(self):
|
||||
return (
|
||||
'<widget class="BECScanPlot2D" name="BECScanPlot2D">\n'
|
||||
' <property name="toolTip" >\n'
|
||||
" <string>BEC plot for 2D scans</string>\n"
|
||||
" </property>\n"
|
||||
' <property name="whatsThis" >\n'
|
||||
" <string>BEC plot for 2D scans in Python using PyQt.</string>\n"
|
||||
" </property>\n"
|
||||
"</widget>\n"
|
||||
)
|
||||
|
||||
def includeFile(self):
|
||||
return "scan2d_plot"
|
||||
56
bec_widgets/qtdesigner_plugins/scan_plot_plugin.py
Normal file
56
bec_widgets/qtdesigner_plugins/scan_plot_plugin.py
Normal file
@@ -0,0 +1,56 @@
|
||||
from qtpy.QtDesigner import QPyDesignerCustomWidgetPlugin
|
||||
from qtpy.QtGui import QIcon
|
||||
|
||||
from bec_widgets.widgets.scan_plot.scan_plot import BECScanPlot
|
||||
|
||||
|
||||
class BECScanPlotPlugin(QPyDesignerCustomWidgetPlugin):
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
|
||||
self._initialized = False
|
||||
|
||||
def initialize(self, formEditor):
|
||||
if self._initialized:
|
||||
return
|
||||
|
||||
self._initialized = True
|
||||
|
||||
def isInitialized(self):
|
||||
return self._initialized
|
||||
|
||||
def createWidget(self, parent):
|
||||
return BECScanPlot(parent)
|
||||
|
||||
def name(self):
|
||||
return "BECScanPlot"
|
||||
|
||||
def group(self):
|
||||
return "BEC widgets"
|
||||
|
||||
def icon(self):
|
||||
return QIcon()
|
||||
|
||||
def toolTip(self):
|
||||
return "BEC plot for scans"
|
||||
|
||||
def whatsThis(self):
|
||||
return "BEC plot for scans"
|
||||
|
||||
def isContainer(self):
|
||||
return False
|
||||
|
||||
def domXml(self):
|
||||
return (
|
||||
'<widget class="BECScanPlot" name="BECScanPlot">\n'
|
||||
' <property name="toolTip" >\n'
|
||||
" <string>BEC plot for scans</string>\n"
|
||||
" </property>\n"
|
||||
' <property name="whatsThis" >\n'
|
||||
" <string>BEC plot for scans in Python using PyQt.</string>\n"
|
||||
" </property>\n"
|
||||
"</widget>\n"
|
||||
)
|
||||
|
||||
def includeFile(self):
|
||||
return "scan_plot"
|
||||
@@ -31,8 +31,6 @@ class ConnectionConfig(BaseModel):
|
||||
class BECConnector:
|
||||
"""Connection mixin class for all BEC widgets, to handle BEC client and device manager"""
|
||||
|
||||
USER_ACCESS = ["get_config"]
|
||||
|
||||
def __init__(self, client=None, config: ConnectionConfig = None, gui_id: str = None):
|
||||
# BEC related connections
|
||||
self.bec_dispatcher = BECDispatcher()
|
||||
@@ -40,7 +38,6 @@ class BECConnector:
|
||||
|
||||
if config:
|
||||
self.config = config
|
||||
self.config.widget_class = self.__class__.__name__
|
||||
else:
|
||||
print(
|
||||
f"No initial config found for {self.__class__.__name__}.\n"
|
||||
|
||||
@@ -11,8 +11,6 @@ from bec_lib import BECClient, ServiceConfig
|
||||
from qtpy.QtCore import QObject
|
||||
from qtpy.QtCore import Signal as pyqtSignal
|
||||
|
||||
from bec_lib.endpoints import EndpointInfo
|
||||
|
||||
# Adding a new pyqt signal requires a class factory, as they must be part of the class definition
|
||||
# and cannot be dynamically added as class attributes after the class has been defined.
|
||||
_signal_class_factory = (
|
||||
@@ -37,7 +35,7 @@ class _BECDispatcher(QObject):
|
||||
|
||||
def __init__(self, bec_config=None):
|
||||
super().__init__()
|
||||
self.client = BECClient()
|
||||
self.client = BECClient(forced=True) # make a new instance
|
||||
|
||||
# TODO: this is a workaround for now to provide service config within qtdesigner, but is
|
||||
# it possible to provide config via a cli arg?
|
||||
@@ -51,70 +49,41 @@ class _BECDispatcher(QObject):
|
||||
self._connections = {}
|
||||
|
||||
def connect_slot(
|
||||
self,
|
||||
slot: Callable,
|
||||
topics: Union[EndpointInfo, str, list[Union[EndpointInfo, str]]],
|
||||
single_callback_for_all_topics=False,
|
||||
self, slot: Callable, topics: Union[str, list], single_callback_for_all_topics=False
|
||||
) -> None:
|
||||
"""Connect widget's pyqt slot, so that it is called on new pub/sub topic message.
|
||||
|
||||
Args:
|
||||
slot (Callable): A slot method/function that accepts two inputs: content and metadata of
|
||||
the corresponding pub/sub message
|
||||
topics (EndpointInfo | str | list): A topic or list of topics that can typically be acquired via bec_lib.MessageEndpoints
|
||||
topics (str | list): A topic or list of topics that can typically be acquired via bec_lib.MessageEndpoints
|
||||
single_callback_for_all_topics (bool): If True, use the same callback for all topics, otherwise use
|
||||
separate callbacks.
|
||||
"""
|
||||
# Normalise the topics input
|
||||
if isinstance(topics, (str, EndpointInfo)):
|
||||
if isinstance(topics, str):
|
||||
topics = [topics]
|
||||
|
||||
endpoint_to_consumer_type = {
|
||||
(topic.endpoint if isinstance(topic, EndpointInfo) else topic): (
|
||||
topic.message_op.name if isinstance(topic, EndpointInfo) else "SEND"
|
||||
)
|
||||
for topic in topics
|
||||
}
|
||||
# Ensure topics_key is a tuple, whether single_callback_for_all_topics is True or False.
|
||||
topics_key = tuple(sorted(topics)) if single_callback_for_all_topics else tuple(topics)
|
||||
|
||||
# Group topics by consumer type
|
||||
consumer_type_to_endpoints = {}
|
||||
for endpoint, consumer_type in endpoint_to_consumer_type.items():
|
||||
if consumer_type not in consumer_type_to_endpoints:
|
||||
consumer_type_to_endpoints[consumer_type] = []
|
||||
consumer_type_to_endpoints[consumer_type].append(endpoint)
|
||||
if topics_key not in self._connections:
|
||||
self._connections[topics_key] = self._create_connection(topics)
|
||||
connection = self._connections[topics_key]
|
||||
if slot not in connection.slots:
|
||||
connection.signal.connect(slot)
|
||||
connection.slots.add(slot)
|
||||
|
||||
for consumer_type, endpoints in consumer_type_to_endpoints.items():
|
||||
topics_key = (
|
||||
tuple(sorted(endpoints)) if single_callback_for_all_topics else tuple(endpoints)
|
||||
)
|
||||
|
||||
if topics_key not in self._connections:
|
||||
self._connections[topics_key] = self._create_connection(endpoints, consumer_type)
|
||||
connection = self._connections[topics_key]
|
||||
|
||||
if slot not in connection.slots:
|
||||
connection.signal.connect(slot)
|
||||
connection.slots.add(slot)
|
||||
|
||||
def _create_connection(self, topics: list, consumer_type: str) -> _Connection:
|
||||
def _create_connection(self, topics: list) -> _Connection:
|
||||
"""Creates a new connection for given topics."""
|
||||
|
||||
def cb(msg):
|
||||
if isinstance(msg, dict):
|
||||
msg = msg["data"]
|
||||
else:
|
||||
msg = msg.value
|
||||
msg = msg.value
|
||||
for connection_key, connection in self._connections.items():
|
||||
if set(topics).intersection(connection_key):
|
||||
if isinstance(msg, list):
|
||||
msg = msg[0]
|
||||
connection.signal.emit(msg.content, msg.metadata)
|
||||
|
||||
try:
|
||||
if consumer_type == "STREAM":
|
||||
self.client.connector.register_stream(topics=topics, cb=cb, newest_only=True)
|
||||
else:
|
||||
self.client.connector.register(topics=topics, cb=cb)
|
||||
self.client.connector.register(topics=topics, cb=cb)
|
||||
except redis.exceptions.ConnectionError:
|
||||
print("Could not connect to Redis, skipping registration of topics.")
|
||||
|
||||
@@ -152,19 +121,14 @@ class _BECDispatcher(QObject):
|
||||
topics (str | list): A corresponding topic or list of topics that can typically be acquired via
|
||||
bec_lib.MessageEndpoints
|
||||
"""
|
||||
# Normalise the topics input
|
||||
if isinstance(topics, (str, EndpointInfo)):
|
||||
if isinstance(topics, str):
|
||||
topics = [topics]
|
||||
|
||||
endpoints = [
|
||||
topic.endpoint if isinstance(topic, EndpointInfo) else topic for topic in topics
|
||||
]
|
||||
|
||||
for key, connection in list(self._connections.items()):
|
||||
if slot in connection.slots:
|
||||
common_topics = set(endpoints).intersection(key)
|
||||
common_topics = set(topics).intersection(key)
|
||||
if common_topics:
|
||||
remaining_topics = set(key) - set(endpoints)
|
||||
remaining_topics = set(key) - set(topics)
|
||||
# Disconnect slot from common topics
|
||||
self._do_disconnect_slot(key, slot)
|
||||
# Reconnect slot to remaining topics if any
|
||||
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
import itertools
|
||||
import os
|
||||
from collections import defaultdict
|
||||
from typing import Literal, Optional, Type
|
||||
from typing import Literal, Optional
|
||||
|
||||
import numpy as np
|
||||
import pyqtgraph as pg
|
||||
@@ -13,17 +13,9 @@ from pydantic import Field
|
||||
from pyqtgraph.Qt import uic
|
||||
from qtpy.QtWidgets import QApplication, QWidget
|
||||
from qtpy.QtWidgets import QVBoxLayout, QMainWindow
|
||||
from qtpy.QtCore import Signal as pyqtSignal
|
||||
|
||||
from bec_widgets.utils import BECConnector, BECDispatcher, ConnectionConfig
|
||||
from bec_widgets.widgets.plots import (
|
||||
BECPlotBase,
|
||||
BECWaveform1D,
|
||||
Waveform1DConfig,
|
||||
WidgetConfig,
|
||||
BECImageShow,
|
||||
)
|
||||
from bec_widgets.widgets.plots.image import ImageConfig
|
||||
from bec_widgets.widgets.plots import BECPlotBase, BECWaveform1D, Waveform1DConfig, WidgetConfig
|
||||
|
||||
|
||||
class FigureConfig(ConnectionConfig):
|
||||
@@ -44,7 +36,6 @@ class WidgetHandler:
|
||||
self.widget_factory = {
|
||||
"PlotBase": (BECPlotBase, WidgetConfig),
|
||||
"Waveform1D": (BECWaveform1D, Waveform1DConfig),
|
||||
"ImShow": (BECImageShow, ImageConfig),
|
||||
}
|
||||
|
||||
def create_widget(
|
||||
@@ -74,8 +65,6 @@ class WidgetHandler:
|
||||
raise ValueError(f"Unsupported widget type: {widget_type}")
|
||||
|
||||
widget_class, config_class = entry
|
||||
if config is not None and isinstance(config, config_class):
|
||||
config = config.model_dump()
|
||||
widget_config_dict = {
|
||||
"widget_class": widget_class.__name__,
|
||||
"parent_id": parent_id,
|
||||
@@ -94,19 +83,7 @@ class WidgetHandler:
|
||||
|
||||
|
||||
class BECFigure(BECConnector, pg.GraphicsLayoutWidget):
|
||||
USER_ACCESS = [
|
||||
"add_plot",
|
||||
"add_image",
|
||||
"plot",
|
||||
"image",
|
||||
"remove",
|
||||
"change_layout",
|
||||
"change_theme",
|
||||
"clear_all",
|
||||
"get_config",
|
||||
]
|
||||
|
||||
clean_signal = pyqtSignal()
|
||||
USER_ACCESS = ["add_plot", "remove", "change_layout", "change_theme", "clear_all"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -132,6 +109,16 @@ class BECFigure(BECConnector, pg.GraphicsLayoutWidget):
|
||||
# Container to keep track of the grid
|
||||
self.grid = []
|
||||
|
||||
def change_theme(self, theme: Literal["dark", "light"]) -> None:
|
||||
"""
|
||||
Change the theme of the figure widget.
|
||||
Args:
|
||||
theme(Literal["dark","light"]): The theme to set for the figure widget.
|
||||
"""
|
||||
qdarktheme.setup_theme(theme)
|
||||
self.setBackground("k" if theme == "dark" else "w")
|
||||
self.config.theme = theme
|
||||
|
||||
def add_plot(
|
||||
self, widget_id: str = None, row: int = None, col: int = None, config=None, **axis_kwargs
|
||||
) -> BECWaveform1D:
|
||||
@@ -153,149 +140,9 @@ class BECFigure(BECConnector, pg.GraphicsLayoutWidget):
|
||||
**axis_kwargs,
|
||||
)
|
||||
|
||||
def plot(
|
||||
self,
|
||||
x_name: str = None,
|
||||
y_name: str = None,
|
||||
x_entry: str = None,
|
||||
y_entry: str = None,
|
||||
x: list | np.ndarray = None,
|
||||
y: list | np.ndarray = None,
|
||||
color: Optional[str] = None,
|
||||
label: Optional[str] = None,
|
||||
validate: bool = True,
|
||||
**axis_kwargs,
|
||||
) -> BECWaveform1D:
|
||||
"""
|
||||
Add a 1D waveform plot to the figure.
|
||||
Args:
|
||||
x_name(str): The name of the device for the x-axis.
|
||||
y_name(str): The name of the device for the y-axis.
|
||||
x_entry(str): The name of the entry for the x-axis.
|
||||
y_entry(str): The name of the entry for the y-axis.
|
||||
x(list | np.ndarray): Custom x data to plot.
|
||||
y(list | np.ndarray): Custom y data to plot.
|
||||
color(str): The color of the curve.
|
||||
label(str): The label of the curve.
|
||||
validate(bool): If True, validate the device names and entries.
|
||||
**axis_kwargs: Additional axis properties to set on the widget after creation.
|
||||
|
||||
Returns:
|
||||
BECWaveform1D: The waveform plot widget.
|
||||
"""
|
||||
waveform = self._find_first_widget_by_class(BECWaveform1D, can_fail=True)
|
||||
if waveform is not None:
|
||||
if axis_kwargs:
|
||||
waveform.set(**axis_kwargs)
|
||||
else:
|
||||
waveform = self.add_plot(**axis_kwargs)
|
||||
|
||||
# User wants to add scan curve
|
||||
if x_name is not None and y_name is not None and x is None and y is None:
|
||||
waveform.add_curve_scan(
|
||||
x_name=x_name,
|
||||
y_name=y_name,
|
||||
x_entry=x_entry,
|
||||
y_entry=y_entry,
|
||||
validate=validate,
|
||||
color=color,
|
||||
label=label,
|
||||
)
|
||||
# User wants to add custom curve
|
||||
elif x is not None and y is not None and x_name is None and y_name is None:
|
||||
waveform.add_curve_custom(
|
||||
x=x,
|
||||
y=y,
|
||||
color=color,
|
||||
label=label,
|
||||
)
|
||||
else:
|
||||
raise ValueError(
|
||||
"Invalid input. Provide either device names (x_name, y_name) or custom data."
|
||||
)
|
||||
return waveform
|
||||
|
||||
def image(
|
||||
self,
|
||||
monitor: str = None,
|
||||
color_bar: Literal["simple", "full"] = "full",
|
||||
color_map: str = "magma",
|
||||
data: np.ndarray = None,
|
||||
vrange: tuple[float, float] = None,
|
||||
**axis_kwargs,
|
||||
) -> BECImageShow:
|
||||
"""
|
||||
Add an image to the figure.
|
||||
Args:
|
||||
monitor(str): The name of the monitor to display.
|
||||
color_bar(Literal["simple","full"]): The type of color bar to display.
|
||||
color_map(str): The color map to use for the image.
|
||||
data(np.ndarray): Custom data to display.
|
||||
vrange(tuple[float, float]): The range of values to display.
|
||||
**axis_kwargs: Additional axis properties to set on the widget after creation.
|
||||
|
||||
Returns:
|
||||
BECImageShow: The image widget.
|
||||
"""
|
||||
image = self._find_first_widget_by_class(BECImageShow, can_fail=True)
|
||||
if image is not None:
|
||||
if axis_kwargs:
|
||||
image.set(**axis_kwargs)
|
||||
else:
|
||||
image = self.add_image(color_bar=color_bar, **axis_kwargs)
|
||||
|
||||
# Setting data #TODO check logic if monitor or data are already created
|
||||
if monitor is not None and data is None:
|
||||
image.add_monitor_image(
|
||||
monitor=monitor, color_map=color_map, vrange=vrange, color_bar=color_bar
|
||||
)
|
||||
elif data is not None and monitor is None:
|
||||
image.add_custom_image(
|
||||
name="custom", data=data, color_map=color_map, vrange=vrange, color_bar=color_bar
|
||||
)
|
||||
elif data is None and monitor is None:
|
||||
# Setting appearance
|
||||
if vrange is not None:
|
||||
image.set_vrange(vmin=vrange[0], vmax=vrange[1])
|
||||
if color_map is not None:
|
||||
image.set_color_map(color_map)
|
||||
else:
|
||||
raise ValueError("Invalid input. Provide either monitor name or custom data.")
|
||||
return image
|
||||
|
||||
def add_image(
|
||||
self,
|
||||
widget_id: str = None,
|
||||
row: int = None,
|
||||
col: int = None,
|
||||
config=None,
|
||||
color_map: str = "magma", # TODO fix passing additional kwargs
|
||||
color_bar: Literal["simple", "full"] = "full",
|
||||
vrange: tuple[float, float] = None,
|
||||
**axis_kwargs,
|
||||
) -> BECImageShow:
|
||||
if config is None:
|
||||
widget_id = self._generate_unique_widget_id()
|
||||
config = ImageConfig(
|
||||
widget_class="BECImageShow",
|
||||
gui_id=widget_id,
|
||||
parent_id=self.gui_id,
|
||||
color_map=color_map,
|
||||
color_bar=color_bar,
|
||||
vrange=vrange,
|
||||
)
|
||||
return self.add_widget(
|
||||
widget_type="ImShow",
|
||||
widget_id=widget_id,
|
||||
row=row,
|
||||
col=col,
|
||||
config=config,
|
||||
**axis_kwargs,
|
||||
)
|
||||
|
||||
def add_widget(
|
||||
self,
|
||||
widget_type: Literal["PlotBase", "Waveform1D", "ImShow"] = "PlotBase",
|
||||
widget_type: Literal["PlotBase", "Waveform1D"] = "PlotBase",
|
||||
widget_id: str = None,
|
||||
row: int = None,
|
||||
col: int = None,
|
||||
@@ -381,35 +228,6 @@ class BECFigure(BECConnector, pg.GraphicsLayoutWidget):
|
||||
else:
|
||||
raise ValueError("Must provide either widget_id or coordinates for removal.")
|
||||
|
||||
def change_theme(self, theme: Literal["dark", "light"]) -> None:
|
||||
"""
|
||||
Change the theme of the figure widget.
|
||||
Args:
|
||||
theme(Literal["dark","light"]): The theme to set for the figure widget.
|
||||
"""
|
||||
qdarktheme.setup_theme(theme)
|
||||
self.setBackground("k" if theme == "dark" else "w")
|
||||
self.config.theme = theme
|
||||
|
||||
def _find_first_widget_by_class(
|
||||
self, widget_class: Type[BECPlotBase], can_fail: bool = True
|
||||
) -> BECPlotBase | None:
|
||||
"""
|
||||
Find the first widget of a given class in the figure.
|
||||
Args:
|
||||
widget_class(Type[BECPlotBase]): The class of the widget to find.
|
||||
can_fail(bool): If True, the method will return None if no widget is found. If False, it will raise an error.
|
||||
Returns:
|
||||
BECPlotBase: The widget of the given class.
|
||||
"""
|
||||
for widget_id, widget in self.widgets.items():
|
||||
if isinstance(widget, widget_class):
|
||||
return widget
|
||||
if can_fail:
|
||||
return None
|
||||
else:
|
||||
raise ValueError(f"No widget of class {widget_class} found.")
|
||||
|
||||
def _remove_by_coordinates(self, row: int, col: int) -> None:
|
||||
"""
|
||||
Remove a widget from the figure by its coordinates.
|
||||
@@ -565,8 +383,6 @@ class BECFigure(BECConnector, pg.GraphicsLayoutWidget):
|
||||
|
||||
def clear_all(self):
|
||||
"""Clear all widgets from the figure and reset to default state"""
|
||||
for widget in self.widgets.values():
|
||||
widget.cleanup()
|
||||
self.clear()
|
||||
self.widgets = defaultdict(dict)
|
||||
self.grid = []
|
||||
@@ -575,11 +391,6 @@ class BECFigure(BECConnector, pg.GraphicsLayoutWidget):
|
||||
widget_class=self.__class__.__name__, gui_id=self.gui_id, theme=theme
|
||||
)
|
||||
|
||||
# def cleanup(self):
|
||||
# """Cleanup the figure widget."""
|
||||
# self.clear_all()
|
||||
# self.clean_signal.emit()
|
||||
|
||||
def start(self):
|
||||
import sys
|
||||
|
||||
@@ -591,28 +402,6 @@ class BECFigure(BECConnector, pg.GraphicsLayoutWidget):
|
||||
sys.exit(app.exec_())
|
||||
|
||||
|
||||
class BECFigureMainWindow(QMainWindow):
|
||||
def __init__(self, parent=None, bec_figure=None):
|
||||
super().__init__(parent)
|
||||
|
||||
self.figure = bec_figure
|
||||
self.setCentralWidget(self.figure)
|
||||
|
||||
self.figure.clean_signal.connect(self.confirm_close)
|
||||
|
||||
self.safe_close = False
|
||||
|
||||
def confirm_close(self):
|
||||
self.safe_close = True
|
||||
|
||||
def closeEvent(self, event):
|
||||
self.figure.cleanup()
|
||||
# self.figure.client.shutdown()
|
||||
if self.safe_close == True:
|
||||
print("Safe close")
|
||||
event.accept()
|
||||
|
||||
|
||||
##################################################
|
||||
##################################################
|
||||
# Debug window
|
||||
@@ -633,7 +422,6 @@ class JupyterConsoleWidget(RichJupyterWidget): # pragma: no cover:
|
||||
self.kernel_client.start_channels()
|
||||
|
||||
self.kernel_manager.kernel.shell.push({"np": np, "pg": pg})
|
||||
# self.set_console_font_size(70)
|
||||
|
||||
def shutdown_kernel(self):
|
||||
self.kernel_client.stop_channels()
|
||||
@@ -652,27 +440,16 @@ class DebugWindow(QWidget): # pragma: no cover:
|
||||
self._init_ui()
|
||||
|
||||
self.splitter.setSizes([200, 100])
|
||||
self.safe_close = False
|
||||
# self.figure.clean_signal.connect(self.confirm_close)
|
||||
|
||||
# console push
|
||||
self.console.kernel_manager.kernel.shell.push(
|
||||
{
|
||||
"fig": self.figure,
|
||||
"w1": self.w1,
|
||||
"w2": self.w2,
|
||||
"w3": self.w3,
|
||||
"w4": self.w4,
|
||||
"bec": self.figure.client,
|
||||
"scans": self.figure.client.scans,
|
||||
"dev": self.figure.client.device_manager.devices,
|
||||
}
|
||||
{"fig": self.figure, "w1": self.w1, "w2": self.w2}
|
||||
)
|
||||
|
||||
def _init_ui(self):
|
||||
# Plotting window
|
||||
self.glw_1_layout = QVBoxLayout(self.glw) # Create a new QVBoxLayout
|
||||
self.figure = BECFigure(parent=self, gui_id="remote") # Create a new BECDeviceMonitor
|
||||
self.figure = BECFigure(parent=self) # Create a new BECDeviceMonitor
|
||||
self.glw_1_layout.addWidget(self.figure) # Add BECDeviceMonitor to the layout
|
||||
|
||||
# add stuff to figure
|
||||
@@ -685,15 +462,13 @@ class DebugWindow(QWidget): # pragma: no cover:
|
||||
|
||||
def _init_figure(self):
|
||||
self.figure.add_widget(widget_type="Waveform1D", row=0, col=0, title="Widget 1")
|
||||
self.figure.add_widget(widget_type="Waveform1D", row=0, col=1, title="Widget 2")
|
||||
self.figure.add_image(
|
||||
title="Image", row=1, col=0, color_map="viridis", color_bar="simple", vrange=(0, 100)
|
||||
)
|
||||
self.figure.add_image(title="Image", row=1, col=1, vrange=(0, 100))
|
||||
self.figure.add_widget(widget_type="Waveform1D", row=1, col=0, title="Widget 2")
|
||||
self.figure.add_widget(widget_type="Waveform1D", row=0, col=1, title="Widget 3")
|
||||
self.figure.add_widget(widget_type="Waveform1D", row=1, col=1, title="Widget 4")
|
||||
|
||||
self.w1 = self.figure[0, 0]
|
||||
self.w2 = self.figure[0, 1]
|
||||
self.w3 = self.figure[1, 0]
|
||||
self.w2 = self.figure[1, 0]
|
||||
self.w3 = self.figure[0, 1]
|
||||
self.w4 = self.figure[1, 1]
|
||||
|
||||
# curves for w1
|
||||
@@ -715,40 +490,24 @@ class DebugWindow(QWidget): # pragma: no cover:
|
||||
)
|
||||
|
||||
# curves for w3
|
||||
# self.w3.add_curve_scan("samx", "bpm4i", pen_style="dash")
|
||||
# self.w3.add_curve_custom(
|
||||
# x=[1, 2, 3, 4, 5],
|
||||
# y=[1, 2, 3, 4, 5],
|
||||
# label="curve-custom",
|
||||
# color="blue",
|
||||
# pen_style="dashdot",
|
||||
# )
|
||||
self.w3.add_curve_scan("samx", "bpm4i", pen_style="dash")
|
||||
self.w3.add_curve_custom(
|
||||
x=[1, 2, 3, 4, 5],
|
||||
y=[1, 2, 3, 4, 5],
|
||||
label="curve-custom",
|
||||
color="blue",
|
||||
pen_style="dashdot",
|
||||
)
|
||||
|
||||
# curves for w4
|
||||
# self.w4.add_curve_scan("samx", "bpm4i", pen_style="dash")
|
||||
# self.w4.add_curve_custom(
|
||||
# x=[1, 2, 3, 4, 5],
|
||||
# y=[1, 2, 3, 4, 5],
|
||||
# label="curve-custom",
|
||||
# color="blue",
|
||||
# pen_style="dashdot",
|
||||
# )
|
||||
|
||||
# Image setting for w3
|
||||
|
||||
self.w3.add_monitor_image("eiger", vrange=(0, 100), color_bar="full")
|
||||
|
||||
# Image setting for w4
|
||||
self.w4.add_monitor_image("eiger", vrange=(0, 100), color_map="viridis")
|
||||
|
||||
# def confirm_close(self):
|
||||
# self.safe_close = True
|
||||
#
|
||||
# def closeEvent(self, event):
|
||||
# self.figure.cleanup()
|
||||
# if self.safe_close == True:
|
||||
# print("Safe close")
|
||||
# event.accept()
|
||||
self.w4.add_curve_scan("samx", "bpm4i", pen_style="dash")
|
||||
self.w4.add_curve_custom(
|
||||
x=[1, 2, 3, 4, 5],
|
||||
y=[1, 2, 3, 4, 5],
|
||||
label="curve-custom",
|
||||
color="blue",
|
||||
pen_style="dashdot",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
|
||||
@@ -6,20 +6,25 @@
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>2104</width>
|
||||
<height>966</height>
|
||||
<width>901</width>
|
||||
<height>1000</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>Plotting Console</string>
|
||||
<string>Form</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="verticalLayout">
|
||||
<layout class="QVBoxLayout" name="verticalLayout_3">
|
||||
<item>
|
||||
<widget class="QSplitter" name="splitter">
|
||||
<widget class="QSplitter" name="splitter_2">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Horizontal</enum>
|
||||
<enum>Qt::Vertical</enum>
|
||||
</property>
|
||||
<widget class="QWidget" name="glw" native="true"/>
|
||||
<widget class="QSplitter" name="splitter">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Horizontal</enum>
|
||||
</property>
|
||||
<widget class="QWidget" name="glw" native="true"/>
|
||||
</widget>
|
||||
<widget class="QWidget" name="widget_console" native="true"/>
|
||||
</widget>
|
||||
</item>
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
from .plot_base import AxisConfig, WidgetConfig, BECPlotBase
|
||||
from .waveform1d import Waveform1DConfig, BECWaveform1D, BECCurve
|
||||
from .image import BECImageShow, ImageItemConfig, BECImageItem
|
||||
|
||||
@@ -1,860 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from typing import Literal, Optional, Any
|
||||
|
||||
import numpy as np
|
||||
import pyqtgraph as pg
|
||||
from pydantic import Field, BaseModel, ValidationError
|
||||
from qtpy.QtCore import QThread, QObject
|
||||
from qtpy.QtCore import Signal as pyqtSignal
|
||||
from qtpy.QtCore import Slot as pyqtSlot
|
||||
from qtpy.QtWidgets import QWidget
|
||||
|
||||
from bec_lib import MessageEndpoints
|
||||
from bec_widgets.utils import ConnectionConfig, BECConnector
|
||||
from bec_widgets.widgets.plots import BECPlotBase, WidgetConfig
|
||||
|
||||
|
||||
class ProcessingConfig(BaseModel):
|
||||
fft: Optional[bool] = Field(False, description="Whether to perform FFT on the monitor data.")
|
||||
log: Optional[bool] = Field(False, description="Whether to perform log on the monitor data.")
|
||||
center_of_mass: Optional[bool] = Field(
|
||||
False, description="Whether to calculate the center of mass of the monitor data."
|
||||
)
|
||||
transpose: Optional[bool] = Field(
|
||||
False, description="Whether to transpose the monitor data before displaying."
|
||||
)
|
||||
rotation: Optional[int] = Field(
|
||||
None, description="The rotation angle of the monitor data before displaying."
|
||||
)
|
||||
|
||||
|
||||
class ImageItemConfig(ConnectionConfig):
|
||||
parent_id: Optional[str] = Field(None, description="The parent plot of the image.")
|
||||
monitor: Optional[str] = Field(None, description="The name of the monitor.")
|
||||
source: Optional[str] = Field(None, description="The source of the curve.")
|
||||
color_map: Optional[str] = Field("magma", description="The color map of the image.")
|
||||
downsample: Optional[bool] = Field(True, description="Whether to downsample the image.")
|
||||
opacity: Optional[float] = Field(1.0, description="The opacity of the image.")
|
||||
vrange: Optional[tuple[int, int]] = Field(
|
||||
None, description="The range of the color bar. If None, the range is automatically set."
|
||||
)
|
||||
color_bar: Optional[Literal["simple", "full"]] = Field(
|
||||
"simple", description="The type of the color bar."
|
||||
)
|
||||
autorange: Optional[bool] = Field(True, description="Whether to autorange the color bar.")
|
||||
processing: ProcessingConfig = Field(
|
||||
default_factory=ProcessingConfig, description="The post processing of the image."
|
||||
)
|
||||
|
||||
|
||||
class ImageConfig(WidgetConfig):
|
||||
images: dict[str, ImageItemConfig] = Field(
|
||||
{},
|
||||
description="The configuration of the images. The key is the name of the image (source).",
|
||||
)
|
||||
|
||||
|
||||
class BECImageItem(BECConnector, pg.ImageItem):
|
||||
USER_ACCESS = [
|
||||
"set",
|
||||
"set_fft",
|
||||
"set_log",
|
||||
"set_rotation",
|
||||
"set_transpose",
|
||||
"set_opacity",
|
||||
"set_autorange",
|
||||
"set_color_map",
|
||||
"set_auto_downsample",
|
||||
"set_monitor",
|
||||
"set_vrange",
|
||||
]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: Optional[ImageItemConfig] = None,
|
||||
gui_id: Optional[str] = None,
|
||||
parent_image: Optional[BECImageItem] = None,
|
||||
**kwargs,
|
||||
):
|
||||
if config is None:
|
||||
config = ImageItemConfig(widget_class=self.__class__.__name__)
|
||||
self.config = config
|
||||
else:
|
||||
self.config = config
|
||||
super().__init__(config=config, gui_id=gui_id)
|
||||
pg.ImageItem.__init__(self)
|
||||
|
||||
self.parent_image = parent_image
|
||||
self.colorbar_bar = None
|
||||
|
||||
self._add_color_bar(
|
||||
self.config.color_bar, self.config.vrange
|
||||
) # TODO can also support None to not have any colorbar
|
||||
self.apply_config()
|
||||
if kwargs:
|
||||
self.set(**kwargs)
|
||||
|
||||
def apply_config(self):
|
||||
"""
|
||||
Apply current configuration.
|
||||
"""
|
||||
self.set_color_map(self.config.color_map)
|
||||
self.set_auto_downsample(self.config.downsample)
|
||||
if self.config.vrange is not None:
|
||||
self.set_vrange(vrange=self.config.vrange)
|
||||
|
||||
def set(self, **kwargs):
|
||||
"""
|
||||
Set the properties of the image.
|
||||
Args:
|
||||
**kwargs: Keyword arguments for the properties to be set.
|
||||
Possible properties:
|
||||
- downsample
|
||||
- color_map
|
||||
- monitor
|
||||
- opacity
|
||||
- vrange
|
||||
- fft
|
||||
- log
|
||||
- rot
|
||||
- transpose
|
||||
"""
|
||||
method_map = {
|
||||
"downsample": self.set_auto_downsample,
|
||||
"color_map": self.set_color_map,
|
||||
"monitor": self.set_monitor,
|
||||
"opacity": self.set_opacity,
|
||||
"vrange": self.set_vrange,
|
||||
"fft": self.set_fft,
|
||||
"log": self.set_log,
|
||||
"rot": self.set_rotation,
|
||||
"transpose": self.set_transpose,
|
||||
}
|
||||
for key, value in kwargs.items():
|
||||
if key in method_map:
|
||||
method_map[key](value)
|
||||
else:
|
||||
print(f"Warning: '{key}' is not a recognized property.")
|
||||
|
||||
def set_fft(self, enable: bool = False):
|
||||
"""
|
||||
Set the FFT of the image.
|
||||
Args:
|
||||
enable(bool): Whether to perform FFT on the monitor data.
|
||||
"""
|
||||
self.config.processing.fft = enable
|
||||
|
||||
def set_log(self, enable: bool = False):
|
||||
"""
|
||||
Set the log of the image.
|
||||
Args:
|
||||
enable(bool): Whether to perform log on the monitor data.
|
||||
"""
|
||||
self.config.processing.log = enable
|
||||
if enable and self.color_bar and self.config.color_bar == "full":
|
||||
self.color_bar.autoHistogramRange()
|
||||
|
||||
def set_rotation(self, deg_90: int = 0):
|
||||
"""
|
||||
Set the rotation of the image.
|
||||
Args:
|
||||
deg_90(int): The rotation angle of the monitor data before displaying.
|
||||
"""
|
||||
self.config.processing.rotation = deg_90
|
||||
|
||||
def set_transpose(self, enable: bool = False):
|
||||
"""
|
||||
Set the transpose of the image.
|
||||
Args:
|
||||
enable(bool): Whether to transpose the image.
|
||||
"""
|
||||
self.config.processing.transpose = enable
|
||||
|
||||
def set_opacity(self, opacity: float = 1.0):
|
||||
"""
|
||||
Set the opacity of the image.
|
||||
Args:
|
||||
opacity(float): The opacity of the image.
|
||||
"""
|
||||
self.setOpacity(opacity)
|
||||
self.config.opacity = opacity
|
||||
|
||||
def set_autorange(self, autorange: bool = True):
|
||||
"""
|
||||
Set the autorange of the color bar.
|
||||
Args:
|
||||
autorange(bool): Whether to autorange the color bar.
|
||||
"""
|
||||
self.config.autorange = autorange
|
||||
if self.color_bar is not None:
|
||||
self.color_bar.autoHistogramRange()
|
||||
|
||||
def set_color_map(self, cmap: str = "magma"):
|
||||
"""
|
||||
Set the color map of the image.
|
||||
Args:
|
||||
cmap(str): The color map of the image.
|
||||
"""
|
||||
self.setColorMap(cmap)
|
||||
if self.color_bar is not None:
|
||||
if self.config.color_bar == "simple":
|
||||
self.color_bar.setColorMap(cmap)
|
||||
elif self.config.color_bar == "full":
|
||||
self.color_bar.gradient.loadPreset(cmap)
|
||||
self.config.color_map = cmap
|
||||
|
||||
def set_auto_downsample(self, auto: bool = True):
|
||||
"""
|
||||
Set the auto downsample of the image.
|
||||
Args:
|
||||
auto(bool): Whether to downsample the image.
|
||||
"""
|
||||
self.setAutoDownsample(auto)
|
||||
self.config.downsample = auto
|
||||
|
||||
def set_monitor(self, monitor: str):
|
||||
"""
|
||||
Set the monitor of the image.
|
||||
Args:
|
||||
monitor(str): The name of the monitor.
|
||||
"""
|
||||
self.config.monitor = monitor
|
||||
|
||||
def set_vrange(self, vmin: float = None, vmax: float = None, vrange: tuple[int, int] = None):
|
||||
"""
|
||||
Set the range of the color bar.
|
||||
Args:
|
||||
vmin(float): Minimum value of the color bar.
|
||||
vmax(float): Maximum value of the color bar.
|
||||
"""
|
||||
if vrange is not None:
|
||||
vmin, vmax = vrange
|
||||
self.setLevels([vmin, vmax])
|
||||
self.config.vrange = (vmin, vmax)
|
||||
self.config.autorange = False
|
||||
if self.color_bar is not None:
|
||||
if self.config.color_bar == "simple":
|
||||
self.color_bar.setLevels(low=vmin, high=vmax)
|
||||
elif self.config.color_bar == "full":
|
||||
self.color_bar.setLevels(min=vmin, max=vmax)
|
||||
self.color_bar.setHistogramRange(vmin - 0.1 * vmin, vmax + 0.1 * vmax)
|
||||
|
||||
def _add_color_bar(
|
||||
self, color_bar_style: str = "simple", vrange: Optional[tuple[int, int]] = None
|
||||
):
|
||||
"""
|
||||
Add color bar to the layout.
|
||||
Args:
|
||||
style(Literal["simple,full"]): The style of the color bar.
|
||||
vrange(tuple[int,int]): The range of the color bar.
|
||||
"""
|
||||
if color_bar_style == "simple":
|
||||
self.color_bar = pg.ColorBarItem(colorMap=self.config.color_map)
|
||||
if vrange is not None:
|
||||
self.color_bar.setLevels(low=vrange[0], high=vrange[1])
|
||||
self.color_bar.setImageItem(self)
|
||||
self.parent_image.addItem(self.color_bar) # , row=0, col=1)
|
||||
self.config.color_bar = "simple"
|
||||
elif color_bar_style == "full":
|
||||
# Setting histogram
|
||||
self.color_bar = pg.HistogramLUTItem()
|
||||
self.color_bar.setImageItem(self)
|
||||
self.color_bar.gradient.loadPreset(self.config.color_map)
|
||||
if vrange is not None:
|
||||
self.color_bar.setLevels(min=vrange[0], max=vrange[1])
|
||||
self.color_bar.setHistogramRange(
|
||||
vrange[0] - 0.1 * vrange[0], vrange[1] + 0.1 * vrange[1]
|
||||
)
|
||||
|
||||
# Adding histogram to the layout
|
||||
self.parent_image.addItem(self.color_bar) # , row=0, col=1)
|
||||
|
||||
# save settings
|
||||
self.config.color_bar = "full"
|
||||
else:
|
||||
raise ValueError("style should be 'simple' or 'full'")
|
||||
|
||||
|
||||
class BECImageShow(BECPlotBase):
|
||||
USER_ACCESS = [
|
||||
"add_image_by_config",
|
||||
"get_image_config",
|
||||
"get_image_list",
|
||||
"get_image_dict",
|
||||
"add_monitor_image",
|
||||
"add_custom_image",
|
||||
"set_vrange",
|
||||
"set_color_map",
|
||||
]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent: Optional[QWidget] = None,
|
||||
parent_figure=None,
|
||||
config: Optional[ImageConfig] = None,
|
||||
client=None,
|
||||
gui_id: Optional[str] = None,
|
||||
):
|
||||
if config is None:
|
||||
config = ImageConfig(widget_class=self.__class__.__name__)
|
||||
super().__init__(
|
||||
parent=parent, parent_figure=parent_figure, config=config, client=client, gui_id=gui_id
|
||||
)
|
||||
|
||||
self._images = defaultdict(dict)
|
||||
self.apply_config(self.config)
|
||||
self.processor = ImageProcessor()
|
||||
self.use_threading = False # TODO WILL be moved to the init method and to figure method
|
||||
|
||||
def _create_thread_worker(self, device: str, image: np.ndarray):
|
||||
thread = QThread()
|
||||
worker = ProcessorWorker(self.processor)
|
||||
worker.moveToThread(thread)
|
||||
|
||||
# Connect signals and slots
|
||||
thread.started.connect(lambda: worker.process_image(device, image))
|
||||
worker.processed.connect(self.update_image)
|
||||
worker.finished.connect(thread.quit)
|
||||
worker.finished.connect(thread.wait)
|
||||
worker.finished.connect(worker.deleteLater)
|
||||
thread.finished.connect(thread.deleteLater)
|
||||
|
||||
thread.start()
|
||||
|
||||
def find_widget_by_id(self, item_id: str) -> BECImageItem:
|
||||
"""
|
||||
Find the widget by its gui_id.
|
||||
Args:
|
||||
item_id(str): The gui_id of the widget.
|
||||
|
||||
Returns:
|
||||
BECImageItem: The widget with the given gui_id.
|
||||
"""
|
||||
for source, images in self._images.items():
|
||||
for monitor, image_item in images.items():
|
||||
if image_item.gui_id == item_id:
|
||||
return image_item
|
||||
|
||||
def find_image_by_monitor(self, item_id: str) -> BECImageItem:
|
||||
"""
|
||||
Find the widget by its gui_id.
|
||||
Args:
|
||||
item_id(str): The gui_id of the widget.
|
||||
|
||||
Returns:
|
||||
BECImageItem: The widget with the given gui_id.
|
||||
"""
|
||||
for source, images in self._images.items():
|
||||
for key, value in images.items():
|
||||
if key == item_id and isinstance(value, BECImageItem):
|
||||
return value
|
||||
elif isinstance(value, dict):
|
||||
result = self.find_image_by_monitor(item_id)
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
def apply_config(self, config: dict | WidgetConfig):
|
||||
"""
|
||||
Apply the configuration to the 1D waveform widget.
|
||||
Args:
|
||||
config(dict|WidgetConfig): Configuration settings.
|
||||
replot_last_scan(bool, optional): If True, replot the last scan. Defaults to False.
|
||||
"""
|
||||
if isinstance(config, dict):
|
||||
try:
|
||||
config = ImageConfig(**config)
|
||||
except ValidationError as e:
|
||||
print(f"Validation error when applying config to BECImageShow: {e}")
|
||||
return
|
||||
self.config = config
|
||||
self.plot_item.clear()
|
||||
|
||||
self.apply_axis_config()
|
||||
self._images = defaultdict(dict)
|
||||
|
||||
# TODO extend by adding image by config
|
||||
|
||||
def change_gui_id(self, new_gui_id: str):
|
||||
"""
|
||||
Change the GUI ID of the image widget and update the parent_id in all associated curves.
|
||||
|
||||
Args:
|
||||
new_gui_id (str): The new GUI ID to be set for the image widget.
|
||||
"""
|
||||
self.gui_id = new_gui_id
|
||||
self.config.gui_id = new_gui_id
|
||||
|
||||
for source, images in self._images.items():
|
||||
for id, image_item in images.items():
|
||||
image_item.config.parent_id = new_gui_id
|
||||
|
||||
def add_image_by_config(self, config: ImageItemConfig | dict) -> BECImageItem:
|
||||
"""
|
||||
Add an image to the widget by configuration.
|
||||
Args:
|
||||
config(ImageItemConfig|dict): The configuration of the image.
|
||||
|
||||
Returns:
|
||||
BECImageItem: The image object.
|
||||
"""
|
||||
if isinstance(config, dict):
|
||||
config = ImageItemConfig(**config)
|
||||
config.parent_id = self.gui_id
|
||||
name = config.monitor if config.monitor is not None else config.gui_id
|
||||
image = self._add_image_object(source=config.source, name=name, config=config)
|
||||
return image
|
||||
|
||||
def get_image_config(self, image_id, dict_output: bool = True) -> ImageItemConfig | dict:
|
||||
"""
|
||||
Get the configuration of the image.
|
||||
Args:
|
||||
image_id(str): The ID of the image.
|
||||
dict_output(bool): Whether to return the configuration as a dictionary. Defaults to True.
|
||||
|
||||
Returns:
|
||||
ImageItemConfig|dict: The configuration of the image.
|
||||
"""
|
||||
for source, images in self._images.items():
|
||||
for id, image in images.items():
|
||||
if id == image_id:
|
||||
if dict_output:
|
||||
return image.config.dict()
|
||||
else:
|
||||
return image.config # TODO check if this works
|
||||
|
||||
def get_image_list(self) -> list[BECImageItem]:
|
||||
"""
|
||||
Get the list of images.
|
||||
Returns:
|
||||
list[BECImageItem]: The list of images.
|
||||
"""
|
||||
images = []
|
||||
for source, images_dict in self._images.items():
|
||||
for id, image in images_dict.items():
|
||||
images.append(image)
|
||||
return images
|
||||
|
||||
def get_image_dict(self) -> dict[str, dict[str, BECImageItem]]:
|
||||
"""
|
||||
Get all images.
|
||||
Returns:
|
||||
dict[str, dict[str, BECImageItem]]: The dictionary of images.
|
||||
"""
|
||||
return self._images
|
||||
|
||||
def add_monitor_image(
|
||||
self,
|
||||
monitor: str,
|
||||
color_map: Optional[str] = "magma",
|
||||
color_bar: Optional[Literal["simple", "full"]] = "simple",
|
||||
downsample: Optional[bool] = True,
|
||||
opacity: Optional[float] = 1.0,
|
||||
vrange: Optional[tuple[int, int]] = None,
|
||||
# post_processing: Optional[PostProcessingConfig] = None,
|
||||
**kwargs,
|
||||
) -> BECImageItem:
|
||||
image_source = "device_monitor"
|
||||
|
||||
image_exits = self._check_image_id(monitor, self._images)
|
||||
if image_exits:
|
||||
raise ValueError(
|
||||
f"Monitor with ID '{monitor}' already exists in widget '{self.gui_id}'."
|
||||
)
|
||||
|
||||
image_config = ImageItemConfig(
|
||||
widget_class="BECImageItem",
|
||||
parent_id=self.gui_id,
|
||||
color_map=color_map,
|
||||
color_bar=color_bar,
|
||||
downsample=downsample,
|
||||
opacity=opacity,
|
||||
vrange=vrange,
|
||||
# post_processing=post_processing,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
image = self._add_image_object(source=image_source, name=monitor, config=image_config)
|
||||
self._connect_device_monitor(monitor)
|
||||
return image
|
||||
|
||||
def add_custom_image(
|
||||
self,
|
||||
name: str,
|
||||
data: Optional[np.ndarray] = None,
|
||||
color_map: Optional[str] = "magma",
|
||||
color_bar: Optional[Literal["simple", "full"]] = "simple",
|
||||
downsample: Optional[bool] = True,
|
||||
opacity: Optional[float] = 1.0,
|
||||
vrange: Optional[tuple[int, int]] = None,
|
||||
# post_processing: Optional[PostProcessingConfig] = None,
|
||||
**kwargs,
|
||||
):
|
||||
image_source = "device_monitor"
|
||||
|
||||
image_exits = self._check_curve_id(name, self._images)
|
||||
if image_exits:
|
||||
raise ValueError(f"Monitor with ID '{name}' already exists in widget '{self.gui_id}'.")
|
||||
|
||||
image_config = ImageItemConfig(
|
||||
widget_class="BECImageItem",
|
||||
parent_id=self.gui_id,
|
||||
monitor=name,
|
||||
color_map=color_map,
|
||||
color_bar=color_bar,
|
||||
downsample=downsample,
|
||||
opacity=opacity,
|
||||
vrange=vrange,
|
||||
# post_processing=post_processing,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
image = self._add_image_object(source=image_source, config=image_config, data=data)
|
||||
return image
|
||||
|
||||
def apply_setting_to_images(
|
||||
self, setting_method_name: str, args: list, kwargs: dict, image_id: str = None
|
||||
):
|
||||
"""
|
||||
Apply a setting to all images or a specific image by its ID.
|
||||
|
||||
Args:
|
||||
setting_method_name (str): The name of the method to apply (e.g., 'set_color_map').
|
||||
args (list): Positional arguments for the setting method.
|
||||
kwargs (dict): Keyword arguments for the setting method.
|
||||
image_id (str, optional): The ID of the specific image to apply the setting to. If None, applies to all images.
|
||||
"""
|
||||
if image_id:
|
||||
image = self.find_image_by_monitor(image_id)
|
||||
if image:
|
||||
getattr(image, setting_method_name)(*args, **kwargs)
|
||||
else:
|
||||
for source, images in self._images.items():
|
||||
for _, image in images.items():
|
||||
getattr(image, setting_method_name)(*args, **kwargs)
|
||||
|
||||
def set_vrange(self, vmin: float, vmax: float, name: str = None):
|
||||
"""
|
||||
Set the range of the color bar.
|
||||
If name is not specified, then set vrange for all images.
|
||||
Args:
|
||||
vmin(float): Minimum value of the color bar.
|
||||
vmax(float): Maximum value of the color bar.
|
||||
name(str): The name of the image. If None, apply to all images.
|
||||
"""
|
||||
self.apply_setting_to_images("set_vrange", args=[vmin, vmax], kwargs={}, image_id=name)
|
||||
|
||||
def set_color_map(self, cmap: str, name: str = None):
|
||||
"""
|
||||
Set the color map of the image.
|
||||
If name is not specified, then set color map for all images.
|
||||
Args:
|
||||
cmap(str): The color map of the image.
|
||||
name(str): The name of the image. If None, apply to all images.
|
||||
"""
|
||||
self.apply_setting_to_images("set_color_map", args=[cmap], kwargs={}, image_id=name)
|
||||
|
||||
def set_processing(self, name: str = None, **kwargs):
|
||||
"""
|
||||
Set the post processing of the image.
|
||||
If name is not specified, then set post processing for all images.
|
||||
Args:
|
||||
name(str): The name of the image. If None, apply to all images.
|
||||
**kwargs: Keyword arguments for the properties to be set.
|
||||
Possible properties:
|
||||
- fft: bool
|
||||
- log: bool
|
||||
- rot: int
|
||||
- transpose: bool
|
||||
"""
|
||||
self.apply_setting_to_images("set", args=[], kwargs=kwargs, image_id=name)
|
||||
|
||||
def set_image_properties(self, name: str = None, **kwargs):
|
||||
"""
|
||||
Set the properties of the image.
|
||||
Args:
|
||||
name(str): The name of the image. If None, apply to all images.
|
||||
**kwargs: Keyword arguments for the properties to be set.
|
||||
Possible properties:
|
||||
- downsample: bool
|
||||
- color_map: str
|
||||
- monitor: str
|
||||
- opacity: float
|
||||
- vrange: tuple[int,int]
|
||||
- fft: bool
|
||||
- log: bool
|
||||
- rot: int
|
||||
- transpose: bool
|
||||
"""
|
||||
self.apply_setting_to_images("set", args=[], kwargs=kwargs, image_id=name)
|
||||
|
||||
def set_fft(self, enable: bool = False, name: str = None):
|
||||
"""
|
||||
Set the FFT of the image.
|
||||
If name is not specified, then set FFT for all images.
|
||||
Args:
|
||||
enable(bool): Whether to perform FFT on the monitor data.
|
||||
name(str): The name of the image. If None, apply to all images.
|
||||
"""
|
||||
self.apply_setting_to_images("set_fft", args=[enable], kwargs={}, image_id=name)
|
||||
|
||||
def set_log(self, enable: bool = False, name: str = None):
|
||||
"""
|
||||
Set the log of the image.
|
||||
If name is not specified, then set log for all images.
|
||||
Args:
|
||||
enable(bool): Whether to perform log on the monitor data.
|
||||
name(str): The name of the image. If None, apply to all images.
|
||||
"""
|
||||
self.apply_setting_to_images("set_log", args=[enable], kwargs={}, image_id=name)
|
||||
|
||||
def set_rotation(self, deg_90: int = 0, name: str = None):
|
||||
"""
|
||||
Set the rotation of the image.
|
||||
If name is not specified, then set rotation for all images.
|
||||
Args:
|
||||
deg_90(int): The rotation angle of the monitor data before displaying.
|
||||
name(str): The name of the image. If None, apply to all images.
|
||||
"""
|
||||
self.apply_setting_to_images("set_rotation", args=[deg_90], kwargs={}, image_id=name)
|
||||
|
||||
def set_transpose(self, enable: bool = False, name: str = None):
|
||||
"""
|
||||
Set the transpose of the image.
|
||||
If name is not specified, then set transpose for all images.
|
||||
Args:
|
||||
enable(bool): Whether to transpose the monitor data before displaying.
|
||||
name(str): The name of the image. If None, apply to all images.
|
||||
"""
|
||||
self.apply_setting_to_images("set_transpose", args=[enable], kwargs={}, image_id=name)
|
||||
|
||||
def toggle_threading(self, use_threading: bool):
|
||||
"""
|
||||
Toggle threading for the widgets postprocessing and updating.
|
||||
Args:
|
||||
use_threading(bool): Whether to use threading.
|
||||
"""
|
||||
self.use_threading = use_threading
|
||||
if self.use_threading is False and self.thread.isRunning():
|
||||
self.cleanup()
|
||||
|
||||
@pyqtSlot(dict)
|
||||
def on_image_update(self, msg: dict):
|
||||
"""
|
||||
Update the image of the device monitor from bec.
|
||||
Args:
|
||||
msg(dict): The message from bec.
|
||||
"""
|
||||
data = msg["data"]
|
||||
device = msg["device"]
|
||||
image_to_update = self._images["device_monitor"][device]
|
||||
processing_config = image_to_update.config.processing
|
||||
self.processor.set_config(processing_config)
|
||||
if self.use_threading:
|
||||
print("using threaded version")
|
||||
self._create_thread_worker(device, data)
|
||||
else:
|
||||
print("using NON-threaded version")
|
||||
data = self.processor.process_image(data)
|
||||
self.update_image(device, data)
|
||||
|
||||
@pyqtSlot(str, np.ndarray)
|
||||
def update_image(self, device: str, data: np.ndarray):
|
||||
"""
|
||||
Update the image of the device monitor.
|
||||
Args:
|
||||
device(str): The name of the device.
|
||||
data(np.ndarray): The data to be updated.
|
||||
"""
|
||||
image_to_update = self._images["device_monitor"][device]
|
||||
image_to_update.updateImage(data, autoLevels=image_to_update.config.autorange)
|
||||
|
||||
def _connect_device_monitor(self, monitor: str):
|
||||
"""
|
||||
Connect to the device monitor.
|
||||
Args:
|
||||
monitor(str): The name of the monitor.
|
||||
"""
|
||||
image_item = self.find_image_by_monitor(monitor)
|
||||
try:
|
||||
previous_monitor = image_item.config.monitor
|
||||
except AttributeError:
|
||||
previous_monitor = None
|
||||
if previous_monitor != monitor:
|
||||
if previous_monitor:
|
||||
self.bec_dispatcher.disconnect_slot(
|
||||
self.on_image_update, MessageEndpoints.device_monitor(previous_monitor)
|
||||
)
|
||||
if monitor:
|
||||
self.bec_dispatcher.connect_slot(
|
||||
self.on_image_update, MessageEndpoints.device_monitor(monitor)
|
||||
)
|
||||
image_item.set_monitor(monitor)
|
||||
|
||||
def _add_image_object(
|
||||
self, source: str, name: str, config: ImageItemConfig, data=None
|
||||
) -> BECImageItem: # TODO fix types
|
||||
config.parent_id = self.gui_id
|
||||
image = BECImageItem(config=config, parent_image=self)
|
||||
self.plot_item.addItem(image)
|
||||
self._images[source][name] = image
|
||||
self.config.images[name] = config
|
||||
if data is not None:
|
||||
image.setImage(data)
|
||||
return image
|
||||
|
||||
def _check_image_id(self, val: Any, dict_to_check: dict) -> bool:
|
||||
"""
|
||||
Check if val is in the values of the dict_to_check or in the values of the nested dictionaries.
|
||||
Args:
|
||||
val(Any): Value to check.
|
||||
dict_to_check(dict): Dictionary to check.
|
||||
|
||||
Returns:
|
||||
bool: True if val is in the values of the dict_to_check or in the values of the nested dictionaries, False otherwise.
|
||||
"""
|
||||
if val in dict_to_check.keys():
|
||||
return True
|
||||
for key in dict_to_check:
|
||||
if isinstance(dict_to_check[key], dict):
|
||||
if self._check_image_id(val, dict_to_check[key]):
|
||||
return True
|
||||
return False
|
||||
|
||||
def cleanup(self):
|
||||
"""
|
||||
Clean up the widget.
|
||||
"""
|
||||
print(f"Cleaning up {self.gui_id}")
|
||||
# for monitor in self._images["device_monitor"]:
|
||||
# self.bec_dispatcher.disconnect_slot(
|
||||
# self.on_image_update, MessageEndpoints.device_monitor(monitor)
|
||||
# )
|
||||
# if self.thread is not None and self.thread.isRunning():
|
||||
# self.thread.quit()
|
||||
# self.thread.wait()
|
||||
|
||||
|
||||
class ImageProcessor:
|
||||
"""
|
||||
Class for processing the image data.
|
||||
"""
|
||||
|
||||
def __init__(self, config: ProcessingConfig = None):
|
||||
if config is None:
|
||||
config = ProcessingConfig()
|
||||
self.config = config
|
||||
|
||||
def set_config(self, config: ProcessingConfig):
|
||||
"""
|
||||
Set the configuration of the processor.
|
||||
Args:
|
||||
config(ProcessingConfig): The configuration of the processor.
|
||||
"""
|
||||
self.config = config
|
||||
|
||||
def FFT(self, data: np.ndarray) -> np.ndarray:
|
||||
"""
|
||||
Perform FFT on the data.
|
||||
Args:
|
||||
data(np.ndarray): The data to be processed.
|
||||
|
||||
Returns:
|
||||
np.ndarray: The processed data.
|
||||
"""
|
||||
return np.abs(np.fft.fftshift(np.fft.fft2(data)))
|
||||
|
||||
def rotation(self, data: np.ndarray, rotate_90: int) -> np.ndarray:
|
||||
"""
|
||||
Rotate the data by 90 degrees n times.
|
||||
Args:
|
||||
data(np.ndarray): The data to be processed.
|
||||
rotate_90(int): The number of 90 degree rotations.
|
||||
|
||||
Returns:
|
||||
np.ndarray: The processed data.
|
||||
"""
|
||||
return np.rot90(data, k=rotate_90, axes=(0, 1))
|
||||
|
||||
def transpose(self, data: np.ndarray) -> np.ndarray:
|
||||
"""
|
||||
Transpose the data.
|
||||
Args:
|
||||
data(np.ndarray): The data to be processed.
|
||||
|
||||
Returns:
|
||||
np.ndarray: The processed data.
|
||||
"""
|
||||
return np.transpose(data)
|
||||
|
||||
def log(self, data: np.ndarray) -> np.ndarray:
|
||||
"""
|
||||
Perform log on the data.
|
||||
Args:
|
||||
data(np.ndarray): The data to be processed.
|
||||
|
||||
Returns:
|
||||
np.ndarray: The processed data.
|
||||
"""
|
||||
# TODO this is not final solution -> data should stay as int16
|
||||
data = data.astype(np.float32)
|
||||
offset = 1e-6
|
||||
data_offset = data + offset
|
||||
return np.log10(data_offset)
|
||||
|
||||
# def center_of_mass(self, data: np.ndarray) -> tuple: # TODO check functionality
|
||||
# return np.unravel_index(np.argmax(data), data.shape)
|
||||
|
||||
def process_image(self, data: np.ndarray) -> np.ndarray:
|
||||
"""
|
||||
Process the data according to the configuration.
|
||||
Args:
|
||||
data(np.ndarray): The data to be processed.
|
||||
|
||||
Returns:
|
||||
np.ndarray: The processed data.
|
||||
"""
|
||||
if self.config.fft:
|
||||
data = self.FFT(data)
|
||||
if self.config.rotation is not None:
|
||||
data = self.rotation(data, self.config.rotation)
|
||||
if self.config.transpose:
|
||||
data = self.transpose(data)
|
||||
if self.config.log:
|
||||
data = self.log(data)
|
||||
return data
|
||||
|
||||
|
||||
class ProcessorWorker(QObject):
|
||||
"""
|
||||
Worker for processing the image data.
|
||||
"""
|
||||
|
||||
processed = pyqtSignal(str, np.ndarray)
|
||||
stopRequested = pyqtSignal()
|
||||
finished = pyqtSignal()
|
||||
|
||||
def __init__(self, processor):
|
||||
super().__init__()
|
||||
self.processor = processor
|
||||
self._isRunning = False
|
||||
self.stopRequested.connect(self.stop)
|
||||
|
||||
@pyqtSlot(str, np.ndarray)
|
||||
def process_image(self, device: str, image: np.ndarray):
|
||||
"""
|
||||
Process the image data.
|
||||
Args:
|
||||
device(str): The name of the device.
|
||||
image(np.ndarray): The image data.
|
||||
"""
|
||||
self._isRunning = True
|
||||
processed_image = self.processor.process_image(image)
|
||||
self._isRunning = False
|
||||
if not self._isRunning:
|
||||
self.processed.emit(device, processed_image)
|
||||
self.finished.emit()
|
||||
|
||||
def stop(self):
|
||||
self._isRunning = False
|
||||
@@ -36,7 +36,7 @@ class WidgetConfig(ConnectionConfig):
|
||||
)
|
||||
|
||||
|
||||
class BECPlotBase(BECConnector, pg.GraphicsLayout):
|
||||
class BECPlotBase(BECConnector, pg.PlotItem):
|
||||
USER_ACCESS = [
|
||||
"set",
|
||||
"set_title",
|
||||
@@ -47,8 +47,7 @@ class BECPlotBase(BECConnector, pg.GraphicsLayout):
|
||||
"set_x_lim",
|
||||
"set_y_lim",
|
||||
"set_grid",
|
||||
"lock_aspect_ratio",
|
||||
"plot",
|
||||
"plot_data",
|
||||
"remove",
|
||||
]
|
||||
|
||||
@@ -63,10 +62,9 @@ class BECPlotBase(BECConnector, pg.GraphicsLayout):
|
||||
if config is None:
|
||||
config = WidgetConfig(widget_class=self.__class__.__name__)
|
||||
super().__init__(client=client, config=config, gui_id=gui_id)
|
||||
pg.GraphicsLayout.__init__(self, parent)
|
||||
pg.PlotItem.__init__(self, parent)
|
||||
|
||||
self.figure = parent_figure
|
||||
self.plot_item = self.addPlot()
|
||||
|
||||
self.add_legend()
|
||||
|
||||
@@ -120,7 +118,7 @@ class BECPlotBase(BECConnector, pg.GraphicsLayout):
|
||||
Args:
|
||||
title(str): Title of the plot widget.
|
||||
"""
|
||||
self.plot_item.setTitle(title)
|
||||
self.setTitle(title)
|
||||
self.config.axis.title = title
|
||||
|
||||
def set_x_label(self, label: str):
|
||||
@@ -129,7 +127,7 @@ class BECPlotBase(BECConnector, pg.GraphicsLayout):
|
||||
Args:
|
||||
label(str): Label of the x-axis.
|
||||
"""
|
||||
self.plot_item.setLabel("bottom", label)
|
||||
self.setLabel("bottom", label)
|
||||
self.config.axis.x_label = label
|
||||
|
||||
def set_y_label(self, label: str):
|
||||
@@ -138,7 +136,7 @@ class BECPlotBase(BECConnector, pg.GraphicsLayout):
|
||||
Args:
|
||||
label(str): Label of the y-axis.
|
||||
"""
|
||||
self.plot_item.setLabel("left", label)
|
||||
self.setLabel("left", label)
|
||||
self.config.axis.y_label = label
|
||||
|
||||
def set_x_scale(self, scale: Literal["linear", "log"] = "linear"):
|
||||
@@ -147,7 +145,7 @@ class BECPlotBase(BECConnector, pg.GraphicsLayout):
|
||||
Args:
|
||||
scale(Literal["linear", "log"]): Scale of the x-axis.
|
||||
"""
|
||||
self.plot_item.setLogMode(x=(scale == "log"))
|
||||
self.setLogMode(x=(scale == "log"))
|
||||
self.config.axis.x_scale = scale
|
||||
|
||||
def set_y_scale(self, scale: Literal["linear", "log"] = "linear"):
|
||||
@@ -156,7 +154,7 @@ class BECPlotBase(BECConnector, pg.GraphicsLayout):
|
||||
Args:
|
||||
scale(Literal["linear", "log"]): Scale of the y-axis.
|
||||
"""
|
||||
self.plot_item.setLogMode(y=(scale == "log"))
|
||||
self.setLogMode(y=(scale == "log"))
|
||||
self.config.axis.y_scale = scale
|
||||
|
||||
def set_x_lim(self, *args) -> None:
|
||||
@@ -179,7 +177,7 @@ class BECPlotBase(BECConnector, pg.GraphicsLayout):
|
||||
else:
|
||||
raise ValueError("set_x_lim expects either two separate arguments or a single tuple")
|
||||
|
||||
self.plot_item.setXRange(x_min, x_max)
|
||||
self.setXRange(x_min, x_max)
|
||||
self.config.axis.x_lim = (x_min, x_max)
|
||||
|
||||
def set_y_lim(self, *args) -> None:
|
||||
@@ -202,7 +200,7 @@ class BECPlotBase(BECConnector, pg.GraphicsLayout):
|
||||
else:
|
||||
raise ValueError("set_y_lim expects either two separate arguments or a single tuple")
|
||||
|
||||
self.plot_item.setYRange(y_min, y_max)
|
||||
self.setYRange(y_min, y_max)
|
||||
self.config.axis.y_lim = (y_min, y_max)
|
||||
|
||||
def set_grid(self, x: bool = False, y: bool = False):
|
||||
@@ -212,23 +210,14 @@ class BECPlotBase(BECConnector, pg.GraphicsLayout):
|
||||
x(bool): Show grid on the x-axis.
|
||||
y(bool): Show grid on the y-axis.
|
||||
"""
|
||||
self.plot_item.showGrid(x, y)
|
||||
self.showGrid(x, y)
|
||||
self.config.axis.x_grid = x
|
||||
self.config.axis.y_grid = y
|
||||
|
||||
def add_legend(self):
|
||||
"""Add legend to the plot"""
|
||||
self.plot_item.addLegend()
|
||||
self.addLegend()
|
||||
|
||||
def lock_aspect_ratio(self, lock):
|
||||
"""
|
||||
Lock aspect ratio.
|
||||
Args:
|
||||
lock(bool): True to lock, False to unlock.
|
||||
"""
|
||||
self.plot_item.setAspectLocked(lock)
|
||||
|
||||
def plot(self, data_x: list | np.ndarray, data_y: list | np.ndarray, **kwargs):
|
||||
def plot_data(self, data_x: list | np.ndarray, data_y: list | np.ndarray, **kwargs):
|
||||
"""
|
||||
Plot custom data on the plot widget. These data are not saved in config.
|
||||
Args:
|
||||
@@ -238,7 +227,7 @@ class BECPlotBase(BECConnector, pg.GraphicsLayout):
|
||||
"""
|
||||
# TODO very basic so far, add more options
|
||||
# TODO decide name of the method
|
||||
self.plot_item.plot(data_x, data_y, **kwargs)
|
||||
self.plot(data_x, data_y, **kwargs)
|
||||
|
||||
def remove(self):
|
||||
"""Remove the plot widget from the figure."""
|
||||
|
||||
@@ -21,6 +21,7 @@ from bec_widgets.widgets.plots import BECPlotBase, WidgetConfig
|
||||
class SignalData(BaseModel):
|
||||
"""The data configuration of a signal in the 1D waveform widget for x and y axis."""
|
||||
|
||||
# TODO add validator on name and entry
|
||||
name: str
|
||||
entry: str
|
||||
unit: Optional[str] = None # todo implement later
|
||||
@@ -30,7 +31,7 @@ class SignalData(BaseModel):
|
||||
class Signal(BaseModel):
|
||||
"""The configuration of a signal in the 1D waveform widget."""
|
||||
|
||||
source: str
|
||||
source: str # TODO add validator on the source type
|
||||
x: SignalData
|
||||
y: SignalData
|
||||
|
||||
@@ -46,7 +47,9 @@ class CurveConfig(ConnectionConfig):
|
||||
pen_style: Optional[Literal["solid", "dash", "dot", "dashdot"]] = Field(
|
||||
"solid", description="The style of the pen of the curve."
|
||||
)
|
||||
source: Optional[str] = Field(None, description="The source of the curve.")
|
||||
source: Optional[str] = Field(
|
||||
None, description="The source of the curve."
|
||||
) # TODO here on or curve??
|
||||
signals: Optional[Signal] = Field(None, description="The signal of the curve.")
|
||||
|
||||
|
||||
@@ -219,7 +222,7 @@ class BECWaveform1D(BECPlotBase):
|
||||
"remove_curve",
|
||||
"scan_history",
|
||||
"curves",
|
||||
# "curves_data",
|
||||
"curves_data",
|
||||
"get_curve",
|
||||
"get_curve_config",
|
||||
"apply_config",
|
||||
@@ -241,7 +244,7 @@ class BECWaveform1D(BECPlotBase):
|
||||
parent=parent, parent_figure=parent_figure, config=config, client=client, gui_id=gui_id
|
||||
)
|
||||
|
||||
self._curves_data = defaultdict(dict)
|
||||
self.curves_data = defaultdict(dict)
|
||||
self.scanID = None
|
||||
|
||||
# Scan segment update proxy
|
||||
@@ -257,19 +260,15 @@ class BECWaveform1D(BECPlotBase):
|
||||
|
||||
self.entry_validator = EntryValidator(self.dev)
|
||||
|
||||
self.add_legend()
|
||||
self.addLegend()
|
||||
self.apply_config(self.config)
|
||||
|
||||
def find_widget_by_id(self, item_id: str) -> BECCurve:
|
||||
"""
|
||||
Find the curve by its ID.
|
||||
Args:
|
||||
item_id(str): ID of the curve.
|
||||
|
||||
Returns:
|
||||
BECCurve: The curve object.
|
||||
"""
|
||||
for curve in self.plot_item.curves:
|
||||
# TODO check config assigning
|
||||
# TODO check the functionality of config generator
|
||||
def find_widget_by_id(
|
||||
self, item_id: str
|
||||
): # TODO implement this on level of BECConnector and all other widgets
|
||||
for curve in self.curves:
|
||||
if curve.gui_id == item_id:
|
||||
return curve
|
||||
|
||||
@@ -288,12 +287,12 @@ class BECWaveform1D(BECPlotBase):
|
||||
return
|
||||
|
||||
self.config = config
|
||||
self.plot_item.clear() # TODO not sure if on the plot or layout level
|
||||
self.clear()
|
||||
|
||||
self.apply_axis_config()
|
||||
# Reset curves
|
||||
self._curves_data = defaultdict(dict)
|
||||
self._curves = self.plot_item.curves
|
||||
self._curves = []
|
||||
for curve_id, curve_config in self.config.curves.items():
|
||||
self.add_curve_by_config(curve_config)
|
||||
if replot_last_scan:
|
||||
@@ -336,7 +335,7 @@ class BECWaveform1D(BECPlotBase):
|
||||
Returns:
|
||||
CurveConfig|dict: Configuration of the curve.
|
||||
"""
|
||||
for source, curves in self._curves_data.items():
|
||||
for source, curves in self.curves_data.items():
|
||||
if curve_id in curves:
|
||||
if dict_output:
|
||||
return curves[curve_id].config.model_dump()
|
||||
@@ -344,7 +343,7 @@ class BECWaveform1D(BECPlotBase):
|
||||
return curves[curve_id].config
|
||||
|
||||
@property
|
||||
def curves(self) -> list[BECCurve]:
|
||||
def curves(self) -> list[BECCurve]: # TODO discuss if it should be marked as @property for RPC
|
||||
"""
|
||||
Get the curves of the plot widget as a list
|
||||
Returns:
|
||||
@@ -357,7 +356,7 @@ class BECWaveform1D(BECPlotBase):
|
||||
self._curves = value
|
||||
|
||||
@property
|
||||
def curves_data(self) -> dict[str, dict[str, BECCurve]]:
|
||||
def curves_data(self) -> dict: # TODO discuss if it should be marked as @property for RPC
|
||||
"""
|
||||
Get the curves data of the plot widget as a dictionary
|
||||
Returns:
|
||||
@@ -366,7 +365,7 @@ class BECWaveform1D(BECPlotBase):
|
||||
return self._curves_data
|
||||
|
||||
@curves_data.setter
|
||||
def curves_data(self, value: dict[str, dict[str, BECCurve]]):
|
||||
def curves_data(self, value: dict):
|
||||
self._curves_data = value
|
||||
|
||||
def get_curve(self, identifier) -> BECCurve:
|
||||
@@ -378,9 +377,9 @@ class BECWaveform1D(BECPlotBase):
|
||||
BECCurve: The curve object.
|
||||
"""
|
||||
if isinstance(identifier, int):
|
||||
return self.plot_item.curves[identifier]
|
||||
return self.curves[identifier]
|
||||
elif isinstance(identifier, str):
|
||||
for source_type, curves in self._curves_data.items():
|
||||
for source_type, curves in self.curves_data.items():
|
||||
if identifier in curves:
|
||||
return curves[identifier]
|
||||
raise ValueError(f"Curve with ID '{identifier}' not found.")
|
||||
@@ -408,9 +407,9 @@ class BECWaveform1D(BECPlotBase):
|
||||
BECCurve: The curve object.
|
||||
"""
|
||||
curve_source = "custom"
|
||||
curve_id = label or f"Curve {len(self.plot_item.curves) + 1}"
|
||||
curve_id = label or f"Curve {len(self.curves) + 1}"
|
||||
|
||||
curve_exits = self._check_curve_id(curve_id, self._curves_data)
|
||||
curve_exits = self._check_curve_id(curve_id, self.curves_data)
|
||||
if curve_exits:
|
||||
raise ValueError(
|
||||
f"Curve with ID '{curve_id}' already exists in widget '{self.gui_id}'."
|
||||
@@ -419,7 +418,7 @@ class BECWaveform1D(BECPlotBase):
|
||||
color = (
|
||||
color
|
||||
or Colors.golden_angle_color(
|
||||
colormap=self.config.color_palette, num=len(self.plot_item.curves) + 1, format="HEX"
|
||||
colormap=self.config.color_palette, num=len(self.curves) + 1, format="HEX"
|
||||
)[-1]
|
||||
)
|
||||
|
||||
@@ -456,8 +455,8 @@ class BECWaveform1D(BECPlotBase):
|
||||
BECCurve: The curve object.
|
||||
"""
|
||||
curve = BECCurve(config=config, name=name)
|
||||
self._curves_data[source][name] = curve
|
||||
self.plot_item.addItem(curve)
|
||||
self.curves_data[source][name] = curve
|
||||
self.addItem(curve)
|
||||
self.config.curves[name] = curve.config
|
||||
if data is not None:
|
||||
curve.setData(data[0], data[1])
|
||||
@@ -498,14 +497,14 @@ class BECWaveform1D(BECPlotBase):
|
||||
|
||||
label = label or f"{y_name}-{y_entry}"
|
||||
|
||||
curve_exits = self._check_curve_id(label, self._curves_data)
|
||||
curve_exits = self._check_curve_id(label, self.curves_data)
|
||||
if curve_exits:
|
||||
raise ValueError(f"Curve with ID '{label}' already exists in widget '{self.gui_id}'.")
|
||||
|
||||
color = (
|
||||
color
|
||||
or Colors.golden_angle_color(
|
||||
colormap=self.config.color_palette, num=len(self.plot_item.curves) + 1, format="HEX"
|
||||
colormap=self.config.color_palette, num=len(self.curves) + 1, format="HEX"
|
||||
)[-1]
|
||||
)
|
||||
|
||||
@@ -593,13 +592,13 @@ class BECWaveform1D(BECPlotBase):
|
||||
Args:
|
||||
curve_id(str): ID of the curve to be removed.
|
||||
"""
|
||||
for source, curves in self._curves_data.items():
|
||||
for source, curves in self.curves_data.items():
|
||||
if curve_id in curves:
|
||||
curve = curves.pop(curve_id)
|
||||
self.plot_item.removeItem(curve)
|
||||
self.removeItem(curve)
|
||||
del self.config.curves[curve_id]
|
||||
if curve in self.plot_item.curves:
|
||||
self.plot_item.curves.remove(curve)
|
||||
if curve in self.curves:
|
||||
self.curves.remove(curve)
|
||||
return
|
||||
raise KeyError(f"Curve with ID '{curve_id}' not found.")
|
||||
|
||||
@@ -609,13 +608,13 @@ class BECWaveform1D(BECPlotBase):
|
||||
Args:
|
||||
N(int): Order of the curve to be removed.
|
||||
"""
|
||||
if N < len(self.plot_item.curves):
|
||||
curve = self.plot_item.curves[N]
|
||||
if N < len(self.curves):
|
||||
curve = self.curves[N]
|
||||
curve_id = curve.name() # Assuming curve's name is used as its ID
|
||||
self.plot_item.removeItem(curve)
|
||||
self.removeItem(curve)
|
||||
del self.config.curves[curve_id]
|
||||
# Remove from self.curve_data
|
||||
for source, curves in self._curves_data.items():
|
||||
for source, curves in self.curves_data.items():
|
||||
if curve_id in curves:
|
||||
del curves[curve_id]
|
||||
break
|
||||
@@ -654,7 +653,7 @@ class BECWaveform1D(BECPlotBase):
|
||||
Args:
|
||||
data(ScanData): Data from the scan segment.
|
||||
"""
|
||||
for curve_id, curve in self._curves_data["scan_segment"].items():
|
||||
for curve_id, curve in self.curves_data["scan_segment"].items():
|
||||
x_name = curve.config.signals.x.name
|
||||
x_entry = curve.config.signals.x.entry
|
||||
y_name = curve.config.signals.y.name
|
||||
@@ -710,7 +709,7 @@ class BECWaveform1D(BECPlotBase):
|
||||
)
|
||||
output = "dict"
|
||||
|
||||
for curve in self.plot_item.curves:
|
||||
for curve in self.curves:
|
||||
x_data, y_data = curve.get_data()
|
||||
if x_data is not None or y_data is not None:
|
||||
if output == "dict":
|
||||
@@ -720,9 +719,9 @@ class BECWaveform1D(BECPlotBase):
|
||||
|
||||
if output == "pandas" and pd is not None:
|
||||
combined_data = pd.concat(
|
||||
[data[curve.name()] for curve in self.plot_item.curves],
|
||||
[data[curve.name()] for curve in self.curves],
|
||||
axis=1,
|
||||
keys=[curve.name() for curve in self.plot_item.curves],
|
||||
keys=[curve.name() for curve in self.curves],
|
||||
)
|
||||
return combined_data
|
||||
return data
|
||||
|
||||
0
bec_widgets/widgets/scan_plot/__init__.py
Normal file
0
bec_widgets/widgets/scan_plot/__init__.py
Normal file
152
bec_widgets/widgets/scan_plot/scan2d_plot.py
Normal file
152
bec_widgets/widgets/scan_plot/scan2d_plot.py
Normal file
@@ -0,0 +1,152 @@
|
||||
from threading import RLock
|
||||
|
||||
import numpy as np
|
||||
import pyqtgraph as pg
|
||||
from bec_lib import MessageEndpoints
|
||||
from bec_lib.logger import bec_logger
|
||||
from qtpy.QtCore import Property as pyqtProperty, Slot as pyqtSlot
|
||||
|
||||
from bec_widgets.utils.bec_dispatcher import BECDispatcher
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
|
||||
pg.setConfigOptions(background="w", foreground="k", antialias=True)
|
||||
|
||||
|
||||
class BECScanPlot2D(pg.GraphicsView):
|
||||
def __init__(self, parent=None, background="default"):
|
||||
super().__init__(parent, background)
|
||||
BECDispatcher().connect_slot(self.on_scan_segment, MessageEndpoints.scan_segment())
|
||||
|
||||
self._scanID = None
|
||||
self._scanID_lock = RLock()
|
||||
|
||||
self._x_channel = ""
|
||||
self._y_channel = ""
|
||||
self._z_channel = ""
|
||||
|
||||
self._xpos = []
|
||||
self._ypos = []
|
||||
|
||||
self._x_ind = None
|
||||
self._y_ind = None
|
||||
|
||||
self.plot_item = pg.PlotItem()
|
||||
self.setCentralItem(self.plot_item)
|
||||
self.plot_item.setAspectLocked(True)
|
||||
|
||||
self.imageItem = pg.ImageItem()
|
||||
self.plot_item.addItem(self.imageItem)
|
||||
|
||||
def reset_plots(self, _scan_segment, metadata):
|
||||
# TODO: Do we reset in case of a scan type change?
|
||||
self.imageItem.clear()
|
||||
|
||||
# TODO: better to check the number of coordinates in metadata["positions"]?
|
||||
if metadata["scan_name"] != "grid_scan":
|
||||
return
|
||||
|
||||
positions = [sorted(set(pos)) for pos in zip(*metadata["positions"])]
|
||||
|
||||
motors = metadata["scan_motors"]
|
||||
if self.x_channel and self.y_channel:
|
||||
self._x_ind = motors.index(self.x_channel) if self.x_channel in motors else None
|
||||
self._y_ind = motors.index(self.y_channel) if self.y_channel in motors else None
|
||||
elif not self.x_channel and not self.y_channel:
|
||||
# Plot the first and second motors along x and y axes respectively
|
||||
self._x_ind = 0
|
||||
self._y_ind = 1
|
||||
else:
|
||||
logger.warning(
|
||||
f"X and Y channels should be either both empty or both set in {self.objectName()}"
|
||||
)
|
||||
|
||||
if self._x_ind is None or self._y_ind is None:
|
||||
return
|
||||
|
||||
xpos = positions[self._x_ind]
|
||||
ypos = positions[self._y_ind]
|
||||
|
||||
self._xpos = xpos
|
||||
self._ypos = ypos
|
||||
|
||||
self.imageItem.setImage(np.zeros(shape=(len(xpos), len(ypos))))
|
||||
|
||||
w = max(xpos) - min(xpos)
|
||||
h = max(ypos) - min(ypos)
|
||||
w_pix = w / (len(xpos) - 1)
|
||||
h_pix = h / (len(ypos) - 1)
|
||||
self.imageItem.setRect(min(xpos) - w_pix / 2, min(ypos) - h_pix / 2, w + w_pix, h + h_pix)
|
||||
|
||||
self.plot_item.setLabel("bottom", motors[self._x_ind])
|
||||
self.plot_item.setLabel("left", motors[self._y_ind])
|
||||
|
||||
@pyqtSlot(dict, dict)
|
||||
def on_scan_segment(self, scan_segment, metadata):
|
||||
# reset plots on scanID change
|
||||
with self._scanID_lock:
|
||||
scan_id = scan_segment["scanID"]
|
||||
if self._scanID != scan_id:
|
||||
self._scanID = scan_id
|
||||
self.reset_plots(scan_segment, metadata)
|
||||
|
||||
if not self.z_channel or metadata["scan_name"] != "grid_scan":
|
||||
return
|
||||
|
||||
if self._x_ind is None or self._y_ind is None:
|
||||
return
|
||||
|
||||
point_coord = metadata["positions"][scan_segment["point_id"]]
|
||||
|
||||
x_coord_ind = self._xpos.index(point_coord[self._x_ind])
|
||||
y_coord_ind = self._ypos.index(point_coord[self._y_ind])
|
||||
|
||||
data = scan_segment["data"]
|
||||
z_new = data[self.z_channel][self.z_channel]["value"]
|
||||
|
||||
image = self.imageItem.image
|
||||
image[x_coord_ind, y_coord_ind] = z_new
|
||||
self.imageItem.setImage()
|
||||
|
||||
@pyqtProperty(str)
|
||||
def x_channel(self):
|
||||
return self._x_channel
|
||||
|
||||
@x_channel.setter
|
||||
def x_channel(self, new_val):
|
||||
self._x_channel = new_val
|
||||
self.plot_item.setLabel("bottom", new_val)
|
||||
|
||||
@pyqtProperty(str)
|
||||
def y_channel(self):
|
||||
return self._y_channel
|
||||
|
||||
@y_channel.setter
|
||||
def y_channel(self, new_val):
|
||||
self._y_channel = new_val
|
||||
self.plot_item.setLabel("left", new_val)
|
||||
|
||||
@pyqtProperty(str)
|
||||
def z_channel(self):
|
||||
return self._z_channel
|
||||
|
||||
@z_channel.setter
|
||||
def z_channel(self, new_val):
|
||||
self._z_channel = new_val
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
|
||||
from qtpy.QtWidgets import QApplication
|
||||
|
||||
app = QApplication(sys.argv)
|
||||
|
||||
plot = BECScanPlot2D()
|
||||
# If x_channel and y_channel are both omitted, they will be inferred from each running grid scan
|
||||
plot.z_channel = "bpm3y"
|
||||
|
||||
plot.show()
|
||||
|
||||
sys.exit(app.exec())
|
||||
152
bec_widgets/widgets/scan_plot/scan_plot.py
Normal file
152
bec_widgets/widgets/scan_plot/scan_plot.py
Normal file
@@ -0,0 +1,152 @@
|
||||
import itertools
|
||||
from threading import RLock
|
||||
|
||||
import pyqtgraph as pg
|
||||
from bec_lib import MessageEndpoints
|
||||
from bec_lib.logger import bec_logger
|
||||
from qtpy.QtCore import Property as pyqtProperty, Slot as pyqtSlot
|
||||
|
||||
from bec_widgets.utils.bec_dispatcher import BECDispatcher
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
|
||||
pg.setConfigOptions(background="w", foreground="k", antialias=True)
|
||||
COLORS = ["#fd7f6f", "#7eb0d5", "#b2e061", "#bd7ebe", "#ffb55a"]
|
||||
|
||||
|
||||
class BECScanPlot(pg.GraphicsView):
|
||||
def __init__(self, parent=None, background="default"):
|
||||
super().__init__(parent, background)
|
||||
BECDispatcher().connect_slot(self.on_scan_segment, MessageEndpoints.scan_segment())
|
||||
|
||||
self.view = pg.PlotItem()
|
||||
self.setCentralItem(self.view)
|
||||
|
||||
self._scanID = None
|
||||
self._scanID_lock = RLock()
|
||||
|
||||
self._x_channel = ""
|
||||
self._y_channel_list = []
|
||||
|
||||
self.scan_curves = {}
|
||||
self.dap_curves = {}
|
||||
|
||||
def reset_plots(self, _scan_segment, _metadata):
|
||||
for plot_curve in {**self.scan_curves, **self.dap_curves}.values():
|
||||
plot_curve.setData(x=[], y=[])
|
||||
|
||||
@pyqtSlot(dict, dict)
|
||||
def on_scan_segment(self, scan_segment, metadata):
|
||||
# reset plots on scanID change
|
||||
with self._scanID_lock:
|
||||
scan_id = scan_segment["scanID"]
|
||||
if self._scanID != scan_id:
|
||||
self._scanID = scan_id
|
||||
self.reset_plots(scan_segment, metadata)
|
||||
|
||||
if not self.x_channel:
|
||||
return
|
||||
|
||||
data = scan_segment["data"]
|
||||
|
||||
if self.x_channel not in data:
|
||||
logger.warning(f"Unknown channel `{self.x_channel}` for X data in {self.objectName()}")
|
||||
return
|
||||
|
||||
x_new = data[self.x_channel][self.x_channel]["value"]
|
||||
for chan, plot_curve in self.scan_curves.items():
|
||||
if not chan:
|
||||
continue
|
||||
|
||||
if chan not in data:
|
||||
logger.warning(f"Unknown channel `{chan}` for Y data in {self.objectName()}")
|
||||
continue
|
||||
|
||||
y_new = data[chan][chan]["value"]
|
||||
x, y = plot_curve.getData() # TODO: is it a good approach?
|
||||
if x is None:
|
||||
x = []
|
||||
if y is None:
|
||||
y = []
|
||||
|
||||
plot_curve.setData(x=[*x, x_new], y=[*y, y_new])
|
||||
|
||||
@pyqtSlot(dict, dict)
|
||||
def redraw_dap(self, content, _metadata):
|
||||
data = content["data"]
|
||||
for chan, plot_curve in self.dap_curves.items():
|
||||
if not chan:
|
||||
continue
|
||||
|
||||
if chan not in data:
|
||||
logger.warning(f"Unknown channel `{chan}` for DAP data in {self.objectName()}")
|
||||
continue
|
||||
|
||||
x_new = data[chan]["x"]
|
||||
y_new = data[chan]["y"]
|
||||
|
||||
plot_curve.setData(x=x_new, y=y_new)
|
||||
|
||||
@pyqtProperty("QStringList")
|
||||
def y_channel_list(self):
|
||||
return self._y_channel_list
|
||||
|
||||
@y_channel_list.setter
|
||||
def y_channel_list(self, new_list):
|
||||
bec_dispatcher = BECDispatcher()
|
||||
# TODO: do we want to care about dap/not dap here?
|
||||
chan_removed = [chan for chan in self._y_channel_list if chan not in new_list]
|
||||
if chan_removed and chan_removed[0].startswith("dap."):
|
||||
chan_removed = chan_removed[0].partition("dap.")[-1]
|
||||
chan_removed_ep = MessageEndpoints.processed_data(chan_removed)
|
||||
bec_dispatcher.disconnect_slot(self.redraw_dap, chan_removed_ep)
|
||||
|
||||
self._y_channel_list = new_list
|
||||
|
||||
# Prepare plot for a potentially different list of y channels
|
||||
self.view.clear()
|
||||
|
||||
self.view.addLegend()
|
||||
colors = itertools.cycle(COLORS)
|
||||
|
||||
for y_chan in new_list:
|
||||
if y_chan.startswith("dap."):
|
||||
y_chan = y_chan.partition("dap.")[-1]
|
||||
curves = self.dap_curves
|
||||
y_chan_ep = MessageEndpoints.processed_data(y_chan)
|
||||
bec_dispatcher.connect_slot(self.redraw_dap, y_chan_ep)
|
||||
else:
|
||||
curves = self.scan_curves
|
||||
|
||||
curves[y_chan] = self.view.plot(
|
||||
x=[], y=[], pen=pg.mkPen(color=next(colors), width=2), name=y_chan
|
||||
)
|
||||
|
||||
if len(new_list) == 1:
|
||||
self.view.setLabel("left", new_list[0])
|
||||
|
||||
@pyqtProperty(str)
|
||||
def x_channel(self):
|
||||
return self._x_channel
|
||||
|
||||
@x_channel.setter
|
||||
def x_channel(self, new_val):
|
||||
self._x_channel = new_val
|
||||
self.view.setLabel("bottom", new_val)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
|
||||
from qtpy.QtWidgets import QApplication
|
||||
|
||||
app = QApplication(sys.argv)
|
||||
|
||||
plot = BECScanPlot()
|
||||
plot.x_channel = "samx"
|
||||
plot.y_channel_list = ["bpm3y", "bpm6y"]
|
||||
|
||||
plot.show()
|
||||
|
||||
sys.exit(app.exec())
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
Before installing BEC Widgets, please ensure the following requirements are met:
|
||||
|
||||
1. **Python Version:** BEC Widgets requires Python version 3.10 or higher. Verify your Python version to ensure compatibility.
|
||||
1. **Python Version:** BEC Widgets requires Python version 3.9 or higher. Verify your Python version to ensure compatibility.
|
||||
2. **BEC Installation:** BEC Widgets works in conjunction with BEC. While BEC is a dependency and will be installed automatically, you can find more information about BEC and its installation process in the [BEC documentation](https://beamline-experiment-control.readthedocs.io/en/latest/).
|
||||
|
||||
**Standard Installation**
|
||||
@@ -43,4 +43,4 @@ If you encounter issues during installation, particularly with PyQt, try purging
|
||||
pip cache purge
|
||||
```
|
||||
|
||||
This can resolve conflicts or issues with package installations.
|
||||
This can resolve conflicts or issues with package installations.
|
||||
@@ -15,7 +15,7 @@ classifiers =
|
||||
package_dir =
|
||||
= .
|
||||
packages = find:
|
||||
python_requires = >=3.10
|
||||
python_requires = >=3.9
|
||||
|
||||
[options.packages.find]
|
||||
where = .
|
||||
|
||||
3
setup.py
3
setup.py
@@ -1,7 +1,7 @@
|
||||
# pylint: disable= missing-module-docstring
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
__version__ = "0.43.0"
|
||||
__version__ = "0.41.1"
|
||||
|
||||
# Default to PyQt6 if no other Qt binding is installed
|
||||
QT_DEPENDENCY = "PyQt6>=6.0"
|
||||
@@ -30,7 +30,6 @@ if __name__ == "__main__":
|
||||
"zmq",
|
||||
"h5py",
|
||||
"pyqtdarktheme",
|
||||
"black",
|
||||
],
|
||||
extras_require={
|
||||
"dev": [
|
||||
|
||||
@@ -206,7 +206,7 @@ def test_connect_one_slot_multiple_topics_single_callback(bec_dispatcher, consum
|
||||
# Simulate messages being published on each topic
|
||||
for topic in topics:
|
||||
msg_with_topic = MessageObject(
|
||||
topic=topic, value=ScanMessage(point_id=0, scanID=0, data={})
|
||||
topic=topic, value=ScanMessage(point_id=0, scanID=0, data={}).dumps()
|
||||
)
|
||||
consumer.register.call_args.kwargs["cb"](msg_with_topic)
|
||||
|
||||
|
||||
@@ -179,16 +179,16 @@ def test_remove_plot_by_providing_nothing(bec_figure):
|
||||
assert "Must provide either widget_id or coordinates for removal." in str(excinfo.value)
|
||||
|
||||
|
||||
# def test_change_theme(bec_figure): #TODO do no work at python 3.12
|
||||
# bec_figure.change_theme("dark")
|
||||
# assert bec_figure.config.theme == "dark"
|
||||
# assert bec_figure.backgroundBrush().color().name() == "#000000"
|
||||
# bec_figure.change_theme("light")
|
||||
# assert bec_figure.config.theme == "light"
|
||||
# assert bec_figure.backgroundBrush().color().name() == "#ffffff"
|
||||
# bec_figure.change_theme("dark")
|
||||
# assert bec_figure.config.theme == "dark"
|
||||
# assert bec_figure.backgroundBrush().color().name() == "#000000"
|
||||
def test_change_theme(bec_figure):
|
||||
bec_figure.change_theme("dark")
|
||||
assert bec_figure.config.theme == "dark"
|
||||
assert bec_figure.backgroundBrush().color().name() == "#000000"
|
||||
bec_figure.change_theme("light")
|
||||
assert bec_figure.config.theme == "light"
|
||||
assert bec_figure.backgroundBrush().color().name() == "#ffffff"
|
||||
bec_figure.change_theme("dark")
|
||||
assert bec_figure.config.theme == "dark"
|
||||
assert bec_figure.backgroundBrush().color().name() == "#000000"
|
||||
|
||||
|
||||
def test_change_layout(bec_figure):
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
import pytest
|
||||
from bec_widgets.cli.generate_cli import ClientGenerator
|
||||
from textwrap import dedent
|
||||
import black
|
||||
|
||||
|
||||
# Mock classes to test the generator
|
||||
class MockBECWaveform1D:
|
||||
USER_ACCESS = ["set_frequency", "set_amplitude"]
|
||||
|
||||
def set_frequency(self, frequency: float) -> list:
|
||||
"""Set the frequency of the waveform."""
|
||||
return [frequency]
|
||||
|
||||
def set_amplitude(self, amplitude: float) -> tuple[float, float]:
|
||||
"""Set the amplitude of the waveform."""
|
||||
return amplitude, amplitude
|
||||
|
||||
|
||||
class MockBECFigure:
|
||||
USER_ACCESS = ["add_plot", "remove_plot"]
|
||||
|
||||
def add_plot(self, plot_id: str):
|
||||
"""Add a plot to the figure."""
|
||||
pass
|
||||
|
||||
def remove_plot(self, plot_id: str):
|
||||
"""Remove a plot from the figure."""
|
||||
pass
|
||||
|
||||
|
||||
def test_client_generator_with_black_formatting():
|
||||
generator = ClientGenerator()
|
||||
generator.generate_client([MockBECWaveform1D, MockBECFigure])
|
||||
|
||||
# Format the expected output with black to ensure it matches the generator output
|
||||
expected_output = dedent(
|
||||
'''\
|
||||
# This file was automatically generated by generate_cli.py
|
||||
|
||||
from bec_widgets.cli.client_utils import rpc_call, RPCBase, BECFigureClientMixin
|
||||
from typing import Literal, Optional, overload
|
||||
|
||||
class MockBECWaveform1D(RPCBase):
|
||||
@rpc_call
|
||||
def set_frequency(self, frequency: float) -> list:
|
||||
"""
|
||||
Set the frequency of the waveform.
|
||||
"""
|
||||
@rpc_call
|
||||
def set_amplitude(self, amplitude: float) -> tuple[float, float]:
|
||||
"""
|
||||
Set the amplitude of the waveform.
|
||||
"""
|
||||
|
||||
class MockBECFigure(RPCBase):
|
||||
@rpc_call
|
||||
def add_plot(self, plot_id: str):
|
||||
"""
|
||||
Add a plot to the figure.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def remove_plot(self, plot_id: str):
|
||||
"""
|
||||
Remove a plot from the figure.
|
||||
"""
|
||||
'''
|
||||
)
|
||||
|
||||
expected_output_formatted = black.format_str(
|
||||
expected_output, mode=black.FileMode(line_length=100)
|
||||
).lstrip()
|
||||
|
||||
generated_output_formatted = black.format_str(
|
||||
generator.header + "\n" + generator.content, mode=black.FileMode(line_length=100)
|
||||
)
|
||||
|
||||
assert expected_output_formatted == generated_output_formatted
|
||||
489
tests/test_plot_app.py
Normal file
489
tests/test_plot_app.py
Normal file
@@ -0,0 +1,489 @@
|
||||
# pylint: disable = no-name-in-module,missing-class-docstring, missing-module-docstring
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pyqtgraph as pg
|
||||
import pytest
|
||||
from qtpy.QtWidgets import QMessageBox
|
||||
|
||||
from bec_widgets.examples.plot_app.plot_app import PlotApp, ErrorHandler
|
||||
|
||||
|
||||
def setup_plot_app(qtbot, config):
|
||||
"""Helper function to set up the PlotApp widget."""
|
||||
client = MagicMock()
|
||||
widget = PlotApp(config=config, client=client)
|
||||
qtbot.addWidget(widget)
|
||||
qtbot.waitExposed(widget)
|
||||
return widget
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def error_handler():
|
||||
# TODO so far tested separately, but the error message scenarios can be tested directly in the plot app
|
||||
return ErrorHandler()
|
||||
|
||||
|
||||
config_device_mode_all_filled = {
|
||||
"plot_settings": {
|
||||
"background_color": "black",
|
||||
"num_columns": 2,
|
||||
"colormap": "plasma",
|
||||
"scan_types": False,
|
||||
},
|
||||
"plot_data": [
|
||||
{
|
||||
"plot_name": "BPM4i plots vs samx",
|
||||
"x": {
|
||||
"label": "Motor Y",
|
||||
"signals": [{"name": "samx", "entry": "samx"}],
|
||||
},
|
||||
"y": {
|
||||
"label": "bpm4i",
|
||||
"signals": [{"name": "bpm4i", "entry": "bpm4i"}],
|
||||
},
|
||||
},
|
||||
{
|
||||
"plot_name": "Gauss plots vs samx",
|
||||
"x": {
|
||||
"label": "Motor X",
|
||||
"signals": [{"name": "samx", "entry": "samx"}],
|
||||
},
|
||||
"y": {
|
||||
"label": "Gauss",
|
||||
"signals": [{"name": "gauss_bpm", "entry": "gauss_bpm"}],
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
config_device_mode_no_entry = {
|
||||
"plot_settings": {
|
||||
"background_color": "white",
|
||||
"num_columns": 1,
|
||||
"colormap": "plasma",
|
||||
"scan_types": False,
|
||||
},
|
||||
"plot_data": [
|
||||
{
|
||||
"plot_name": "BPM4i plots vs samx",
|
||||
"x": {
|
||||
"label": "Motor Y",
|
||||
"signals": [{"name": "samx"}], # Entry is missing
|
||||
},
|
||||
"y": {
|
||||
"label": "bpm4i",
|
||||
"signals": [{"name": "bpm4i"}], # Entry is missing
|
||||
},
|
||||
},
|
||||
{
|
||||
"plot_name": "Gauss plots vs samx",
|
||||
"x": {
|
||||
"label": "Motor X",
|
||||
"signals": [{"name": "samx"}], # Entry is missing
|
||||
},
|
||||
"y": {
|
||||
"label": "Gauss",
|
||||
"signals": [{"name": "gauss_bpm"}], # Entry is missing
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
config_scan_mode = config = {
|
||||
"plot_settings": {
|
||||
"background_color": "white",
|
||||
"num_columns": 3,
|
||||
"colormap": "plasma",
|
||||
"scan_types": True,
|
||||
},
|
||||
"plot_data": {
|
||||
"grid_scan": [
|
||||
{
|
||||
"plot_name": "Grid plot 1",
|
||||
"x": {"label": "Motor X", "signals": [{"name": "samx", "entry": "samx"}]},
|
||||
"y": {
|
||||
"label": "BPM",
|
||||
"signals": [
|
||||
{"name": "gauss_bpm", "entry": "gauss_bpm"},
|
||||
{"name": "gauss_adc1", "entry": "gauss_adc1"},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
"plot_name": "Grid plot 2",
|
||||
"x": {"label": "Motor X", "signals": [{"name": "samx", "entry": "samx"}]},
|
||||
"y": {
|
||||
"label": "BPM",
|
||||
"signals": [
|
||||
{"name": "gauss_bpm", "entry": "gauss_bpm"},
|
||||
{"name": "gauss_adc1", "entry": "gauss_adc1"},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
"plot_name": "Grid plot 3",
|
||||
"x": {"label": "Motor Y", "signals": [{"name": "samx", "entry": "samx"}]},
|
||||
"y": {
|
||||
"label": "BPM",
|
||||
"signals": [{"name": "gauss_bpm", "entry": "gauss_bpm"}],
|
||||
},
|
||||
},
|
||||
{
|
||||
"plot_name": "Grid plot 4",
|
||||
"x": {"label": "Motor Y", "signals": [{"name": "samx", "entry": "samx"}]},
|
||||
"y": {
|
||||
"label": "BPM",
|
||||
"signals": [{"name": "gauss_adc3", "entry": "gauss_adc3"}],
|
||||
},
|
||||
},
|
||||
],
|
||||
"line_scan": [
|
||||
{
|
||||
"plot_name": "BPM plot",
|
||||
"x": {"label": "Motor X", "signals": [{"name": "samx"}]},
|
||||
"y": {
|
||||
"label": "BPM",
|
||||
"signals": [
|
||||
{"name": "gauss_bpm", "entry": "gauss_bpm"},
|
||||
{"name": "gauss_adc1", "entry": "gauss_adc1"},
|
||||
{"name": "gauss_adc2", "entry": "gauss_adc2"},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
"plot_name": "Multi",
|
||||
"x": {"label": "Motor X", "signals": [{"name": "samx", "entry": "samx"}]},
|
||||
"y": {
|
||||
"label": "Multi",
|
||||
"signals": [
|
||||
{"name": "gauss_bpm", "entry": "gauss_bpm"},
|
||||
{"name": "samx", "entry": ["samx", "samx_setpoint"]},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
"plot_name": "Multi",
|
||||
"x": {"label": "Motor X", "signals": [{"name": "samx", "entry": "samx"}]},
|
||||
"y": {
|
||||
"label": "Multi",
|
||||
"signals": [
|
||||
{"name": "gauss_bpm", "entry": "gauss_bpm"},
|
||||
{"name": "samx", "entry": ["samx", "samx_setpoint"]},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
config_all_wrong = {
|
||||
"plot_settings": {
|
||||
"background_color": "white",
|
||||
"num_columns": 1,
|
||||
"colormap": "plasma",
|
||||
"scan_types": False,
|
||||
},
|
||||
"plot_data": [
|
||||
{
|
||||
"plot_name": "BPM4i plots vs samx",
|
||||
"x": {
|
||||
"label": "Motor Y",
|
||||
# signals are missing
|
||||
},
|
||||
"y": {
|
||||
"label": "bpm4i",
|
||||
"signals": [{"name": "bpm4i", "entry": "gauss_bpm"}], # wrong entry
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config, plot_setting_bg, num_plot ,pg_background",
|
||||
[
|
||||
(config_device_mode_all_filled, "black", 2, "k"),
|
||||
(config_device_mode_no_entry, "white", 2, "w"),
|
||||
(config_scan_mode, "white", 4, "w"),
|
||||
],
|
||||
)
|
||||
def test_init_config(qtbot, config, plot_setting_bg, num_plot, pg_background):
|
||||
plot_app = setup_plot_app(qtbot, config)
|
||||
assert plot_app.plot_settings["background_color"] == plot_setting_bg
|
||||
assert len(plot_app.plot_data) == num_plot
|
||||
assert pg.getConfigOption("background") == pg_background
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config, num_columns_input, expected_num_columns, expected_plot_names, expected_coordinates",
|
||||
[
|
||||
(
|
||||
config_device_mode_all_filled,
|
||||
2,
|
||||
2,
|
||||
["BPM4i plots vs samx", "Gauss plots vs samx"],
|
||||
[(0, 0), (0, 1)],
|
||||
),
|
||||
(
|
||||
config_device_mode_all_filled,
|
||||
5,
|
||||
2,
|
||||
["BPM4i plots vs samx", "Gauss plots vs samx"],
|
||||
[(0, 0), (0, 1)],
|
||||
), # num_columns greater than number of plots
|
||||
(
|
||||
config_device_mode_no_entry,
|
||||
1,
|
||||
1,
|
||||
["BPM4i plots vs samx", "Gauss plots vs samx"],
|
||||
[(0, 0), (1, 0)],
|
||||
),
|
||||
(
|
||||
config_device_mode_no_entry,
|
||||
2,
|
||||
2,
|
||||
["BPM4i plots vs samx", "Gauss plots vs samx"],
|
||||
[(0, 0), (0, 1)],
|
||||
),
|
||||
(
|
||||
config_device_mode_no_entry,
|
||||
5,
|
||||
2,
|
||||
["BPM4i plots vs samx", "Gauss plots vs samx"],
|
||||
[(0, 0), (0, 1)],
|
||||
), # num_columns greater than number of plots,
|
||||
(
|
||||
config_scan_mode,
|
||||
2,
|
||||
2,
|
||||
[
|
||||
"Grid plot 1",
|
||||
"Grid plot 2",
|
||||
"Grid plot 3",
|
||||
"Grid plot 4",
|
||||
],
|
||||
[(0, 0), (0, 1), (1, 0), (1, 1)],
|
||||
),
|
||||
(
|
||||
config_scan_mode,
|
||||
3,
|
||||
3,
|
||||
[
|
||||
"Grid plot 1",
|
||||
"Grid plot 2",
|
||||
"Grid plot 3",
|
||||
"Grid plot 4",
|
||||
],
|
||||
[(0, 0), (0, 1), (0, 2), (1, 0)],
|
||||
),
|
||||
(
|
||||
config_scan_mode,
|
||||
5,
|
||||
4,
|
||||
[
|
||||
"Grid plot 1",
|
||||
"Grid plot 2",
|
||||
"Grid plot 3",
|
||||
"Grid plot 4",
|
||||
],
|
||||
[(0, 0), (0, 1), (0, 2), (0, 3)],
|
||||
), # num_columns greater than number of plots
|
||||
],
|
||||
)
|
||||
def test_init_ui(
|
||||
qtbot,
|
||||
config,
|
||||
num_columns_input,
|
||||
expected_num_columns,
|
||||
expected_plot_names,
|
||||
expected_coordinates,
|
||||
):
|
||||
plot_app = setup_plot_app(qtbot, config)
|
||||
plot_app.init_ui(num_columns_input)
|
||||
|
||||
# Validate number of columns
|
||||
assert plot_app.plot_settings["num_columns"] == expected_num_columns
|
||||
|
||||
# Validate the plots are created correctly
|
||||
for expected_name in expected_plot_names:
|
||||
assert expected_name in plot_app.plots.keys()
|
||||
|
||||
# Validate the grid_coordinates
|
||||
assert plot_app.grid_coordinates == expected_coordinates
|
||||
|
||||
|
||||
def mock_getitem(dev_name):
|
||||
"""Helper function to mock the __getitem__ method of the 'dev' object.""" ""
|
||||
mock_instance = MagicMock()
|
||||
if dev_name == "samx":
|
||||
mock_instance._hints = "samx"
|
||||
elif dev_name == "bpm4i":
|
||||
mock_instance._hints = "bpm4i"
|
||||
elif dev_name == "gauss_bpm":
|
||||
mock_instance._hints = "gauss_bpm"
|
||||
|
||||
return mock_instance
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config, msg, metadata, expected_data",
|
||||
[
|
||||
# Case: msg does not have 'scanID'
|
||||
(config_device_mode_all_filled, {"data": {}}, {}, {}),
|
||||
# Case: scan_types is False, msg contains all valid fields, and entry is present in config
|
||||
(
|
||||
config_device_mode_all_filled,
|
||||
{
|
||||
"data": {
|
||||
"samx": {"samx": {"value": 10}},
|
||||
"bpm4i": {"bpm4i": {"value": 5}},
|
||||
"gauss_bpm": {"gauss_bpm": {"value": 7}},
|
||||
},
|
||||
"scanID": 1,
|
||||
},
|
||||
{},
|
||||
{
|
||||
("samx", "samx", "bpm4i", "bpm4i"): {"x": [10], "y": [5]},
|
||||
("samx", "samx", "gauss_bpm", "gauss_bpm"): {"x": [10], "y": [7]},
|
||||
},
|
||||
),
|
||||
# Case: scan_types is False, msg contains all valid fields and entry is missing in config, should use hints
|
||||
(
|
||||
config_device_mode_no_entry,
|
||||
{
|
||||
"data": {
|
||||
"samx": {"samx": {"value": 10}},
|
||||
"bpm4i": {"bpm4i": {"value": 5}},
|
||||
"gauss_bpm": {"gauss_bpm": {"value": 7}},
|
||||
},
|
||||
"scanID": 1,
|
||||
},
|
||||
{},
|
||||
{
|
||||
("samx", "samx", "bpm4i", "bpm4i"): {"x": [10], "y": [5]},
|
||||
("samx", "samx", "gauss_bpm", "gauss_bpm"): {"x": [10], "y": [7]},
|
||||
},
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_on_scan_segment(qtbot, config, msg, metadata, expected_data):
|
||||
plot_app = setup_plot_app(qtbot, config)
|
||||
|
||||
# Initialize and run test
|
||||
plot_app.data = {}
|
||||
plot_app.scanID = 0
|
||||
|
||||
# Get hints
|
||||
plot_app.dev.__getitem__.side_effect = mock_getitem
|
||||
|
||||
plot_app.on_scan_segment(msg, metadata)
|
||||
assert plot_app.data == expected_data
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config, msg, metadata, expected_exception_message",
|
||||
[
|
||||
# Case: scan_types is True, but metadata does not contain 'scan_name'
|
||||
(
|
||||
config_scan_mode,
|
||||
{"data": {}, "scanID": 1},
|
||||
{}, # No 'scan_name' in metadata
|
||||
"Scan name not found in metadata. Please check the scan_name in the YAML config or in bec configuration.",
|
||||
),
|
||||
# Case: scan_types is True, metadata contains non-existing 'scan_name'
|
||||
(
|
||||
config_scan_mode,
|
||||
{"data": {}, "scanID": 1},
|
||||
{"scan_name": "non_existing_scan"},
|
||||
"Scan name non_existing_scan not found in the YAML config. Please check the scan_name in the YAML config "
|
||||
"or in bec configuration.",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_on_scan_message_error_handling(qtbot, config, msg, metadata, expected_exception_message):
|
||||
plot_app = setup_plot_app(qtbot, config)
|
||||
|
||||
# Initialize
|
||||
plot_app.init_curves = MagicMock()
|
||||
plot_app.data = {}
|
||||
plot_app.scanID = 0
|
||||
|
||||
plot_app.dev.__getitem__.side_effect = mock_getitem
|
||||
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
plot_app.on_scan_segment(msg, metadata)
|
||||
assert str(exc_info.value) == expected_exception_message
|
||||
|
||||
|
||||
####################
|
||||
# ErrorHandler tests
|
||||
####################
|
||||
def test_initialization(error_handler):
|
||||
assert error_handler.errors == []
|
||||
assert error_handler.parent is None
|
||||
assert error_handler.retry_action is None
|
||||
|
||||
|
||||
@patch(
|
||||
"bec_widgets.examples.plot_app.plot_app.QMessageBox.critical", return_value=QMessageBox.Retry
|
||||
)
|
||||
def test_handle_error_retry(mocked_critical, error_handler):
|
||||
retry_action = MagicMock()
|
||||
error_handler.set_retry_action(retry_action)
|
||||
error_handler.handle_error("error message")
|
||||
retry_action.assert_called_once()
|
||||
|
||||
|
||||
@patch(
|
||||
"bec_widgets.examples.plot_app.plot_app.QMessageBox.critical", return_value=QMessageBox.Cancel
|
||||
)
|
||||
def test_handle_error_cancel(mocked_critical, error_handler):
|
||||
retry_action = MagicMock()
|
||||
with pytest.raises(SystemExit) as excinfo:
|
||||
error_handler.handle_error("error message")
|
||||
assert excinfo.value.code == 1
|
||||
retry_action.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config, expected_errors",
|
||||
[
|
||||
(config_device_mode_all_filled, []),
|
||||
(config_device_mode_no_entry, []),
|
||||
(config_scan_mode, []),
|
||||
(
|
||||
config_all_wrong,
|
||||
["Missing 'signals' configuration for x axis in plot 0 - 'BPM4i plots vs samx'"],
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_error_handler(error_handler, config, expected_errors):
|
||||
# Mock QMessageBox
|
||||
error_handler.handle_error = MagicMock()
|
||||
|
||||
# Mock logging
|
||||
with unittest.mock.patch("bec_widgets.examples.plot_app.plot_app.logging") as mocked_logging:
|
||||
error_handler.validate_config_file(config)
|
||||
|
||||
# Assert
|
||||
assert error_handler.errors == expected_errors
|
||||
|
||||
# If there are expected errors, check if handle_error was called
|
||||
if expected_errors:
|
||||
error_handler.handle_error.assert_called_once()
|
||||
mocked_logging.error.assert_called()
|
||||
else:
|
||||
mocked_logging.error.assert_not_called()
|
||||
error_handler.handle_error.assert_not_called()
|
||||
|
||||
|
||||
def test_validate_plot_config(error_handler):
|
||||
plot_config = {
|
||||
"x": {"label": "Motor X", "signals": []}, # empty signals list should trigger an error
|
||||
"y": {"label": "Motor Y", "signals": [{"name": "samx", "entry": "samx"}]},
|
||||
}
|
||||
error_handler.validate_plot_config(plot_config, 0)
|
||||
assert error_handler.errors == [
|
||||
"'signals' configuration for x axis in plot 0 must be a non-empty list"
|
||||
]
|
||||
@@ -23,18 +23,18 @@ def test_plot_base_axes_by_separate_methods(bec_figure):
|
||||
plot_base.set_x_scale("log")
|
||||
plot_base.set_y_scale("log")
|
||||
|
||||
assert plot_base.plot_item.titleLabel.text == "Test Title"
|
||||
assert plot_base.titleLabel.text == "Test Title"
|
||||
assert plot_base.config.axis.title == "Test Title"
|
||||
assert plot_base.plot_item.getAxis("bottom").labelText == "Test x Label"
|
||||
assert plot_base.getAxis("bottom").labelText == "Test x Label"
|
||||
assert plot_base.config.axis.x_label == "Test x Label"
|
||||
assert plot_base.plot_item.getAxis("left").labelText == "Test y Label"
|
||||
assert plot_base.getAxis("left").labelText == "Test y Label"
|
||||
assert plot_base.config.axis.y_label == "Test y Label"
|
||||
assert plot_base.config.axis.x_lim == (1, 100)
|
||||
assert plot_base.config.axis.y_lim == (5, 500)
|
||||
assert plot_base.plot_item.ctrl.xGridCheck.isChecked() == True
|
||||
assert plot_base.plot_item.ctrl.yGridCheck.isChecked() == True
|
||||
assert plot_base.plot_item.ctrl.logXCheck.isChecked() == True
|
||||
assert plot_base.plot_item.ctrl.logYCheck.isChecked() == True
|
||||
assert plot_base.ctrl.xGridCheck.isChecked() == True
|
||||
assert plot_base.ctrl.yGridCheck.isChecked() == True
|
||||
assert plot_base.ctrl.logXCheck.isChecked() == True
|
||||
assert plot_base.ctrl.logYCheck.isChecked() == True
|
||||
|
||||
|
||||
def test_plot_base_axes_added_by_kwargs(bec_figure):
|
||||
@@ -50,13 +50,13 @@ def test_plot_base_axes_added_by_kwargs(bec_figure):
|
||||
y_scale="log",
|
||||
)
|
||||
|
||||
assert plot_base.plot_item.titleLabel.text == "Test Title"
|
||||
assert plot_base.titleLabel.text == "Test Title"
|
||||
assert plot_base.config.axis.title == "Test Title"
|
||||
assert plot_base.plot_item.getAxis("bottom").labelText == "Test x Label"
|
||||
assert plot_base.getAxis("bottom").labelText == "Test x Label"
|
||||
assert plot_base.config.axis.x_label == "Test x Label"
|
||||
assert plot_base.plot_item.getAxis("left").labelText == "Test y Label"
|
||||
assert plot_base.getAxis("left").labelText == "Test y Label"
|
||||
assert plot_base.config.axis.y_label == "Test y Label"
|
||||
assert plot_base.config.axis.x_lim == (1, 100)
|
||||
assert plot_base.config.axis.y_lim == (5, 500)
|
||||
assert plot_base.plot_item.ctrl.logXCheck.isChecked() == True
|
||||
assert plot_base.plot_item.ctrl.logYCheck.isChecked() == True
|
||||
assert plot_base.ctrl.logXCheck.isChecked() == True
|
||||
assert plot_base.ctrl.logYCheck.isChecked() == True
|
||||
|
||||
26
tests/test_problem.py
Normal file
26
tests/test_problem.py
Normal file
@@ -0,0 +1,26 @@
|
||||
import pytest
|
||||
|
||||
from bec_widgets.cli.client import BECFigure
|
||||
from bec_widgets.cli.server import BECWidgetsCLIServer
|
||||
from bec_widgets.utils.bec_dispatcher import _BECDispatcher
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def rpc_server(qtbot):
|
||||
# make a new dispatcher (not using the singleton), since the server is supposed to run in another process
|
||||
dispatcher = _BECDispatcher()
|
||||
server = BECWidgetsCLIServer(gui_id="id_test", dispatcher=dispatcher)
|
||||
qtbot.addWidget(server.fig)
|
||||
qtbot.waitExposed(server.fig)
|
||||
qtbot.wait(200)
|
||||
yield server
|
||||
server.client.shutdown()
|
||||
|
||||
|
||||
def test_rpc_waveform1d(rpc_server, qtbot):
|
||||
fig = BECFigure(rpc_server.gui_id)
|
||||
ax = fig.add_plot()
|
||||
curve = ax.add_curve_custom([1, 2, 3], [1, 2, 3])
|
||||
curve.set_color("red")
|
||||
curve = ax.curves[0]
|
||||
curve.set_color("blue")
|
||||
92
tests/test_scan_plot.py
Normal file
92
tests/test_scan_plot.py
Normal file
@@ -0,0 +1,92 @@
|
||||
# pylint: disable = no-name-in-module,missing-class-docstring, missing-module-docstring
|
||||
from bec_widgets.widgets.scan_plot import scan_plot
|
||||
|
||||
|
||||
def test_scan_plot(qtbot):
|
||||
"""Test ScanPlot"""
|
||||
plot = scan_plot.BECScanPlot()
|
||||
qtbot.addWidget(plot)
|
||||
plot.show()
|
||||
qtbot.waitExposed(plot)
|
||||
|
||||
plot.x_channel = "x"
|
||||
plot.y_channel_list = ["y1", "y2"]
|
||||
|
||||
plot.on_scan_segment(
|
||||
{
|
||||
"data": {
|
||||
"x": {"x": {"value": 1}},
|
||||
"y1": {"y1": {"value": 1}},
|
||||
"y2": {"y2": {"value": 3}},
|
||||
},
|
||||
"scanID": "test",
|
||||
},
|
||||
{"scanID": "test", "scan_number": 1, "scan_report_devices": ["x"]},
|
||||
)
|
||||
plot.on_scan_segment(
|
||||
{
|
||||
"data": {
|
||||
"x": {"x": {"value": 2}},
|
||||
"y1": {"y1": {"value": 2}},
|
||||
"y2": {"y2": {"value": 4}},
|
||||
},
|
||||
"scanID": "test",
|
||||
},
|
||||
{"scanID": "test", "scan_number": 1, "scan_report_devices": ["x"]},
|
||||
)
|
||||
|
||||
assert all(plot.scan_curves["y1"].getData()[0] == [1, 2])
|
||||
assert all(plot.scan_curves["y2"].getData()[1] == [3, 4])
|
||||
|
||||
|
||||
def test_scan_plot_clears_data(qtbot):
|
||||
"""Test ScanPlot"""
|
||||
plot = scan_plot.BECScanPlot()
|
||||
qtbot.addWidget(plot)
|
||||
plot.show()
|
||||
qtbot.waitExposed(plot)
|
||||
|
||||
plot.x_channel = "x"
|
||||
plot.y_channel_list = ["y1", "y2"]
|
||||
|
||||
plot.on_scan_segment(
|
||||
{
|
||||
"data": {
|
||||
"x": {"x": {"value": 1}},
|
||||
"y1": {"y1": {"value": 1}},
|
||||
"y2": {"y2": {"value": 3}},
|
||||
},
|
||||
"scanID": "test",
|
||||
},
|
||||
{"scanID": "test", "scan_number": 1, "scan_report_devices": ["x"]},
|
||||
)
|
||||
plot.reset_plots({}, {})
|
||||
plot.on_scan_segment(
|
||||
{
|
||||
"data": {
|
||||
"x": {"x": {"value": 2}},
|
||||
"y1": {"y1": {"value": 2}},
|
||||
"y2": {"y2": {"value": 4}},
|
||||
},
|
||||
"scanID": "test",
|
||||
},
|
||||
{"scanID": "test", "scan_number": 1, "scan_report_devices": ["x"]},
|
||||
)
|
||||
|
||||
assert all(plot.scan_curves["y1"].getData()[0] == [2])
|
||||
assert all(plot.scan_curves["y2"].getData()[1] == [4])
|
||||
|
||||
|
||||
def test_scan_plot_redraws_dap(qtbot):
|
||||
"""Test ScanPlot"""
|
||||
plot = scan_plot.BECScanPlot()
|
||||
qtbot.addWidget(plot)
|
||||
plot.show()
|
||||
qtbot.waitExposed(plot)
|
||||
|
||||
plot.y_channel_list = ["dap.y1", "dap.y2"]
|
||||
|
||||
plot.redraw_dap({"data": {"y1": {"x": [1], "y": [1]}, "y2": {"x": [2], "y": [2]}}}, {})
|
||||
|
||||
assert all(plot.dap_curves["y1"].getData()[0] == [1])
|
||||
assert all(plot.dap_curves["y2"].getData()[1] == [2])
|
||||
@@ -106,7 +106,7 @@ def test_create_waveform1D_by_config(bec_figure):
|
||||
w1_config_output = w1.get_config()
|
||||
|
||||
assert w1_config_input == w1_config_output
|
||||
assert w1.plot_item.titleLabel.text == "Widget 1"
|
||||
assert w1.titleLabel.text == "Widget 1"
|
||||
assert w1.config.axis.title == "Widget 1"
|
||||
|
||||
|
||||
@@ -185,7 +185,7 @@ def test_remove_curve(bec_figure):
|
||||
w1.remove_curve(0)
|
||||
w1.remove_curve("bpm3a-bpm3a")
|
||||
|
||||
assert len(w1.plot_item.curves) == 0
|
||||
assert len(w1.curves) == 0
|
||||
assert w1.curves_data["scan_segment"] == {}
|
||||
|
||||
with pytest.raises(ValueError) as excinfo:
|
||||
|
||||
Reference in New Issue
Block a user