-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmother_controller.py
More file actions
1547 lines (1400 loc) · 57.1 KB
/
mother_controller.py
File metadata and controls
1547 lines (1400 loc) · 57.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import os
import re
import tempfile
import zipfile
from functools import partial
from importlib.metadata import version
from io import BytesIO
from pathlib import Path
import petab.v1 as petab
import qtawesome as qta
import yaml
from petab.versions import get_major_version
from PySide6.QtCore import QSettings, Qt, QTimer, QUrl
from PySide6.QtGui import (
QAction,
QDesktopServices,
QKeySequence,
QUndoStack,
)
from PySide6.QtWidgets import (
QApplication,
QCheckBox,
QFileDialog,
QHBoxLayout,
QInputDialog,
QLineEdit,
QMessageBox,
QTableView,
QToolButton,
QWhatsThis,
QWidget,
)
from ..C import APP_NAME, REPO_URL
from ..models import PEtabModel, SbmlViewerModel
from ..settings_manager import SettingsDialog, settings_manager
from ..utils import (
CaptureLogHandler,
get_selected,
process_file,
)
from ..views import TaskBar
from ..views.other_views import NextStepsPanel
from .logger_controller import LoggerController
from .sbml_controller import SbmlController
from .table_controllers import (
ConditionController,
MeasurementController,
ObservableController,
ParameterController,
VisualizationController,
)
from .utils import (
RecentFilesManager,
_WhatsThisClickHelp,
filtered_error,
prompt_overwrite_or_append,
)
class MainController:
"""Main controller class.
Handles the communication between controllers. Handles general tasks.
Mother controller to all other controllers. One controller to rule them
all.
"""
def __init__(self, view, model: PEtabModel):
"""Initialize the main controller.
Parameters
----------
view: MainWindow
The main window.
model: PEtabModel
The PEtab model.
"""
self.undo_stack = QUndoStack()
self.task_bar = None
self.view = view
self.model = model
self.logger = LoggerController(view.logger_views)
# CONTROLLERS
self.measurement_controller = MeasurementController(
self.view.measurement_dock,
self.model.measurement,
self.logger,
self.undo_stack,
self,
)
self.observable_controller = ObservableController(
self.view.observable_dock,
self.model.observable,
self.logger,
self.undo_stack,
self,
)
self.parameter_controller = ParameterController(
self.view.parameter_dock,
self.model.parameter,
self.logger,
self.undo_stack,
self,
)
self.condition_controller = ConditionController(
self.view.condition_dock,
self.model.condition,
self.logger,
self.undo_stack,
self,
)
self.visualization_controller = VisualizationController(
self.view.visualization_dock,
self.model.visualization,
self.logger,
self.undo_stack,
self,
)
self.simulation_controller = MeasurementController(
self.view.simulation_dock,
self.model.simulation,
self.logger,
self.undo_stack,
self,
)
self.sbml_controller = SbmlController(
self.view.sbml_viewer, self.model.sbml, self.logger, self
)
self.controllers = [
self.measurement_controller,
self.observable_controller,
self.parameter_controller,
self.condition_controller,
self.sbml_controller,
self.visualization_controller,
self.simulation_controller,
]
# Recent Files
self.recent_files_manager = RecentFilesManager(max_files=10)
# Checkbox states for Find + Replace
self.petab_checkbox_states = {
"measurement": False,
"observable": False,
"parameter": False,
"condition": False,
"visualization": False,
"simulation": False,
}
self.sbml_checkbox_states = {"sbml": False, "antimony": False}
self.unsaved_changes = False
# Next Steps Panel
self.next_steps_panel = NextStepsPanel(self.view)
self.next_steps_panel.dont_show_again_changed.connect(
self._handle_next_steps_dont_show_again
)
self.filter = QLineEdit()
self.filter_active = {} # Saves which tables the filter applies to
self.actions = self.setup_actions()
self.view.setup_toolbar(self.actions)
self.plotter = None
self.init_plotter()
self.setup_connections()
self.setup_task_bar()
self.setup_context_menu()
@property
def window_title(self):
"""Return the window title based on the model."""
if isinstance(self.model.sbml, SbmlViewerModel):
return self.model.sbml.model_id
return APP_NAME
def setup_context_menu(self):
"""Sets up context menus for the tables."""
for controller in self.controllers:
if controller == self.sbml_controller:
continue
controller.setup_context_menu(self.actions)
def setup_task_bar(self):
"""Create shortcuts for the main window."""
self.view.task_bar = TaskBar(self.view, self.actions)
self.task_bar = self.view.task_bar
# CONNECTIONS
def setup_connections(self):
"""Setup connections.
Sets all connections that communicate from one different
Models/Views/Controllers to another. Also sets general connections.
"""
# Rename Observable
self.observable_controller.observable_2be_renamed.connect(
partial(
self.measurement_controller.rename_value,
column_names="observableId",
)
)
self.observable_controller.observable_2be_renamed.connect(
partial(
self.visualization_controller.rename_value,
column_names="yValues",
)
)
# Maybe TODO: add renaming dataset id?
# Rename Condition
self.condition_controller.condition_2be_renamed.connect(
partial(
self.measurement_controller.rename_value,
column_names=[
"simulationConditionId",
"preequilibrationConditionId",
],
)
)
# Plotting Disable Temporarily
for controller in self.controllers:
if controller == self.sbml_controller:
continue
controller.model.plotting_needs_break.connect(
self.plotter.disable_plotting
)
# Add new condition or observable
self.model.measurement.relevant_id_changed.connect(
lambda x, y, z: self.observable_controller.maybe_add_observable(
x, y
)
if z == "observable"
else self.condition_controller.maybe_add_condition(x, y)
if z == "condition"
else None
)
# Maybe Move to a Plot Model
self.view.measurement_dock.table_view.selectionModel().selectionChanged.connect(
self._on_table_selection_changed
)
self.view.simulation_dock.table_view.selectionModel().selectionChanged.connect(
self._on_simulation_selection_changed
)
# Unsaved Changes
self.model.measurement.something_changed.connect(
self.unsaved_changes_change
)
self.model.observable.something_changed.connect(
self.unsaved_changes_change
)
self.model.parameter.something_changed.connect(
self.unsaved_changes_change
)
self.model.condition.something_changed.connect(
self.unsaved_changes_change
)
self.model.visualization.something_changed.connect(
self.unsaved_changes_change
)
self.model.simulation.something_changed.connect(
self.unsaved_changes_change
)
self.model.sbml.something_changed.connect(self.unsaved_changes_change)
# Visibility
self.sync_visibility_with_actions()
# Recent Files
self.recent_files_manager.open_file.connect(
partial(self.open_file, mode="overwrite")
)
# Settings logging
settings_manager.new_log_message.connect(self.logger.log_message)
# Update Parameter SBML Model
self.sbml_controller.overwritten_model.connect(
self.parameter_controller.update_handler_sbml
)
# Plotting update. Regulated through a Timer
self._plot_update_timer = QTimer()
self._plot_update_timer.setSingleShot(True)
self._plot_update_timer.setInterval(0)
self._plot_update_timer.timeout.connect(self.init_plotter)
for controller in [
self.measurement_controller,
self.condition_controller,
self.visualization_controller,
self.simulation_controller,
]:
controller.overwritten_df.connect(self._schedule_plot_update)
def setup_actions(self):
"""Setup actions for the main controller."""
actions = {
"close": QAction(qta.icon("mdi6.close"), "&Close", self.view)
}
# Close
actions["close"].setShortcut(QKeySequence.Close)
actions["close"].triggered.connect(self.view.close)
# New File
actions["new"] = QAction(
qta.icon("mdi6.file-document"), "&New", self.view
)
actions["new"].setShortcut(QKeySequence.New)
actions["new"].triggered.connect(self.new_file)
# Open File
actions["open"] = QAction(
qta.icon("mdi6.folder-open"), "&Open...", self.view
)
actions["open"].setShortcut(QKeySequence.Open)
actions["open"].triggered.connect(
partial(self.open_file, mode="overwrite")
)
# Add File
actions["add"] = QAction(qta.icon("mdi6.table-plus"), "Add", self.view)
actions["add"].setShortcut("Ctrl+Shift+O")
actions["add"].triggered.connect(
partial(self.open_file, mode="append")
)
# Load Examples
actions["load_example_boehm"] = QAction(
qta.icon("mdi6.book-open-page-variant"),
"Load Example: Boehm",
self.view,
)
actions["load_example_boehm"].triggered.connect(
partial(self.load_example, "Boehm")
)
actions["load_example_simple"] = QAction(
qta.icon("mdi6.book-open-page-variant"),
"Load Example: Simple Conversion",
self.view,
)
actions["load_example_simple"].triggered.connect(
partial(self.load_example, "Simple_Conversion")
)
# Save
actions["save"] = QAction(
qta.icon("mdi6.content-save-all"), "&Save As...", self.view
)
actions["save"].setShortcut(QKeySequence.Save)
actions["save"].triggered.connect(self.save_model)
actions["save_single_table"] = QAction(
qta.icon("mdi6.table-arrow-down"), "Save This Table", self.view
)
actions["save_single_table"].triggered.connect(self.save_single_table)
# Find + Replace
actions["find"] = QAction(qta.icon("mdi6.magnify"), "Find", self.view)
actions["find"].setShortcut(QKeySequence.Find)
actions["find"].triggered.connect(self.find)
actions["find+replace"] = QAction(
qta.icon("mdi6.find-replace"), "Find/Replace", self.view
)
actions["find+replace"].setShortcut(QKeySequence.Replace)
actions["find+replace"].triggered.connect(self.replace)
# Copy / Paste
actions["copy"] = QAction(
qta.icon("mdi6.content-copy"), "Copy", self.view
)
actions["copy"].setShortcut(QKeySequence.Copy)
actions["copy"].triggered.connect(self.copy_to_clipboard)
actions["paste"] = QAction(
qta.icon("mdi6.content-paste"), "Paste", self.view
)
actions["paste"].setShortcut(QKeySequence.Paste)
actions["paste"].triggered.connect(self.paste_from_clipboard)
actions["cut"] = QAction(
qta.icon("mdi6.content-cut"), "&Cut", self.view
)
actions["cut"].setShortcut(QKeySequence.Cut)
actions["cut"].triggered.connect(self.cut)
# add/delete row
actions["add_row"] = QAction(
qta.icon("mdi6.table-row-plus-after"), "Add Row", self.view
)
actions["add_row"].triggered.connect(self.add_row)
actions["delete_row"] = QAction(
qta.icon("mdi6.table-row-remove"), "Delete Row(s)", self.view
)
actions["delete_row"].triggered.connect(self.delete_rows)
# add/delete column
actions["add_column"] = QAction(
qta.icon("mdi6.table-column-plus-after"),
"Add Column...",
self.view,
)
actions["add_column"].triggered.connect(self.add_column)
actions["delete_column"] = QAction(
qta.icon("mdi6.table-column-remove"), "Delete Column(s)", self.view
)
actions["delete_column"].triggered.connect(self.delete_column)
# check petab model
actions["check_petab"] = QAction(
qta.icon("mdi6.checkbox-multiple-marked-circle-outline"),
"Check PEtab",
self.view,
)
actions["check_petab"].triggered.connect(self.check_model)
actions["reset_model"] = QAction(
qta.icon("mdi6.restore"), "Reset SBML Model", self.view
)
actions["reset_model"].triggered.connect(
self.sbml_controller.reset_to_original_model
)
# Recent Files
actions["recent_files"] = self.recent_files_manager.tool_bar_menu
# simulate action
actions["simulate"] = QAction(
qta.icon("mdi6.play"), "Simulate", self.view
)
actions["simulate"].triggered.connect(self.simulate)
# Filter widget
filter_widget = QWidget()
filter_layout = QHBoxLayout()
filter_layout.setContentsMargins(0, 0, 0, 0)
filter_widget.setLayout(filter_layout)
self.filter_input = QLineEdit()
self.filter_input.setPlaceholderText("Filter...")
filter_layout.addWidget(self.filter_input)
for table_n, table_name in zip(
["m", "p", "o", "c", "v", "s"],
[
"measurement",
"parameter",
"observable",
"condition",
"visualization",
"simulation",
],
strict=False,
):
tool_button = QToolButton()
icon = qta.icon(
f"mdi6.alpha-{table_n}",
"mdi6.filter",
options=[
{"scale_factor": 1.5, "offset": (-0.2, -0.2)},
{"off": "mdi6.filter-off", "offset": (0.3, 0.3)},
],
)
tool_button.setIcon(icon)
tool_button.setCheckable(True)
tool_button.setChecked(True)
tool_button.setToolTip(f"Filter for {table_name} table")
filter_layout.addWidget(tool_button)
self.filter_active[table_name] = tool_button
self.filter_active[table_name].toggled.connect(self.filter_table)
actions["filter_widget"] = filter_widget
self.filter_input.textChanged.connect(self.filter_table)
# show/hide elements
for element in [
"measurement",
"observable",
"parameter",
"condition",
"visualization",
"simulation",
]:
actions[f"show_{element}"] = QAction(
f"{element.capitalize()} Table", self.view
)
actions[f"show_{element}"].setCheckable(True)
actions[f"show_{element}"].setChecked(True)
actions["show_logger"] = QAction("Info", self.view)
actions["show_logger"].setCheckable(True)
actions["show_logger"].setChecked(True)
actions["show_plot"] = QAction("Data Plot", self.view)
actions["show_plot"].setCheckable(True)
actions["show_plot"].setChecked(True)
actions["show_sbml_editor"] = QAction("SBML Editor", self.view)
actions["show_sbml_editor"].setCheckable(True)
actions["show_sbml_editor"].setChecked(True)
# What's This action
actions["whats_this"] = QAction(
qta.icon("mdi6.help-circle"), "Enter Help Mode", self.view
)
actions["whats_this"].setCheckable(True)
actions["whats_this"].setShortcut("Shift+F1")
self._whats_this_filter = _WhatsThisClickHelp(actions["whats_this"])
actions["whats_this"].toggled.connect(self._toggle_whats_this_mode)
# About action
actions["about"] = QAction(
qta.icon("mdi6.information"), "&About", self.view
)
actions["about"].triggered.connect(self.about)
# connect actions
actions["reset_view"] = QAction(
qta.icon("mdi6.view-grid-plus"), "Reset View", self.view
)
actions["reset_view"].triggered.connect(self.view.default_view)
# Clear Log
actions["clear_log"] = QAction(
qta.icon("mdi6.delete"), "Clear Log", self.view
)
actions["clear_log"].triggered.connect(self.logger.clear_log)
# Settings
actions["settings"] = QAction(
qta.icon("mdi6.cog"), "Settings", self.view
)
actions["settings"].triggered.connect(self.open_settings)
# Opening the PEtab documentation
actions["open_documentation"] = QAction(
qta.icon("mdi6.web"), "View PEtab Documentation", self.view
)
actions["open_documentation"].triggered.connect(
lambda: QDesktopServices.openUrl(
QUrl(
"https://petab.readthedocs.io/en/latest/v1/"
"documentation_data_format.html"
)
)
)
# Show next steps panel action
actions["next_steps"] = QAction(
qta.icon("mdi6.lightbulb-on"), "Possible next steps...", self.view
)
actions["next_steps"].triggered.connect(self._show_next_steps_panel)
# Undo / Redo
actions["undo"] = QAction(qta.icon("mdi6.undo"), "&Undo", self.view)
actions["undo"].setShortcut(QKeySequence.Undo)
actions["undo"].triggered.connect(self.undo_stack.undo)
actions["undo"].setEnabled(self.undo_stack.canUndo())
self.undo_stack.canUndoChanged.connect(actions["undo"].setEnabled)
actions["redo"] = QAction(qta.icon("mdi6.redo"), "&Redo", self.view)
actions["redo"].setShortcut(QKeySequence.Redo)
actions["redo"].triggered.connect(self.undo_stack.redo)
actions["redo"].setEnabled(self.undo_stack.canRedo())
self.undo_stack.canRedoChanged.connect(actions["redo"].setEnabled)
# Clear cells
actions["clear_cells"] = QAction(
qta.icon("mdi6.delete"), "&Clear Cells", self.view
)
actions["clear_cells"].setShortcuts(
[QKeySequence.Delete, QKeySequence.Backspace]
)
actions["clear_cells"].triggered.connect(self.clear_cells)
return actions
def sync_visibility_with_actions(self):
"""Sync dock visibility and QAction states in both directions."""
dock_map = {
"measurement": self.view.measurement_dock,
"observable": self.view.observable_dock,
"parameter": self.view.parameter_dock,
"condition": self.view.condition_dock,
"logger": self.view.logger_dock,
"plot": self.view.plot_dock,
"visualization": self.view.visualization_dock,
"simulation": self.view.simulation_dock,
}
for key, dock in dock_map.items():
action = self.actions[f"show_{key}"]
# Initial sync: block signal to avoid triggering unwanted
# visibility changes
was_blocked = action.blockSignals(True)
action.setChecked(dock.isVisible())
action.blockSignals(was_blocked)
# Connect QAction ↔ DockWidget syncing
action.toggled.connect(dock.setVisible)
dock.visibilityChanged.connect(action.setChecked)
# Connect SBML editor visibility toggle
sbml_action = self.actions["show_sbml_editor"]
sbml_widget = self.view.sbml_viewer.sbml_widget
# Store action reference in view for context menus
self.view.sbml_viewer.sbml_toggle_action = sbml_action
# Connect menu action to widget visibility
sbml_action.toggled.connect(sbml_widget.setVisible)
def save_model(self):
options = QFileDialog.Options()
file_name, filtering = QFileDialog.getSaveFileName(
self.view,
"Save Project",
"",
"COMBINE Archive (*.omex);;Zip Files (*.zip);;Folder",
options=options,
)
if not file_name:
return False
if filtering == "COMBINE Archive (*.omex)":
self.model.save_as_omex(file_name)
elif filtering == "Folder":
if file_name.endswith("."):
file_name = file_name[:-1]
target = Path(file_name)
target.mkdir(parents=True, exist_ok=True)
self.model.save(str(target))
file_name = str(target)
else:
if not file_name.endswith(".zip"):
file_name += ".zip"
# Create a temporary directory to save the model's files
with tempfile.TemporaryDirectory() as temp_dir:
self.model.save(temp_dir)
# Create a bytes buffer to hold the zip file in memory
buffer = BytesIO()
with zipfile.ZipFile(buffer, "w") as zip_file:
# Add files to zip archive
for root, _, files in os.walk(temp_dir):
for file in files:
file_path = os.path.join(root, file)
with open(file_path, "rb") as f:
zip_file.writestr(file, f.read())
with open(file_name, "wb") as f:
f.write(buffer.getvalue())
QMessageBox.information(
self.view,
"Save Project",
f"Project saved successfully to {file_name}",
)
# Show next steps panel if not disabled
dont_show = settings_manager.get_value(
"next_steps/dont_show_again", False, bool
)
if not dont_show:
self.next_steps_panel.show_panel()
return True
def save_single_table(self):
"""Save the currently active table to a tsv-file."""
active_controller = self.active_controller()
if not active_controller:
QMessageBox.warning(
self.view,
"Save Table",
"No active table to save.",
)
return None
file_name, _ = QFileDialog.getSaveFileName(
self.view,
"Save Table (as *.tsv)",
f"{active_controller.model.table_type}.tsv",
"TSV Files (*.tsv)",
)
if not file_name:
return False
active_controller.save_table(file_name)
return True
def handle_selection_changed(self):
"""Update the plot when selection in the measurement table changes."""
self.update_plot()
def handle_data_changed(self, top_left, bottom_right, roles):
"""Update the plot when the data in the measurement table changes."""
if not roles or Qt.DisplayRole in roles:
self.update_plot()
def update_plot(self):
"""Update the plot with the selected measurement data.
Extracts the selected data points from the measurement table and
updates the plot visualization with this data.
"""
selection_model = (
self.view.measurement_dock.table_view.selectionModel()
)
indexes = selection_model.selectedIndexes()
if not indexes:
return
selected_points = {}
for index in indexes:
if index.row() == self.model.measurement.get_df().shape[0]:
continue
row = index.row()
observable_id = self.model.measurement._data_frame.iloc[row][
"observableId"
]
if observable_id not in selected_points:
selected_points[observable_id] = []
selected_points[observable_id].append(
{
"x": self.model.measurement._data_frame.iloc[row]["time"],
"y": self.model.measurement._data_frame.iloc[row][
"measurement"
],
}
)
if selected_points == {}:
return
measurement_data = self.model.measurement._data_frame
plot_data = {"all_data": [], "selected_points": selected_points}
for observable_id in selected_points:
observable_data = measurement_data[
measurement_data["observableId"] == observable_id
]
plot_data["all_data"].append(
{
"observable_id": observable_id,
"x": observable_data["time"].tolist(),
"y": observable_data["measurement"].tolist(),
}
)
self.view.plot_dock.update_visualization(plot_data)
def open_file(self, file_path=None, mode=None):
"""Determines appropriate course of action for a given file.
Course of action depends on file extension, separator and header
structure. Opens the file in the appropriate controller.
"""
if not file_path:
file_path, _ = QFileDialog.getOpenFileName(
self.view,
"Open File",
"",
"All supported (*.yaml *.yml *.xml *.sbml *.tsv *.csv *.txt "
"*.omex);;"
"PEtab Problems (*.yaml *.yml);;SBML Files (*.xml *.sbml);;"
"PEtab Tables or Data Matrix (*.tsv *.csv *.txt);;"
"COMBINE Archive (*.omex);;"
"All files (*)",
)
if not file_path:
return
# handle file appropriately
actionable, sep = process_file(file_path, self.logger)
if actionable in ["yaml", "sbml", "omex"] and mode == "append":
self.logger.log_message(
f"Append mode is not supported for *.{actionable} files.",
color="red",
)
return
if not actionable:
return
if mode is None:
if actionable in ["yaml", "sbml", "omex"]:
mode = "overwrite"
else:
mode = prompt_overwrite_or_append(self)
if mode is None:
return
self.recent_files_manager.add_file(file_path)
self._open_file(actionable, file_path, sep, mode)
def _open_file(self, actionable, file_path, sep, mode):
"""Overwrites the File in the appropriate controller.
Actionable dictates which controller to use.
"""
if actionable == "yaml":
self.open_yaml_and_load_files(file_path)
elif actionable == "omex":
self.open_omex_and_load_files(file_path)
elif actionable == "sbml":
self.sbml_controller.overwrite_sbml(file_path)
elif actionable == "measurement":
self.measurement_controller.open_table(file_path, sep, mode)
elif actionable == "observable":
self.observable_controller.open_table(file_path, sep, mode)
elif actionable == "parameter":
self.parameter_controller.open_table(file_path, sep, mode)
elif actionable == "condition":
self.condition_controller.open_table(file_path, sep, mode)
elif actionable == "visualization":
self.visualization_controller.open_table(file_path, sep, mode)
elif actionable == "simulation":
self.simulation_controller.open_table(file_path, sep, mode)
elif actionable == "data_matrix":
self.measurement_controller.process_data_matrix_file(
file_path, mode, sep
)
def _validate_yaml_structure(self, yaml_content):
"""Validate PEtab YAML structure before attempting to load files.
Parameters
----------
yaml_content : dict
The parsed YAML content.
Returns
-------
tuple
(is_valid: bool, errors: list[str])
"""
errors = []
# Check format version
if "format_version" not in yaml_content:
errors.append("Missing 'format_version' field")
# Check problems array
if "problems" not in yaml_content:
errors.append("Missing 'problems' field")
return False, errors
if (
not isinstance(yaml_content["problems"], list)
or not yaml_content["problems"]
):
errors.append("'problems' must be a non-empty list")
return False, errors
problem = yaml_content["problems"][0]
# Optional but recommended fields
if (
"visualization_files" not in problem
or not problem["visualization_files"]
):
errors.append("Warning: No visualization_files specified")
# Required fields in problem
for field in [
"sbml_files",
"measurement_files",
"observable_files",
"condition_files",
]:
if field not in problem or not problem[field]:
errors.append("Problem must contain at least one SBML file")
# Check parameter_file (at root level)
if "parameter_file" not in yaml_content:
errors.append("Missing 'parameter_file' at root level")
return len([e for e in errors if "Warning" not in e]) == 0, errors
def _validate_files_exist(self, yaml_dir, yaml_content):
"""Validate that all files referenced in YAML exist.
Parameters
----------
yaml_dir : Path
The directory containing the YAML file.
yaml_content : dict
The parsed YAML content.
Returns
-------
tuple
(all_exist: bool, missing_files: list[str])
"""
missing_files = []
problem = yaml_content["problems"][0]
# Check SBML files
for sbml_file in problem.get("sbml_files", []):
if not (yaml_dir / sbml_file).exists():
missing_files.append(str(sbml_file))
# Check measurement files
for meas_file in problem.get("measurement_files", []):
if not (yaml_dir / meas_file).exists():
missing_files.append(str(meas_file))
# Check observable files
for obs_file in problem.get("observable_files", []):
if not (yaml_dir / obs_file).exists():
missing_files.append(str(obs_file))
# Check condition files
for cond_file in problem.get("condition_files", []):
if not (yaml_dir / cond_file).exists():
missing_files.append(str(cond_file))
# Check parameter file
if "parameter_file" in yaml_content:
param_file = yaml_content["parameter_file"]
if not (yaml_dir / param_file).exists():
missing_files.append(str(param_file))
# Check visualization files (optional)
for vis_file in problem.get("visualization_files", []):
if not (yaml_dir / vis_file).exists():
missing_files.append(str(vis_file))
return len(missing_files) == 0, missing_files
def _load_file_list(self, controller, file_list, file_type, yaml_dir):
"""Load multiple files for a given controller.
Parameters
----------
controller : object
The controller to load files into (e.g., measurement_controller).
file_list : list[str]
List of file names to load.
file_type : str
Human-readable file type for logging (e.g., "measurement").
yaml_dir : Path
The directory containing the YAML and data files.
"""
for i, file_name in enumerate(file_list):
file_mode = "overwrite" if i == 0 else "append"
controller.open_table(yaml_dir / file_name, mode=file_mode)
self.logger.log_message(
f"Loaded {file_type} file ({i + 1}/{len(file_list)}): {file_name}",
color="blue",
)
def open_yaml_and_load_files(self, yaml_path=None, mode="overwrite"):
"""Open files from a YAML configuration.
Opens a dialog to upload yaml file. Creates a PEtab problem and
overwrites the current PEtab model with the new problem.
"""
if not yaml_path:
yaml_path, _ = QFileDialog.getOpenFileName(
self.view, "Open YAML File", "", "YAML Files (*.yaml *.yml)"
)
if not yaml_path:
return
try:
for controller in self.controllers:
if controller == self.sbml_controller:
continue
controller.release_completers()
# Load the YAML content
with open(yaml_path, encoding="utf-8") as file:
yaml_content = yaml.safe_load(file)
# Validate PEtab version
if (major := get_major_version(yaml_content)) != 1:
raise ValueError(
f"Only PEtab v1 problems are currently supported. "
f"Detected version: {major}.x."
)
# Validate YAML structure
is_valid, errors = self._validate_yaml_structure(yaml_content)
if not is_valid:
error_msg = "Invalid YAML structure:\n - " + "\n - ".join(
[e for e in errors if "Warning" not in e]
)
self.logger.log_message(error_msg, color="red")
QMessageBox.critical(
self.view, "Invalid PEtab YAML", error_msg
)
return
# Log warnings but continue
warnings = [e for e in errors if "Warning" in e]
for warning in warnings:
self.logger.log_message(warning, color="orange")
# Resolve the directory of the YAML file to handle relative paths
yaml_dir = Path(yaml_path).parent
# Validate file existence
all_exist, missing_files = self._validate_files_exist(
yaml_dir, yaml_content
)
if not all_exist:
error_msg = (
"The following files referenced in the YAML are missing:\n - "
+ "\n - ".join(missing_files)
)
self.logger.log_message(error_msg, color="red")
QMessageBox.critical(self.view, "Missing Files", error_msg)
return
problem = yaml_content["problems"][0]
# Load SBML model (required, single file)
sbml_files = problem.get("sbml_files", [])
if sbml_files:
sbml_file_path = yaml_dir / sbml_files[0]
self.sbml_controller.overwrite_sbml(sbml_file_path)
self.logger.log_message(
f"Loaded SBML file: {sbml_files[0]}", color="blue"
)
# Load measurement files (multiple allowed)
measurement_files = problem.get("measurement_files", [])
if measurement_files:
self._load_file_list(
self.measurement_controller,
measurement_files,
"measurement",
yaml_dir,
)
# Load observable files (multiple allowed)
observable_files = problem.get("observable_files", [])
if observable_files:
self._load_file_list(