etho-python 0.23.0__py3-none-any.whl → 1.2__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.
etho/app.py CHANGED
@@ -11,12 +11,12 @@ import psutil
11
11
  import threading
12
12
  import queue
13
13
 
14
- from qtpy import QtWidgets
15
- from qtpy.QtGui import QIcon, QPalette
16
- from qtpy.QtWidgets import (
17
- QApplication,
18
- QTableView,
19
- QGridLayout,
14
+ from qtpy import QtWidgets
15
+ from qtpy.QtGui import QIcon, QPalette
16
+ from qtpy.QtWidgets import (
17
+ QApplication,
18
+ QTableView,
19
+ QGridLayout,
20
20
  QWidget,
21
21
  QMainWindow,
22
22
  QPushButton,
@@ -28,9 +28,9 @@ from qtpy.QtWidgets import (
28
28
  QLabel,
29
29
  QSplitter,
30
30
  QProgressBar,
31
- )
32
-
33
- from qtpy.QtCore import QAbstractTableModel, Qt, QTimer
31
+ )
32
+
33
+ from qtpy.QtCore import QAbstractTableModel, Qt, QTimer
34
34
 
35
35
  from pyqtgraph.parametertree import Parameter, ParameterTree
36
36
 
@@ -39,24 +39,24 @@ from . import client
39
39
  from .utils.config import readconfig
40
40
 
41
41
 
42
- logger = logging.getLogger(__name__)
43
-
44
- _ICON_DIR = Path(__file__).with_name("assets")
45
- _LIGHT_ICON = _ICON_DIR / "etho_icon1_pipeline_light.svg"
46
- _DARK_ICON = _ICON_DIR / "etho_icon1_pipeline_dark.svg"
47
-
48
-
49
- def _system_icon(app: QApplication) -> QIcon:
50
- icon_path = _LIGHT_ICON
51
- try:
52
- window_role = getattr(getattr(QPalette, "ColorRole", QPalette), "Window")
53
- if app.palette().color(window_role).lightness() < 128:
54
- icon_path = _DARK_ICON
55
- except Exception:
56
- pass
57
- if not icon_path.exists():
58
- icon_path = _LIGHT_ICON
59
- return QIcon(icon_path.as_posix())
42
+ logger = logging.getLogger(__name__)
43
+
44
+ _ICON_DIR = Path(__file__).with_name("assets")
45
+ _LIGHT_ICON = _ICON_DIR / "etho_icon1_pipeline_light.svg"
46
+ _DARK_ICON = _ICON_DIR / "etho_icon1_pipeline_dark.svg"
47
+
48
+
49
+ def _system_icon(app: QApplication) -> QIcon:
50
+ icon_path = _LIGHT_ICON
51
+ try:
52
+ window_role = getattr(getattr(QPalette, "ColorRole", QPalette), "Window")
53
+ if app.palette().color(window_role).lightness() < 128:
54
+ icon_path = _DARK_ICON
55
+ except Exception:
56
+ pass
57
+ if not icon_path.exists():
58
+ icon_path = _LIGHT_ICON
59
+ return QIcon(icon_path.as_posix())
60
60
 
61
61
 
62
62
  class PandasModel(QAbstractTableModel):
@@ -99,7 +99,7 @@ class PandasModel(QAbstractTableModel):
99
99
  self.endResetModel()
100
100
 
101
101
 
102
- class TableView(QTableView):
102
+ class TableView(QTableView):
103
103
  def __init__(self, model, child=None, folder=None):
104
104
  QTableView.__init__(self)
105
105
  self._child = child
@@ -123,56 +123,56 @@ class TableView(QTableView):
123
123
  self.data = self._child.data_from_filename(self.selected_string)
124
124
  self._child.replaceData(self.data)
125
125
 
126
- def edit_file(self):
127
- if self._folder is not None:
128
- print(f"code {self.folder}/{self.selected_string}")
129
- os.system(f"code {self.folder}/{self.selected_string}")
130
-
131
-
132
- def _parameter_item(name, value):
133
- item = {"name": str(name)}
134
-
135
- if isinstance(value, dict):
136
- item["type"] = "group"
137
- item["original_type"] = "dict"
138
- item["children"] = [_parameter_item(key, val) for key, val in value.items()]
139
- elif isinstance(value, list):
140
- item["type"] = "group"
141
- item["original_type"] = "list"
142
- scalar_names = [str(val) for val in value if not isinstance(val, (dict, list))]
143
- use_checkboxes = len(scalar_names) == len(value) and len(set(scalar_names)) == len(scalar_names)
144
- if use_checkboxes:
145
- item["list_mode"] = "checkbox"
146
- item["children"] = [{"name": str(val), "type": "bool", "value": True, "original_value": val} for val in value]
147
- else:
148
- item["children"] = [_parameter_item(idx, val) for idx, val in enumerate(value)]
149
- elif isinstance(value, bool):
150
- item["type"] = "bool"
151
- item["value"] = value
152
- elif isinstance(value, int):
153
- item["type"] = "int"
154
- item["value"] = value
155
- elif isinstance(value, float):
156
- item["type"] = "float"
157
- item["value"] = value
158
- elif value is None:
159
- item["type"] = "str"
160
- item["value"] = ""
161
- item["original_type"] = "none"
162
- else:
163
- item["type"] = "str"
164
- item["value"] = str(value)
165
-
166
- return item
167
-
168
-
169
- # format to parametertree
170
- def from_yaml(d, readonly=True):
171
- pt = [_parameter_item(key, val) for key, val in d.items()]
172
- p = Parameter.create(name="Protocol parameters", type="group", children=pt)
173
- if readonly:
174
- children_read_only(p.children())
175
- return p
126
+ def edit_file(self):
127
+ if self._folder is not None:
128
+ print(f"code {self.folder}/{self.selected_string}")
129
+ os.system(f"code {self.folder}/{self.selected_string}")
130
+
131
+
132
+ def _parameter_item(name, value):
133
+ item = {"name": str(name)}
134
+
135
+ if isinstance(value, dict):
136
+ item["type"] = "group"
137
+ item["original_type"] = "dict"
138
+ item["children"] = [_parameter_item(key, val) for key, val in value.items()]
139
+ elif isinstance(value, list):
140
+ item["type"] = "group"
141
+ item["original_type"] = "list"
142
+ scalar_names = [str(val) for val in value if not isinstance(val, (dict, list))]
143
+ use_checkboxes = len(scalar_names) == len(value) and len(set(scalar_names)) == len(scalar_names)
144
+ if use_checkboxes:
145
+ item["list_mode"] = "checkbox"
146
+ item["children"] = [{"name": str(val), "type": "bool", "value": True, "original_value": val} for val in value]
147
+ else:
148
+ item["children"] = [_parameter_item(idx, val) for idx, val in enumerate(value)]
149
+ elif isinstance(value, bool):
150
+ item["type"] = "bool"
151
+ item["value"] = value
152
+ elif isinstance(value, int):
153
+ item["type"] = "int"
154
+ item["value"] = value
155
+ elif isinstance(value, float):
156
+ item["type"] = "float"
157
+ item["value"] = value
158
+ elif value is None:
159
+ item["type"] = "str"
160
+ item["value"] = ""
161
+ item["original_type"] = "none"
162
+ else:
163
+ item["type"] = "str"
164
+ item["value"] = str(value)
165
+
166
+ return item
167
+
168
+
169
+ # format to parametertree
170
+ def from_yaml(d, readonly=True):
171
+ pt = [_parameter_item(key, val) for key, val in d.items()]
172
+ p = Parameter.create(name="Protocol parameters", type="group", children=pt)
173
+ if readonly:
174
+ children_read_only(p.children())
175
+ return p
176
176
 
177
177
 
178
178
  def children_read_only(children):
@@ -183,18 +183,18 @@ def children_read_only(children):
183
183
  child.setReadonly()
184
184
 
185
185
 
186
- def to_yaml(p):
187
- if p.children():
188
- if p.opts.get("original_type") == "list":
189
- if p.opts.get("list_mode") == "checkbox":
190
- return [child.opts.get("original_value", child.name()) for child in p.children() if child.value()]
191
- return [to_yaml(child) for child in p.children()]
192
- return {child.name(): to_yaml(child) for child in p.children()}
193
-
194
- value = p.value()
195
- if p.opts.get("original_type") == "none":
196
- return yaml.safe_load(value)
197
- return value
186
+ def to_yaml(p):
187
+ if p.children():
188
+ if p.opts.get("original_type") == "list":
189
+ if p.opts.get("list_mode") == "checkbox":
190
+ return [child.opts.get("original_value", child.name()) for child in p.children() if child.value()]
191
+ return [to_yaml(child) for child in p.children()]
192
+ return {child.name(): to_yaml(child) for child in p.children()}
193
+
194
+ value = p.value()
195
+ if p.opts.get("original_type") == "none":
196
+ return yaml.safe_load(value)
197
+ return value
198
198
 
199
199
 
200
200
  def load(filename: str):
@@ -279,7 +279,7 @@ def monitor(event1, event2, callback, progress=None, progress_total=100):
279
279
  time.sleep(1)
280
280
 
281
281
 
282
- class MainWindow(QMainWindow):
282
+ class MainWindow(QMainWindow):
283
283
  def __init__(
284
284
  self,
285
285
  protocol_folder: Optional[Union[str, os.PathLike]] = None,
@@ -306,27 +306,29 @@ class MainWindow(QMainWindow):
306
306
  if not self.playlist_folder.exists():
307
307
  raise FileExistsError(f"{self.playlist_folder} does not exist!")
308
308
 
309
- logging.info(f"Loading playlists from {self.playlist_folder}.")
310
-
311
- self.setWindowTitle("etho control")
312
- self.run_thread = None
313
- self.stop_event = None
314
- self.done_event = None
315
- self.run_timer = QTimer(self)
316
- self.run_timer.setInterval(200)
317
- self.run_timer.timeout.connect(self.sync_run_state)
318
-
319
- # Buttons
320
- buttons = QVBoxLayout()
321
- self.button = {}
322
- self.button["Refresh lists"] = QPushButton("Refresh lists")
323
- self.button["Refresh lists"].clicked.connect(self.refresh_lists)
324
- self.button["Start"] = QPushButton("Start")
325
- self.button["Start"].clicked.connect(self.start)
326
- self.button["Stop"] = QPushButton("Stop")
327
- self.button["Stop"].clicked.connect(self.request_stop)
309
+ logging.info(f"Loading playlists from {self.playlist_folder}.")
310
+
311
+ self.setWindowTitle("etho control")
312
+ self.run_thread = None
313
+ self.stop_event = None
314
+ self.done_event = None
315
+ self.run_timer = QTimer(self)
316
+ self.run_timer.setInterval(200)
317
+ self.run_timer.timeout.connect(self.sync_run_state)
318
+
319
+ # Buttons
320
+ buttons = QVBoxLayout()
321
+ self.button = {}
322
+ self.button["Refresh lists"] = QPushButton("Refresh lists")
323
+ self.button["Refresh lists"].clicked.connect(self.refresh_lists)
324
+ self.button["Start"] = QPushButton("Start")
325
+ self.button["Start"].clicked.connect(self.start)
326
+ self.button["Stop"] = QPushButton("Stop")
327
+ self.button["Stop"].clicked.connect(self.request_stop)
328
328
  self.button["Camera_preview"] = QPushButton("Camera preview")
329
329
  self.button["Camera_preview"].clicked.connect(self.camera_preview)
330
+ self.button["Exit"] = QPushButton("Exit")
331
+ self.button["Exit"].clicked.connect(self.close)
330
332
  self.button["Debug"] = QCheckBox("Debug")
331
333
  self.button["Progress"] = QCheckBox("Show Progress")
332
334
  self.button["Progress"].setChecked(True)
@@ -334,17 +336,7 @@ class MainWindow(QMainWindow):
334
336
  [buttons.addWidget(b) for b in self.button.values()]
335
337
 
336
338
  self.help = QtWidgets.QLabel(
337
- "<br>"
338
- "<br>"
339
- "<B>Instructions</B><br>"
340
- "<br>"
341
- "Single Click on<br>"
342
- " playlist or protocol.<br>"
343
- "previews the file.<br>"
344
- "<br>"
345
- "Double Click opens<br>"
346
- "playlist or protocol<br>"
347
- "in VS code.<br>"
339
+ "<br><br><B>Instructions</B><br><br>Single Click on<br> playlist or protocol.<br>previews the file.<br><br>Double Click opens<br>playlist or protocol<br>in VS code.<br>"
348
340
  )
349
341
  buttons.addWidget(self.help)
350
342
 
@@ -358,18 +350,18 @@ class MainWindow(QMainWindow):
358
350
  self.layout.setColumnStretch(2, 1)
359
351
  self.layout.setColumnStretch(1, 2)
360
352
 
361
- widget = QWidget()
362
- widget.setLayout(self.layout)
363
- self.setCentralWidget(widget)
364
- self.set_run_buttons(False)
365
-
366
- def on_protocol_changed(self, param, changes):
367
- self.current_protocol = to_yaml(param)
368
-
369
- def refresh_lists(self, init: bool = False):
370
- playlist_files = sorted(self.playlist_folder.glob("*.txt"))
371
- if len(playlist_files) == 0:
372
- raise FileNotFoundError(f"No files found in {self.playlist_folder}.")
353
+ widget = QWidget()
354
+ widget.setLayout(self.layout)
355
+ self.setCentralWidget(widget)
356
+ self.set_run_buttons(False)
357
+
358
+ def on_protocol_changed(self, param, changes):
359
+ self.current_protocol = to_yaml(param)
360
+
361
+ def refresh_lists(self, init: bool = False):
362
+ playlist_files = sorted(self.playlist_folder.glob("*.txt"))
363
+ if len(playlist_files) == 0:
364
+ raise FileNotFoundError(f"No files found in {self.playlist_folder}.")
373
365
 
374
366
  df_playlists = pd.DataFrame({"playlist": sorted([Path(plf).name for plf in playlist_files])})
375
367
  playlist_file = Path(playlist_files[0]).name
@@ -391,27 +383,27 @@ class MainWindow(QMainWindow):
391
383
  if len(protocol_files) == 0:
392
384
  raise FileNotFoundError(f"No files found in {self.protocol_folder}.")
393
385
 
394
- df_protocols = pd.DataFrame({"protocol": sorted([Path(plf).name for plf in protocol_files])})
395
- # Content of selected protocol file
396
- protocol_file = Path(protocol_files[0]).name
397
- protocol_from_filename = lambda filename: from_yaml(load(self.protocol_folder / filename), readonly=False)
398
- protocol_model = protocol_from_filename(protocol_file)
399
-
400
- protocol_view = ParameterTree()
401
-
402
- def set_protocol_model(parameter):
403
- self.current_protocol = to_yaml(parameter)
404
- parameter.sigTreeStateChanged.connect(self.on_protocol_changed)
405
- protocol_view.protocol_model = parameter
406
- protocol_view.setParameters(parameter, showTop=False)
407
-
408
- set_protocol_model(protocol_model)
409
- protocol_view.replaceData = set_protocol_model
410
- protocol_view.data_from_filename = protocol_from_filename
411
-
412
- # List of protocol files
413
- protocols_model = PandasModel(df_protocols, editable=False)
414
- protocols_view = TableView(protocols_model, protocol_view, self.protocol_folder)
386
+ df_protocols = pd.DataFrame({"protocol": sorted([Path(plf).name for plf in protocol_files])})
387
+ # Content of selected protocol file
388
+ protocol_file = Path(protocol_files[0]).name
389
+ protocol_from_filename = lambda filename: from_yaml(load(self.protocol_folder / filename), readonly=False)
390
+ protocol_model = protocol_from_filename(protocol_file)
391
+
392
+ protocol_view = ParameterTree()
393
+
394
+ def set_protocol_model(parameter):
395
+ self.current_protocol = to_yaml(parameter)
396
+ parameter.sigTreeStateChanged.connect(self.on_protocol_changed)
397
+ protocol_view.protocol_model = parameter
398
+ protocol_view.setParameters(parameter, showTop=False)
399
+
400
+ set_protocol_model(protocol_model)
401
+ protocol_view.replaceData = set_protocol_model
402
+ protocol_view.data_from_filename = protocol_from_filename
403
+
404
+ # List of protocol files
405
+ protocols_model = PandasModel(df_protocols, editable=False)
406
+ protocols_view = TableView(protocols_model, protocol_view, self.protocol_folder)
415
407
  protocols_view.setAlternatingRowColors(True)
416
408
  protocols_view.folder = self.protocol_folder
417
409
  protocols_view.selectRow(0)
@@ -450,13 +442,13 @@ class MainWindow(QMainWindow):
450
442
  self.protocol_view = protocol_view
451
443
  self.protocols_view = protocols_view
452
444
 
453
- def start(self, preview: bool = False):
454
- if self.run_thread is not None and self.run_thread.is_alive():
455
- return
456
-
457
- msg = []
458
- if self.playlists_view.selected_string is None:
459
- msg.append("playlist")
445
+ def start(self, preview: bool = False):
446
+ if self.run_thread is not None and self.run_thread.is_alive():
447
+ return
448
+
449
+ msg = []
450
+ if self.playlists_view.selected_string is None:
451
+ msg.append("playlist")
460
452
 
461
453
  if self.protocols_view.selected_string is None:
462
454
  msg.append("protocol")
@@ -468,99 +460,100 @@ class MainWindow(QMainWindow):
468
460
  dlg.exec_()
469
461
  return
470
462
 
471
- stop_event = threading.Event()
472
- done_event = threading.Event()
473
-
474
- kwargs = {
475
- "playlistfile": (self.playlist_folder / self.playlists_view.selected_string).as_posix(),
476
- "protocolfile": (self.protocol_folder / self.protocols_view.selected_string).as_posix(),
477
- "protocol": self.current_protocol,
478
- "debug": self.button["Debug"].isChecked(),
479
- "show_progress": self.button["Progress"].isChecked(),
480
- "monitor": True,
481
- "save_prefix": None,
482
- "preview": preview,
483
- "_stop_event": stop_event,
484
- "_done_event": done_event,
485
- }
486
-
487
- rich.print("Starting experiment with these args:")
488
- rich.print(kwargs)
489
-
490
- self.stop_event = stop_event
491
- self.done_event = done_event
492
- self.run_thread = threading.Thread(target=self.run_client, kwargs=kwargs, daemon=True)
493
- self.set_run_buttons(True)
494
- self.run_thread.start()
495
- self.run_timer.start()
496
-
497
- # dlg = RunDialog(stop_event, done_event, queue_total)
498
- # dlg.exec_()
499
-
500
- def run_client(self, **kwargs):
501
- done_event = kwargs.get("_done_event")
502
- try:
503
- client.client(**kwargs)
504
- except Exception:
505
- logging.exception("Experiment failed.")
506
- finally:
507
- if done_event is not None:
508
- done_event.set()
509
-
510
- def request_stop(self):
511
- if self.stop_event is None:
512
- return
513
- self.stop_event.set()
514
- self.set_run_buttons(True, stopping=True)
515
-
516
- def sync_run_state(self):
517
- if self.run_thread is None:
518
- self.run_timer.stop()
519
- self.set_run_buttons(False)
520
- return
521
-
522
- if self.stop_event is not None and self.stop_event.is_set():
523
- self.set_run_buttons(True, stopping=True)
524
-
525
- if self.run_thread.is_alive():
526
- return
527
-
528
- if self.done_event is not None and not self.done_event.is_set():
529
- return
530
-
531
- self.run_timer.stop()
532
- self.run_thread = None
533
- self.stop_event = None
534
- self.done_event = None
535
- self.set_run_buttons(False)
536
-
537
- def set_run_buttons(self, running: bool, stopping: bool = False):
538
- self.button["Start"].setEnabled(not running)
463
+ stop_event = threading.Event()
464
+ done_event = threading.Event()
465
+
466
+ kwargs = {
467
+ "playlistfile": (self.playlist_folder / self.playlists_view.selected_string).as_posix(),
468
+ "protocolfile": (self.protocol_folder / self.protocols_view.selected_string).as_posix(),
469
+ "protocol": self.current_protocol,
470
+ "debug": self.button["Debug"].isChecked(),
471
+ "show_progress": self.button["Progress"].isChecked(),
472
+ "monitor": True,
473
+ "save_prefix": None,
474
+ "preview": preview,
475
+ "_stop_event": stop_event,
476
+ "_done_event": done_event,
477
+ }
478
+
479
+ rich.print("Starting experiment with these args:")
480
+ rich.print(kwargs)
481
+
482
+ self.stop_event = stop_event
483
+ self.done_event = done_event
484
+ self.run_thread = threading.Thread(target=self.run_client, kwargs=kwargs, daemon=True)
485
+ self.set_run_buttons(True)
486
+ self.run_thread.start()
487
+ self.run_timer.start()
488
+
489
+ # dlg = RunDialog(stop_event, done_event, queue_total)
490
+ # dlg.exec_()
491
+
492
+ def run_client(self, **kwargs):
493
+ done_event = kwargs.get("_done_event")
494
+ try:
495
+ client.client(**kwargs)
496
+ except Exception:
497
+ logging.exception("Experiment failed.")
498
+ finally:
499
+ if done_event is not None:
500
+ done_event.set()
501
+
502
+ def request_stop(self):
503
+ if self.stop_event is None:
504
+ return
505
+ self.stop_event.set()
506
+ self.set_run_buttons(True, stopping=True)
507
+
508
+ def sync_run_state(self):
509
+ if self.run_thread is None:
510
+ self.run_timer.stop()
511
+ self.set_run_buttons(False)
512
+ return
513
+
514
+ if self.stop_event is not None and self.stop_event.is_set():
515
+ self.set_run_buttons(True, stopping=True)
516
+
517
+ if self.run_thread.is_alive():
518
+ return
519
+
520
+ if self.done_event is not None and not self.done_event.is_set():
521
+ return
522
+
523
+ self.run_timer.stop()
524
+ self.run_thread = None
525
+ self.stop_event = None
526
+ self.done_event = None
527
+ self.set_run_buttons(False)
528
+
529
+ def set_run_buttons(self, running: bool, stopping: bool = False):
530
+ self.button["Start"].setEnabled(not running)
539
531
  self.button["Camera_preview"].setEnabled(not running)
540
532
  self.button["Refresh lists"].setEnabled(not running)
541
533
  self.button["Stop"].setEnabled(running and not stopping)
542
534
  self.button["Stop"].setText("Stopping..." if stopping else "Stop")
543
-
544
- def camera_preview(self):
545
- self.start(preview=True)
535
+ self.button["Exit"].setEnabled(not running)
536
+
537
+ def camera_preview(self):
538
+ self.start(preview=True)
546
539
 
547
540
 
548
- def main(protocol_folder: Optional[str] = None, playlist_folder: Optional[str] = None):
541
+ def main(protocol_folder: Optional[str] = None, playlist_folder: Optional[str] = None):
549
542
  """Opens the graphical user interface.
550
543
 
551
544
  Args:
552
545
  protocol_folder (Optional[str]): Folder with protocol files.
553
- Defaults to value ['HEAD']['protocolfolder'] from `~/ethoconfig.yml`.
546
+ Defaults to value `protocolfolder` in `~/ethoconfig/ethoconfig.yml`.
554
547
  playlist_folder (Optional[str]): Folder with playlist files.
555
- Defaults to value ['HEAD']['playlistfolder'] from `~/ethoconfig.yml`.
548
+ Defaults to value `playlistfolder` in `~/ethoconfig/ethoconfig.yml`.
556
549
  """
557
- app = QApplication(sys.argv)
558
- icon = _system_icon(app)
559
- app.setWindowIcon(icon)
560
-
561
- m = MainWindow(protocol_folder, playlist_folder)
562
- m.setWindowIcon(icon)
563
- m.show()
550
+ app = QApplication(sys.argv)
551
+ icon = _system_icon(app)
552
+ app.setWindowIcon(icon)
553
+
554
+ m = MainWindow(protocol_folder, playlist_folder)
555
+ m.setWindowIcon(icon)
556
+ m.show()
564
557
 
565
558
  sys.exit(app.exec_())
566
559