Skip to content

apps.open_ephys

OpenEphysAppSettings

Bases: ServiceSettings

Settings for Open Ephys App.

settings_customise_sources classmethod

settings_customise_sources(
    settings_cls: type[BaseSettings],
    init_settings: PydanticBaseSettingsSource,
    env_settings: PydanticBaseSettingsSource,
    dotenv_settings: PydanticBaseSettingsSource,
    file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]

Customizes the settings sources to include the safe YAML settings source.

Parameters:

Name Type Description Default
settings_cls type[BaseSettings]

The settings class

required
init_settings PydanticBaseSettingsSource

The initial settings source

required
env_settings PydanticBaseSettingsSource

The environment settings source

required
dotenv_settings PydanticBaseSettingsSource

The dotenv settings source

required
file_secret_settings PydanticBaseSettingsSource

The file secret settings source

required

Returns:

Type Description
tuple[PydanticBaseSettingsSource, ...]

Tuple[PydanticBaseSettingsSource, ...]: A tuple of settings sources

Source code in src/clabe/services.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
@classmethod
def settings_customise_sources(
    cls,
    settings_cls: type[ps.BaseSettings],
    init_settings: ps.PydanticBaseSettingsSource,
    env_settings: ps.PydanticBaseSettingsSource,
    dotenv_settings: ps.PydanticBaseSettingsSource,
    file_secret_settings: ps.PydanticBaseSettingsSource,
) -> tuple[ps.PydanticBaseSettingsSource, ...]:
    """
    Customizes the settings sources to include the safe YAML settings source.

    Args:
        settings_cls: The settings class
        init_settings: The initial settings source
        env_settings: The environment settings source
        dotenv_settings: The dotenv settings source
        file_secret_settings: The file secret settings source

    Returns:
        Tuple[PydanticBaseSettingsSource, ...]: A tuple of settings sources
    """
    yaml_sources = [
        _SafeYamlSettingsSource(settings_cls, yaml_file=p, yaml_config_section=cls.__yml_section__)
        for p in KNOWN_CONFIG_FILES
    ]
    # The in-memory document ranks right after the first (local override) config file
    return (
        init_settings,
        *yaml_sources[:1],
        _InMemorySettingsSource(settings_cls, config_section=cls.__yml_section__),
        *yaml_sources[1:],
        env_settings,
        dotenv_settings,
        file_secret_settings,
    )

OpenEphysApp

OpenEphysApp(
    settings: OpenEphysAppSettings,
    skip_validation: bool = False,
)

Bases: ExecutableApp, _DefaultExecutorMixin

A class to manage the execution of Open Ephys GUI.

Handles Open Ephys GUI execution, configuration management, and process monitoring for ephys experiments.

Methods:

Name Description
run

Executes the Open Ephys GUI

launch

Starts the GUI in the background and waits until its API responds

start

Starts recording

stop

Stops recording

close

Quits the GUI and waits for it to exit

get_result

Retrieves the result of the Open Ephys execution

add_app_settings

Adds or updates application settings

validate

Validates the Open Ephys application configuration

Initializes the OpenEphysApp instance.

Parameters:

Name Type Description Default
settings OpenEphysAppSettings

Settings for the Open Ephys App

required
skip_validation bool

Whether to skip validation of required files

False
Example
# Create and run a Open Ephys app
app = OpenEphysApp(settings=OpenEphysAppSettings(signal_chain="signal_chain.xml"))
app.run()
Source code in src/clabe/apps/open_ephys.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def __init__(
    self,
    settings: OpenEphysAppSettings,
    skip_validation: bool = False,
) -> None:
    """
    Initializes the OpenEphysApp instance.

    Args:
        settings: Settings for the Open Ephys App
        skip_validation: Whether to skip validation of required files

    Example:
        ```python
        # Create and run a Open Ephys app
        app = OpenEphysApp(settings=OpenEphysAppSettings(signal_chain="signal_chain.xml"))
        app.run()
        ```
    """
    self.settings = settings
    self.signal_chain = Path(self.settings.signal_chain).resolve()
    self.executable = Path(self.settings.executable).resolve()
    self._client = _OpenEphysGuiClient(host=self.settings.address, port=self.settings.port)
    self._gui: asyncio.Task[CommandResult] | None = None

    if not skip_validation:
        self.validate()

    self._command = Command[CommandResult](
        cmd=[str(self.executable), str(self.signal_chain), *(["--headless"] if self.settings.headless else [])],
        output_parser=identity_parser,
    )

