mlgidGUI 0.4.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. mlgidGUI/__init__.py +52 -0
  2. mlgidGUI/__main__.py +7 -0
  3. mlgidGUI/__version.py +1 -0
  4. mlgidGUI/app/__init__.py +8 -0
  5. mlgidGUI/app/actions_stack.py +1 -0
  6. mlgidGUI/app/app.py +67 -0
  7. mlgidGUI/app/cif_rois/__init__.py +0 -0
  8. mlgidGUI/app/cif_rois/cif_peaks_calculation.py +57 -0
  9. mlgidGUI/app/cif_rois/cif_simulation/__init__.py +0 -0
  10. mlgidGUI/app/cif_rois/cif_simulation/data/__init__.py +0 -0
  11. mlgidGUI/app/cif_rois/cif_simulation/data/atoms.py +15 -0
  12. mlgidGUI/app/cif_rois/cif_simulation/data/export_database.py +28 -0
  13. mlgidGUI/app/cif_rois/cif_simulation/experiment.py +57 -0
  14. mlgidGUI/app/cif_rois/cif_simulation/giwaxs_sim.py +286 -0
  15. mlgidGUI/app/cif_rois/cif_simulation/int_sim.py +105 -0
  16. mlgidGUI/app/cif_rois/cif_simulation/possible_directions.py +20 -0
  17. mlgidGUI/app/cif_rois/cif_simulation/q_sim.py +159 -0
  18. mlgidGUI/app/data_manager/__init__.py +4 -0
  19. mlgidGUI/app/data_manager/data_manager.py +164 -0
  20. mlgidGUI/app/data_manager/import_from_h5.py +68 -0
  21. mlgidGUI/app/data_manager/load_data.py +78 -0
  22. mlgidGUI/app/data_manager/pascal/__init__.py +2 -0
  23. mlgidGUI/app/data_manager/pascal/annotation_fabric.py +59 -0
  24. mlgidGUI/app/data_manager/pascal/draw_objects.py +119 -0
  25. mlgidGUI/app/data_manager/pascal/exceptions.py +6 -0
  26. mlgidGUI/app/data_manager/pascal/format_convertor.py +127 -0
  27. mlgidGUI/app/data_manager/pascal/pascal_annotation.py +85 -0
  28. mlgidGUI/app/data_manager/pascal/protocol_implementations.py +28 -0
  29. mlgidGUI/app/data_manager/pascal/protocols.py +47 -0
  30. mlgidGUI/app/data_manager/pascal/utils.py +64 -0
  31. mlgidGUI/app/data_manager/save_dataset.py +57 -0
  32. mlgidGUI/app/data_manager/save_h5.py +178 -0
  33. mlgidGUI/app/data_manager/saving_parameters.py +88 -0
  34. mlgidGUI/app/debug_tracker.py +129 -0
  35. mlgidGUI/app/edf_reader.py +135 -0
  36. mlgidGUI/app/file_manager/__init__.py +201 -0
  37. mlgidGUI/app/file_manager/config_manager.py +76 -0
  38. mlgidGUI/app/file_manager/keys.py +542 -0
  39. mlgidGUI/app/file_manager/npy_file_manager.py +17 -0
  40. mlgidGUI/app/file_manager/object_file_manager.py +77 -0
  41. mlgidGUI/app/file_manager/project_structure.py +169 -0
  42. mlgidGUI/app/file_manager/read_fits.py +76 -0
  43. mlgidGUI/app/file_manager/read_geometry.py +54 -0
  44. mlgidGUI/app/file_manager/read_images.py +31 -0
  45. mlgidGUI/app/file_manager/read_meta_roi.py +40 -0
  46. mlgidGUI/app/file_manager/read_polar_images.py +22 -0
  47. mlgidGUI/app/file_manager/read_radial_profile.py +6 -0
  48. mlgidGUI/app/file_manager/read_roi_data.py +39 -0
  49. mlgidGUI/app/fitting/__init__.py +5 -0
  50. mlgidGUI/app/fitting/background.py +92 -0
  51. mlgidGUI/app/fitting/fit.py +128 -0
  52. mlgidGUI/app/fitting/fit_holder.py +273 -0
  53. mlgidGUI/app/fitting/fit_object.py +247 -0
  54. mlgidGUI/app/fitting/functions.py +107 -0
  55. mlgidGUI/app/fitting/range_strategy.py +14 -0
  56. mlgidGUI/app/fitting/utils.py +17 -0
  57. mlgidGUI/app/geometry.py +236 -0
  58. mlgidGUI/app/geometry_holder.py +131 -0
  59. mlgidGUI/app/image_holder.py +200 -0
  60. mlgidGUI/app/image_processing.py +23 -0
  61. mlgidGUI/app/polar_image.py +96 -0
  62. mlgidGUI/app/profiles/__init__.py +5 -0
  63. mlgidGUI/app/profiles/angular_profile.py +20 -0
  64. mlgidGUI/app/profiles/basic_profile.py +169 -0
  65. mlgidGUI/app/profiles/radial_profile.py +38 -0
  66. mlgidGUI/app/read_image.py +21 -0
  67. mlgidGUI/app/rois/__init__.py +4 -0
  68. mlgidGUI/app/rois/new_roi_dict.py +670 -0
  69. mlgidGUI/app/rois/roi.py +194 -0
  70. mlgidGUI/app/rois/roi_colors.py +76 -0
  71. mlgidGUI/app/rois/roi_data.py +177 -0
  72. mlgidGUI/app/rois/roi_dict.py +466 -0
  73. mlgidGUI/app/rois/roi_meta_data.py +149 -0
  74. mlgidGUI/app/structures/__init__.py +6 -0
  75. mlgidGUI/app/structures/crystal_ring.py +19 -0
  76. mlgidGUI/app/structures/crystals_holders.py +144 -0
  77. mlgidGUI/app/structures/custom_crystal.py +45 -0
  78. mlgidGUI/app/structures/get_ring_list.py +89 -0
  79. mlgidGUI/app/transformations.py +82 -0
  80. mlgidGUI/app/update/__init__.py +3 -0
  81. mlgidGUI/app/update/check_version.py +51 -0
  82. mlgidGUI/app/update/launch_program.py +15 -0
  83. mlgidGUI/app/update/script_update.py +64 -0
  84. mlgidGUI/app/utils.py +124 -0
  85. mlgidGUI/gui/__init__.py +3 -0
  86. mlgidGUI/gui/background_tasks.py +41 -0
  87. mlgidGUI/gui/background_update.py +87 -0
  88. mlgidGUI/gui/basic_widgets/__init__.py +12 -0
  89. mlgidGUI/gui/basic_widgets/buttons.py +144 -0
  90. mlgidGUI/gui/basic_widgets/labels.py +51 -0
  91. mlgidGUI/gui/basic_widgets/mouse_events.py +119 -0
  92. mlgidGUI/gui/basic_widgets/path_line.py +162 -0
  93. mlgidGUI/gui/basic_widgets/plots_1d.py +365 -0
  94. mlgidGUI/gui/basic_widgets/plots_2d.py +224 -0
  95. mlgidGUI/gui/basic_widgets/popups.py +164 -0
  96. mlgidGUI/gui/basic_widgets/progress_bar.py +127 -0
  97. mlgidGUI/gui/basic_widgets/setup_widgets.py +138 -0
  98. mlgidGUI/gui/basic_widgets/sliders.py +616 -0
  99. mlgidGUI/gui/basic_widgets/spinner.py +65 -0
  100. mlgidGUI/gui/basic_widgets/toolbars.py +19 -0
  101. mlgidGUI/gui/debug_widgets.py +388 -0
  102. mlgidGUI/gui/dock_area.py +115 -0
  103. mlgidGUI/gui/exception_message.py +42 -0
  104. mlgidGUI/gui/fitting/__init__.py +2 -0
  105. mlgidGUI/gui/fitting/fit_widget.py +966 -0
  106. mlgidGUI/gui/fitting/inplace_fit.py +536 -0
  107. mlgidGUI/gui/fitting/selected_fit_widget.py +286 -0
  108. mlgidGUI/gui/gui_main.py +349 -0
  109. mlgidGUI/gui/image_viewer.py +323 -0
  110. mlgidGUI/gui/init_window.py +170 -0
  111. mlgidGUI/gui/load_window/__init__.py +2 -0
  112. mlgidGUI/gui/load_window/load_folder.py +61 -0
  113. mlgidGUI/gui/load_window/load_h5.py +73 -0
  114. mlgidGUI/gui/notifications.py +68 -0
  115. mlgidGUI/gui/polar_image_viewer.py +153 -0
  116. mlgidGUI/gui/profiles/__init__.py +1 -0
  117. mlgidGUI/gui/profiles/angular_profile_widget.py +62 -0
  118. mlgidGUI/gui/profiles/radial_profile_widget.py +164 -0
  119. mlgidGUI/gui/project_manager/__init__.py +17 -0
  120. mlgidGUI/gui/project_manager/cif_files_widget.py +196 -0
  121. mlgidGUI/gui/project_manager/cif_results.py +146 -0
  122. mlgidGUI/gui/project_manager/metadata_widget.py +15 -0
  123. mlgidGUI/gui/project_manager/project_viewer.py +151 -0
  124. mlgidGUI/gui/project_manager/roi_widget.py +171 -0
  125. mlgidGUI/gui/roi_widgets/__init__.py +6 -0
  126. mlgidGUI/gui/roi_widgets/abstract_roi_holder.py +189 -0
  127. mlgidGUI/gui/roi_widgets/abstract_roi_widget.py +111 -0
  128. mlgidGUI/gui/roi_widgets/cif_file_widget.py +16 -0
  129. mlgidGUI/gui/roi_widgets/cif_peak_widget.py +43 -0
  130. mlgidGUI/gui/roi_widgets/confidence_level_widget.py +105 -0
  131. mlgidGUI/gui/roi_widgets/roi_1d_widget.py +136 -0
  132. mlgidGUI/gui/roi_widgets/roi_2d_rect_widget.py +98 -0
  133. mlgidGUI/gui/roi_widgets/roi_2d_ring_widget.py +203 -0
  134. mlgidGUI/gui/roi_widgets/rois_context_menu.py +150 -0
  135. mlgidGUI/gui/roi_widgets/select_roi_color_widget.py +58 -0
  136. mlgidGUI/gui/save_window/__init__.py +152 -0
  137. mlgidGUI/gui/save_window/format_box.py +33 -0
  138. mlgidGUI/gui/save_window/num_selected_widget.py +45 -0
  139. mlgidGUI/gui/save_window/options_widgets.py +105 -0
  140. mlgidGUI/gui/save_window/save_mode_box.py +30 -0
  141. mlgidGUI/gui/save_window/select_images.py +198 -0
  142. mlgidGUI/gui/tools.py +179 -0
  143. mlgidGUI/static/__init__.py +0 -0
  144. mlgidGUI/static/icons/__init__.py +0 -0
  145. mlgidGUI/static/icons/add.png +0 -0
  146. mlgidGUI/static/icons/add_yellow.png +0 -0
  147. mlgidGUI/static/icons/angular_profile.png +0 -0
  148. mlgidGUI/static/icons/arrow.png +0 -0
  149. mlgidGUI/static/icons/baseline.png +0 -0
  150. mlgidGUI/static/icons/center.png +0 -0
  151. mlgidGUI/static/icons/confirm.png +0 -0
  152. mlgidGUI/static/icons/control_widget.png +0 -0
  153. mlgidGUI/static/icons/data.png +0 -0
  154. mlgidGUI/static/icons/delete.png +0 -0
  155. mlgidGUI/static/icons/delete_yellow.png +0 -0
  156. mlgidGUI/static/icons/error.png +0 -0
  157. mlgidGUI/static/icons/find.png +0 -0
  158. mlgidGUI/static/icons/fit.png +0 -0
  159. mlgidGUI/static/icons/fix_all.png +0 -0
  160. mlgidGUI/static/icons/flip_horizontal.png +0 -0
  161. mlgidGUI/static/icons/flip_vertical.png +0 -0
  162. mlgidGUI/static/icons/folder.png +0 -0
  163. mlgidGUI/static/icons/fromfullscreen.png +0 -0
  164. mlgidGUI/static/icons/h5_folder.png +0 -0
  165. mlgidGUI/static/icons/h5_group_folder.png +0 -0
  166. mlgidGUI/static/icons/info.png +0 -0
  167. mlgidGUI/static/icons/interpolate.png +0 -0
  168. mlgidGUI/static/icons/item.png +0 -0
  169. mlgidGUI/static/icons/properties.png +0 -0
  170. mlgidGUI/static/icons/radial_profile.png +0 -0
  171. mlgidGUI/static/icons/roi_item.png +0 -0
  172. mlgidGUI/static/icons/rotate.png +0 -0
  173. mlgidGUI/static/icons/rotate_image.png +0 -0
  174. mlgidGUI/static/icons/rotate_right.png +0 -0
  175. mlgidGUI/static/icons/setup.png +0 -0
  176. mlgidGUI/static/icons/setup_white.png +0 -0
  177. mlgidGUI/static/icons/tofullscreen.png +0 -0
  178. mlgidGUI/static/icons/unfix_all.png +0 -0
  179. mlgidGUI/static/icons/update.png +0 -0
  180. mlgidGUI/static/icons/update_suggested.png +0 -0
  181. mlgidGUI/static/icons/window_icon.png +0 -0
  182. mlgidGUI/static/icons/window_icon_256.png +0 -0
  183. mlgidGUI/utils/__init__.py +1 -0
  184. mlgidGUI/utils/project2h5.py +11 -0
  185. mlgidgui-0.4.1.dist-info/METADATA +119 -0
  186. mlgidgui-0.4.1.dist-info/RECORD +202 -0
  187. mlgidgui-0.4.1.dist-info/WHEEL +5 -0
  188. mlgidgui-0.4.1.dist-info/entry_points.txt +5 -0
  189. mlgidgui-0.4.1.dist-info/licenses/LICENSE +674 -0
  190. mlgidgui-0.4.1.dist-info/top_level.txt +4 -0
  191. tests/__init__.py +0 -0
  192. tests/conftest.py +1 -0
  193. tests/fixures/__init__.py +2 -0
  194. tests/fixures/projects.py +102 -0
  195. tests/func/__init__.py +1 -0
  196. tests/func/test_loading_state.py +21 -0
  197. tests/func/test_parse_project_data.py +23 -0
  198. tests/func/test_save.py +62 -0
  199. tests/unit/__init__.py +0 -0
  200. tests/unit/rois/__init__.py +0 -0
  201. tests/unit/rois/test_basic_operations.py +18 -0
  202. tests/unit/test_add_data.py +33 -0
