diff --git a/README.rst b/README.rst index b595a4f..1c924aa 100644 --- a/README.rst +++ b/README.rst @@ -289,7 +289,17 @@ 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. - +* **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. 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*, + *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. 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..2837d04 --- /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 reference 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/extensions/spectro_concepts.py b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py new file mode 100644 index 0000000..3298571 --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/extensions/spectro_concepts.py @@ -0,0 +1,326 @@ +"""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 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 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: + +* 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, 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; +* 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. +""" +from datetime import datetime +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.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, Step + +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 + +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')]} + +SPECTROMETER_PLUGINS = ('MockSpectro',) # the plugins of the detectors that are spectrometers + +TERMS_FILE = Path(__file__).parent.parent.joinpath('resources', 'ontology', 'spectro_ontology.ttl') + + +class SpectroConcepts(CustomExt): + + 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.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['log'] = gutils.Dock('Log') + self.dockarea.addDock(self.docks['log']) # the left column, the viewers come on its right + self.log_widget = QtWidgets.QPlainTextEdit(readOnly=True) + 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) + + 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) + + 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 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' + else: + self._load_spectro_ontology() + manager.update_channels_from_dashboard() + manager.probe() + 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} + 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.log('Prepare the demo', text) + self.set_status(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""" + 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 == kind + and manager.assignment.get(c.key)} + + def _derivations(self) -> Optional[Derivations]: + """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 + 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 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()) + steps, problems = derivations.plan(detector_terms, self.ontology_manager.moves_for_states) + return steps, problems, derivations + + def show_what_is_possible(self) -> str: + """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: + 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(steps, problems, derivations) + self.log('What can I measure?', text) + self.set_status(text.splitlines()[0] if text else 'Idle') + return text + + def _describe(self, steps: list[Step], problems: dict[str, list[str]], derivations: Derivations) -> str: + lines = [] + 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)') + for step in steps: + 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}') + 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) + + # ---- the protocol: set the bench, grab, for each measurement + def run_protocol(self): + if self._busy or self.ontology_manager is None: + return + 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)}') + 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] + 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) + 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.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() + + 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 + 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 _finish(self): + derivations = self._derivations() + 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=[*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.log('Measure and compute', '\n'.join(lines)) + self.set_status(lines[1]) + self._busy = False + self.set_action_enabled('run', True) + + def _on_timeout(self, missing_modules: list): + 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('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: 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.status = 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/spectro_bench.py b/src/pymodaq_plugins_mockexamples/hardware/spectro_bench.py new file mode 100644 index 0000000..d184b41 --- /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 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 +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 reference 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 new file mode 100644 index 0000000..398b95a --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/ontology_derivations.py @@ -0,0 +1,137 @@ +"""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 (``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 +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 dataclasses import dataclass +from typing import Callable, Iterable, Optional + +import numpy as np +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) + + +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, +} + + +@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 + + 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)) + self.requirements: dict[str, list[str]] = {} # measurement term -> the states of the bench it 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]]] + ) -> 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 (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 + + Returns + ------- + 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 = moves_for_states(self.requirements[measurement]) + if missing: + problems[measurement] = sorted(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""" + 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..e6529a3 --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/resources/ontology/spectro_ontology.ttl @@ -0,0 +1,80 @@ +@prefix mock: . +@prefix pq: . +@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) +# 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 +# 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: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 ; + 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 ; + 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 ; + 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 ; + 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: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 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). +# 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:NamedIndividual , mock:BeamBlock ; + rdfs:label "Beam open"@en ; skos:definition "The beam goes through."@en . +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: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 ) ] . 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..cf89ff7 --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/resources/spectro_lab_a.xml @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000..02a3dc0 --- /dev/null +++ b/src/pymodaq_plugins_mockexamples/resources/spectro_lab_b.xml @@ -0,0 +1 @@ +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 new file mode 100644 index 0000000..68cd03b --- /dev/null +++ b/tests/test_ontology_derivations.py @@ -0,0 +1,115 @@ +"""What the terms let the experiment do: the statements of 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.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 = NS + 'Spectrum' +BEAM_BLOCKED, BEAM_OPEN, REFERENCE_IN, SAMPLE_IN = (NS + name for name in ('BeamBlocked', 'BeamOpen', 'ReferenceInBeam', + 'SampleInBeam')) + + +@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(): + 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): + assert derivations.rules[TRANSMITTANCE] == sorted([SAMPLE, REFERENCE, DARK]) + assert derivations.rules[ABSORBANCE] == [TRANSMITTANCE] + + +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, REFERENCE_IN]) + assert derivations.requirements[SAMPLE] == sorted([BEAM_OPEN, SAMPLE_IN]) + + +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.), REFERENCE_IN: ('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', 12.5)]), Step(REFERENCE, [('M2', 3.), ('M1', 0.)]), + Step(SAMPLE, [('M2', 3.), ('M1', 1.)])] + + +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'], fake_moves(VALUES)) == ([], {}) + + +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_general_spectrum_is_not_a_sample_spectrum(derivations): + available = spectra() + available[SPECTRUM] = available.pop(SAMPLE) + assert derivations.computable(available) == [] + + +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 + reference = bench.grab_spectrum() + bench.sample_position = 1 + 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 new file mode 100644 index 0000000..32000d8 --- /dev/null +++ b/tests/test_spectro_concepts.py @@ -0,0 +1,141 @@ +"""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 is, is the plugin and, for the user, the term assigned +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 + 'ReferenceInBeam': ('M1', 0.), NS + 'SampleInBeam': ('M1', 1.)} + + +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 + 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() + + +@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, 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() + 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): + assert extension.ontology_manager.source is not None + assert NS + 'Transmittance' in extension.ontology_manager.terms + + +def test_nothing_can_be_measured_without_terms(extension): + assert extension.show_what_is_possible().startswith('Nothing can be measured yet') + + +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, 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, 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 + extension.run_protocol() + qtbot.waitUntil(lambda: not extension._busy, timeout=30000) + 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() + 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.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)