pymodaq 5.0.18__py3-none-any.whl → 5.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of pymodaq might be problematic. Click here for more details.

Files changed (92) hide show
  1. pymodaq/__init__.py +23 -11
  2. pymodaq/control_modules/__init__.py +1 -0
  3. pymodaq/control_modules/daq_move.py +451 -246
  4. pymodaq/control_modules/daq_move_ui/__init__.py +0 -0
  5. pymodaq/control_modules/daq_move_ui/factory.py +48 -0
  6. pymodaq/control_modules/{daq_move_ui.py → daq_move_ui/ui_base.py} +168 -210
  7. pymodaq/control_modules/daq_move_ui/uis/__init__.py +0 -0
  8. pymodaq/control_modules/daq_move_ui/uis/binary.py +139 -0
  9. pymodaq/control_modules/daq_move_ui/uis/original.py +120 -0
  10. pymodaq/control_modules/daq_move_ui/uis/relative.py +124 -0
  11. pymodaq/control_modules/daq_move_ui/uis/simple.py +126 -0
  12. pymodaq/control_modules/daq_viewer.py +113 -101
  13. pymodaq/control_modules/daq_viewer_ui.py +41 -31
  14. pymodaq/control_modules/mocks.py +2 -2
  15. pymodaq/control_modules/move_utility_classes.py +113 -41
  16. pymodaq/control_modules/thread_commands.py +137 -0
  17. pymodaq/control_modules/ui_utils.py +72 -0
  18. pymodaq/control_modules/utils.py +107 -63
  19. pymodaq/control_modules/viewer_utility_classes.py +13 -17
  20. pymodaq/dashboard.py +1294 -625
  21. pymodaq/examples/qt_less_standalone_module.py +48 -11
  22. pymodaq/extensions/__init__.py +8 -3
  23. pymodaq/extensions/adaptive/__init__.py +2 -0
  24. pymodaq/extensions/adaptive/adaptive_optimization.py +179 -0
  25. pymodaq/extensions/adaptive/loss_function/_1d_loss_functions.py +73 -0
  26. pymodaq/extensions/adaptive/loss_function/_2d_loss_functions.py +73 -0
  27. pymodaq/extensions/adaptive/loss_function/__init__.py +3 -0
  28. pymodaq/extensions/adaptive/loss_function/loss_factory.py +110 -0
  29. pymodaq/extensions/adaptive/utils.py +123 -0
  30. pymodaq/extensions/bayesian/__init__.py +1 -1
  31. pymodaq/extensions/bayesian/acquisition/__init__.py +2 -0
  32. pymodaq/extensions/bayesian/acquisition/acquisition_function_factory.py +80 -0
  33. pymodaq/extensions/bayesian/acquisition/base_acquisition_function.py +105 -0
  34. pymodaq/extensions/bayesian/bayesian_optimization.py +143 -0
  35. pymodaq/extensions/bayesian/utils.py +71 -297
  36. pymodaq/extensions/daq_logger/daq_logger.py +7 -12
  37. pymodaq/extensions/daq_logger/h5logging.py +1 -1
  38. pymodaq/extensions/daq_scan.py +30 -55
  39. pymodaq/extensions/data_mixer/__init__.py +0 -0
  40. pymodaq/extensions/data_mixer/daq_0Dviewer_DataMixer.py +97 -0
  41. pymodaq/extensions/data_mixer/data_mixer.py +262 -0
  42. pymodaq/extensions/data_mixer/model.py +108 -0
  43. pymodaq/extensions/data_mixer/models/__init__.py +0 -0
  44. pymodaq/extensions/data_mixer/models/equation_model.py +91 -0
  45. pymodaq/extensions/data_mixer/models/gaussian_fit_model.py +65 -0
  46. pymodaq/extensions/data_mixer/parser.py +53 -0
  47. pymodaq/extensions/data_mixer/utils.py +23 -0
  48. pymodaq/extensions/h5browser.py +3 -34
  49. pymodaq/extensions/optimizers_base/__init__.py +0 -0
  50. pymodaq/extensions/optimizers_base/optimizer.py +1016 -0
  51. pymodaq/extensions/optimizers_base/thread_commands.py +22 -0
  52. pymodaq/extensions/optimizers_base/utils.py +427 -0
  53. pymodaq/extensions/pid/actuator_controller.py +3 -2
  54. pymodaq/extensions/pid/daq_move_PID.py +107 -30
  55. pymodaq/extensions/pid/pid_controller.py +613 -287
  56. pymodaq/extensions/pid/utils.py +8 -5
  57. pymodaq/extensions/utils.py +17 -2
  58. pymodaq/resources/config_template.toml +57 -0
  59. pymodaq/resources/preset_default.xml +1 -1
  60. pymodaq/utils/config.py +10 -4
  61. pymodaq/utils/daq_utils.py +14 -0
  62. pymodaq/utils/data.py +1 -0
  63. pymodaq/utils/gui_utils/loader_utils.py +25 -15
  64. pymodaq/utils/h5modules/module_saving.py +134 -22
  65. pymodaq/utils/leco/daq_move_LECODirector.py +123 -84
  66. pymodaq/utils/leco/daq_xDviewer_LECODirector.py +84 -97
  67. pymodaq/utils/leco/director_utils.py +32 -16
  68. pymodaq/utils/leco/leco_director.py +104 -27
  69. pymodaq/utils/leco/pymodaq_listener.py +186 -97
  70. pymodaq/utils/leco/rpc_method_definitions.py +43 -0
  71. pymodaq/utils/leco/utils.py +25 -25
  72. pymodaq/utils/managers/batchscan_manager.py +12 -11
  73. pymodaq/utils/managers/modules_manager.py +74 -33
  74. pymodaq/utils/managers/overshoot_manager.py +11 -10
  75. pymodaq/utils/managers/preset_manager.py +100 -64
  76. pymodaq/utils/managers/preset_manager_utils.py +163 -107
  77. pymodaq/utils/managers/remote_manager.py +21 -16
  78. pymodaq/utils/scanner/scan_factory.py +12 -3
  79. pymodaq/utils/scanner/scan_selector.py +1 -3
  80. pymodaq/utils/scanner/scanner.py +35 -6
  81. pymodaq/utils/scanner/scanners/_1d_scanners.py +15 -46
  82. pymodaq/utils/scanner/scanners/_2d_scanners.py +21 -68
  83. pymodaq/utils/scanner/scanners/sequential.py +50 -31
  84. pymodaq/utils/scanner/scanners/tabular.py +45 -28
  85. {pymodaq-5.0.18.dist-info → pymodaq-5.1.0.dist-info}/METADATA +7 -6
  86. pymodaq-5.1.0.dist-info/RECORD +154 -0
  87. {pymodaq-5.0.18.dist-info → pymodaq-5.1.0.dist-info}/entry_points.txt +0 -2
  88. pymodaq/extensions/bayesian/bayesian_optimisation.py +0 -690
  89. pymodaq/utils/leco/desktop.ini +0 -2
  90. pymodaq-5.0.18.dist-info/RECORD +0 -121
  91. {pymodaq-5.0.18.dist-info → pymodaq-5.1.0.dist-info}/WHEEL +0 -0
  92. {pymodaq-5.0.18.dist-info → pymodaq-5.1.0.dist-info}/licenses/LICENSE +0 -0
