-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathpotku.py
executable file
·1526 lines (1307 loc) · 60.7 KB
/
potku.py
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
#!/usr/bin/env python
# coding=utf-8
"""
Created on 21.3.2013
Updated on 18.4.2024
Potku
Copyright (C) 2013-2018 Jarkko Aalto, Severi Jääskeläinen, Samuel Kaiponen,
Timo Konu, Samuli Kärkkäinen, Samuli Rahkonen, Miika Raunio, Heta Rekilä and
Sinikka Siironen, 2020 Juhani Sundell, 2013-2024 Jaakko Julin
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program (file named 'LICENSE').
"""
__author__ = "Jarkko Aalto \n Timo Konu \n Samuli Kärkkäinen \n Samuli " \
"Rahkonen \n Miika Raunio \n Severi Jääskeläinen \n Samuel " \
"Kaiponen \n Heta Rekilä \n Sinikka Siironen \n Juhani Sundell \
\n Jaakko Julin"
__version__ = "2.0"
import functools
import gc
import os
import platform
import shutil
import subprocess
import sys
import argparse
from datetime import datetime
from datetime import timedelta
from pathlib import Path
from typing import Union
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from PyQt5 import uic
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QAbstractItemView, QMessageBox
from PyQt5.QtWidgets import QMenu
from PyQt5.QtWidgets import QTreeWidgetItem
import modules.general_functions as gf
import dialogs.dialog_functions as df
import widgets.gui_utils as gutils
import widgets.input_validation as iv
from dialogs.about import AboutDialog
from dialogs.file_dialogs import open_file_dialog
from dialogs.global_settings import GlobalSettingsDialog
from dialogs.measurement.import_binary import ImportDialogBinary
from dialogs.measurement.import_measurement import ImportMeasurementsDialog
from dialogs.measurement.load_measurement import LoadMeasurementDialog
from dialogs.new_request import RequestNewDialog
from dialogs.request_settings import RequestSettingsDialog
from dialogs.simulation.new_simulation import SimulationNewDialog
from modules.global_settings import GlobalSettings
from modules.measurement import Measurement
from modules.request import Request
from modules.selection import Selector
from modules.simulation import Simulation
from widgets.base_tab import BaseTab
from widgets.gui_utils import StatusBarHandler
from widgets.icon_manager import IconManager
from widgets.measurement.tab import MeasurementTabWidget
from widgets.simulation.tab import SimulationTabWidget
from modules.config_manager import ConfigManager
class Potku(QtWidgets.QMainWindow):
"""Potku is main window class.
"""
# Maximum number of recently opened .request files to store and show in
# the menu.
MAX_RECENT_FILES = 20
RECENT_FILES_KEY = "recently_opened"
settings_updated = QtCore.pyqtSignal([], [GlobalSettings])
def __init__(self):
"""Init main window for Potku.
"""
super().__init__()
version_number, version_date = gf.get_version_number_and_date()
potku_version = f'Potku {version_number} - {version_date}'
self.setWindowTitle(potku_version)
parser = argparse.ArgumentParser(prog=potku_version)
parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output')
parser.add_argument('--no-scroll', action='store_true',
help='Ignore mouse wheel events in comboboxes and spinboxes')
parser.add_argument('request', nargs='?', type=str, default=None)
args = parser.parse_args()
if args.verbose:
print("Potku root directory is " + str(gf.get_root_dir()))
print("C programs installed in " + str(gf.get_bin_dir()))
uic.loadUi(gutils.get_ui_dir() / "ui_main_window.ui", self)
# Disable mouse wheel scrolling in all spin boxes and combo boxes as
# requested by a user (see comments in
# https://github.com/JYU-IBA/potku/issues/214).
# if --no-scroll is given
if args.no_scroll:
gutils.disable_scrolling_in_spin_boxes()
gutils.disable_scrolling_in_combo_boxes()
self.title = self.windowTitle()
self.treeWidget.setHeaderLabel("")
self.icon_manager = IconManager()
self.settings = GlobalSettings()
self.request = None
# Holds references to all the tab widgets in "tab_measurements"
# (even when they are removed from the QTabWidget)
self.tab_widgets = {}
self.tab_id = 0 # identification for each tab
# Set up connections within UI
self.actionNew_Measurement.triggered.connect(self.open_new_measurement)
self.requestSettingsButton.clicked.connect(self.open_request_settings)
self.globalSettingsButton.clicked.connect(self.open_global_settings)
self.tabs.tabCloseRequested.connect(self.remove_tab)
self.treeWidget.itemDoubleClicked.connect(self.focus_selected_tab)
self.requestNewButton.clicked.connect(self.make_new_request)
self.requestOpenButton.clicked.connect(self.open_request)
self.actionNew_Request.triggered.connect(self.make_new_request)
self.actionOpen_Request.triggered.connect(self.open_request)
self.addNewMeasurementButton.clicked.connect(self.open_new_measurement)
self.actionNew_measurement_2.triggered.connect(
self.open_new_measurement)
self.actionImport_jyfl.triggered.connect(self.import_jyfl)
self.actionBinary_data_lst.triggered.connect(self.import_binary)
self.action_manual.triggered.connect(self.__open_manual)
self.actionDataHelp.triggered.connect(self.__open_data_help)
self.actionSave_cuts.triggered.connect(
self.current_measurement_save_cuts)
self.actionAnalyze_elemental_losses.triggered.connect(
self.current_measurement_analyze_elemental_losses)
self.actionCreate_energy_spectrum.triggered.connect(
self.current_measurement_create_energy_spectrum)
self.actionCreate_depth_profile.triggered.connect(
self.current_measurement_create_depth_profile)
self.actionGlobal_Settings.triggered.connect(self.open_global_settings)
self.actionRequest_Settings.triggered.connect(
self.open_request_settings)
self.actionAbout.triggered.connect(AboutDialog)
self.actionNew_Request_2.triggered.connect(self.make_new_request)
self.actionOpen_Request_2.triggered.connect(self.open_request)
# Should save changes
self.actionExit.triggered.connect(self.close)
self.menuImport.setEnabled(False)
# by default show left panel when opening application
gutils.set_potku_setting("left_panel_shown", True)
df.set_up_side_panel(self, "left_panel_shown", "left")
# Set up simulation connections within UI
self.actionNew_Simulation.triggered.connect(
self.create_new_simulation)
self.actionNew_Simulation_2.triggered.connect(
self.create_new_simulation)
self.actionCreate_energy_spectrum_sim.triggered.connect(
self.current_simulation_create_energy_spectrum)
self.addNewSimulationButton.clicked.connect(
self.create_new_simulation)
# Set up styles for main window
# Cannot use os.path.join or pathlib, since PyQT+css want a URL-style (relative?) path
images_dir = str(gf.get_images_dir().relative_to(os.getcwd())).replace("\\", "/")
bg_blue = images_dir + "/background_blue.svg"
bg_green = images_dir + "/background_green.svg"
style_intro = "QWidget#introduceTab {border-image: url(" \
+ bg_blue + ");}"
style_mesinfo = ("QWidget#infoTab {border-image: url(" +
bg_green + ");}")
self.introduceTab.setStyleSheet(style_intro)
self.infoTab.setStyleSheet(style_mesinfo)
self.__remove_info_tab()
self.setWindowIcon(self.icon_manager.get_icon("potku_icon.ico"))
self.update_recent_file_menu()
# Set main window's icons to place
self.__set_icons()
self.showMaximized()
if args.request:
self.__open_request(Path(args.request))
def __initialize_tree_view(self):
"""Inits the tree view and creates the top level items.
"""
self.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu)
self.treeWidget.customContextMenuRequested.connect(self.__open_menu)
self.treeWidget.setDropIndicatorShown(True)
self.treeWidget.setDragDropMode(QAbstractItemView.InternalMove)
# Disable dragging since it doesn't do anything yet
# TODO: Dragging changes the order of the items in tree and directory
self.treeWidget.setDragEnabled(False)
self.treeWidget.setSelectionMode(QAbstractItemView.SingleSelection)
self.treeWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.treeWidget.itemChanged[QTreeWidgetItem, int].connect(
self.__rename_dir)
def __open_menu(self, position):
"""Opens the right click menu in tree view.
"""
indexes = self.treeWidget.selectedIndexes()
level = 0
if len(indexes) > 0:
level = 0
index = indexes[0]
while index.parent().isValid():
index = index.parent()
level += 1
menu = QMenu()
if level == 1:
menu.addAction("Rename", self.__rename_tree_item)
menu.addAction("Remove", self.__remove_tree_item)
current_item = self.treeWidget.currentItem()
if current_item and isinstance(current_item.obj, Measurement):
menu.addAction("Make master", self.__make_master_measurement)
menu.addAction("Remove master", self.__remove_master_measurement)
menu.addAction(
"Exclude from slaves", lambda: self.__set_slave_status(False))
menu.addAction(
"Include as slave", lambda: self.__set_slave_status(True))
menu.exec_(self.treeWidget.viewport().mapToGlobal(position))
def __rename_tree_item(self):
"""Renames selected tree item in tree view and in folder structure.
"""
clicked_item = self.treeWidget.currentItem()
self.treeWidget.editItem(clicked_item)
@gutils.block_treewidget_signals
def __rename_dir(self, *_):
"""Renames object based on selected tree item. This method is called
when tree item is changed.
"""
clicked_item = self.treeWidget.currentItem()
if not clicked_item:
return
# TODO do all name validation in the backend modules
valid_text = iv.validate_text_input(clicked_item.text(0))
if valid_text != clicked_item.text(0):
QtWidgets.QMessageBox.information(
self, "Notice",
"You can't use special characters other than '-' in the name.",
QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
clicked_item.setText(0, clicked_item.obj.name)
return
if valid_text == "":
clicked_item.setText(0, clicked_item.obj.name)
return
if valid_text == clicked_item.obj.name:
clicked_item.setText(0, clicked_item.obj.name)
return
new_name = valid_text
try:
clicked_item.obj: Union[Measurement, Simulation]
clicked_item.obj.rename(new_name)
except OSError as e:
QtWidgets.QMessageBox.critical(
self, "Error", str(e),
QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
if type(clicked_item.obj) is Measurement:
# Update Energy spectrum, Composition changes and Depth profile
# save files.
for i in range(self.tabs.count()):
tab_widget = self.tabs.widget(i)
if tab_widget.obj is clicked_item.obj:
if tab_widget.energy_spectrum_widget:
tab_widget.energy_spectrum_widget.update_use_cuts()
tab_widget.energy_spectrum_widget.save_to_file()
if tab_widget.elemental_losses_widget:
tab_widget.elemental_losses_widget.update_cuts()
tab_widget.elemental_losses_widget.save_to_file()
if tab_widget.depth_profile_widget:
tab_widget.depth_profile_widget.update_use_cuts()
tab_widget.depth_profile_widget.save_to_file()
self.remove_tab(i)
self.tabs.insertTab(i, tab_widget,
clicked_item.obj.name)
self.tabs.setCurrentWidget(tab_widget)
break
elif type(clicked_item.obj) is Simulation:
# Update Tab name
for i in range(self.tabs.count()):
tab_widget = self.tabs.widget(i)
if tab_widget.obj is clicked_item.obj:
self.remove_tab(i)
self.tabs.insertTab(i, tab_widget,
clicked_item.obj.name)
self.tabs.setCurrentWidget(tab_widget)
break
clicked_item.setText(0, clicked_item.obj.name)
@gutils.block_treewidget_signals
def __remove_tree_item(self):
"""Removes selected tree item in tree view and in folder structure.
"""
clicked_item = self.treeWidget.currentItem()
if clicked_item:
if type(clicked_item.obj) is Measurement:
obj_type = "measurement"
elif type(clicked_item.obj) is Simulation:
obj_type = "simulation"
else:
obj_type = "" # TODO: place for sample type checking.
reply = QtWidgets.QMessageBox.question(
self, "Confirmation",
f"Deleting selected {obj_type} will delete all files and "
f"folders under selected {obj_type} directory.\n\n"
f"Are you sure you want to delete selected {obj_type}?",
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel)
if reply == QtWidgets.QMessageBox.No or reply == \
QtWidgets.QMessageBox.Cancel:
return # If clicked Yes, then continue normally
# Remove object from Sample
clicked_item.parent().obj.remove_obj(clicked_item.obj)
clicked_item.obj.close_log_files()
# Remove object directory
shutil.rmtree(clicked_item.obj.directory)
# Remove object from tree
clicked_item.parent().removeChild(clicked_item)
# Remove object tab
for i in range(self.tabs.count()):
if self.tabs.widget(i).obj is clicked_item.obj:
self.tabs.removeTab(i)
break
self.tab_widgets.pop(clicked_item.obj.tab_id)
def closeEvent(self, event):
"""
Save recoil elements and simulation targets and close the program.
"""
if self.request is not None:
for sample in self.request.samples.samples:
for simulation in sample.simulations.simulations.values():
for elem_sim in simulation.element_simulations:
for recoil_element in elem_sim.recoil_elements:
recoil_element.to_file(elem_sim.directory)
simulation.target.to_file(
Path(simulation.directory, simulation.target.name +
".target"))
if not self.are_simulations_stopped():
# TODO also needs to be done when new request is being opened
event.ignore()
return
widget = self.tabs.currentWidget()
if isinstance(widget, BaseTab):
widget.save_geometries()
super().closeEvent(event)
def are_simulations_stopped(self):
"""Checks all running simulations for current request and prompts
user to stop them. Returns True if user chooses to stop the
simulations or there are no simulations, otherwise returns False.
"""
if self.request is not None:
sims = {
*self.request.get_running_optimizations(),
*self.request.get_running_simulations()
}
if sims:
reply = QtWidgets.QMessageBox.question(
self, "Running simulations",
"There are simulations currently running. These must be "
"stopped before closing the program.\n"
"Do you want stop the simulations?",
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel,
QtWidgets.QMessageBox.Yes
)
if reply == QtWidgets.QMessageBox.Cancel:
return False
events = [sim.stop() for sim in sims]
for e in events:
# Note: while the worst case scenario is that we'll be
# stuck here for len(sims) seconds, it is likely that
# all simulations have stopped within 0.2 seconds (the
# default interval for checking stopping requests). Some
# overhead for releasing locks and notifying listeners
# is also to be expected.
e.wait(timeout=1)
return True
def current_measurement_create_depth_profile(self):
"""Opens the depth profile analyzation tool for the current open
measurement tab widget.
"""
widget = self.tabs.currentWidget()
if isinstance(widget, MeasurementTabWidget):
widget.open_depth_profile()
else:
QtWidgets.QMessageBox.question(
self, "Notification",
"An open measurement is required to do this action.",
QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
def current_measurement_analyze_elemental_losses(self):
"""Opens the element losses analyzation tool for the current open
measurement tab widget.
"""
widget = self.tabs.currentWidget()
if isinstance(widget, MeasurementTabWidget):
widget.open_element_losses()
else:
QtWidgets.QMessageBox.question(
self, "Notification",
"An open measurement is required to do this action.",
QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
def current_measurement_create_energy_spectrum(self):
"""Opens the energy spectrum analyzation tool for the current open
measurement tab widget.
"""
widget = self.tabs.currentWidget()
if isinstance(widget, MeasurementTabWidget):
widget.open_energy_spectrum()
else:
QtWidgets.QMessageBox.question(
self, "Notification",
"An open measurement is required to do this action.",
QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
def current_measurement_save_cuts(self):
"""Saves the current open measurement tab widget's selected cuts
to cut files.
"""
widget = self.tabs.currentWidget()
if isinstance(widget, MeasurementTabWidget):
widget.measurement_save_cuts()
else:
QtWidgets.QMessageBox.question(
self, "Notification",
"An open measurement is required to do this action.",
QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
def current_simulation_create_energy_spectrum(self):
"""
Opens the energy spectrum analyzation tool for the current open
simulation tab widget.
"""
widget = self.tabs.currentWidget()
if isinstance(widget, MeasurementTabWidget):
widget.open_energy_spectrum()
else:
QtWidgets.QMessageBox.question(
self, "Notification",
"An open simulation is required to do this action.",
QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
def delete_selections(self):
"""Deletes the selected tree widget items.
"""
# TODO: Memory isn't released correctly. Maybe because of matplotlib.
selected_tabs = [self.tab_widgets[item.tab_id] for
item in self.treeWidget.selectedItems()]
if selected_tabs: # Ask user a confirmation.
reply = QtWidgets.QMessageBox.question(
self, "Confirmation",
"Deleting selected measurements will delete all files and "
"folders under selected measurement directories.\n\n"
"Are you sure you want to delete selected measurements?",
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel)
if reply == QtWidgets.QMessageBox.No or reply == \
QtWidgets.QMessageBox.Cancel:
return # If clicked Yes, then continue normally
for tab in selected_tabs:
measurement = self.request.samples.measurements.get_key_value(
tab.tab_id)
try:
# Close and remove logs
measurement.close_log_files()
# Remove measurement's directory tree
shutil.rmtree(measurement.directory)
Path(self.request.directory /
measurement.measurement_file).unlink()
except:
QtWidgets.QMessageBox.question(
self, "Confirmation",
"Problem with deleting files.",
QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
# TODO check that this is the intented way of setting the
# loggers in case something went wrong.
measurement.set_up_log_files(measurement.directory,
measurement.request.directory)
return
self.request.samples.measurements.remove_by_tab_id(tab.tab_id)
remove_index = self.tabs.indexOf(tab)
self.remove_tab(remove_index) # Remove measurement from open tabs
tab.histogram.matplotlib.delete()
tab.elemental_losses_widget.matplotlib.delete()
tab.energy_spectrum_widget.matplotlib.delete()
tab.depth_profile_widget.matplotlib.delete()
tab.mdiArea.closeAllSubWindows()
del self.tab_widgets[tab.tab_id]
tab.close()
tab.deleteLater()
# Remove selected from tree widget
root = self.treeWidget.invisibleRootItem()
for item in self.treeWidget.selectedItems():
(item.parent() or root).removeChild(item)
gc.collect() # Suggest garbage collector to clean.
@gutils.block_treewidget_signals
def focus_selected_tab(self, clicked_item, *_):
"""Focus to selected tab (in tree widget) and if it isn't open, open it.
Args:
clicked_item: TreeWidgetItem with tab_id attribute (int) that
connects the item to the corresponding MeasurementTabWidget
*_: unused event args.
"""
sbh = StatusBarHandler(self.statusbar)
try:
tab_id = clicked_item.tab_id
tab = self.tab_widgets[tab_id]
if type(tab) is SimulationTabWidget:
kwargs = {
"settings": self.settings,
"settings_updated": self.settings_updated,
"ion_division": self.settings.get_ion_division(),
"min_presim_ions": self.settings.get_min_presim_ions(),
"min_sim_ions": self.settings.get_min_simulation_ions()
}
else:
kwargs = {}
tab.load_data(
progress=sbh.reporter.get_sub_reporter(lambda x: 0.9 * x),
**kwargs)
name = tab.obj.name
if type(tab) is MeasurementTabWidget:
master_mea = tab.obj.request.get_master()
if master_mea and tab.obj.name == master_mea.name:
name = f"{name} (master)"
# Check that the tab to be focused exists.
if not self.__tab_exists(tab_id):
self.tabs.addTab(tab, name)
self.tabs.setCurrentWidget(tab)
self.__change_tab_icon(clicked_item)
except AttributeError as e:
print(e) # TODO remove print
sbh.reporter.report(100)
def import_jyfl(self):
"""Import JYFL style evnt file measurements into request.
"""
if not self.request:
return
# For loading measurements.
import_dialog = ImportMeasurementsDialog(
self.request, self.icon_manager, self.statusbar, self)
if import_dialog.imported:
self.__remove_info_tab()
def import_binary(self):
"""Import binary measurements into request.
Import binary measurements from
"""
if not self.request:
return
import_dialog = ImportDialogBinary(
self.request, self.icon_manager, self.statusbar, self)
if import_dialog.imported:
self.__remove_info_tab()
def load_request_measurements(self, measurements=None, progress=None):
"""Load measurement files in the request.
Args:
measurements: A list representing loadable measurements when
importing measurements to the request.
progress: a ProgressReporter object
"""
if measurements is None:
measurements = []
if measurements:
samples_with_measurements = measurements
load_data = True
else:
# a dict with the sample as a key, and measurements' info file paths
# in the value as a list
samples_with_measurements = \
self.request.samples.get_samples_and_measurements()
load_data = False
count = len(samples_with_measurements)
dirtyinteger = 0
for sample, measurements in samples_with_measurements.items():
for measurement_file in measurements:
self.add_new_tab("measurement", measurement_file, sample,
dirtyinteger, count, load_data=load_data)
if progress is not None:
progress.report(dirtyinteger / count * 100)
dirtyinteger += 1
if progress is not None:
progress.report(100)
def load_request_samples(self, progress=None):
""""Load sample files in the request.
Args:
progress: a ProgressReporter object
"""
sample_paths_in_request = self.request.get_sample_directories()
if sample_paths_in_request:
for i, sample_path in enumerate(sample_paths_in_request):
sample = self.request.samples.add_sample(sample_path=sample_path)
self.add_root_item_to_tree(sample)
if progress is not None:
progress.report(i / len(sample_paths_in_request) * 100)
if progress is not None:
progress.report(100)
def load_request_simulations(self, simulations=None, progress=None):
"""Load simulation files in the request.
Args:
simulations: A list representing loadable simulation when importing
simulation to the request.
progress: a ProgressReporter object
"""
if simulations is None:
simulations = []
if simulations:
samples_with_simulations = simulations
load_data = True
else:
samples_with_simulations = \
self.request.samples.get_samples_and_simulations()
load_data = False
count = len(samples_with_simulations)
dirtyinteger = 0
for sample, simulations in samples_with_simulations.items():
for simulation_file in simulations:
self.add_new_tab("simulation", simulation_file, sample,
dirtyinteger, count, load_data=load_data)
if progress is not None:
progress.report(dirtyinteger / count * 100)
dirtyinteger += 1
if progress is not None:
progress.report(100)
pass
def make_new_request(self):
"""Opens a dialog for creating a new request.
"""
if not self.are_simulations_stopped():
return
# The directory for request is already created after this
dialog = RequestNewDialog(self)
# TODO: regex check for directory. I.E. do not allow asd/asd
if dialog.directory:
self.__close_request()
title = f"{self.title} - Request: {dialog.name}"
self.setWindowTitle(title)
self.treeWidget.setHeaderLabel(f"Request: {dialog.name}")
self.__initialize_tree_view()
self.request = Request(
dialog.directory, dialog.name, self.settings, self.tab_widgets)
self.settings.set_request_directory_last_open(dialog.directory)
self.request.log("Request created.")
# Request made, close introduction tab
self.__remove_introduction_tab()
self.__open_info_tab()
self.__set_request_buttons_enabled(True)
self.add_to_recent_files(Path(self.request.request_file))
def open_global_settings(self):
"""Opens global settings dialog.
"""
gsd = GlobalSettingsDialog(self.settings)
gsd.settings_updated.connect(self.settings_updated[GlobalSettings].emit)
gsd.exec_()
def open_new_measurement(self):
"""Opens file an open dialog and if filename is given opens new
measurement from it.
"""
if self.request is None:
return
dialog = LoadMeasurementDialog(self.request.samples.samples,
self.request.directory)
sample_name = dialog.sample_str
if dialog.path:
try:
self.tabs.removeTab(self.tabs.indexOf(
self.measurement_info_tab))
except AttributeError:
pass # If there is no info tab, no need to worry about.
sbh = StatusBarHandler(self.statusbar)
try:
sample_item = self.treeWidget.findItems(
sample_name, Qt.MatchEndsWith, 0)[0]
except IndexError:
# Sample is not yet in the tree, so add it
sample_item = self.__add_sample(sample_name)
self.add_new_tab(
"measurement", dialog.path, sample_item.obj, load_data=True,
object_name=dialog.name,
progress=sbh.reporter.get_sub_reporter(lambda x: 0.9 * x))
self.__remove_info_tab()
sbh.reporter.report(100)
def create_new_simulation(self):
"""
Opens a dialog for creating a new simulation.
"""
dialog = SimulationNewDialog(self.request.samples.samples)
simulation_name = dialog.name
sample_name = dialog.sample_str
if simulation_name and sample_name:
sbh = StatusBarHandler(self.statusbar)
try:
sample_item = self.treeWidget.findItems(sample_name,
Qt.MatchEndsWith, 0)[0]
except IndexError:
# Sample is not yet in the tree, so add it
sample_item = self.__add_sample(sample_name)
serial_number = sample_item.obj.get_running_int_simulation()
sample_item.obj.increase_running_int_simulation_by_1()
self.add_new_tab("simulation", Path(
self.request.directory, sample_item.obj.directory,
Simulation.DIRECTORY_PREFIX + "%02d" % serial_number + "-" +
dialog.name, f"{dialog.name}.mccfg"), sample_item.obj,
load_data=True,
progress=sbh.reporter.get_sub_reporter(
lambda x: 0.9 * x
))
self.__remove_info_tab()
sbh.reporter.report(100)
def __add_sample(self, sample_name):
"""Creates a new Sample object and adds it to tree view.
Args:
sample_name: Sample name.
Return:
TreeWidgetItem
"""
sample = self.request.samples.add_sample(name=sample_name)
return self.add_root_item_to_tree(sample)
def update_recent_file_menu(self, files=None):
"""Updates the recently opened file menu. Previous actions are
replaced by new ones based on the given list of files.
Args:
files: list of files to be shown in the menu
"""
# Note: when running Potku as a Python script on Mac, the recently
# opened files menu becomes inactive after creating a new request.
# This is fixed when Potku is bundled intp an app.
self.menuOpen_recent.clear()
if files is None:
files = Potku.get_recent_files()
for f in files[:Potku.MAX_RECENT_FILES]:
act = self.menuOpen_recent.addAction(str(f))
act.triggered.connect(
functools.partial(self.__open_request, Path(f)))
if not files:
act = self.menuOpen_recent.addAction("<empty>")
act.setEnabled(False)
else:
self.menuOpen_recent.addSeparator()
act = self.menuOpen_recent.addAction("Empty recently opened list")
act.triggered.connect(self.clear_recent_files)
def clear_recent_files(self):
"""Clears the list of recently opened files.
"""
gutils.remove_potku_setting(key=Potku.RECENT_FILES_KEY)
self.update_recent_file_menu(files=[])
@staticmethod
def get_recent_files():
"""Returns a list of recently opened .request files. Files are sorted
so that the most recent is first.
"""
return gutils.get_potku_setting(Potku.RECENT_FILES_KEY, [], list)
@staticmethod
def set_recent_files(files):
"""Stores the list of files as the most recently opened files.
Args:
files: list of file paths (as strings) to store
"""
gutils.set_potku_setting(Potku.RECENT_FILES_KEY,
files[:Potku.MAX_RECENT_FILES])
def add_to_recent_files(self, file):
"""Inserts the given file as the first element in the recently
opened file list and updates the menu.
Args:
file: file to be added to the list
"""
files = Potku.get_recent_files()
file_str = str(file)
try:
files.remove(file_str)
except ValueError:
# File was not in list, nothing to do
pass
files.insert(0, file_str)
Potku.set_recent_files(files)
self.update_recent_file_menu(files=files)
def remove_from_recent_files(self, file):
"""Removes a file from recently added file list.
Args:
file: file to be removed
"""
files = Potku.get_recent_files()
try:
files.remove(str(file))
Potku.set_recent_files(files)
self.update_recent_file_menu(files=files)
except ValueError:
# File was not in list, nothing to do
pass
def open_request(self):
"""Shows a dialog to open a request.
"""
if not self.are_simulations_stopped():
return
file = open_file_dialog(
self, self.settings.get_request_directory_last_open(),
"Open an existing request", "Request file (*.request)")
if file:
self.__open_request(Path(file))
def __open_request(self, file: Path):
"""Opens a request in the main"""
if not self.are_simulations_stopped():
return
try:
request = Request.from_file(file, self.settings, self.tab_widgets)
except Exception as e:
QtWidgets.QMessageBox.critical(
self, "Error", f"Could not open the request: {e}",
QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok
)
self.remove_from_recent_files(file)
return
# Checks for maximum path length. If too long some files might not be reachable
if (gf.check_max_path_length()[0] > 240):
msgBox = QMessageBox()
msgBox.setIcon(QMessageBox.Information)
msgBox.setText( f"Longest path is now {gf.check_max_path_length()[0]} characters long.\n"
f"There might be problems if Windows maximum path length (256) is exceeded")
msgBox.setWindowTitle("Path length warning")
msgBox.setStandardButtons(QMessageBox.Ok)
msgBox.exec()
sbh = StatusBarHandler(self.statusbar)
self.__close_request()
self.add_to_recent_files(Path(file))
self.request = request
self.setWindowTitle("{0} - Request: {1}".format(
self.title,
self.request.get_name()))
self.treeWidget.setHeaderLabel(
"Request: {0}".format(self.request.get_name()))
self.__initialize_tree_view()
folder = file.parent
self.settings.set_request_directory_last_open(folder)
sbh.reporter.report(20)
self.load_request_samples(progress=sbh.reporter.get_sub_reporter(
lambda x: 20 + 0.2 * x
))
self.load_request_measurements(progress=sbh.reporter.get_sub_reporter(
lambda x: 40 + 0.2 * x
))
self.load_request_simulations(progress=sbh.reporter.get_sub_reporter(
lambda x: 80 + 0.2 * x
))
self.__remove_introduction_tab()
self.__set_request_buttons_enabled(True)
master_measurement = self.request.has_master()
nonslaves = self.request.get_nonslaves()
if master_measurement != "":
self.request.set_master(master_measurement)
master_measurement_name = master_measurement.name
else:
master_measurement_name = None
for sample in self.request.samples.samples:
# Get Sample item from tree
try:
sample_item = self.treeWidget.findItems(
"%02d" % sample.serial_number + " " + sample.name,
Qt.MatchEndsWith,
0)[0]
for i in range(sample_item.childCount()):
item = sample_item.child(i)
tab_widget = self.tab_widgets[item.tab_id]
tab_name = tab_widget.obj.name
if master_measurement_name and \
item.tab_id == master_measurement.tab_id:
item.setText(0, "{0} (master)".format(master_measurement_name))
elif tab_widget.obj in nonslaves or \
not master_measurement_name or isinstance(tab_widget.obj, Simulation):
item.setText(0, tab_name)
else:
item.setText(0, "{0} (slave)".format(tab_name))
for i in range(sample_item.childCount()):
item = sample_item.child(i)
tab_widget = self.tab_widgets[item.tab_id]
tab_name = tab_widget.simulation.name
item.setText(0, tab_name)
except:
# TODO Sample was not found in tree.
pass