@@ -0,0 +1,144 @@
1
+ # -*- coding: utf-8 -*-
2
+ from pathlib import Path
3
+ from typing import List
4
+
5
+ from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, QThreadPool
6
+
7
+ from .custom_crystal import CustomCrystal, CrystalRing
8
+ from ..utils import CorruptedFileError
9
+
10
+
11
+ class CrystalsHolder(QObject):
12
+ sigCrystalAdded = pyqtSignal(CustomCrystal)
13
+ sigCrystalRemoved = pyqtSignal(CustomCrystal)
14
+ sigErrorCrystalAlreadyExists = pyqtSignal(CustomCrystal)
15
+ sigCrystalSelected = pyqtSignal(CustomCrystal)
16
+ sigRingSelected = pyqtSignal(CrystalRing)
17
+
18
+ def __init__(self, parent=None):
19
+ super().__init__(parent)
20
+ self._crystals: dict = {}
21
+ self._q_max: float = 1
22
+
23
+ @property
24
+ def q_max(self):
25
+ return self._q_max
26
+
27
+ def __getitem__(self, item):
28
+ return self._crystals[item]
29
+
30
+ def __iter__(self):
31
+ yield from self._crystals.values()
32
+
33
+ @pyqtSlot(CustomCrystal, name='crystalSelected')
34
+ def crystal_selected(self, crystal: CustomCrystal):
35
+ self.sigCrystalSelected.emit(crystal)
36
+
37
+ @pyqtSlot(CrystalRing, name='ringSelected')
38
+ def ring_selected(self, crystal: CustomCrystal):
39
+ self.sigRingSelected.emit(crystal)
40
+
41
+ @pyqtSlot(CustomCrystal, name='addCrystal')
42
+ def add_crystal(self, crystal: CustomCrystal):
43
+ if crystal.key not in self._crystals:
44
+ crystal.set_q_max(self._q_max)
45
+ self._crystals[crystal.key] = crystal
46
+ self.sigCrystalAdded.emit(crystal)
47
+ else:
48
+ self.sigErrorCrystalAlreadyExists.emit(crystal)
49
+
50
+ @pyqtSlot(CustomCrystal, name='removeCrystal')
51
+ def remove_crystal(self, crystal: CustomCrystal):
52
+ try:
53
+ self.sigCrystalRemoved.emit(self._crystals.pop(crystal.key))
54
+ except KeyError as err:
55
+ raise KeyError(f'Crystal {crystal.key} not found') from err
56
+
57
+ @pyqtSlot(Path, name='addCrystalFromCif')
58
+ def add_crystal_from_cif(self, cif_path: Path):
59
+ try:
60
+ crystal = CustomCrystal.from_cif(str(cif_path.resolve()))
61
+ except:
62
+ raise CorruptedFileError(f'Cif file {str(cif_path.resolve())}'
63
+ f' seems to be corrupted or structured in a wrong way. ')
64
+ self.add_crystal(crystal)
65
+
66
+ @property
67
+ def crystals(self) -> List[CustomCrystal]:
68
+ return list(self._crystals.values())
69
+
70
+ @pyqtSlot(float, name='setQMax')
71
+ def set_q_max(self, q_max: float):
72
+ if q_max != self._q_max:
73
+ self._q_max = q_max
74
+ for crystal in self._crystals.values():
75
+ crystal.set_q_max(q_max)
76
+
77
+
78
+ class SelectedCrystalsHolder(CrystalsHolder):
79
+ sigQMaxChanged = pyqtSignal()
80
+ sigCrystalChecked = pyqtSignal(CustomCrystal)
81
+ sigCrystalUnchecked = pyqtSignal(CustomCrystal)
82
+
83
+ def __init__(self, parent):
84
+ super().__init__(parent)
85
+ self._checked_crystals = {}
86
+ self._q_thread_pool = QThreadPool(self)
87
+ self.sigCrystalAdded.connect(self.crystal_checked)
88
+ self.sigCrystalRemoved.connect(self.crystal_unchecked)
89
+
90
+ def crystal_is_checked(self, crystal: CustomCrystal):
91
+ return crystal.key in self._checked_crystals
92
+
93
+ @pyqtSlot(CustomCrystal, name='crystalChecked')
94
+ def crystal_checked(self, crystal: CustomCrystal):
95
+ if crystal.key not in self._checked_crystals:
96
+ self._checked_crystals[crystal.key] = crystal
97
+ self.sigCrystalChecked.emit(crystal)
98
+
99
+ @pyqtSlot(CustomCrystal, name='crystalUnchecked')
100
+ def crystal_unchecked(self, crystal: CustomCrystal):
101
+ try:
102
+ del self._checked_crystals[crystal.key]
103
+ self.sigCrystalUnchecked.emit(crystal)
104
+ except KeyError:
105
+ pass
106
+
107
+ @property
108
+ def is_updated(self):
109
+ return all(map(lambda c: c.is_updated, self.crystals))
110
+
111
+ def update_rings(self, *args, **kwargs):
112
+ for crystal in self.crystals:
113
+ crystal.update_rings(*args, **kwargs)
114
+
115
+ @property
116
+ def checked_crystals(self) -> List[CustomCrystal]:
117
+ return list(self._checked_crystals.values())
118
+
119
+ @pyqtSlot(float, name='setQMax')
120
+ def set_q_max(self, q_max: float):
121
+ if q_max != self._q_max:
122
+ self._q_max = q_max
123
+ if self._crystals:
124
+ for crystal in self._crystals.values():
125
+ crystal.set_q_max(q_max)
126
+ self.sigQMaxChanged.emit()
127
+
128
+
129
+ class CrystalsDatabase(CrystalsHolder):
130
+
131
+ def __init__(self, parent=None):
132
+ super(CrystalsDatabase, self).__init__(parent)
133
+ self.selected_holder = SelectedCrystalsHolder(self)
134
+
135
+ @pyqtSlot(object, name='addToSelected')
136
+ def add_to_selected(self, key: CustomCrystal or str):
137
+ if isinstance(key, CustomCrystal):
138
+ key = key.key
139
+ self.selected_holder.add_crystal(self[key])
140
+
141
+ @pyqtSlot(float, name='setQMax')
142
+ def set_q_max(self, q_max: float):
143
+ super().set_q_max(q_max)
144
+ self.selected_holder.set_q_max(q_max)
@@ -0,0 +1,45 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from typing import List
4
+ from crystals import Crystal
5
+
6
+ from .crystal_ring import CrystalRing
7
+ from .get_ring_list import get_crystal_rings, get_sorted_rings, RingDict
8
+
9
+
10
+ class CustomCrystal(Crystal):
11
+ def __init__(self, unitcell, lattice_vectors, source=None, **kwargs):
12
+ super().__init__(unitcell, lattice_vectors, source=source, **kwargs)
13
+ self._key = f'{self.chemical_formula}{self.source}'
14
+ self._ring_dict: RingDict = {}
15
+ self._is_updated: bool = False
16
+ self._q_max: float = 5
17
+
18
+ @classmethod
19
+ def from_crystal(cls, crystal: Crystal):
20
+ return cls(crystal.unitcell, crystal.lattice_vectors, crystal.source)
21
+
22
+ @property
23
+ def is_updated(self) -> bool:
24
+ return self._is_updated
25
+
26
+ def update_rings(self, *args, **kwargs) -> None:
27
+ if not self._is_updated:
28
+ self._update_rings(*args, **kwargs)
29
+ self._is_updated = True
30
+
31
+ @property
32
+ def rings(self) -> List[CrystalRing]:
33
+ return get_sorted_rings(self._ring_dict, self._q_max)
34
+
35
+ @property
36
+ def key(self) -> str:
37
+ return self._key
38
+
39
+ def set_q_max(self, q_max) -> None:
40
+ if q_max > self._q_max:
41
+ self._is_updated = False
42
+ self._q_max = q_max
43
+
44
+ def _update_rings(self, *args, **kwargs) -> None:
45
+ self._ring_dict = get_crystal_rings(self, self._q_max, ring_dict=self._ring_dict, *args, **kwargs)
@@ -0,0 +1,89 @@
1
+ # -*- coding: utf-8 -*-
2
+ import logging
3
+ from itertools import product
4
+ from typing import Dict, Tuple, Union, List, Callable
5
+ import cmath
6
+ import numpy as np
7
+
8
+ from crystals import Crystal
9
+ from periodictable import cromermann as cr_ff
10
+
11
+ from .crystal_ring import CrystalRing
12
+
13
+ MillerIndices = Tuple[int, int, int]
14
+ RingDict = Dict[MillerIndices, Union[CrystalRing, None]]
15
+ RingCalculationCallback = Callable[[int], bool]
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ def get_sorted_rings(ring_dict: RingDict, q_max: float) -> List[CrystalRing]:
21
+ return sorted(list(filter(lambda ring: ring and ring.radius <= q_max, ring_dict.values())),
22
+ key=lambda ring: ring.radius)
23
+
24
+
25
+ def get_crystal_rings(crystal: Crystal,
26
+ q_max: float,
27
+ min_sf: float = 0.01,
28
+ max_num: int = 10,
29
+ ring_dict: RingDict = None,
30
+ process_callback: RingCalculationCallback = None,
31
+ set_max_callback: RingCalculationCallback = None,
32
+ ) -> RingDict:
33
+ miller_indices: MillerIndices
34
+ min_num: int
35
+ process_callback = process_callback or _empty_callback()
36
+ set_max_callback = set_max_callback or _empty_callback()
37
+
38
+ if ring_dict:
39
+ min_num = max(map(max, ring_dict.keys()))
40
+ else:
41
+ min_num = 0
42
+ ring_dict: RingDict = {}
43
+
44
+ for h in range(min_num, max_num):
45
+ miller_indices = (h, 0, 0)
46
+ ring = _get_ring(crystal, miller_indices, min_sf)
47
+ logger.debug(f'Calc miller indices {miller_indices}')
48
+ if ring and ring.radius > q_max:
49
+ max_num = h
50
+ break
51
+
52
+ ring_dict[miller_indices] = ring
53
+
54
+ set_max_callback(max_num ** 3)
55
+
56
+ for i, miller_indices in enumerate(product(list(range(min_num, max_num)), repeat=3)):
57
+ logger.debug(f'Calc miller indices {miller_indices}')
58
+ if miller_indices not in ring_dict:
59
+ ring_dict[miller_indices] = _get_ring(crystal, miller_indices, min_sf)
60
+ process_callback(i)
61
+
62
+ return ring_dict
63
+
64
+
65
+ def _empty_callback() -> RingCalculationCallback:
66
+ def func(idx: int):
67
+ return True
68
+
69
+ return func
70
+
71
+
72
+ def _get_ring(crystal: Crystal, miller_indices: MillerIndices, min_sf: float) -> Union[CrystalRing, None]:
73
+ scattering_vector = crystal.scattering_vector(miller_indices)
74
+ q = np.linalg.norm(scattering_vector)
75
+ sf = _calc_structure_factor(q, miller_indices, crystal) * _structure_factor_coef(miller_indices)
76
+ if sf >= min_sf:
77
+ return CrystalRing(radius=q, miller_indices=miller_indices, intensity=sf, crystal=crystal)
78
+
79
+
80
+ def _structure_factor_coef(miller_indices: MillerIndices) -> int:
81
+ return 2 ** sum(map(bool, miller_indices))
82
+
83
+
84
+ def _calc_structure_factor(q: float, miller_indices: MillerIndices, crystal: Crystal) -> float:
85
+ sf = 0
86
+ for atom in crystal:
87
+ ff = cr_ff.fxrayatq(atom.element, q, charge=None)
88
+ sf = sf + ff * cmath.exp(2 * np.pi * 1j * np.dot(miller_indices, atom.coords_fractional))
89
+ return abs(sf)
@@ -0,0 +1,82 @@
1
+ from enum import Enum
2
+
3
+ import numpy as np
4
+
5
+ __all__ = ['TransformationsHolder', 'Transformation', 'UnknownTransformation']
6
+
7
+
8
+ class UnknownTransformation(ValueError):
9
+ pass
10
+
11
+
12
+ class Flip(object):
13
+ __slots__ = ('axis',)
14
+
15
+ def __init__(self, axis: int):
16
+ self.axis = axis
17
+
18
+ def __call__(self, img: np.ndarray):
19
+ return np.flip(img, self.axis)
20
+
21
+
22
+ class Rotate(object):
23
+ __slots__ = ('k',)
24
+
25
+ def __init__(self, k: int):
26
+ self.k = k
27
+
28
+ def __call__(self, img: np.ndarray):
29
+ return np.rot90(img, self.k)
30
+
31
+
32
+ class Transformation(Enum):
33
+ horizontal_flip = Flip(1)
34
+ vertical_flip = Flip(0)
35
+ rotate_right = Rotate(-1)
36
+ rotate_left = Rotate(1)
37
+
38
+
39
+ _T_DICT = {
40
+ '1234': (),
41
+ '1324': (Flip(1), Rotate(1)),
42
+ '2413': (Rotate(1),),
43
+ '2143': (Flip(1),),
44
+ '3142': (Rotate(-1),),
45
+ '3412': (Flip(0),),
46
+ '4321': (Flip(0), Flip(1)),
47
+ '4231': (Rotate(1), Flip(1))
48
+ }
49
+
50
+
51
+ class TransformationsHolder(object):
52
+ def __init__(self, key: str = None):
53
+ self._img = np.array([[1, 2], [3, 4]])
54
+ if key:
55
+ self.update(key)
56
+
57
+ def __call__(self, image):
58
+ for op in self._operations:
59
+ image = op(image)
60
+ return image
61
+
62
+ def add(self, op: Transformation):
63
+ self._img = op.value(self._img)
64
+
65
+ def clear(self):
66
+ self._img = np.array([[1, 2], [3, 4]])
67
+
68
+ @property
69
+ def _operations(self) -> tuple:
70
+ return _T_DICT[self.key]
71
+
72
+ @property
73
+ def key(self):
74
+ return ''.join(map(str, self._img.ravel()))
75
+
76
+ def update(self, key: str):
77
+ self._img = np.array([[1, 2], [3, 4]])
78
+ try:
79
+ for op in _T_DICT[key]:
80
+ self._img = op(self._img)
81
+ except KeyError:
82
+ raise UnknownTransformation(f'Key {key} doesn\'t correspond to any known transformation.')
@@ -0,0 +1,3 @@
1
+ from .check_version import check_outdated, CheckVersionMessage
2
+ from .script_update import giwaxs_gui_update, update_package
3
+ from .launch_program import launch_detached
@@ -0,0 +1,51 @@
1
+ import json
2
+ from enum import Enum, auto
3
+ import logging
4
+ import requests
5
+ from packaging.version import parse as parse_version
6
+
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ class CheckVersionMessage(Enum):
12
+ new_version_available = auto()
13
+ latest_version_installed = auto()
14
+ no_internet = auto()
15
+ error = auto()
16
+ not_checked = auto()
17
+ updated = auto()
18
+ failed_updating = auto()
19
+
20
+
21
+ def check_outdated(version: str, package: str = 'mlgidGUI') -> CheckVersionMessage:
22
+ logger.info(f'Checking the latest version of the {package} package.')
23
+
24
+ url = f'https://pypi.python.org/pypi/{package}/json'
25
+
26
+ try:
27
+ response = requests.get(url).text
28
+ except requests.ConnectionError:
29
+ logger.info(f'No internet.')
30
+ return CheckVersionMessage.no_internet
31
+
32
+ try:
33
+ current_version = parse_version(version)
34
+ latest_version = json.loads(response)['info']['version']
35
+ latest_version = parse_version(latest_version)
36
+
37
+ if current_version < latest_version:
38
+ message = CheckVersionMessage.new_version_available
39
+ message.version = latest_version
40
+ logger.info(f'Current version: {current_version}')
41
+ logger.info(f'New version available : {latest_version}.')
42
+ return message
43
+ else:
44
+ message = CheckVersionMessage.latest_version_installed
45
+ message.version = latest_version
46
+ logger.info(f'latest_version_installed : {message.version}.')
47
+ return message
48
+
49
+ except Exception as err:
50
+ logger.exception(err)
51
+ return CheckVersionMessage.error
@@ -0,0 +1,15 @@
1
+ # -*- coding: utf-8 -*-
2
+ import platform
3
+ import subprocess
4
+ import os
5
+
6
+
7
+ def launch_detached():
8
+ try:
9
+ if platform.system() == 'Windows':
10
+ subprocess.Popen('mlgidGUI', creationflags=subprocess.DETACHED_PROCESS)
11
+ else:
12
+ subprocess.Popen(['nohup', 'mlgidGUI'], shell=False, stdout=None, stderr=None, preexec_fn=os.setpgrp)
13
+
14
+ except subprocess.CalledProcessError:
15
+ return -1
@@ -0,0 +1,64 @@
1
+ import subprocess
2
+ import sys
3
+ import logging
4
+ import argparse
5
+ import platform
6
+ import os
7
+
8
+
9
+ def update_package(version: str = '', num_of_attempts: int = 2) -> bool:
10
+ logger = logging.getLogger(__name__)
11
+ logger.info(f'Updating the package to {version}...')
12
+
13
+ try:
14
+ if platform.system() == 'Windows':
15
+ subprocess.check_call(['giwaxs_gui_update', f'--version={version}',
16
+ f'--num_of_attempts={num_of_attempts}'],
17
+ creationflags=subprocess.CREATE_NO_WINDOW)
18
+ else:
19
+ subprocess.check_call(['nohup', 'giwaxs_gui_update', f'--version={version}',
20
+ f'--num_of_attempts={num_of_attempts}'],
21
+ shell=False, stdout=None, stderr=None, preexec_fn=os.setpgrp)
22
+ return True
23
+
24
+ except (subprocess.CalledProcessError, FileNotFoundError) as err:
25
+ logger.exception(err)
26
+ return False
27
+
28
+
29
+ def giwaxs_gui_update() -> int:
30
+ parser = argparse.ArgumentParser(description='Update mlgidGUI package.')
31
+
32
+ parser.add_argument('--version', type=str, default='', help='the target version')
33
+ parser.add_argument('--num_of_attempts', type=int, default=2, help='number of attempts to update')
34
+ parser.add_argument('--package', type=str, default='mlgidGUI', help='the target package')
35
+
36
+ args = parser.parse_args()
37
+ num_of_attempts: int = args.num_of_attempts
38
+ package: str = args.package
39
+ version: str = args.version
40
+
41
+ if version:
42
+ package = f'{package}=={version}'
43
+
44
+ for i in range(num_of_attempts):
45
+ try:
46
+ subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--user', '--upgrade', package])
47
+ return 0
48
+
49
+ except subprocess.CalledProcessError:
50
+ continue
51
+
52
+ for i in range(num_of_attempts):
53
+ try:
54
+ subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', package])
55
+ return 0
56
+
57
+ except subprocess.CalledProcessError:
58
+ continue
59
+
60
+ return 1
61
+
62
+
63
+ if __name__ == '__main__':
64
+ giwaxs_gui_update()
mlgidGUI/app/utils.py ADDED
@@ -0,0 +1,124 @@
1
+ import logging
2
+ import sys
3
+ import traceback
4
+
5
+ from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal, QRunnable
6
+
7
+ from scipy import sparse
8
+ from scipy.sparse.linalg import spsolve
9
+ from scipy.ndimage import gaussian_filter1d
10
+
11
+ import numpy as np
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class SingletonMeta(type):
17
+ _instance = None
18
+
19
+ def __call__(cls, *args, **kwargs):
20
+ if cls._instance is None:
21
+ cls._instance = super().__call__(*args, **kwargs)
22
+ return cls._instance
23
+
24
+ def clear(cls):
25
+ cls._instance = None
26
+
27
+ class InternalError(Exception):
28
+ pass
29
+
30
+
31
+ class CorruptedFileError(Exception):
32
+ pass
33
+
34
+
35
+ def baseline_correction(y: np.ndarray,
36
+ smoothness_param: float,
37
+ asymmetry_param: float,
38
+ max_niter: int = 1000) -> np.ndarray:
39
+ z = np.zeros_like(y)
40
+ if smoothness_param <= 0 or asymmetry_param <= 0:
41
+ return z
42
+ y_size = y.size
43
+ laplacian = sparse.diags([1, -2, 1], [0, -1, -2], shape=(y_size, y_size - 2))
44
+ laplacian_matrix = laplacian.dot(laplacian.transpose())
45
+
46
+ w = np.ones(y_size)
47
+ for i in range(max_niter):
48
+ W = sparse.spdiags(w, 0, y_size, y_size)
49
+ Z = W + smoothness_param * laplacian_matrix
50
+ z = spsolve(Z, w * y)
51
+ w_new = asymmetry_param * (y > z) + (1 - asymmetry_param) * (y < z)
52
+ if np.allclose(w, w_new):
53
+ break
54
+ w = w_new
55
+ else:
56
+ logger.info(f'Solution has not converged, max number of iterations reached.')
57
+ return np.nan_to_num(z)
58
+
59
+
60
+ def smooth_curve(y: np.ndarray, sigma: float) -> np.ndarray or None:
61
+ if y is not None:
62
+ if sigma > 0:
63
+ return gaussian_filter1d(y, sigma)
64
+ else:
65
+ return y
66
+
67
+
68
+ class WorkerSignals(QObject):
69
+ finished = pyqtSignal()
70
+ error = pyqtSignal(tuple)
71
+ result = pyqtSignal(object)
72
+
73
+
74
+ class Worker(QRunnable):
75
+ log = logging.getLogger(__name__)
76
+
77
+ def __init__(self, fn, *args, signals: WorkerSignals = None, **kwargs):
78
+ super(Worker, self).__init__()
79
+
80
+ self.fn = fn
81
+ self.args = args
82
+ self.kwargs = kwargs
83
+ self.signals = signals or WorkerSignals()
84
+
85
+ def call_func(self):
86
+ return self.fn(*self.args, **self.kwargs)
87
+
88
+ @pyqtSlot()
89
+ def run(self):
90
+
91
+ try:
92
+ result = self.call_func()
93
+ except Exception as err:
94
+ self.log.exception(err)
95
+ traceback.print_exc()
96
+ exctype, value = sys.exc_info()[:2]
97
+ try:
98
+ self.signals.error.emit((exctype, value, traceback.format_exc()))
99
+ except RuntimeError:
100
+ return
101
+ else:
102
+ try:
103
+ self.signals.result.emit(result)
104
+ except RuntimeError:
105
+ return
106
+ finally:
107
+ try:
108
+ self.signals.finished.emit()
109
+ except RuntimeError:
110
+ return
111
+
112
+
113
+ class UpdateWorkerSignals(WorkerSignals):
114
+ sigSetMax = pyqtSignal(int)
115
+ sigSetProgress = pyqtSignal(int)
116
+
117
+
118
+ class UpdateWorker(Worker):
119
+ def __init__(self, fn, *args, **kwargs):
120
+ super().__init__(fn, *args, signals=UpdateWorkerSignals(), **kwargs)
121
+
122
+ def call_func(self):
123
+ return self.fn(*self.args, process_callback=self.signals.sigSetProgress.emit,
124
+ set_max_callback=self.signals.sigSetMax.emit, **self.kwargs)
@@ -0,0 +1,3 @@
1
+ from .gui_main import GIWAXSMainWindow, GIWAXSMainController
2
+ from .exception_message import UncaughtHook
3
+ from .debug_widgets import DebugWindow
@@ -0,0 +1,41 @@
1
+ # -*- coding: utf-8 -*-
2
+ from typing import Hashable, Callable
3
+
4
+ from PyQt5.QtCore import QThreadPool, QObject, pyqtSlot, pyqtSignal
5
+
6
+ from ..app.utils import Worker, SingletonMeta
7
+
8
+
9
+ class _BackgroundTasksNotifications(QObject):
10
+ sigAddNotification = pyqtSignal(object, object)
11
+ sigRemoveNotification = pyqtSignal(object)
12
+ sigAddProgressBar = pyqtSignal(object)
13
+
14
+ def __init__(self, parent=None):
15
+ super().__init__(parent)
16
+ self._q_thread_pool = QThreadPool(self)
17
+
18
+ @pyqtSlot(str, name='removeNotification')
19
+ def remove_notification(self, name: Hashable):
20
+ self.sigRemoveNotification.emit(name)
21
+
22
+ @pyqtSlot(object, object, name='addNotification')
23
+ def add_notification(self, notification, name: Hashable = None):
24
+ self.sigAddNotification.emit(notification, name)
25
+
26
+ def add_worker(self, worker: Worker, *, auto_delete: bool = True):
27
+ if auto_delete:
28
+ worker.autoDelete()
29
+ self._q_thread_pool.start(worker)
30
+
31
+ def add_progress_bar(self, progress_bar_func: Callable):
32
+ self.sigAddProgressBar.emit(progress_bar_func)
33
+
34
+
35
+ class BackgroundTasks(metaclass=SingletonMeta):
36
+ def __init__(self, parent=None):
37
+ self._tasks = _BackgroundTasksNotifications(parent)
38
+
39
+ @property
40
+ def tasks(self) -> _BackgroundTasksNotifications:
41
+ return self._tasks