-
Notifications
You must be signed in to change notification settings - Fork 7
/
recoil_atom_distribution.py
2552 lines (2205 loc) · 103 KB
/
recoil_atom_distribution.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
# coding=utf-8
"""
Created on 1.3.2018
Updated on 27.5.2019
Potku is a graphical user interface for analyzation and
visualization of measurement data collected from a ToF-ERD
telescope. For physics calculations Potku uses external
analyzation components.
Copyright (C) 2018 Severi Jääskeläinen, Samuel Kaiponen, Heta Rekilä and
Sinikka Siironen, 2020 Juhani Sundell
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 'LICENCE').
"""
__author__ = "Severi Jääskeläinen \n Samuel Kaiponen \n Heta Rekilä \n " \
"Sinikka Siironen \n Juhani Sundell"
__version__ = "2.0"
import matplotlib
import modules.general_functions as gf
import dialogs.dialog_functions as df
from widgets.matplotlib import mpl_utils
from pathlib import Path
from typing import Optional
from typing import Tuple
from typing import Dict
from typing import List
from dialogs.simulation.multiply_area import MultiplyAreaDialog
from dialogs.simulation.recoil_element_selection import \
RecoilElementSelectionDialog
from dialogs.simulation.recoil_info_dialog import RecoilInfoDialog
from matplotlib import offsetbox
from matplotlib.widgets import RectangleSelector
from matplotlib.widgets import SpanSelector
from modules.element import Element
from modules.point import Point
from modules.enums import SimulationType
from modules.recoil_element import RecoilElement
from modules.element_simulation import ElementSimulation
from modules.simulation import Simulation
from modules.target import Target
from modules.global_settings import GlobalSettings
from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5 import QtWidgets
from PyQt5.QtCore import QLocale
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtCore import pyqtSignal
from widgets.matplotlib.mpl_utils import VerticalLimits
from widgets.matplotlib.mpl_utils import AlternatingLimits
from widgets.matplotlib.base import MatplotlibWidget
from widgets.matplotlib.simulation.element import ElementWidget
from widgets.simulation.controls import SimulationControlsWidget
from widgets.simulation.percentage_widget import PercentageWidget
from widgets.simulation.point_coordinates import PointCoordinatesWidget
from widgets.simulation.recoil_element import RecoilElementWidget
from widgets.base_tab import BaseTab
from widgets.icon_manager import IconManager
class ElementManager:
"""A class that manipulates the elements of the simulation.
A Simulation can have 0...n ElementSimulations.
Each ElementSimulation has 0..n RecoilElements.
Each RecoilElement has 1 Element, 1 ElementWidget and 2...n Points.
"""
def __init__(self, parent_tab, parent, icon_manager, simulation: Simulation,
statusbar=None):
"""
Initializes element manager.
Args:
parent_tab: SimulationTabWidget object.
parent: RecoilAtomDistributionWidget object.
icon_manager: IconManager object.
simulation: Simulation object.
"""
self.parent_tab = parent_tab
self.parent = parent
self.icon_manager = icon_manager
self.simulation = simulation
self.statusbar = statusbar
self.element_simulations = self.simulation.element_simulations
def get_element_simulation_with_recoil_element(
self, recoil_element: RecoilElement) -> ElementSimulation:
"""Get element simulation with recoil element.
Args:
recoil_element: A RecoilElement object.
Return:
ElementSimulation.
"""
# TODO no usages, may remove
for element_simulation in self.element_simulations:
if element_simulation.get_main_recoil() == recoil_element:
return element_simulation
def get_element_simulation_with_radio_button(
self, radio_button) -> ElementSimulation:
"""
Get element simulation with radio button.
Args:
radio_button: A radio button widget.
Return:
ElementSimulation.
"""
for element_simulation in self.element_simulations:
for button in self.get_radio_buttons(element_simulation):
if button == radio_button:
return element_simulation
@staticmethod
def get_recoil_element_with_radio_button(
radio_button,
element_simulation: ElementSimulation) -> RecoilElement:
"""
Get recoil element with radio button from given element simulation.
Args:
radio_button: A radio button widget.
element_simulation: An ElementSimulation object.
Return:
RecoilElement.
"""
for recoil_element in element_simulation.recoil_elements:
if recoil_element.widgets[0].radio_button == radio_button:
return recoil_element
def add_new_element_simulation(
self, element: Element, color: str, spectra_changed=None,
recoil_name_changed=None, settings_updated=None,
**kwargs) -> ElementSimulation:
"""
Create a new ElementSimulation and RecoilElement with default points.
Args:
element: Element that tells the element to add.
color: QColor object for recoil color.
spectra_changed: pyqtSignal that is emitted when recoil element
distribution is changed, causing the spectra to change also.
recoil_name_changed: pyqtSignal that is emitted when recoil element
name changes
settings_updated: pyqtSignal that is emitted when settings are
changed
kwargs: keyword arguments passed down to SimulationControlsWidget
Return:
Created ElementSimulation
"""
# TODO check that element does not exist
# There is no y_2 if there is only one layer
y_2 = None
# Set first point
xs = [0.00]
first_layer = self.parent.target.layers[0]
if element in first_layer.elements:
ys = [element.amount]
else:
ys = [self.parent.get_minimum_concentration()]
# Make two points for each change between layers
layer_index = 0
for layer in self.parent.target.layers:
# Set x-coordinates for the both points
x_1 = layer.start_depth + layer.thickness
xs.append(x_1)
x_2 = x_1 + self.parent.x_res
xs.append(x_2)
# Set y-coordinate for the first point
for current_element in layer.elements:
if (current_element.symbol == element.symbol and
current_element.isotope == element.isotope):
y_1 = current_element.amount
break
else:
y_1 = self.parent.get_minimum_concentration()
ys.append(y_1)
# Set y-coordinate for the second point if not in the last layer
if layer_index + 1 < len(self.parent.target.layers):
next_layer = self.parent.target.layers[layer_index+1]
current_symbol = element.symbol
current_isotope = element.isotope
for next_element in next_layer.elements:
if (next_element.symbol == current_symbol and
next_element.isotope == current_isotope):
y_2 = next_element.amount
break
else:
y_2 = self.parent.get_minimum_concentration()
if y_2 is not None:
ys.append(y_2)
layer_index += 1
# Removes last point from the list
if y_2 is not None:
ys.pop()
xs.pop()
xys = list(zip(xs, ys))
points = []
for xy in xys:
points.append(Point(xy))
rec_type = self.simulation.request.default_element_simulation\
.simulation_type.get_recoil_type()
recoil_element = RecoilElement(
element, points, color, rec_type=rec_type)
element_simulation = self.simulation.add_element_simulation(
recoil_element)
element_widget = ElementWidget(
self.parent, element, self.parent_tab, element_simulation, color,
self.icon_manager, statusbar=self.statusbar,
spectra_changed=spectra_changed,
recoil_name_changed=recoil_name_changed,
settings_updated=settings_updated)
recoil_element.widgets.append(element_widget)
# Add simulation controls widget
simulation_controls_widget = SimulationControlsWidget(
element_simulation, self.parent,
recoil_name_changed=recoil_name_changed,
settings_updated=settings_updated, **kwargs)
self.parent_tab.contentsLayout.addWidget(simulation_controls_widget)
element_simulation.get_main_recoil().widgets.append(
simulation_controls_widget)
return element_simulation
def add_element_simulation(
self, element_simulation: ElementSimulation, spectra_changed=None,
recoil_name_changed=None, settings_updated=None, **kwargs):
"""
Add an existing ElementSimulation.
Args:
element_simulation: ElementSimulation to be added.
spectra_changed: pyqtSignal that is emitted when recoil element
distribution is changed, causing the spectra to change also.
recoil_name_changed: pyqtSignal that is emitted when recoil name
changes.
settings_updated: pyqtSignal that is emitted when simulation
settings are updated
kwargs: keyword arguments passed down to SimulationControl
"""
main_element_widget = ElementWidget(
self.parent, element_simulation.get_main_recoil().element,
self.parent_tab, element_simulation,
element_simulation.get_main_recoil().color, self.icon_manager,
statusbar=self.statusbar, spectra_changed=spectra_changed,
recoil_name_changed=recoil_name_changed,
settings_updated=settings_updated)
element_simulation.get_main_recoil().widgets.append(
main_element_widget)
# Add simulation controls widget
simulation_controls_widget = SimulationControlsWidget(
element_simulation, self.parent,
recoil_name_changed=recoil_name_changed,
settings_updated=settings_updated, **kwargs)
self.parent_tab.contentsLayout.addWidget(simulation_controls_widget)
element_simulation.get_main_recoil().widgets.append(
simulation_controls_widget)
# Add other recoil element widgets
for i in range(1, len(element_simulation.recoil_elements)):
self.add_secondary_recoil(
element_simulation.recoil_elements[i],
element_simulation, main_element_widget,
spectra_changed=spectra_changed,
recoil_name_changed=recoil_name_changed)
def add_secondary_recoil(self, recoil_element, element_simulation,
main_element_widget, spectra_changed=None,
recoil_name_changed=None):
"""Adds an existing secondary RecoilElement to the given
ElementSimulation object.
"""
recoil_element_widget = RecoilElementWidget(
self.parent, self.parent_tab, main_element_widget,
element_simulation, recoil_element.color, recoil_element,
statusbar=self.statusbar, spectra_changed=spectra_changed,
recoil_name_changed=recoil_name_changed
)
recoil_element.widgets.append(recoil_element_widget)
# Check if there are e.g. Default-1 named recoil elements. If so,
# increase element.running_int_recoil
recoil_name = recoil_element.name
if recoil_name.startswith("Default-"):
possible_int = recoil_name.split('-')[1]
try:
integer = int(possible_int)
main_element_widget.running_int_recoil = integer + 1
except ValueError:
pass
return recoil_element_widget
def update_element_simulation(self, element_simulation: ElementSimulation,
spectra_changed=None,
recoil_name_changed=None):
# TODO refactor and clean this up
main_element_widget = next(
(w for w in element_simulation.get_main_recoil().widgets
if isinstance(w, ElementWidget)), None)
rw = None
for recoil in element_simulation.recoil_elements:
# Check that the recoil does not already have a widget.
secondary = next((w for w in
recoil.widgets
if isinstance(w, RecoilElementWidget) or
isinstance(w, ElementWidget)), None)
if secondary is None:
rw = self.add_secondary_recoil(
recoil, element_simulation, main_element_widget,
spectra_changed=spectra_changed,
recoil_name_changed=recoil_name_changed)
self.parent.radios.addButton(rw.radio_button)
self.parent.other_recoils.append(recoil)
for i in range(self.parent.recoil_vertical_layout.count()):
if self.parent.recoil_vertical_layout.itemAt(i).widget() \
== main_element_widget:
self.parent.recoil_vertical_layout.insertWidget(
i + 1, rw)
break
if rw is not None:
rw.radio_button.setChecked(True)
def remove_element_simulation(self, element_simulation: ElementSimulation):
"""Remove element simulation.
Args:
element_simulation: An ElementSimulation object to be removed.
"""
element_simulation.get_main_recoil().delete_widgets()
self.element_simulations.remove(element_simulation)
# Delete all files that relate to element_simulation
element_simulation.delete_all_files()
@staticmethod
def get_radio_buttons(element_simulation: ElementSimulation):
"""
Get all radio buttons based on element simulation.
Args:
element_simulation: An ElementSimulation object.
Return:
List of buttons that have the same ElementSimulation reference.
"""
radio_buttons = []
for recoil_element in element_simulation.recoil_elements:
radio_buttons.append(recoil_element.widgets[0].radio_button)
return radio_buttons
def has_element(self, element: Element) -> bool:
"""Checks whether any ElementSimulation has an element that matches
the given argument.
"""
return next((True for elem_sim in self.element_simulations if
elem_sim.has_element(element)), False)
# setter and getter for full_edit_on property
def _full_edit_to_btn(instance, attr, value):
btn = getattr(instance, attr)
if value:
btn.setText("Full edit unlocked")
else:
btn.setText("Unlock full edit")
def _full_edit_from_btn(instance, attr):
btn = getattr(instance, attr)
return btn.text() == "Full edit unlocked"
class RecoilAtomDistributionWidget(MatplotlibWidget):
"""Matplotlib simulation recoil atom distribution widget.
Using this widget, the user can edit the recoil atom distribution
for the simulation.
"""
color_scheme = {
"Default color": "jet",
"Greyscale": "Greys",
"Greyscale (inverted)": "gray"
}
tool_modes = {
0: "",
1: "pan/zoom", # Matplotlib's drag
2: "zoom rect" # Matplotlib's zoom
}
# Signal that is emitted when recoil distribution changes
recoil_dist_changed = pyqtSignal(RecoilElement, ElementSimulation)
# Signal that is emitted when limit values are changed
limit_changed = pyqtSignal()
update_element_simulation = pyqtSignal(ElementSimulation)
recoil_name_changed = pyqtSignal(ElementSimulation, RecoilElement)
# TODO change this to minimum_concentration_changed
full_edit_changed = pyqtSignal()
@property
def full_edit_on(self) -> bool:
return _full_edit_from_btn(self, "edit_lock_push_button")
@full_edit_on.setter
def full_edit_on(self, value: bool):
_full_edit_to_btn(self, "edit_lock_push_button", value)
self.full_edit_changed.emit()
def __init__(self, parent: "TargetWidget", simulation: Simulation,
target: Target, tab: BaseTab, icon_manager: IconManager,
settings: GlobalSettings,
statusbar: Optional[QtWidgets.QStatusBar] = None, **kwargs):
"""Inits recoil atom distribution widget.
Args:
parent: a TargetWidget class object.
simulation: a Simulation object.
target: a Target object.
tab: a SimulationTabWidget
icon_manager: an IconManager class object.
"""
# TODO change the button text when full edit is on (or use radio btns)
super().__init__(parent)
self.parent = parent
self.canvas.manager.set_title("Recoil Atom Distribution")
self.axes.format_coord = mpl_utils.format_coord
self.__icon_manager = icon_manager
self.tab = tab
self.simulation = simulation
self._settings = settings
self.current_element_simulation: Optional[ElementSimulation] = None
self.current_recoil_element: Optional[RecoilElement] = None
self.element_manager = ElementManager(
self.tab, self, self.__icon_manager, self.simulation, statusbar)
self.target = target
self.layer_colors = [(0.9, 0.9, 0.9), (0.85, 0.85, 0.85)]
# Setting up the element scroll area
widget = QtWidgets.QWidget()
self.recoil_vertical_layout = QtWidgets.QVBoxLayout()
self.recoil_vertical_layout.setContentsMargins(0, 0, 0, 0)
widget.setLayout(self.recoil_vertical_layout)
scroll_vertical_layout = QtWidgets.QVBoxLayout()
self.parent.recoilScrollAreaContents.setLayout(scroll_vertical_layout)
scroll_vertical_layout.addWidget(widget)
scroll_vertical_layout.addItem(
QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum,
QtWidgets.QSizePolicy.Expanding))
self.parent.addPushButton.clicked.connect(
lambda: self.add_element_with_dialog(**kwargs))
self.parent.removePushButton.clicked.connect(
self.remove_current_element)
self.parent.removeallPushButton.clicked.connect(
self.remove_all_elements)
self.radios = QtWidgets.QButtonGroup(self)
self.radios.buttonToggled[QtWidgets.QAbstractButton, bool].connect(
self.choose_element)
self.parent.editPushButton.clicked.connect(
self.open_recoil_element_info)
self.edit_lock_push_button = self.parent.editLockPushButton
self.edit_lock_push_button.clicked.connect(self.unlock_or_lock_edit)
self.full_edit_on = True
# Locations of points about to be dragged at the time of click
self.click_locations = []
# Distances between points about to be dragged
self.x_dist_left = [] # x dist to leftmost point
self.x_dist_right = [] # x dist to rightmost point
self.y_dist_lowest = [] # y dist to lowest point
# Index of lowest point about to be dragged
self.lowest_dr_p_i = 0
# Minimum x distance between points
self.x_res = 0.01
# Minimum y coordinate for points
# self.y_min = 0.0001
# Markers representing points
self.markers = None
# Lines connecting markers
self.lines = None
# Markers representing selected points
self.markers_selected = None
# Points that are being dragged
self.dragged_points = []
# Points that have been selected
self.selected_points = []
# Clicked point
self.clicked_point: Optional[Point] = None
# If point has been clicked
self.point_clicked = False
# Event for right clicking, used for either showing context menu of
# rectangle select
self.__rectangle_event_click = None
# Event for releasing right click
self.__rectangle_event_release = None
# Interval that is common for all recoils
self.common_interval: Optional[VerticalLimits] = None
# Individual intervals for each recoil
self.individual_intervals: Dict[RecoilElement, AlternatingLimits] = {}
self.area_limits_for_all_on = False
# Are individual limits for recoils on or not
self.area_limits_individual_on = False
# Save current points to backlog
self.__save_points = True
# Used in checking whether graph was clicked or span select was used
self.__x_start = None
self.__x_end = None
self.annotations = []
self.trans = matplotlib.transforms.blended_transform_factory(
self.axes.transData, self.axes.transAxes)
# Span selection tool (used to select all points within a range
# on the x axis)
self.span_selector = SpanSelector(
self.axes, self.on_span_select, "horizontal", useblit=True,
rectprops=dict(alpha=0.5, facecolor="red"), button=1,
span_stays=True, onmove_callback=self.on_span_motion)
self.span_selector.set_active(False)
self.rectangle_selector = RectangleSelector(
self.axes, self.on_rectangle_select, useblit=True, drawtype="box",
rectprops=dict(alpha=0.5, facecolor="red"), button=3)
# Connections and setup
self.canvas.mpl_connect("button_press_event", self.on_click)
self.canvas.mpl_connect("button_release_event", self.on_release)
self.canvas.mpl_connect("motion_notify_event", self.on_motion)
self.locale = QLocale.c()
self.clipboard = QGuiApplication.clipboard()
self.ratio_str = self.clipboard.text()
self.clipboard.changed.connect(self.__update_multiply_action)
self.__button_individual_limits = None
self.coordinates_widget: Optional[PointCoordinatesWidget] = None
self.coordinates_action = None
self.point_remove_action = None
# This customizes the toolbar buttons
self.__fork_toolbar_buttons()
# Remember x limits to set when the user has returned from Target view.
self.original_x_limits = None
self.name_y_axis = "Relative Concentration"
self.name_x_axis = "Depth [nm]"
self.anchored_box = None
self.__show_all_recoil = True
# This holds all the recoils that aren't current ly selected
self.other_recoils = []
self.other_recoils_lines = []
self.target_thickness = 0
self.colormap = self._settings.get_element_colors()
self.parent.percentButton.clicked.connect(self.__create_percent_widget)
self.parent.percentButton.setEnabled(True)
self.on_draw()
if self.simulation.element_simulations:
self.__update_figure(**kwargs)
for button in self.radios.buttons():
button.setChecked(True)
break
self.update_element_simulation.connect(
lambda elem_sim: self.element_manager.update_element_simulation(
elem_sim, spectra_changed=self.recoil_dist_changed,
recoil_name_changed=self.recoil_name_changed))
def emit_distribution_change(self):
"""Emits recoil distribution changed signal if recoil element
and element simulation are selected.
"""
# FIXME comes here twice after spinbox is edited
if self.current_recoil_element is None:
return
if self.current_element_simulation is None:
return
self.recoil_dist_changed.emit(
self.current_recoil_element, self.current_element_simulation)
def get_current_main_recoil(self) -> Optional[RecoilElement]:
"""Returns the main recoil of currently selected ElementSimulation.
"""
if self.current_element_simulation is not None:
return self.current_element_simulation.get_main_recoil()
return None
def main_recoil_selected(self) -> bool:
"""Checks whether currently selected RecoilElement is also the main
recoil.
"""
if self.current_recoil_element is None:
return False
return self.current_recoil_element is self.get_current_main_recoil()
def editing_restricted(self) -> bool:
"""Checks whether editing the distribution is restricted (due to full
edit being off or main recoil not being selected).
"""
return not self.full_edit_on or not self.main_recoil_selected()
def first_point_selected(self) -> bool:
"""Checks whether currently selected point is first in the
distribution.
"""
return self.clicked_point is \
self.current_recoil_element.get_first_point()
def first_point_in_selection(self) -> bool:
"""Checks whether the first point of the distribution is in current
selection of points.
"""
return self.point_in_selection(
self.current_recoil_element.get_first_point())
def last_point_selected(self) -> bool:
"""Checks whether currently selected point is the last point in the
distribution.
"""
return self.clicked_point is \
self.current_recoil_element.get_last_point()
def last_point_in_selection(self) -> bool:
"""Checks whether the last point of the distribution is in current
selection of points.
"""
return self.point_in_selection(
self.current_recoil_element.get_last_point())
def point_in_selection(self, point: Point):
"""Checks whether the given point is in current selection of points.
"""
return point in self.selected_points
def zero_point_selected(self) -> bool:
"""Checks whether currently selected point is a zero point.
"""
return self.clicked_point.get_y() == 0.0
def zero_point_in_selection(self) -> bool:
"""Checks whether current selection contains a zero point.
"""
return 0.0 in (p.get_y() for p in self.selected_points)
def selected_between_zeros(self) -> bool:
"""Checks whether currently selected point is between two zero
points.
"""
return self.current_recoil_element.between_zeros(self.clicked_point)
def get_minimum_concentration(self) -> float:
"""Returns the minimum concentration that points can be dragged to.
"""
return self._settings.get_minimum_concentration()
def get_current_interval(self) -> Optional[VerticalLimits]:
return self.individual_intervals.get(
self.current_recoil_element, None)
def get_main_interval(self) -> Optional[VerticalLimits]:
return self.individual_intervals.get(
self.get_current_main_recoil(), None)
def update_current_interval(self, x: Optional[float] = None):
if x is not None and \
self.current_recoil_element in self.individual_intervals:
self.individual_intervals[
self.current_recoil_element].update_graph(x)
elif self.current_recoil_element not in self.individual_intervals:
self.individual_intervals[self.current_recoil_element] = \
AlternatingLimits(
self.canvas, self.axes,
xs=self.current_recoil_element.get_range(),
colors=("orange", "green"), flush=False
)
def set_individual_intervals_visible(self, b: bool):
for interval in self.individual_intervals.values():
interval.set_visible(b)
def highlight_selected_interval(self):
selected = self.get_current_interval()
if selected is not None:
selected.set_alpha(1.0)
for interval in self.individual_intervals.values():
if interval is not selected:
interval.set_alpha(0.2)
def get_individual_limits(self) -> Dict[RecoilElement, Tuple[float, float]]:
"""Returns individual area limits for each recoil element.
"""
return {
recoil: self.individual_intervals[recoil].get_range()
for recoil in self.simulation.get_recoil_elements()
if recoil in self.individual_intervals
}
def get_common_limits(self, rounding=None) \
-> Tuple[Optional[float], Optional[float]]:
"""Returns a common are limit for all recoil elements.
"""
if self.common_interval is None:
return None, None
xs = self.common_interval.get_range()
if rounding is not None:
return tuple(round(x, rounding) for x in xs)
return tuple(xs)
def get_all_limits(self) -> Dict:
"""Returns both common and individual area limits as a dictionary.
"""
return {
"common": self.get_common_limits(),
**self.get_individual_limits()
}
def __update_figure(self, **kwargs):
"""Update figure.
"""
for element_simulation in self.simulation.element_simulations:
self.add_element(
element_simulation.get_main_recoil().element,
element_simulation=element_simulation, **kwargs)
self.simulation.element_simulations[0].get_main_recoil(). \
widgets[0].radio_button.setChecked(True)
self.show_other_recoils()
def __create_percent_widget(self):
"""Create a widget that calculates and shows the percentages of recoils
on the same interval and their individual intervals.
"""
recoils = self.simulation.get_recoil_elements()
percentage_widget = PercentageWidget(
recoils, self.__icon_manager,
distribution_changed=self.recoil_dist_changed,
interval_changed=self.limit_changed,
get_limits=self.get_all_limits
)
self.tab.add_widget(percentage_widget)
def open_recoil_element_info(self):
"""Open recoil element info.
"""
dialog = RecoilInfoDialog(
self.current_recoil_element, self.colormap,
self.current_element_simulation)
if dialog.isOk:
new_values = dialog.get_properties()
try:
old_recoil_name = self.current_recoil_element.name
self.current_element_simulation.update_recoil_element(
self.current_recoil_element,
new_values)
# If name has changed
if old_recoil_name != self.current_recoil_element.name:
# Delete energy spectra that use recoil
df.delete_recoil_espe(
self.tab,
f"{self.current_recoil_element.prefix}-"
f"{old_recoil_name}")
self.recoil_name_changed.emit(
self.current_element_simulation,
self.current_recoil_element)
self.update_recoil_element_info_labels()
self.update_colors()
except KeyError:
error_box = QtWidgets.QMessageBox()
error_box.setIcon(QtWidgets.QMessageBox.Warning)
error_box.addButton(QtWidgets.QMessageBox.Ok)
error_box.setText(
"All recoil element information could not be saved.")
error_box.setWindowTitle("Error")
error_box.exec()
def save_mcsimu_rec_profile(self, directory: Path, progress=None):
"""Save information to .mcsimu and .profile files.
Args:
directory: Directory where to save to.
progress: ProgressReporter.
"""
length = len(self.element_manager.element_simulations)
for i, element_simulation in enumerate(
self.element_manager.element_simulations):
element_simulation.to_file(
Path(directory, f"{element_simulation.get_full_name()}.mcsimu")
)
for recoil_element in element_simulation.recoil_elements:
recoil_element.to_file(directory)
element_simulation.profile_to_file(
Path(directory,
f"{element_simulation.name_prefix}.profile"))
if progress is not None:
progress.report((i / length) * 100)
if progress is not None:
progress.report(100)
def unlock_or_lock_edit(self):
"""Unlock or lock full edit.
"""
if not self.full_edit_on:
# TODO use the function in dialog functions
# Check if current element simulation is running
add = None
if self.current_element_simulation.is_simulation_running() and not\
self.current_element_simulation.is_optimization_running():
add = "Are you sure you want to unlock full edit for this" \
" running element simulation?\nIt will be stopped and " \
"all its simulation results will be deleted.\n\nUnlock " \
"full edit anyway?"
elif self.current_element_simulation.is_simulation_finished() \
and not \
self.current_element_simulation.is_optimization_finished() \
and not \
self.current_element_simulation.is_optimization_running():
add = "Are you sure you want to unlock full edit for this " \
"element simulation?\nAll its simulation results will " \
"be deleted.\n\nUnlock full edit anyway?"
if add is not None:
reply = QtWidgets.QMessageBox.warning(
self.parent, "Confirm", add,
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.Cancel)
if reply == QtWidgets.QMessageBox.No or reply == \
QtWidgets.QMessageBox.Cancel:
return
self.current_element_simulation.unlock_edit()
self.current_element_simulation.reset()
self.full_edit_on = True
if self.last_point_selected():
self.point_remove_action.setEnabled(True)
self.coordinates_widget.set_x_enabled(True)
else:
self.current_element_simulation.lock_edit()
self.full_edit_on = False
self.update_plot()
def update_colors(self):
"""Update the view with current recoil element's color.
"""
self.current_recoil_element.widgets[0].circle.set_color(
self.current_recoil_element.color)
self.update_plot()
def choose_element(self, button: QtWidgets.QRadioButton, checked: bool):
"""Choose element from view.
Args:
button: Radio button.
checked: Whether button is checked or not.
"""
if not checked:
return
# Update limit and area parts
# self.set_individual_intervals_visible(False)
# if self.anchored_box is not None:
# self.anchored_box.set_visible(False)
# Do necessary changes in adding and deleting recoil elements pt 1
if self.current_recoil_element:
self.other_recoils.append(self.current_recoil_element)
current_element_simulation = self.element_manager \
.get_element_simulation_with_radio_button(button)
self.current_element_simulation = current_element_simulation
self.current_recoil_element = \
self.element_manager.get_recoil_element_with_radio_button(
button, self.current_element_simulation)
# pt 2
try:
self.other_recoils.remove(self.current_recoil_element)
except ValueError:
pass # Not in list
# Disable element simulation deletion button and full edit for
# other than main recoil element
if not self.main_recoil_selected():
self.parent.removePushButton.setEnabled(False)
self.edit_lock_push_button.setEnabled(False)
# Update zero values and intervals for main recoil element
self.get_current_main_recoil().update_zero_values()
# If zero values changed, update them to current recoil element
if self.get_current_main_recoil().zero_intervals_on_x != \
self.current_recoil_element.zero_intervals_on_x or \
self.get_current_main_recoil().zero_values_on_x != \
self.current_recoil_element.zero_values_on_x:
# If zeros changed, destroy backlog
self.current_recoil_element.delete_backlog()
self.update_current_recoils_zeros()
self.delete_and_add_possible_extra_points()
else:
self.parent.removePushButton.setEnabled(True)
self.edit_lock_push_button.setEnabled(True)
self.parent.elementInfoWidget.show()
# Put full edit on if element simulation allows it
self.full_edit_on = \
self.current_element_simulation.get_full_edit_on()
self.update_recoil_element_info_labels()
self.dragged_points.clear()
self.selected_points.clear()
self.point_remove_action.setEnabled(False)
self.highlight_selected_interval()
self.set_individual_intervals_visible(self.area_limits_individual_on)
# Update limit and area parts
if self.area_limits_individual_on:
self.__calculate_selected_area()
# Make all other recoils grey
self.show_other_recoils()
self.update_plot()
def show_other_recoils(self):
"""Show other recoils than current recoil in grey.
"""
for line in self.other_recoils_lines:
line.set_visible(False)
# TODO it would be better to update the old lines rather than keep
# adding new lines
self.other_recoils_lines = []
for element_simulation in self.simulation.element_simulations:
for recoil in element_simulation.recoil_elements:
if recoil in self.other_recoils:
xs = recoil.get_xs()
ys = recoil.get_ys()
rec_line = self.axes.plot(
xs, ys, color=recoil.color, alpha=0.3, visible=True,
zorder=1)
self.other_recoils_lines.append(rec_line[0])
self.fig.canvas.draw_idle()
def delete_and_add_possible_extra_points(self):
"""If current recoil element has too many or too little points at the