command property

Get the command to execute.

client property

client: _OpenEphysGuiClient

Get the Open Ephys GUI client.

validate

validate()

Validates the existence of required files and directories.

Raises:

Type Description
FileNotFoundError

If any required file or directory is missing

Source code in src/clabe/apps/open_ephys.py
84
85
86
87
88
89
90
91
92
93
94
def validate(self):
    """
    Validates the existence of required files and directories.

    Raises:
        FileNotFoundError: If any required file or directory is missing
    """
    if not Path(self.executable).exists():
        raise FileNotFoundError(f"Executable not found: {self.executable}")
    if not Path(self.signal_chain).exists():
        raise FileNotFoundError(f"Signal chain file not found: {self.signal_chain}")

launch async

launch(
    executor: AsyncExecutor | None = None,
    *,
    timeout: float = 180.0,
    poll_interval: float = 0.5,
) -> _OpenEphysGuiClient

Starts the GUI in the background and waits until its HTTP API responds.

Call :meth:close when done, e.g. in a finally block, to quit the GUI. If launching fails, the GUI is closed before the error is raised.

When executor runs commands on another machine (it has a host, like clabe.xml_rpc.RemoteRepository) and settings.address is a loopback address, the client is pointed at that machine instead. The GUI's port must then be reachable from this machine.

Parameters:

Name Type Description Default
executor AsyncExecutor | None

Executor to run the GUI with. Defaults to a local executor.

None
timeout float

Seconds to wait for the API to respond after starting the GUI. Startup can take minutes while hardware processors (e.g. Neuropix-PXI, NI-DAQmx) search for devices.

180.0
poll_interval float

Seconds between attempts to reach the API.

0.5

Returns:

Type Description
_OpenEphysGuiClient

The client connected to the running GUI.

Raises:

Type Description
RuntimeError

If the GUI is already launched, or exits before its API responds.

TimeoutError

If the API does not respond within timeout.

CommandError

If the GUI exits with a non-zero code before its API responds.

Example
await app.launch(executor=remote)
try:
    app.start()
    await behavior_app.run_async()
    app.stop()
finally:
    await app.close()
Source code in src/clabe/apps/open_ephys.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
async def launch(
    self,
    executor: AsyncExecutor | None = None,
    *,
    timeout: float = 180.0,
    poll_interval: float = 0.5,
) -> "_OpenEphysGuiClient":
    """Starts the GUI in the background and waits until its HTTP API responds.

    Call :meth:`close` when done, e.g. in a ``finally`` block, to quit the GUI. If launching
    fails, the GUI is closed before the error is raised.

    When ``executor`` runs commands on another machine (it has a ``host``, like
    ``clabe.xml_rpc.RemoteRepository``) and ``settings.address`` is a loopback address, the client
    is pointed at that machine instead. The GUI's port must then be reachable from this machine.

    Args:
        executor: Executor to run the GUI with. Defaults to a local executor.
        timeout: Seconds to wait for the API to respond after starting the GUI. Startup can take
            minutes while hardware processors (e.g. Neuropix-PXI, NI-DAQmx) search for devices.
        poll_interval: Seconds between attempts to reach the API.

    Returns:
        The client connected to the running GUI.

    Raises:
        RuntimeError: If the GUI is already launched, or exits before its API responds.
        TimeoutError: If the API does not respond within ``timeout``.
        CommandError: If the GUI exits with a non-zero code before its API responds.

    Example:
        ```python
        await app.launch(executor=remote)
        try:
            app.start()
            await behavior_app.run_async()
            app.stop()
        finally:
            await app.close()
        ```
    """
    if self._gui is not None:
        raise RuntimeError("Open Ephys GUI is already launched; call close() first.")
    host = getattr(executor, "host", None)
    if host is not None and self.settings.address in _LOOPBACK_ADDRESSES:
        self._client = _OpenEphysGuiClient(host=host, port=self.settings.port)

    self._gui = asyncio.create_task(self.run_async(executor=executor))
    try:
        await self._wait_until_ready(self._gui, timeout, poll_interval)
    except BaseException:
        # The launch error is the one to report; how the GUI then exits is secondary
        try:
            await self.close()
        except Exception as e:  # noqa: BLE001 -- must not mask the launch error
            logger.debug("Open Ephys GUI failed while closing after a failed launch: %s", e)
        raise
    return self._client