@@ -1,690 +0,0 @@
1
- from typing import List, Union, Optional
2
- import tempfile
3
- from pathlib import Path
4
-
5
- from qtpy import QtWidgets, QtCore
6
- import time
7
- import numpy as np
8
-
9
- from pymodaq.utils.data import DataToExport, DataToActuators, DataCalculated, DataActuator
10
- from pymodaq.utils.managers.modules_manager import ModulesManager
11
- from pymodaq_utils import utils
12
- from pymodaq_utils import config as config_mod
13
- from pymodaq_utils.enums import BaseEnum
14
-
15
-
16
- from pymodaq_utils.logger import set_logger, get_module_name
17
-
18
- from pymodaq_gui.plotting.data_viewers.viewer0D import Viewer0D
19
- from pymodaq_gui.plotting.data_viewers.viewer import ViewerDispatcher, ViewersEnum
20
- from pymodaq_gui.utils import QLED
21
- from pymodaq_gui.utils.utils import mkQApp
22
- from pymodaq_gui import utils as gutils
23
- from pymodaq_gui.parameter import utils as putils
24
- from pymodaq_gui.h5modules.saving import H5Saver
25
-
26
- try:
27
- from pymodaq_gui.config_saver_loader import ConfigSaverLoader
28
- except ModuleNotFoundError:
29
- from pymodaq_gui.config import ConfigSaverLoader #backcompatibility
30
-
31
- from pymodaq_data.h5modules.data_saving import DataEnlargeableSaver
32
-
33
-
34
- from pymodaq.extensions.bayesian.utils import (get_bayesian_models, BayesianModelGeneric,
35
- BayesianAlgorithm, UtilityKind,
36
- UtilityParameters, StopType, StoppingParameters)
37
- from pymodaq.post_treatment.load_and_plot import LoaderPlotter
38
- from pymodaq.extensions.bayesian.utils import BayesianConfig
39
- from pymodaq.extensions.utils import CustomExt
40
-
41
- EXTENSION_NAME = 'BayesianOptimisation'
42
- CLASS_NAME = 'BayesianOptimisation'
43
-
44
- logger = set_logger(get_module_name(__file__))
45
- config = config_mod.Config()
46
-
47
-
48
- class DataNames(BaseEnum):
49
- Fitness = 0
50
- Individual = 1
51
- ProbedData = 2
52
- Actuators = 3
53
- Kappa = 4
54
-
55
-
56
- class BayesianOptimisation(CustomExt):
57
- """ PyMoDAQ extension of the DashBoard to perform the optimization of a target signal
58
- taken form the detectors as a function of one or more parameters controlled by the actuators.
59
- """
60
-
61
- command_runner = QtCore.Signal(utils.ThreadCommand)
62
- models = get_bayesian_models()
63
- explored_viewer_name = 'algo/ProbedData'
64
- optimisation_done_signal = QtCore.Signal(DataToExport)
65
-
66
- params = [
67
- {'title': 'Main Settings:', 'name': 'main_settings', 'expanded': True, 'type': 'group',
68
- 'children': [
69
- {'title': 'Utility Function:', 'name': 'utility', 'expanded': False, 'type': 'group',
70
- 'children': [
71
- {'title': 'Kind', 'name': 'kind', 'type': 'list',
72
- 'limits': UtilityKind.to_dict_value()},
73
- {'title': 'Kappa:', 'name': 'kappa', 'type': 'slide', 'value': 2.576,
74
- 'min': 0.001, 'max': 100, 'subtype': 'log',
75
- 'tip': 'Parameter to indicate how closed are the next parameters sampled.'
76
- 'Higher value = favors spaces that are least explored.'
77
- 'Lower value = favors spaces where the regression function is the '
78
- 'highest.'},
79
- {'title': 'Kappa actual:', 'name': 'kappa_actual', 'type': 'float', 'value': 2.576,
80
- 'tip': 'Current value of the kappa parameter', 'readonly': True},
81
- {'title': 'xi:', 'name': 'xi', 'type': 'slide', 'value': 0,
82
- 'tip': 'Governs the exploration/exploitation tradeoff.'
83
- 'Lower prefers exploitation, higher prefers exploration.'},
84
- {'title': 'Kappa decay:', 'name': 'kappa_decay', 'type': 'float', 'value': 0.9,
85
- 'tip': 'kappa is multiplied by this factor every iteration.'},
86
- {'title': 'Kappa decay delay:', 'name': 'kappa_decay_delay', 'type': 'int',
87
- 'value': 20, 'tip': 'Number of iterations that must have passed before applying '
88
- 'the decay to kappa.'},
89
- ]},
90
- {'title': 'Stopping Criteria:', 'name': 'stopping', 'expanded': False, 'type': 'group',
91
- 'children': [
92
- {'title': 'Niteration', 'name': 'niter', 'type': 'int', 'value': 100, 'min': -1},
93
- {'title': 'Type:', 'name': 'stop_type', 'type': 'list',
94
- 'limits': StopType.names()},
95
- {'title': 'Tolerance', 'name': 'tolerance', 'type': 'slide', 'value': 1e-2,
96
- 'min': 1e-8, 'max': 1, 'subtype': 'log',},
97
- {'title': 'Npoints', 'name': 'npoints', 'type': 'int', 'value': 5, 'min': 1},
98
- ]},
99
- {'title': 'Ini. State', 'name': 'ini_random', 'type': 'int', 'value': 5},
100
- {'title': 'bounds', 'name': 'bounds', 'type': 'group', 'children': []},
101
- ]},
102
-
103
- {'title': 'Models', 'name': 'models', 'type': 'group', 'expanded': True, 'visible': True,
104
- 'children': [
105
- {'title': 'Models class:', 'name': 'model_class', 'type': 'list',
106
- 'limits': [d['name'] for d in models]},
107
- {'title': 'Ini Model', 'name': 'ini_model', 'type': 'action', },
108
- {'title': 'Ini Algo', 'name': 'ini_runner', 'type': 'action', 'enabled': False},
109
- {'title': 'Model params:', 'name': 'model_params', 'type': 'group', 'children': []},
110
- ]},
111
- {'title': 'Move settings:', 'name': 'move_settings', 'expanded': True, 'type': 'group',
112
- 'visible': False, 'children': [
113
- {'title': 'Units:', 'name': 'units', 'type': 'str', 'value': ''}]},
114
-
115
- ]
116
-
117
- def __init__(self, dockarea, dashboard):
118
- super().__init__(dockarea, dashboard)
119
-
120
- self.algorithm: Optional[BayesianAlgorithm] = None
121
- self.viewer_fitness: Optional[Viewer0D] = None
122
- self.viewer_observable: Optional[ViewerDispatcher] = None
123
- self.model_class: Optional[BayesianModelGeneric] = None
124
- self._save_main_settings = True
125
- self._modules_manager = ModulesManager(self.dashboard.detector_modules,
126
- self.dashboard.actuators_modules)
127
- self.modules_manager.actuators_changed[list].connect(self.update_actuators)
128
- self.modules_manager.settings.child('data_dimensions').setOpts(expanded=False)
129
- self.modules_manager.settings.child('actuators_positions').setOpts(expanded=False)
130
- self.setup_ui()
131
-
132
- self.bayesian_config = BayesianConfig()
133
- self.mainsettings_saver_loader = ConfigSaverLoader(
134
- self.settings.child('main_settings'), self.bayesian_config)
135
-
136
- self.h5temp: H5Saver = None
137
- self.temp_path: tempfile.TemporaryDirectory = None
138
-
139
- self.enlargeable_saver: DataEnlargeableSaver = None
140
- self.live_plotter = LoaderPlotter(self.dockarea)
141
-
142
- self.enl_index = 0
143
-
144
- self.settings.child('models', 'ini_model').sigActivated.connect(
145
- self.get_action('ini_model').trigger)
146
-
147
- self.settings.child('models', 'ini_runner').sigActivated.connect(
148
- self.get_action('ini_runner').trigger)
149
-
150
- @property
151
- def modules_manager(self) -> ModulesManager:
152
- return self._modules_manager
153
-
154
- def setup_docks(self):
155
- """
156
- to be subclassed to setup the docks layout
157
- for instance:
158
-
159
- self.docks['ADock'] = gutils.Dock('ADock name)
160
- self.dockarea.addDock(self.docks['ADock"])
161
- self.docks['AnotherDock'] = gutils.Dock('AnotherDock name)
162
- self.dockarea.addDock(self.docks['AnotherDock"], 'bottom', self.docks['ADock"])
163
-
164
- See Also
165
- ########
166
- pyqtgraph.dockarea.Dock
167
- """
168
- self.docks['settings'] = gutils.Dock('Settings')
169
- self.dockarea.addDock(self.docks['settings'])
170
- splitter = QtWidgets.QSplitter(QtCore.Qt.Vertical)
171
- self.docks['settings'].addWidget(splitter)
172
- splitter.addWidget(self.settings_tree)
173
- splitter.addWidget(self.modules_manager.settings_tree)
174
- self.modules_manager.show_only_control_modules(False)
175
- splitter.setSizes((int(self.dockarea.height() / 2),
176
- int(self.dockarea.height() / 2)))
177
-
178
- widget_observable = QtWidgets.QWidget()
179
- widget_observable.setLayout(QtWidgets.QHBoxLayout())
180
- observable_dockarea = gutils.DockArea()
181
- widget_observable.layout().addWidget(observable_dockarea)
182
- self.viewer_observable = ViewerDispatcher(observable_dockarea, direction='bottom')
183
- self.docks['observable'] = gutils.Dock('Observable')
184
- self.dockarea.addDock(self.docks['observable'], 'right', self.docks['settings'])
185
- self.docks['observable'].addWidget(widget_observable)
186
-
187
- if len(self.models) != 0:
188
- self.get_set_model_params(self.models[0]['name'])
189
-
190
- def get_set_model_params(self, model_name):
191
- self.settings.child('models', 'model_params').clearChildren()
192
- if len(self.models) > 0:
193
- model_class = utils.find_dict_in_list_from_key_val(self.models, 'name', model_name)['class']
194
- params = getattr(model_class, 'params')
195
- self.settings.child('models', 'model_params').addChildren(params)
196
-
197
- def setup_menu(self, menubar: QtWidgets.QMenuBar = None):
198
- '''
199
- to be subclassed
200
- create menu for actions contained into the self.actions_manager, for instance:
201
-
202
- For instance:
203
-
204
- file_menu = self.menubar.addMenu('File')
205
- self.actions_manager.affect_to('load', file_menu)
206
- self.actions_manager.affect_to('save', file_menu)
207
-
208
- file_menu.addSeparator()
209
- self.actions_manager.affect_to('quit', file_menu)
210
- '''
211
- pass
212
-
213
- def value_changed(self, param):
214
- ''' to be subclassed for actions to perform when one of the param's value in self.settings is changed
215
-
216
- For instance:
217
- if param.name() == 'do_something':
218
- if param.value():
219
- print('Do something')
220
- self.settings.child('main_settings', 'something_done').setValue(False)
221
-
222
- Parameters
223
- ----------
224
- param: (Parameter) the parameter whose value just changed
225
- '''
226
- if param.name() == 'model_class':
227
- self.get_set_model_params(param.value())
228
- elif param.name() in putils.iter_children(self.settings.child('models', 'model_params'), []):
229
- if self.model_class is not None:
230
- self.model_class.update_settings(param)
231
- elif param.name() in putils.iter_children(
232
- self.settings.child('main_settings', 'utility'), []):
233
- if param.name() != 'kappa_actual':
234
- self.update_utility_function()
235
- elif param.name() in putils.iter_children(
236
- self.settings.child('main_settings', 'bounds'), []):
237
- self.update_bounds()
238
- elif param.name() in putils.iter_children(
239
- self.settings.child('main_settings', 'stopping'), []):
240
- self.update_stopping_criteria()
241
- if self._save_main_settings and param.name() in putils.iter_children(
242
- self.settings.child('main_settings'), []):
243
- self.mainsettings_saver_loader.save_config()
244
-
245
- def update_utility_function(self):
246
- utility_settings = self.settings.child('main_settings', 'utility')
247
- uparams = UtilityParameters(utility_settings['kind'], utility_settings['kappa'],
248
- utility_settings['xi'], utility_settings['kappa_decay'],
249
- utility_settings['kappa_decay_delay'])
250
- self.command_runner.emit(utils.ThreadCommand('utility', uparams))
251
-
252
- def get_stopping_parameters(self) -> StoppingParameters:
253
- stopping_settings = self.settings.child('main_settings', 'stopping')
254
- stopping_params = StoppingParameters(stopping_settings['niter'],
255
- stopping_settings['stop_type'],
256
- stopping_settings['tolerance'],
257
- stopping_settings['npoints'])
258
- return stopping_params
259
-
260
- def update_stopping_criteria(self):
261
- self.command_runner.emit(utils.ThreadCommand('stopping', self.get_stopping_parameters()))
262
-
263
- def update_bounds(self):
264
- bounds = {}
265
- for child in self.settings.child('main_settings', 'bounds').children():
266
- bounds[child.name()] = (child['min'], child['max'])
267
-
268
- self.command_runner.emit(utils.ThreadCommand('bounds', bounds))
269
-
270
- def setup_actions(self):
271
- logger.debug('setting actions')
272
- self.add_action('quit', 'Quit', 'close2', "Quit program")
273
- self.add_action('ini_model', 'Init Model', 'ini')
274
- self.add_widget('model_led', QLED, toolbar=self.toolbar)
275
- self.add_action('ini_runner', 'Init the Optimisation Algorithm', 'ini', checkable=True,
276
- enabled=False)
277
- self.add_widget('runner_led', QLED, toolbar=self.toolbar)
278
- self.add_action('run', 'Run Optimisation', 'run2', checkable=True, enabled=False)
279
- self.add_action('gotobest', 'Got to best individual', 'move_contour', enabled=False,
280
- tip='Go to the best individual guessed by the algorithm')
281
- logger.debug('actions set')
282
-
283
- def connect_things(self):
284
- logger.debug('connecting things')
285
- self.connect_action('quit', self.quit, )
286
- self.connect_action('ini_model', self.ini_model)
287
- self.connect_action('ini_runner', self.ini_optimisation_runner)
288
- self.connect_action('run', self.run_optimisation)
289
- self.connect_action('gotobest', self.go_to_best)
290
-
291
- def go_to_best(self):
292
- best_individual = self.algorithm.best_individual
293
- actuators = self.modules_manager.selected_actuators_name
294
- dte_act = DataToActuators('best', data=[
295
- DataActuator(actuators[ind], data=float(best_individual[ind])) for ind in range(len(best_individual))
296
- ],
297
- mode='abs')
298
- self.modules_manager.connect_actuators(True)
299
- self.modules_manager.move_actuators(dte_act, polling=True)
300
- self.modules_manager.connect_actuators(False)
301
-
302
- self.modules_manager.grab_datas()
303
-
304
- def quit(self):
305
- self.dockarea.parent().close()
306
- self.clean_h5_temp()
307
-
308
- def set_model(self):
309
- model_name = self.settings.child('models', 'model_class').value()
310
- self.model_class = utils.find_dict_in_list_from_key_val(
311
- self.models, 'name', model_name)['class'](self)
312
- self.model_class.ini_model_base()
313
-
314
- def ini_temp_file(self):
315
- self.clean_h5_temp()
316
-
317
- self.h5temp = H5Saver()
318
- self.temp_path = tempfile.TemporaryDirectory(prefix='pymo')
319
- addhoc_file_path = Path(self.temp_path.name).joinpath('bayesian_temp_data.h5')
320
- self.h5temp.init_file(custom_naming=True, addhoc_file_path=addhoc_file_path)
321
- act_names = [child.name() for child in self.settings.child( 'main_settings',
322
- 'bounds').children()]
323
- act_units = [self.modules_manager.get_mod_from_name(act_name, 'act').units for act_name
324
- in act_names]
325
- self.enlargeable_saver = DataEnlargeableSaver(
326
- self.h5temp,
327
- enl_axis_names=act_names,
328
- enl_axis_units=act_units)
329
-
330
- def ini_live_plot(self):
331
- self.live_plotter.h5saver = self.h5temp
332
- act_names = [child.name() for child in self.settings.child('main_settings',
333
- 'bounds').children()]
334
- act_units = [self.modules_manager.get_mod_from_name(act_name, 'act').units for act_name
335
- in act_names]
336
- if len(act_names) == 1:
337
- viewer_enum = 'Viewer1D'
338
- elif len(act_names) == 2:
339
- viewer_enum = 'Viewer2D'
340
- else:
341
- viewer_enum = 'ViewerND'
342
- viewers = self.live_plotter.prepare_viewers([viewer_enum],
343
- viewers_name=[self.explored_viewer_name])
344
- for viewer in viewers:
345
- if viewer.has_action('crosshair'):
346
- viewer.get_action('crosshair').trigger()
347
- if hasattr(viewer.view, 'collapse_lineout_widgets'):
348
- viewer.view.collapse_lineout_widgets()
349
- if viewer.has_action('sort'):
350
- if not viewer.is_action_checked('sort'):
351
- viewer.get_action('sort').trigger()
352
- if viewer.has_action('scatter'):
353
- if not viewer.is_action_checked('scatter'):
354
- viewer.get_action('scatter').trigger()
355
-
356
- QtWidgets.QApplication.processEvents()
357
- win_width = self.dockarea.width()
358
- self.docks['settings'].container().setSizes((int(win_width / 5),
359
- int(2 * win_width / 5),
360
- int(2 * win_width / 5), 10, 10))
361
-
362
- def update_actuators(self, actuators: List[str]):
363
- if self.is_action_checked('ini_runner'):
364
- self.get_action('ini_runner').trigger()
365
- QtWidgets.QApplication.processEvents()
366
-
367
- self._save_main_settings = False
368
-
369
- for child in self.settings.child('main_settings', 'bounds').children():
370
- self.settings.child('main_settings', 'bounds').removeChild(child)
371
- params = []
372
- for actuator in actuators:
373
- params.append({'title': actuator, 'name': actuator, 'type': 'group', 'children': [
374
- {'title': 'min', 'name': 'min', 'type': 'float', 'value': -5},
375
- {'title': 'max', 'name': 'max', 'type': 'float', 'value': 5},
376
- ]})
377
- self.settings.child('main_settings', 'bounds').addChildren(params)
378
- self.mainsettings_saver_loader.base_path = [self.model_class.__class__.__name__] + \
379
- self.modules_manager.selected_actuators_name
380
- self.mainsettings_saver_loader.load_config()
381
- self._save_main_settings = True
382
-
383
- def format_bounds(self):
384
- bound_dict = {}
385
- for bound in self.settings.child('main_settings', 'bounds').children():
386
- bound_dict.update({bound.name(): (bound['min'], bound['max'])})
387
- return bound_dict
388
-
389
- def set_algorithm(self):
390
- self.algorithm = BayesianAlgorithm(
391
- ini_random=self.settings['main_settings', 'ini_random'],
392
- bounds=self.format_bounds(),)
393
-
394
- def ini_model(self):
395
- try:
396
- if self.model_class is None:
397
- self.set_model()
398
-
399
- self.modules_manager.selected_actuators_name = self.model_class.actuators_name
400
- self.modules_manager.selected_detectors_name = self.model_class.detectors_name
401
-
402
- self.enable_controls_opti(True)
403
- self.get_action('model_led').set_as_true()
404
- self.set_action_enabled('ini_model', False)
405
-
406
- self.viewer_observable.update_viewers(['Viewer0D', 'Viewer0D'],
407
- ['Fitness', 'Individual'])
408
- self.settings.child('models', 'ini_model').setValue(True)
409
- self.settings.child('models', 'ini_runner').setOpts(enabled=True)
410
- self.set_action_enabled('ini_runner', True)
411
-
412
- self.mainsettings_saver_loader.base_path = [self.model_class.__class__.__name__] + \
413
- self.modules_manager.selected_actuators_name
414
- self.mainsettings_saver_loader.load_config()
415
-
416
- try: # this is correct for Default Model and probably for all models...
417
- self.model_class.settings.child('optimizing_signal', 'data_probe').activate()
418
- except Exception:
419
- pass
420
-
421
- except Exception as e:
422
- logger.exception(str(e))
423
-
424
- def ini_optimisation_runner(self):
425
- if self.is_action_checked('ini_runner'):
426
- self.set_algorithm()
427
-
428
- self.settings.child('models', 'ini_runner').setValue(True)
429
- self.enl_index = 0
430
-
431
- self.ini_temp_file()
432
- self.ini_live_plot()
433
-
434
- self.runner_thread = QtCore.QThread()
435
- runner = OptimisationRunner(self.model_class, self.modules_manager, self.algorithm,
436
- self.get_stopping_parameters())
437
- self.runner_thread.runner = runner
438
- runner.algo_output_signal.connect(self.process_output)
439
- runner.algo_finished.connect(self.optimisation_done)
440
- self.command_runner.connect(runner.queue_command)
441
-
442
- runner.moveToThread(self.runner_thread)
443
-
444
- self.runner_thread.start()
445
- self.get_action('runner_led').set_as_true()
446
- self.set_action_enabled('run', True)
447
- self.model_class.runner_initialized()
448
- self.update_utility_function()
449
- else:
450
- if self.is_action_checked('run'):
451
- self.get_action('run').trigger()
452
- QtWidgets.QApplication.processEvents()
453
- self.runner_thread.terminate()
454
- self.get_action('runner_led').set_as_false()
455
-
456
- def clean_h5_temp(self):
457
- if self.temp_path is not None:
458
- try:
459
- self.h5temp.close()
460
- self.temp_path.cleanup()
461
- except Exception as e:
462
- logger.exception(str(e))
463
-
464
- def optimisation_done(self, dte: DataToExport):
465
- self.go_to_best()
466
- self.optimisation_done_signal.emit(dte)
467
-
468
- def process_output(self, dte: DataToExport):
469
-
470
- self.enl_index += 1
471
- dwa_kappa = dte.remove(dte.get_data_from_name(DataNames.Kappa.name))
472
- self.settings.child('main_settings', 'utility', 'kappa_actual').setValue(
473
- float(dwa_kappa[0][0])
474
- )
475
-
476
- dwa_data = dte.remove(dte.get_data_from_name(DataNames.ProbedData.name))
477
- dwa_actuators: DataActuator = dte.remove(dte.get_data_from_name(DataNames.Actuators.name))
478
- self.viewer_observable.show_data(dte)
479
-
480
- # dwa_observations = self.algorithm.get_dwa_obervations(
481
- # self.modules_manager.selected_actuators_name)
482
- self.model_class.update_plots()
483
-
484
- best_individual = dte.get_data_from_name(DataNames.Individual.name)
485
- best_indiv_as_list = [float(best_individual[ind][0]) for ind in range(len(best_individual))]
486
-
487
-
488
- self.enlargeable_saver.add_data('/RawData', dwa_data,
489
- axis_values=dwa_actuators.values())
490
- if len(best_indiv_as_list) == 1 or (
491
- len(best_indiv_as_list) == 2 and self.enl_index >= 3):
492
- self.update_data_plot(target_at=dwa_actuators.values(),
493
- crosshair_at=best_indiv_as_list)
494
-
495
- def update_data_plot(self, target_at=None, crosshair_at=None):
496
- self.live_plotter.load_plot_data(remove_navigation=False,
497
- crosshair_at=crosshair_at,
498
- target_at=target_at)
499
-
500
- def enable_controls_opti(self, enable: bool):
501
- pass
502
-
503
- def run_optimisation(self):
504
- if self.is_action_checked('run'):
505
- self.get_action('run').set_icon('pause')
506
- self.command_runner.emit(utils.ThreadCommand('start', {}))
507
- QtWidgets.QApplication.processEvents()
508
- QtWidgets.QApplication.processEvents()
509
- self.command_runner.emit(utils.ThreadCommand('run', {}))
510
- else:
511
- self.get_action('run').set_icon('run2')
512
- self.command_runner.emit(utils.ThreadCommand('stop', {}))
513
- self.set_action_enabled('gotobest', True)
514
-
515
- QtWidgets.QApplication.processEvents()
516
-
517
-
518
- class OptimisationRunner(QtCore.QObject):
519
- algo_output_signal = QtCore.Signal(DataToExport)
520
- algo_finished = QtCore.Signal(DataToExport)
521
-
522
- def __init__(self, model_class: BayesianModelGeneric, modules_manager: ModulesManager,
523
- algorithm: BayesianAlgorithm, stopping_params: StoppingParameters):
524
- super().__init__()
525
-
526
- self.det_done_datas: DataToExport = None
527
- self.input_from_dets: float = None
528
- self.outputs: List[np.ndarray] = []
529
- self.dte_actuators: DataToExport = None
530
- self.stopping_params: StoppingParameters = stopping_params
531
-
532
- self.model_class: BayesianModelGeneric = model_class
533
- self.modules_manager: ModulesManager = modules_manager
534
-
535
- self.running = True
536
-
537
- self.optimisation_algorithm: BayesianAlgorithm = algorithm
538
-
539
- self._ind_iter: int = 0
540
-
541
- @QtCore.Slot(utils.ThreadCommand)
542
- def queue_command(self, command: utils.ThreadCommand):
543
- """
544
- """
545
- if command.command == "run":
546
- self.run_opti(**command.attribute)
547
-
548
- elif command.command == "stop":
549
- self.running = False
550
-
551
- elif command.command == 'utility':
552
- utility_params: UtilityParameters = command.attribute
553
- self.optimisation_algorithm.set_utility_function(
554
- utility_params.kind,
555
- kappa=utility_params.kappa,
556
- xi=utility_params.xi,
557
- kappa_decay=utility_params.kappa_decay,
558
- kappa_decay_delay=utility_params.kappa_decay_delay)
559
-
560
- elif command.command == 'stopping':
561
- self.stopping_params: StoppingParameters = command.attribute
562
-
563
- elif command.command == 'bounds':
564
- self.optimisation_algorithm.set_bounds(command.attribute)
565
-
566
- def run_opti(self, sync_detectors=True, sync_acts=True):
567
- """Start the optimisation loop
568
-
569
- Parameters
570
- ----------
571
- sync_detectors: (bool) if True will make sure all selected detectors (if any) all got their data before calling
572
- the model
573
- sync_acts: (bool) if True will make sure all selected actuators (if any) all reached their target position
574
- before calling the model
575
- """
576
- self.running = True
577
- converged = False
578
- try:
579
- if sync_detectors:
580
- self.modules_manager.connect_detectors()
581
- if sync_acts:
582
- self.modules_manager.connect_actuators()
583
-
584
- self.current_time = time.perf_counter()
585
- logger.info('Optimisation loop starting')
586
- while self.running:
587
- self._ind_iter += 1
588
-
589
- next_target = self.optimisation_algorithm.ask()
590
-
591
- self.outputs = next_target
592
- self.output_to_actuators: DataToActuators =\
593
- self.model_class.convert_output(
594
- self.outputs,
595
- best_individual=self.optimisation_algorithm.best_individual
596
- )
597
-
598
- self.modules_manager.move_actuators(self.output_to_actuators,
599
- self.output_to_actuators.mode,
600
- polling=sync_acts)
601
-
602
- # Do the evaluation (measurements)
603
- self.det_done_datas = self.modules_manager.grab_data()
604
- self.input_from_dets = self.model_class.convert_input(self.det_done_datas)
605
-
606
- # Run the algo internal mechanic
607
- self.optimisation_algorithm.tell(float(self.input_from_dets))
608
-
609
- dte = DataToExport('algo',
610
- data=[self.individual_as_data(
611
- np.array([self.optimisation_algorithm.best_fitness]),
612
- DataNames.Fitness.name),
613
- self.individual_as_data(
614
- self.optimisation_algorithm.best_individual,
615
- DataNames.Individual.name),
616
- DataCalculated(DataNames.ProbedData.name,
617
- data=[np.array([self.input_from_dets])],
618
- ),
619
- self.output_to_actuators.merge_as_dwa(
620
- 'Data0D', DataNames.Actuators.name),
621
- DataCalculated(
622
- DataNames.Kappa.name,
623
- data=[
624
- np.array([self.optimisation_algorithm.kappa])])
625
- ])
626
- self.algo_output_signal.emit(dte)
627
-
628
- self.optimisation_algorithm.update_utility_function()
629
-
630
- if self.optimisation_algorithm.stopping(self._ind_iter, self.stopping_params):
631
- converged = True
632
- break
633
-
634
- self.current_time = time.perf_counter()
635
- QtWidgets.QApplication.processEvents()
636
-
637
- logger.info('Optimisation loop exiting')
638
- self.modules_manager.connect_actuators(False)
639
- self.modules_manager.connect_detectors(False)
640
-
641
- if converged:
642
- self.algo_finished.emit(dte)
643
-
644
- except Exception as e:
645
- logger.exception(str(e))
646
-
647
- @staticmethod
648
- def individual_as_data(individual: np.ndarray, name: str = 'Individual') -> DataCalculated:
649
- return DataCalculated(name, data=[np.atleast_1d(np.squeeze(coordinate)) for coordinate in
650
- np.atleast_1d(np.squeeze(individual))])
651
-
652
-
653
- def main(init_qt=True):
654
- import sys
655
- from pathlib import Path
656
- from pymodaq.utils.daq_utils import get_set_preset_path
657
-
658
- if init_qt: # used for the test suite
659
- app = mkQApp("PyMoDAQ Dashboard")
660
-
661
- from pymodaq.dashboard import DashBoard
662
-
663
- win = QtWidgets.QMainWindow()
664
- area = gutils.dock.DockArea()
665
- win.setCentralWidget(area)
666
- win.resize(1000, 500)
667
-
668
- dashboard = DashBoard(area)
669
- daq_scan = None
670
- file = Path(get_set_preset_path()).joinpath(f"{'beam_steering_mock'}.xml")
671
-
672
- if file.exists():
673
- dashboard.set_preset_mode(file)
674
- daq_scan = dashboard.load_bayesian()
675
- else:
676
- msgBox = QtWidgets.QMessageBox()
677
- msgBox.setText(f"The default file specified in the configuration file does not exists!\n"
678
- f"{file}\n"
679
- f"Impossible to load the DAQScan Module")
680
- msgBox.setStandardButtons(msgBox.Ok)
681
- ret = msgBox.exec()
682
-
683
- if init_qt:
684
- sys.exit(app.exec_())
685
- return dashboard, daq_scan, win
686
-
687
-
688
- if __name__ == '__main__':
689
- main()
690
-