DataLab Client (sigima.client)#
The sigima.client module provides a proxy to DataLab application through XML-RPC protocol.
DataLab may be controlled remotely using the XML-RPC protocol which is natively supported by Python (and many other languages). Remote controlling allows to access DataLab main features from a separate process.
From an IDE#
DataLab may be controlled remotely from an IDE (e.g. Spyder or any other IDE, or even a Jupyter Notebook) that runs a Python script. It allows to connect to a running DataLab instance, adds a signal and an image, and then runs calculations. This feature is exposed by the sigima.client.SimpleRemoteProxy class.
From a third-party application#
DataLab may also be controlled remotely from a third-party application, for the same purpose.
If the third-party application is written in Python 3, it may directly use
cdlclient.SimpleRemoteProxy as mentioned above. From another language,
it is also achievable, but it requires to implement a XML-RPC client in this
language using the same methods of proxy server as in the
cdlclient.SimpleRemoteProxy class.
Data (signals and images) may also be exchanged between DataLab and the remote client application, in both directions.
The remote client application may be run on the same computer as DataLab or on different computer. In the latter case, the remote client application must know the IP address of the computer running DataLab.
The remote client application may be run before or after DataLab. In the latter case, the remote client application must try to connect to DataLab until it succeeds.
Supported features#
- Supported features are the following:
Switch to signal or image panel
Remove all signals and images
Save current session to a HDF5 file
Open HDF5 files into current session
Browse HDF5 file
Open a signal or an image from file
Add a signal
Add an image
Get object list
Run calculation with parameters
Example
Here is an example in Python 3 of a script that connects to a running DataLab instance, adds a signal and an image, and then runs calculations (the cell structure of the script make it convenient to be used in Spyder IDE):
"""
DataLab remote control example
==============================
Example of remote control of DataLab current session,
from a Python script running outside DataLab (e.g. in Spyder)
This example demonstrates how to control DataLab remotely using the
SimpleRemoteProxy from Sigima. The script can be run from any Python
environment outside of DataLab to interact with an active DataLab session.
.. note::
This example is not executed during documentation build as it requires
an active DataLab session to connect to. It is included in the gallery
for reference and can be run manually when DataLab is running.
"""
# %% Importing necessary modules
# NumPy for numerical array computations:
import numpy as np
# DataLab remote control client:
from sigima.client import SimpleRemoteProxy as RemoteProxy
# %% Connecting to DataLab current session
proxy = RemoteProxy(autoconnect=False)
proxy.connect(timeout=0.0, retries=1) # No timeout for rapid failure if not running
# %% Executing commands in DataLab (...)
z = np.random.rand(20, 20)
proxy.add_image("toto", z)
# %% Executing commands in DataLab (...)
proxy.toggle_auto_refresh(False) # Turning off auto-refresh
x = np.array([1.0, 2.0, 3.0])
y = np.array([4.0, 5.0, -1.0])
proxy.add_signal("toto", x, y)
# %% Executing commands in DataLab (...)
proxy.calc("derivative")
proxy.toggle_auto_refresh(True) # Turning on auto-refresh
# %% Executing commands in DataLab (...)
proxy.set_current_panel("image")
# %% Executing a lot of commands without refreshing DataLab
z = np.random.rand(400, 400)
proxy.add_image("foobar", z)
with proxy.context_no_refresh():
for _idx in range(100):
proxy.calc("fft")
Additional features#
For simple remote controlling, sigima.client.SimpleRemoteProxy may be
used. For more advanced remote controlling, the datalab.control.proxy.RemoteProxy
class provided by the DataLab package may be used.
See DataLab documentation for more details about the
datalab.control.proxy.RemoteProxy class (on the section “Remote control”).
API#
Remote client#
- class sigima.client.remote.SimpleRemoteProxy(autoconnect: bool = True)[source]#
Object representing a proxy/client to DataLab XML-RPC server. This object is used to call DataLab functions from a Python script.
This is a subset of DataLab’s RemoteClient class, with only the methods that do not require DataLab object model to be implemented.
- Parameters:
autoconnect – If True, automatically connect to DataLab XML-RPC server. Defaults to True.
- Raises:
ConnectionRefusedError – DataLab is currently not running
Examples
Here is a simple example of how to use SimpleRemoteProxy in a Python script or in a Jupyter notebook:
>>> from sigima.client import SimpleRemoteProxy >>> proxy = SimpleRemoteProxy() # autoconnect is on by default Connecting to DataLab XML-RPC server...OK (port: 28867) >>> proxy.get_version() '1.0.0' >>> proxy.add_signal("toto", np.array([1., 2., 3.]), np.array([4., 5., -1.])) True >>> proxy.get_object_titles() ['toto'] >>> proxy["toto"] <sigima.objects.signal.SignalObj at 0x7f7f1c0b4a90> >>> "toto" in proxy True >>> proxy[1] <sigima.objects.signal.SignalObj at 0x7f7f1c0b4a90> >>> proxy[1].data array([1., 2., 3.])
- connect(port: str | None = None, timeout: float | None = None, retries: int | None = None) None[source]#
Try to connect to DataLab XML-RPC server.
- Parameters:
port (str | None) – XML-RPC port to connect to. If not specified, the port is automatically retrieved from DataLab configuration.
timeout (float | None) – Maximum time to wait for connection in seconds. Defaults to 5.0. This is the total maximum wait time, not per retry.
retries (int | None) – Number of retries. Defaults to 10. This parameter is deprecated and will be removed in a future version (kept for backward compatibility).
- Raises:
ConnectionRefusedError – Unable to connect to DataLab
ValueError – Invalid timeout (must be >= 0.0)
ValueError – Invalid number of retries (must be >= 1)
- add_signal(title: str, xdata: ndarray, ydata: ndarray, xunit: str | None = None, yunit: str | None = None, xlabel: str | None = None, ylabel: str | None = None) bool[source]#
Add signal data to DataLab.
- Parameters:
title (str) – Signal title
xdata (numpy.ndarray) – X data
ydata (numpy.ndarray) – Y data
xunit (str | None) – X unit. Defaults to None.
yunit (str | None) – Y unit. Defaults to None.
xlabel (str | None) – X label. Defaults to None.
ylabel (str | None) – Y label. Defaults to None.
- Returns:
True if signal was added successfully, False otherwise
- Return type:
- Raises:
ValueError – Invalid xdata dtype
ValueError – Invalid ydata dtype
- add_image(title: str, data: ndarray, xunit: str | None = None, yunit: str | None = None, zunit: str | None = None, xlabel: str | None = None, ylabel: str | None = None, zlabel: str | None = None) bool[source]#
Add image data to DataLab.
- Parameters:
title (str) – Image title
data (numpy.ndarray) – Image data
xunit (str | None) – X unit. Defaults to None.
yunit (str | None) – Y unit. Defaults to None.
zunit (str | None) – Z unit. Defaults to None.
xlabel (str | None) – X label. Defaults to None.
ylabel (str | None) – Y label. Defaults to None.
zlabel (str | None) – Z label. Defaults to None.
- Returns:
True if image was added successfully, False otherwise
- Return type:
- Raises:
ValueError – Invalid data dtype
- add_object(obj: SignalObj | ImageObj, group_id: str = '', set_current: bool = True) None[source]#
Add object to DataLab.
- Parameters:
obj – Signal or image object
group_id – group id in which to add the object. Defaults to “”
set_current – if True, set the added object as current
- set_object(obj: SignalObj | ImageObj) None[source]#
Update an existing object in DataLab.
The object is identified by its UUID (carried in metadata from a previous
get_object()call).- Parameters:
obj – Signal or image object with the same UUID as an existing object
- load_from_directory(path: str) None[source]#
Open objects from directory in current panel (signals/images).
- Parameters:
path – directory path
- calc(name: str, param: DataSet | None = None) None[source]#
Call compute function
namein current panel’s processor.- Parameters:
name – Compute function name
param – Compute function parameter. Defaults to None.
- Raises:
ValueError – unknown function
- get_object(nb_id_title: int | str | None = None, panel: str | None = None) SignalObj | ImageObj[source]#
Get object (signal/image) from index.
- Parameters:
nb_id_title – Object number, or object id, or object title. Defaults to None (current object).
panel – Panel name. Defaults to None (current panel).
- Returns:
Object
- Raises:
KeyError – if object not found
- get_object_shapes(nb_id_title: int | str | None = None, panel: str | None = None) list[source]#
Get plot item shapes associated to object (signal/image).
- Parameters:
nb_id_title – Object number, or object id, or object title. Defaults to None (current object).
panel – Panel name. Defaults to None (current panel).
- Returns:
List of plot item shapes
Base proxy#
- class sigima.client.base.SimpleBaseProxy(datalab: ServerProxy | None = None)[source]#
Simple common base class for DataLab proxies
This is a subset of DataLab’s BaseProxy, with only the methods that do not require DataLab object model to be implemented.
- Parameters:
datalab (DLMainWindow | ServerProxy | None) – DLMainWindow instance or ServerProxy instance. If None, then the proxy implementation will have to set it later (e.g. see SimpleRemoteProxy).
- get_current_panel() str[source]#
Return current panel name.
- Returns:
Panel name (valid values: “signal”, “image”, “macro”))
- Return type:
- set_current_panel(panel: str) None[source]#
Switch to panel.
- Parameters:
panel (str) – Panel name (valid values: “signal”, “image”, “macro”))
- toggle_auto_refresh(state: bool) None[source]#
Toggle auto refresh state.
- Parameters:
state (bool) – Auto refresh state
- context_no_refresh() Callable[source]#
Return a context manager to temporarily disable auto refresh.
- Returns:
Context manager
Example
>>> with proxy.context_no_refresh(): ... proxy.add_image("image1", data1) ... proxy.compute_fft() ... proxy.compute_wiener() ... proxy.compute_ifft() ... # Auto refresh is disabled during the above operations
- toggle_show_titles(state: bool) None[source]#
Toggle show titles state.
- Parameters:
state (bool) – Show titles state
- save_to_h5_file(filename: str) None[source]#
Save to a DataLab HDF5 file.
- Parameters:
filename (str) – HDF5 file name
- open_h5_files(h5files: list[str] | None = None, import_all: bool | None = None, reset_all: bool | None = None) None[source]#
Open a DataLab HDF5 file or import from any other HDF5 file.
- import_h5_file(filename: str, reset_all: bool | None = None) None[source]#
Open DataLab HDF5 browser to Import HDF5 file.
- load_h5_workspace(h5files: list[str] | str, reset_all: bool = True) None[source]#
Load HDF5 workspace files without showing file dialog.
This method loads one or more DataLab native HDF5 files directly, bypassing the file dialog. It is safe to call from the internal console or any context where Qt dialogs would cause threading issues.
- Parameters:
h5files – Path(s) to HDF5 file(s). Can be a single path string or a list of paths.
reset_all – If True (default), reset workspace before loading. If False, append to existing workspace.
- Raises:
ValueError – if file is not a DataLab native HDF5 file
- save_h5_workspace(filename: str) None[source]#
Save workspace to HDF5 file without showing file dialog.
This method saves the current workspace to a DataLab native HDF5 file directly, bypassing the file dialog. It is safe to call from the internal console or any context where Qt dialogs would cause threading issues.
- Parameters:
filename – Path to the output HDF5 file
- load_from_files(filenames: list[str]) None[source]#
Open objects from files in current panel (signals/images).
- Parameters:
filenames – list of file names
- add_group(title: str, panel: str | None = None, select: bool = False) None[source]#
Add group to DataLab.
- Parameters:
title – Group title
panel – Panel name (valid values: “signal”, “image”). Defaults to None.
select – Select the group after creation. Defaults to False.
- get_sel_object_uuids(include_groups: bool = False) list[str][source]#
Return selected objects uuids.
- Parameters:
include_groups – If True, also return objects from selected groups.
- Returns:
List of selected objects uuids.
- get_current_object_uuid() str | None[source]#
Return current object uuid in current panel.
- Returns:
UUID of the current object, or None if no object is current.
- select_objects(selection: list[int | str], panel: str | None = None) None[source]#
Select objects in current panel.
- Parameters:
selection – List of object numbers (1 to N) or uuids to select
panel – panel name (valid values: “signal”, “image”). If None, current panel is used. Defaults to None.
- select_groups(selection: list[int | str] | None = None, panel: str | None = None) None[source]#
Select groups in current panel.
- Parameters:
selection – List of group numbers (1 to N), or list of group uuids, or None to select all groups. Defaults to None.
panel (str | None) – panel name (valid values: “signal”, “image”). If None, current panel is used. Defaults to None.
- delete_metadata(refresh_plot: bool = True, keep_roi: bool = False) None[source]#
Delete metadata of selected objects
- Parameters:
refresh_plot – Refresh plot. Defaults to True.
keep_roi – Keep ROI. Defaults to False.
- get_group_titles_with_object_info() tuple[list[str], list[list[str]], list[list[str]]][source]#
Return groups titles and lists of inner objects uuids and titles.
- Returns:
groups titles, lists of inner objects uuids and titles
- Return type:
Tuple
- get_object_titles(panel: str | None = None) list[str][source]#
Get object (signal/image) list for current panel. Objects are sorted by group number and object index in group.
- Parameters:
panel – panel name (valid values: “signal”, “image”, “macro”). If None, current data panel is used (i.e. signal or image panel).
- Returns:
List of object titles
- Raises:
ValueError – if panel not found
- get_object_uuids(panel: str | None = None, group: int | str | None = None) list[str][source]#
Get object (signal/image) uuid list for current panel. Objects are sorted by group number and object index in group.
- Parameters:
panel – panel name (valid values: “signal”, “image”). If None, current panel is used.
group – Group number, or group id, or group title. Defaults to None (all groups).
- Returns:
List of object uuids
- Raises:
ValueError – if panel not found
- add_label_with_title(title: str | None = None, panel: str | None = None) None[source]#
Add a label with object title on the associated plot
- run_macro(number_or_title: int | str | None = None) None[source]#
Run macro.
- Parameters:
number – Number of the macro (starting at 1). Defaults to None (run current macro, or does nothing if there is no macro).