start

start(record: bool = True) -> Status

Starts recording, or only acquisition when record is False.

Returns:

Type Description
Status

The GUI's mode after the request.

Source code in src/clabe/apps/open_ephys.py
165
166
167
168
169
170
171
def start(self, record: bool = True) -> "Status":
    """Starts recording, or only acquisition when ``record`` is False.

    Returns:
        The GUI's mode after the request.
    """
    return self._client.start_recording() if record else self._client.start_acquisition()

set_recording_directory

set_recording_directory(
    directory: PathLike | str,
) -> RecordingResponse

Makes every Record Node record to exactly directory, e.g. <data directory>/<session>/ecephys.

The path is as the machine running the GUI sees it. Call it after :meth:launch and before :meth:start. Its parent must already exist, e.g. created by :meth:clabe.xml_rpc.RemoteRepository.register_session. The directory itself must not: the GUI creates it when recording starts, and if it already exists, records to a new sibling instead (e.g. ecephys (1)). So do not create it, or anything inside it, beforehand.

Parameters:

Name Type Description Default
directory PathLike | str

Directory to record to.

required

Returns:

Type Description
RecordingResponse

The recording configuration after the change.

Raises:

Type Description
ValueError

If the GUI did not accept the directory, e.g. because its parent does not exist.

Source code in src/clabe/apps/open_ephys.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
def set_recording_directory(self, directory: os.PathLike | str) -> "RecordingResponse":
    """Makes every Record Node record to exactly ``directory``, e.g. ``<data directory>/<session>/ecephys``.

    The path is as the machine running the GUI sees it. Call it after :meth:`launch` and before :meth:`start`.
    Its parent must already exist, e.g. created by :meth:`clabe.xml_rpc.RemoteRepository.register_session`.
    The directory itself must not: the GUI creates it when recording starts, and if it already exists, records
    to a new sibling instead (e.g. ``ecephys (1)``). So do not create it, or anything inside it, beforehand.

    Args:
        directory: Directory to record to.

    Returns:
        The recording configuration after the change.

    Raises:
        ValueError: If the GUI did not accept the directory, e.g. because its parent does not exist.
    """
    directory = PureWindowsPath(directory)
    # The GUI names the directory prepend_text + base_text + append_text, under parent_directory
    response = self._client.set_recording_config(
        parent_directory=str(directory.parent), base_text=directory.name, prepend_text="", append_text=""
    )
    # Record Nodes saved in the signal chain with their own directory may not follow the default
    for node in response.record_nodes:
        if PureWindowsPath(node.parent_directory) != directory.parent:
            response = self._client.set_record_node_config(node.node_id, parent_directory=str(directory.parent))
    # The GUI ignores a parent that does not exist, without an error, and keeps recording to its previous one
    ignored = [
        str(PureWindowsPath(p))
        for p in [response.parent_directory, *(n.parent_directory for n in response.record_nodes)]
        if PureWindowsPath(p) != directory.parent
    ]
    if ignored:
        raise ValueError(
            f"Open Ephys did not accept {directory.parent} as the recording directory's parent and would record "
            f"to {sorted(set(ignored))}. Check that it exists on the machine running the GUI."
        )
    return response

stop

stop() -> Status

Stops recording and acquisition.

Returns:

Type Description
Status

The GUI's mode after the request.

Source code in src/clabe/apps/open_ephys.py
212
213
214
215
216
217
218
def stop(self) -> "Status":
    """Stops recording and acquisition.

    Returns:
        The GUI's mode after the request.
    """
    return self._client.stop()

close async

close(timeout: float = 30.0) -> CommandResult | None

Asks the GUI to quit and waits for it to exit. Does nothing if it is not launched.

Parameters:

Name Type Description Default
timeout float

Seconds to wait for the GUI to exit after asking it to quit.

30.0

Returns:

Type Description
CommandResult | None

The GUI's result, or None if it was not launched or did not exit within timeout.

Raises:

Type Description
CommandError

If the GUI exited with a non-zero code.

