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,105 @@
1
+ import numpy as np
2
+
3
+
4
+ class Intensity:
5
+ """
6
+ A class to calculate the GIWAXS intensities
7
+ ...
8
+ Attributes
9
+ ----------
10
+ atoms : np.ndarray
11
+ list of elements in the structure
12
+ atoms_positions: np.ndarray
13
+ relative atom coordinates (related with the atoms attribute)
14
+ q_3d : np.ndarray
15
+ peak vectors in 3d reciprocal space
16
+ q_1d : np.ndarray
17
+ absolute peak positions in reciprocal space
18
+ mi : np.ndarray
19
+ miller indices
20
+ wavelength : float
21
+ beam wavelength, Å
22
+ ai : float
23
+ incidence angle, deg
24
+ database: Database
25
+ database with form-factors
26
+
27
+ Methods
28
+ -------
29
+ get_intensities():
30
+ returns intensities for each peak position
31
+ """
32
+
33
+ def __init__(self,
34
+ atoms: np.ndarray, # list of elements in the structure,
35
+ atoms_positions: np.ndarray, # relative atom coordinates
36
+ q_3d: np.ndarray, # 3d vectors - (E, 3) - [[qx, qy, qz]]
37
+ mi: np.ndarray, # 3d vectors - (E, 3) - [[h, k, l]]
38
+ wavelength: float, # angstrom
39
+ ai: float, # Incidence angle, deg.
40
+ database
41
+ ):
42
+ self.atoms = atoms
43
+ self.atoms_positions = atoms_positions
44
+ self.q_3d = q_3d
45
+ self.q_1d = np.linalg.norm(q_3d, axis=-1) # 1d vectors - len(q), shape = N, N-number of peaks in 1D
46
+ self.mi = mi
47
+
48
+ self.wavelength = wavelength
49
+ self.ai = ai
50
+ self.database = database
51
+
52
+ def get_intensities(self):
53
+ """ Returns intensities for each peak position """
54
+ intensity = self._get_intensities_from_mi()
55
+ #intensity_corrected = intensity * self._lorentz_correction() * self._polarization_correction()
56
+ return intensity
57
+
58
+ def _get_intensities_from_mi(self) -> np.ndarray:
59
+ """ Returns intensities for each peak position """
60
+
61
+ #full_ff_matrix, atom_list = ff_extract() # atom_list: list of all possible elements: len = 98
62
+ # full_ff_matrix: shape = (98, 10000)
63
+ # 98 - number of elements, 10000 - calculated ff in range(0,10,0.001)
64
+ sum_fs = self._get_sf(self.database.full_atom_list, self.database.full_ff_matrix) # structure factor
65
+
66
+ intensity = np.abs(sum_fs) ** 2
67
+ return intensity
68
+ # return _normalize_vec(intensity)
69
+
70
+ def _get_sf(self,
71
+ atom_list: np.ndarray, # list of all possible elements: len = 98
72
+ full_ff_matrix: np.ndarray,
73
+ # shape = (98, 10000), 98 - number of elements, 10000 - calculated ff in range(0,10,0.001)
74
+ ) -> np.ndarray:
75
+ """ Returns structure factor as a sum of scattering amplitudes for all atoms """
76
+
77
+ ffs = self._get_ff(atom_list, full_ff_matrix) # form factors: (number of elements, len(mi))
78
+
79
+ sf = np.multiply(ffs, np.exp(2 * np.pi * 1j
80
+ * np.matmul(self.atoms_positions,
81
+ self.mi.T))) # scattering factors: (number of elements, len(mi))
82
+
83
+ sum_sf = np.sum(sf, axis=0) # structure factor: (len(mi)) /////// len(mi)==len(q_vectors)
84
+
85
+ return sum_sf
86
+
87
+ def _get_ff(self,
88
+ atom_list: np.ndarray, # list of all possible elements: len = 98
89
+ full_ff_matrix: np.ndarray,
90
+ # shape = (98, 10000), 98 - number of elements, 10000 - calculated ff in range(0,10,0.001))
91
+ ) -> np.ndarray:
92
+ """ Return X-ray form factors at specified q """
93
+
94
+ # smbl is resolved here
95
+ smbl_num = []
96
+ for smbl in self.atoms:
97
+ if smbl not in atom_list:
98
+ raise KeyError('element {} does not exist'.format(smbl))
99
+ smbl_num.extend(np.where(smbl == atom_list)[0])
100
+
101
+ # !!!! WORKS ONLY FOR q_list_default = np.arange(0,10, 0.001)!!!!!
102
+ q_list_num = (self.q_1d * 1000).astype(np.int32)
103
+ ff_matrix = full_ff_matrix[smbl_num][:, q_list_num]
104
+
105
+ return ff_matrix # shape = (len(symbol_list), len(q_vectors))
@@ -0,0 +1,20 @@
1
+ from itertools import product
2
+ import numpy as np
3
+
4
+
5
+ def get_unique_directions(idx_min: int, idx_max: int,
6
+ dtype: np.dtype = np.float32
7
+ ) -> np.ndarray:
8
+ """ Generate possible orientations of crystal growth """
9
+ direct = np.array(_get_all_directions(idx_min, idx_max), dtype=dtype)
10
+ direct_norm = direct / np.linalg.norm(direct, axis=1)[..., np.newaxis]
11
+ dir_unique = np.unique(direct_norm, axis=0)
12
+ return dir_unique
13
+
14
+
15
+ def _get_all_directions(idx_min: int, idx_max: int):
16
+ return list(filter(any, product(list(range(idx_min, idx_max + 1)), repeat=3)))
17
+
18
+
19
+ if __name__ == "__main__":
20
+ directions = get_unique_directions(0, 5)
@@ -0,0 +1,159 @@
1
+ import numpy as np
2
+ from typing import Union
3
+ from .possible_directions import get_unique_directions
4
+
5
+
6
+ class QPos:
7
+ """
8
+ A class to calculate the q positions in 3d reciprocal space
9
+ ...
10
+ Attributes
11
+ ----------
12
+ lat_par : np.ndarray
13
+ lattice parameters
14
+ mi : np.ndarray
15
+ miller indices
16
+ rec : np.ndarray
17
+ reciprocal vectors
18
+ q_3d : np.ndarray
19
+ peak positions in 3d reciprocal space
20
+
21
+ Methods
22
+ -------
23
+ calculate_q3d():
24
+ calculates the q vectors in 3d reciprocal space
25
+ rotate_vect(orientation, baz):
26
+ rotate crystal
27
+ """
28
+
29
+ def __init__(self,
30
+ lat_par: np.ndarray, # np.array([a,b,c,α,β,γ], dtype=np.float32)
31
+ mi: np.ndarray # 3d vectors - (E, 3) - [h, k, l]
32
+ ):
33
+ self.lat_par = lat_par
34
+ self.mi = mi
35
+ self.rec, self.q_3d = self.calculate_q3d()
36
+
37
+ def calculate_q3d(self):
38
+ """ Calculate q_3d vectors from lattice parameters and miller indices"""
39
+ try:
40
+ a1, a2, a3 = self._lattice_vectors_from_parameters()
41
+ except TypeError:
42
+ return None
43
+
44
+ rec = self._calc_reciprocal_vectors(a1, a2, a3)
45
+ q_vectors = self.mi @ rec
46
+ return rec, q_vectors
47
+
48
+ def rotate_vect(self,
49
+ orientation: Union[None, str, np.ndarray], # e.g. 'random' or np.array([0., 1., 0.])
50
+ baz: np.ndarray = np.array([0., 0., 1.], dtype=np.float32), # basZ
51
+ dtype=np.float32) -> np.ndarray:
52
+ """
53
+ Rotate crystal
54
+
55
+ Parameters
56
+ ----------
57
+ orientation : Union[str, np.ndarray]
58
+ orientation of the crystal growth
59
+ baz : torch.Tensor, optional
60
+ basis vector for the default orientation, default=np.array([0., 0., 1.], dtype=np.float32)
61
+
62
+ Returns
63
+ -------
64
+ q_3d (np.ndarray): peak positions in 3d reciprocal space
65
+ """
66
+ if orientation is None:
67
+ return self.q_3d
68
+ elif isinstance(orientation, str):
69
+ directions = get_unique_directions(0, 5)
70
+ orientation = directions[np.random.randint(len(directions))] # choose one of the possible orientations
71
+ elif isinstance(orientation, np.ndarray) and orientation.shape == (3,):
72
+ orientation = orientation / np.linalg.norm(orientation, axis=0)
73
+ else:
74
+ raise TypeError('orientation is not correct - use np.array with size (3,) or "random"')
75
+
76
+ if np.all(baz == orientation):
77
+ return self.q_3d
78
+
79
+ baz = baz #@ self.rec
80
+ orient = orientation @ self.rec
81
+
82
+ v1 = orient / np.linalg.norm(orient, axis=0)
83
+ v2 = baz / np.linalg.norm(baz, axis=0)
84
+ _n = np.cross(v1, v2)
85
+ n = _n / np.linalg.norm(_n, axis=0)
86
+
87
+ cos_phi = v1 @ v2
88
+ sin_phi = np.sqrt(1 - cos_phi ** 2)
89
+
90
+ a_1 = np.stack((n[..., 0] ** 2 * (1 - cos_phi) + cos_phi,
91
+ n[..., 0] * n[..., 1] * (1 - cos_phi) + n[..., 2] * sin_phi,
92
+ n[..., 0] * n[..., 2] * (1 - cos_phi) - n[..., 1] * sin_phi))
93
+
94
+ a_2 = np.stack((n[..., 0] * n[..., 1] * (1 - cos_phi) - n[..., 2] * sin_phi,
95
+ n[..., 1] ** 2 * (1 - cos_phi) + cos_phi,
96
+ n[..., 1] * n[..., 2] * (1 - cos_phi) + n[..., 0] * sin_phi))
97
+
98
+ a_3 = np.stack((n[..., 0] * n[..., 2] * (1 - cos_phi) + n[..., 1] * sin_phi,
99
+ n[..., 1] * n[..., 2] * (1 - cos_phi) - n[..., 0] * sin_phi,
100
+ n[..., 2] ** 2 * (1 - cos_phi) + cos_phi))
101
+
102
+ R = np.stack((a_1, a_2, a_3), dtype=dtype)
103
+ q_rot = self.q_3d @ R
104
+
105
+ return q_rot
106
+
107
+ def _lattice_vectors_from_parameters(self, vol_min=11, dtype=np.float32):
108
+ """ Returns lattice vectors corresponding to lattice parameters"""
109
+ pi = np.pi
110
+ a, b, c = self.lat_par[:3]
111
+ alpha, beta, gamma = self.lat_par[3:] * pi / 180
112
+
113
+ unit_volume = np.sqrt(
114
+ 1.0
115
+ + 2.0 * np.cos(alpha) * np.cos(beta) * np.cos(gamma)
116
+ - np.cos(alpha) ** 2
117
+ - np.cos(beta) ** 2
118
+ - np.cos(gamma) ** 2
119
+ )
120
+
121
+ if np.isnan(unit_volume) or (a * b * c * unit_volume < vol_min):
122
+ raise ValueError('Too small unit_volume')
123
+
124
+ # reciprocal lattice
125
+ # a_recip = np.sin(alpha) / (a * unit_volume)
126
+ # cos_gamma_recip = (np.cos(alpha) * np.cos(beta) - np.cos(gamma)
127
+ # ) / (np.sin(alpha) * np.sin(beta))
128
+ # sin_gamma_recip = np.sqrt(1 - cos_gamma_recip ** 2)
129
+
130
+ # a1 = np.array(
131
+ # [1 / a_recip, -cos_gamma_recip / sin_gamma_recip / a_recip, np.cos(beta) * a], dtype=dtype
132
+ # )
133
+ # a2 = np.array([0, b * np.sin(alpha), b * np.cos(alpha)], dtype=dtype)
134
+ # a3 = np.array([0, 0, c], dtype=dtype)
135
+
136
+ # reciprocal lattice
137
+ a1 = np.array([a, 0, 0], dtype=dtype)
138
+ a2 = np.array([b * np.cos(gamma), b * np.sin(gamma), 0], dtype=dtype)
139
+ a31 = c * np.cos(beta)
140
+ a32 = c * (np.cos(alpha) - np.cos(beta) * np.cos(gamma)) / np.sin(gamma)
141
+ a33 = (c ** 2 - a31 ** 2 - a32 ** 2) ** 0.5
142
+ a3 = np.array([a31, a32, a33], dtype=dtype)
143
+
144
+ return a1, a2, a3
145
+
146
+ @staticmethod
147
+ def _calc_reciprocal_vectors(a1: np.ndarray,
148
+ a2: np.ndarray,
149
+ a3: np.ndarray,
150
+ dtype=np.float32
151
+ ) -> np.ndarray:
152
+ """ Returns vectors in reciprocal space corresponding to lattice vectors """
153
+ pi = np.pi
154
+
155
+ unit_volume = np.dot(a1, np.cross(a2, a3, axis=0))
156
+ b1 = np.cross(a2, a3, axis=0)
157
+ b2 = np.cross(a3, a1, axis=0)
158
+ b3 = np.cross(a1, a2, axis=0)
159
+ return np.stack([b1, b2, b3], dtype=dtype) * 2 * pi / unit_volume
@@ -0,0 +1,4 @@
1
+ from .saving_parameters import (SavingParameters, SaveMode, SaveFormats,
2
+ RoiSavingType, MetaTextFormats, TextFormats)
3
+ from .data_manager import (DataManager, ImageData, FolderData,
4
+ ImageDataFlags, FolderDataFlags)
@@ -0,0 +1,164 @@
1
+ from typing import Dict, List
2
+ from pathlib import Path
3
+ from os import path
4
+ import logging
5
+ from shutil import copytree, copyfile
6
+ import math
7
+
8
+ from ..file_manager import FileManager, ImageKey, FolderKey, keys, ImagePathKey
9
+ from .load_data import (FolderData, FolderDataFlags,
10
+ ImageData, ImageDataFlags, load_image_data, load_folder_data)
11
+ from ..image_holder import ImageHolder
12
+ from .import_from_h5 import ImportProjectFromH5
13
+ from .saving_parameters import SavingParameters, SaveFormats
14
+ from .save_h5 import SaveH5
15
+ from .save_dataset import save_for_object_detection
16
+
17
+ class DataManager(object):
18
+ def __init__(self, fm: FileManager, image_holder: ImageHolder):
19
+ self.last_save_successfull = False
20
+ self._fm = fm
21
+ self._image_holder = image_holder
22
+ self._log = logging.getLogger(__name__)
23
+ self._save_h5 = SaveH5(fm, image_holder)
24
+
25
+ def save(self, params: SavingParameters):
26
+ if params.format.value == SaveFormats.entire_h5.value:
27
+ self.last_save_successfull = self._save_h5.save(params)
28
+ elif params.format.value == SaveFormats.partial_h5.value:
29
+ self.last_save_successfull = self._save_h5.save(params)
30
+ elif params.format.value == SaveFormats.object_detection.value:
31
+ self.last_save_successfull = save_for_object_detection(self._fm, self._image_holder, params)
32
+ else:
33
+ raise ValueError("Save format is not yet supported.")
34
+
35
+
36
+ def project2h5(self,
37
+ dest: str or Path,
38
+ skip_empty_images: bool = True,
39
+ save_image=True,
40
+ save_polar_image=True,
41
+ save_geometries=True,
42
+ save_roi_keys=True,
43
+ save_roi_metadata=True,
44
+ **kwargs):
45
+
46
+ dest = Path(dest)
47
+
48
+ if not dest.parent.is_dir():
49
+ raise NotADirectoryError(f"Folder {str(dest.parent)} does not exist.")
50
+
51
+ if dest.is_file():
52
+ raise FileExistsError(f"File {str(dest)} already exists.")
53
+
54
+ params = SavingParameters(
55
+ self.get_paths_dict(self._fm.root, skip_empty_images=skip_empty_images),
56
+ dest,
57
+ save_image=save_image,
58
+ save_polar_image=save_polar_image,
59
+ save_geometries=save_geometries,
60
+ save_roi_keys=save_roi_keys,
61
+ save_roi_metadata=save_roi_metadata,
62
+ **kwargs
63
+ )
64
+ self.save(params)
65
+
66
+ def load_project_from_h5(self, h5_path, project_path):
67
+ return ImportProjectFromH5(self._fm).load(project_path, h5_path)
68
+
69
+ def import_image(self, source_img_path: Path):
70
+ #self._fm.open_project(self._fm._project_folder)
71
+
72
+ # create source images folder if not already created
73
+ dest_img_folder = self._fm._project_folder / 'images'
74
+ dest_img_folder.mkdir(exist_ok=True)
75
+
76
+ # save imported image in the source images folder
77
+ img_name = keys.validate_filename(path.basename(source_img_path)) # extract filename from sourcepath and change to allowed filename
78
+ _, extension = path.splitext(source_img_path)
79
+ dest_img_path = dest_img_folder / str(img_name + extension)
80
+ copyfile(source_img_path, dest_img_path)
81
+
82
+ img_key = self._fm.add_root_path_to_project(dest_img_path)
83
+ self._fm.change_image(img_key)
84
+
85
+ def import_cif(self, source_cif_path: Path):
86
+ # create source folder if not already created
87
+ dest_cif_folder = self._fm._project_folder / 'CIF_files'
88
+ dest_cif_folder.mkdir(exist_ok=True)
89
+
90
+ # save imported cif in the source folder
91
+ cif_file_name = keys.validate_filename(path.basename(source_cif_path)) # extract filename from sourcepath and change to allowed filename
92
+ _, extension = path.splitext(source_cif_path)
93
+ dest_cif_path = dest_cif_folder / str(cif_file_name + extension)
94
+ copyfile(source_cif_path, dest_cif_path)
95
+
96
+ self._fm.add_root_path_to_project(dest_cif_path)
97
+
98
+ def import_folder(self, source_path: Path):
99
+ if not source_path.is_dir():
100
+ self._log.exception('provided folder path is not a directory')
101
+ return None
102
+
103
+ self._fm.open_project(self._fm._project_folder)
104
+ folder_name = path.basename(source_path)
105
+ destination_path = self._fm._project_folder / 'images' / folder_name
106
+
107
+ try:
108
+ copytree(source_path, destination_path, dirs_exist_ok=True)
109
+ except Exception as e:
110
+ self._log.exception('could not import folder, maybe it already exists')
111
+ return None
112
+
113
+ self._fm.add_root_path_to_project(destination_path)
114
+
115
+ def estimate_folder_size(self, source_path: Path):
116
+ try:
117
+ size_bytes = sum(f.stat().st_size for f in source_path.glob('**/*') if f.is_file())
118
+ if size_bytes == 0:
119
+ return "0B"
120
+ size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
121
+ i = int(math.floor(math.log(size_bytes, 1024)))
122
+ p = math.pow(1024, i)
123
+ s = round(size_bytes / p, 2)
124
+ return "%s %s" % (s, size_name[i])
125
+
126
+ except Exception as e:
127
+ self._log.exception('could not estimate folder size')
128
+ return ""
129
+
130
+
131
+ def load_image_data(self, key: ImageKey,
132
+ flags: ImageDataFlags = ImageDataFlags.ALL) -> ImageData:
133
+ return load_image_data(self._fm, self._image_holder, key, flags)
134
+
135
+ def load_folder_data(self, key: FolderKey,
136
+ flags: FolderDataFlags = FolderDataFlags.ALL) -> FolderData:
137
+ return load_folder_data(self._fm, self._image_holder, key, flags)
138
+
139
+ def get_paths_dict(self,
140
+ folder_key: FolderKey = None,
141
+ skip_empty_images: bool = True,
142
+ ) -> Dict[FolderKey, List[ImageKey]]:
143
+ folder_key = folder_key or self._fm.root
144
+ paths_dict: Dict[FolderKey, List[ImageKey]] = {}
145
+ _fill_paths_dict(paths_dict, folder_key, skip_empty_images, self._fm)
146
+ return paths_dict
147
+
148
+
149
+ def _fill_paths_dict(
150
+ paths_dict: Dict[FolderKey, List[ImageKey]],
151
+ folder_key: FolderKey,
152
+ skip_empty_images: bool,
153
+ fm: FileManager,
154
+ ):
155
+ if folder_key.images_num:
156
+ img_keys = list(folder_key.image_children)
157
+
158
+ if skip_empty_images:
159
+ img_keys = [key for key in img_keys if fm.rois_data[key]]
160
+
161
+ paths_dict[folder_key] = img_keys
162
+
163
+ for folder_child_key in folder_key.folder_children:
164
+ _fill_paths_dict(paths_dict, folder_child_key, skip_empty_images, fm)
@@ -0,0 +1,68 @@
1
+ import os
2
+ from h5py import File, Group
3
+ from PIL import Image
4
+ from pathlib import Path
5
+
6
+ from ..geometry import Geometry
7
+ from ..rois import RoiData
8
+ from ..file_manager import ImagePathKey, FileManager, keys
9
+
10
+
11
+ class ImportProjectFromH5(object):
12
+ def __init__(self, fm: FileManager):
13
+ self.fm = fm
14
+
15
+ def load(self, h5path: Path, project_path: Path,):
16
+ if os.listdir(project_path):
17
+ raise IOError('New project folder needs to be empty!')
18
+
19
+ self.fm.open_project(project_path)
20
+
21
+ img_folder = project_path / 'images'
22
+ img_folder.mkdir()
23
+
24
+ with File(h5path, 'r') as f:
25
+ for folder_name, group in f.items():
26
+
27
+ folder_path = img_folder / keys.validate_filename(folder_name)
28
+ folder_path.mkdir()
29
+
30
+ folder_key = self.fm.add_root_path_to_project(folder_path)
31
+
32
+ self.fm.geometries.default[folder_key] = Geometry.fromdict(dict(group.attrs))
33
+
34
+ for idx, (img_name, img_data) in enumerate(_parse_imgs_from_h5_group(group)):
35
+ img = img_data['image']
36
+ img_name = keys.validate_filename(img_name)
37
+ img_path = folder_path / str(img_name + '.tiff')
38
+ Image.fromarray(img).save(img_path,'tiff')
39
+ img_key = ImagePathKey(project_path, folder_key, path=img_path, idx=idx)
40
+ folder_key._image_children.append(img_key)
41
+ self.fm.polar_images[img_key] = img_data.get('polar_image', None)
42
+ self.fm.rois_data[img_key] = img_data.get('roi_data', None)
43
+
44
+
45
+ def _parse_imgs_from_h5_group(h5group: Group, skip_empty_imgs: bool = False):
46
+ for img_name, img_group in h5group.items():
47
+ try:
48
+ img_data = {}
49
+
50
+ if 'roi_data' in img_group:
51
+ roi_dict = {
52
+ k: v[()] for k, v in img_group['roi_data'].items()
53
+ }
54
+ img_data['roi_data'] = RoiData.from_dict(roi_dict)
55
+
56
+ if skip_empty_imgs and not len(img_data['roi_data']):
57
+ continue
58
+
59
+ elif skip_empty_imgs:
60
+ continue
61
+
62
+ for key in ('image', 'polar_image'):
63
+ if key in img_group:
64
+ img_data[key] = img_group[key][()]
65
+
66
+ yield img_name, img_data
67
+ except:
68
+ pass
@@ -0,0 +1,78 @@
1
+ from enum import Flag, auto
2
+ from typing import NamedTuple
3
+ from numpy import ndarray
4
+ from ..geometry import Geometry
5
+ from ..image_holder import ImageHolder
6
+ from ..file_manager import ImageKey, FolderKey, FileManager
7
+ from ..rois import RoiData, RoiMetaData
8
+
9
+ class ImageData(NamedTuple):
10
+ image_key: ImageKey
11
+ image: ndarray
12
+ polar_image: ndarray
13
+ geometry: Geometry
14
+ default_geometry: bool
15
+ roi_data: RoiData
16
+
17
+
18
+ class ImageDataFlags(Flag):
19
+ IMAGE = auto()
20
+ POLAR_IMAGE = auto()
21
+ GEOMETRY = auto()
22
+ ROI_DATA = auto()
23
+ ALL = IMAGE | POLAR_IMAGE | GEOMETRY | ROI_DATA
24
+
25
+
26
+ class FolderData(NamedTuple):
27
+ folder_key: FolderKey
28
+ roi_metadata: RoiMetaData
29
+ default_geometry: Geometry
30
+
31
+
32
+ class FolderDataFlags(Flag):
33
+ ROI_METADATA = auto()
34
+ GEOMETRY = auto()
35
+ ALL = ROI_METADATA | GEOMETRY
36
+
37
+
38
+ def load_image_data(fm: FileManager, image_holder: ImageHolder, image_key: ImageKey,
39
+ flags: ImageDataFlags = ImageDataFlags.ALL) -> ImageData:
40
+ image = None
41
+ polar_image = None
42
+ geometry = None
43
+ default_geometry = True
44
+ roi_data = None
45
+
46
+ if ImageDataFlags.GEOMETRY in flags or ImageDataFlags.IMAGE in flags:
47
+ geometry = fm.geometries[image_key]
48
+ if geometry:
49
+ default_geometry = False
50
+ else:
51
+ geometry = fm.geometries.default[image_key.parent]
52
+
53
+ if ImageDataFlags.POLAR_IMAGE in flags:
54
+ image, polar_image, _ = image_holder.get_data_by_key(image_key)
55
+ else:
56
+ if ImageDataFlags.IMAGE in flags:
57
+ image = image_key.get_image()
58
+ if image is not None:
59
+ if geometry:
60
+ image = geometry.t(image)
61
+ if ImageDataFlags.ROI_DATA in flags:
62
+ roi_data = fm.rois_data[image_key]
63
+
64
+ return ImageData(image_key=image_key, image=image,
65
+ polar_image=polar_image, geometry=geometry,
66
+ default_geometry=default_geometry,
67
+ roi_data=roi_data)
68
+
69
+ def load_folder_data(self, folder_key: FolderKey, flags: FolderDataFlags = None) -> FolderData:
70
+ roi_metadata = None
71
+ geometry = None
72
+
73
+ if FolderDataFlags.ROI_METADATA in flags:
74
+ roi_metadata = self._fm.rois_meta_data[folder_key]
75
+ if FolderDataFlags.GEOMETRY in flags:
76
+ geometry = self._fm.geometries.default[folder_key]
77
+ return FolderData(folder_key=folder_key, roi_metadata=roi_metadata,
78
+ default_geometry=geometry)
@@ -0,0 +1,2 @@
1
+ from .annotation_fabric import annotation_from_xml
2
+ from .pascal_annotation import Annotation, annotation_from_yolo
@@ -0,0 +1,59 @@
1
+ from copy import deepcopy
2
+ from pathlib import Path
3
+ from typing import Optional, Union
4
+
5
+ from xmlobj import get_xml_obj
6
+ from xmlobj.xmlmapping import XMLMixin
7
+
8
+ from .draw_objects import DrawObjectsMixin
9
+ from .exceptions import InconsistentAnnotation, ParseException
10
+ from .format_convertor import FormatConvertorMixin
11
+ from .protocols import PascalAnnotation, Size
12
+ from .utils import _is_primitive, _check_bnd_box
13
+
14
+
15
+ def annotation_from_xml(
16
+ file_path: Union[str, Path],
17
+ attr_type_spec: Optional[dict] = None,
18
+ clip_zero: bool = True,
19
+ ) -> Union[PascalAnnotation, DrawObjectsMixin, FormatConvertorMixin, XMLMixin]:
20
+ """
21
+ Make annotation object from PascalVOC annotation file
22
+
23
+ Parameters
24
+ ----------
25
+ file: path to xml file
26
+ attr_type_spec: dict, optional
27
+ specify attribute types to explicitly cast attribute values
28
+ clip_zero: clip negative bbox values to 0
29
+
30
+ Returns
31
+ -------
32
+ Annotation object
33
+ """
34
+ try:
35
+ obj = get_xml_obj(
36
+ file_path,
37
+ mixin_clsasses=[DrawObjectsMixin, FormatConvertorMixin],
38
+ attr_type_spec=attr_type_spec,
39
+ )
40
+ except Exception as ex:
41
+ raise ParseException(ex)
42
+ if hasattr(obj, "object"):
43
+ obj_ = getattr(obj, "object")
44
+ if isinstance(obj_, list):
45
+ objects = [deepcopy(obj) for obj in obj_]
46
+ elif not _is_primitive(obj_):
47
+ objects = [deepcopy(obj_)]
48
+ else:
49
+ raise ParseException("Cannot parse objects")
50
+ setattr(obj, "objects", objects)
51
+ delattr(obj, "object")
52
+ if isinstance(obj, PascalAnnotation):
53
+ if (obj.filename is None and len(obj.objects) == 0) or not isinstance(
54
+ obj.size, Size
55
+ ):
56
+ raise InconsistentAnnotation(f"File {file_path} is not PascalVOCAnnotation")
57
+ for object in obj:
58
+ object.bndbox = _check_bnd_box(object.bndbox, clip_zero)
59
+ return obj