From 4bb8ab179dcbb5e4870b017c9f0a59ace527db0b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:32:40 +0000 Subject: [PATCH 01/18] Ontology Logger extension: a logger annotating the saved data with the terms of the ontology manager Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81mHyjs9x4DB6NLuNY --- README.rst | 5 ++ .../extensions/ontology_logger.py | 71 +++++++++++++++ .../resources/ontology/basic_terms.toml | 37 ++++++++ tests/test_ontology_logger.py | 87 +++++++++++++++++++ 4 files changed, 200 insertions(+) create mode 100644 src/pymodaq_plugins_mockexamples/extensions/ontology_logger.py create mode 100644 src/pymodaq_plugins_mockexamples/resources/ontology/basic_terms.toml create mode 100644 tests/test_ontology_logger.py diff --git a/README.rst b/README.rst index b595a4f..249d065 100644 --- a/README.rst +++ b/README.rst @@ -289,6 +289,11 @@ Extensions save them. It shows how to use the ``modules_manager``, how to wait for the instruments with callbacks instead of blocking the GUI, units on the positions and a clean shutdown. It works with the mock instruments of PyMoDAQ. See "How a Dashboard extension works" in the PyMoDAQ documentation. +* **Ontology Logger** (*extensions/ontology_logger.py*): a DAQ_Logger whose saved data carry the ontology terms assigned + to the channels of the instruments. It needs the ``pymodaq_ontology`` package (PyMoDAQ ``dev`` branch for now): its + *Ontology* manager of the Dashboard assigns a term to each channel, and this extension asks the manager to annotate + what its worker saves (``semantic_iri`` attribute). A small ontology for the mock instruments is given in + *resources/ontology/basic_terms.toml*. Without ``pymodaq_ontology`` it works as a plain logger. Installation instructions diff --git a/src/pymodaq_plugins_mockexamples/extensions/ontology_logger.py b/src/pymodaq_plugins_mockexamples/extensions/ontology_logger.py new file mode 100644 index 0000000..be7accb --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/extensions/ontology_logger.py @@ -0,0 +1,71 @@ +"""Demo extension: a DAQ_Logger whose saved data carry the terms of an ontology + +It shows how an extension works with the ``OntologyManager`` of the ``pymodaq_ontology`` package: + +* the manager lives in the Dashboard (menu *Ontology*): the user assigns a term to each channel of the instruments +* the extension asks the manager to annotate the data saved by its worker (``attach_worker``): the ``semantic_iri`` + extra attribute is written with the data +* it gives the manager a small ontology of its own (``resources/ontology/basic_terms.toml``) if none was loaded yet + +Without ``pymodaq_ontology`` the extension is a plain logger and says so. +""" +from pathlib import Path +from typing import Optional, TYPE_CHECKING + +from pymodaq_utils.logger import set_logger, get_module_name + +from pymodaq.extensions.daq_logger.daq_logger import DAQLogger +from pymodaq_gui.utils.dock import DockArea + +if TYPE_CHECKING: + from pymodaq.dashboard import DashBoard + +logger = set_logger(get_module_name(__file__)) + +EXTENSION_NAME = 'Ontology Logger' # displayed in the Extensions menu of the Dashboard +CLASS_NAME = 'OntologyLogger' # the name of the class below + +TERMS_FILE = Path(__file__).parent.parent.joinpath('resources', 'ontology', 'basic_terms.toml') + + +class OntologyLogger(DAQLogger): + """A logger annotating what it saves with the terms assigned in the ontology manager of the Dashboard""" + h5_base_group_name = 'OntologyLogger' + + def __init__(self, dockarea: DockArea = None, dashboard: 'DashBoard' = None): + super().__init__(dockarea, dashboard) + self.ontology_manager = getattr(dashboard, 'extra_managers', {}).get('ontology') + if self.ontology_manager is None: + self.update_status('pymodaq_ontology is not installed: the data are saved without annotation') + return + if self.ontology_manager.source is None: + self._load_basic_terms() + self.ontology_manager.attach_worker(self.logging) + + def _load_basic_terms(self, path: Optional[Path] = None) -> None: + from pymodaq_ontology.source_factory import SourceFactory + self.ontology_manager.set_source(SourceFactory.create('terms', str(path or TERMS_FILE))) + + def _quit_fun(self) -> bool: + can_quit = super()._quit_fun() + if can_quit and self.ontology_manager is not None: + self.ontology_manager.detach_worker(self.logging) + return can_quit + + +def main(): + """Run the extension on its own (the Dashboard stays hidden), see ``-x EXPERIMENT_NAME -s STATE_NAME``""" + import sys + from pymodaq_gui.qt_utils import mkQApp + from pymodaq.dashboard import load_dashboard_with_arguments + from pymodaq.utils.gui_utils.loader_utils import create_extension + + app = mkQApp('Ontology Logger') + win, dashboard, _ = load_dashboard_with_arguments(show_dashboard=False, load_extension=False) + win.mainwindow.setVisible(False) + win_ext, ext = create_extension(dashboard, OntologyLogger, show_extension=True) + sys.exit(app.exec()) + + +if __name__ == '__main__': + main() diff --git a/src/pymodaq_plugins_mockexamples/resources/ontology/basic_terms.toml b/src/pymodaq_plugins_mockexamples/resources/ontology/basic_terms.toml new file mode 100644 index 0000000..e5badc7 --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/resources/ontology/basic_terms.toml @@ -0,0 +1,37 @@ +# A basic ontology for the mock instruments, in the format read by the "terms" source of pymodaq_ontology. +# The IRIs are examples (the namespace is not published): replace them by the ones of a real ontology. + +[[term]] +iri = "http://example.org/mockexamples#Signal" +label = "Signal" +category = "Detection" +description = "Any signal measured by a detector." +roles = ["detector"] + +[[term]] +iri = "http://example.org/mockexamples#Photodiode" +label = "Photodiode signal" +category = "Detection" +description = "Voltage delivered by a photodiode." +roles = ["detector"] + +[[term]] +iri = "http://example.org/mockexamples#Temperature" +label = "Temperature" +category = "Environment" +description = "Temperature of the sample or of the setup." +roles = ["detector", "actuator"] + +[[term]] +iri = "http://example.org/mockexamples#Position" +label = "Position" +category = "Control" +description = "Position of a moving stage." +roles = ["actuator"] + +[[term]] +iri = "http://example.org/mockexamples#Wavelength" +label = "Wavelength" +category = "Control" +description = "Wavelength selected by a monochromator or a laser." +roles = ["actuator"] diff --git a/tests/test_ontology_logger.py b/tests/test_ontology_logger.py new file mode 100644 index 0000000..2ee88e5 --- /dev/null +++ b/tests/test_ontology_logger.py @@ -0,0 +1,87 @@ +"""Tests of the demo extension annotating the saved data with the terms of an ontology""" +import pytest +import qt_themes +from pytest import fixture +from qtpy import QtWidgets + +pytest.importorskip('pymodaq_plugins_mock', reason='The mock instruments of PyMoDAQ are needed') +pytest.importorskip('pymodaq_ontology', reason='The ontology manager is needed') + +from pymodaq_utils.config import GlobalConfig + +from pymodaq.control_modules.enums import DAQTypesEnum +from pymodaq.dashboard import create_load_dashboard +from pymodaq.extensions.daq_logger.daq_logger import DAQLogger +from pymodaq.utils.gui_utils.loader_utils import create_extension + +from pymodaq_ontology import manager as manager_module + +from pymodaq_plugins_mockexamples.extensions import ontology_logger +from pymodaq_plugins_mockexamples.extensions.ontology_logger import OntologyLogger + +PHOTODIODE = 'http://example.org/mockexamples#Photodiode' + + +def test_is_a_dashboard_extension(): + assert ontology_logger.EXTENSION_NAME + assert ontology_logger.CLASS_NAME == OntologyLogger.__name__ + assert issubclass(OntologyLogger, DAQLogger) + assert ontology_logger.TERMS_FILE.is_file() + + +@fixture +def dashboard(qtbot, tmp_path, monkeypatch): + monkeypatch.setattr(manager_module, 'get_set_config_dir', lambda name, user=False: tmp_path / name) + (tmp_path / 'ontology').mkdir() + config = GlobalConfig() + qt_themes.set_theme(theme=config('gui', 'style', 'theme')[0], style=config('gui', 'style', 'style')[0]) + shared_ui, dashboard = create_load_dashboard(show_dashboard=False) + qtbot.addWidget(shared_ui.parent) + qtbot.addWidget(dashboard.tree) + + creator = dashboard.module_creator + detector = creator.create_detector('Det', DAQTypesEnum.DAQ0D) + creator.set_detector_type(detector, DAQTypesEnum.DAQ0D, 'Mock') + creator.add_detector(detector) + detector.init_hardware_ui(True) + qtbot.waitUntil(lambda: detector.initialized_state, timeout=10000) + dashboard.modules_manager.detectors_all = [detector] + yield dashboard + QtWidgets.QApplication.processEvents() + dashboard.quit_fun() + + +@fixture +def extension(dashboard): + win_ext, ext = create_extension(dashboard, OntologyLogger, show_extension=False) + ext.do_things_after_experiment_set('mock experiment', False) + yield ext + ext.quit_fun() + + +def test_the_basic_ontology_is_given_to_the_manager(extension): + manager = extension.ontology_manager + assert manager is not None + assert PHOTODIODE in manager.terms + + +def test_the_saved_data_carry_the_assigned_term(extension, qtbot, tmp_path): + manager = extension.ontology_manager + manager.probe() + channels = [c for c in manager.channels if c.module == 'Det'] + assert channels + manager.assign(channels[0].key, PHOTODIODE) # only the first channel of the mock detector + + extension.h5_manager.get_h5saver().settings['base_path'] = str(tmp_path) # not in the user's data folder + extension.modules_manager.selected_detectors_name = ['Det'] # the logger saves the selected detectors + extension.logging.start() + extension.modules_manager.detectors[0].snap() + qtbot.waitUntil(lambda: extension.status_manager.n_saved >= 1, timeout=15000) + extension.logging.stop('test') + qtbot.waitUntil(lambda: extension.settings['saver_worker', 'worker_tasks'] == 0, timeout=15000) + + h5saver = extension.h5_manager.h5saver + nodes = [n for n in h5saver.walk_nodes('/') if 'semantic_iri' in n.attrs] + assert nodes + iris = nodes[0].attrs['semantic_iri'] + assert PHOTODIODE in ([iris] if isinstance(iris, str) else list(iris)) From a104d0036ccbc90399ff8b374f7cba058f7d80e1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 20:41:35 +0000 Subject: [PATCH 02/18] Ontology Logger: select the instruments by the concept of their channels, with a hierarchy of terms Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81mHyjs9x4DB6NLuNY --- README.rst | 4 +- .../extensions/ontology_logger.py | 40 +++++++++++++++++++ .../resources/ontology/basic_terms.toml | 19 +++++++++ tests/test_ontology_logger.py | 39 ++++++++++++++---- 4 files changed, 94 insertions(+), 8 deletions(-) diff --git a/README.rst b/README.rst index 249d065..bca5d75 100644 --- a/README.rst +++ b/README.rst @@ -293,7 +293,9 @@ Extensions to the channels of the instruments. It needs the ``pymodaq_ontology`` package (PyMoDAQ ``dev`` branch for now): its *Ontology* manager of the Dashboard assigns a term to each channel, and this extension asks the manager to annotate what its worker saves (``semantic_iri`` attribute). A small ontology for the mock instruments is given in - *resources/ontology/basic_terms.toml*. Without ``pymodaq_ontology`` it works as a plain logger. + *resources/ontology/basic_terms.toml*: its terms know what they are a kind of, so choosing the concept *Optical signal* + and the action *Select the channels of the concept* selects the instruments whose channels are photodiode signals or + spectra, whatever the instruments are called. Without ``pymodaq_ontology`` it works as a plain logger. Installation instructions diff --git a/src/pymodaq_plugins_mockexamples/extensions/ontology_logger.py b/src/pymodaq_plugins_mockexamples/extensions/ontology_logger.py index be7accb..2ac52bf 100644 --- a/src/pymodaq_plugins_mockexamples/extensions/ontology_logger.py +++ b/src/pymodaq_plugins_mockexamples/extensions/ontology_logger.py @@ -6,6 +6,9 @@ * the extension asks the manager to annotate the data saved by its worker (``attach_worker``): the ``semantic_iri`` extra attribute is written with the data * it gives the manager a small ontology of its own (``resources/ontology/basic_terms.toml``) if none was loaded yet +* the terms know what they are a kind of (``broader``): choose a concept, for instance *Optical signal*, and the + action *Select the channels of the concept* selects the instruments with a channel whose term is that concept or + a kind of it (a *Photodiode signal* is an *Optical signal*), whatever the instruments are called Without ``pymodaq_ontology`` the extension is a plain logger and says so. """ @@ -31,6 +34,9 @@ class OntologyLogger(DAQLogger): """A logger annotating what it saves with the terms assigned in the ontology manager of the Dashboard""" h5_base_group_name = 'OntologyLogger' + params = DAQLogger.params + [ + {'title': 'Concept:', 'name': 'concept', 'type': 'list', 'limits': {}}, # label -> IRI, filled by the manager + ] def __init__(self, dockarea: DockArea = None, dashboard: 'DashBoard' = None): super().__init__(dockarea, dashboard) @@ -40,8 +46,42 @@ def __init__(self, dockarea: DockArea = None, dashboard: 'DashBoard' = None): return if self.ontology_manager.source is None: self._load_basic_terms() + self._update_concepts() self.ontology_manager.attach_worker(self.logging) + def setup_actions(self): + super().setup_actions() + self.add_action('select_concept', 'Select the channels of the concept', 'hub', + tip='Select the instruments with a channel whose term is the concept or a kind of it') + + def connect_things(self): + super().connect_things() + self.connect_action('select_concept', self.select_channels_of_concept) + + def _update_concepts(self) -> None: + """The terms of the ontology that have kinds (the concepts), by label""" + hierarchy = self.ontology_manager.hierarchy + concepts = {term.label: iri for iri, term in hierarchy.terms.items() if hierarchy.children(iri)} + self.settings.child('concept').setLimits(concepts) + + def select_channels_of_concept(self) -> str: + """Select the instruments with a channel of the chosen concept. Returns what was done, as text""" + manager = self.ontology_manager + if manager is None or not self.settings['concept']: + message = 'No concept to select' + else: + manager.update_channels_from_dashboard() + manager.probe() # the channels of the detectors are found by a snap + channels = manager.channels_of_concept(self.settings['concept']) + detectors = sorted({c.module for c in channels if c.kind == 'detector'}) + actuators = sorted({c.module for c in channels if c.kind == 'actuator'}) + self.modules_manager.selected_detectors_name = detectors + self.modules_manager.selected_actuators_name = actuators + label = manager.terms[self.settings['concept']].label + message = f'{len(channels)} channels of "{label}": detectors {detectors}, actuators {actuators}' + self.update_status(message) + return message + def _load_basic_terms(self, path: Optional[Path] = None) -> None: from pymodaq_ontology.source_factory import SourceFactory self.ontology_manager.set_source(SourceFactory.create('terms', str(path or TERMS_FILE))) diff --git a/src/pymodaq_plugins_mockexamples/resources/ontology/basic_terms.toml b/src/pymodaq_plugins_mockexamples/resources/ontology/basic_terms.toml index e5badc7..1d110fc 100644 --- a/src/pymodaq_plugins_mockexamples/resources/ontology/basic_terms.toml +++ b/src/pymodaq_plugins_mockexamples/resources/ontology/basic_terms.toml @@ -1,5 +1,6 @@ # A basic ontology for the mock instruments, in the format read by the "terms" source of pymodaq_ontology. # The IRIs are examples (the namespace is not published): replace them by the ones of a real ontology. +# ``broader`` says what a term is a kind of: the Ontology Logger uses it to find the channels of a concept. [[term]] iri = "http://example.org/mockexamples#Signal" @@ -8,12 +9,29 @@ category = "Detection" description = "Any signal measured by a detector." roles = ["detector"] +[[term]] +iri = "http://example.org/mockexamples#OpticalSignal" +label = "Optical signal" +category = "Detection" +description = "A signal produced by light." +roles = ["detector"] +broader = ["http://example.org/mockexamples#Signal"] + [[term]] iri = "http://example.org/mockexamples#Photodiode" label = "Photodiode signal" category = "Detection" description = "Voltage delivered by a photodiode." roles = ["detector"] +broader = ["http://example.org/mockexamples#OpticalSignal"] + +[[term]] +iri = "http://example.org/mockexamples#Spectrum" +label = "Spectrum" +category = "Detection" +description = "Intensity as a function of the wavelength." +roles = ["detector"] +broader = ["http://example.org/mockexamples#OpticalSignal"] [[term]] iri = "http://example.org/mockexamples#Temperature" @@ -21,6 +39,7 @@ label = "Temperature" category = "Environment" description = "Temperature of the sample or of the setup." roles = ["detector", "actuator"] +broader = ["http://example.org/mockexamples#Signal"] [[term]] iri = "http://example.org/mockexamples#Position" diff --git a/tests/test_ontology_logger.py b/tests/test_ontology_logger.py index 2ee88e5..7b62c6b 100644 --- a/tests/test_ontology_logger.py +++ b/tests/test_ontology_logger.py @@ -19,7 +19,11 @@ from pymodaq_plugins_mockexamples.extensions import ontology_logger from pymodaq_plugins_mockexamples.extensions.ontology_logger import OntologyLogger -PHOTODIODE = 'http://example.org/mockexamples#Photodiode' +NS = 'http://example.org/mockexamples#' +PHOTODIODE = NS + 'Photodiode' +TEMPERATURE = NS + 'Temperature' +OPTICAL = NS + 'OpticalSignal' +SIGNAL = NS + 'Signal' def test_is_a_dashboard_extension(): @@ -40,12 +44,15 @@ def dashboard(qtbot, tmp_path, monkeypatch): qtbot.addWidget(dashboard.tree) creator = dashboard.module_creator - detector = creator.create_detector('Det', DAQTypesEnum.DAQ0D) - creator.set_detector_type(detector, DAQTypesEnum.DAQ0D, 'Mock') - creator.add_detector(detector) - detector.init_hardware_ui(True) - qtbot.waitUntil(lambda: detector.initialized_state, timeout=10000) - dashboard.modules_manager.detectors_all = [detector] + detectors = [] + for name in ('Det', 'Other'): + detector = creator.create_detector(name, DAQTypesEnum.DAQ0D) + creator.set_detector_type(detector, DAQTypesEnum.DAQ0D, 'Mock') + creator.add_detector(detector) + detector.init_hardware_ui(True) + detectors.append(detector) + qtbot.waitUntil(lambda: all(d.initialized_state for d in detectors), timeout=10000) + dashboard.modules_manager.detectors_all = detectors yield dashboard QtWidgets.QApplication.processEvents() dashboard.quit_fun() @@ -85,3 +92,21 @@ def test_the_saved_data_carry_the_assigned_term(extension, qtbot, tmp_path): assert nodes iris = nodes[0].attrs['semantic_iri'] assert PHOTODIODE in ([iris] if isinstance(iris, str) else list(iris)) + + +def test_select_the_instruments_by_what_their_channels_mean(extension): + """The names of the modules say nothing: the terms assigned to their channels do""" + manager = extension.ontology_manager + manager.probe() + det = next(c for c in manager.channels if c.module == 'Det') + other = next(c for c in manager.channels if c.module == 'Other') + manager.assign(det.key, PHOTODIODE) + manager.assign(other.key, TEMPERATURE) + + extension.settings['concept'] = OPTICAL + extension.select_channels_of_concept() + assert extension.modules_manager.selected_detectors_name == ['Det'] # a photodiode signal is an optical signal + + extension.settings['concept'] = SIGNAL + extension.select_channels_of_concept() + assert extension.modules_manager.selected_detectors_name == ['Det', 'Other'] # both are signals From 4ca799700fadba01646ff766cd71d7fb73684205 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 20:53:05 +0000 Subject: [PATCH 03/18] Ontology Logger: the basic ontology is a Turtle file read by the rdf source Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81mHyjs9x4DB6NLuNY --- README.rst | 2 +- .../extensions/ontology_logger.py | 10 ++-- .../resources/ontology/basic_ontology.ttl | 34 +++++++++++ .../resources/ontology/basic_terms.toml | 56 ------------------- 4 files changed, 40 insertions(+), 62 deletions(-) create mode 100644 src/pymodaq_plugins_mockexamples/resources/ontology/basic_ontology.ttl delete mode 100644 src/pymodaq_plugins_mockexamples/resources/ontology/basic_terms.toml diff --git a/README.rst b/README.rst index bca5d75..174da05 100644 --- a/README.rst +++ b/README.rst @@ -293,7 +293,7 @@ Extensions to the channels of the instruments. It needs the ``pymodaq_ontology`` package (PyMoDAQ ``dev`` branch for now): its *Ontology* manager of the Dashboard assigns a term to each channel, and this extension asks the manager to annotate what its worker saves (``semantic_iri`` attribute). A small ontology for the mock instruments is given in - *resources/ontology/basic_terms.toml*: its terms know what they are a kind of, so choosing the concept *Optical signal* + *resources/ontology/basic_ontology.ttl* (Turtle, read by the ``rdf`` source): its terms know what they are a kind of, so choosing the concept *Optical signal* and the action *Select the channels of the concept* selects the instruments whose channels are photodiode signals or spectra, whatever the instruments are called. Without ``pymodaq_ontology`` it works as a plain logger. diff --git a/src/pymodaq_plugins_mockexamples/extensions/ontology_logger.py b/src/pymodaq_plugins_mockexamples/extensions/ontology_logger.py index 2ac52bf..398f206 100644 --- a/src/pymodaq_plugins_mockexamples/extensions/ontology_logger.py +++ b/src/pymodaq_plugins_mockexamples/extensions/ontology_logger.py @@ -5,7 +5,7 @@ * the manager lives in the Dashboard (menu *Ontology*): the user assigns a term to each channel of the instruments * the extension asks the manager to annotate the data saved by its worker (``attach_worker``): the ``semantic_iri`` extra attribute is written with the data -* it gives the manager a small ontology of its own (``resources/ontology/basic_terms.toml``) if none was loaded yet +* it gives the manager a small ontology of its own (``resources/ontology/basic_ontology.ttl``) if none was loaded yet * the terms know what they are a kind of (``broader``): choose a concept, for instance *Optical signal*, and the action *Select the channels of the concept* selects the instruments with a channel whose term is that concept or a kind of it (a *Photodiode signal* is an *Optical signal*), whatever the instruments are called @@ -28,7 +28,7 @@ EXTENSION_NAME = 'Ontology Logger' # displayed in the Extensions menu of the Dashboard CLASS_NAME = 'OntologyLogger' # the name of the class below -TERMS_FILE = Path(__file__).parent.parent.joinpath('resources', 'ontology', 'basic_terms.toml') +TERMS_FILE = Path(__file__).parent.parent.joinpath('resources', 'ontology', 'basic_ontology.ttl') class OntologyLogger(DAQLogger): @@ -45,7 +45,7 @@ def __init__(self, dockarea: DockArea = None, dashboard: 'DashBoard' = None): self.update_status('pymodaq_ontology is not installed: the data are saved without annotation') return if self.ontology_manager.source is None: - self._load_basic_terms() + self._load_basic_ontology() self._update_concepts() self.ontology_manager.attach_worker(self.logging) @@ -82,9 +82,9 @@ def select_channels_of_concept(self) -> str: self.update_status(message) return message - def _load_basic_terms(self, path: Optional[Path] = None) -> None: + def _load_basic_ontology(self, path: Optional[Path] = None) -> None: from pymodaq_ontology.source_factory import SourceFactory - self.ontology_manager.set_source(SourceFactory.create('terms', str(path or TERMS_FILE))) + self.ontology_manager.set_source(SourceFactory.create('rdf', str(path or TERMS_FILE))) def _quit_fun(self) -> bool: can_quit = super()._quit_fun() diff --git a/src/pymodaq_plugins_mockexamples/resources/ontology/basic_ontology.ttl b/src/pymodaq_plugins_mockexamples/resources/ontology/basic_ontology.ttl new file mode 100644 index 0000000..d316eb1 --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/resources/ontology/basic_ontology.ttl @@ -0,0 +1,34 @@ +@prefix mock: . +@prefix owl: . +@prefix rdfs: . +@prefix skos: . +@prefix sosa: . + +# A basic ontology for the mock instruments, read by the "rdf" source of pymodaq_ontology. +# The IRIs are examples (the namespace is not published): replace them by the ones of a real ontology. +# ``rdfs:subClassOf`` says what a term is a kind of: the Ontology Logger uses it to find the channels of a concept. +# A term that is a kind of sosa:ObservableProperty is meant for detectors, of sosa:ActuatableProperty for actuators. + +mock:Signal a owl:Class ; rdfs:subClassOf sosa:ObservableProperty ; + rdfs:label "Signal"@en ; skos:definition "Any signal measured by a detector."@en . + +mock:OpticalSignal a owl:Class ; rdfs:subClassOf mock:Signal ; + rdfs:label "Optical signal"@en ; skos:definition "A signal produced by light."@en . + +mock:Photodiode a owl:Class ; rdfs:subClassOf mock:OpticalSignal ; + rdfs:label "Photodiode signal"@en ; skos:definition "Voltage delivered by a photodiode."@en . + +mock:Spectrum a owl:Class ; rdfs:subClassOf mock:OpticalSignal ; + rdfs:label "Spectrum"@en ; skos:definition "Intensity as a function of the wavelength."@en . + +mock:Temperature a owl:Class ; rdfs:subClassOf mock:Signal ; + rdfs:label "Temperature"@en ; skos:definition "Temperature of the sample or of the setup."@en . + +mock:Control a owl:Class ; rdfs:subClassOf sosa:ActuatableProperty ; + rdfs:label "Control"@en ; skos:definition "Anything the experiment sets."@en . + +mock:Position a owl:Class ; rdfs:subClassOf mock:Control ; + rdfs:label "Position"@en ; skos:definition "Position of a moving stage."@en . + +mock:Wavelength a owl:Class ; rdfs:subClassOf mock:Control ; + rdfs:label "Wavelength"@en ; skos:definition "Wavelength selected by a monochromator or a laser."@en . diff --git a/src/pymodaq_plugins_mockexamples/resources/ontology/basic_terms.toml b/src/pymodaq_plugins_mockexamples/resources/ontology/basic_terms.toml deleted file mode 100644 index 1d110fc..0000000 --- a/src/pymodaq_plugins_mockexamples/resources/ontology/basic_terms.toml +++ /dev/null @@ -1,56 +0,0 @@ -# A basic ontology for the mock instruments, in the format read by the "terms" source of pymodaq_ontology. -# The IRIs are examples (the namespace is not published): replace them by the ones of a real ontology. -# ``broader`` says what a term is a kind of: the Ontology Logger uses it to find the channels of a concept. - -[[term]] -iri = "http://example.org/mockexamples#Signal" -label = "Signal" -category = "Detection" -description = "Any signal measured by a detector." -roles = ["detector"] - -[[term]] -iri = "http://example.org/mockexamples#OpticalSignal" -label = "Optical signal" -category = "Detection" -description = "A signal produced by light." -roles = ["detector"] -broader = ["http://example.org/mockexamples#Signal"] - -[[term]] -iri = "http://example.org/mockexamples#Photodiode" -label = "Photodiode signal" -category = "Detection" -description = "Voltage delivered by a photodiode." -roles = ["detector"] -broader = ["http://example.org/mockexamples#OpticalSignal"] - -[[term]] -iri = "http://example.org/mockexamples#Spectrum" -label = "Spectrum" -category = "Detection" -description = "Intensity as a function of the wavelength." -roles = ["detector"] -broader = ["http://example.org/mockexamples#OpticalSignal"] - -[[term]] -iri = "http://example.org/mockexamples#Temperature" -label = "Temperature" -category = "Environment" -description = "Temperature of the sample or of the setup." -roles = ["detector", "actuator"] -broader = ["http://example.org/mockexamples#Signal"] - -[[term]] -iri = "http://example.org/mockexamples#Position" -label = "Position" -category = "Control" -description = "Position of a moving stage." -roles = ["actuator"] - -[[term]] -iri = "http://example.org/mockexamples#Wavelength" -label = "Wavelength" -category = "Control" -description = "Wavelength selected by a monochromator or a laser." -roles = ["actuator"] From b2f38ce022da9c4d80ca6d826e9f7f6d64bd450e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 21:52:49 +0000 Subject: [PATCH 04/18] Add the Spectro Concepts demo extension: what the terms of the channels allow to compute Simulated spectrometers (dark, reference, sample), two experiments with different module names, a small spectro ontology declaring the derivations (transmittance, absorbance), the extension and its tests. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81mHyjs9x4DB6NLuNY --- README.rst | 8 + .../daq_1Dviewer_MockSpectroDark.py | 14 ++ .../daq_1Dviewer_MockSpectroReference.py | 14 ++ .../daq_1Dviewer_MockSpectroSample.py | 46 ++++ .../extensions/spectro_concepts.py | 229 ++++++++++++++++++ .../hardware/mock_spectro.py | 43 ++++ .../ontology_derivations.py | 95 ++++++++ .../resources/ontology/spectro_ontology.ttl | 53 ++++ .../resources/spectro_lab_a.xml | 1 + .../resources/spectro_lab_b.xml | 1 + tests/test_ontology_derivations.py | 72 ++++++ tests/test_spectro_concepts.py | 97 ++++++++ 12 files changed, 673 insertions(+) create mode 100644 src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroDark.py create mode 100644 src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroReference.py create mode 100644 src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroSample.py create mode 100644 src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py create mode 100644 src/pymodaq_plugins_mockexamples/hardware/mock_spectro.py create mode 100644 src/pymodaq_plugins_mockexamples/ontology_derivations.py create mode 100644 src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl create mode 100644 src/pymodaq_plugins_mockexamples/resources/spectro_lab_a.xml create mode 100644 src/pymodaq_plugins_mockexamples/resources/spectro_lab_b.xml create mode 100644 tests/test_ontology_derivations.py create mode 100644 tests/test_spectro_concepts.py diff --git a/README.rst b/README.rst index 174da05..bcbccc5 100644 --- a/README.rst +++ b/README.rst @@ -296,6 +296,14 @@ Extensions *resources/ontology/basic_ontology.ttl* (Turtle, read by the ``rdf`` source): its terms know what they are a kind of, so choosing the concept *Optical signal* and the action *Select the channels of the concept* selects the instruments whose channels are photodiode signals or spectra, whatever the instruments are called. Without ``pymodaq_ontology`` it works as a plain logger. +* **Spectro Concepts** (*extensions/spectro_concepts.py*): what the ontology terms of the channels let the experiment + do, whatever the instruments are called. It needs the ``pymodaq_ontology`` package (PyMoDAQ ``dev`` branch for now). + The experiments ``spectro_lab_a.xml`` and ``spectro_lab_b.xml`` have three simulated spectrometers (plugins + *MockSpectroDark*, *MockSpectroReference*, *MockSpectroSample*) with neutral names that differ from one experiment to + the other. Assign *Dark spectrum*, *Reference spectrum* and *Sample spectrum* to their channels in the *Ontology* + manager: the action *What can I compute?* tells that the *Transmittance* and the *Absorbance* can be computed (the + ontology *resources/ontology/spectro_ontology.ttl* says what each one is derived from) or what is missing, and *Grab + and compute* shows them live, with the formulas coded in the extension. Installation instructions diff --git a/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroDark.py b/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroDark.py new file mode 100644 index 0000000..20f163c --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroDark.py @@ -0,0 +1,14 @@ +"""Ontology demo: the simulated spectrometer measuring the dark spectrum, see MockSpectroSample""" +from pymodaq.control_modules.viewer_utility_classes import main + +from pymodaq_plugins_mockexamples.daq_viewer_plugins.plugins_1D.daq_1Dviewer_MockSpectroSample import \ + DAQ_1DViewer_MockSpectroSample + + +class DAQ_1DViewer_MockSpectroDark(DAQ_1DViewer_MockSpectroSample): + """Counts of the dark measurement, on a wavelength axis in nm""" + kind = 'dark' + + +if __name__ == '__main__': + main(__file__) diff --git a/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroReference.py b/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroReference.py new file mode 100644 index 0000000..03e3f14 --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroReference.py @@ -0,0 +1,14 @@ +"""Ontology demo: the simulated spectrometer measuring the reference spectrum, see MockSpectroSample""" +from pymodaq.control_modules.viewer_utility_classes import main + +from pymodaq_plugins_mockexamples.daq_viewer_plugins.plugins_1D.daq_1Dviewer_MockSpectroSample import \ + DAQ_1DViewer_MockSpectroSample + + +class DAQ_1DViewer_MockSpectroReference(DAQ_1DViewer_MockSpectroSample): + """Counts of the reference measurement, on a wavelength axis in nm""" + kind = 'reference' + + +if __name__ == '__main__': + main(__file__) diff --git a/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroSample.py b/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroSample.py new file mode 100644 index 0000000..e43aeec --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroSample.py @@ -0,0 +1,46 @@ +"""Ontology demo: a simulated spectrometer looking at the lamp through a sample (the spectrum is in counts) + +The three plugins ``MockSpectroDark``, ``MockSpectroReference`` and ``MockSpectroSample`` are the same instrument +measuring a different thing. In the Dashboard the modules are given neutral names (experiments ``spectro_lab_a`` and +``spectro_lab_b``): it is the term assigned in the ontology manager that tells what each one measures. +""" +from pymodaq.control_modules.viewer_utility_classes import DAQ_Viewer_base, comon_parameters, main +from pymodaq.utils.data import DataFromPlugins, Axis +from pymodaq_data import DataToExport + +from pymodaq_plugins_mockexamples.hardware.mock_spectro import MockSpectro + + +class DAQ_1DViewer_MockSpectroSample(DAQ_Viewer_base): + """Counts of the lamp through the sample, on a wavelength axis in nm""" + kind = 'sample' + params = comon_parameters + + def ini_attributes(self): + self.controller: MockSpectro = None + + def ini_detector(self, controller=None): + self.controller = MockSpectro(self.kind) if self.is_master else controller + return f'Simulated spectrometer ({self.kind})', True + + def close(self): + if self.is_master and self.controller is not None: + self.controller.close() + + def commit_settings(self, param): + pass + + def grab_data(self, Naverage=1, **kwargs): + axis = Axis(data=self.controller.get_wavelength_axis(), label='wavelength', units='nm', index=0) + spectrum = sum(self.controller.grab_spectrum() for _ in range(max(Naverage, 1))) / max(Naverage, 1) + self.dte_signal.emit(DataToExport( + name=type(self).__name__, + data=[DataFromPlugins(name='Spectrum', data=[spectrum], dim='Data1D', labels=['intensity'], + units='counts', axes=[axis])])) + + def stop(self): + pass + + +if __name__ == '__main__': + main(__file__) diff --git a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py new file mode 100644 index 0000000..2235141 --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py @@ -0,0 +1,229 @@ +"""Demo extension: what the terms of the channels let the experiment do, whatever the instruments are called + +It uses the ``OntologyManager`` of the ``pymodaq_ontology`` package (menu *Ontology* of the Dashboard). The user assigns +a term to the channels of the instruments (for instance *Dark spectrum*, *Reference spectrum*, *Sample spectrum*), and +the extension, which never reads the names of the modules, can then: + +* tell what can be **computed** from the terms (the ontology says that a *Transmittance* is derived from the sample, the + reference and the dark spectra, and an *Absorbance* from the transmittance), and what is **missing** if it cannot; +* compute and show it live, with the formulas coded here; +* check that what the channels give has the **unit** the term expects (counts for a spectrum). + +Try it with the experiments ``spectro_lab_a`` and ``spectro_lab_b``: the same three simulated spectrometers with +different names. Assign the terms in each one, the extension works the same. + +Without ``pymodaq_ontology`` the extension tells that it cannot work. +""" +from pathlib import Path +from typing import Optional + +import numpy as np +from qtpy import QtWidgets + +from rdflib import URIRef +from pymodaq_utils.logger import set_logger, get_module_name + +from pymodaq_data import DataToExport +from pymodaq_data.data import DataCalculated + +from pymodaq_gui import utils as gutils +from pymodaq_gui.plotting.data_viewers import ViewerDispatcher + +from pymodaq.utils.custom_ext import CustomExt +from pymodaq.utils.managers.modules import ModuleType + +from pymodaq_plugins_mockexamples.ontology_derivations import Derivations, MOCK + +logger = set_logger(get_module_name(__file__)) + +EXTENSION_NAME = 'Spectro Concepts' # displayed in the Extensions menu of the Dashboard +CLASS_NAME = 'SpectroConcepts' # the name of the class below + +TERMS_FILE = Path(__file__).parent.parent.joinpath('resources', 'ontology', 'spectro_ontology.ttl') + + +class SpectroConcepts(CustomExt): + + params = [ + {'title': 'Average:', 'name': 'average', 'type': 'int', 'value': 1, 'min': 1}, + {'title': 'Status:', 'name': 'status', 'type': 'str', 'value': 'Idle', 'readonly': True}, + ] + + def __init__(self, parent: gutils.DockArea, dashboard): + super().__init__(parent, dashboard) + self.ontology_manager = getattr(dashboard, 'extra_managers', {}).get('ontology') + self._busy = False + self.derivations: Optional[Derivations] = None + self.setup_ui() + if self.ontology_manager is None: + self.set_status('pymodaq_ontology is not installed: nothing to compute') + elif self.ontology_manager.source is None: + self._load_spectro_ontology() + + def setup_docks_and_widgets(self): + self.docks['settings'] = gutils.Dock('Settings') + self.dockarea.addDock(self.docks['settings']) + self.docks['settings'].addWidget(self.settings_tree) + self.docks['what'] = gutils.Dock('What the terms allow') + self.dockarea.addDock(self.docks['what'], 'bottom', self.docks['settings']) + self.what = QtWidgets.QPlainTextEdit(readOnly=True) + self.docks['what'].addWidget(self.what) + self.viewer = ViewerDispatcher(self.dockarea, title='Data') + + def setup_menus_and_toolbars(self, menubar: QtWidgets.QMenuBar = None): + self.create_dashboard_toolbar(add_break=False) + + def setup_actions(self): + self.add_action('check', 'What can I compute?', 'help', + tip='Tell what the terms of the channels allow, without acquiring') + self.add_action('grab', 'Grab and compute', 'camera', tip='Grab all the detectors, compute and show') + + def connect_things(self): + self.connect_action('check', self.show_what_is_possible) + self.connect_action('grab', self.grab_and_compute) + self.modules_manager.timeout_signal.connect(self._on_timeout) + + def _load_spectro_ontology(self) -> None: + from pymodaq_ontology.source_factory import SourceFactory + self.ontology_manager.set_source(SourceFactory.create('rdf', str(TERMS_FILE))) + + # ---- the ontology side: terms of the channels + def terms_of_detectors(self) -> dict[str, str]: + """Term assigned to each channel of the detectors, by channel key""" + manager = self.ontology_manager + manager.update_channels_from_dashboard() + return {c.key: manager.assignment.get(c.key) for c in manager.channels if c.kind == 'detector' + and manager.assignment.get(c.key)} + + def _derivations(self) -> Optional[Derivations]: + """The derivations declared by the ontology of the manager (read again if the source changed)""" + graph = getattr(self.ontology_manager.source, 'graph', None) + if graph is None: + return None + if self.derivations is None or self.derivations.graph is not graph: + self.derivations = Derivations(graph, self.ontology_manager.hierarchy.is_a) + return self.derivations + + def _label(self, iri: str) -> str: + term = self.ontology_manager.terms.get(iri) + return term.label if term else iri + + def show_what_is_possible(self) -> str: + """Say what can be computed from the terms assigned to the channels (without acquiring). Returns the text""" + if self.ontology_manager is None: + text = 'pymodaq_ontology is not installed' + else: + derivations = self._derivations() + assigned = self.terms_of_detectors() + terms = {iri: None for iri in assigned.values()} + if derivations is None: + text = 'The ontology loaded in the manager has no graph: load an RDF ontology' + else: + text = self._describe(assigned, derivations.computable(terms), derivations.missing(terms)) + self.what.setPlainText(text) + self.set_status(text.splitlines()[0] if text else 'Idle') + return text + + def _describe(self, assigned: dict[str, str], computable: list[str], missing: dict[str, list[str]]) -> str: + lines = [] + if computable: + lines.append('Can compute: ' + ', '.join(self._label(i) for i in computable)) + else: + lines.append('Nothing can be computed yet') + for output, inputs in missing.items(): + lines.append(f'{self._label(output)} needs: ' + ', '.join(self._label(i) for i in inputs)) + lines.append('') + lines.append('Channels with a term:') + lines.extend(f' {key} -> {self._label(iri)}' for key, iri in assigned.items()) + return '\n'.join(lines) + + # ---- acquisition + def grab_and_compute(self): + if self._busy or self.ontology_manager is None: + return + self.modules_manager.selected_detectors_name = self.modules_manager.detectors_name + self._busy = True + self.set_action_enabled('grab', False) + self.set_status('Grabbing') + self.modules_manager.grab_data_with_callback(callback=self._on_data) + + def _on_data(self, data: DataToExport): + self.modules_manager.forget_callback(self._on_data, ModuleType.Detector) + try: + self.compute_and_show(data) + finally: + self._busy = False + self.set_action_enabled('grab', True) + + def arrays_by_term(self, data: DataToExport) -> tuple[dict[str, np.ndarray], list[str], list]: + """The array of each term assigned to a channel of the data, the unit problems and the axis of the first one""" + from pymodaq_ontology.channels import Channel + from pymodaq_ontology.terms import DETECTOR + assigned = self.ontology_manager.assignment + graph = self.ontology_manager.source.graph + arrays, problems, axis = {}, [], None + for dwa in data.data: + labels = list(dwa.labels) if getattr(dwa, 'labels', None) else [] + for index, array in enumerate(dwa.data): + label = labels[index] if index < len(labels) else f'CH{index:02d}' + key = Channel(module=dwa.origin, kind=DETECTOR, data_name=dwa.name, label=label).key + iri = assigned.get(key) + if not iri: + continue + arrays[iri] = np.asarray(array, dtype=float) + if axis is None and dwa.axes: + axis = dwa.axes[0] + expected = graph.value(URIRef(iri), MOCK.unit) + if expected is not None and str(expected) != '1' and dwa.units and str(expected) != dwa.units: + problems.append(f'{key}: {dwa.units} where {self._label(iri)} expects {expected}') + return arrays, problems, axis + + def compute_and_show(self, data: DataToExport) -> None: + derivations = self._derivations() + if derivations is None: + self.set_status('No RDF ontology loaded in the manager') + return + arrays, problems, axis = self.arrays_by_term(data) + results = derivations.compute(arrays) + computed = [DataCalculated(self._label(iri), data=[array], axes=[axis] if axis is not None else [], + labels=[self._label(iri)]) for iri, array in results.items()] + self.viewer.show_data(DataToExport('spectro', data=[*data, *computed])) + lines = [self._describe(self.terms_of_detectors(), derivations.computable(arrays), + derivations.missing(arrays))] + lines.extend(f'Unit: {p}' for p in problems) + self.what.setPlainText('\n'.join(lines)) + self.set_status(lines[0].splitlines()[0]) + + def _on_timeout(self, missing_modules: list): + self.modules_manager.forget_callback(self._on_data, ModuleType.Control) + self._busy = False + self.set_action_enabled('grab', True) + self.set_status(f'Timeout: {", ".join(missing_modules)}') + + def set_status(self, status: str): + self.settings.child('status').setValue(status) + + def _quit_fun(self) -> bool: + if self._busy: + self.update_status('Wait for the end of the grab before quitting') + return False + self.modules_manager.timeout_signal.disconnect(self._on_timeout) + return True + + +def main(): + """Run the extension on its own (the Dashboard stays hidden), see ``-x EXPERIMENT_NAME -s STATE_NAME``""" + import sys + from pymodaq_gui.qt_utils import mkQApp + from pymodaq.dashboard import load_dashboard_with_arguments + from pymodaq.utils.gui_utils.loader_utils import create_extension + + app = mkQApp('Spectro Concepts') + win, dashboard, _ = load_dashboard_with_arguments(show_dashboard=False, load_extension=False) + win.mainwindow.setVisible(False) + win_ext, ext = create_extension(dashboard, SpectroConcepts, show_extension=True) + sys.exit(app.exec()) + + +if __name__ == '__main__': + main() diff --git a/src/pymodaq_plugins_mockexamples/hardware/mock_spectro.py b/src/pymodaq_plugins_mockexamples/hardware/mock_spectro.py new file mode 100644 index 0000000..5b217d2 --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/hardware/mock_spectro.py @@ -0,0 +1,43 @@ +"""A simulated spectrophotometer measuring, in counts, the dark, the lamp (reference) or the lamp through a sample + +The sample absorbs around 550 nm: its transmittance is about 0.9 away from the band and drops to 0.2 at the centre. +Used by the plugins ``MockSpectroDark``, ``MockSpectroReference`` and ``MockSpectroSample`` of the ontology demo. +""" +import numpy as np + +KINDS = ('dark', 'reference', 'sample') +WAVELENGTHS = np.linspace(400., 800., 400) # nm +DARK_LEVEL = 100. # counts +LAMP_MAX = 20000. # counts at the maximum of the lamp spectrum + + +def lamp_spectrum() -> np.ndarray: + """Counts of the lamp alone, without the dark level""" + return LAMP_MAX * np.exp(-((WAVELENGTHS - 600.) / 200.) ** 2) + + +def transmittance_of_sample() -> np.ndarray: + """Fraction of the light that goes through the sample""" + return 0.9 - 0.7 * np.exp(-((WAVELENGTHS - 550.) / 30.) ** 2) + + +class MockSpectro: + """Spectra in counts of the kind asked ('dark', 'reference' or 'sample'), with a little noise""" + + def __init__(self, kind: str): + if kind not in KINDS: + raise ValueError(f'kind must be one of {KINDS}, not {kind}') + self.kind = kind + self._rng = np.random.default_rng() + + def get_wavelength_axis(self) -> np.ndarray: + return WAVELENGTHS.copy() + + def grab_spectrum(self) -> np.ndarray: + signal = {'dark': np.zeros_like(WAVELENGTHS), 'reference': lamp_spectrum(), + 'sample': lamp_spectrum() * transmittance_of_sample()}[self.kind] + counts = DARK_LEVEL + signal + return counts + self._rng.normal(0., 1., counts.shape) * np.sqrt(counts) * 0.2 + + def close(self) -> None: + pass diff --git a/src/pymodaq_plugins_mockexamples/ontology_derivations.py b/src/pymodaq_plugins_mockexamples/ontology_derivations.py new file mode 100644 index 0000000..8cbfa6d --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/ontology_derivations.py @@ -0,0 +1,95 @@ +"""What can be computed from the terms of the channels: the derivations declared by an ontology + +The ontology says that a term is ``mock:derivedFrom`` other terms (``Transmittance`` from the sample, the reference and +the dark spectra). This module reads these statements in the RDF graph and, given the arrays of the channels that have +a term, tells what can be computed, what is missing, and computes it. It knows nothing about the instruments: it works +on terms. A channel whose term is a kind of the input (a ``SampleSpectrum`` is a ``Spectrum``) is accepted wherever the +input is that more general term. +""" +from typing import Callable, Optional + +import numpy as np +from rdflib import Graph, Namespace, URIRef + +MOCK = Namespace('http://example.org/mockexamples#') +SAMPLE, REFERENCE, DARK = (str(MOCK[name]) for name in ('SampleSpectrum', 'ReferenceSpectrum', 'DarkSpectrum')) +TRANSMITTANCE, ABSORBANCE = str(MOCK.Transmittance), str(MOCK.Absorbance) + + +def _transmittance(inputs: dict[str, np.ndarray]) -> np.ndarray: + dark = inputs[DARK] + reference = inputs[REFERENCE] - dark + with np.errstate(divide='ignore', invalid='ignore'): + return np.where(reference > 0, (inputs[SAMPLE] - dark) / reference, np.nan) + + +def _absorbance(inputs: dict[str, np.ndarray]) -> np.ndarray: + with np.errstate(divide='ignore', invalid='ignore'): + return -np.log10(np.where(inputs[TRANSMITTANCE] > 0, inputs[TRANSMITTANCE], np.nan)) + + +FORMULAS: dict[str, Callable[[dict[str, np.ndarray]], np.ndarray]] = { + TRANSMITTANCE: _transmittance, + ABSORBANCE: _absorbance, +} + + +class Derivations: + """The derivations of an ontology graph + + Parameters + ---------- + graph: rdflib.Graph + the ontology, with ``mock:derivedFrom`` statements + is_a: callable + ``is_a(term, other)``: whether the term is ``other`` or a kind of it (the hierarchy of the ontology manager) + """ + + def __init__(self, graph: Graph, is_a: Callable[[str, str], bool]): + self.graph = graph + self.is_a = is_a + self.rules: dict[str, list[str]] = {} + for output in set(graph.subjects(MOCK.derivedFrom, None)): + self.rules[str(output)] = sorted(str(i) for i in graph.objects(output, MOCK.derivedFrom) + if isinstance(i, URIRef)) + + def _provider(self, wanted: str, available: dict[str, np.ndarray]) -> Optional[str]: + """The available term standing for the wanted one: the same or a kind of it""" + return next((term for term in sorted(available) if self.is_a(term, wanted)), None) + + def missing(self, available: dict[str, np.ndarray]) -> dict[str, list[str]]: + """For each derived term that cannot be computed yet, the inputs that no channel (or derivation) provides""" + have = dict(available) + for output, _inputs in self._order(have): + have[output] = None # placeholder, only the terms are looked at here + return {output: [i for i in inputs if self._provider(i, have) is None] + for output, inputs in self.rules.items() + if output not in have and any(self._provider(i, have) is None for i in inputs)} + + def _order(self, available: dict) -> list[tuple[str, list[str]]]: + """The derivations that can be done, in an order where each one has its inputs""" + have, done = dict(available), [] + progress = True + while progress: + progress = False + for output, inputs in self.rules.items(): + if output not in have and all(self._provider(i, have) is not None for i in inputs): + have[output] = None + done.append((output, inputs)) + progress = True + return done + + def computable(self, available: dict[str, np.ndarray]) -> list[str]: + """The derived terms that can be computed, each after its inputs""" + return [output for output, _ in self._order(available)] + + def compute(self, available: dict[str, np.ndarray]) -> dict[str, np.ndarray]: + """The arrays of the derived terms that can be computed (those without a formula are left out)""" + have = dict(available) + results = {} + for output, inputs in self._order(available): + if output not in FORMULAS: + continue + arrays = {i: have[self._provider(i, have)] for i in inputs} + have[output] = results[output] = FORMULAS[output](arrays) + return results diff --git a/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl b/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl new file mode 100644 index 0000000..1a6a104 --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl @@ -0,0 +1,53 @@ +@prefix mock: . +@prefix owl: . +@prefix rdfs: . +@prefix skos: . +@prefix sosa: . + +# Ontology of the spectro demo (extension "Spectro Concepts"), read by the "rdf" source of pymodaq_ontology. +# The IRIs are examples (the namespace is not published): replace them by the ones of a real ontology. +# +# Besides "is a kind of" (rdfs:subClassOf) the terms say what they are physically: +# mock:quantity the physical quantity ("intensity", "ratio"...) +# mock:unit its unit ("counts", "1" for a pure number) +# mock:derivedFrom the terms it is computed from; mock:formula tells how (documentation, the code is in the extension) + +mock:quantity a owl:AnnotationProperty ; rdfs:label "quantity"@en . +mock:unit a owl:AnnotationProperty ; rdfs:label "unit"@en . +mock:formula a owl:AnnotationProperty ; rdfs:label "formula"@en . +mock:derivedFrom a owl:ObjectProperty ; rdfs:label "derived from"@en . + +mock:Signal a owl:Class ; rdfs:subClassOf sosa:ObservableProperty ; + rdfs:label "Signal"@en ; skos:definition "Any signal measured by a detector."@en . + +mock:Spectrum a owl:Class ; rdfs:subClassOf mock:Signal ; + rdfs:label "Spectrum"@en ; skos:definition "Light intensity as a function of the wavelength, in counts."@en ; + mock:quantity "intensity" ; mock:unit "counts" . + +mock:DarkSpectrum a owl:Class ; rdfs:subClassOf mock:Spectrum ; + rdfs:label "Dark spectrum"@en ; skos:definition "Spectrum with no light: the offset of the detector."@en . + +mock:ReferenceSpectrum a owl:Class ; rdfs:subClassOf mock:Spectrum ; + rdfs:label "Reference spectrum"@en ; skos:definition "Spectrum of the lamp alone, without the sample."@en . + +mock:SampleSpectrum a owl:Class ; rdfs:subClassOf mock:Spectrum ; + rdfs:label "Sample spectrum"@en ; skos:definition "Spectrum of the lamp after the sample."@en . + +mock:Transmittance a owl:Class ; rdfs:subClassOf mock:Signal ; + rdfs:label "Transmittance"@en ; skos:definition "Fraction of the light that goes through the sample."@en ; + mock:quantity "ratio" ; mock:unit "1" ; + mock:derivedFrom mock:SampleSpectrum , mock:ReferenceSpectrum , mock:DarkSpectrum ; + mock:formula "(sample - dark) / (reference - dark)" . + +mock:Absorbance a owl:Class ; rdfs:subClassOf mock:Signal ; + rdfs:label "Absorbance"@en ; skos:definition "Decimal logarithm of the inverse of the transmittance."@en ; + mock:quantity "ratio" ; mock:unit "1" ; + mock:derivedFrom mock:Transmittance ; + mock:formula "-log10(transmittance)" . + +mock:Control a owl:Class ; rdfs:subClassOf sosa:ActuatableProperty ; + rdfs:label "Control"@en ; skos:definition "Anything the experiment sets."@en . + +mock:Wavelength a owl:Class ; rdfs:subClassOf mock:Control ; + rdfs:label "Wavelength"@en ; skos:definition "Wavelength selected by a monochromator or a laser."@en ; + mock:quantity "length" ; mock:unit "nm" . diff --git a/src/pymodaq_plugins_mockexamples/resources/spectro_lab_a.xml b/src/pymodaq_plugins_mockexamples/resources/spectro_lab_a.xml new file mode 100644 index 0000000..c105a63 --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/resources/spectro_lab_a.xml @@ -0,0 +1 @@ +Det_1MockSpectroDarkDAQ1D1str('Master')4100Det_2MockSpectroReferenceDAQ1D1str('Master')4101Det_3MockSpectroSampleDAQ1D1str('Master')4102 diff --git a/src/pymodaq_plugins_mockexamples/resources/spectro_lab_b.xml b/src/pymodaq_plugins_mockexamples/resources/spectro_lab_b.xml new file mode 100644 index 0000000..3ee7abe --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/resources/spectro_lab_b.xml @@ -0,0 +1 @@ +S1MockSpectroSampleDAQ1D1str('Master')4100S2MockSpectroDarkDAQ1D1str('Master')4101S3MockSpectroReferenceDAQ1D1str('Master')4102 diff --git a/tests/test_ontology_derivations.py b/tests/test_ontology_derivations.py new file mode 100644 index 0000000..b3c43b8 --- /dev/null +++ b/tests/test_ontology_derivations.py @@ -0,0 +1,72 @@ +"""What can be computed from the terms: the derivations declared by the spectro ontology (no GUI needed)""" +import numpy as np +import pytest + +pytest.importorskip('pymodaq_ontology', reason='The ontology manager is needed') + +from pymodaq_ontology.source_factory import SourceFactory +from pymodaq_ontology.terms import TermHierarchy + +from pymodaq_plugins_mockexamples.extensions.spectro_concepts import TERMS_FILE +from pymodaq_plugins_mockexamples.hardware.mock_spectro import (MockSpectro, WAVELENGTHS, lamp_spectrum, + transmittance_of_sample, DARK_LEVEL) +from pymodaq_plugins_mockexamples.ontology_derivations import (Derivations, SAMPLE, REFERENCE, DARK, TRANSMITTANCE, + ABSORBANCE) + +NS = 'http://example.org/mockexamples#' + + +@pytest.fixture +def derivations(): + source = SourceFactory.create('rdf', str(TERMS_FILE)) + terms = source.terms() # also reads the graph + return Derivations(source.graph, TermHierarchy(terms).is_a) + + +def spectra(): + return {iri: MockSpectro(kind).grab_spectrum() for iri, kind in + ((SAMPLE, 'sample'), (REFERENCE, 'reference'), (DARK, 'dark'))} + + +def test_the_ontology_declares_the_derivations(derivations): + assert derivations.rules[TRANSMITTANCE] == sorted([SAMPLE, REFERENCE, DARK]) + assert derivations.rules[ABSORBANCE] == [TRANSMITTANCE] + + +def test_nothing_is_computable_without_the_inputs(derivations): + assert derivations.computable({}) == [] + assert derivations.missing({}) == {TRANSMITTANCE: sorted([SAMPLE, REFERENCE, DARK]), + ABSORBANCE: [TRANSMITTANCE]} + + +def test_the_missing_input_is_named(derivations): + available = spectra() + del available[DARK] + assert derivations.computable(available) == [] + assert derivations.missing(available)[TRANSMITTANCE] == [DARK] + + +def test_transmittance_then_absorbance(derivations): + available = spectra() + assert derivations.computable(available) == [TRANSMITTANCE, ABSORBANCE] + results = derivations.compute(available) + expected = transmittance_of_sample() + band = np.argmin(np.abs(WAVELENGTHS - 550.)) + assert results[TRANSMITTANCE][band] == pytest.approx(expected[band], abs=0.05) + assert results[ABSORBANCE][band] == pytest.approx(-np.log10(expected[band]), abs=0.1) + + +def test_a_kind_of_the_input_is_accepted(derivations): + """Whatever term stands for the sample (here the more general Spectrum is NOT enough, a kind of sample is)""" + assert derivations.is_a(SAMPLE, NS + 'Spectrum') + available = spectra() + available[NS + 'Spectrum'] = available.pop(SAMPLE) # a general spectrum is not a sample spectrum + assert derivations.computable(available) == [] + + +def test_the_mock_spectra(): + assert MockSpectro('dark').grab_spectrum().mean() == pytest.approx(DARK_LEVEL, rel=0.1) + assert MockSpectro('reference').grab_spectrum().max() > 10 * DARK_LEVEL + assert lamp_spectrum().max() > 0 + with pytest.raises(ValueError): + MockSpectro('unknown') diff --git a/tests/test_spectro_concepts.py b/tests/test_spectro_concepts.py new file mode 100644 index 0000000..eac21ec --- /dev/null +++ b/tests/test_spectro_concepts.py @@ -0,0 +1,97 @@ +"""Test of the demo extension working on the terms of the channels, with the simulated spectrometers""" +import pytest +import qt_themes +from pytest import fixture +from qtpy import QtWidgets + +pytest.importorskip('pymodaq_plugins_mock', reason='The mock instruments of PyMoDAQ are needed') +pytest.importorskip('pymodaq_ontology', reason='The ontology manager is needed') + +from pymodaq_utils.config import GlobalConfig + +from pymodaq.control_modules.enums import DAQTypesEnum +from pymodaq.dashboard import create_load_dashboard +from pymodaq.utils.custom_ext import CustomExt +from pymodaq.utils.gui_utils.loader_utils import create_extension + +from pymodaq_ontology import manager as manager_module + +from pymodaq_plugins_mockexamples.extensions import spectro_concepts +from pymodaq_plugins_mockexamples.extensions.spectro_concepts import SpectroConcepts + +NS = 'http://example.org/mockexamples#' +# the names of the modules say nothing: what each one measures is the plugin and, for the user, the term assigned +MODULES = {'S1': 'MockSpectroSample', 'S2': 'MockSpectroDark', 'S3': 'MockSpectroReference'} +TERMS = {'S1': NS + 'SampleSpectrum', 'S2': NS + 'DarkSpectrum', 'S3': NS + 'ReferenceSpectrum'} + + +def test_is_a_dashboard_extension(): + assert spectro_concepts.EXTENSION_NAME + assert spectro_concepts.CLASS_NAME == SpectroConcepts.__name__ + assert issubclass(SpectroConcepts, CustomExt) + assert spectro_concepts.TERMS_FILE.is_file() + + +@fixture +def dashboard(qtbot, tmp_path, monkeypatch): + monkeypatch.setattr(manager_module, 'get_set_config_dir', lambda name, user=False: tmp_path / name) + (tmp_path / 'ontology').mkdir() + config = GlobalConfig() + qt_themes.set_theme(theme=config('gui', 'style', 'theme')[0], style=config('gui', 'style', 'style')[0]) + shared_ui, dashboard = create_load_dashboard(show_dashboard=False) + qtbot.addWidget(shared_ui.parent) + qtbot.addWidget(dashboard.tree) + + creator = dashboard.module_creator + detectors = [] + for name, plugin in MODULES.items(): + detector = creator.create_detector(name, DAQTypesEnum.DAQ1D) + creator.set_detector_type(detector, DAQTypesEnum.DAQ1D, plugin) + creator.add_detector(detector) + detector.init_hardware_ui(True) + detectors.append(detector) + qtbot.waitUntil(lambda: all(d.initialized_state for d in detectors), timeout=10000) + dashboard.modules_manager.detectors_all = detectors + yield dashboard + QtWidgets.QApplication.processEvents() + dashboard.quit_fun() + + +@fixture +def extension(dashboard): + win_ext, ext = create_extension(dashboard, SpectroConcepts, show_extension=False) + ext.do_things_after_experiment_set('spectro experiment', False) + yield ext + ext.quit_fun() + + +def assign(extension, modules): + manager = extension.ontology_manager + manager.probe() + for module in modules: + channel = next(c for c in manager.channels if c.module == module) + manager.assign(channel.key, TERMS[module]) + + +def test_the_spectro_ontology_is_given_to_the_manager(extension): + assert extension.ontology_manager.source is not None + assert NS + 'Transmittance' in extension.ontology_manager.terms + + +def test_nothing_to_compute_without_terms(extension): + assert extension.show_what_is_possible().startswith('Nothing can be computed yet') + + +def test_the_missing_term_is_named(extension): + assign(extension, ['S1', 'S3']) # sample and reference, no dark + text = extension.show_what_is_possible() + assert text.startswith('Nothing can be computed yet') + assert 'Transmittance needs: Dark spectrum' in text + + +def test_transmittance_and_absorbance_are_computed_whatever_the_names(extension, qtbot): + assign(extension, ['S1', 'S2', 'S3']) + assert extension.show_what_is_possible().startswith('Can compute: Transmittance, Absorbance') + extension.grab_and_compute() + qtbot.waitUntil(lambda: not extension._busy, timeout=15000) + assert extension.settings['status'].startswith('Can compute: Transmittance, Absorbance') From bd8ab9417f7892b70fb0fc8a596bb5e50728a9f1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:00:33 +0000 Subject: [PATCH 05/18] Spectro Concepts: one bench with a beam block and a cuvette holder, the ontology gives the state for each measurement Remove the Ontology Logger. The extension plans the measurements from the terms of the actuators and of the spectrometer (dark: beam blocked; reference: blank cuvette; sample: sample cuvette), runs them, then computes the transmittance and the absorbance. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81mHyjs9x4DB6NLuNY --- README.rst | 26 ++- .../daq_move_MockBeamBlock.py | 55 ++++++ .../daq_move_MockSampleChanger.py | 18 ++ .../plugins_1D/daq_1Dviewer_MockSpectro.py | 46 +++++ .../daq_1Dviewer_MockSpectroDark.py | 14 -- .../daq_1Dviewer_MockSpectroReference.py | 14 -- .../daq_1Dviewer_MockSpectroSample.py | 46 ----- .../extensions/ontology_logger.py | 111 ------------ .../extensions/spectro_concepts.py | 166 +++++++++++------- .../hardware/mock_spectro.py | 43 ----- .../hardware/spectro_bench.py | 61 +++++++ .../ontology_derivations.py | 63 ++++++- .../resources/ontology/basic_ontology.ttl | 34 ---- .../resources/ontology/spectro_ontology.ttl | 29 ++- .../resources/spectro_lab_a.xml | 2 +- .../resources/spectro_lab_b.xml | 2 +- tests/test_ontology_derivations.py | 64 +++++-- tests/test_ontology_logger.py | 112 ------------ tests/test_spectro_concepts.py | 61 ++++--- 19 files changed, 458 insertions(+), 509 deletions(-) create mode 100644 src/pymodaq_plugins_mockexamples/daq_move_plugins/daq_move_MockBeamBlock.py create mode 100644 src/pymodaq_plugins_mockexamples/daq_move_plugins/daq_move_MockSampleChanger.py create mode 100644 src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectro.py delete mode 100644 src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroDark.py delete mode 100644 src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroReference.py delete mode 100644 src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroSample.py delete mode 100644 src/pymodaq_plugins_mockexamples/extensions/ontology_logger.py delete mode 100644 src/pymodaq_plugins_mockexamples/hardware/mock_spectro.py create mode 100644 src/pymodaq_plugins_mockexamples/hardware/spectro_bench.py delete mode 100644 src/pymodaq_plugins_mockexamples/resources/ontology/basic_ontology.ttl delete mode 100644 tests/test_ontology_logger.py diff --git a/README.rst b/README.rst index bcbccc5..52866f0 100644 --- a/README.rst +++ b/README.rst @@ -289,22 +289,16 @@ Extensions save them. It shows how to use the ``modules_manager``, how to wait for the instruments with callbacks instead of blocking the GUI, units on the positions and a clean shutdown. It works with the mock instruments of PyMoDAQ. See "How a Dashboard extension works" in the PyMoDAQ documentation. -* **Ontology Logger** (*extensions/ontology_logger.py*): a DAQ_Logger whose saved data carry the ontology terms assigned - to the channels of the instruments. It needs the ``pymodaq_ontology`` package (PyMoDAQ ``dev`` branch for now): its - *Ontology* manager of the Dashboard assigns a term to each channel, and this extension asks the manager to annotate - what its worker saves (``semantic_iri`` attribute). A small ontology for the mock instruments is given in - *resources/ontology/basic_ontology.ttl* (Turtle, read by the ``rdf`` source): its terms know what they are a kind of, so choosing the concept *Optical signal* - and the action *Select the channels of the concept* selects the instruments whose channels are photodiode signals or - spectra, whatever the instruments are called. Without ``pymodaq_ontology`` it works as a plain logger. -* **Spectro Concepts** (*extensions/spectro_concepts.py*): what the ontology terms of the channels let the experiment - do, whatever the instruments are called. It needs the ``pymodaq_ontology`` package (PyMoDAQ ``dev`` branch for now). - The experiments ``spectro_lab_a.xml`` and ``spectro_lab_b.xml`` have three simulated spectrometers (plugins - *MockSpectroDark*, *MockSpectroReference*, *MockSpectroSample*) with neutral names that differ from one experiment to - the other. Assign *Dark spectrum*, *Reference spectrum* and *Sample spectrum* to their channels in the *Ontology* - manager: the action *What can I compute?* tells that the *Transmittance* and the *Absorbance* can be computed (the - ontology *resources/ontology/spectro_ontology.ttl* says what each one is derived from) or what is missing, and *Grab - and compute* shows them live, with the formulas coded in the extension. - +* **Spectro Concepts** (*extensions/spectro_concepts.py*): what the ontology terms of the channels let the experiment do, + whatever the modules are called. It needs the ``pymodaq_ontology`` package (PyMoDAQ ``dev`` branch for now). The + experiments ``spectro_lab_a.xml`` and ``spectro_lab_b.xml`` simulate an absorption bench: one spectrometer + (*MockSpectro*), a beam block (*MockBeamBlock*) and a cuvette holder (*MockSampleChanger*), with neutral module names + that differ from one experiment to the other. Assign the terms *Spectrum*, *Beam block* and *Cuvette holder* to them in + the *Ontology* manager. The ontology *resources/ontology/spectro_ontology.ttl* says in which state of the bench a + spectrum is a *Dark spectrum* (beam blocked), a *Reference spectrum* (blank cuvette) or a *Sample spectrum*, and that a + *Transmittance* and an *Absorbance* are derived from them. The action *What can I measure?* tells what can be measured + and computed, or which actuator term is missing; *Measure and compute* sets the bench for each measurement, grabs, then + computes and shows the results, with the formulas coded in the extension. Installation instructions ========================= diff --git a/src/pymodaq_plugins_mockexamples/daq_move_plugins/daq_move_MockBeamBlock.py b/src/pymodaq_plugins_mockexamples/daq_move_plugins/daq_move_MockBeamBlock.py new file mode 100644 index 0000000..c62c5b2 --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/daq_move_plugins/daq_move_MockBeamBlock.py @@ -0,0 +1,55 @@ +"""Ontology demo: the beam block of a simulated absorption bench (1 blocks the beam, 0 lets it through) + +The beam block, the cuvette holder (``MockSampleChanger``) and the spectrometer (``MockSpectro``) share one simulated +bench (see ``hardware/spectro_bench.py``): all are masters, nothing to link in the experiment. +""" +from pymodaq.control_modules.move_utility_classes import DAQ_Move_base, comon_parameters_fun, main, DataActuatorType +from pymodaq.utils.data import DataActuator + +from pymodaq_plugins_mockexamples.hardware.spectro_bench import SpectroBench + + +class DAQ_Move_MockBeamBlock(DAQ_Move_base): + """Sets ``beam_block`` of the bench""" + _controller_units = '' + is_multiaxes = True + _axis_names = ['Block'] + _epsilons = 0.01 + attribute = 'beam_block' # of the bench, set by this plugin + + params = [] + comon_parameters_fun(axis_names=_axis_names, epsilon=_epsilons) + data_actuator_type = DataActuatorType.DataActuator + + def ini_attributes(self): + self.controller: SpectroBench = None + + def get_actuator_value(self) -> DataActuator: + pos = DataActuator(self._title, data=float(getattr(self.controller, self.attribute)), units=self.axis_unit) + return self.get_position_with_scaling(pos) + + def close(self): + pass + + def commit_settings(self, param): + pass + + def ini_stage(self, controller: SpectroBench = None): + self.controller = SpectroBench.shared() + return 'Simulated absorption bench initialized', True + + def move_abs(self, position: DataActuator): + position = self.check_bound(position) + self.target_value = position + setattr(self.controller, self.attribute, float(self.target_value.value(self.axis_unit))) + + def move_rel(self, position: DataActuator): + position = self.check_bound(self.current_value + position) - self.current_value + self.target_value = position + self.current_value + setattr(self.controller, self.attribute, float(self.target_value.value(self.axis_unit))) + + def stop_motion(self): + self.move_done() + + +if __name__ == '__main__': + main(__file__) diff --git a/src/pymodaq_plugins_mockexamples/daq_move_plugins/daq_move_MockSampleChanger.py b/src/pymodaq_plugins_mockexamples/daq_move_plugins/daq_move_MockSampleChanger.py new file mode 100644 index 0000000..290fd9c --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/daq_move_plugins/daq_move_MockSampleChanger.py @@ -0,0 +1,18 @@ +"""Ontology demo: the cuvette holder of a simulated absorption bench (0 the blank cuvette, 1 the sample), see +``MockBeamBlock``""" +from pymodaq.control_modules.move_utility_classes import comon_parameters_fun, main, DataActuatorType + +from pymodaq_plugins_mockexamples.daq_move_plugins.daq_move_MockBeamBlock import DAQ_Move_MockBeamBlock + + +class DAQ_Move_MockSampleChanger(DAQ_Move_MockBeamBlock): + """Sets ``sample_position`` of the bench""" + _axis_names = ['Holder'] + attribute = 'sample_position' + + params = [] + comon_parameters_fun(axis_names=_axis_names, epsilon=DAQ_Move_MockBeamBlock._epsilons) + data_actuator_type = DataActuatorType.DataActuator + + +if __name__ == '__main__': + main(__file__) diff --git a/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectro.py b/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectro.py new file mode 100644 index 0000000..d30e0f9 --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectro.py @@ -0,0 +1,46 @@ +"""Ontology demo: the spectrometer of a simulated absorption bench, in counts on a wavelength axis in nm + +What it sees depends on the beam block (``MockBeamBlock``) and on the cuvette holder (``MockSampleChanger``), which +share the same simulated bench (``hardware/spectro_bench.py``). The module has a +neutral name in the experiments ``spectro_lab_a`` and ``spectro_lab_b``: what a spectrum means depends on the state of +the bench when it is taken, which is what the ontology describes. +""" +from pymodaq.control_modules.viewer_utility_classes import DAQ_Viewer_base, comon_parameters, main +from pymodaq.utils.data import DataFromPlugins, Axis +from pymodaq_data import DataToExport + +from pymodaq_plugins_mockexamples.hardware.spectro_bench import SpectroBench + + +class DAQ_1DViewer_MockSpectro(DAQ_Viewer_base): + """Counts of the spectrometer of the bench, on a wavelength axis in nm""" + params = comon_parameters + + def ini_attributes(self): + self.controller: SpectroBench = None + + def ini_detector(self, controller=None): + self.controller = SpectroBench.shared() + return 'Simulated spectrometer', True + + def close(self): + pass + + def commit_settings(self, param): + pass + + def grab_data(self, Naverage=1, **kwargs): + axis = Axis(data=self.controller.get_wavelength_axis(), label='wavelength', units='nm', index=0) + n = max(Naverage, 1) + spectrum = sum(self.controller.grab_spectrum() for _ in range(n)) / n + self.dte_signal.emit(DataToExport( + name='MockSpectro', + data=[DataFromPlugins(name='Spectrum', data=[spectrum], dim='Data1D', labels=['intensity'], + units='counts', axes=[axis])])) + + def stop(self): + pass + + +if __name__ == '__main__': + main(__file__) diff --git a/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroDark.py b/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroDark.py deleted file mode 100644 index 20f163c..0000000 --- a/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroDark.py +++ /dev/null @@ -1,14 +0,0 @@ -"""Ontology demo: the simulated spectrometer measuring the dark spectrum, see MockSpectroSample""" -from pymodaq.control_modules.viewer_utility_classes import main - -from pymodaq_plugins_mockexamples.daq_viewer_plugins.plugins_1D.daq_1Dviewer_MockSpectroSample import \ - DAQ_1DViewer_MockSpectroSample - - -class DAQ_1DViewer_MockSpectroDark(DAQ_1DViewer_MockSpectroSample): - """Counts of the dark measurement, on a wavelength axis in nm""" - kind = 'dark' - - -if __name__ == '__main__': - main(__file__) diff --git a/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroReference.py b/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroReference.py deleted file mode 100644 index 03e3f14..0000000 --- a/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroReference.py +++ /dev/null @@ -1,14 +0,0 @@ -"""Ontology demo: the simulated spectrometer measuring the reference spectrum, see MockSpectroSample""" -from pymodaq.control_modules.viewer_utility_classes import main - -from pymodaq_plugins_mockexamples.daq_viewer_plugins.plugins_1D.daq_1Dviewer_MockSpectroSample import \ - DAQ_1DViewer_MockSpectroSample - - -class DAQ_1DViewer_MockSpectroReference(DAQ_1DViewer_MockSpectroSample): - """Counts of the reference measurement, on a wavelength axis in nm""" - kind = 'reference' - - -if __name__ == '__main__': - main(__file__) diff --git a/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroSample.py b/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroSample.py deleted file mode 100644 index e43aeec..0000000 --- a/src/pymodaq_plugins_mockexamples/daq_viewer_plugins/plugins_1D/daq_1Dviewer_MockSpectroSample.py +++ /dev/null @@ -1,46 +0,0 @@ -"""Ontology demo: a simulated spectrometer looking at the lamp through a sample (the spectrum is in counts) - -The three plugins ``MockSpectroDark``, ``MockSpectroReference`` and ``MockSpectroSample`` are the same instrument -measuring a different thing. In the Dashboard the modules are given neutral names (experiments ``spectro_lab_a`` and -``spectro_lab_b``): it is the term assigned in the ontology manager that tells what each one measures. -""" -from pymodaq.control_modules.viewer_utility_classes import DAQ_Viewer_base, comon_parameters, main -from pymodaq.utils.data import DataFromPlugins, Axis -from pymodaq_data import DataToExport - -from pymodaq_plugins_mockexamples.hardware.mock_spectro import MockSpectro - - -class DAQ_1DViewer_MockSpectroSample(DAQ_Viewer_base): - """Counts of the lamp through the sample, on a wavelength axis in nm""" - kind = 'sample' - params = comon_parameters - - def ini_attributes(self): - self.controller: MockSpectro = None - - def ini_detector(self, controller=None): - self.controller = MockSpectro(self.kind) if self.is_master else controller - return f'Simulated spectrometer ({self.kind})', True - - def close(self): - if self.is_master and self.controller is not None: - self.controller.close() - - def commit_settings(self, param): - pass - - def grab_data(self, Naverage=1, **kwargs): - axis = Axis(data=self.controller.get_wavelength_axis(), label='wavelength', units='nm', index=0) - spectrum = sum(self.controller.grab_spectrum() for _ in range(max(Naverage, 1))) / max(Naverage, 1) - self.dte_signal.emit(DataToExport( - name=type(self).__name__, - data=[DataFromPlugins(name='Spectrum', data=[spectrum], dim='Data1D', labels=['intensity'], - units='counts', axes=[axis])])) - - def stop(self): - pass - - -if __name__ == '__main__': - main(__file__) diff --git a/src/pymodaq_plugins_mockexamples/extensions/ontology_logger.py b/src/pymodaq_plugins_mockexamples/extensions/ontology_logger.py deleted file mode 100644 index 398f206..0000000 --- a/src/pymodaq_plugins_mockexamples/extensions/ontology_logger.py +++ /dev/null @@ -1,111 +0,0 @@ -"""Demo extension: a DAQ_Logger whose saved data carry the terms of an ontology - -It shows how an extension works with the ``OntologyManager`` of the ``pymodaq_ontology`` package: - -* the manager lives in the Dashboard (menu *Ontology*): the user assigns a term to each channel of the instruments -* the extension asks the manager to annotate the data saved by its worker (``attach_worker``): the ``semantic_iri`` - extra attribute is written with the data -* it gives the manager a small ontology of its own (``resources/ontology/basic_ontology.ttl``) if none was loaded yet -* the terms know what they are a kind of (``broader``): choose a concept, for instance *Optical signal*, and the - action *Select the channels of the concept* selects the instruments with a channel whose term is that concept or - a kind of it (a *Photodiode signal* is an *Optical signal*), whatever the instruments are called - -Without ``pymodaq_ontology`` the extension is a plain logger and says so. -""" -from pathlib import Path -from typing import Optional, TYPE_CHECKING - -from pymodaq_utils.logger import set_logger, get_module_name - -from pymodaq.extensions.daq_logger.daq_logger import DAQLogger -from pymodaq_gui.utils.dock import DockArea - -if TYPE_CHECKING: - from pymodaq.dashboard import DashBoard - -logger = set_logger(get_module_name(__file__)) - -EXTENSION_NAME = 'Ontology Logger' # displayed in the Extensions menu of the Dashboard -CLASS_NAME = 'OntologyLogger' # the name of the class below - -TERMS_FILE = Path(__file__).parent.parent.joinpath('resources', 'ontology', 'basic_ontology.ttl') - - -class OntologyLogger(DAQLogger): - """A logger annotating what it saves with the terms assigned in the ontology manager of the Dashboard""" - h5_base_group_name = 'OntologyLogger' - params = DAQLogger.params + [ - {'title': 'Concept:', 'name': 'concept', 'type': 'list', 'limits': {}}, # label -> IRI, filled by the manager - ] - - def __init__(self, dockarea: DockArea = None, dashboard: 'DashBoard' = None): - super().__init__(dockarea, dashboard) - self.ontology_manager = getattr(dashboard, 'extra_managers', {}).get('ontology') - if self.ontology_manager is None: - self.update_status('pymodaq_ontology is not installed: the data are saved without annotation') - return - if self.ontology_manager.source is None: - self._load_basic_ontology() - self._update_concepts() - self.ontology_manager.attach_worker(self.logging) - - def setup_actions(self): - super().setup_actions() - self.add_action('select_concept', 'Select the channels of the concept', 'hub', - tip='Select the instruments with a channel whose term is the concept or a kind of it') - - def connect_things(self): - super().connect_things() - self.connect_action('select_concept', self.select_channels_of_concept) - - def _update_concepts(self) -> None: - """The terms of the ontology that have kinds (the concepts), by label""" - hierarchy = self.ontology_manager.hierarchy - concepts = {term.label: iri for iri, term in hierarchy.terms.items() if hierarchy.children(iri)} - self.settings.child('concept').setLimits(concepts) - - def select_channels_of_concept(self) -> str: - """Select the instruments with a channel of the chosen concept. Returns what was done, as text""" - manager = self.ontology_manager - if manager is None or not self.settings['concept']: - message = 'No concept to select' - else: - manager.update_channels_from_dashboard() - manager.probe() # the channels of the detectors are found by a snap - channels = manager.channels_of_concept(self.settings['concept']) - detectors = sorted({c.module for c in channels if c.kind == 'detector'}) - actuators = sorted({c.module for c in channels if c.kind == 'actuator'}) - self.modules_manager.selected_detectors_name = detectors - self.modules_manager.selected_actuators_name = actuators - label = manager.terms[self.settings['concept']].label - message = f'{len(channels)} channels of "{label}": detectors {detectors}, actuators {actuators}' - self.update_status(message) - return message - - def _load_basic_ontology(self, path: Optional[Path] = None) -> None: - from pymodaq_ontology.source_factory import SourceFactory - self.ontology_manager.set_source(SourceFactory.create('rdf', str(path or TERMS_FILE))) - - def _quit_fun(self) -> bool: - can_quit = super()._quit_fun() - if can_quit and self.ontology_manager is not None: - self.ontology_manager.detach_worker(self.logging) - return can_quit - - -def main(): - """Run the extension on its own (the Dashboard stays hidden), see ``-x EXPERIMENT_NAME -s STATE_NAME``""" - import sys - from pymodaq_gui.qt_utils import mkQApp - from pymodaq.dashboard import load_dashboard_with_arguments - from pymodaq.utils.gui_utils.loader_utils import create_extension - - app = mkQApp('Ontology Logger') - win, dashboard, _ = load_dashboard_with_arguments(show_dashboard=False, load_extension=False) - win.mainwindow.setVisible(False) - win_ext, ext = create_extension(dashboard, OntologyLogger, show_extension=True) - sys.exit(app.exec()) - - -if __name__ == '__main__': - main() diff --git a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py index 2235141..0340e77 100644 --- a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py +++ b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py @@ -1,16 +1,17 @@ -"""Demo extension: what the terms of the channels let the experiment do, whatever the instruments are called +"""Demo extension: what the terms of the channels let the experiment do, whatever the modules are called -It uses the ``OntologyManager`` of the ``pymodaq_ontology`` package (menu *Ontology* of the Dashboard). The user assigns -a term to the channels of the instruments (for instance *Dark spectrum*, *Reference spectrum*, *Sample spectrum*), and -the extension, which never reads the names of the modules, can then: +It uses the ``OntologyManager`` of the ``pymodaq_ontology`` package (menu *Ontology* of the Dashboard). The bench of the +experiments ``spectro_lab_a`` and ``spectro_lab_b`` is one spectrometer, a beam block and a cuvette holder, with neutral +module names. The user assigns a term to each of them (*Spectrum* to the spectrometer, *Beam block* and *Cuvette holder* +to the actuators) and the extension, which never reads the names of the modules, can then: -* tell what can be **computed** from the terms (the ontology says that a *Transmittance* is derived from the sample, the - reference and the dark spectra, and an *Absorbance* from the transmittance), and what is **missing** if it cannot; -* compute and show it live, with the formulas coded here; -* check that what the channels give has the **unit** the term expects (counts for a spectrum). - -Try it with the experiments ``spectro_lab_a`` and ``spectro_lab_b``: the same three simulated spectrometers with -different names. Assign the terms in each one, the extension works the same. +* tell what it can **measure**: the ontology says in which state of the bench a spectrum is a *Dark spectrum* (beam + blocked), a *Reference spectrum* (beam open, blank cuvette) or a *Sample spectrum*; the extension finds the actuators + by their terms and what is missing if one cannot be found; +* tell what it can then **compute** (a *Transmittance* is derived from the three spectra, an *Absorbance* from the + transmittance) and run the whole protocol: set the bench, grab, three times, then compute and show, with the formulas + coded here; +* check that what a channel gives has the **unit** its term expects (counts for a spectrum). Without ``pymodaq_ontology`` the extension tells that it cannot work. """ @@ -29,10 +30,12 @@ from pymodaq_gui import utils as gutils from pymodaq_gui.plotting.data_viewers import ViewerDispatcher +from pymodaq.control_modules.enums import MoveType from pymodaq.utils.custom_ext import CustomExt +from pymodaq.utils.data import DataActuator from pymodaq.utils.managers.modules import ModuleType -from pymodaq_plugins_mockexamples.ontology_derivations import Derivations, MOCK +from pymodaq_plugins_mockexamples.ontology_derivations import Derivations, MOCK, Step logger = set_logger(get_module_name(__file__)) @@ -45,7 +48,6 @@ class SpectroConcepts(CustomExt): params = [ - {'title': 'Average:', 'name': 'average', 'type': 'int', 'value': 1, 'min': 1}, {'title': 'Status:', 'name': 'status', 'type': 'str', 'value': 'Idle', 'readonly': True}, ] @@ -53,6 +55,7 @@ def __init__(self, parent: gutils.DockArea, dashboard): super().__init__(parent, dashboard) self.ontology_manager = getattr(dashboard, 'extra_managers', {}).get('ontology') self._busy = False + self._queue, self._results, self._problems, self._step, self._axis = [], {}, [], None, None self.derivations: Optional[Derivations] = None self.setup_ui() if self.ontology_manager is None: @@ -74,13 +77,14 @@ def setup_menus_and_toolbars(self, menubar: QtWidgets.QMenuBar = None): self.create_dashboard_toolbar(add_break=False) def setup_actions(self): - self.add_action('check', 'What can I compute?', 'help', - tip='Tell what the terms of the channels allow, without acquiring') - self.add_action('grab', 'Grab and compute', 'camera', tip='Grab all the detectors, compute and show') + self.add_action('check', 'What can I measure?', 'help', + tip='Tell what the terms of the channels allow to measure and compute, without acquiring') + self.add_action('run', 'Measure and compute', 'camera', + tip='Set the bench for each measurement, grab, then compute and show') def connect_things(self): self.connect_action('check', self.show_what_is_possible) - self.connect_action('grab', self.grab_and_compute) + self.connect_action('run', self.run_protocol) self.modules_manager.timeout_signal.connect(self._on_timeout) def _load_spectro_ontology(self) -> None: @@ -88,15 +92,15 @@ def _load_spectro_ontology(self) -> None: self.ontology_manager.set_source(SourceFactory.create('rdf', str(TERMS_FILE))) # ---- the ontology side: terms of the channels - def terms_of_detectors(self) -> dict[str, str]: - """Term assigned to each channel of the detectors, by channel key""" + def terms_of(self, kind: str) -> dict[str, str]: + """Term assigned to each channel of the detectors or of the actuators, by channel key""" manager = self.ontology_manager manager.update_channels_from_dashboard() - return {c.key: manager.assignment.get(c.key) for c in manager.channels if c.kind == 'detector' + return {c.key: manager.assignment.get(c.key) for c in manager.channels if c.kind == kind and manager.assignment.get(c.key)} def _derivations(self) -> Optional[Derivations]: - """The derivations declared by the ontology of the manager (read again if the source changed)""" + """The statements of the ontology of the manager (read again if the source changed)""" graph = getattr(self.ontology_manager.source, 'graph', None) if graph is None: return None @@ -108,54 +112,91 @@ def _label(self, iri: str) -> str: term = self.ontology_manager.terms.get(iri) return term.label if term else iri + def make_plan(self) -> tuple[list[Step], dict[str, list[str]], Optional[Derivations]]: + derivations = self._derivations() + if derivations is None: + return [], {}, None + detector_terms = set(self.terms_of('detector').values()) + actuator_terms = {key: iri for key, iri in self.terms_of('actuator').items()} # the key is the module + steps, problems = derivations.plan(detector_terms, actuator_terms) + return steps, problems, derivations + def show_what_is_possible(self) -> str: - """Say what can be computed from the terms assigned to the channels (without acquiring). Returns the text""" + """Say what can be measured and computed with the terms assigned to the channels (without acquiring)""" if self.ontology_manager is None: text = 'pymodaq_ontology is not installed' else: - derivations = self._derivations() - assigned = self.terms_of_detectors() - terms = {iri: None for iri in assigned.values()} + steps, problems, derivations = self.make_plan() if derivations is None: text = 'The ontology loaded in the manager has no graph: load an RDF ontology' else: - text = self._describe(assigned, derivations.computable(terms), derivations.missing(terms)) + text = self._describe(steps, problems, derivations) self.what.setPlainText(text) self.set_status(text.splitlines()[0] if text else 'Idle') return text - def _describe(self, assigned: dict[str, str], computable: list[str], missing: dict[str, list[str]]) -> str: + def _describe(self, steps: list[Step], problems: dict[str, list[str]], derivations: Derivations) -> str: lines = [] - if computable: - lines.append('Can compute: ' + ', '.join(self._label(i) for i in computable)) + if steps: + lines.append('Can measure: ' + ', '.join(self._label(step.term) for step in steps)) else: - lines.append('Nothing can be computed yet') - for output, inputs in missing.items(): - lines.append(f'{self._label(output)} needs: ' + ', '.join(self._label(i) for i in inputs)) - lines.append('') - lines.append('Channels with a term:') - lines.extend(f' {key} -> {self._label(iri)}' for key, iri in assigned.items()) + lines.append('Nothing can be measured yet (assign a term to the spectrometer and to the actuators)') + for step in steps: + lines.append(f' {self._label(step.term)}: ' + ', '.join(f'{module} = {value:g}' + for module, value in step.moves)) + for term, controls in problems.items(): + lines.append(f'{self._label(term)} needs an actuator with the term: ' + + ', '.join(self._label(c) for c in controls)) + available = {step.term: None for step in steps} + computable = derivations.computable(available) + if computable: + lines.append('Then can compute: ' + ', '.join(self._label(i) for i in computable)) return '\n'.join(lines) - # ---- acquisition - def grab_and_compute(self): + # ---- the protocol: set the bench, grab, for each measurement + def run_protocol(self): if self._busy or self.ontology_manager is None: return - self.modules_manager.selected_detectors_name = self.modules_manager.detectors_name - self._busy = True - self.set_action_enabled('grab', False) - self.set_status('Grabbing') + steps, problems, derivations = self.make_plan() + if not steps or problems: + self.show_what_is_possible() + return + self._queue, self._results, self._problems, self._busy = list(steps), {}, [], True + self.set_action_enabled('run', False) + self._next_step() + + def _next_step(self): + if not self._queue: + self._finish() + return + self._step = self._queue.pop(0) + self.set_status(f'Measuring {self._label(self._step.term)}') + detectors = sorted({c.module for c in self.ontology_manager.channels if c.kind == 'detector' + and self.ontology_manager.assignment.get(c.key)}) + self.modules_manager.selected_actuators_name = [module for module, _ in self._step.moves] + self.modules_manager.selected_detectors_name = detectors + target = DataToExport('target', data=[ + DataActuator(module, data=value, units=self.modules_manager.get_mod_from_name( + module, ModuleType.Actuator).units) for module, value in self._step.moves]) + self.modules_manager.move_actuators_with_callback(target, mode=MoveType.ABS, callback=self._on_move_done) + + def _on_move_done(self, positions: DataToExport): + self.modules_manager.forget_callback(self._on_move_done, ModuleType.Actuator) self.modules_manager.grab_data_with_callback(callback=self._on_data) def _on_data(self, data: DataToExport): self.modules_manager.forget_callback(self._on_data, ModuleType.Detector) - try: - self.compute_and_show(data) - finally: - self._busy = False - self.set_action_enabled('grab', True) - - def arrays_by_term(self, data: DataToExport) -> tuple[dict[str, np.ndarray], list[str], list]: + arrays, problems, axis = self.arrays_by_term(data) + # the channel with the general term (Spectrum) gives the spectrum of the measurement (Dark spectrum...) + derivations = self._derivations() + spectrum = next((array for term, array in arrays.items() if derivations.is_a(self._step.term, term)), None) + if spectrum is not None: + self._results[self._step.term] = spectrum + self._axis = axis + self._problems.extend(p for p in problems if p not in self._problems) + self._next_step() + + def arrays_by_term(self, data: DataToExport) -> tuple[dict[str, np.ndarray], list[str], object]: """The array of each term assigned to a channel of the data, the unit problems and the axis of the first one""" from pymodaq_ontology.channels import Channel from pymodaq_ontology.terms import DETECTOR @@ -178,26 +219,27 @@ def arrays_by_term(self, data: DataToExport) -> tuple[dict[str, np.ndarray], lis problems.append(f'{key}: {dwa.units} where {self._label(iri)} expects {expected}') return arrays, problems, axis - def compute_and_show(self, data: DataToExport) -> None: + def _finish(self): derivations = self._derivations() - if derivations is None: - self.set_status('No RDF ontology loaded in the manager') - return - arrays, problems, axis = self.arrays_by_term(data) - results = derivations.compute(arrays) - computed = [DataCalculated(self._label(iri), data=[array], axes=[axis] if axis is not None else [], + results = derivations.compute(self._results) + measured = [DataCalculated(self._label(iri), data=[array], axes=[self._axis] if self._axis is not None else [], + labels=[self._label(iri)], units='counts') for iri, array in self._results.items()] + computed = [DataCalculated(self._label(iri), data=[array], axes=[self._axis] if self._axis is not None else [], labels=[self._label(iri)]) for iri, array in results.items()] - self.viewer.show_data(DataToExport('spectro', data=[*data, *computed])) - lines = [self._describe(self.terms_of_detectors(), derivations.computable(arrays), - derivations.missing(arrays))] - lines.extend(f'Unit: {p}' for p in problems) + self.viewer.show_data(DataToExport('spectro', data=[*measured, *computed])) + lines = ['Measured: ' + ', '.join(self._label(i) for i in self._results), + 'Computed: ' + (', '.join(self._label(i) for i in results) or 'nothing')] + lines.extend(f'Unit: {p}' for p in self._problems) self.what.setPlainText('\n'.join(lines)) - self.set_status(lines[0].splitlines()[0]) + self.set_status(lines[1]) + self._busy = False + self.set_action_enabled('run', True) def _on_timeout(self, missing_modules: list): - self.modules_manager.forget_callback(self._on_data, ModuleType.Control) + for callback in (self._on_move_done, self._on_data): + self.modules_manager.forget_callback(callback, ModuleType.Control) self._busy = False - self.set_action_enabled('grab', True) + self.set_action_enabled('run', True) self.set_status(f'Timeout: {", ".join(missing_modules)}') def set_status(self, status: str): diff --git a/src/pymodaq_plugins_mockexamples/hardware/mock_spectro.py b/src/pymodaq_plugins_mockexamples/hardware/mock_spectro.py deleted file mode 100644 index 5b217d2..0000000 --- a/src/pymodaq_plugins_mockexamples/hardware/mock_spectro.py +++ /dev/null @@ -1,43 +0,0 @@ -"""A simulated spectrophotometer measuring, in counts, the dark, the lamp (reference) or the lamp through a sample - -The sample absorbs around 550 nm: its transmittance is about 0.9 away from the band and drops to 0.2 at the centre. -Used by the plugins ``MockSpectroDark``, ``MockSpectroReference`` and ``MockSpectroSample`` of the ontology demo. -""" -import numpy as np - -KINDS = ('dark', 'reference', 'sample') -WAVELENGTHS = np.linspace(400., 800., 400) # nm -DARK_LEVEL = 100. # counts -LAMP_MAX = 20000. # counts at the maximum of the lamp spectrum - - -def lamp_spectrum() -> np.ndarray: - """Counts of the lamp alone, without the dark level""" - return LAMP_MAX * np.exp(-((WAVELENGTHS - 600.) / 200.) ** 2) - - -def transmittance_of_sample() -> np.ndarray: - """Fraction of the light that goes through the sample""" - return 0.9 - 0.7 * np.exp(-((WAVELENGTHS - 550.) / 30.) ** 2) - - -class MockSpectro: - """Spectra in counts of the kind asked ('dark', 'reference' or 'sample'), with a little noise""" - - def __init__(self, kind: str): - if kind not in KINDS: - raise ValueError(f'kind must be one of {KINDS}, not {kind}') - self.kind = kind - self._rng = np.random.default_rng() - - def get_wavelength_axis(self) -> np.ndarray: - return WAVELENGTHS.copy() - - def grab_spectrum(self) -> np.ndarray: - signal = {'dark': np.zeros_like(WAVELENGTHS), 'reference': lamp_spectrum(), - 'sample': lamp_spectrum() * transmittance_of_sample()}[self.kind] - counts = DARK_LEVEL + signal - return counts + self._rng.normal(0., 1., counts.shape) * np.sqrt(counts) * 0.2 - - def close(self) -> None: - pass diff --git a/src/pymodaq_plugins_mockexamples/hardware/spectro_bench.py b/src/pymodaq_plugins_mockexamples/hardware/spectro_bench.py new file mode 100644 index 0000000..03b8579 --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/hardware/spectro_bench.py @@ -0,0 +1,61 @@ +"""A simulated absorption bench: a lamp, a beam block, a cuvette holder and one spectrometer + +What the spectrometer measures depends on the two actuators of the bench, as on a real one: + +* the beam block (1: the light is blocked, the spectrometer sees only its dark level; 0: the beam goes through) +* the cuvette holder (0: the blank cuvette, the spectrometer sees the lamp; 1: the cuvette with the sample, which + absorbs around 550 nm: its transmittance is about 0.9 away from the band and 0.2 at its centre) + +Used by the plugins ``MockBeamBlock``, ``MockSampleChanger`` (actuators) and ``MockSpectro`` (the spectrometer) of the +ontology demo, as in the experiments ``spectro_lab_a`` and ``spectro_lab_b``. The three modules share the one bench of the +process (:meth:`SpectroBench.shared`): it is a simulation, a real bench would be one controller shared by its modules. +""" +import numpy as np + +WAVELENGTHS = np.linspace(400., 800., 400) # nm +DARK_LEVEL = 100. # counts +LAMP_MAX = 20000. # counts at the maximum of the lamp spectrum + + +def lamp_spectrum() -> np.ndarray: + """Counts of the lamp alone, without the dark level""" + return LAMP_MAX * np.exp(-((WAVELENGTHS - 600.) / 200.) ** 2) + + +def transmittance_of_sample() -> np.ndarray: + """Fraction of the light that goes through the sample""" + return 0.9 - 0.7 * np.exp(-((WAVELENGTHS - 550.) / 30.) ** 2) + + +class SpectroBench: + """The bench: set ``beam_block`` and ``sample_position``, then read a spectrum, in counts, with a little noise""" + + _shared: 'SpectroBench' = None + + @classmethod + def shared(cls) -> 'SpectroBench': + """The bench used by all the modules of the process""" + if cls._shared is None: + cls._shared = cls() + return cls._shared + + def __init__(self): + self.beam_block = 0. # 1: the beam is blocked + self.sample_position = 0. # 1: the cuvette with the sample is in the beam, 0: the blank one + self._rng = np.random.default_rng() + + def get_wavelength_axis(self) -> np.ndarray: + return WAVELENGTHS.copy() + + def grab_spectrum(self) -> np.ndarray: + if self.beam_block >= 0.5: + signal = np.zeros_like(WAVELENGTHS) + elif self.sample_position >= 0.5: + signal = lamp_spectrum() * transmittance_of_sample() + else: + signal = lamp_spectrum() + counts = DARK_LEVEL + signal + return counts + self._rng.normal(0., 1., counts.shape) * np.sqrt(counts) * 0.2 + + def close(self) -> None: + pass diff --git a/src/pymodaq_plugins_mockexamples/ontology_derivations.py b/src/pymodaq_plugins_mockexamples/ontology_derivations.py index 8cbfa6d..2a43eb0 100644 --- a/src/pymodaq_plugins_mockexamples/ontology_derivations.py +++ b/src/pymodaq_plugins_mockexamples/ontology_derivations.py @@ -1,12 +1,14 @@ -"""What can be computed from the terms of the channels: the derivations declared by an ontology - -The ontology says that a term is ``mock:derivedFrom`` other terms (``Transmittance`` from the sample, the reference and -the dark spectra). This module reads these statements in the RDF graph and, given the arrays of the channels that have -a term, tells what can be computed, what is missing, and computes it. It knows nothing about the instruments: it works -on terms. A channel whose term is a kind of the input (a ``SampleSpectrum`` is a ``Spectrum``) is accepted wherever the -input is that more general term. +"""What the terms of the channels let the experiment do: the statements of an ontology about measuring and computing + +The ontology says in which states of the bench a spectrum has a meaning (``mock:requires``: the dark spectrum with the +beam blocked...) and that a term is ``mock:derivedFrom`` other terms (``Transmittance`` from the sample, the reference +and the dark spectra). This module reads these statements in the RDF graph and, given the terms of the channels and of +the actuators, plans the measurements to do, tells what can be computed and what is missing, and computes it. It +knows nothing about the instruments: it works on terms. A term that is a kind of the wanted one (a ``SampleSpectrum`` +is a ``Spectrum``) is accepted wherever the wanted one is asked. """ -from typing import Callable, Optional +from dataclasses import dataclass +from typing import Callable, Iterable, Optional import numpy as np from rdflib import Graph, Namespace, URIRef @@ -34,6 +36,13 @@ def _absorbance(inputs: dict[str, np.ndarray]) -> np.ndarray: } +@dataclass +class Step: + """A measurement of the protocol: what the spectrum will mean and the controls to set before grabbing it""" + term: str + moves: list # (actuator module, value) + + class Derivations: """The derivations of an ontology graph @@ -52,6 +61,44 @@ def __init__(self, graph: Graph, is_a: Callable[[str, str], bool]): for output in set(graph.subjects(MOCK.derivedFrom, None)): self.rules[str(output)] = sorted(str(i) for i in graph.objects(output, MOCK.derivedFrom) if isinstance(i, URIRef)) + self.requirements: dict[str, list[tuple[str, float]]] = {} # measurement term -> (control term, value) + for term in set(graph.subjects(MOCK.requires, None)): + self.requirements[str(term)] = sorted( + (str(graph.value(state, MOCK.control)), float(graph.value(state, MOCK.value))) + for state in graph.objects(term, MOCK.requires)) + + def plan(self, detector_terms: Iterable[str], actuator_terms: dict[str, str] + ) -> tuple[list[Step], dict[str, list[str]]]: + """The measurements that the channels can make and what blocks the others + + Parameters + ---------- + detector_terms: the terms assigned to the channels of the detectors; a channel can make the measurements that are + kinds of its term (a channel with the term *Spectrum* can measure the dark, the reference and the sample) + actuator_terms: the term assigned to each actuator, by module name + + Returns + ------- + the steps (the measurement and the moves to do first), and for the measurements that cannot be made the controls + for which no actuator has a term + """ + detector_terms = list(detector_terms) + steps, problems = [], {} + for measurement in sorted(self.requirements): + if not any(self.is_a(measurement, term) for term in detector_terms): + continue + moves, missing = [], [] + for control, value in self.requirements[measurement]: + module = next((m for m, term in sorted(actuator_terms.items()) if self.is_a(term, control)), None) + if module is None: + missing.append(control) + else: + moves.append((module, value)) + if missing: + problems[measurement] = sorted(set(missing)) + else: + steps.append(Step(measurement, moves)) + return steps, problems def _provider(self, wanted: str, available: dict[str, np.ndarray]) -> Optional[str]: """The available term standing for the wanted one: the same or a kind of it""" diff --git a/src/pymodaq_plugins_mockexamples/resources/ontology/basic_ontology.ttl b/src/pymodaq_plugins_mockexamples/resources/ontology/basic_ontology.ttl deleted file mode 100644 index d316eb1..0000000 --- a/src/pymodaq_plugins_mockexamples/resources/ontology/basic_ontology.ttl +++ /dev/null @@ -1,34 +0,0 @@ -@prefix mock: . -@prefix owl: . -@prefix rdfs: . -@prefix skos: . -@prefix sosa: . - -# A basic ontology for the mock instruments, read by the "rdf" source of pymodaq_ontology. -# The IRIs are examples (the namespace is not published): replace them by the ones of a real ontology. -# ``rdfs:subClassOf`` says what a term is a kind of: the Ontology Logger uses it to find the channels of a concept. -# A term that is a kind of sosa:ObservableProperty is meant for detectors, of sosa:ActuatableProperty for actuators. - -mock:Signal a owl:Class ; rdfs:subClassOf sosa:ObservableProperty ; - rdfs:label "Signal"@en ; skos:definition "Any signal measured by a detector."@en . - -mock:OpticalSignal a owl:Class ; rdfs:subClassOf mock:Signal ; - rdfs:label "Optical signal"@en ; skos:definition "A signal produced by light."@en . - -mock:Photodiode a owl:Class ; rdfs:subClassOf mock:OpticalSignal ; - rdfs:label "Photodiode signal"@en ; skos:definition "Voltage delivered by a photodiode."@en . - -mock:Spectrum a owl:Class ; rdfs:subClassOf mock:OpticalSignal ; - rdfs:label "Spectrum"@en ; skos:definition "Intensity as a function of the wavelength."@en . - -mock:Temperature a owl:Class ; rdfs:subClassOf mock:Signal ; - rdfs:label "Temperature"@en ; skos:definition "Temperature of the sample or of the setup."@en . - -mock:Control a owl:Class ; rdfs:subClassOf sosa:ActuatableProperty ; - rdfs:label "Control"@en ; skos:definition "Anything the experiment sets."@en . - -mock:Position a owl:Class ; rdfs:subClassOf mock:Control ; - rdfs:label "Position"@en ; skos:definition "Position of a moving stage."@en . - -mock:Wavelength a owl:Class ; rdfs:subClassOf mock:Control ; - rdfs:label "Wavelength"@en ; skos:definition "Wavelength selected by a monochromator or a laser."@en . diff --git a/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl b/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl index 1a6a104..fbd5993 100644 --- a/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl +++ b/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl @@ -11,11 +11,17 @@ # mock:quantity the physical quantity ("intensity", "ratio"...) # mock:unit its unit ("counts", "1" for a pure number) # mock:derivedFrom the terms it is computed from; mock:formula tells how (documentation, the code is in the extension) +# mock:requires the states of the bench in which a spectrum has this meaning: the same spectrometer gives the +# dark spectrum with the beam blocked, the reference with the blank cuvette, the sample with the +# sample cuvette. A state says which control it is a value of (mock:control) and which one (mock:value). mock:quantity a owl:AnnotationProperty ; rdfs:label "quantity"@en . mock:unit a owl:AnnotationProperty ; rdfs:label "unit"@en . mock:formula a owl:AnnotationProperty ; rdfs:label "formula"@en . mock:derivedFrom a owl:ObjectProperty ; rdfs:label "derived from"@en . +mock:requires a owl:ObjectProperty ; rdfs:label "requires"@en . +mock:control a owl:AnnotationProperty ; rdfs:label "control"@en . +mock:value a owl:AnnotationProperty ; rdfs:label "value"@en . mock:Signal a owl:Class ; rdfs:subClassOf sosa:ObservableProperty ; rdfs:label "Signal"@en ; skos:definition "Any signal measured by a detector."@en . @@ -25,13 +31,16 @@ mock:Spectrum a owl:Class ; rdfs:subClassOf mock:Signal ; mock:quantity "intensity" ; mock:unit "counts" . mock:DarkSpectrum a owl:Class ; rdfs:subClassOf mock:Spectrum ; - rdfs:label "Dark spectrum"@en ; skos:definition "Spectrum with no light: the offset of the detector."@en . + rdfs:label "Dark spectrum"@en ; skos:definition "Spectrum with no light: the offset of the detector."@en ; + mock:requires mock:BeamBlocked . mock:ReferenceSpectrum a owl:Class ; rdfs:subClassOf mock:Spectrum ; - rdfs:label "Reference spectrum"@en ; skos:definition "Spectrum of the lamp alone, without the sample."@en . + rdfs:label "Reference spectrum"@en ; skos:definition "Spectrum of the lamp alone, without the sample."@en ; + mock:requires mock:BeamOpen , mock:BlankInBeam . mock:SampleSpectrum a owl:Class ; rdfs:subClassOf mock:Spectrum ; - rdfs:label "Sample spectrum"@en ; skos:definition "Spectrum of the lamp after the sample."@en . + rdfs:label "Sample spectrum"@en ; skos:definition "Spectrum of the lamp after the sample."@en ; + mock:requires mock:BeamOpen , mock:SampleInBeam . mock:Transmittance a owl:Class ; rdfs:subClassOf mock:Signal ; rdfs:label "Transmittance"@en ; skos:definition "Fraction of the light that goes through the sample."@en ; @@ -48,6 +57,14 @@ mock:Absorbance a owl:Class ; rdfs:subClassOf mock:Signal ; mock:Control a owl:Class ; rdfs:subClassOf sosa:ActuatableProperty ; rdfs:label "Control"@en ; skos:definition "Anything the experiment sets."@en . -mock:Wavelength a owl:Class ; rdfs:subClassOf mock:Control ; - rdfs:label "Wavelength"@en ; skos:definition "Wavelength selected by a monochromator or a laser."@en ; - mock:quantity "length" ; mock:unit "nm" . +mock:BeamBlock a owl:Class ; rdfs:subClassOf mock:Control ; + rdfs:label "Beam block"@en ; skos:definition "Blocks the beam (1) or lets it through (0)."@en . + +mock:SampleHolder a owl:Class ; rdfs:subClassOf mock:Control ; + rdfs:label "Cuvette holder"@en ; skos:definition "Puts the blank cuvette (0) or the cuvette with the sample (1) in the beam."@en . + +# the states of the controls (not terms to assign: they are what the terms above require) +mock:BeamBlocked mock:control mock:BeamBlock ; mock:value 1 ; rdfs:label "beam blocked" . +mock:BeamOpen mock:control mock:BeamBlock ; mock:value 0 ; rdfs:label "beam open" . +mock:BlankInBeam mock:control mock:SampleHolder ; mock:value 0 ; rdfs:label "blank cuvette in the beam" . +mock:SampleInBeam mock:control mock:SampleHolder ; mock:value 1 ; rdfs:label "sample cuvette in the beam" . diff --git a/src/pymodaq_plugins_mockexamples/resources/spectro_lab_a.xml b/src/pymodaq_plugins_mockexamples/resources/spectro_lab_a.xml index c105a63..cf89ff7 100644 --- a/src/pymodaq_plugins_mockexamples/resources/spectro_lab_a.xml +++ b/src/pymodaq_plugins_mockexamples/resources/spectro_lab_a.xml @@ -1 +1 @@ -Det_1MockSpectroDarkDAQ1D1str('Master')4100Det_2MockSpectroReferenceDAQ1D1str('Master')4101Det_3MockSpectroSampleDAQ1D1str('Master')4102 +Act_1MockBeamBlockstr('Simple')1str('Master')4101str('Block')Act_2MockSampleChangerstr('Simple')1str('Master')4102str('Holder')Det_1MockSpectroDAQ1D1str('Master')4103 diff --git a/src/pymodaq_plugins_mockexamples/resources/spectro_lab_b.xml b/src/pymodaq_plugins_mockexamples/resources/spectro_lab_b.xml index 3ee7abe..02a3dc0 100644 --- a/src/pymodaq_plugins_mockexamples/resources/spectro_lab_b.xml +++ b/src/pymodaq_plugins_mockexamples/resources/spectro_lab_b.xml @@ -1 +1 @@ -S1MockSpectroSampleDAQ1D1str('Master')4100S2MockSpectroDarkDAQ1D1str('Master')4101S3MockSpectroReferenceDAQ1D1str('Master')4102 +M2MockBeamBlockstr('Simple')1str('Master')4201str('Block')M1MockSampleChangerstr('Simple')1str('Master')4202str('Holder')SpectroMockSpectroDAQ1D1str('Master')4203 diff --git a/tests/test_ontology_derivations.py b/tests/test_ontology_derivations.py index b3c43b8..1681c5d 100644 --- a/tests/test_ontology_derivations.py +++ b/tests/test_ontology_derivations.py @@ -1,4 +1,4 @@ -"""What can be computed from the terms: the derivations declared by the spectro ontology (no GUI needed)""" +"""What the terms let the experiment do: the statements of the spectro ontology (no GUI needed)""" import numpy as np import pytest @@ -8,12 +8,13 @@ from pymodaq_ontology.terms import TermHierarchy from pymodaq_plugins_mockexamples.extensions.spectro_concepts import TERMS_FILE -from pymodaq_plugins_mockexamples.hardware.mock_spectro import (MockSpectro, WAVELENGTHS, lamp_spectrum, - transmittance_of_sample, DARK_LEVEL) -from pymodaq_plugins_mockexamples.ontology_derivations import (Derivations, SAMPLE, REFERENCE, DARK, TRANSMITTANCE, - ABSORBANCE) +from pymodaq_plugins_mockexamples.hardware.spectro_bench import (SpectroBench, WAVELENGTHS, transmittance_of_sample, + DARK_LEVEL) +from pymodaq_plugins_mockexamples.ontology_derivations import (Derivations, Step, SAMPLE, REFERENCE, DARK, + TRANSMITTANCE, ABSORBANCE) NS = 'http://example.org/mockexamples#' +SPECTRUM, BEAM_BLOCK, HOLDER = NS + 'Spectrum', NS + 'BeamBlock', NS + 'SampleHolder' @pytest.fixture @@ -24,8 +25,12 @@ def derivations(): def spectra(): - return {iri: MockSpectro(kind).grab_spectrum() for iri, kind in - ((SAMPLE, 'sample'), (REFERENCE, 'reference'), (DARK, 'dark'))} + bench = SpectroBench() + out = {} + for iri, (block, sample) in ((DARK, (1, 0)), (REFERENCE, (0, 0)), (SAMPLE, (0, 1))): + bench.beam_block, bench.sample_position = block, sample + out[iri] = bench.grab_spectrum() + return out def test_the_ontology_declares_the_derivations(derivations): @@ -33,6 +38,30 @@ def test_the_ontology_declares_the_derivations(derivations): assert derivations.rules[ABSORBANCE] == [TRANSMITTANCE] +def test_the_ontology_declares_the_state_of_the_bench_for_each_measurement(derivations): + assert derivations.requirements[DARK] == [(BEAM_BLOCK, 1.)] + assert derivations.requirements[REFERENCE] == [(BEAM_BLOCK, 0.), (HOLDER, 0.)] + assert derivations.requirements[SAMPLE] == [(BEAM_BLOCK, 0.), (HOLDER, 1.)] + + +def test_the_plan_finds_the_actuators_by_their_terms(derivations): + """A spectrometer and two actuators with names that say nothing""" + steps, problems = derivations.plan([SPECTRUM], {'M2': BEAM_BLOCK, 'M1': HOLDER}) + assert problems == {} + assert steps == [Step(DARK, [('M2', 1.)]), Step(REFERENCE, [('M2', 0.), ('M1', 0.)]), + Step(SAMPLE, [('M2', 0.), ('M1', 1.)])] + + +def test_the_plan_names_what_is_missing(derivations): + steps, problems = derivations.plan([SPECTRUM], {'M2': BEAM_BLOCK}) # no cuvette holder + assert [s.term for s in steps] == [DARK] + assert problems == {REFERENCE: [HOLDER], SAMPLE: [HOLDER]} + + +def test_a_channel_with_an_unrelated_term_measures_nothing(derivations): + assert derivations.plan([NS + 'Temperature'], {'M2': BEAM_BLOCK, 'M1': HOLDER}) == ([], {}) + + def test_nothing_is_computable_without_the_inputs(derivations): assert derivations.computable({}) == [] assert derivations.missing({}) == {TRANSMITTANCE: sorted([SAMPLE, REFERENCE, DARK]), @@ -56,17 +85,18 @@ def test_transmittance_then_absorbance(derivations): assert results[ABSORBANCE][band] == pytest.approx(-np.log10(expected[band]), abs=0.1) -def test_a_kind_of_the_input_is_accepted(derivations): - """Whatever term stands for the sample (here the more general Spectrum is NOT enough, a kind of sample is)""" - assert derivations.is_a(SAMPLE, NS + 'Spectrum') +def test_a_general_spectrum_is_not_a_sample_spectrum(derivations): available = spectra() - available[NS + 'Spectrum'] = available.pop(SAMPLE) # a general spectrum is not a sample spectrum + available[SPECTRUM] = available.pop(SAMPLE) assert derivations.computable(available) == [] -def test_the_mock_spectra(): - assert MockSpectro('dark').grab_spectrum().mean() == pytest.approx(DARK_LEVEL, rel=0.1) - assert MockSpectro('reference').grab_spectrum().max() > 10 * DARK_LEVEL - assert lamp_spectrum().max() > 0 - with pytest.raises(ValueError): - MockSpectro('unknown') +def test_the_bench_follows_its_actuators(): + bench = SpectroBench() + bench.beam_block = 1 + assert bench.grab_spectrum().mean() == pytest.approx(DARK_LEVEL, rel=0.1) + bench.beam_block, bench.sample_position = 0, 0 + blank = bench.grab_spectrum() + bench.sample_position = 1 + assert bench.grab_spectrum()[np.argmin(np.abs(WAVELENGTHS - 550.))] < 0.4 * blank[np.argmin(np.abs(WAVELENGTHS - 550.))] + assert SpectroBench.shared() is SpectroBench.shared() diff --git a/tests/test_ontology_logger.py b/tests/test_ontology_logger.py deleted file mode 100644 index 7b62c6b..0000000 --- a/tests/test_ontology_logger.py +++ /dev/null @@ -1,112 +0,0 @@ -"""Tests of the demo extension annotating the saved data with the terms of an ontology""" -import pytest -import qt_themes -from pytest import fixture -from qtpy import QtWidgets - -pytest.importorskip('pymodaq_plugins_mock', reason='The mock instruments of PyMoDAQ are needed') -pytest.importorskip('pymodaq_ontology', reason='The ontology manager is needed') - -from pymodaq_utils.config import GlobalConfig - -from pymodaq.control_modules.enums import DAQTypesEnum -from pymodaq.dashboard import create_load_dashboard -from pymodaq.extensions.daq_logger.daq_logger import DAQLogger -from pymodaq.utils.gui_utils.loader_utils import create_extension - -from pymodaq_ontology import manager as manager_module - -from pymodaq_plugins_mockexamples.extensions import ontology_logger -from pymodaq_plugins_mockexamples.extensions.ontology_logger import OntologyLogger - -NS = 'http://example.org/mockexamples#' -PHOTODIODE = NS + 'Photodiode' -TEMPERATURE = NS + 'Temperature' -OPTICAL = NS + 'OpticalSignal' -SIGNAL = NS + 'Signal' - - -def test_is_a_dashboard_extension(): - assert ontology_logger.EXTENSION_NAME - assert ontology_logger.CLASS_NAME == OntologyLogger.__name__ - assert issubclass(OntologyLogger, DAQLogger) - assert ontology_logger.TERMS_FILE.is_file() - - -@fixture -def dashboard(qtbot, tmp_path, monkeypatch): - monkeypatch.setattr(manager_module, 'get_set_config_dir', lambda name, user=False: tmp_path / name) - (tmp_path / 'ontology').mkdir() - config = GlobalConfig() - qt_themes.set_theme(theme=config('gui', 'style', 'theme')[0], style=config('gui', 'style', 'style')[0]) - shared_ui, dashboard = create_load_dashboard(show_dashboard=False) - qtbot.addWidget(shared_ui.parent) - qtbot.addWidget(dashboard.tree) - - creator = dashboard.module_creator - detectors = [] - for name in ('Det', 'Other'): - detector = creator.create_detector(name, DAQTypesEnum.DAQ0D) - creator.set_detector_type(detector, DAQTypesEnum.DAQ0D, 'Mock') - creator.add_detector(detector) - detector.init_hardware_ui(True) - detectors.append(detector) - qtbot.waitUntil(lambda: all(d.initialized_state for d in detectors), timeout=10000) - dashboard.modules_manager.detectors_all = detectors - yield dashboard - QtWidgets.QApplication.processEvents() - dashboard.quit_fun() - - -@fixture -def extension(dashboard): - win_ext, ext = create_extension(dashboard, OntologyLogger, show_extension=False) - ext.do_things_after_experiment_set('mock experiment', False) - yield ext - ext.quit_fun() - - -def test_the_basic_ontology_is_given_to_the_manager(extension): - manager = extension.ontology_manager - assert manager is not None - assert PHOTODIODE in manager.terms - - -def test_the_saved_data_carry_the_assigned_term(extension, qtbot, tmp_path): - manager = extension.ontology_manager - manager.probe() - channels = [c for c in manager.channels if c.module == 'Det'] - assert channels - manager.assign(channels[0].key, PHOTODIODE) # only the first channel of the mock detector - - extension.h5_manager.get_h5saver().settings['base_path'] = str(tmp_path) # not in the user's data folder - extension.modules_manager.selected_detectors_name = ['Det'] # the logger saves the selected detectors - extension.logging.start() - extension.modules_manager.detectors[0].snap() - qtbot.waitUntil(lambda: extension.status_manager.n_saved >= 1, timeout=15000) - extension.logging.stop('test') - qtbot.waitUntil(lambda: extension.settings['saver_worker', 'worker_tasks'] == 0, timeout=15000) - - h5saver = extension.h5_manager.h5saver - nodes = [n for n in h5saver.walk_nodes('/') if 'semantic_iri' in n.attrs] - assert nodes - iris = nodes[0].attrs['semantic_iri'] - assert PHOTODIODE in ([iris] if isinstance(iris, str) else list(iris)) - - -def test_select_the_instruments_by_what_their_channels_mean(extension): - """The names of the modules say nothing: the terms assigned to their channels do""" - manager = extension.ontology_manager - manager.probe() - det = next(c for c in manager.channels if c.module == 'Det') - other = next(c for c in manager.channels if c.module == 'Other') - manager.assign(det.key, PHOTODIODE) - manager.assign(other.key, TEMPERATURE) - - extension.settings['concept'] = OPTICAL - extension.select_channels_of_concept() - assert extension.modules_manager.selected_detectors_name == ['Det'] # a photodiode signal is an optical signal - - extension.settings['concept'] = SIGNAL - extension.select_channels_of_concept() - assert extension.modules_manager.selected_detectors_name == ['Det', 'Other'] # both are signals diff --git a/tests/test_spectro_concepts.py b/tests/test_spectro_concepts.py index eac21ec..22cba69 100644 --- a/tests/test_spectro_concepts.py +++ b/tests/test_spectro_concepts.py @@ -20,9 +20,9 @@ from pymodaq_plugins_mockexamples.extensions.spectro_concepts import SpectroConcepts NS = 'http://example.org/mockexamples#' -# the names of the modules say nothing: what each one measures is the plugin and, for the user, the term assigned -MODULES = {'S1': 'MockSpectroSample', 'S2': 'MockSpectroDark', 'S3': 'MockSpectroReference'} -TERMS = {'S1': NS + 'SampleSpectrum', 'S2': NS + 'DarkSpectrum', 'S3': NS + 'ReferenceSpectrum'} +# the names of the modules say nothing: what each one is, is the plugin and, for the user, the term assigned +ACTUATORS = {'M2': 'MockBeamBlock', 'M1': 'MockSampleChanger'} +TERMS = {'M2': NS + 'BeamBlock', 'M1': NS + 'SampleHolder', 'Spectro': NS + 'Spectrum'} def test_is_a_dashboard_extension(): @@ -43,15 +43,20 @@ def dashboard(qtbot, tmp_path, monkeypatch): qtbot.addWidget(dashboard.tree) creator = dashboard.module_creator - detectors = [] - for name, plugin in MODULES.items(): - detector = creator.create_detector(name, DAQTypesEnum.DAQ1D) - creator.set_detector_type(detector, DAQTypesEnum.DAQ1D, plugin) - creator.add_detector(detector) - detector.init_hardware_ui(True) - detectors.append(detector) - qtbot.waitUntil(lambda: all(d.initialized_state for d in detectors), timeout=10000) - dashboard.modules_manager.detectors_all = detectors + actuators = [] + for name, plugin in ACTUATORS.items(): + actuator = creator.create_actuator(name, plugin, 'Simple') + creator.set_actuator_type(actuator, plugin) + creator.add_actuator(actuator) + actuator.init_hardware_ui(True) + actuators.append(actuator) + detector = creator.create_detector('Spectro', DAQTypesEnum.DAQ1D) + creator.set_detector_type(detector, DAQTypesEnum.DAQ1D, 'MockSpectro') + creator.add_detector(detector) + detector.init_hardware_ui(True) + qtbot.waitUntil(lambda: detector.initialized_state and all(a.initialized_state for a in actuators), timeout=10000) + dashboard.modules_manager.detectors_all = [detector] + dashboard.modules_manager.actuators_all = actuators yield dashboard QtWidgets.QApplication.processEvents() dashboard.quit_fun() @@ -67,6 +72,7 @@ def extension(dashboard): def assign(extension, modules): manager = extension.ontology_manager + manager.update_channels_from_dashboard() manager.probe() for module in modules: channel = next(c for c in manager.channels if c.module == module) @@ -78,20 +84,27 @@ def test_the_spectro_ontology_is_given_to_the_manager(extension): assert NS + 'Transmittance' in extension.ontology_manager.terms -def test_nothing_to_compute_without_terms(extension): - assert extension.show_what_is_possible().startswith('Nothing can be computed yet') +def test_nothing_can_be_measured_without_terms(extension): + assert extension.show_what_is_possible().startswith('Nothing can be measured yet') -def test_the_missing_term_is_named(extension): - assign(extension, ['S1', 'S3']) # sample and reference, no dark +def test_the_missing_actuator_is_named(extension): + assign(extension, ['Spectro', 'M2']) # no term for the cuvette holder text = extension.show_what_is_possible() - assert text.startswith('Nothing can be computed yet') - assert 'Transmittance needs: Dark spectrum' in text + assert text.startswith('Can measure: Dark spectrum') + assert 'Sample spectrum needs an actuator with the term: Cuvette holder' in text -def test_transmittance_and_absorbance_are_computed_whatever_the_names(extension, qtbot): - assign(extension, ['S1', 'S2', 'S3']) - assert extension.show_what_is_possible().startswith('Can compute: Transmittance, Absorbance') - extension.grab_and_compute() - qtbot.waitUntil(lambda: not extension._busy, timeout=15000) - assert extension.settings['status'].startswith('Can compute: Transmittance, Absorbance') +def test_the_protocol_measures_and_computes_whatever_the_names(extension, qtbot): + assign(extension, ['Spectro', 'M2', 'M1']) + text = extension.show_what_is_possible() + assert text.startswith('Can measure: Dark spectrum, Reference spectrum, Sample spectrum') + assert 'Then can compute: Transmittance, Absorbance' in text + extension.run_protocol() + qtbot.waitUntil(lambda: not extension._busy, timeout=30000) + assert extension.settings['status'] == 'Computed: Transmittance, Absorbance' + assert set(extension._results) == {NS + 'DarkSpectrum', NS + 'ReferenceSpectrum', NS + 'SampleSpectrum'} + # the spectra are the ones of the states of the bench: dark level, lamp, lamp through the sample + dark, reference, sample = (extension._results[NS + name].mean() + for name in ('DarkSpectrum', 'ReferenceSpectrum', 'SampleSpectrum')) + assert dark < 200 < sample < reference From f0f8e992f145eacb9183947322e3ec07e38ec8d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:16:42 +0000 Subject: [PATCH 06/18] Spectro Concepts: the states of the bench are terms, their values are associated in the ontology manager The ontology no longer says that a value stands for a state: the user associates the value of each actuator, as configured on the bench, with a state term in the manager; the extension only asks for states. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81mHyjs9x4DB6NLuNY --- README.rst | 7 ++-- .../extensions/spectro_concepts.py | 17 ++++---- .../ontology_derivations.py | 26 +++++------- .../resources/ontology/spectro_ontology.ttl | 20 +++++---- tests/test_ontology_derivations.py | 41 ++++++++++++------- tests/test_spectro_concepts.py | 25 ++++++----- 6 files changed, 77 insertions(+), 59 deletions(-) diff --git a/README.rst b/README.rst index 52866f0..1fe26d5 100644 --- a/README.rst +++ b/README.rst @@ -293,11 +293,12 @@ Extensions whatever the modules are called. It needs the ``pymodaq_ontology`` package (PyMoDAQ ``dev`` branch for now). The experiments ``spectro_lab_a.xml`` and ``spectro_lab_b.xml`` simulate an absorption bench: one spectrometer (*MockSpectro*), a beam block (*MockBeamBlock*) and a cuvette holder (*MockSampleChanger*), with neutral module names - that differ from one experiment to the other. Assign the terms *Spectrum*, *Beam block* and *Cuvette holder* to them in - the *Ontology* manager. The ontology *resources/ontology/spectro_ontology.ttl* says in which state of the bench a + that differ from one experiment to the other. In the *Ontology* manager assign the term *Spectrum* to the spectrometer + and associate the value of each actuator, as configured on the bench, with a state (*Beam blocked*, *Beam open*, + *Blank in beam*, *Sample in beam*). The ontology *resources/ontology/spectro_ontology.ttl* says in which state of the bench a spectrum is a *Dark spectrum* (beam blocked), a *Reference spectrum* (blank cuvette) or a *Sample spectrum*, and that a *Transmittance* and an *Absorbance* are derived from them. The action *What can I measure?* tells what can be measured - and computed, or which actuator term is missing; *Measure and compute* sets the bench for each measurement, grabs, then + and computed, or which state has no value yet; *Measure and compute* sets the bench for each measurement, grabs, then computes and shows the results, with the formulas coded in the extension. Installation instructions diff --git a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py index 0340e77..169f95c 100644 --- a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py +++ b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py @@ -2,12 +2,14 @@ It uses the ``OntologyManager`` of the ``pymodaq_ontology`` package (menu *Ontology* of the Dashboard). The bench of the experiments ``spectro_lab_a`` and ``spectro_lab_b`` is one spectrometer, a beam block and a cuvette holder, with neutral -module names. The user assigns a term to each of them (*Spectrum* to the spectrometer, *Beam block* and *Cuvette holder* -to the actuators) and the extension, which never reads the names of the modules, can then: +module names. The user assigns the term *Spectrum* to the +spectrometer, and associates each value of the actuators, as configured on the bench (1, 0, 12.5...), with a state of +the ontology (*Beam blocked*, *Beam open*, *Blank in beam*, *Sample in beam*) in the manager. The extension only knows +states, never the values nor the names of the modules, and can then: * tell what it can **measure**: the ontology says in which state of the bench a spectrum is a *Dark spectrum* (beam - blocked), a *Reference spectrum* (beam open, blank cuvette) or a *Sample spectrum*; the extension finds the actuators - by their terms and what is missing if one cannot be found; + blocked), a *Reference spectrum* (beam open, blank cuvette) or a *Sample spectrum*; the manager gives the moves that + reach these states, or tells which state has no value yet; * tell what it can then **compute** (a *Transmittance* is derived from the three spectra, an *Absorbance* from the transmittance) and run the whole protocol: set the bench, grab, three times, then compute and show, with the formulas coded here; @@ -117,8 +119,7 @@ def make_plan(self) -> tuple[list[Step], dict[str, list[str]], Optional[Derivati if derivations is None: return [], {}, None detector_terms = set(self.terms_of('detector').values()) - actuator_terms = {key: iri for key, iri in self.terms_of('actuator').items()} # the key is the module - steps, problems = derivations.plan(detector_terms, actuator_terms) + steps, problems = derivations.plan(detector_terms, self.ontology_manager.moves_for_states) return steps, problems, derivations def show_what_is_possible(self) -> str: @@ -140,12 +141,12 @@ def _describe(self, steps: list[Step], problems: dict[str, list[str]], derivatio if steps: lines.append('Can measure: ' + ', '.join(self._label(step.term) for step in steps)) else: - lines.append('Nothing can be measured yet (assign a term to the spectrometer and to the actuators)') + lines.append('Nothing can be measured yet (assign a term to the spectrometer)') for step in steps: lines.append(f' {self._label(step.term)}: ' + ', '.join(f'{module} = {value:g}' for module, value in step.moves)) for term, controls in problems.items(): - lines.append(f'{self._label(term)} needs an actuator with the term: ' + lines.append(f'{self._label(term)} needs a value of an actuator for: ' + ', '.join(self._label(c) for c in controls)) available = {step.term: None for step in steps} computable = derivations.computable(available) diff --git a/src/pymodaq_plugins_mockexamples/ontology_derivations.py b/src/pymodaq_plugins_mockexamples/ontology_derivations.py index 2a43eb0..4d77123 100644 --- a/src/pymodaq_plugins_mockexamples/ontology_derivations.py +++ b/src/pymodaq_plugins_mockexamples/ontology_derivations.py @@ -61,13 +61,12 @@ def __init__(self, graph: Graph, is_a: Callable[[str, str], bool]): for output in set(graph.subjects(MOCK.derivedFrom, None)): self.rules[str(output)] = sorted(str(i) for i in graph.objects(output, MOCK.derivedFrom) if isinstance(i, URIRef)) - self.requirements: dict[str, list[tuple[str, float]]] = {} # measurement term -> (control term, value) + self.requirements: dict[str, list[str]] = {} # measurement term -> the states of the bench it requires for term in set(graph.subjects(MOCK.requires, None)): - self.requirements[str(term)] = sorted( - (str(graph.value(state, MOCK.control)), float(graph.value(state, MOCK.value))) - for state in graph.objects(term, MOCK.requires)) + self.requirements[str(term)] = sorted(str(state) for state in graph.objects(term, MOCK.requires)) - def plan(self, detector_terms: Iterable[str], actuator_terms: dict[str, str] + def plan(self, detector_terms: Iterable[str], + moves_for_states: Callable[[list[str]], tuple[list[tuple[str, float]], list[str]]] ) -> tuple[list[Step], dict[str, list[str]]]: """The measurements that the channels can make and what blocks the others @@ -75,27 +74,22 @@ def plan(self, detector_terms: Iterable[str], actuator_terms: dict[str, str] ---------- detector_terms: the terms assigned to the channels of the detectors; a channel can make the measurements that are kinds of its term (a channel with the term *Spectrum* can measure the dark, the reference and the sample) - actuator_terms: the term assigned to each actuator, by module name + moves_for_states: ``moves_for_states(states)``, given by the ontology manager: the moves (actuator, value) to + reach the states, and the states for which the user associated no value Returns ------- - the steps (the measurement and the moves to do first), and for the measurements that cannot be made the controls - for which no actuator has a term + the steps (the measurement and the moves to do first), and for the measurements that cannot be made the states + with no value """ detector_terms = list(detector_terms) steps, problems = [], {} for measurement in sorted(self.requirements): if not any(self.is_a(measurement, term) for term in detector_terms): continue - moves, missing = [], [] - for control, value in self.requirements[measurement]: - module = next((m for m, term in sorted(actuator_terms.items()) if self.is_a(term, control)), None) - if module is None: - missing.append(control) - else: - moves.append((module, value)) + moves, missing = moves_for_states(self.requirements[measurement]) if missing: - problems[measurement] = sorted(set(missing)) + problems[measurement] = sorted(missing) else: steps.append(Step(measurement, moves)) return steps, problems diff --git a/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl b/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl index fbd5993..825d3b6 100644 --- a/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl +++ b/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl @@ -13,15 +13,15 @@ # mock:derivedFrom the terms it is computed from; mock:formula tells how (documentation, the code is in the extension) # mock:requires the states of the bench in which a spectrum has this meaning: the same spectrometer gives the # dark spectrum with the beam blocked, the reference with the blank cuvette, the sample with the -# sample cuvette. A state says which control it is a value of (mock:control) and which one (mock:value). +# sample cuvette. A state is a kind of control (Beam blocked is a Beam block). The value of the +# actuator that stands for a state is not here: it depends on the bench, the user associates it in +# the ontology manager. mock:quantity a owl:AnnotationProperty ; rdfs:label "quantity"@en . mock:unit a owl:AnnotationProperty ; rdfs:label "unit"@en . mock:formula a owl:AnnotationProperty ; rdfs:label "formula"@en . mock:derivedFrom a owl:ObjectProperty ; rdfs:label "derived from"@en . mock:requires a owl:ObjectProperty ; rdfs:label "requires"@en . -mock:control a owl:AnnotationProperty ; rdfs:label "control"@en . -mock:value a owl:AnnotationProperty ; rdfs:label "value"@en . mock:Signal a owl:Class ; rdfs:subClassOf sosa:ObservableProperty ; rdfs:label "Signal"@en ; skos:definition "Any signal measured by a detector."@en . @@ -63,8 +63,12 @@ mock:BeamBlock a owl:Class ; rdfs:subClassOf mock:Control ; mock:SampleHolder a owl:Class ; rdfs:subClassOf mock:Control ; rdfs:label "Cuvette holder"@en ; skos:definition "Puts the blank cuvette (0) or the cuvette with the sample (1) in the beam."@en . -# the states of the controls (not terms to assign: they are what the terms above require) -mock:BeamBlocked mock:control mock:BeamBlock ; mock:value 1 ; rdfs:label "beam blocked" . -mock:BeamOpen mock:control mock:BeamBlock ; mock:value 0 ; rdfs:label "beam open" . -mock:BlankInBeam mock:control mock:SampleHolder ; mock:value 0 ; rdfs:label "blank cuvette in the beam" . -mock:SampleInBeam mock:control mock:SampleHolder ; mock:value 1 ; rdfs:label "sample cuvette in the beam" . +# the states of the controls: what the terms above require (terms to associate with a value of the actuator) +mock:BeamBlocked a owl:Class ; rdfs:subClassOf mock:BeamBlock ; + rdfs:label "Beam blocked"@en ; skos:definition "The beam is blocked: the detector sees no light."@en . +mock:BeamOpen a owl:Class ; rdfs:subClassOf mock:BeamBlock ; + rdfs:label "Beam open"@en ; skos:definition "The beam goes through."@en . +mock:BlankInBeam a owl:Class ; rdfs:subClassOf mock:SampleHolder ; + rdfs:label "Blank in beam"@en ; skos:definition "The blank cuvette is in the beam."@en . +mock:SampleInBeam a owl:Class ; rdfs:subClassOf mock:SampleHolder ; + rdfs:label "Sample in beam"@en ; skos:definition "The cuvette with the sample is in the beam."@en . diff --git a/tests/test_ontology_derivations.py b/tests/test_ontology_derivations.py index 1681c5d..4fe734b 100644 --- a/tests/test_ontology_derivations.py +++ b/tests/test_ontology_derivations.py @@ -14,7 +14,9 @@ TRANSMITTANCE, ABSORBANCE) NS = 'http://example.org/mockexamples#' -SPECTRUM, BEAM_BLOCK, HOLDER = NS + 'Spectrum', NS + 'BeamBlock', NS + 'SampleHolder' +SPECTRUM = NS + 'Spectrum' +BEAM_BLOCKED, BEAM_OPEN, BLANK, SAMPLE_IN = (NS + name for name in ('BeamBlocked', 'BeamOpen', 'BlankInBeam', + 'SampleInBeam')) @pytest.fixture @@ -39,27 +41,38 @@ def test_the_ontology_declares_the_derivations(derivations): def test_the_ontology_declares_the_state_of_the_bench_for_each_measurement(derivations): - assert derivations.requirements[DARK] == [(BEAM_BLOCK, 1.)] - assert derivations.requirements[REFERENCE] == [(BEAM_BLOCK, 0.), (HOLDER, 0.)] - assert derivations.requirements[SAMPLE] == [(BEAM_BLOCK, 0.), (HOLDER, 1.)] + """The states, not the values: the value of an actuator for a state is the user's, in the manager""" + assert derivations.requirements[DARK] == [BEAM_BLOCKED] + assert derivations.requirements[REFERENCE] == sorted([BEAM_OPEN, BLANK]) + assert derivations.requirements[SAMPLE] == sorted([BEAM_OPEN, SAMPLE_IN]) -def test_the_plan_finds_the_actuators_by_their_terms(derivations): - """A spectrometer and two actuators with names that say nothing""" - steps, problems = derivations.plan([SPECTRUM], {'M2': BEAM_BLOCK, 'M1': HOLDER}) +def fake_moves(values): + """What the manager gives: the (actuator, value) for each state, and the states with no value""" + def moves_for_states(states): + return [values[s] for s in states if s in values], [s for s in states if s not in values] + return moves_for_states + + +VALUES = {BEAM_BLOCKED: ('M2', 12.5), BEAM_OPEN: ('M2', 3.), BLANK: ('M1', 0.), SAMPLE_IN: ('M1', 1.)} + + +def test_the_plan_gives_the_moves_of_the_states(derivations): + steps, problems = derivations.plan([SPECTRUM], fake_moves(VALUES)) assert problems == {} - assert steps == [Step(DARK, [('M2', 1.)]), Step(REFERENCE, [('M2', 0.), ('M1', 0.)]), - Step(SAMPLE, [('M2', 0.), ('M1', 1.)])] + assert steps == [Step(DARK, [('M2', 12.5)]), Step(REFERENCE, [('M2', 3.), ('M1', 0.)]), + Step(SAMPLE, [('M2', 3.), ('M1', 1.)])] -def test_the_plan_names_what_is_missing(derivations): - steps, problems = derivations.plan([SPECTRUM], {'M2': BEAM_BLOCK}) # no cuvette holder - assert [s.term for s in steps] == [DARK] - assert problems == {REFERENCE: [HOLDER], SAMPLE: [HOLDER]} +def test_the_plan_names_the_states_without_value(derivations): + values = {k: v for k, v in VALUES.items() if k != SAMPLE_IN} + steps, problems = derivations.plan([SPECTRUM], fake_moves(values)) + assert [s.term for s in steps] == [DARK, REFERENCE] + assert problems == {SAMPLE: [SAMPLE_IN]} def test_a_channel_with_an_unrelated_term_measures_nothing(derivations): - assert derivations.plan([NS + 'Temperature'], {'M2': BEAM_BLOCK, 'M1': HOLDER}) == ([], {}) + assert derivations.plan([NS + 'Temperature'], fake_moves(VALUES)) == ([], {}) def test_nothing_is_computable_without_the_inputs(derivations): diff --git a/tests/test_spectro_concepts.py b/tests/test_spectro_concepts.py index 22cba69..a9de865 100644 --- a/tests/test_spectro_concepts.py +++ b/tests/test_spectro_concepts.py @@ -22,7 +22,9 @@ NS = 'http://example.org/mockexamples#' # the names of the modules say nothing: what each one is, is the plugin and, for the user, the term assigned ACTUATORS = {'M2': 'MockBeamBlock', 'M1': 'MockSampleChanger'} -TERMS = {'M2': NS + 'BeamBlock', 'M1': NS + 'SampleHolder', 'Spectro': NS + 'Spectrum'} +# the value of each state is what the user configured on the bench (here the bench blocks above 0.5) +STATES = {NS + 'BeamBlocked': ('M2', 1.), NS + 'BeamOpen': ('M2', 0.), + NS + 'BlankInBeam': ('M1', 0.), NS + 'SampleInBeam': ('M1', 1.)} def test_is_a_dashboard_extension(): @@ -70,13 +72,16 @@ def extension(dashboard): ext.quit_fun() -def assign(extension, modules): +def assign(extension, states): + """Assign the term of the spectrometer and associate the values of the actuators with states""" manager = extension.ontology_manager manager.update_channels_from_dashboard() manager.probe() - for module in modules: - channel = next(c for c in manager.channels if c.module == module) - manager.assign(channel.key, TERMS[module]) + channel = next(c for c in manager.channels if c.module == 'Spectro') + manager.assign(channel.key, NS + 'Spectrum') + for state in states: + actuator, value = STATES[state] + manager.assign_state(actuator, value, state) def test_the_spectro_ontology_is_given_to_the_manager(extension): @@ -88,15 +93,15 @@ def test_nothing_can_be_measured_without_terms(extension): assert extension.show_what_is_possible().startswith('Nothing can be measured yet') -def test_the_missing_actuator_is_named(extension): - assign(extension, ['Spectro', 'M2']) # no term for the cuvette holder +def test_the_state_without_value_is_named(extension): + assign(extension, [s for s in STATES if s != NS + 'SampleInBeam']) text = extension.show_what_is_possible() - assert text.startswith('Can measure: Dark spectrum') - assert 'Sample spectrum needs an actuator with the term: Cuvette holder' in text + assert text.startswith('Can measure: Dark spectrum, Reference spectrum') + assert 'Sample spectrum needs a value of an actuator for: Sample in beam' in text def test_the_protocol_measures_and_computes_whatever_the_names(extension, qtbot): - assign(extension, ['Spectro', 'M2', 'M1']) + assign(extension, list(STATES)) text = extension.show_what_is_possible() assert text.startswith('Can measure: Dark spectrum, Reference spectrum, Sample spectrum') assert 'Then can compute: Transmittance, Absorbance' in text From cd848b87fd34296a9b863df6f14c35cd81cb9e5c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:17:12 +0000 Subject: [PATCH 07/18] Spectro Concepts: line lengths --- .../extensions/spectro_concepts.py | 4 ++-- src/pymodaq_plugins_mockexamples/ontology_derivations.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py index 169f95c..870f5e3 100644 --- a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py +++ b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py @@ -146,8 +146,8 @@ def _describe(self, steps: list[Step], problems: dict[str, list[str]], derivatio lines.append(f' {self._label(step.term)}: ' + ', '.join(f'{module} = {value:g}' for module, value in step.moves)) for term, controls in problems.items(): - lines.append(f'{self._label(term)} needs a value of an actuator for: ' - + ', '.join(self._label(c) for c in controls)) + states = ', '.join(self._label(c) for c in controls) + lines.append(f'{self._label(term)} needs a value of an actuator for: {states}') available = {step.term: None for step in steps} computable = derivations.computable(available) if computable: diff --git a/src/pymodaq_plugins_mockexamples/ontology_derivations.py b/src/pymodaq_plugins_mockexamples/ontology_derivations.py index 4d77123..ca1834f 100644 --- a/src/pymodaq_plugins_mockexamples/ontology_derivations.py +++ b/src/pymodaq_plugins_mockexamples/ontology_derivations.py @@ -72,8 +72,8 @@ def plan(self, detector_terms: Iterable[str], Parameters ---------- - detector_terms: the terms assigned to the channels of the detectors; a channel can make the measurements that are - kinds of its term (a channel with the term *Spectrum* can measure the dark, the reference and the sample) + detector_terms: the terms assigned to the channels of the detectors; a channel can make the measurements + that are kinds of its term (a channel with the term *Spectrum* can measure the dark, the reference and the sample) moves_for_states: ``moves_for_states(states)``, given by the ontology manager: the moves (actuator, value) to reach the states, and the states for which the user associated no value From cfaf918ae67d52f9cf06a3cb58bb0db87869ef5f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:17:39 +0000 Subject: [PATCH 08/18] Spectro Concepts: line lengths --- .../extensions/spectro_concepts.py | 4 ++-- src/pymodaq_plugins_mockexamples/ontology_derivations.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py index 870f5e3..2b7fcb6 100644 --- a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py +++ b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py @@ -143,8 +143,8 @@ def _describe(self, steps: list[Step], problems: dict[str, list[str]], derivatio else: lines.append('Nothing can be measured yet (assign a term to the spectrometer)') for step in steps: - lines.append(f' {self._label(step.term)}: ' + ', '.join(f'{module} = {value:g}' - for module, value in step.moves)) + moves = ', '.join(f'{module} = {value:g}' for module, value in step.moves) + lines.append(f' {self._label(step.term)}: {moves}') for term, controls in problems.items(): states = ', '.join(self._label(c) for c in controls) lines.append(f'{self._label(term)} needs a value of an actuator for: {states}') diff --git a/src/pymodaq_plugins_mockexamples/ontology_derivations.py b/src/pymodaq_plugins_mockexamples/ontology_derivations.py index ca1834f..5a3fbaf 100644 --- a/src/pymodaq_plugins_mockexamples/ontology_derivations.py +++ b/src/pymodaq_plugins_mockexamples/ontology_derivations.py @@ -73,7 +73,7 @@ def plan(self, detector_terms: Iterable[str], Parameters ---------- detector_terms: the terms assigned to the channels of the detectors; a channel can make the measurements - that are kinds of its term (a channel with the term *Spectrum* can measure the dark, the reference and the sample) + that are kinds of its term (the term *Spectrum* can measure the dark, the reference and the sample) moves_for_states: ``moves_for_states(states)``, given by the ontology manager: the moves (actuator, value) to reach the states, and the states for which the user associated no value From 2831a48a8a0c1fcbd90866d80ac7584f2c84e461 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 09:22:55 +0000 Subject: [PATCH 09/18] Spectro Concepts: the cuvette state is Reference in beam, not blank Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81mHyjs9x4DB6NLuNY --- README.rst | 4 ++-- .../daq_move_plugins/daq_move_MockSampleChanger.py | 2 +- .../extensions/spectro_concepts.py | 8 ++++---- .../hardware/spectro_bench.py | 4 ++-- .../resources/ontology/spectro_ontology.ttl | 10 +++++----- tests/test_ontology_derivations.py | 10 +++++----- tests/test_spectro_concepts.py | 2 +- 7 files changed, 20 insertions(+), 20 deletions(-) diff --git a/README.rst b/README.rst index 1fe26d5..1c924aa 100644 --- a/README.rst +++ b/README.rst @@ -295,8 +295,8 @@ Extensions (*MockSpectro*), a beam block (*MockBeamBlock*) and a cuvette holder (*MockSampleChanger*), with neutral module names that differ from one experiment to the other. In the *Ontology* manager assign the term *Spectrum* to the spectrometer and associate the value of each actuator, as configured on the bench, with a state (*Beam blocked*, *Beam open*, - *Blank in beam*, *Sample in beam*). The ontology *resources/ontology/spectro_ontology.ttl* says in which state of the bench a - spectrum is a *Dark spectrum* (beam blocked), a *Reference spectrum* (blank cuvette) or a *Sample spectrum*, and that a + *Reference in beam*, *Sample in beam*). The ontology *resources/ontology/spectro_ontology.ttl* says in which state of the bench a + spectrum is a *Dark spectrum* (beam blocked), a *Reference spectrum* (reference cuvette) or a *Sample spectrum*, and that a *Transmittance* and an *Absorbance* are derived from them. The action *What can I measure?* tells what can be measured and computed, or which state has no value yet; *Measure and compute* sets the bench for each measurement, grabs, then computes and shows the results, with the formulas coded in the extension. diff --git a/src/pymodaq_plugins_mockexamples/daq_move_plugins/daq_move_MockSampleChanger.py b/src/pymodaq_plugins_mockexamples/daq_move_plugins/daq_move_MockSampleChanger.py index 290fd9c..2837d04 100644 --- a/src/pymodaq_plugins_mockexamples/daq_move_plugins/daq_move_MockSampleChanger.py +++ b/src/pymodaq_plugins_mockexamples/daq_move_plugins/daq_move_MockSampleChanger.py @@ -1,4 +1,4 @@ -"""Ontology demo: the cuvette holder of a simulated absorption bench (0 the blank cuvette, 1 the sample), see +"""Ontology demo: the cuvette holder of a simulated absorption bench (0 the reference cuvette, 1 the sample), see ``MockBeamBlock``""" from pymodaq.control_modules.move_utility_classes import comon_parameters_fun, main, DataActuatorType diff --git a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py index 2b7fcb6..e8e2dc1 100644 --- a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py +++ b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py @@ -4,12 +4,12 @@ experiments ``spectro_lab_a`` and ``spectro_lab_b`` is one spectrometer, a beam block and a cuvette holder, with neutral module names. The user assigns the term *Spectrum* to the spectrometer, and associates each value of the actuators, as configured on the bench (1, 0, 12.5...), with a state of -the ontology (*Beam blocked*, *Beam open*, *Blank in beam*, *Sample in beam*) in the manager. The extension only knows -states, never the values nor the names of the modules, and can then: +the ontology (*Beam blocked*, *Beam open*, *Reference in beam*, *Sample in beam*) in the manager. The extension only +knows states, never the values nor the names of the modules, and can then: * tell what it can **measure**: the ontology says in which state of the bench a spectrum is a *Dark spectrum* (beam - blocked), a *Reference spectrum* (beam open, blank cuvette) or a *Sample spectrum*; the manager gives the moves that - reach these states, or tells which state has no value yet; + blocked), a *Reference spectrum* (beam open, reference cuvette) or a *Sample spectrum*; the manager gives the moves + that reach these states, or tells which state has no value yet; * tell what it can then **compute** (a *Transmittance* is derived from the three spectra, an *Absorbance* from the transmittance) and run the whole protocol: set the bench, grab, three times, then compute and show, with the formulas coded here; diff --git a/src/pymodaq_plugins_mockexamples/hardware/spectro_bench.py b/src/pymodaq_plugins_mockexamples/hardware/spectro_bench.py index 03b8579..d184b41 100644 --- a/src/pymodaq_plugins_mockexamples/hardware/spectro_bench.py +++ b/src/pymodaq_plugins_mockexamples/hardware/spectro_bench.py @@ -3,7 +3,7 @@ What the spectrometer measures depends on the two actuators of the bench, as on a real one: * the beam block (1: the light is blocked, the spectrometer sees only its dark level; 0: the beam goes through) -* the cuvette holder (0: the blank cuvette, the spectrometer sees the lamp; 1: the cuvette with the sample, which +* the cuvette holder (0: the reference cuvette, the spectrometer sees the lamp; 1: the cuvette with the sample, which absorbs around 550 nm: its transmittance is about 0.9 away from the band and 0.2 at its centre) Used by the plugins ``MockBeamBlock``, ``MockSampleChanger`` (actuators) and ``MockSpectro`` (the spectrometer) of the @@ -41,7 +41,7 @@ def shared(cls) -> 'SpectroBench': def __init__(self): self.beam_block = 0. # 1: the beam is blocked - self.sample_position = 0. # 1: the cuvette with the sample is in the beam, 0: the blank one + self.sample_position = 0. # 1: the cuvette with the sample is in the beam, 0: the reference one self._rng = np.random.default_rng() def get_wavelength_axis(self) -> np.ndarray: diff --git a/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl b/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl index 825d3b6..13365f3 100644 --- a/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl +++ b/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl @@ -12,7 +12,7 @@ # mock:unit its unit ("counts", "1" for a pure number) # mock:derivedFrom the terms it is computed from; mock:formula tells how (documentation, the code is in the extension) # mock:requires the states of the bench in which a spectrum has this meaning: the same spectrometer gives the -# dark spectrum with the beam blocked, the reference with the blank cuvette, the sample with the +# dark spectrum with the beam blocked, the reference with the reference cuvette, the sample with the # sample cuvette. A state is a kind of control (Beam blocked is a Beam block). The value of the # actuator that stands for a state is not here: it depends on the bench, the user associates it in # the ontology manager. @@ -36,7 +36,7 @@ mock:DarkSpectrum a owl:Class ; rdfs:subClassOf mock:Spectrum ; mock:ReferenceSpectrum a owl:Class ; rdfs:subClassOf mock:Spectrum ; rdfs:label "Reference spectrum"@en ; skos:definition "Spectrum of the lamp alone, without the sample."@en ; - mock:requires mock:BeamOpen , mock:BlankInBeam . + mock:requires mock:BeamOpen , mock:ReferenceInBeam . mock:SampleSpectrum a owl:Class ; rdfs:subClassOf mock:Spectrum ; rdfs:label "Sample spectrum"@en ; skos:definition "Spectrum of the lamp after the sample."@en ; @@ -61,14 +61,14 @@ mock:BeamBlock a owl:Class ; rdfs:subClassOf mock:Control ; rdfs:label "Beam block"@en ; skos:definition "Blocks the beam (1) or lets it through (0)."@en . mock:SampleHolder a owl:Class ; rdfs:subClassOf mock:Control ; - rdfs:label "Cuvette holder"@en ; skos:definition "Puts the blank cuvette (0) or the cuvette with the sample (1) in the beam."@en . + rdfs:label "Cuvette holder"@en ; skos:definition "Puts the reference cuvette (0) or the cuvette with the sample (1) in the beam."@en . # the states of the controls: what the terms above require (terms to associate with a value of the actuator) mock:BeamBlocked a owl:Class ; rdfs:subClassOf mock:BeamBlock ; rdfs:label "Beam blocked"@en ; skos:definition "The beam is blocked: the detector sees no light."@en . mock:BeamOpen a owl:Class ; rdfs:subClassOf mock:BeamBlock ; rdfs:label "Beam open"@en ; skos:definition "The beam goes through."@en . -mock:BlankInBeam a owl:Class ; rdfs:subClassOf mock:SampleHolder ; - rdfs:label "Blank in beam"@en ; skos:definition "The blank cuvette is in the beam."@en . +mock:ReferenceInBeam a owl:Class ; rdfs:subClassOf mock:SampleHolder ; + rdfs:label "Reference in beam"@en ; skos:definition "The reference cuvette is in the beam."@en . mock:SampleInBeam a owl:Class ; rdfs:subClassOf mock:SampleHolder ; rdfs:label "Sample in beam"@en ; skos:definition "The cuvette with the sample is in the beam."@en . diff --git a/tests/test_ontology_derivations.py b/tests/test_ontology_derivations.py index 4fe734b..68cd03b 100644 --- a/tests/test_ontology_derivations.py +++ b/tests/test_ontology_derivations.py @@ -15,7 +15,7 @@ NS = 'http://example.org/mockexamples#' SPECTRUM = NS + 'Spectrum' -BEAM_BLOCKED, BEAM_OPEN, BLANK, SAMPLE_IN = (NS + name for name in ('BeamBlocked', 'BeamOpen', 'BlankInBeam', +BEAM_BLOCKED, BEAM_OPEN, REFERENCE_IN, SAMPLE_IN = (NS + name for name in ('BeamBlocked', 'BeamOpen', 'ReferenceInBeam', 'SampleInBeam')) @@ -43,7 +43,7 @@ def test_the_ontology_declares_the_derivations(derivations): def test_the_ontology_declares_the_state_of_the_bench_for_each_measurement(derivations): """The states, not the values: the value of an actuator for a state is the user's, in the manager""" assert derivations.requirements[DARK] == [BEAM_BLOCKED] - assert derivations.requirements[REFERENCE] == sorted([BEAM_OPEN, BLANK]) + assert derivations.requirements[REFERENCE] == sorted([BEAM_OPEN, REFERENCE_IN]) assert derivations.requirements[SAMPLE] == sorted([BEAM_OPEN, SAMPLE_IN]) @@ -54,7 +54,7 @@ def moves_for_states(states): return moves_for_states -VALUES = {BEAM_BLOCKED: ('M2', 12.5), BEAM_OPEN: ('M2', 3.), BLANK: ('M1', 0.), SAMPLE_IN: ('M1', 1.)} +VALUES = {BEAM_BLOCKED: ('M2', 12.5), BEAM_OPEN: ('M2', 3.), REFERENCE_IN: ('M1', 0.), SAMPLE_IN: ('M1', 1.)} def test_the_plan_gives_the_moves_of_the_states(derivations): @@ -109,7 +109,7 @@ def test_the_bench_follows_its_actuators(): bench.beam_block = 1 assert bench.grab_spectrum().mean() == pytest.approx(DARK_LEVEL, rel=0.1) bench.beam_block, bench.sample_position = 0, 0 - blank = bench.grab_spectrum() + reference = bench.grab_spectrum() bench.sample_position = 1 - assert bench.grab_spectrum()[np.argmin(np.abs(WAVELENGTHS - 550.))] < 0.4 * blank[np.argmin(np.abs(WAVELENGTHS - 550.))] + assert bench.grab_spectrum()[np.argmin(np.abs(WAVELENGTHS - 550.))] < 0.4 * reference[np.argmin(np.abs(WAVELENGTHS - 550.))] assert SpectroBench.shared() is SpectroBench.shared() diff --git a/tests/test_spectro_concepts.py b/tests/test_spectro_concepts.py index a9de865..cd595f6 100644 --- a/tests/test_spectro_concepts.py +++ b/tests/test_spectro_concepts.py @@ -24,7 +24,7 @@ ACTUATORS = {'M2': 'MockBeamBlock', 'M1': 'MockSampleChanger'} # the value of each state is what the user configured on the bench (here the bench blocks above 0.5) STATES = {NS + 'BeamBlocked': ('M2', 1.), NS + 'BeamOpen': ('M2', 0.), - NS + 'BlankInBeam': ('M1', 0.), NS + 'SampleInBeam': ('M1', 1.)} + NS + 'ReferenceInBeam': ('M1', 0.), NS + 'SampleInBeam': ('M1', 1.)} def test_is_a_dashboard_extension(): From 5e4576c9410a25264172396838c9e13223578f73 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 15:46:32 +0000 Subject: [PATCH 10/18] spectro ontology: mark the states of the controls (kinds of pq:State) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81mHyjs9x4DB6NLuNY --- .../resources/ontology/spectro_ontology.ttl | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl b/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl index 13365f3..16365c2 100644 --- a/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl +++ b/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl @@ -1,4 +1,5 @@ @prefix mock: . +@prefix pq: . @prefix owl: . @prefix rdfs: . @prefix skos: . @@ -63,12 +64,13 @@ mock:BeamBlock a owl:Class ; rdfs:subClassOf mock:Control ; mock:SampleHolder a owl:Class ; rdfs:subClassOf mock:Control ; rdfs:label "Cuvette holder"@en ; skos:definition "Puts the reference cuvette (0) or the cuvette with the sample (1) in the beam."@en . -# the states of the controls: what the terms above require (terms to associate with a value of the actuator) -mock:BeamBlocked a owl:Class ; rdfs:subClassOf mock:BeamBlock ; +# the states of the controls: what the terms above require (terms to associate with a value of the actuator). +# A kind of pq:State is a state, not a channel: the manager shows it but does not let it be assigned to a channel. +mock:BeamBlocked a owl:Class ; rdfs:subClassOf mock:BeamBlock , pq:State ; rdfs:label "Beam blocked"@en ; skos:definition "The beam is blocked: the detector sees no light."@en . -mock:BeamOpen a owl:Class ; rdfs:subClassOf mock:BeamBlock ; +mock:BeamOpen a owl:Class ; rdfs:subClassOf mock:BeamBlock , pq:State ; rdfs:label "Beam open"@en ; skos:definition "The beam goes through."@en . -mock:ReferenceInBeam a owl:Class ; rdfs:subClassOf mock:SampleHolder ; +mock:ReferenceInBeam a owl:Class ; rdfs:subClassOf mock:SampleHolder , pq:State ; rdfs:label "Reference in beam"@en ; skos:definition "The reference cuvette is in the beam."@en . -mock:SampleInBeam a owl:Class ; rdfs:subClassOf mock:SampleHolder ; +mock:SampleInBeam a owl:Class ; rdfs:subClassOf mock:SampleHolder , pq:State ; rdfs:label "Sample in beam"@en ; skos:definition "The cuvette with the sample is in the beam."@en . From 6399f01aa9fe08f1b08aa224b8595bc9afea282a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 15:51:20 +0000 Subject: [PATCH 11/18] spectro ontology: the states are the members of an enumeration (owl:oneOf) of their control Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81mHyjs9x4DB6NLuNY --- .../resources/ontology/spectro_ontology.ttl | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl b/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl index 16365c2..8608463 100644 --- a/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl +++ b/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl @@ -1,5 +1,4 @@ @prefix mock: . -@prefix pq: . @prefix owl: . @prefix rdfs: . @prefix skos: . @@ -65,12 +64,16 @@ mock:SampleHolder a owl:Class ; rdfs:subClassOf mock:Control ; rdfs:label "Cuvette holder"@en ; skos:definition "Puts the reference cuvette (0) or the cuvette with the sample (1) in the beam."@en . # the states of the controls: what the terms above require (terms to associate with a value of the actuator). -# A kind of pq:State is a state, not a channel: the manager shows it but does not let it be assigned to a channel. -mock:BeamBlocked a owl:Class ; rdfs:subClassOf mock:BeamBlock , pq:State ; +# They are the members of an enumeration (owl:oneOf) of their control: a state, not a channel, so the manager shows +# it but does not let it be assigned to a channel. +mock:BeamBlocked a owl:NamedIndividual , mock:BeamBlock ; rdfs:label "Beam blocked"@en ; skos:definition "The beam is blocked: the detector sees no light."@en . -mock:BeamOpen a owl:Class ; rdfs:subClassOf mock:BeamBlock , pq:State ; +mock:BeamOpen a owl:NamedIndividual , mock:BeamBlock ; rdfs:label "Beam open"@en ; skos:definition "The beam goes through."@en . -mock:ReferenceInBeam a owl:Class ; rdfs:subClassOf mock:SampleHolder , pq:State ; +mock:ReferenceInBeam a owl:NamedIndividual , mock:SampleHolder ; rdfs:label "Reference in beam"@en ; skos:definition "The reference cuvette is in the beam."@en . -mock:SampleInBeam a owl:Class ; rdfs:subClassOf mock:SampleHolder , pq:State ; +mock:SampleInBeam a owl:NamedIndividual , mock:SampleHolder ; rdfs:label "Sample in beam"@en ; skos:definition "The cuvette with the sample is in the beam."@en . + +mock:BeamBlock owl:equivalentClass [ a owl:Class ; owl:oneOf ( mock:BeamBlocked mock:BeamOpen ) ] . +mock:SampleHolder owl:equivalentClass [ a owl:Class ; owl:oneOf ( mock:ReferenceInBeam mock:SampleInBeam ) ] . From 3a2e08abd6d797a683fbb57f1ffa382223f2bccc Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 16:17:03 +0000 Subject: [PATCH 12/18] spectro ontology: requiresState, the predicate of PyMoDAQ read by the ontology manager Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81mHyjs9x4DB6NLuNY --- .../ontology_derivations.py | 7 ++++--- .../resources/ontology/spectro_ontology.ttl | 11 ++++++----- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/pymodaq_plugins_mockexamples/ontology_derivations.py b/src/pymodaq_plugins_mockexamples/ontology_derivations.py index 5a3fbaf..398b95a 100644 --- a/src/pymodaq_plugins_mockexamples/ontology_derivations.py +++ b/src/pymodaq_plugins_mockexamples/ontology_derivations.py @@ -1,6 +1,6 @@ """What the terms of the channels let the experiment do: the statements of an ontology about measuring and computing -The ontology says in which states of the bench a spectrum has a meaning (``mock:requires``: the dark spectrum with the +The ontology says in which states of the bench a spectrum has a meaning (``pq:requiresState``: the dark spectrum with the beam blocked...) and that a term is ``mock:derivedFrom`` other terms (``Transmittance`` from the sample, the reference and the dark spectra). This module reads these statements in the RDF graph and, given the terms of the channels and of the actuators, plans the measurements to do, tells what can be computed and what is missing, and computes it. It @@ -14,6 +14,7 @@ from rdflib import Graph, Namespace, URIRef MOCK = Namespace('http://example.org/mockexamples#') +REQUIRES_STATE = URIRef('https://pymodaq.cnrs.fr/ontology#requiresState') # read by the ontology manager too SAMPLE, REFERENCE, DARK = (str(MOCK[name]) for name in ('SampleSpectrum', 'ReferenceSpectrum', 'DarkSpectrum')) TRANSMITTANCE, ABSORBANCE = str(MOCK.Transmittance), str(MOCK.Absorbance) @@ -62,8 +63,8 @@ def __init__(self, graph: Graph, is_a: Callable[[str, str], bool]): self.rules[str(output)] = sorted(str(i) for i in graph.objects(output, MOCK.derivedFrom) if isinstance(i, URIRef)) self.requirements: dict[str, list[str]] = {} # measurement term -> the states of the bench it requires - for term in set(graph.subjects(MOCK.requires, None)): - self.requirements[str(term)] = sorted(str(state) for state in graph.objects(term, MOCK.requires)) + for term in set(graph.subjects(REQUIRES_STATE, None)): + self.requirements[str(term)] = sorted(str(state) for state in graph.objects(term, REQUIRES_STATE)) def plan(self, detector_terms: Iterable[str], moves_for_states: Callable[[list[str]], tuple[list[tuple[str, float]], list[str]]] diff --git a/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl b/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl index 8608463..e6529a3 100644 --- a/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl +++ b/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl @@ -1,4 +1,5 @@ @prefix mock: . +@prefix pq: . @prefix owl: . @prefix rdfs: . @prefix skos: . @@ -11,7 +12,8 @@ # mock:quantity the physical quantity ("intensity", "ratio"...) # mock:unit its unit ("counts", "1" for a pure number) # mock:derivedFrom the terms it is computed from; mock:formula tells how (documentation, the code is in the extension) -# mock:requires the states of the bench in which a spectrum has this meaning: the same spectrometer gives the +# pq:requiresState (a predicate of PyMoDAQ, read by the ontology manager) the states of the bench in which a +# spectrum has this meaning: the same spectrometer gives the # dark spectrum with the beam blocked, the reference with the reference cuvette, the sample with the # sample cuvette. A state is a kind of control (Beam blocked is a Beam block). The value of the # actuator that stands for a state is not here: it depends on the bench, the user associates it in @@ -21,7 +23,6 @@ mock:quantity a owl:AnnotationProperty ; rdfs:label "quantity"@en . mock:unit a owl:AnnotationProperty ; rdfs:label "unit"@en . mock:formula a owl:AnnotationProperty ; rdfs:label "formula"@en . mock:derivedFrom a owl:ObjectProperty ; rdfs:label "derived from"@en . -mock:requires a owl:ObjectProperty ; rdfs:label "requires"@en . mock:Signal a owl:Class ; rdfs:subClassOf sosa:ObservableProperty ; rdfs:label "Signal"@en ; skos:definition "Any signal measured by a detector."@en . @@ -32,15 +33,15 @@ mock:Spectrum a owl:Class ; rdfs:subClassOf mock:Signal ; mock:DarkSpectrum a owl:Class ; rdfs:subClassOf mock:Spectrum ; rdfs:label "Dark spectrum"@en ; skos:definition "Spectrum with no light: the offset of the detector."@en ; - mock:requires mock:BeamBlocked . + pq:requiresState mock:BeamBlocked . mock:ReferenceSpectrum a owl:Class ; rdfs:subClassOf mock:Spectrum ; rdfs:label "Reference spectrum"@en ; skos:definition "Spectrum of the lamp alone, without the sample."@en ; - mock:requires mock:BeamOpen , mock:ReferenceInBeam . + pq:requiresState mock:BeamOpen , mock:ReferenceInBeam . mock:SampleSpectrum a owl:Class ; rdfs:subClassOf mock:Spectrum ; rdfs:label "Sample spectrum"@en ; skos:definition "Spectrum of the lamp after the sample."@en ; - mock:requires mock:BeamOpen , mock:SampleInBeam . + pq:requiresState mock:BeamOpen , mock:SampleInBeam . mock:Transmittance a owl:Class ; rdfs:subClassOf mock:Signal ; rdfs:label "Transmittance"@en ; skos:definition "Fraction of the light that goes through the sample."@en ; From 1b943ab2f3e8e03fd6efc77440bacfe86d1a724f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 21:19:15 +0000 Subject: [PATCH 13/18] Spectro Concepts: one button prepares the demo (ontology, probe, term of the spectrometer, states of the actuators) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81mHyjs9x4DB6NLuNY --- .../extensions/spectro_concepts.py | 38 +++++++++++++++++++ tests/test_spectro_concepts.py | 11 ++++++ 2 files changed, 49 insertions(+) diff --git a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py index e8e2dc1..8a1b04f 100644 --- a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py +++ b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py @@ -44,6 +44,11 @@ EXTENSION_NAME = 'Spectro Concepts' # displayed in the Extensions menu of the Dashboard CLASS_NAME = 'SpectroConcepts' # the name of the class below +NS = 'http://example.org/mockexamples#' +# the values of the actuators of the simulated bench, by plugin, with the state of the ontology each one means +BENCH_STATES = {'MockBeamBlock': [(1., NS + 'BeamBlocked'), (0., NS + 'BeamOpen')], + 'MockSampleChanger': [(0., NS + 'ReferenceInBeam'), (1., NS + 'SampleInBeam')]} + TERMS_FILE = Path(__file__).parent.parent.joinpath('resources', 'ontology', 'spectro_ontology.ttl') @@ -79,12 +84,16 @@ def setup_menus_and_toolbars(self, menubar: QtWidgets.QMenuBar = None): self.create_dashboard_toolbar(add_break=False) def setup_actions(self): + self.add_action('prepare', 'Prepare the demo', 'settings', + tip='Load the ontology, probe the detectors, give the term Spectrum to the spectrometer and ' + 'associate the values of the bench actuators with their states') self.add_action('check', 'What can I measure?', 'help', tip='Tell what the terms of the channels allow to measure and compute, without acquiring') self.add_action('run', 'Measure and compute', 'camera', tip='Set the bench for each measurement, grab, then compute and show') def connect_things(self): + self.connect_action('prepare', self.prepare_demo) self.connect_action('check', self.show_what_is_possible) self.connect_action('run', self.run_protocol) self.modules_manager.timeout_signal.connect(self._on_timeout) @@ -93,6 +102,35 @@ def _load_spectro_ontology(self) -> None: from pymodaq_ontology.source_factory import SourceFactory self.ontology_manager.set_source(SourceFactory.create('rdf', str(TERMS_FILE))) + def prepare_demo(self) -> str: + """Everything the user would do in the manager, as a shortcut for the experiments ``spectro_lab_a`` or + ``spectro_lab_b`` (the modules of the Dashboard: the experiment is loaded by the Dashboard, the extension is + started from it): load the ontology, probe the detectors, assign *Spectrum* to the spectrometer and associate + the values of the beam block and of the cuvette holder (found by their plugin) with their states.""" + manager = self.ontology_manager + if manager is None: + text = 'pymodaq_ontology is not installed' + else: + self._load_spectro_ontology() + manager.update_channels_from_dashboard() + manager.probe() + detectors = [c for c in manager.channels if c.kind == 'detector'] + for channel in detectors: + manager.assign(channel.key, NS + 'Spectrum') + actuators = {a.title: a.actuator for a in self.modules_manager.actuators_all} + associated = 0 + for module, plugin in actuators.items(): + for value, state in BENCH_STATES.get(plugin, []): + manager.assign_state(module, value, state) + associated += 1 + text = (f'Prepared: Spectrum given to {len(detectors)} detector channel(s), {associated} actuator values ' + f'associated with a state') + if not detectors or not associated: + text += ' (is the experiment spectro_lab_a or spectro_lab_b loaded?)' + self.set_status(text) + self.what.setPlainText(text) + return text + # ---- the ontology side: terms of the channels def terms_of(self, kind: str) -> dict[str, str]: """Term assigned to each channel of the detectors or of the actuators, by channel key""" diff --git a/tests/test_spectro_concepts.py b/tests/test_spectro_concepts.py index cd595f6..09b4a87 100644 --- a/tests/test_spectro_concepts.py +++ b/tests/test_spectro_concepts.py @@ -113,3 +113,14 @@ def test_the_protocol_measures_and_computes_whatever_the_names(extension, qtbot) dark, reference, sample = (extension._results[NS + name].mean() for name in ('DarkSpectrum', 'ReferenceSpectrum', 'SampleSpectrum')) assert dark < 200 < sample < reference + + +def test_one_button_prepares_the_assignment(extension, qtbot): + text = extension.prepare_demo() + assert text.startswith('Prepared: Spectrum given to 1 detector channel(s), 4 actuator values') + qtbot.wait(10) + shown = extension.show_what_is_possible() + assert shown.startswith('Can measure: Dark spectrum, Reference spectrum, Sample spectrum') + extension.run_protocol() + qtbot.waitUntil(lambda: not extension._busy, timeout=30000) + assert extension.settings['status'] == 'Computed: Transmittance, Absorbance' From bc8e3c55bdcf51fa310af5bb44e9dd3fa34665f2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 21:19:22 +0000 Subject: [PATCH 14/18] Spectro Concepts: describe the prepare button in the docstring Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81mHyjs9x4DB6NLuNY --- .../extensions/spectro_concepts.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py index 8a1b04f..a97e613 100644 --- a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py +++ b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py @@ -2,7 +2,10 @@ It uses the ``OntologyManager`` of the ``pymodaq_ontology`` package (menu *Ontology* of the Dashboard). The bench of the experiments ``spectro_lab_a`` and ``spectro_lab_b`` is one spectrometer, a beam block and a cuvette holder, with neutral -module names. The user assigns the term *Spectrum* to the +module names. The button *Prepare the demo* does the next two steps in one click (the Dashboard has loaded the +experiment): it loads the ontology, probes the detectors and assigns the term *Spectrum* to the spectrometer, then +associates the values of the beam block and of the cuvette holder with their states. By hand, the user assigns the +term *Spectrum* to the spectrometer, and associates each value of the actuators, as configured on the bench (1, 0, 12.5...), with a state of the ontology (*Beam blocked*, *Beam open*, *Reference in beam*, *Sample in beam*) in the manager. The extension only knows states, never the values nor the names of the modules, and can then: From d3eef213901710e72578ad9e1938dad75987fa95 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 21:30:06 +0000 Subject: [PATCH 15/18] Spectro Concepts: the term Spectrum goes only to the detectors that are spectrometers (by plugin) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81mHyjs9x4DB6NLuNY --- .../extensions/spectro_concepts.py | 8 ++++++-- tests/test_spectro_concepts.py | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py index a97e613..3c1e61f 100644 --- a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py +++ b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py @@ -52,6 +52,8 @@ BENCH_STATES = {'MockBeamBlock': [(1., NS + 'BeamBlocked'), (0., NS + 'BeamOpen')], 'MockSampleChanger': [(0., NS + 'ReferenceInBeam'), (1., NS + 'SampleInBeam')]} +SPECTROMETER_PLUGINS = ('MockSpectro',) # the plugins of the detectors that are spectrometers + TERMS_FILE = Path(__file__).parent.parent.joinpath('resources', 'ontology', 'spectro_ontology.ttl') @@ -108,7 +110,7 @@ def _load_spectro_ontology(self) -> None: def prepare_demo(self) -> str: """Everything the user would do in the manager, as a shortcut for the experiments ``spectro_lab_a`` or ``spectro_lab_b`` (the modules of the Dashboard: the experiment is loaded by the Dashboard, the extension is - started from it): load the ontology, probe the detectors, assign *Spectrum* to the spectrometer and associate + started from it): load the ontology, probe the detectors, assign *Spectrum* to the spectrometers (found by their plugin) and associate the values of the beam block and of the cuvette holder (found by their plugin) with their states.""" manager = self.ontology_manager if manager is None: @@ -117,7 +119,9 @@ def prepare_demo(self) -> str: self._load_spectro_ontology() manager.update_channels_from_dashboard() manager.probe() - detectors = [c for c in manager.channels if c.kind == 'detector'] + spectrometers = {d.title for d in self.modules_manager.detectors_all + if d.detector.module_name in SPECTROMETER_PLUGINS} + detectors = [c for c in manager.channels if c.kind == 'detector' and c.module in spectrometers] for channel in detectors: manager.assign(channel.key, NS + 'Spectrum') actuators = {a.title: a.actuator for a in self.modules_manager.actuators_all} diff --git a/tests/test_spectro_concepts.py b/tests/test_spectro_concepts.py index 09b4a87..6110d17 100644 --- a/tests/test_spectro_concepts.py +++ b/tests/test_spectro_concepts.py @@ -124,3 +124,18 @@ def test_one_button_prepares_the_assignment(extension, qtbot): extension.run_protocol() qtbot.waitUntil(lambda: not extension._busy, timeout=30000) assert extension.settings['status'] == 'Computed: Transmittance, Absorbance' + + +def test_the_term_is_given_to_the_spectrometer_only(extension, dashboard, qtbot): + creator = dashboard.module_creator + other = creator.create_detector('Other', DAQTypesEnum.DAQ0D) + creator.set_detector_type(other, DAQTypesEnum.DAQ0D, 'Mock') + creator.add_detector(other) + other.init_hardware_ui(True) + qtbot.waitUntil(lambda: other.initialized_state, timeout=10000) + dashboard.modules_manager.detectors_all = [*dashboard.modules_manager.detectors_all, other] + extension.prepare_demo() + manager = extension.ontology_manager + assigned = {k for k, v in manager.assignment.values.items() if v} + assert assigned and all(key.startswith('Spectro/') for key in assigned) + assert any(c.module == 'Other' for c in manager.channels) From cf156cb0667ec1794e2bd22f0bf5f3f085e0570a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 21:49:37 +0000 Subject: [PATCH 16/18] Spectro Concepts: a wide log under the viewers replaces the cramped text zone; each action and step writes to it Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81mHyjs9x4DB6NLuNY --- .../extensions/spectro_concepts.py | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py index 3c1e61f..69d81ab 100644 --- a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py +++ b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py @@ -20,6 +20,7 @@ Without ``pymodaq_ontology`` the extension tells that it cannot work. """ +from datetime import datetime from pathlib import Path from typing import Optional @@ -79,11 +80,12 @@ def setup_docks_and_widgets(self): self.docks['settings'] = gutils.Dock('Settings') self.dockarea.addDock(self.docks['settings']) self.docks['settings'].addWidget(self.settings_tree) - self.docks['what'] = gutils.Dock('What the terms allow') - self.dockarea.addDock(self.docks['what'], 'bottom', self.docks['settings']) - self.what = QtWidgets.QPlainTextEdit(readOnly=True) - self.docks['what'].addWidget(self.what) self.viewer = ViewerDispatcher(self.dockarea, title='Data') + self.docks['log'] = gutils.Dock('Log') + self.dockarea.addDock(self.docks['log'], 'bottom') # under everything: wide, one line per fact + self.log_widget = QtWidgets.QPlainTextEdit(readOnly=True) + self.log_widget.setLineWrapMode(QtWidgets.QPlainTextEdit.LineWrapMode.NoWrap) + self.docks['log'].addWidget(self.log_widget) def setup_menus_and_toolbars(self, menubar: QtWidgets.QMenuBar = None): self.create_dashboard_toolbar(add_break=False) @@ -134,8 +136,8 @@ def prepare_demo(self) -> str: f'associated with a state') if not detectors or not associated: text += ' (is the experiment spectro_lab_a or spectro_lab_b loaded?)' + self.log('Prepare the demo', text) self.set_status(text) - self.what.setPlainText(text) return text # ---- the ontology side: terms of the channels @@ -177,7 +179,7 @@ def show_what_is_possible(self) -> str: text = 'The ontology loaded in the manager has no graph: load an RDF ontology' else: text = self._describe(steps, problems, derivations) - self.what.setPlainText(text) + self.log('What can I measure?', text) self.set_status(text.splitlines()[0] if text else 'Idle') return text @@ -217,6 +219,8 @@ def _next_step(self): return self._step = self._queue.pop(0) self.set_status(f'Measuring {self._label(self._step.term)}') + moves = ', '.join(f'{module} = {value:g}' for module, value in self._step.moves) + self.log(f'Measuring {self._label(self._step.term)}', f'moves: {moves}') detectors = sorted({c.module for c in self.ontology_manager.channels if c.kind == 'detector' and self.ontology_manager.assignment.get(c.key)}) self.modules_manager.selected_actuators_name = [module for module, _ in self._step.moves] @@ -238,6 +242,7 @@ def _on_data(self, data: DataToExport): spectrum = next((array for term, array in arrays.items() if derivations.is_a(self._step.term, term)), None) if spectrum is not None: self._results[self._step.term] = spectrum + self.log(f'Got {self._label(self._step.term)}', f'mean {spectrum.mean():.4g} counts') self._axis = axis self._problems.extend(p for p in problems if p not in self._problems) self._next_step() @@ -273,10 +278,11 @@ def _finish(self): computed = [DataCalculated(self._label(iri), data=[array], axes=[self._axis] if self._axis is not None else [], labels=[self._label(iri)]) for iri, array in results.items()] self.viewer.show_data(DataToExport('spectro', data=[*measured, *computed])) + self.dockarea.moveDock(self.docks['log'], 'bottom', None) # wide, under the viewers that just appeared lines = ['Measured: ' + ', '.join(self._label(i) for i in self._results), 'Computed: ' + (', '.join(self._label(i) for i in results) or 'nothing')] lines.extend(f'Unit: {p}' for p in self._problems) - self.what.setPlainText('\n'.join(lines)) + self.log('Measure and compute', '\n'.join(lines)) self.set_status(lines[1]) self._busy = False self.set_action_enabled('run', True) @@ -288,6 +294,11 @@ def _on_timeout(self, missing_modules: list): self.set_action_enabled('run', True) self.set_status(f'Timeout: {", ".join(missing_modules)}') + def log(self, action: str, text: str = '') -> None: + """Add to the log what an action did: a titled block with the time, one fact by line""" + lines = [f'[{datetime.now():%H:%M:%S}] {action}', *(f' {line}' for line in text.splitlines()), ''] + self.log_widget.appendPlainText('\n'.join(lines)) + def set_status(self, status: str): self.settings.child('status').setValue(status) From 2e318fd695c58df33a00ecbe2bd7f7eeb4e934fd Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 21:49:46 +0000 Subject: [PATCH 17/18] Spectro Concepts: wrap a docstring line Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81mHyjs9x4DB6NLuNY --- .../extensions/spectro_concepts.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py index 69d81ab..8f0d447 100644 --- a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py +++ b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py @@ -112,8 +112,9 @@ def _load_spectro_ontology(self) -> None: def prepare_demo(self) -> str: """Everything the user would do in the manager, as a shortcut for the experiments ``spectro_lab_a`` or ``spectro_lab_b`` (the modules of the Dashboard: the experiment is loaded by the Dashboard, the extension is - started from it): load the ontology, probe the detectors, assign *Spectrum* to the spectrometers (found by their plugin) and associate - the values of the beam block and of the cuvette holder (found by their plugin) with their states.""" + started from it): load the ontology, probe the detectors, assign *Spectrum* to the spectrometers (found by + their plugin) and associate the values of the beam block and of the cuvette holder (found by their plugin) + with their states.""" manager = self.ontology_manager if manager is None: text = 'pymodaq_ontology is not installed' From a8127e42b4513f6bb8d9371fec1bf78e01b6ef70 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 22:18:56 +0000 Subject: [PATCH 18/18] Spectro Concepts: the log takes the left dock in place of the settings tree, a time on each line and a separator between actions Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81mHyjs9x4DB6NLuNY --- .../extensions/spectro_concepts.py | 25 ++++++++----------- tests/test_spectro_concepts.py | 4 +-- 2 files changed, 13 insertions(+), 16 deletions(-) diff --git a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py index 8f0d447..3298571 100644 --- a/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py +++ b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py @@ -60,32 +60,28 @@ class SpectroConcepts(CustomExt): - params = [ - {'title': 'Status:', 'name': 'status', 'type': 'str', 'value': 'Idle', 'readonly': True}, - ] + params = [] # nothing to set: the toolbar acts, the log tells def __init__(self, parent: gutils.DockArea, dashboard): super().__init__(parent, dashboard) self.ontology_manager = getattr(dashboard, 'extra_managers', {}).get('ontology') self._busy = False + self.status = 'Idle' self._queue, self._results, self._problems, self._step, self._axis = [], {}, [], None, None self.derivations: Optional[Derivations] = None self.setup_ui() if self.ontology_manager is None: - self.set_status('pymodaq_ontology is not installed: nothing to compute') + self.log('Start', 'pymodaq_ontology is not installed: nothing to compute') elif self.ontology_manager.source is None: self._load_spectro_ontology() def setup_docks_and_widgets(self): - self.docks['settings'] = gutils.Dock('Settings') - self.dockarea.addDock(self.docks['settings']) - self.docks['settings'].addWidget(self.settings_tree) - self.viewer = ViewerDispatcher(self.dockarea, title='Data') self.docks['log'] = gutils.Dock('Log') - self.dockarea.addDock(self.docks['log'], 'bottom') # under everything: wide, one line per fact + self.dockarea.addDock(self.docks['log']) # the left column, the viewers come on its right self.log_widget = QtWidgets.QPlainTextEdit(readOnly=True) - self.log_widget.setLineWrapMode(QtWidgets.QPlainTextEdit.LineWrapMode.NoWrap) self.docks['log'].addWidget(self.log_widget) + self.log_widget.setMinimumWidth(420) # a line of the log fits without wrapping + self.viewer = ViewerDispatcher(self.dockarea, title='Data') def setup_menus_and_toolbars(self, menubar: QtWidgets.QMenuBar = None): self.create_dashboard_toolbar(add_break=False) @@ -279,7 +275,6 @@ def _finish(self): computed = [DataCalculated(self._label(iri), data=[array], axes=[self._axis] if self._axis is not None else [], labels=[self._label(iri)]) for iri, array in results.items()] self.viewer.show_data(DataToExport('spectro', data=[*measured, *computed])) - self.dockarea.moveDock(self.docks['log'], 'bottom', None) # wide, under the viewers that just appeared lines = ['Measured: ' + ', '.join(self._label(i) for i in self._results), 'Computed: ' + (', '.join(self._label(i) for i in results) or 'nothing')] lines.extend(f'Unit: {p}' for p in self._problems) @@ -293,15 +288,17 @@ def _on_timeout(self, missing_modules: list): self.modules_manager.forget_callback(callback, ModuleType.Control) self._busy = False self.set_action_enabled('run', True) + self.log('Timeout', ', '.join(missing_modules)) self.set_status(f'Timeout: {", ".join(missing_modules)}') def log(self, action: str, text: str = '') -> None: - """Add to the log what an action did: a titled block with the time, one fact by line""" - lines = [f'[{datetime.now():%H:%M:%S}] {action}', *(f' {line}' for line in text.splitlines()), ''] + """Add to the log what an action did: the action then one fact by line, each with its time, and a separator""" + now = f'{datetime.now():%H:%M:%S}' + lines = [f'[{now}] {action}', *(f'[{now}] {line}' for line in text.splitlines()), '-' * 44] self.log_widget.appendPlainText('\n'.join(lines)) def set_status(self, status: str): - self.settings.child('status').setValue(status) + self.status = status def _quit_fun(self) -> bool: if self._busy: diff --git a/tests/test_spectro_concepts.py b/tests/test_spectro_concepts.py index 6110d17..32000d8 100644 --- a/tests/test_spectro_concepts.py +++ b/tests/test_spectro_concepts.py @@ -107,7 +107,7 @@ def test_the_protocol_measures_and_computes_whatever_the_names(extension, qtbot) assert 'Then can compute: Transmittance, Absorbance' in text extension.run_protocol() qtbot.waitUntil(lambda: not extension._busy, timeout=30000) - assert extension.settings['status'] == 'Computed: Transmittance, Absorbance' + assert extension.status == 'Computed: Transmittance, Absorbance' assert set(extension._results) == {NS + 'DarkSpectrum', NS + 'ReferenceSpectrum', NS + 'SampleSpectrum'} # the spectra are the ones of the states of the bench: dark level, lamp, lamp through the sample dark, reference, sample = (extension._results[NS + name].mean() @@ -123,7 +123,7 @@ def test_one_button_prepares_the_assignment(extension, qtbot): assert shown.startswith('Can measure: Dark spectrum, Reference spectrum, Sample spectrum') extension.run_protocol() qtbot.waitUntil(lambda: not extension._busy, timeout=30000) - assert extension.settings['status'] == 'Computed: Transmittance, Absorbance' + assert extension.status == 'Computed: Transmittance, Absorbance' def test_the_term_is_given_to_the_spectrometer_only(extension, dashboard, qtbot):