Source code in src/clabe/apps/open_ephys.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
async def close(self, timeout: float = 30.0) -> CommandResult | None:
    """Asks the GUI to quit and waits for it to exit. Does nothing if it is not launched.

    Args:
        timeout: Seconds to wait for the GUI to exit after asking it to quit.

    Returns:
        The GUI's result, or None if it was not launched or did not exit within ``timeout``.

    Raises:
        CommandError: If the GUI exited with a non-zero code.
    """
    gui, self._gui = self._gui, None
    if gui is None:
        return None
    if not gui.done():
        try:
            await asyncio.to_thread(self._client.quit)
        except requests.RequestException as e:
            # The GUI may close the connection as it quits, or not be reachable at all
            logger.debug("Quit request to Open Ephys GUI failed: %s", e)
        done, _ = await asyncio.wait({gui}, timeout=timeout)
        if not done:
            gui.cancel()
            # Cancelling stops waiting for the process but does not end it
            logger.warning("Open Ephys GUI did not exit within %ss of quitting; it may still be running", timeout)
            return None
    if gui.cancelled():
        return None
    return gui.result()

run

run(
    executor_kwargs: dict[str, Any] | None = None,
    *,
    executor: Executor | None = None,
) -> CommandResult

Execute the command and return the result.

Parameters:

Name Type Description Default
executor_kwargs dict[str, Any] | None

Keyword arguments forwarded to the local executor.

None
executor Executor | None

Executor to run the command with, e.g. a RemoteRepository to run it on another machine. Defaults to a local executor built from executor_kwargs.

None
Source code in src/clabe/apps/_executors.py
288
289
290
291
292
293
294
295
296
297
298
299
@runnable
def run(self, executor_kwargs: dict[str, Any] | None = None, *, executor: Executor | None = None) -> CommandResult:
    """Execute the command and return the result.

    Args:
        executor_kwargs: Keyword arguments forwarded to the local executor.
        executor: Executor to run the command with, e.g. a ``RemoteRepository`` to run it on
            another machine. Defaults to a local executor built from ``executor_kwargs``.
    """
    if executor is not None and executor_kwargs is not None:
        raise ValueError("Pass either executor or executor_kwargs, not both.")
    return self.command.execute(executor or LocalExecutor(**(executor_kwargs or {})))

run_async async

run_async(
    executor_kwargs: dict[str, Any] | None = None,
    *,
    executor: AsyncExecutor | None = None,
) -> CommandResult

Execute the command asynchronously and return the result.

Parameters:

Name Type Description Default
executor_kwargs dict[str, Any] | None

Keyword arguments forwarded to the local executor.

None
executor AsyncExecutor | None

Executor to run the command with, e.g. a RemoteRepository to run it on another machine. Defaults to a local executor built from executor_kwargs.

None
Source code in src/clabe/apps/_executors.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
@runnable
async def run_async(
    self, executor_kwargs: dict[str, Any] | None = None, *, executor: AsyncExecutor | None = None
) -> CommandResult:
    """Execute the command asynchronously and return the result.

    Args:
        executor_kwargs: Keyword arguments forwarded to the local executor.
        executor: Executor to run the command with, e.g. a ``RemoteRepository`` to run it on
            another machine. Defaults to a local executor built from ``executor_kwargs``.
    """
    if executor is not None and executor_kwargs is not None:
        raise ValueError("Pass either executor or executor_kwargs, not both.")
    return await self.command.execute_async(executor or AsyncLocalExecutor(**(executor_kwargs or {})))

Status

Bases: str, Enum

GUI acquisition/recording mode.

StatusResponse

Bases: BaseModel

Response from /api/status endpoint.

StatusRequest

Bases: BaseModel

Request to set GUI acquisition/recording mode.

RecordNode

Bases: BaseModel

Information about a Record Node.

RecordingResponse

Bases: BaseModel

Response from /api/recording endpoint.

RecordingRequest

Bases: BaseModel

Request to update recording configuration.

RecordNodeRequest

Bases: BaseModel

Request to update a specific Record Node.

Stream

Bases: BaseModel

Data stream information.

Processor

Bases: BaseModel

Processor/plugin information.

ProcessorsResponse

Bases: BaseModel

Response from /api/processors endpoint.

ConfigRequest

Bases: BaseModel

Request to send configuration message to a processor.

MessageRequest

Bases: BaseModel

Request to broadcast a message to all processors.

WindowRequest

Bases: BaseModel

Request to control GUI window (GUI versions before v1.1).

QuitRequest

Bases: BaseModel

Request to shut down the GUI (/api/quit, GUI v1.1+).