Marker#:'
- html_text += '
' + str(int(marker_index) + 1)
+ html_text += (
+ ''
+ + str(int(marker_index) + 1)
+ )
html_text += " - File#:"
html_text += '' + str(file_index)
html_text += ""
diff --git a/notebooks/__code/registration/registration.py b/notebooks/__code/registration/registration.py
index 9101b31d..a5b927a2 100755
--- a/notebooks/__code/registration/registration.py
+++ b/notebooks/__code/registration/registration.py
@@ -18,7 +18,9 @@
from __code.registration.manual import ManualLauncher
from __code.registration.marker_handler import MarkerHandler
from __code.registration.registration_auto import RegistrationAuto
-from __code.registration.registration_auto_confirmation import RegistrationAutoConfirmationLauncher
+from __code.registration.registration_auto_confirmation import (
+ RegistrationAutoConfirmationLauncher,
+)
from __code.registration.registration_marker import RegistrationMarkersLauncher
from __code.registration.registration_profile import RegistrationProfileLauncher
from __code.registration.table_handler import TableHandler
@@ -85,7 +87,8 @@ def __init__(self, parent=None, data_dict=None):
)
)
ui_full_path = os.path.join(
- os.path.dirname(os.path.dirname(os.path.dirname(__file__))), os.path.join("ui", "ui_registration.ui")
+ os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
+ os.path.join("ui", "ui_registration.ui"),
)
self.ui = load_ui(ui_full_path, baseinstance=self)
@@ -100,7 +103,9 @@ def __init__(self, parent=None, data_dict=None):
self.data_dict_raw = copy.deepcopy(data_dict)
self.reference_image = self.data_dict["data"][self.reference_image_index]
self.working_dir = os.path.dirname(self.data_dict["file_name"][0])
- self.reference_image_short_name = str(os.path.basename(self.data_dict["file_name"][0]))
+ self.reference_image_short_name = str(
+ os.path.basename(self.data_dict["file_name"][0])
+ )
# initialization
o_init = Initialization(parent=self)
@@ -116,7 +121,11 @@ def __init__(self, parent=None, data_dict=None):
) # because by default first row = reference selected
def filter_checkbox_clicked(self):
- list_ui = [self.ui.filter_column_name_comboBox, self.ui.filter_logic_comboBox, self.ui.filter_value]
+ list_ui = [
+ self.ui.filter_column_name_comboBox,
+ self.ui.filter_logic_comboBox,
+ self.ui.filter_value,
+ ]
for _ui in list_ui:
_ui.setEnabled(self.ui.filter_checkBox.isChecked())
@@ -230,7 +239,9 @@ def slider_file_changed(self, index_selected):
self.ui.tableWidget.blockSignals(False)
def help_button_clicked(self):
- webbrowser.open("https://neutronimaging.pages.ornl.gov/tutorial/notebooks/registration/")
+ webbrowser.open(
+ "https://neutronimaging.pages.ornl.gov/tutorial/notebooks/registration/"
+ )
def ok_button_clicked(self):
self.close()
@@ -258,7 +269,11 @@ def next_image_button_clicked(self):
def selection_all_clicked(self):
_is_checked = self.ui.selection_all.isChecked()
- list_widgets = [self.ui.top_row_label, self.ui.bottom_row_label, self.ui.opacity_selection_slider]
+ list_widgets = [
+ self.ui.top_row_label,
+ self.ui.bottom_row_label,
+ self.ui.opacity_selection_slider,
+ ]
for _widget in list_widgets:
_widget.setEnabled(not _is_checked)
self.display_image()
@@ -294,7 +309,9 @@ def manual_registration_button_clicked(self):
)
def auto_registration_button_clicked(self):
- o_registration_auto_confirmed = RegistrationAutoConfirmationLauncher(parent=self)
+ o_registration_auto_confirmed = RegistrationAutoConfirmationLauncher(
+ parent=self
+ )
def markers_registration_button_clicked(self):
o_markers_registration = RegistrationMarkersLauncher(parent=self)
@@ -320,7 +337,9 @@ def profiler_registration_button_clicked(self):
def start_auto_registration(self):
o_auto_register = RegistrationAuto(
- parent=self, reference_image=self.reference_image, floating_images=self.data_dict["data"]
+ parent=self,
+ reference_image=self.reference_image,
+ floating_images=self.data_dict["data"],
)
o_auto_register.auto_align()
diff --git a/notebooks/__code/registration/registration_auto.py b/notebooks/__code/registration/registration_auto.py
index 8582cbfc..b5893b4f 100755
--- a/notebooks/__code/registration/registration_auto.py
+++ b/notebooks/__code/registration/registration_auto.py
@@ -25,7 +25,9 @@ def auto_align(self):
self.parent.eventProgress.setVisible(True)
for _row, _image in enumerate(_list_images):
- [yoffset, xoffset], error, diffphase = register_translation(_ref_image, _image)
+ [yoffset, xoffset], error, diffphase = register_translation(
+ _ref_image, _image
+ )
if not _row == self.parent.reference_image_index:
self.parent.set_item(row=_row, col=1, value=xoffset)
self.parent.set_item(row=_row, col=2, value=yoffset)
diff --git a/notebooks/__code/registration/registration_auto_confirmation.py b/notebooks/__code/registration/registration_auto_confirmation.py
index 0d83070d..e884120a 100755
--- a/notebooks/__code/registration/registration_auto_confirmation.py
+++ b/notebooks/__code/registration/registration_auto_confirmation.py
@@ -35,7 +35,9 @@ def __init__(self, parent=None):
def initialize_widgets(self):
_file_path = os.path.dirname(__file__)
- warning_image_file = os.path.abspath(os.path.join(_file_path, "../static/warning_icon.png"))
+ warning_image_file = os.path.abspath(
+ os.path.join(_file_path, "../static/warning_icon.png")
+ )
warning_image = QPixmap(warning_image_file)
self.ui.warning_label.setPixmap(warning_image)
diff --git a/notebooks/__code/registration/registration_marker.py b/notebooks/__code/registration/registration_marker.py
index 7a59d279..685b3f76 100755
--- a/notebooks/__code/registration/registration_marker.py
+++ b/notebooks/__code/registration/registration_marker.py
@@ -70,7 +70,9 @@ def resizing_column(self, index_column, old_size, new_size):
_table_ui = self.parent.markers_table[_key]["ui"]
if not (_table_ui == _live_table_ui):
for _col, _size in enumerate(self.parent.markers_table_column_width):
- _table_ui.setColumnWidth(_col, self.parent.markers_table_column_width[_col])
+ _table_ui.setColumnWidth(
+ _col, self.parent.markers_table_column_width[_col]
+ )
def init_widgets(self):
if self.parent.markers_table == {}:
@@ -109,14 +111,20 @@ def populate_using_markers_table(self):
selected_row = o_main_table.get_row_selected()
for _col, _size in enumerate(self.parent.markers_table_column_width):
- _table.setColumnWidth(_col, self.parent.markers_table_column_width[_col])
+ _table.setColumnWidth(
+ _col, self.parent.markers_table_column_width[_col]
+ )
_table.horizontalHeader().sectionResized.connect(self.resizing_column)
_table.cellClicked.connect(
- lambda row=0, column=0, tab_index=_key_tab_name: self.table_row_clicked(row, column, tab_index)
+ lambda row=0, column=0, tab_index=_key_tab_name: self.table_row_clicked(
+ row, column, tab_index
+ )
)
_table.itemSelectionChanged.connect(
- lambda key_tab_name=_key_tab_name: self.cell_clicked(key_tab_name=_key_tab_name)
+ lambda key_tab_name=_key_tab_name: self.cell_clicked(
+ key_tab_name=_key_tab_name
+ )
)
_data_dict = self.parent.markers_table[_key_tab_name]["data"]
@@ -251,7 +259,9 @@ def copy_cell(self, row_selected=-1, column_selected=-1):
cell_value = str(table_ui.item(row_selected, column_selected).text())
self.parent.marker_table_buffer_cell = cell_value
- def paste_cell(self, top_row_selected=-1, bottom_row_selected=-1, column_selected=-1):
+ def paste_cell(
+ self, top_row_selected=-1, bottom_row_selected=-1, column_selected=-1
+ ):
cell_contain_to_copy = self.parent.marker_table_buffer_cell
table_ui = self.get_current_table_ui()
markers_table = self.parent.markers_table
@@ -262,7 +272,9 @@ def paste_cell(self, top_row_selected=-1, bottom_row_selected=-1, column_selecte
marker_axis = "y"
for _row in np.arange(top_row_selected, bottom_row_selected + 1):
_file = str(table_ui.item(_row, 0).text())
- markers_table[marker_name]["data"][_file][marker_axis] = cell_contain_to_copy
+ markers_table[marker_name]["data"][_file][marker_axis] = (
+ cell_contain_to_copy
+ )
table_ui.item(_row, column_selected).setText(str(cell_contain_to_copy))
self.parent.markers_table = markers_table
@@ -328,7 +340,9 @@ def table_right_click(self, position):
menu.addSeparator()
self.start_marker = menu.addAction("Set marker interpolation initial position")
- self.end_marker = menu.addAction("Set marker interpolation final position and process intermediate markers")
+ self.end_marker = menu.addAction(
+ "Set marker interpolation final position and process intermediate markers"
+ )
if self.parent.markers_initial_position["row"] is None:
self.end_marker.setEnabled(False)
@@ -338,7 +352,9 @@ def table_right_click(self, position):
action = menu.exec_(QtGui.QCursor.pos())
if action == copy_cell:
- self.copy_cell(row_selected=top_row_selected, column_selected=left_column_selected)
+ self.copy_cell(
+ row_selected=top_row_selected, column_selected=left_column_selected
+ )
elif action == paste_cell:
self.paste_cell(
@@ -359,7 +375,9 @@ def start_marker_initialized(self):
self.parent.markers_initial_position["row"] = row_selected
self.parent.markers_initial_position["tab_name"] = tab_selected
o_table = TableHandler(table_ui=self.parent.markers_table[tab_selected]["ui"])
- o_table.set_item_with_str(row=row_selected, column=3, cell_str="Interpolation starting position")
+ o_table.set_item_with_str(
+ row=row_selected, column=3, cell_str="Interpolation starting position"
+ )
def end_marker_initialized(self):
tab_selected = self.get_current_active_tab()
@@ -384,10 +402,14 @@ def end_marker_initialized(self):
coeff = 1
for _row in np.arange(from_row + 1, to_row):
xoffset_value = int(np.round(xoffset_from + coeff * delta_xoffset))
- o_table.set_item_with_str(row=_row, column=1, cell_str=str(xoffset_value))
+ o_table.set_item_with_str(
+ row=_row, column=1, cell_str=str(xoffset_value)
+ )
yoffset_value = int(np.round(yoffset_from + coeff * delta_yoffset))
- o_table.set_item_with_str(row=_row, column=2, cell_str=str(yoffset_value))
+ o_table.set_item_with_str(
+ row=_row, column=2, cell_str=str(yoffset_value)
+ )
coeff += 1
self.parent.markers_initial_position["row"] = None
@@ -443,7 +465,12 @@ def add_marker_button_clicked(self):
x = self.parent.o_MarkerDefaultSettings.x
y = self.parent.o_MarkerDefaultSettings.y
self.__populate_table_row(table, _row, _short_file, x, y)
- _data_dict[_short_file] = {"x": x, "y": y, "marker_ui": None, "label_ui": None}
+ _data_dict[_short_file] = {
+ "x": x,
+ "y": y,
+ "marker_ui": None,
+ "label_ui": None,
+ }
_marker_dict["data"] = _data_dict
@@ -452,7 +479,9 @@ def add_marker_button_clicked(self):
self.ui.tabWidget.setCurrentIndex(number_of_tabs - 1)
table.itemChanged.connect(self.table_cell_modified)
table.itemSelectionChanged.connect(
- lambda key_tab_name=new_marker_name: self.cell_clicked(key_tab_name=new_marker_name)
+ lambda key_tab_name=new_marker_name: self.cell_clicked(
+ key_tab_name=new_marker_name
+ )
)
self.parent.markers_table[new_marker_name] = _marker_dict
@@ -520,8 +549,12 @@ def run_registration_button_clicked(self):
for _marker in markers_table.keys():
_list_files = markers_table[_marker]["data"]
for _file in _list_files:
- markers_list[_file]["x"].append(markers_table[_marker]["data"][_file]["x"])
- markers_list[_file]["y"].append(markers_table[_marker]["data"][_file]["y"])
+ markers_list[_file]["x"].append(
+ markers_table[_marker]["data"][_file]["x"]
+ )
+ markers_list[_file]["y"].append(
+ markers_table[_marker]["data"][_file]["y"]
+ )
step += 1
self.parent.eventProgress.setValue(step)
diff --git a/notebooks/__code/registration/registration_profile.py b/notebooks/__code/registration/registration_profile.py
index 45ad5ed7..62bf1091 100755
--- a/notebooks/__code/registration/registration_profile.py
+++ b/notebooks/__code/registration/registration_profile.py
@@ -28,7 +28,9 @@
from __code._utilities.color import Color
from __code._utilities.file import make_or_reset_folder
from __code.registration import interact_me_style, normal_style
-from __code.registration.calculate_profiles_difference import CalculateProfilesDifference
+from __code.registration.calculate_profiles_difference import (
+ CalculateProfilesDifference,
+)
class RegistrationProfileLauncher:
@@ -370,7 +372,9 @@ def init_reference_image(self):
self.reference_image_short_name = self.parent.reference_image_short_name
else:
self.reference_image = self.data_dict["data"][self.reference_image_index]
- self.reference_image_short_name = os.path.basename(self.data_dict["file_name"][self.reference_image_index])
+ self.reference_image_short_name = os.path.basename(
+ self.data_dict["file_name"][self.reference_image_index]
+ )
def init_table(self):
data_dict = self.data_dict
@@ -554,7 +558,9 @@ def replot_profile_lines(self, is_horizontal=False):
def update_selected_file_profile_plots(self, is_horizontal=True):
index_selected = self._get_selected_row()
- self.update_single_profile(file_selected=index_selected, is_horizontal=is_horizontal)
+ self.update_single_profile(
+ file_selected=index_selected, is_horizontal=is_horizontal
+ )
def update_single_profile(self, file_selected=-1, is_horizontal=True):
if is_horizontal:
@@ -568,7 +574,9 @@ def update_single_profile(self, file_selected=-1, is_horizontal=True):
profile_2d_ui.clear()
# always display the reference image
- [xaxis, ref_profile] = self.get_profile(image_index=self.reference_image_index, is_horizontal=is_horizontal)
+ [xaxis, ref_profile] = self.get_profile(
+ image_index=self.reference_image_index, is_horizontal=is_horizontal
+ )
try:
profile_2d_ui.plot(xaxis, ref_profile, pen=self.roi[label]["color-peak"])
@@ -576,10 +584,16 @@ def update_single_profile(self, file_selected=-1, is_horizontal=True):
pass
if file_selected != self.reference_image_index:
- [xaxis, selected_profile] = self.get_profile(image_index=file_selected, is_horizontal=is_horizontal)
+ [xaxis, selected_profile] = self.get_profile(
+ image_index=file_selected, is_horizontal=is_horizontal
+ )
try:
- profile_2d_ui.plot(xaxis, selected_profile, pen=self.list_rgb_profile_color[file_selected])
+ profile_2d_ui.plot(
+ xaxis,
+ selected_profile,
+ pen=self.list_rgb_profile_color[file_selected],
+ )
except Exception:
pass
@@ -628,10 +642,14 @@ def calculate_all_profiles(self):
def calculate_profile(self, file_index=-1, is_horizontal=True):
if is_horizontal:
- [xaxis, profile] = self.get_profile(image_index=file_index, is_horizontal=True)
+ [xaxis, profile] = self.get_profile(
+ image_index=file_index, is_horizontal=True
+ )
label = "horizontal"
else:
- [xaxis, profile] = self.get_profile(image_index=file_index, is_horizontal=False)
+ [xaxis, profile] = self.get_profile(
+ image_index=file_index, is_horizontal=False
+ )
label = "vertical"
_profile = {}
@@ -744,7 +762,9 @@ def register_images(self):
self.eventProgress.setVisible(False)
QApplication.processEvents()
- def calculate_and_display_current_peak(self, force_recalculation=True, is_horizontal=True):
+ def calculate_and_display_current_peak(
+ self, force_recalculation=True, is_horizontal=True
+ ):
if is_horizontal:
label = "horizontal"
else:
@@ -765,8 +785,12 @@ def calculate_and_display_current_peak(self, force_recalculation=True, is_horizo
self.display_current_peak(is_horizontal=is_horizontal)
if force_recalculation:
- self.calculate_profile(file_index=index_selected, is_horizontal=is_horizontal)
- self.recalculate_current_peak(file_index=index_selected, is_horizontal=is_horizontal)
+ self.calculate_profile(
+ file_index=index_selected, is_horizontal=is_horizontal
+ )
+ self.recalculate_current_peak(
+ file_index=index_selected, is_horizontal=is_horizontal
+ )
self.display_current_peak(is_horizontal=is_horizontal)
@@ -802,8 +826,12 @@ def display_current_peak(self, is_horizontal=True):
self.verti_infinite_line_ui = infinite_line_ui
def calculate_and_display_hori_and_verti_peaks(self, force_recalculation=True):
- self.calculate_and_display_current_peak(force_recalculation=force_recalculation, is_horizontal=True)
- self.calculate_and_display_current_peak(force_recalculation=force_recalculation, is_horizontal=False)
+ self.calculate_and_display_current_peak(
+ force_recalculation=force_recalculation, is_horizontal=True
+ )
+ self.calculate_and_display_current_peak(
+ force_recalculation=force_recalculation, is_horizontal=False
+ )
def copy_register_parameters_to_main_table(self):
nbr_row = self.ui.tableWidget.rowCount()
@@ -825,7 +853,9 @@ def full_reset(self):
def vertical_roi_moved(self):
"""when the vertical roi is moved, we need to make sure the width stays within the max we defined
and we need refresh the peak calculation"""
- region = self.vertical_profile.getArraySlice(self.live_image, self.ui.image_view.imageItem)
+ region = self.vertical_profile.getArraySlice(
+ self.live_image, self.ui.image_view.imageItem
+ )
x0 = region[0][0].start
x1 = region[0][0].stop
@@ -846,7 +876,9 @@ def vertical_roi_moved(self):
def horizontal_roi_moved(self):
"""when the horizontal roi is moved, we need to make sure the height stays within the max we defined
and we need to refresh the peak calculation"""
- region = self.horizontal_profile.getArraySlice(self.live_image, self.ui.image_view.imageItem)
+ region = self.horizontal_profile.getArraySlice(
+ self.live_image, self.ui.image_view.imageItem
+ )
x0 = region[0][0].start
x1 = region[0][0].stop
@@ -891,7 +923,9 @@ def calculate_profiles_differences(self):
def help_button_clicked(self):
import webbrowser
- webbrowser.open("https://neutronimaging.ornl.gov/tutorials/imaging-notebooks/registration/")
+ webbrowser.open(
+ "https://neutronimaging.ornl.gov/tutorials/imaging-notebooks/registration/"
+ )
def slider_file_changed(self, value):
self._select_table_row(value)
@@ -939,10 +973,17 @@ def export_button_clicked(self):
"""save registered images back to the main UI"""
# self.registered_all_images_button_clicked()
_export_folder = QFileDialog.getExistingDirectory(
- self, directory=self.working_dir, caption="Select Output Folder", options=QFileDialog.ShowDirsOnly
+ self,
+ directory=self.working_dir,
+ caption="Select Output Folder",
+ options=QFileDialog.ShowDirsOnly,
)
if _export_folder:
- o_export = ExportRegistration(parent=self, input_working_dir=self.working_dir, export_folder=_export_folder)
+ o_export = ExportRegistration(
+ parent=self,
+ input_working_dir=self.working_dir,
+ export_folder=_export_folder,
+ )
o_export.run()
QApplication.processEvents()
@@ -1058,7 +1099,9 @@ def run(self):
self.parent.eventProgress.setValue(0)
self.parent.eventProgress.setVisible(True)
- export_folder = os.path.join(self.export_folder, self.input_dir_name + "_registered")
+ export_folder = os.path.join(
+ self.export_folder, self.input_dir_name + "_registered"
+ )
make_or_reset_folder(export_folder)
for _row, _data in enumerate(data_dict["data"]):
diff --git a/notebooks/__code/rename_files.py b/notebooks/__code/rename_files.py
index 4bb93a70..4016b4a0 100755
--- a/notebooks/__code/rename_files.py
+++ b/notebooks/__code/rename_files.py
@@ -55,8 +55,12 @@ def __init__(self, o_format=None):
self.working_dir = o_format.working_dir
if self.list_files:
- _random_input_list = utilities.get_n_random_element(input_list=self.list_files, n=10)
- self.random_input_list = [os.path.basename(_file) for _file in _random_input_list]
+ _random_input_list = utilities.get_n_random_element(
+ input_list=self.list_files, n=10
+ )
+ self.random_input_list = [
+ os.path.basename(_file) for _file in _random_input_list
+ ]
self.basename = os.path.basename(self.list_files[0])
@@ -127,16 +131,22 @@ def show(self):
# current schema name
self.box2 = widgets.HBox(
[
- widgets.Label("Pre. Index Separator", layout=widgets.Layout(width="15%")),
+ widgets.Label(
+ "Pre. Index Separator", layout=widgets.Layout(width="15%")
+ ),
widgets.Text(value="_", layout=widgets.Layout(width="5%")),
]
)
self.box2b = widgets.HBox(
[
- widgets.Label("Untouched filename part:", layout=widgets.Layout(width="20%")),
+ widgets.Label(
+ "Untouched filename part:", layout=widgets.Layout(width="20%")
+ ),
widgets.Label("", layout=widgets.Layout(width="40%")),
- widgets.IntRangeSlider(value=[0, 2], min=0, max=len(self.basename), step=1),
+ widgets.IntRangeSlider(
+ value=[0, 2], min=0, max=len(self.basename), step=1
+ ),
]
)
self.int_range_slider = self.box2b.children[2]
@@ -145,11 +155,17 @@ def show(self):
self.box4 = widgets.HBox(
[
- widgets.Label("Current Name Schema: ", layout=widgets.Layout(width="20%")),
- widgets.Label(self.current_naming_schema(), layout=widgets.Layout(width="30%")),
+ widgets.Label(
+ "Current Name Schema: ", layout=widgets.Layout(width="20%")
+ ),
+ widgets.Label(
+ self.current_naming_schema(), layout=widgets.Layout(width="30%")
+ ),
widgets.Label("Random Input:", layout=widgets.Layout(width="15%")),
widgets.Dropdown(
- options=self.random_input_list, value=self.random_input_list[0], layout=widgets.Layout(width="50%")
+ options=self.random_input_list,
+ value=self.random_input_list[0],
+ layout=widgets.Layout(width="50%"),
),
]
)
@@ -157,36 +173,54 @@ def show(self):
self.box2.children[1].on_trait_change(self.pre_index_text_changed, "value")
before = widgets.VBox([self.box2, self.box2b, self.box4])
self.random_input_checkbox = self.box4.children[3]
- self.random_input_checkbox.observe(self.random_input_checkbox_value_changed, "value")
+ self.random_input_checkbox.observe(
+ self.random_input_checkbox_value_changed, "value"
+ )
# new naming schema
box_text_width = "10%"
self.box1 = widgets.HBox(
[
- widgets.Label("New prefix File Name", layout=widgets.Layout(width="10%")),
+ widgets.Label(
+ "New prefix File Name", layout=widgets.Layout(width="10%")
+ ),
widgets.Checkbox(
- value=True, description="Use previous prefix name", layout=widgets.Layout(width="30%")
+ value=True,
+ description="Use previous prefix name",
+ layout=widgets.Layout(width="30%"),
),
]
)
self.use_previous_prefix_widget = self.box1.children[1]
- self.box1.children[1].observe(self.changed_use_previous_prefix_name, names="value")
+ self.box1.children[1].observe(
+ self.changed_use_previous_prefix_name, names="value"
+ )
self.box1b = widgets.HBox(
[
widgets.Label("", layout=widgets.Layout(width="10%")),
- widgets.Checkbox(value=False, description="Use new prefix", layout=widgets.Layout(width="20%")),
- widgets.Text(value="image", disabled=True, layout=widgets.Layout(width="25%")),
+ widgets.Checkbox(
+ value=False,
+ description="Use new prefix",
+ layout=widgets.Layout(width="20%"),
+ ),
+ widgets.Text(
+ value="image", disabled=True, layout=widgets.Layout(width="25%")
+ ),
]
)
self.box1b.children[2].observe(self.changed_use_new_prefix_name, names="value")
self.new_prefix_text_widget = self.box1b.children[2]
self.user_new_prefix_widget = self.box1b.children[1]
- self.user_new_prefix_widget.observe(self.changed_use_new_prefix_name, names="value")
+ self.user_new_prefix_widget.observe(
+ self.changed_use_new_prefix_name, names="value"
+ )
self.box5 = widgets.HBox(
[
- widgets.Label("New Index Separator", layout=widgets.Layout(width="15%")),
+ widgets.Label(
+ "New Index Separator", layout=widgets.Layout(width="15%")
+ ),
widgets.Text(value="_", layout=widgets.Layout(width=box_text_width)),
]
)
@@ -208,7 +242,9 @@ def show(self):
self.box6 = widgets.HBox(
[
widgets.Label("New Name Schema: ", layout=widgets.Layout(width="20%")),
- widgets.Label(self.new_naming_schema(), layout=widgets.Layout(width="40%")),
+ widgets.Label(
+ self.new_naming_schema(), layout=widgets.Layout(width="40%")
+ ),
]
)
@@ -217,13 +253,17 @@ def show(self):
self.box7.children[1].on_trait_change(self.post_text_changed, "value")
self.box8.children[1].on_trait_change(self.post_text_changed, "value")
- after = widgets.VBox([self.box1, self.box1b, self.box5, self.box7, self.box8, self.box6])
+ after = widgets.VBox(
+ [self.box1, self.box1b, self.box5, self.box7, self.box8, self.box6]
+ )
accordion = widgets.Accordion(children=[before, after])
accordion.set_title(0, "Current Schema Name")
accordion.set_title(1, "New Naming Schema")
- output_ui_1 = widgets.HBox([widgets.Label("Example of naming: ", layout=widgets.Layout(width="20%"))])
+ output_ui_1 = widgets.HBox(
+ [widgets.Label("Example of naming: ", layout=widgets.Layout(width="20%"))]
+ )
self.output_ui_2 = widgets.HBox(
[
@@ -240,7 +280,9 @@ def show(self):
)
self.output_ui_3.children[1].add_class("result_label")
- vbox = widgets.VBox([accordion, output_ui_1, self.output_ui_2, self.output_ui_3])
+ vbox = widgets.VBox(
+ [accordion, output_ui_1, self.output_ui_2, self.output_ui_3]
+ )
display(vbox)
self.demo_output_file_name()
@@ -248,7 +290,9 @@ def show(self):
self.changed_use_new_prefix_name()
def demo_output_file_name(self):
- input_file = self.get_basename_of_current_dropdown_selected_file(is_with_ext=True)
+ input_file = self.get_basename_of_current_dropdown_selected_file(
+ is_with_ext=True
+ )
self.output_ui_2.children[1].value = input_file
old_index_separator = self.get_old_index_separator()
@@ -340,7 +384,12 @@ def generate_new_file_name(
try:
_index = int(_name_separated[-1]) + offset
- new_name = prefix + new_index_separator + "{:0{}}".format(_index, new_number_of_digits) + self.ext
+ new_name = (
+ prefix
+ + new_index_separator
+ + "{:0{}}".format(_index, new_number_of_digits)
+ + self.ext
+ )
except ValueError:
_index = _name_separated[-1]
new_name = prefix + new_index_separator + _index + self.ext
@@ -361,7 +410,9 @@ def get_dict_old_new_filenames(self):
new_number_of_digits = self.get_new_number_of_digits()
offset = self.box8.children[1].value
- list_of_input_basename_files = [os.path.basename(_file) for _file in list_of_input_files]
+ list_of_input_basename_files = [
+ os.path.basename(_file) for _file in list_of_input_files
+ ]
new_list = {}
for _file_index, _file in enumerate(list_of_input_basename_files):
@@ -392,7 +443,11 @@ def select_export_folder(self):
type="directory",
)
else:
- display(HTML('You need to fix the namig convention first!'))
+ display(
+ HTML(
+ 'You need to fix the namig convention first!'
+ )
+ )
def export(self, selected):
self.output_folder_ui.shortcut_buttons.close()
@@ -401,7 +456,9 @@ def export(self, selected):
new_output_folder = os.path.abspath(selected)
utilities.copy_files(
- dict_old_new_names=dict_old_new_names, new_output_folder=new_output_folder, overwrite=False
+ dict_old_new_names=dict_old_new_names,
+ new_output_folder=new_output_folder,
+ overwrite=False,
)
self.new_list_files = dict_old_new_names
@@ -420,7 +477,9 @@ def display_renaming_result(self, selected):
[
widgets.Label("Renmaing results: ", layout=widgets.Layout(width="20%")),
widgets.Dropdown(
- options=self.renaming_result, value=self.renaming_result[0], layout=widgets.Layout(width="80%")
+ options=self.renaming_result,
+ value=self.renaming_result[0],
+ layout=widgets.Layout(width="80%"),
),
]
)
diff --git a/notebooks/__code/rename_files/rename_files.py b/notebooks/__code/rename_files/rename_files.py
index 6dd23a9a..2654779e 100755
--- a/notebooks/__code/rename_files/rename_files.py
+++ b/notebooks/__code/rename_files/rename_files.py
@@ -15,7 +15,9 @@ def __init__(self, working_dir=""):
def select_input_files(self):
self.input_files_ui = fileselector.FileSelectorPanel(
- instruction="Select List of Files", start_dir=self.working_dir, multiple=True
+ instruction="Select List of Files",
+ start_dir=self.working_dir,
+ multiple=True,
)
self.input_files_ui.show()
@@ -80,8 +82,12 @@ def __init__(self, o_format=None):
raise ValueError("FormatFileNameIndex object is missing!")
if self.list_files:
- _random_input_list = utilities.get_n_random_element(input_list=self.list_files, n=10)
- self.random_input_list = [os.path.basename(_file) for _file in _random_input_list]
+ _random_input_list = utilities.get_n_random_element(
+ input_list=self.list_files, n=10
+ )
+ self.random_input_list = [
+ os.path.basename(_file) for _file in _random_input_list
+ ]
self.basename = os.path.basename(self.list_files[0])
@@ -172,16 +178,22 @@ def show(self):
# current schema name
self.box2 = widgets.HBox(
[
- widgets.Label("Pre. Index Separator", layout=widgets.Layout(width="15%")),
+ widgets.Label(
+ "Pre. Index Separator", layout=widgets.Layout(width="15%")
+ ),
widgets.Text(value="_", layout=widgets.Layout(width="5%")),
]
)
self.box2b = widgets.HBox(
[
- widgets.Label("Untouched filename part:", layout=widgets.Layout(width="20%")),
+ widgets.Label(
+ "Untouched filename part:", layout=widgets.Layout(width="20%")
+ ),
widgets.Label("", layout=widgets.Layout(width="40%")),
- widgets.IntRangeSlider(value=[0, 2], min=0, max=len(self.basename), step=1),
+ widgets.IntRangeSlider(
+ value=[0, 2], min=0, max=len(self.basename), step=1
+ ),
]
)
self.int_range_slider = self.box2b.children[2]
@@ -190,11 +202,17 @@ def show(self):
self.box4 = widgets.HBox(
[
- widgets.Label("Current Name Schema: ", layout=widgets.Layout(width="20%")),
- widgets.Label(self.current_naming_schema(), layout=widgets.Layout(width="30%")),
+ widgets.Label(
+ "Current Name Schema: ", layout=widgets.Layout(width="20%")
+ ),
+ widgets.Label(
+ self.current_naming_schema(), layout=widgets.Layout(width="30%")
+ ),
widgets.Label("Random Input:", layout=widgets.Layout(width="15%")),
widgets.Dropdown(
- options=self.random_input_list, value=self.random_input_list[0], layout=widgets.Layout(width="50%")
+ options=self.random_input_list,
+ value=self.random_input_list[0],
+ layout=widgets.Layout(width="50%"),
),
]
)
@@ -202,57 +220,93 @@ def show(self):
self.box2.children[1].on_trait_change(self.pre_index_text_changed, "value")
before = widgets.VBox([self.box2, self.box2b, self.box4])
self.random_input_checkbox = self.box4.children[3]
- self.random_input_checkbox.observe(self.random_input_checkbox_value_changed, "value")
+ self.random_input_checkbox.observe(
+ self.random_input_checkbox_value_changed, "value"
+ )
# new naming schema
box_text_width = "10%"
self.box1 = widgets.HBox(
[
- widgets.Label("New prefix File Name", layout=widgets.Layout(width="20%")),
+ widgets.Label(
+ "New prefix File Name", layout=widgets.Layout(width="20%")
+ ),
widgets.Checkbox(
- value=True, description="Use previous prefix name", layout=widgets.Layout(width="30%")
+ value=True,
+ description="Use previous prefix name",
+ layout=widgets.Layout(width="30%"),
),
]
)
self.use_previous_prefix_widget = self.box1.children[1]
- self.box1.children[1].observe(self.changed_use_previous_prefix_name, names="value")
+ self.box1.children[1].observe(
+ self.changed_use_previous_prefix_name, names="value"
+ )
self.box1b = widgets.HBox(
[
widgets.Label("", layout=widgets.Layout(width="20%")),
- widgets.Checkbox(value=False, description="Use new prefix", layout=widgets.Layout(width="20%")),
- widgets.Text(value="image", disabled=True, layout=widgets.Layout(width="25%")),
+ widgets.Checkbox(
+ value=False,
+ description="Use new prefix",
+ layout=widgets.Layout(width="20%"),
+ ),
+ widgets.Text(
+ value="image", disabled=True, layout=widgets.Layout(width="25%")
+ ),
]
)
self.box1b.children[2].observe(self.changed_use_new_prefix_name, names="value")
self.new_prefix_text_widget = self.box1b.children[2]
self.user_new_prefix_widget = self.box1b.children[1]
- self.user_new_prefix_widget.observe(self.changed_use_new_prefix_name, names="value")
+ self.user_new_prefix_widget.observe(
+ self.changed_use_new_prefix_name, names="value"
+ )
self.suffix_box1 = widgets.HBox(
[
- widgets.Label("New suffix File Name", layout=widgets.Layout(width="20%")),
- widgets.Checkbox(value=True, description="Use digit suffix", layout=widgets.Layout(width="30%")),
+ widgets.Label(
+ "New suffix File Name", layout=widgets.Layout(width="20%")
+ ),
+ widgets.Checkbox(
+ value=True,
+ description="Use digit suffix",
+ layout=widgets.Layout(width="30%"),
+ ),
]
)
self.use_digit_suffix_widget = self.suffix_box1.children[1]
- self.suffix_box1.children[1].observe(self.changed_use_digit_suffix_name, names="value")
+ self.suffix_box1.children[1].observe(
+ self.changed_use_digit_suffix_name, names="value"
+ )
self.suffix_box2 = widgets.HBox(
[
widgets.Label("", layout=widgets.Layout(width="20%")),
- widgets.Checkbox(value=False, description="Use new suffix", layout=widgets.Layout(width="20%")),
- widgets.Text(value="", disabled=True, layout=widgets.Layout(width="25%")),
+ widgets.Checkbox(
+ value=False,
+ description="Use new suffix",
+ layout=widgets.Layout(width="20%"),
+ ),
+ widgets.Text(
+ value="", disabled=True, layout=widgets.Layout(width="25%")
+ ),
]
)
- self.suffix_box2.children[2].observe(self.changed_use_new_suffix_name, names="value")
+ self.suffix_box2.children[2].observe(
+ self.changed_use_new_suffix_name, names="value"
+ )
self.user_new_suffix_widget = self.suffix_box2.children[1]
self.new_suffix_text_widget = self.suffix_box2.children[2]
- self.user_new_suffix_widget.observe(self.changed_use_new_suffix_name, names="value")
+ self.user_new_suffix_widget.observe(
+ self.changed_use_new_suffix_name, names="value"
+ )
self.box5 = widgets.HBox(
[
- widgets.Label("New Index Separator", layout=widgets.Layout(width="15%")),
+ widgets.Label(
+ "New Index Separator", layout=widgets.Layout(width="15%")
+ ),
widgets.Text(value="_", layout=widgets.Layout(width=box_text_width)),
]
)
@@ -275,14 +329,18 @@ def show(self):
self.box9 = widgets.HBox(
[
widgets.Label("Extension", layout=widgets.Layout(width="15%")),
- widgets.Text(value=current_ext, layout=widgets.Layout(width=box_text_width)),
+ widgets.Text(
+ value=current_ext, layout=widgets.Layout(width=box_text_width)
+ ),
]
)
self.box6 = widgets.HBox(
[
widgets.Label("New Name Schema: ", layout=widgets.Layout(width="20%")),
- widgets.Label(self.new_naming_schema(), layout=widgets.Layout(width="40%")),
+ widgets.Label(
+ self.new_naming_schema(), layout=widgets.Layout(width="40%")
+ ),
]
)
@@ -310,7 +368,9 @@ def show(self):
accordion.set_title(0, "Current Schema Name")
accordion.set_title(1, "New Naming Schema")
- output_ui_1 = widgets.HBox([widgets.Label("Example of naming: ", layout=widgets.Layout(width="20%"))])
+ output_ui_1 = widgets.HBox(
+ [widgets.Label("Example of naming: ", layout=widgets.Layout(width="20%"))]
+ )
self.output_ui_2 = widgets.HBox(
[
@@ -327,7 +387,9 @@ def show(self):
)
self.output_ui_3.children[1].add_class("result_label")
- vbox = widgets.VBox([accordion, output_ui_1, self.output_ui_2, self.output_ui_3])
+ vbox = widgets.VBox(
+ [accordion, output_ui_1, self.output_ui_2, self.output_ui_3]
+ )
display(vbox)
self.demo_output_file_name()
@@ -335,7 +397,9 @@ def show(self):
self.changed_use_new_prefix_name()
def demo_output_file_name(self):
- input_file = self.get_basename_of_current_dropdown_selected_file(is_with_ext=False)
+ input_file = self.get_basename_of_current_dropdown_selected_file(
+ is_with_ext=False
+ )
self.output_ui_2.children[1].value = input_file
new_name = self.box6.children[1].value
@@ -452,7 +516,12 @@ def generate_new_file_name(
if suffix_flag:
new_name = prefix + new_index_separator + suffix + ext
else:
- new_name = prefix + new_index_separator + "{:0{}}".format(file_index, new_number_of_digits) + ext
+ new_name = (
+ prefix
+ + new_index_separator
+ + "{:0{}}".format(file_index, new_number_of_digits)
+ + ext
+ )
# except ValueError:
# # print(f"Could not parse index from {_name_separated[-1]}")
@@ -484,7 +553,9 @@ def get_dict_old_new_filenames(self):
else:
suffix = ""
- list_of_input_basename_files = [os.path.basename(_file) for _file in list_of_input_files]
+ list_of_input_basename_files = [
+ os.path.basename(_file) for _file in list_of_input_files
+ ]
new_list = {}
for _file_index, _file in enumerate(list_of_input_basename_files):
@@ -511,8 +582,14 @@ def get_dict_old_new_filenames(self):
def check_new_names(self):
dict_old_new_names = self.get_dict_old_new_filenames()
- old_names_new_names = [f"{os.path.basename(_key)} -> {_value}" for _key, _value in dict_old_new_names.items()]
- select_widget = widgets.Select(options=old_names_new_names, layout=widgets.Layout(width="100%", height="400px"))
+ old_names_new_names = [
+ f"{os.path.basename(_key)} -> {_value}"
+ for _key, _value in dict_old_new_names.items()
+ ]
+ select_widget = widgets.Select(
+ options=old_names_new_names,
+ layout=widgets.Layout(width="100%", height="400px"),
+ )
display(select_widget)
def select_export_folder(self):
@@ -527,7 +604,11 @@ def select_export_folder(self):
type="directory",
)
else:
- display(HTML('You need to fix the namig convention first!'))
+ display(
+ HTML(
+ 'You need to fix the namig convention first!'
+ )
+ )
def export(self, selected):
input_folder = os.path.abspath(self.input_folder)
@@ -535,10 +616,14 @@ def export(self, selected):
self.output_folder_ui.shortcut_buttons.close()
dict_old_new_names = self.get_dict_old_new_filenames()
- new_output_folder = os.path.join(os.path.abspath(selected), input_folder_renamed)
+ new_output_folder = os.path.join(
+ os.path.abspath(selected), input_folder_renamed
+ )
utilities.copy_files(
- dict_old_new_names=dict_old_new_names, new_output_folder=new_output_folder, overwrite=False
+ dict_old_new_names=dict_old_new_names,
+ new_output_folder=new_output_folder,
+ overwrite=False,
)
self.new_list_files = dict_old_new_names
diff --git a/notebooks/__code/resonance_fitting/__init__.py b/notebooks/__code/resonance_fitting/__init__.py
index 6accc17d..a60c77f1 100644
--- a/notebooks/__code/resonance_fitting/__init__.py
+++ b/notebooks/__code/resonance_fitting/__init__.py
@@ -44,11 +44,12 @@ class DetectorType:
},
}
-VENUS_RES_FUNC=Path("/SNS/VENUS/shared/instrument/resonance/_fts_bl10_0p5meV_1keV_25pts.txt")
-SAMMY_EXE_PATH=Path("/SNS/software/sammy/bin/sammy")
+VENUS_RES_FUNC = Path(
+ "/SNS/VENUS/shared/instrument/resonance/_fts_bl10_0p5meV_1keV_25pts.txt"
+)
+SAMMY_EXE_PATH = Path("/SNS/software/sammy/bin/sammy")
-class Parent:
+class Parent:
def __init__(self, parent=None):
self.parent = parent
-
\ No newline at end of file
diff --git a/notebooks/__code/resonance_fitting/get.py b/notebooks/__code/resonance_fitting/get.py
index 79e325bb..bc301e6f 100644
--- a/notebooks/__code/resonance_fitting/get.py
+++ b/notebooks/__code/resonance_fitting/get.py
@@ -2,19 +2,18 @@
class Get(Parent):
-
def full_name_of_element_from_abreviation(self, abbreviation: str) -> str:
"""Get the full name of an element from its abbreviation.
Args:
- abbreviation (str): The abbreviation of the element (e.g., 'H' for Hydrogen).
-
+ abbreviation (str): The abbreviation of the element (e.g., 'H' for Hydrogen).
+
Returns:
str: The full name of the element.
"""
dict_elements = self.parent.dict_elements
for _element_name in dict_elements.keys():
- _abbreviation = dict_elements[_element_name]['symbol']
+ _abbreviation = dict_elements[_element_name]["symbol"]
if _abbreviation == abbreviation:
return _element_name
raise ValueError(f"Element with abbreviation '{abbreviation}' not found.")
diff --git a/notebooks/__code/resonance_fitting/normalization_for_timepix.py b/notebooks/__code/resonance_fitting/normalization_for_timepix.py
index 245f8c22..c4d9b694 100644
--- a/notebooks/__code/resonance_fitting/normalization_for_timepix.py
+++ b/notebooks/__code/resonance_fitting/normalization_for_timepix.py
@@ -73,7 +73,9 @@ def _worker(fl):
return (imread(fl).astype(LOAD_DTYPE)).swapaxes(0, 1)
-def load_data_using_multithreading(list_tif: list = None, combine_tof: bool = False) -> np.ndarray:
+def load_data_using_multithreading(
+ list_tif: list = None, combine_tof: bool = False
+) -> np.ndarray:
"""load data using multithreading"""
with mp.Pool(processes=40) as pool:
data = pool.map(_worker, list_tif)
@@ -92,7 +94,9 @@ def retrieve_list_of_tif(folder: str) -> list:
def create_x_axis_file(
- lambda_array: np.ndarray = None, energy_array: np.ndarray = None, output_folder: str = "./"
+ lambda_array: np.ndarray = None,
+ energy_array: np.ndarray = None,
+ output_folder: str = "./",
) -> str:
"""create x axis file with lambda, energy and tof arrays"""
x_axis_data = {
@@ -160,10 +164,16 @@ def normalization_with_list_of_runs(
export_corrected_stack_of_sample_data = export_mode.get("sample_stack", False)
export_corrected_stack_of_ob_data = export_mode.get("ob_stack", False)
- export_corrected_stack_of_normalized_data = export_mode.get("normalized_stack", False)
- export_corrected_integrated_sample_data = export_mode.get("sample_integrated", False)
+ export_corrected_stack_of_normalized_data = export_mode.get(
+ "normalized_stack", False
+ )
+ export_corrected_integrated_sample_data = export_mode.get(
+ "sample_integrated", False
+ )
export_corrected_integrated_ob_data = export_mode.get("ob_integrated", False)
- export_corrected_integrated_normalized_data = export_mode.get("normalized_integrated", False)
+ export_corrected_integrated_normalized_data = export_mode.get(
+ "normalized_integrated", False
+ )
export_x_axis = export_mode.get("x_axis", True)
logging.info(f"{export_corrected_stack_of_sample_data = }")
@@ -181,13 +191,18 @@ def normalization_with_list_of_runs(
nexus_root_path=nexus_path,
)
ob_master_dict, ob_status_metadata = create_master_dict(
- list_run_numbers=ob_run_numbers, data_type=DataType.ob, instrument=instrument, nexus_root_path=nexus_path
+ list_run_numbers=ob_run_numbers,
+ data_type=DataType.ob,
+ instrument=instrument,
+ nexus_root_path=nexus_path,
)
# only for SNAP
if instrument == "SNAP":
for _run in sample_master_dict.keys():
- sample_master_dict[_run][MasterDictKeys.detector_delay_us] = detector_delay_us
+ sample_master_dict[_run][MasterDictKeys.detector_delay_us] = (
+ detector_delay_us
+ )
for _run in ob_master_dict.keys():
ob_master_dict[_run][MasterDictKeys.detector_delay_us] = detector_delay_us
@@ -197,25 +212,32 @@ def normalization_with_list_of_runs(
logging.info(f"loading ob# {_ob_run_number} ... ")
if verbose:
display(HTML(f"Loading ob# {_ob_run_number} ..."))
- ob_master_dict[_ob_run_number][MasterDictKeys.data] = load_data_using_multithreading(
- ob_master_dict[_ob_run_number][MasterDictKeys.list_tif], combine_tof=False
+ ob_master_dict[_ob_run_number][MasterDictKeys.data] = (
+ load_data_using_multithreading(
+ ob_master_dict[_ob_run_number][MasterDictKeys.list_tif],
+ combine_tof=False,
+ )
)
logging.info(f"ob# {_ob_run_number} loaded!")
logging.info(f"{ob_master_dict[_ob_run_number][MasterDictKeys.data].shape = }")
if verbose:
display(HTML(f"ob# {_ob_run_number} loaded!"))
- display(HTML(f"{ob_master_dict[_ob_run_number][MasterDictKeys.data].shape = }"))
+ display(
+ HTML(f"{ob_master_dict[_ob_run_number][MasterDictKeys.data].shape = }")
+ )
if proton_charge_flag:
normalized_by_proton_charge = (
- sample_status_metadata.all_proton_charge_found and ob_status_metadata.all_proton_charge_found
+ sample_status_metadata.all_proton_charge_found
+ and ob_status_metadata.all_proton_charge_found
)
else:
normalized_by_proton_charge = False
if shutter_counts_flag:
normalized_by_shutter_counts = (
- sample_status_metadata.all_shutter_counts_found and ob_status_metadata.all_shutter_counts_found
+ sample_status_metadata.all_shutter_counts_found
+ and ob_status_metadata.all_shutter_counts_found
)
else:
normalized_by_shutter_counts = False
@@ -248,7 +270,9 @@ def normalization_with_list_of_runs(
export_corrected_stack_of_ob_data,
export_corrected_integrated_ob_data,
ob_data_combined,
- spectra_file_name=ob_master_dict[_ob_run_number][MasterDictKeys.spectra_file_name],
+ spectra_file_name=ob_master_dict[_ob_run_number][
+ MasterDictKeys.spectra_file_name
+ ],
)
# load sample images
@@ -256,22 +280,33 @@ def normalization_with_list_of_runs(
logging.info(f"loading sample# {_sample_run_number} ... ")
if verbose:
display(HTML(f"Loading sample# {_sample_run_number} ..."))
- sample_master_dict[_sample_run_number][MasterDictKeys.data] = load_data_using_multithreading(
- sample_master_dict[_sample_run_number][MasterDictKeys.list_tif], combine_tof=False
+ sample_master_dict[_sample_run_number][MasterDictKeys.data] = (
+ load_data_using_multithreading(
+ sample_master_dict[_sample_run_number][MasterDictKeys.list_tif],
+ combine_tof=False,
+ )
)
logging.info(f"sample# {_sample_run_number} loaded!")
- logging.info(f"{sample_master_dict[_sample_run_number][MasterDictKeys.data].shape = }")
+ logging.info(
+ f"{sample_master_dict[_sample_run_number][MasterDictKeys.data].shape = }"
+ )
if verbose:
display(HTML(f"sample# {_sample_run_number} loaded!"))
- display(HTML(f"{sample_master_dict[_sample_run_number][MasterDictKeys.data].shape = }"))
+ display(
+ HTML(
+ f"{sample_master_dict[_sample_run_number][MasterDictKeys.data].shape = }"
+ )
+ )
if correct_chips_alignment_flag:
logging.info("Correcting chips alignment ...")
if verbose:
display(HTML("Correcting chips alignment ..."))
for _sample_run_number in sample_master_dict.keys():
- sample_master_dict[_sample_run_number][MasterDictKeys.data] = correct_chips_alignment(
- sample_master_dict[_sample_run_number][MasterDictKeys.data]
+ sample_master_dict[_sample_run_number][MasterDictKeys.data] = (
+ correct_chips_alignment(
+ sample_master_dict[_sample_run_number][MasterDictKeys.data]
+ )
)
logging.info("Chips alignment corrected!")
if verbose:
@@ -303,17 +338,25 @@ def normalization_with_list_of_runs(
logging.info("**********************************")
if normalized_by_proton_charge:
- proton_charge = sample_master_dict[_sample_run_number][MasterDictKeys.proton_charge]
+ proton_charge = sample_master_dict[_sample_run_number][
+ MasterDictKeys.proton_charge
+ ]
_sample_data = _sample_data / proton_charge
if normalized_by_shutter_counts:
list_shutter_values_for_each_image = produce_list_shutter_for_each_image(
- list_time_spectra=ob_master_dict[_ob_run_number][MasterDictKeys.list_spectra],
- list_shutter_counts=sample_master_dict[_sample_run_number][MasterDictKeys.shutter_counts],
+ list_time_spectra=ob_master_dict[_ob_run_number][
+ MasterDictKeys.list_spectra
+ ],
+ list_shutter_counts=sample_master_dict[_sample_run_number][
+ MasterDictKeys.shutter_counts
+ ],
)
sample_data = []
- for _sample, _shutter_value in zip(_sample_data, list_shutter_values_for_each_image, strict=False):
+ for _sample, _shutter_value in zip(
+ _sample_data, list_shutter_values_for_each_image, strict=False
+ ):
sample_data.append(_sample / _shutter_value)
_sample_data = np.array(sample_data)
@@ -323,14 +366,19 @@ def normalization_with_list_of_runs(
logging.info(f"{ob_data_combined.dtype = }")
# export sample data after correction if requested
- if export_corrected_stack_of_sample_data or export_corrected_integrated_sample_data:
+ if (
+ export_corrected_stack_of_sample_data
+ or export_corrected_integrated_sample_data
+ ):
export_sample_images(
output_folder,
export_corrected_stack_of_sample_data,
export_corrected_integrated_sample_data,
_sample_run_number,
_sample_data,
- spectra_file_name=sample_master_dict[_sample_run_number][MasterDictKeys.spectra_file_name],
+ spectra_file_name=sample_master_dict[_sample_run_number][
+ MasterDictKeys.spectra_file_name
+ ],
)
# _sample_data = np.divide(_sample_data, ob_data_combined, out=np.zeros_like(_sample_data), where=ob_data_combined!=0)
@@ -350,8 +398,12 @@ def normalization_with_list_of_runs(
logging.info(f"{normalized_data[_sample_run_number].shape = }")
logging.info(f"{normalized_data[_sample_run_number].dtype = }")
- detector_delay_us = sample_master_dict[_sample_run_number][MasterDictKeys.detector_delay_us]
- time_spectra = sample_master_dict[_sample_run_number][MasterDictKeys.list_spectra]
+ detector_delay_us = sample_master_dict[_sample_run_number][
+ MasterDictKeys.detector_delay_us
+ ]
+ time_spectra = sample_master_dict[_sample_run_number][
+ MasterDictKeys.list_spectra
+ ]
lambda_array = convert_array_from_time_to_lambda(
time_array=time_spectra,
@@ -374,11 +426,15 @@ def normalization_with_list_of_runs(
if preview:
# display preview of normalized data
- fig, axs1 = plt.subplots(1, 2, figsize=(2 * PLOT_SIZE.width, PLOT_SIZE.height))
+ fig, axs1 = plt.subplots(
+ 1, 2, figsize=(2 * PLOT_SIZE.width, PLOT_SIZE.height)
+ )
sample_data_integrated = np.nanmean(_sample_data, axis=0)
im0 = axs1[0].imshow(sample_data_integrated, cmap="gray")
plt.colorbar(im0, ax=axs1[0])
- axs1[0].set_title(f"Sample data: {_sample_run_number} | detector delay: {detector_delay_us:.2f} us")
+ axs1[0].set_title(
+ f"Sample data: {_sample_run_number} | detector delay: {detector_delay_us:.2f} us"
+ )
sample_integrated1 = np.nansum(_sample_data, axis=1)
sample_integrated = np.nansum(sample_integrated1, axis=1)
@@ -387,7 +443,9 @@ def normalization_with_list_of_runs(
axs1[1].set_ylabel("mean of full image")
plt.tight_layout
- fig, axs2 = plt.subplots(1, 2, figsize=(2 * PLOT_SIZE.width, PLOT_SIZE.height))
+ fig, axs2 = plt.subplots(
+ 1, 2, figsize=(2 * PLOT_SIZE.width, PLOT_SIZE.height)
+ )
ob_data_integrated = np.nanmean(ob_data_combined, axis=0)
im1 = axs2[0].imshow(ob_data_integrated, cmap="gray")
plt.colorbar(im1, ax=axs2[0])
@@ -400,8 +458,12 @@ def normalization_with_list_of_runs(
axs2[1].set_ylabel("mean of full image")
plt.tight_layout()
- fig, axs3 = plt.subplots(1, 2, figsize=(2 * PLOT_SIZE.width, PLOT_SIZE.height))
- normalized_data_integrated = np.nanmean(normalized_data[_sample_run_number], axis=0)
+ fig, axs3 = plt.subplots(
+ 1, 2, figsize=(2 * PLOT_SIZE.width, PLOT_SIZE.height)
+ )
+ normalized_data_integrated = np.nanmean(
+ normalized_data[_sample_run_number], axis=0
+ )
im2 = axs3[0].imshow(normalized_data_integrated, cmap="gray")
plt.colorbar(im2, ax=axs3[0])
axs3[0].set_title(f"Normalized data {_sample_run_number}")
@@ -413,7 +475,9 @@ def normalization_with_list_of_runs(
axs3[1].set_ylabel("mean of full image")
plt.tight_layout()
- fig, axs4 = plt.subplots(1, 2, figsize=(2 * PLOT_SIZE.width, PLOT_SIZE.height))
+ fig, axs4 = plt.subplots(
+ 1, 2, figsize=(2 * PLOT_SIZE.width, PLOT_SIZE.height)
+ )
axs4[0].plot(lambda_array, profile, "*")
axs4[0].set_xlabel("Lambda (A)")
axs4[0].set_ylabel("mean of full image")
@@ -426,24 +490,36 @@ def normalization_with_list_of_runs(
plt.show()
- if export_corrected_integrated_normalized_data or export_corrected_stack_of_normalized_data:
+ if (
+ export_corrected_integrated_normalized_data
+ or export_corrected_stack_of_normalized_data
+ ):
# make up new output folder name
list_ob_runs = list(ob_master_dict.keys())
- str_ob_runs = "_".join([str(_ob_run_number) for _ob_run_number in list_ob_runs])
+ str_ob_runs = "_".join(
+ [str(_ob_run_number) for _ob_run_number in list_ob_runs]
+ )
full_output_folder = os.path.join(
- output_folder, f"normalized_sample_{_sample_run_number}_obs_{str_ob_runs}"
+ output_folder,
+ f"normalized_sample_{_sample_run_number}_obs_{str_ob_runs}",
) # issue for WEI here !
full_output_folder = os.path.abspath(full_output_folder)
os.makedirs(full_output_folder, exist_ok=True)
if export_corrected_integrated_normalized_data:
# making up the integrated sample data
- sample_data_integrated = np.nanmean(normalized_data[_sample_run_number], axis=0)
+ sample_data_integrated = np.nanmean(
+ normalized_data[_sample_run_number], axis=0
+ )
full_file_name = os.path.join(full_output_folder, "integrated.tif")
- logging.info(f"\t -> Exporting integrated normalized data to {full_file_name} ...")
+ logging.info(
+ f"\t -> Exporting integrated normalized data to {full_file_name} ..."
+ )
make_tiff(data=sample_data_integrated, filename=full_file_name)
- logging.info(f"\t -> Exporting integrated normalized data to {full_file_name} is done!")
+ logging.info(
+ f"\t -> Exporting integrated normalized data to {full_file_name} is done!"
+ )
if export_corrected_stack_of_normalized_data:
output_stack_folder = os.path.join(full_output_folder, "stack")
@@ -451,12 +527,20 @@ def normalization_with_list_of_runs(
os.makedirs(output_stack_folder, exist_ok=True)
for _index, _data in enumerate(normalized_data[_sample_run_number]):
- _output_file = os.path.join(output_stack_folder, f"image{_index:04d}.tif")
+ _output_file = os.path.join(
+ output_stack_folder, f"image{_index:04d}.tif"
+ )
make_tiff(data=_data, filename=_output_file)
- logging.info(f"\t -> Exporting normalized data to {output_stack_folder} is done!")
+ logging.info(
+ f"\t -> Exporting normalized data to {output_stack_folder} is done!"
+ )
print(f"Exported normalized tif images are in: {output_stack_folder}!")
- spectra_file = sample_master_dict[_sample_run_number][MasterDictKeys.spectra_file_name]
- logging.info(f"Exported time spectra file {spectra_file} to {output_stack_folder}!")
+ spectra_file = sample_master_dict[_sample_run_number][
+ MasterDictKeys.spectra_file_name
+ ]
+ logging.info(
+ f"Exported time spectra file {spectra_file} to {output_stack_folder}!"
+ )
shutil.copy(spectra_file, output_stack_folder)
# create x-axis file
@@ -475,7 +559,9 @@ def get_detector_offset_from_nexus(nexus_path: str) -> float:
"""get the detector offset from the nexus file"""
with h5py.File(nexus_path, "r") as hdf5_data:
try:
- detector_offset_micros = hdf5_data["entry"]["DASlogs"]["BL10:Det:TH:DSPT1:TIDelay"]["value"][0]
+ detector_offset_micros = hdf5_data["entry"]["DASlogs"][
+ "BL10:Det:TH:DSPT1:TIDelay"
+ ]["value"][0]
except KeyError:
detector_offset_micros = None
return detector_offset_micros
@@ -504,7 +590,9 @@ def export_sample_images(
make_tiff(data=_data, filename=_output_file)
logging.info(f"\t -> Exporting sample data to {output_stack_folder} is done!")
shutil.copy(spectra_file_name, os.path.join(output_stack_folder))
- logging.info(f"\t -> Exporting spectra file {spectra_file_name} to {output_stack_folder} is done!")
+ logging.info(
+ f"\t -> Exporting spectra file {spectra_file_name} to {output_stack_folder} is done!"
+ )
if export_corrected_integrated_sample_data:
# making up the integrated sample data
@@ -512,7 +600,9 @@ def export_sample_images(
full_file_name = os.path.join(sample_output_folder, "integrated.tif")
logging.info(f"\t -> Exporting integrated sample data to {full_file_name} ...")
make_tiff(data=sample_data_integrated, filename=full_file_name)
- logging.info(f"\t -> Exporting integrated sample data to {full_file_name} is done!")
+ logging.info(
+ f"\t -> Exporting integrated sample data to {full_file_name} is done!"
+ )
display(HTML(f"Created folder {output_stack_folder} for sample outputs!"))
@@ -529,10 +619,13 @@ def export_ob_images(
logging.info(f"> Exporting combined ob images to {output_folder} ...")
logging.info(f"\t{ob_run_numbers = }")
list_ob_runs_number_only = [
- str(isolate_run_number_from_full_path(_ob_run_number)) for _ob_run_number in ob_run_numbers
+ str(isolate_run_number_from_full_path(_ob_run_number))
+ for _ob_run_number in ob_run_numbers
]
if len(list_ob_runs_number_only) == 1:
- ob_output_folder = os.path.join(output_folder, f"ob_{list_ob_runs_number_only[0]}")
+ ob_output_folder = os.path.join(
+ output_folder, f"ob_{list_ob_runs_number_only[0]}"
+ )
else:
str_list_ob_runs = "_".join(list_ob_runs_number_only)
ob_output_folder = os.path.join(output_folder, f"ob_{str_list_ob_runs}")
@@ -561,12 +654,16 @@ def export_ob_images(
logging.info(f"\t -> Exporting ob data to {output_stack_folder} is done!")
# copy spectra file to the output folder
shutil.copy(spectra_file_name, os.path.join(output_stack_folder))
- logging.info(f"\t -> Exported spectra file {spectra_file_name} to {output_stack_folder}!")
+ logging.info(
+ f"\t -> Exported spectra file {spectra_file_name} to {output_stack_folder}!"
+ )
display(HTML(f"Created folder {output_stack_folder} for OB outputs!"))
-def normalization(sample_folder=None, ob_folder=None, output_folder="./", verbose=False):
+def normalization(
+ sample_folder=None, ob_folder=None, output_folder="./", verbose=False
+):
pass
@@ -646,7 +743,9 @@ def update_dict_with_shutter_counts(master_dict: dict) -> tuple[dict, bool]:
if _value == "0":
break
list_shutter_counts.append(float(_value))
- master_dict[run_number][MasterDictKeys.shutter_counts] = list_shutter_counts
+ master_dict[run_number][MasterDictKeys.shutter_counts] = (
+ list_shutter_counts
+ )
return master_dict, status_all_shutter_counts_found
@@ -677,7 +776,9 @@ def update_dict_with_proton_charge(master_dict: dict) -> tuple[dict, bool]:
_nexus_path = master_dict[_run_number][MasterDictKeys.nexus_path]
try:
with h5py.File(_nexus_path, "r") as hdf5_data:
- proton_charge = hdf5_data["entry"][MasterDictKeys.proton_charge][0] / 1e12
+ proton_charge = (
+ hdf5_data["entry"][MasterDictKeys.proton_charge][0] / 1e12
+ )
except KeyError:
proton_charge = None
status_all_proton_charge_found = False
@@ -688,7 +789,9 @@ def update_dict_with_proton_charge(master_dict: dict) -> tuple[dict, bool]:
def update_dict_with_list_of_images(master_dict: dict) -> dict:
"""update the master dict with list of images"""
for _run_number in master_dict.keys():
- list_tif = retrieve_list_of_tif(master_dict[_run_number][MasterDictKeys.data_path])
+ list_tif = retrieve_list_of_tif(
+ master_dict[_run_number][MasterDictKeys.data_path]
+ )
master_dict[_run_number][MasterDictKeys.list_tif] = list_tif
@@ -699,7 +802,9 @@ def get_list_run_number(data_folder: str) -> list:
return list_run_number
-def update_dict_with_nexus_full_path(nexus_root_path: str, instrument: str, master_dict: dict) -> dict:
+def update_dict_with_nexus_full_path(
+ nexus_root_path: str, instrument: str, master_dict: dict
+) -> dict:
"""create dict of nexus path for each run number"""
for run_number in master_dict.keys():
master_dict[run_number][MasterDictKeys.nexus_path] = os.path.join(
@@ -717,7 +822,9 @@ def update_with_nexus_metadata(master_dict: dict) -> dict:
def update_dict_with_data_full_path(data_root_path: str, master_dict: dict) -> dict:
"""create dict of data path for each run number"""
for run_number in master_dict.keys():
- master_dict[run_number][MasterDictKeys.data_path] = os.path.join(data_root_path, f"Run_{run_number}")
+ master_dict[run_number][MasterDictKeys.data_path] = os.path.join(
+ data_root_path, f"Run_{run_number}"
+ )
def create_master_dict(
@@ -775,7 +882,9 @@ def create_master_dict(
return master_dict, status_metadata
-def produce_list_shutter_for_each_image(list_time_spectra: list = None, list_shutter_counts: list = None) -> list:
+def produce_list_shutter_for_each_image(
+ list_time_spectra: list = None, list_shutter_counts: list = None
+) -> list:
"""produce list of shutter counts for each image"""
delat_time_spectra = list_time_spectra[1] - list_time_spectra[0]
@@ -785,18 +894,26 @@ def produce_list_shutter_for_each_image(list_time_spectra: list = None, list_shu
logging.info(f"\t{list_index_jump = }")
logging.info(f"\t{list_shutter_counts = }")
- list_shutter_values_for_each_image = np.zeros(len(list_time_spectra), dtype=np.float32)
+ list_shutter_values_for_each_image = np.zeros(
+ len(list_time_spectra), dtype=np.float32
+ )
if len(list_shutter_counts) == 1: # resonance mode
list_shutter_values_for_each_image.fill(list_shutter_counts[0])
return list_shutter_values_for_each_image
- list_shutter_values_for_each_image[0 : list_index_jump[0] + 1].fill(list_shutter_counts[0])
+ list_shutter_values_for_each_image[0 : list_index_jump[0] + 1].fill(
+ list_shutter_counts[0]
+ )
for _index in range(1, len(list_index_jump)):
_start = list_index_jump[_index - 1]
_end = list_index_jump[_index]
- list_shutter_values_for_each_image[_start + 1 : _end + 1].fill(list_shutter_counts[_index])
+ list_shutter_values_for_each_image[_start + 1 : _end + 1].fill(
+ list_shutter_counts[_index]
+ )
- list_shutter_values_for_each_image[list_index_jump[-1] + 1 :] = list_shutter_counts[-1]
+ list_shutter_values_for_each_image[list_index_jump[-1] + 1 :] = list_shutter_counts[
+ -1
+ ]
return list_shutter_values_for_each_image
@@ -817,7 +934,9 @@ def combine_ob_images(
for _ob_run_number in ob_master_dict.keys():
logging.info(f"Combining ob# {_ob_run_number} ...")
- ob_data = np.array(ob_master_dict[_ob_run_number][MasterDictKeys.data], dtype=np.float32)
+ ob_data = np.array(
+ ob_master_dict[_ob_run_number][MasterDictKeys.data], dtype=np.float32
+ )
# get statistics of ob data
data_shape = ob_data.shape
@@ -826,7 +945,9 @@ def combine_ob_images(
number_of_zeros = np.sum(ob_data == 0)
logging.info(f"\t ob data shape: {data_shape}")
logging.info(f"\t Number of zeros in ob data: {number_of_zeros}")
- logging.info(f"\t Percentage of zeros in ob data: {number_of_zeros / (data_shape[0] * nbr_pixels) * 100:.2f}%")
+ logging.info(
+ f"\t Percentage of zeros in ob data: {number_of_zeros / (data_shape[0] * nbr_pixels) * 100:.2f}%"
+ )
logging.info(f"\t Mean of ob data: {np.mean(ob_data)}")
logging.info(f"\t maximum of ob data: {np.max(ob_data)}")
logging.info(f"\t minimum of ob data: {np.min(ob_data)}")
@@ -842,14 +963,20 @@ def combine_ob_images(
logging.info("\t -> Normalized by shutter counts")
list_shutter_values_for_each_image = produce_list_shutter_for_each_image(
- list_time_spectra=ob_master_dict[_ob_run_number][MasterDictKeys.list_spectra],
- list_shutter_counts=ob_master_dict[_ob_run_number][MasterDictKeys.shutter_counts],
+ list_time_spectra=ob_master_dict[_ob_run_number][
+ MasterDictKeys.list_spectra
+ ],
+ list_shutter_counts=ob_master_dict[_ob_run_number][
+ MasterDictKeys.shutter_counts
+ ],
)
logging.info(f"{list_shutter_values_for_each_image.shape = }")
temp_ob_data = np.empty_like(ob_data, dtype=np.float32)
for _index in range(len(list_shutter_values_for_each_image)):
- temp_ob_data[_index] = ob_data[_index] / list_shutter_values_for_each_image[_index]
+ temp_ob_data[_index] = (
+ ob_data[_index] / list_shutter_values_for_each_image[_index]
+ )
logging.info(f"{temp_ob_data.shape = }")
ob_data = temp_ob_data.copy()
@@ -897,9 +1024,15 @@ def combine_ob_images(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
- parser.add_argument("--sample", type=str, nargs=1, help="Full path to sample run number")
- parser.add_argument("--ob", type=str, nargs=1, help="Full path to the ob run number")
- parser.add_argument("--output", type=str, nargs=1, help="Path to the output folder", default="./")
+ parser.add_argument(
+ "--sample", type=str, nargs=1, help="Full path to sample run number"
+ )
+ parser.add_argument(
+ "--ob", type=str, nargs=1, help="Full path to the ob run number"
+ )
+ parser.add_argument(
+ "--output", type=str, nargs=1, help="Path to the output folder", default="./"
+ )
args = parser.parse_args()
logging.info(f"{args = }")
@@ -948,7 +1081,9 @@ def combine_ob_images(
# normalization(sample_folder=sample_folder, ob_folder=ob_folder, output_folder=output_folder)
- print(f"Normalization is done! Check the log file {log_file_name} for more details!")
+ print(
+ f"Normalization is done! Check the log file {log_file_name} for more details!"
+ )
print(f"Exported data to {output_folder}")
# sample = /SNS/VENUS/IPTS-34808/shared/autoreduce/mcp/November17_Sample6_UA_H_Batteries_1_5_Angs_min_30Hz_5C
diff --git a/notebooks/__code/resonance_fitting/normalization_for_timepix1_timepix3.py b/notebooks/__code/resonance_fitting/normalization_for_timepix1_timepix3.py
index 0e59f51b..0d80e774 100644
--- a/notebooks/__code/resonance_fitting/normalization_for_timepix1_timepix3.py
+++ b/notebooks/__code/resonance_fitting/normalization_for_timepix1_timepix3.py
@@ -14,7 +14,6 @@
from IPython.display import HTML, display
from PIL import Image
from skimage.io import imread
-from scipy.ndimage import median_filter
# from enum import Enum
# from scipy.constants import h, c, electron_volt, m_n
@@ -82,7 +81,9 @@ def _worker(fl):
return (imread(fl).astype(LOAD_DTYPE)).swapaxes(0, 1)
-def load_data_using_multithreading(list_tif: list = None, combine_tof: bool = False) -> np.ndarray:
+def load_data_using_multithreading(
+ list_tif: list = None, combine_tof: bool = False
+) -> np.ndarray:
"""load data using multithreading"""
with mp.Pool(processes=40) as pool:
data = pool.map(_worker, list_tif)
@@ -101,7 +102,9 @@ def retrieve_list_of_tif(folder: str) -> list:
def create_x_axis_file(
- lambda_array: np.ndarray = None, energy_array: np.ndarray = None, output_folder: str = "./"
+ lambda_array: np.ndarray = None,
+ energy_array: np.ndarray = None,
+ output_folder: str = "./",
) -> str:
"""create x axis file with lambda, energy and tof arrays"""
x_axis_data = {
@@ -139,6 +142,7 @@ def correct_chips_alignment(data: np.ndarray, config: dict) -> np.ndarray:
# return data_corrected
return data
+
def normalization_with_list_of_full_path(
sample_dict: dict = None,
ob_dict: dict = None,
@@ -208,10 +212,16 @@ def normalization_with_list_of_full_path(
export_corrected_stack_of_sample_data = export_mode.get("sample_stack", False)
export_corrected_stack_of_ob_data = export_mode.get("ob_stack", False)
- export_corrected_stack_of_normalized_data = export_mode.get("normalized_stack", False)
- export_corrected_integrated_sample_data = export_mode.get("sample_integrated", False)
+ export_corrected_stack_of_normalized_data = export_mode.get(
+ "normalized_stack", False
+ )
+ export_corrected_integrated_sample_data = export_mode.get(
+ "sample_integrated", False
+ )
export_corrected_integrated_ob_data = export_mode.get("ob_integrated", False)
- export_corrected_integrated_normalized_data = export_mode.get("normalized_integrated", False)
+ export_corrected_integrated_normalized_data = export_mode.get(
+ "normalized_integrated", False
+ )
export_x_axis = export_mode.get("x_axis", True)
logging.info(f"{export_corrected_stack_of_sample_data = }")
@@ -238,32 +248,40 @@ def normalization_with_list_of_full_path(
logging.info(f"loading ob# {_ob_run_number} ... ")
if verbose:
display(HTML(f"Loading ob# {_ob_run_number} ..."))
- ob_master_dict[_ob_run_number][MasterDictKeys.data] = load_data_using_multithreading(
- ob_master_dict[_ob_run_number][MasterDictKeys.list_tif], combine_tof=False
+ ob_master_dict[_ob_run_number][MasterDictKeys.data] = (
+ load_data_using_multithreading(
+ ob_master_dict[_ob_run_number][MasterDictKeys.list_tif],
+ combine_tof=False,
+ )
)
logging.info(f"ob# {_ob_run_number} loaded!")
logging.info(f"{ob_master_dict[_ob_run_number][MasterDictKeys.data].shape = }")
if verbose:
display(HTML(f"ob# {_ob_run_number} loaded!"))
- display(HTML(f"{ob_master_dict[_ob_run_number][MasterDictKeys.data].shape = }"))
+ display(
+ HTML(f"{ob_master_dict[_ob_run_number][MasterDictKeys.data].shape = }")
+ )
if proton_charge_flag:
normalized_by_proton_charge = (
- sample_status_metadata.all_proton_charge_found and ob_status_metadata.all_proton_charge_found
+ sample_status_metadata.all_proton_charge_found
+ and ob_status_metadata.all_proton_charge_found
)
else:
normalized_by_proton_charge = False
if monitor_counts_flag:
normalized_by_monitor_counts = (
- sample_status_metadata.all_monitor_counts_found and ob_status_metadata.all_monitor_counts_found
+ sample_status_metadata.all_monitor_counts_found
+ and ob_status_metadata.all_monitor_counts_found
)
else:
normalized_by_monitor_counts = False
if shutter_counts_flag:
normalized_by_shutter_counts = (
- sample_status_metadata.all_shutter_counts_found and ob_status_metadata.all_shutter_counts_found
+ sample_status_metadata.all_shutter_counts_found
+ and ob_status_metadata.all_shutter_counts_found
)
else:
normalized_by_shutter_counts = False
@@ -280,9 +298,15 @@ def normalization_with_list_of_full_path(
max_iterations=max_iterations,
)
logging.info(f"{ob_data_combined.shape = }")
- logging.info(f"number of NaN in ob_data_combined data: {np.sum(np.isnan(ob_data_combined))}")
- logging.info(f"number of inf in ob_data_combined data: {np.sum(np.isinf(ob_data_combined))}")
- logging.info(f"number of zeros in ob_data_combined data: {np.sum(ob_data_combined == 0)} ")
+ logging.info(
+ f"number of NaN in ob_data_combined data: {np.sum(np.isnan(ob_data_combined))}"
+ )
+ logging.info(
+ f"number of inf in ob_data_combined data: {np.sum(np.isinf(ob_data_combined))}"
+ )
+ logging.info(
+ f"number of zeros in ob_data_combined data: {np.sum(ob_data_combined == 0)} "
+ )
if verbose:
display(HTML(f"{ob_data_combined.shape = }"))
@@ -291,7 +315,9 @@ def normalization_with_list_of_full_path(
logging.info("Correcting chips alignment ...")
if verbose:
display(HTML("Correcting chips alignment ..."))
- ob_data_combined = correct_chips_alignment(ob_data_combined, correct_chips_alignment_config)
+ ob_data_combined = correct_chips_alignment(
+ ob_data_combined, correct_chips_alignment_config
+ )
logging.info("Chips alignment corrected!")
if verbose:
display(HTML("Chips alignment corrected!"))
@@ -304,7 +330,9 @@ def normalization_with_list_of_full_path(
export_corrected_stack_of_ob_data,
export_corrected_integrated_ob_data,
ob_data_combined,
- spectra_file_name=ob_master_dict[_ob_run_number][MasterDictKeys.spectra_file_name],
+ spectra_file_name=ob_master_dict[_ob_run_number][
+ MasterDictKeys.spectra_file_name
+ ],
)
# load dc images
@@ -312,39 +340,56 @@ def normalization_with_list_of_full_path(
logging.info(f"loading dc# {_dc_run_number} ... ")
if verbose:
display(HTML(f"Loading dc# {_dc_run_number} ..."))
- dc_master_dict[_dc_run_number][MasterDictKeys.data] = load_data_using_multithreading(
- dc_master_dict[_dc_run_number][MasterDictKeys.list_tif], combine_tof=False
+ dc_master_dict[_dc_run_number][MasterDictKeys.data] = (
+ load_data_using_multithreading(
+ dc_master_dict[_dc_run_number][MasterDictKeys.list_tif],
+ combine_tof=False,
+ )
)
logging.info(f"dc# {_dc_run_number} loaded!")
logging.info(f"{dc_master_dict[_dc_run_number][MasterDictKeys.data].shape = }")
if verbose:
display(HTML(f"dc# {_dc_run_number} loaded!"))
- display(HTML(f"{dc_master_dict[_dc_run_number][MasterDictKeys.data].shape = }"))
+ display(
+ HTML(f"{dc_master_dict[_dc_run_number][MasterDictKeys.data].shape = }")
+ )
# combine all ob images
dc_data_combined = combine_dc_images(dc_master_dict)
-
+
# load sample images
for _sample_run_number in sample_master_dict.keys():
logging.info(f"loading sample# {_sample_run_number} ... ")
if verbose:
display(HTML(f"Loading sample# {_sample_run_number} ..."))
- sample_master_dict[_sample_run_number][MasterDictKeys.data] = load_data_using_multithreading(
- sample_master_dict[_sample_run_number][MasterDictKeys.list_tif], combine_tof=False
+ sample_master_dict[_sample_run_number][MasterDictKeys.data] = (
+ load_data_using_multithreading(
+ sample_master_dict[_sample_run_number][MasterDictKeys.list_tif],
+ combine_tof=False,
+ )
)
logging.info(f"sample# {_sample_run_number} loaded!")
- logging.info(f"{sample_master_dict[_sample_run_number][MasterDictKeys.data].shape = }")
+ logging.info(
+ f"{sample_master_dict[_sample_run_number][MasterDictKeys.data].shape = }"
+ )
if verbose:
display(HTML(f"sample# {_sample_run_number} loaded!"))
- display(HTML(f"{sample_master_dict[_sample_run_number][MasterDictKeys.data].shape = }"))
+ display(
+ HTML(
+ f"{sample_master_dict[_sample_run_number][MasterDictKeys.data].shape = }"
+ )
+ )
if correct_chips_alignment_flag:
logging.info("Correcting chips alignment ...")
if verbose:
display(HTML("Correcting chips alignment ..."))
for _sample_run_number in sample_master_dict.keys():
- sample_master_dict[_sample_run_number][MasterDictKeys.data] = correct_chips_alignment(
- sample_master_dict[_sample_run_number][MasterDictKeys.data], correct_chips_alignment_config
+ sample_master_dict[_sample_run_number][MasterDictKeys.data] = (
+ correct_chips_alignment(
+ sample_master_dict[_sample_run_number][MasterDictKeys.data],
+ correct_chips_alignment_config,
+ )
)
logging.info("Chips alignment corrected!")
if verbose:
@@ -369,7 +414,9 @@ def normalization_with_list_of_full_path(
logging.info(f"\t sample data shape: {data_shape}")
logging.info(f"\t data type of _sample_data: {_sample_data.dtype}")
logging.info(f"\t Number of zeros in sample data: {number_of_zeros}")
- logging.info(f"\t Number of nan in sample data: {np.sum(np.isnan(_sample_data))}")
+ logging.info(
+ f"\t Number of nan in sample data: {np.sum(np.isnan(_sample_data))}"
+ )
logging.info(
f"\t Percentage of zeros in sample data: {number_of_zeros / (data_shape[0] * nbr_pixels) * 100:.2f}%"
)
@@ -380,7 +427,9 @@ def normalization_with_list_of_full_path(
if normalized_by_proton_charge:
logging.info("\t -> Normalized by proton charge")
- proton_charge = sample_master_dict[_sample_run_number][MasterDictKeys.proton_charge]
+ proton_charge = sample_master_dict[_sample_run_number][
+ MasterDictKeys.proton_charge
+ ]
logging.info(f"\t\t proton charge: {proton_charge} C")
logging.info(f"\t\t{type(proton_charge) = }")
logging.info(f"\t\tbefore division: {_sample_data.dtype = }")
@@ -389,7 +438,9 @@ def normalization_with_list_of_full_path(
if normalized_by_monitor_counts:
logging.info("\t -> Normalized by monitor counts")
- monitor_counts = sample_master_dict[_sample_run_number][MasterDictKeys.monitor_counts]
+ monitor_counts = sample_master_dict[_sample_run_number][
+ MasterDictKeys.monitor_counts
+ ]
logging.info(f"\t\t monitor counts: {monitor_counts}")
logging.info(f"\t\t{type(monitor_counts) = }")
_sample_data = _sample_data / monitor_counts
@@ -397,12 +448,18 @@ def normalization_with_list_of_full_path(
if normalized_by_shutter_counts:
list_shutter_values_for_each_image = produce_list_shutter_for_each_image(
- list_time_spectra=ob_master_dict[_ob_run_number][MasterDictKeys.list_spectra],
- list_shutter_counts=sample_master_dict[_sample_run_number][MasterDictKeys.shutter_counts],
+ list_time_spectra=ob_master_dict[_ob_run_number][
+ MasterDictKeys.list_spectra
+ ],
+ list_shutter_counts=sample_master_dict[_sample_run_number][
+ MasterDictKeys.shutter_counts
+ ],
)
sample_data = []
- for _sample, _shutter_value in zip(_sample_data, list_shutter_values_for_each_image, strict=False):
+ for _sample, _shutter_value in zip(
+ _sample_data, list_shutter_values_for_each_image, strict=False
+ ):
sample_data.append(_sample / _shutter_value)
_sample_data = np.array(sample_data)
@@ -412,52 +469,74 @@ def normalization_with_list_of_full_path(
logging.info(f"{ob_data_combined.dtype = }")
# export sample data after correction if requested
- if export_corrected_stack_of_sample_data or export_corrected_integrated_sample_data:
+ if (
+ export_corrected_stack_of_sample_data
+ or export_corrected_integrated_sample_data
+ ):
export_sample_images(
output_folder,
export_corrected_stack_of_sample_data,
export_corrected_integrated_sample_data,
_sample_run_number,
_sample_data,
- spectra_file_name=sample_master_dict[_sample_run_number][MasterDictKeys.spectra_file_name],
+ spectra_file_name=sample_master_dict[_sample_run_number][
+ MasterDictKeys.spectra_file_name
+ ],
)
if dc_data_combined is not None:
- logging.info(f"normalization with DC subtraction")
- _normalized_data = np.divide(np.subtract(_sample_data, dc_data_combined), np.subtract(ob_data_combined, dc_data_combined),
- out=np.zeros_like(_sample_data),
- where=(ob_data_combined - dc_data_combined)!=0)
+ logging.info("normalization with DC subtraction")
+ _normalized_data = np.divide(
+ np.subtract(_sample_data, dc_data_combined),
+ np.subtract(ob_data_combined, dc_data_combined),
+ out=np.zeros_like(_sample_data),
+ where=(ob_data_combined - dc_data_combined) != 0,
+ )
else:
- logging.info(f"normalization without DC subtraction")
- _normalized_data = np.divide(_sample_data, ob_data_combined,
- out=np.zeros_like(_sample_data),
- where=ob_data_combined!=0)
-
+ logging.info("normalization without DC subtraction")
+ _normalized_data = np.divide(
+ _sample_data,
+ ob_data_combined,
+ out=np.zeros_like(_sample_data),
+ where=ob_data_combined != 0,
+ )
+
_normalized_data[ob_data_combined == 0] = 0
normalized_data[_sample_run_number] = _normalized_data
# normalized_data[_sample_run_number] = np.array(np.divide(_sample_data, ob_data_combined))
logging.info(f"{normalized_data[_sample_run_number].shape = }")
logging.info(f"{normalized_data[_sample_run_number].dtype = }")
- logging.info(f"number of NaN in normalized data: {np.sum(np.isnan(normalized_data[_sample_run_number]))}")
- logging.info(f"number of inf in normalized data: {np.sum(np.isinf(normalized_data[_sample_run_number]))}")
+ logging.info(
+ f"number of NaN in normalized data: {np.sum(np.isnan(normalized_data[_sample_run_number]))}"
+ )
+ logging.info(
+ f"number of inf in normalized data: {np.sum(np.isinf(normalized_data[_sample_run_number]))}"
+ )
- detector_delay_us = sample_master_dict[_sample_run_number][MasterDictKeys.detector_delay_us]
- time_spectra = sample_master_dict[_sample_run_number][MasterDictKeys.list_spectra]
+ detector_delay_us = sample_master_dict[_sample_run_number][
+ MasterDictKeys.detector_delay_us
+ ]
+ time_spectra = sample_master_dict[_sample_run_number][
+ MasterDictKeys.list_spectra
+ ]
if time_spectra is None:
- logging.info("Time spectra is None, cannot convert to lambda or energy arrays")
+ logging.info(
+ "Time spectra is None, cannot convert to lambda or energy arrays"
+ )
lambda_array = None
energy_array = None
-
- else:
- logging.info(f"We have a time_spectra!")
+ else:
+ logging.info("We have a time_spectra!")
logging.info(f"time spectra shape: {time_spectra.shape}")
-
+
if detector_delay_us is None:
detector_delay_us = 0.0
- logging.info(f"detector delay is None, setting it to {detector_delay_us} us")
+ logging.info(
+ f"detector delay is None, setting it to {detector_delay_us} us"
+ )
logging.info(f"we have a detector delay of {detector_delay_us} us")
@@ -487,26 +566,29 @@ def normalization_with_list_of_full_path(
logging.info(f"Preview: {preview = }")
if preview:
-
# display preview of normalized data
- fig, axs1 = plt.subplots(1, 2, figsize=(2 * PLOT_SIZE.width, PLOT_SIZE.height))
+ fig, axs1 = plt.subplots(
+ 1, 2, figsize=(2 * PLOT_SIZE.width, PLOT_SIZE.height)
+ )
sample_data_integrated = np.nanmean(_sample_data, axis=0)
im0 = axs1[0].imshow(sample_data_integrated, cmap="gray")
plt.colorbar(im0, ax=axs1[0])
display(HTML(f"Preview of run {_sample_run_number}
"))
display(HTML(f"detector delay: {detector_delay_us:.2f} us"))
-
- axs1[0].set_title(f"Integrated Sample data")
+
+ axs1[0].set_title("Integrated Sample data")
sample_integrated1 = np.nansum(_sample_data, axis=1)
sample_integrated = np.nansum(sample_integrated1, axis=1)
- axs1[1].plot(sample_integrated, 'o')
+ axs1[1].plot(sample_integrated, "o")
axs1[1].set_xlabel("File image index")
axs1[1].set_ylabel("mean of full image")
plt.tight_layout()
- fig, axs2 = plt.subplots(1, 2, figsize=(2 * PLOT_SIZE.width, PLOT_SIZE.height))
+ fig, axs2 = plt.subplots(
+ 1, 2, figsize=(2 * PLOT_SIZE.width, PLOT_SIZE.height)
+ )
ob_data_integrated = np.nanmean(ob_data_combined, axis=0)
im1 = axs2[0].imshow(ob_data_integrated, cmap="gray")
plt.colorbar(im1, ax=axs2[0])
@@ -514,13 +596,15 @@ def normalization_with_list_of_full_path(
ob_integrated1 = np.nansum(ob_data_combined, axis=1)
ob_integrated = np.nansum(ob_integrated1, axis=1)
- axs2[1].plot(ob_integrated, 'o')
+ axs2[1].plot(ob_integrated, "o")
axs2[1].set_xlabel("File image index")
axs2[1].set_ylabel("mean of full image")
plt.tight_layout()
if dc_data_combined is not None:
- fig, axs_dc = plt.subplots(1, 2, figsize=(2 * PLOT_SIZE.width, PLOT_SIZE.height))
+ fig, axs_dc = plt.subplots(
+ 1, 2, figsize=(2 * PLOT_SIZE.width, PLOT_SIZE.height)
+ )
dc_data_integrated = np.nanmean(dc_data_combined, axis=0)
im_dc = axs_dc[0].imshow(dc_data_integrated, cmap="gray")
plt.colorbar(im_dc, ax=axs_dc[0])
@@ -528,26 +612,32 @@ def normalization_with_list_of_full_path(
dc_integrated1 = np.nansum(dc_data_combined, axis=1)
dc_integrated = np.nansum(dc_integrated1, axis=1)
- axs_dc[1].plot(dc_integrated, 'o')
+ axs_dc[1].plot(dc_integrated, "o")
axs_dc[1].set_xlabel("File image index")
axs_dc[1].set_ylabel("mean of full image")
plt.tight_layout()
- fig, axs3 = plt.subplots(1, 2, figsize=(2 * PLOT_SIZE.width, PLOT_SIZE.height))
- normalized_data_integrated = np.nanmean(normalized_data[_sample_run_number], axis=0)
+ fig, axs3 = plt.subplots(
+ 1, 2, figsize=(2 * PLOT_SIZE.width, PLOT_SIZE.height)
+ )
+ normalized_data_integrated = np.nanmean(
+ normalized_data[_sample_run_number], axis=0
+ )
im2 = axs3[0].imshow(normalized_data_integrated, cmap="gray")
plt.colorbar(im2, ax=axs3[0])
- axs3[0].set_title(f"Integrated Normalized data")
+ axs3[0].set_title("Integrated Normalized data")
profile_step1 = np.nanmean(normalized_data[_sample_run_number], axis=1)
profile = np.nanmean(profile_step1, axis=1)
- axs3[1].plot(profile, 'o')
+ axs3[1].plot(profile, "o")
axs3[1].set_xlabel("File image index")
axs3[1].set_ylabel("mean of full image")
plt.tight_layout()
if lambda_array is not None:
- fig, axs4 = plt.subplots(1, 2, figsize=(2 * PLOT_SIZE.width, PLOT_SIZE.height))
+ fig, axs4 = plt.subplots(
+ 1, 2, figsize=(2 * PLOT_SIZE.width, PLOT_SIZE.height)
+ )
logging.info(f"{np.shape(profile) = }")
axs4[0].plot(lambda_array, profile, "*")
@@ -562,24 +652,36 @@ def normalization_with_list_of_full_path(
plt.show()
- if export_corrected_integrated_normalized_data or export_corrected_stack_of_normalized_data:
+ if (
+ export_corrected_integrated_normalized_data
+ or export_corrected_stack_of_normalized_data
+ ):
# make up new output folder name
list_ob_runs = list(ob_master_dict.keys())
- str_ob_runs = "_".join([str(_ob_run_number) for _ob_run_number in list_ob_runs])
+ str_ob_runs = "_".join(
+ [str(_ob_run_number) for _ob_run_number in list_ob_runs]
+ )
full_output_folder = os.path.join(
- output_folder, f"normalized_sample_{_sample_run_number}_obs_{str_ob_runs}"
+ output_folder,
+ f"normalized_sample_{_sample_run_number}_obs_{str_ob_runs}",
) # issue for WEI here !
full_output_folder = os.path.abspath(full_output_folder)
os.makedirs(full_output_folder, exist_ok=True)
if export_corrected_integrated_normalized_data:
# making up the integrated sample data
- sample_data_integrated = np.nanmean(normalized_data[_sample_run_number], axis=0)
+ sample_data_integrated = np.nanmean(
+ normalized_data[_sample_run_number], axis=0
+ )
full_file_name = os.path.join(full_output_folder, "integrated.tif")
- logging.info(f"\t -> Exporting integrated normalized data to {full_file_name} ...")
+ logging.info(
+ f"\t -> Exporting integrated normalized data to {full_file_name} ..."
+ )
make_tiff(data=sample_data_integrated, filename=full_file_name)
- logging.info(f"\t -> Exporting integrated normalized data to {full_file_name} is done!")
+ logging.info(
+ f"\t -> Exporting integrated normalized data to {full_file_name} is done!"
+ )
if export_corrected_stack_of_normalized_data:
output_stack_folder = os.path.join(full_output_folder, "stack")
@@ -587,14 +689,22 @@ def normalization_with_list_of_full_path(
os.makedirs(output_stack_folder, exist_ok=True)
for _index, _data in enumerate(normalized_data[_sample_run_number]):
- _output_file = os.path.join(output_stack_folder, f"image{_index:04d}.tif")
+ _output_file = os.path.join(
+ output_stack_folder, f"image{_index:04d}.tif"
+ )
make_tiff(data=_data, filename=_output_file)
- logging.info(f"\t -> Exporting normalized data to {output_stack_folder} is done!")
+ logging.info(
+ f"\t -> Exporting normalized data to {output_stack_folder} is done!"
+ )
print(f"Exported normalized tif images are in: {output_stack_folder}!")
- spectra_file = sample_master_dict[_sample_run_number][MasterDictKeys.spectra_file_name]
+ spectra_file = sample_master_dict[_sample_run_number][
+ MasterDictKeys.spectra_file_name
+ ]
if spectra_file and Path(spectra_file).exists():
- logging.info(f"Exported time spectra file {spectra_file} to {output_stack_folder}!")
+ logging.info(
+ f"Exported time spectra file {spectra_file} to {output_stack_folder}!"
+ )
shutil.copy(spectra_file, output_stack_folder)
# create x-axis file
@@ -613,7 +723,9 @@ def get_detector_offset_from_nexus(nexus_path: str) -> float:
"""get the detector offset from the nexus file"""
with h5py.File(nexus_path, "r") as hdf5_data:
try:
- detector_offset_micros = hdf5_data["entry"]["DASlogs"]["BL10:Det:TH:DSPT1:TIDelay"]["value"][0]
+ detector_offset_micros = hdf5_data["entry"]["DASlogs"][
+ "BL10:Det:TH:DSPT1:TIDelay"
+ ]["value"][0]
except KeyError:
detector_offset_micros = None
return detector_offset_micros
@@ -642,7 +754,9 @@ def export_sample_images(
make_tiff(data=_data, filename=_output_file)
logging.info(f"\t -> Exporting sample data to {output_stack_folder} is done!")
shutil.copy(spectra_file_name, os.path.join(output_stack_folder))
- logging.info(f"\t -> Exporting spectra file {spectra_file_name} to {output_stack_folder} is done!")
+ logging.info(
+ f"\t -> Exporting spectra file {spectra_file_name} to {output_stack_folder} is done!"
+ )
if export_corrected_integrated_sample_data:
# making up the integrated sample data
@@ -650,7 +764,9 @@ def export_sample_images(
full_file_name = os.path.join(sample_output_folder, "integrated.tif")
logging.info(f"\t -> Exporting integrated sample data to {full_file_name} ...")
make_tiff(data=sample_data_integrated, filename=full_file_name)
- logging.info(f"\t -> Exporting integrated sample data to {full_file_name} is done!")
+ logging.info(
+ f"\t -> Exporting integrated sample data to {full_file_name} is done!"
+ )
display(HTML(f"Created folder {output_stack_folder} for sample outputs!"))
@@ -667,10 +783,13 @@ def export_ob_images(
logging.info(f"> Exporting combined ob images to {output_folder} ...")
logging.info(f"\t{ob_run_numbers = }")
list_ob_runs_number_only = [
- str(isolate_run_number_from_full_path(_ob_run_number)) for _ob_run_number in ob_run_numbers
+ str(isolate_run_number_from_full_path(_ob_run_number))
+ for _ob_run_number in ob_run_numbers
]
if len(list_ob_runs_number_only) == 1:
- ob_output_folder = os.path.join(output_folder, f"ob_{list_ob_runs_number_only[0]}")
+ ob_output_folder = os.path.join(
+ output_folder, f"ob_{list_ob_runs_number_only[0]}"
+ )
else:
str_list_ob_runs = "_".join(list_ob_runs_number_only)
ob_output_folder = os.path.join(output_folder, f"ob_{str_list_ob_runs}")
@@ -699,7 +818,9 @@ def export_ob_images(
logging.info(f"\t -> Exporting ob data to {output_stack_folder} is done!")
# copy spectra file to the output folder
shutil.copy(spectra_file_name, os.path.join(output_stack_folder))
- logging.info(f"\t -> Exported spectra file {spectra_file_name} to {output_stack_folder}!")
+ logging.info(
+ f"\t -> Exported spectra file {spectra_file_name} to {output_stack_folder}!"
+ )
display(HTML(f"Created folder {output_stack_folder} for OB outputs!"))
@@ -790,7 +911,9 @@ def update_dict_with_shutter_counts(master_dict: dict) -> tuple[dict, bool]:
if _value == "0":
break
list_shutter_counts.append(float(_value))
- master_dict[run_number][MasterDictKeys.shutter_counts] = list_shutter_counts
+ master_dict[run_number][MasterDictKeys.shutter_counts] = (
+ list_shutter_counts
+ )
return master_dict, status_all_shutter_counts_found
@@ -827,11 +950,15 @@ def update_dict_with_proton_charge(master_dict: dict) -> tuple[dict, bool]:
try:
with h5py.File(_nexus_path, "r") as hdf5_data:
- proton_charge = hdf5_data["entry"][MasterDictKeys.proton_charge][0] / 1e12
+ proton_charge = (
+ hdf5_data["entry"][MasterDictKeys.proton_charge][0] / 1e12
+ )
except KeyError:
proton_charge = None
status_all_proton_charge_found = False
- master_dict[_run_number][MasterDictKeys.proton_charge] = np.float32(proton_charge)
+ master_dict[_run_number][MasterDictKeys.proton_charge] = np.float32(
+ proton_charge
+ )
return status_all_proton_charge_found
@@ -852,14 +979,18 @@ def update_dict_with_monitor_counts(master_dict: dict) -> bool:
except KeyError:
monitor_counts = None
status_all_monitor_counts_found = False
- master_dict[_run_number][MasterDictKeys.monitor_counts] = np.float32(monitor_counts)
+ master_dict[_run_number][MasterDictKeys.monitor_counts] = np.float32(
+ monitor_counts
+ )
return status_all_monitor_counts_found
def update_dict_with_list_of_images(master_dict: dict) -> dict:
"""update the master dict with list of images"""
for _run_number in master_dict.keys():
- list_tif = retrieve_list_of_tif(master_dict[_run_number][MasterDictKeys.data_path])
+ list_tif = retrieve_list_of_tif(
+ master_dict[_run_number][MasterDictKeys.data_path]
+ )
logging.info(f"Retrieved {len(list_tif)} tif files for run {_run_number}!")
master_dict[_run_number][MasterDictKeys.list_tif] = list_tif
@@ -871,7 +1002,9 @@ def get_list_run_number(data_folder: str) -> list:
return list_run_number
-def update_dict_with_nexus_full_path(nexus_root_path: str, instrument: str, master_dict: dict) -> dict:
+def update_dict_with_nexus_full_path(
+ nexus_root_path: str, instrument: str, master_dict: dict
+) -> dict:
"""create dict of nexus path for each run number"""
for run_number in master_dict.keys():
master_dict[run_number][MasterDictKeys.nexus_path] = os.path.join(
@@ -892,7 +1025,9 @@ def update_with_nexus_metadata(master_dict: dict) -> dict:
def update_dict_with_data_full_path(data_root_path: str, master_dict: dict) -> dict:
"""create dict of data path for each run number"""
for run_number in master_dict.keys():
- master_dict[run_number][MasterDictKeys.data_path] = os.path.join(data_root_path, f"Run_{run_number}")
+ master_dict[run_number][MasterDictKeys.data_path] = os.path.join(
+ data_root_path, f"Run_{run_number}"
+ )
def create_master_dict(
@@ -942,7 +1077,9 @@ def create_master_dict(
return master_dict, status_metadata
-def produce_list_shutter_for_each_image(list_time_spectra: list = None, list_shutter_counts: list = None) -> list:
+def produce_list_shutter_for_each_image(
+ list_time_spectra: list = None, list_shutter_counts: list = None
+) -> list:
"""produce list of shutter counts for each image"""
delat_time_spectra = list_time_spectra[1] - list_time_spectra[0]
@@ -952,31 +1089,41 @@ def produce_list_shutter_for_each_image(list_time_spectra: list = None, list_shu
logging.info(f"\t{list_index_jump = }")
logging.info(f"\t{list_shutter_counts = }")
- list_shutter_values_for_each_image = np.zeros(len(list_time_spectra), dtype=np.float32)
+ list_shutter_values_for_each_image = np.zeros(
+ len(list_time_spectra), dtype=np.float32
+ )
if len(list_shutter_counts) == 1: # resonance mode
list_shutter_values_for_each_image.fill(list_shutter_counts[0])
return list_shutter_values_for_each_image
- list_shutter_values_for_each_image[0 : list_index_jump[0] + 1].fill(list_shutter_counts[0])
+ list_shutter_values_for_each_image[0 : list_index_jump[0] + 1].fill(
+ list_shutter_counts[0]
+ )
for _index in range(1, len(list_index_jump)):
_start = list_index_jump[_index - 1]
_end = list_index_jump[_index]
- list_shutter_values_for_each_image[_start + 1 : _end + 1].fill(list_shutter_counts[_index])
+ list_shutter_values_for_each_image[_start + 1 : _end + 1].fill(
+ list_shutter_counts[_index]
+ )
- list_shutter_values_for_each_image[list_index_jump[-1] + 1 :] = list_shutter_counts[-1]
+ list_shutter_values_for_each_image[list_index_jump[-1] + 1 :] = list_shutter_counts[
+ -1
+ ]
return list_shutter_values_for_each_image
-def replace_zero_with_local_median(data: np.ndarray,
- kernel_size: Tuple[int, int, int] = (3, 3, 3),
- max_iterations: int = 10) -> np.ndarray:
+def replace_zero_with_local_median(
+ data: np.ndarray,
+ kernel_size: Tuple[int, int, int] = (3, 3, 3),
+ max_iterations: int = 10,
+) -> np.ndarray:
"""
Replace 0 values in a 3D array using local median filtering.
This function ONLY processes small neighborhoods around 0 pixels,
avoiding expensive computation on the entire dataset.
-
+
Parameters:
-----------
data : np.ndarray
@@ -987,7 +1134,7 @@ def replace_zero_with_local_median(data: np.ndarray,
max_iterations : int
Maximum number of iterations to replace 0 values
Default is 10
-
+
Returns:
--------
np.ndarray
@@ -1006,7 +1153,7 @@ def replace_zero_with_local_median(data: np.ndarray,
# Calculate padding for kernel
pad_h, pad_w, pad_d = [k // 2 for k in kernel_size]
-
+
for iteration in range(max_iterations):
# Find current 0 locations
zero_coords = np.argwhere(result == 0)
@@ -1016,13 +1163,15 @@ def replace_zero_with_local_median(data: np.ndarray,
logging.info(f"All 0 values replaced after {iteration} iterations")
break
- logging.info(f"Iteration {iteration + 1}: {current_zero_count} 0 values remaining")
+ logging.info(
+ f"Iteration {iteration + 1}: {current_zero_count} 0 values remaining"
+ )
# Process each 0 pixel individually
replaced_count = 0
for coord in zero_coords:
y, x, z = coord
-
+
# Define the local neighborhood bounds
y_min = max(0, y - pad_h)
y_max = min(result.shape[0], y + pad_h + 1)
@@ -1030,13 +1179,13 @@ def replace_zero_with_local_median(data: np.ndarray,
x_max = min(result.shape[1], x + pad_w + 1)
z_min = max(0, z - pad_d)
z_max = min(result.shape[2], z + pad_d + 1)
-
+
# Extract the local neighborhood
neighborhood = result[y_min:y_max, x_min:x_max, z_min:z_max]
-
+
# Get non-NaN values in the neighborhood
valid_values = neighborhood[~np.isnan(neighborhood)]
-
+
# If we have valid values, compute median and replace
if len(valid_values) > 0:
median_value = np.median(valid_values)
@@ -1048,30 +1197,34 @@ def replace_zero_with_local_median(data: np.ndarray,
# If no progress was made, break
if replaced_count == 0:
remaining_zero_count = np.sum(result == 0)
- logging.info(f"No progress made. {remaining_zero_count} zero values could not be replaced")
+ logging.info(
+ f"No progress made. {remaining_zero_count} zero values could not be replaced"
+ )
logging.info("(These may be in regions with no valid neighbors)")
break
final_zero_count = np.sum(result == 0)
logging.info(f"Final zero count: {final_zero_count}")
- logging.info(f"Successfully replaced {initial_zero_count - final_zero_count} zero values")
+ logging.info(
+ f"Successfully replaced {initial_zero_count - final_zero_count} zero values"
+ )
return result
def combine_dc_images(dc_master_dict: dict) -> np.ndarray:
"""combine all dc images
-
+
Parameters:
-----------
dc_master_dict : dict
master dict of dc run numbers
-
+
Returns:
--------
np.ndarray
combined dc data
-
+
"""
logging.info("Combining all dark current images")
full_dc_data = []
@@ -1082,7 +1235,9 @@ def combine_dc_images(dc_master_dict: dict) -> np.ndarray:
for _dc_run_number in dc_master_dict.keys():
logging.info(f"Combining dc# {_dc_run_number} ...")
- dc_data = np.array(dc_master_dict[_dc_run_number][MasterDictKeys.data], dtype=np.float32)
+ dc_data = np.array(
+ dc_master_dict[_dc_run_number][MasterDictKeys.data], dtype=np.float32
+ )
full_dc_data.append(dc_data)
logging.info(f"{np.shape(full_dc_data) = }")
@@ -1101,11 +1256,11 @@ def combine_ob_images(
use_shutter_counts: bool = False,
replace_ob_zeros_by_nan: bool = False,
replace_ob_zeros_by_local_median: bool = False,
- kernel_size_for_local_median: Tuple[int, int, int] = (3, 3, 3),
+ kernel_size_for_local_median: Tuple[int, int, int] = (3, 3, 3),
max_iterations: int = 10,
) -> np.ndarray:
"""combine all ob images and correct by proton charge and shutter counts
-
+
Parameters:
-----------
ob_master_dict : dict
@@ -1124,12 +1279,12 @@ def combine_ob_images(
kernel size for local median filtering
max_iterations : int
maximum number of iterations for local median filtering
-
+
Returns:
--------
np.ndarray
combined ob data
-
+
"""
logging.info("Combining all open beam images")
@@ -1137,15 +1292,21 @@ def combine_ob_images(
logging.info(f"\tcorrecting by monitor counts: {use_monitor_counts}")
logging.info(f"\tshutter counts: {use_shutter_counts}")
logging.info(f"\treplace ob zeros by nan: {replace_ob_zeros_by_nan}")
- logging.info(f"\treplace ob zeros by local median: {replace_ob_zeros_by_local_median}")
- logging.info(f"\tkernel size for local median: y:{kernel_size_for_local_median[0]}, "
- f"x:{kernel_size_for_local_median[1]}, "
- f"tof:{kernel_size_for_local_median[2]}")
+ logging.info(
+ f"\treplace ob zeros by local median: {replace_ob_zeros_by_local_median}"
+ )
+ logging.info(
+ f"\tkernel size for local median: y:{kernel_size_for_local_median[0]}, "
+ f"x:{kernel_size_for_local_median[1]}, "
+ f"tof:{kernel_size_for_local_median[2]}"
+ )
full_ob_data_corrected = []
for _ob_run_number in ob_master_dict.keys():
logging.info(f"Combining ob# {_ob_run_number} ...")
- ob_data = np.array(ob_master_dict[_ob_run_number][MasterDictKeys.data], dtype=np.float32)
+ ob_data = np.array(
+ ob_master_dict[_ob_run_number][MasterDictKeys.data], dtype=np.float32
+ )
# get statistics of ob data
data_shape = ob_data.shape
@@ -1154,7 +1315,9 @@ def combine_ob_images(
number_of_zeros = np.sum(ob_data == 0)
logging.info(f"\t ob data shape: {data_shape}")
logging.info(f"\t Number of zeros in ob data: {number_of_zeros}")
- logging.info(f"\t Percentage of zeros in ob data: {number_of_zeros / (data_shape[0] * nbr_pixels) * 100:.2f}%")
+ logging.info(
+ f"\t Percentage of zeros in ob data: {number_of_zeros / (data_shape[0] * nbr_pixels) * 100:.2f}%"
+ )
logging.info(f"\t Mean of ob data: {np.mean(ob_data)}")
logging.info(f"\t maximum of ob data: {np.max(ob_data)}")
logging.info(f"\t minimum of ob data: {np.min(ob_data)}")
@@ -1172,7 +1335,9 @@ def combine_ob_images(
if use_monitor_counts:
logging.info("\t -> Normalized by monitor counts")
- monitor_counts = ob_master_dict[_ob_run_number][MasterDictKeys.monitor_counts]
+ monitor_counts = ob_master_dict[_ob_run_number][
+ MasterDictKeys.monitor_counts
+ ]
logging.info(f"\t\t monitor counts: {monitor_counts}")
logging.info(f"\t\t{type(monitor_counts) = }")
ob_data = ob_data / monitor_counts
@@ -1182,14 +1347,20 @@ def combine_ob_images(
logging.info("\t -> Normalized by shutter counts")
list_shutter_values_for_each_image = produce_list_shutter_for_each_image(
- list_time_spectra=ob_master_dict[_ob_run_number][MasterDictKeys.list_spectra],
- list_shutter_counts=ob_master_dict[_ob_run_number][MasterDictKeys.shutter_counts],
+ list_time_spectra=ob_master_dict[_ob_run_number][
+ MasterDictKeys.list_spectra
+ ],
+ list_shutter_counts=ob_master_dict[_ob_run_number][
+ MasterDictKeys.shutter_counts
+ ],
)
logging.info(f"{list_shutter_values_for_each_image.shape = }")
temp_ob_data = np.empty_like(ob_data, dtype=np.float32)
for _index in range(len(list_shutter_values_for_each_image)):
- temp_ob_data[_index] = ob_data[_index] / list_shutter_values_for_each_image[_index]
+ temp_ob_data[_index] = (
+ ob_data[_index] / list_shutter_values_for_each_image[_index]
+ )
logging.info(f"{temp_ob_data.shape = }")
ob_data = temp_ob_data.copy()
@@ -1197,9 +1368,11 @@ def combine_ob_images(
# logging.info(f"{ob_data_combined.shape = }")
if replace_ob_zeros_by_local_median:
- ob_data = replace_zero_with_local_median(ob_data,
- kernel_size=kernel_size_for_local_median,
- max_iterations=max_iterations)
+ ob_data = replace_zero_with_local_median(
+ ob_data,
+ kernel_size=kernel_size_for_local_median,
+ max_iterations=max_iterations,
+ )
full_ob_data_corrected.append(ob_data)
logging.info(f"{np.shape(full_ob_data_corrected) = }")
@@ -1224,9 +1397,15 @@ def combine_ob_images(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
- parser.add_argument("--sample", type=str, nargs=1, help="Full path to sample run number")
- parser.add_argument("--ob", type=str, nargs=1, help="Full path to the ob run number")
- parser.add_argument("--output", type=str, nargs=1, help="Path to the output folder", default="./")
+ parser.add_argument(
+ "--sample", type=str, nargs=1, help="Full path to sample run number"
+ )
+ parser.add_argument(
+ "--ob", type=str, nargs=1, help="Full path to the ob run number"
+ )
+ parser.add_argument(
+ "--output", type=str, nargs=1, help="Path to the output folder", default="./"
+ )
args = parser.parse_args()
logging.info(f"{args = }")
@@ -1275,7 +1454,9 @@ def combine_ob_images(
# normalization(sample_folder=sample_folder, ob_folder=ob_folder, output_folder=output_folder)
- print(f"Normalization is done! Check the log file {log_file_name} for more details!")
+ print(
+ f"Normalization is done! Check the log file {log_file_name} for more details!"
+ )
print(f"Exported data to {output_folder}")
# sample = /SNS/VENUS/IPTS-34808/shared/autoreduce/mcp/November17_Sample6_UA_H_Batteries_1_5_Angs_min_30Hz_5C
diff --git a/notebooks/__code/resonance_fitting/resonance_fitting.py b/notebooks/__code/resonance_fitting/resonance_fitting.py
index 65fdc9de..1b7d94ee 100644
--- a/notebooks/__code/resonance_fitting/resonance_fitting.py
+++ b/notebooks/__code/resonance_fitting/resonance_fitting.py
@@ -1,7 +1,5 @@
-import glob
from dotenv import load_dotenv
import logging as notebook_logging
-from logging.handlers import RotatingFileHandler
import os
from loguru import logger
from pathlib import Path
@@ -11,16 +9,17 @@
import ipywidgets as widgets
import matplotlib.pyplot as plt
from IPython.display import HTML, display
-from ipywidgets import interactive
-from PIL import Image
import periodictable
import ipysheet
-from ipysheet import sheet, cell, row, column, from_dataframe, to_array, calculation
+from ipysheet import from_dataframe, to_array
# from pleiades.processing.normalization import normalization as normalization_with_pleaides
# from pleiades.processing import Roi as PleiadesRoi
# from pleiades.processing import Facility
-from pleiades.sammy.io.data_manager import convert_csv_to_sammy_twenty, validate_sammy_twenty_format
+from pleiades.sammy.io.data_manager import (
+ convert_csv_to_sammy_twenty,
+ validate_sammy_twenty_format,
+)
from pleiades.sammy.io.json_manager import JsonManager
from pleiades.sammy.io.inp_manager import InpManager
from pleiades.sammy.backends.local import LocalSammyRunner
@@ -29,26 +28,18 @@
from pleiades.sammy.results.manager import ResultsManager
from __code.resonance_fitting import VENUS_RES_FUNC, SAMMY_EXE_PATH
-from __code._utilities.list import extract_list_of_runs_from_string
-from __code._utilities.nexus import extract_file_path_from_nexus
from __code._utilities.logger import display_dictionary_in_logging
# from __code.ipywe.myfileselector import MyFileSelectorPanel
-from __code.resonance_fitting.config import DEBUG_DATA, timepix1_config, timepix3_config
+from __code.resonance_fitting.config import DEBUG_DATA
from __code.resonance_fitting.get import Get
from __code.normalization_tof.normalization_tof import NormalizationTof
from __code.ipywe.fileselector import FileSelectorPanel as FileSelectorPanel
-from __code.normalization_tof import DetectorType, autoreduce_dir, distance_source_detector_m, raw_dir
-from __code.normalization_tof.normalization_for_timepix1_timepix3 import (
- load_data_using_multithreading,
- # normalization,
- normalization_with_list_of_full_path,
- retrieve_list_of_tif,
-)
FONT_SIZE = 14
+
class FilesPaths:
logging = None
transmission = None
@@ -56,6 +47,7 @@ class FilesPaths:
json_path = None
sammy_files_multi_mode = None
+
class FolderPaths:
working = None
stagging = None
@@ -69,18 +61,17 @@ class FolderPaths:
class ResonanceFitting(NormalizationTof):
-
df_to_use = None
- horizontal_box = None # total abundance display box
+ horizontal_box = None # total abundance display box
def __init__(self, working_dir=None, debug=False):
self.folder_paths = FolderPaths()
self.files_paths = FilesPaths()
-
+
self.initialize_logging()
load_dotenv(".envrc")
-
+
if debug:
self.folder_paths.working = Path(DEBUG_DATA.working_dir)
self.folder_paths.output = Path(DEBUG_DATA.output_folder)
@@ -105,7 +96,9 @@ def __init__(self, working_dir=None, debug=False):
# self.autoreduce_dir = autoreduce_dir[_beamline][0] + str(ipts) + autoreduce_dir[_beamline][1]
# self.shared_dir = str(Path(shared_dir[self.instrument][0]) / str(ipts) / shared_dir[self.instrument][1])
- self.folder_paths.shared = Path("/") / _facility / self.instrument / str(ipts) / "shared"
+ self.folder_paths.shared = (
+ Path("/") / _facility / self.instrument / str(ipts) / "shared"
+ )
notebook_logging.info(f"Instrument: {self.instrument}")
notebook_logging.info(f"Working dir: {self.folder_paths.working}")
@@ -116,15 +109,17 @@ def __init__(self, working_dir=None, debug=False):
def initialize_logging(self):
- logger.remove() # Remove default logger
+ logger.remove() # Remove default logger
LOG_PATH = "/SNS/VENUS/shared/log/"
base_file_name = Path(__file__).name
file_name_without_extension = Path(base_file_name).stem
user_name = os.getlogin() # add user name to the log file name
- log_file_name = LOG_PATH / Path(f"{user_name}_{str(file_name_without_extension)}.log")
+ log_file_name = LOG_PATH / Path(
+ f"{user_name}_{str(file_name_without_extension)}.log"
+ )
self.files_paths.logging = log_file_name
-
+
# rotating_handler = RotatingFileHandler(log_file_name,
# maxBytes=50*1024*1024, # 50 MB
# backupCount=5)
@@ -140,8 +135,14 @@ def initialize_logging(self):
format="[%(levelname)s] - %(asctime)s - %(message)s",
level=notebook_logging.INFO,
)
- notebook_logging.info(f"*** Starting a new script {file_name_without_extension} ***")
- display(HTML(f"Log file: {log_file_name}"))
+ notebook_logging.info(
+ f"*** Starting a new script {file_name_without_extension} ***"
+ )
+ display(
+ HTML(
+ f"Log file: {log_file_name}"
+ )
+ )
def select_normalized_text_file(self):
self.file_selector = FileSelectorPanel(
@@ -169,7 +170,7 @@ def select_isotope_and_abundance(self):
list_elements = periodictable.elements
dict_elements = {}
for _el in list_elements:
- dict_elements[_el.name.capitalize()] = {'symbol': _el.symbol}
+ dict_elements[_el.name.capitalize()] = {"symbol": _el.symbol}
list_elements_names = list(dict_elements.keys())
list_elements_names.sort()
self.dict_elements = dict_elements
@@ -177,13 +178,17 @@ def select_isotope_and_abundance(self):
if self.debug:
default_symbol_selected = DEBUG_DATA.isotope_element
for _el_name in dict_elements.keys():
- if dict_elements[_el_name]['symbol'] == default_symbol_selected:
+ if dict_elements[_el_name]["symbol"] == default_symbol_selected:
default_element_selected = _el_name
break
else:
default_element_selected = "Hydrogen"
- display(HTML(f"Select element/isotopes to use:"))
+ display(
+ HTML(
+ f"Select element/isotopes to use:"
+ )
+ )
self.list_elements_widget = widgets.Dropdown(
options=list_elements_names,
value=default_element_selected,
@@ -191,12 +196,12 @@ def select_isotope_and_abundance(self):
disabled=False,
)
display(self.list_elements_widget)
- self.list_elements_widget.observe(self._on_element_change, names='value')
-
+ self.list_elements_widget.observe(self._on_element_change, names="value")
+
self._display_tables_and_buttons()
# empty stylesheet table for now
- _df = pd.DataFrame({'Isotope': [None], 'Abundance (%)': [0]})
+ _df = pd.DataFrame({"Isotope": [None], "Abundance (%)": [0]})
self.isotope_to_use_sheet = from_dataframe(_df)
self.df_to_use = _df
display(self.isotope_to_use_sheet)
@@ -210,8 +215,12 @@ def perform_fitting(self):
self._sammy_files_multi_mode()
self._local_sammy_config()
self._multi_isotope_sammy_execution()
-
- display(HTML(f"SAMMY input files created in: {self.folder_paths.sammy_working}!") )
+
+ display(
+ HTML(
+ f"SAMMY input files created in: {self.folder_paths.sammy_working}!"
+ )
+ )
def display_results(self):
self._results_analysis()
@@ -226,7 +235,11 @@ def _output_folder_selected(self, folder_path):
def _transmitted_text_file_selected(self, file_path):
file_path = Path(file_path)
notebook_logging.info(f"Transmitted text file selected: {file_path}")
- display(HTML(f"Transmission file: {file_path.name} ... selected!"))
+ display(
+ HTML(
+ f"Transmission file: {file_path.name} ... selected!"
+ )
+ )
self.files_paths.transmission = file_path
@@ -234,31 +247,39 @@ def _transmitted_text_file_selected(self, file_path):
def _display_transmitted_data(self):
notebook_logging.info("Displaying transmitted data ...")
- df = pd.read_csv(self.files_paths.transmission,
- delim_whitespace=True,
- names=['Energy (eV)', 'Transmission', 'Uncertainty'],
- index_col=False,
- skiprows=1)
- display(HTML(f"Transmitted data preview:"))
+ df = pd.read_csv(
+ self.files_paths.transmission,
+ delim_whitespace=True,
+ names=["Energy (eV)", "Transmission", "Uncertainty"],
+ index_col=False,
+ skiprows=1,
+ )
+ display(
+ HTML(
+ f"Transmitted data preview:"
+ )
+ )
display(df.head(10))
-
+
fig, ax = plt.subplots(figsize=(10, 6))
- ax.errorbar(df['Energy (eV)'],
- df['Transmission'],
- yerr=df['Uncertainty'],
- fmt='o',
- markersize=3,
- label=str(self.files_paths.transmission.name),
- color='blue',
- ecolor='lightgray',
- elinewidth=1,
- capsize=2)
- ax.set_xlabel('Energy (eV)')
- ax.set_xscale('log')
- ax.set_yscale('log')
+ ax.errorbar(
+ df["Energy (eV)"],
+ df["Transmission"],
+ yerr=df["Uncertainty"],
+ fmt="o",
+ markersize=3,
+ label=str(self.files_paths.transmission.name),
+ color="blue",
+ ecolor="lightgray",
+ elinewidth=1,
+ capsize=2,
+ )
+ ax.set_xlabel("Energy (eV)")
+ ax.set_xscale("log")
+ ax.set_yscale("log")
ax.grid(True, which="both", ls="--", lw=0.5)
- ax.set_ylabel('Transmission')
- ax.set_title(f'Transmitted Data with Uncertainty')
+ ax.set_ylabel("Transmission")
+ ax.set_title("Transmitted Data with Uncertainty")
ax.legend()
plt.show()
@@ -279,32 +300,64 @@ def _stagging_folders_setup(self, file_path):
Path(self.folder_paths.sammy_working).mkdir(parents=True, exist_ok=True)
Path(self.folder_paths.sammy_output).mkdir(parents=True, exist_ok=True)
-
- notebook_logging.info("\nStagging folders setup:")
- notebook_logging.info(f"output folder: {self.folder_paths.output} ... {self.folder_paths.output.is_dir()} ")
- notebook_logging.info(f"Stagging folder: {self.folder_paths.stagging} ... {self.folder_paths.stagging.is_dir()}")
- notebook_logging.info(f"Spectra folder: {self.folder_paths.spectra} ... {self.folder_paths.spectra.is_dir()}")
- notebook_logging.info(f"Twenty folder: {self.folder_paths.twenty} ... {self.folder_paths.twenty.is_dir()}")
- notebook_logging.info(f"SAMMY working folder: {self.folder_paths.sammy_working} ... {self.folder_paths.sammy_working.is_dir()}")
- notebook_logging.info(f"SAMMY output folder: {self.folder_paths.sammy_output} ... {self.folder_paths.sammy_output.is_dir()}")
- display(HTML(f"Stagging folders created!"))
+ notebook_logging.info("\nStagging folders setup:")
+ notebook_logging.info(
+ f"output folder: {self.folder_paths.output} ... {self.folder_paths.output.is_dir()} "
+ )
+ notebook_logging.info(
+ f"Stagging folder: {self.folder_paths.stagging} ... {self.folder_paths.stagging.is_dir()}"
+ )
+ notebook_logging.info(
+ f"Spectra folder: {self.folder_paths.spectra} ... {self.folder_paths.spectra.is_dir()}"
+ )
+ notebook_logging.info(
+ f"Twenty folder: {self.folder_paths.twenty} ... {self.folder_paths.twenty.is_dir()}"
+ )
+ notebook_logging.info(
+ f"SAMMY working folder: {self.folder_paths.sammy_working} ... {self.folder_paths.sammy_working.is_dir()}"
+ )
+ notebook_logging.info(
+ f"SAMMY output folder: {self.folder_paths.sammy_output} ... {self.folder_paths.sammy_output.is_dir()}"
+ )
+ display(
+ HTML(
+ f"Stagging folders created!"
+ )
+ )
notebook_logging.info("")
def _converting_transmission_to_twenty_format(self):
- notebook_logging.info("Converting transmission data .txt to .twenty format for SAMMY ...")
- twenty_file = self.folder_paths.twenty / self.files_paths.transmission.name.replace(".txt", ".twenty")
+ notebook_logging.info(
+ "Converting transmission data .txt to .twenty format for SAMMY ..."
+ )
+ twenty_file = (
+ self.folder_paths.twenty
+ / self.files_paths.transmission.name.replace(".txt", ".twenty")
+ )
convert_csv_to_sammy_twenty(self.files_paths.transmission, twenty_file)
if validate_sammy_twenty_format(twenty_file):
- notebook_logging.info(f"Conversion successful! Twenty file created at: {twenty_file}")
- display(HTML(f"Twenty file created at: {twenty_file}"))
+ notebook_logging.info(
+ f"Conversion successful! Twenty file created at: {twenty_file}"
+ )
+ display(
+ HTML(
+ f"Twenty file created at: {twenty_file}"
+ )
+ )
else:
- notebook_logging.error("Conversion failed! The generated .twenty file is not valid.")
- display(HTML(f"Conversion failed! The generated .twenty file is not valid."))
+ notebook_logging.error(
+ "Conversion failed! The generated .twenty file is not valid."
+ )
+ display(
+ HTML(
+ f"Conversion failed! The generated .twenty file is not valid."
+ )
+ )
def _on_element_change(self, change):
notebook_logging.info(f"Element selected: {change['new']}")
self.isotope_sheet.close()
- element_symbol = self.dict_elements[change['new']]['symbol']
+ element_symbol = self.dict_elements[change["new"]]["symbol"]
self._create_and_display_isotope_table(element_symbol=element_symbol)
self.isotope_to_use_sheet.close()
@@ -321,16 +374,15 @@ def _on_element_change(self, change):
def _get_dict_isotopes(self, element_symbol):
"""
Get a dictionary of isotopes and their abundances for a given element.
-
+
dict = {[isotope_name]: {'abundance': None, 'mass': None}}
-
+
return dict
"""
# element = periodictable.elements.symbol(element_name)
_dict = {}
for _el in getattr(periodictable, element_symbol):
- _dict[str(_el)] = {'abundance': _el.abundance,
- 'mass': _el.mass}
+ _dict[str(_el)] = {"abundance": _el.abundance, "mass": _el.mass}
notebook_logging.info(f"in get_dict_isotopes: {element_symbol = }, {_dict = }")
return _dict
@@ -342,8 +394,10 @@ def _create_and_display_isotope_table(self, element_symbol):
list_isotopes_for_this_element = dict_isotopes.keys()
notebook_logging.info(f"{list_isotopes_for_this_element}")
# list_mass_isotopes = [dict_isotopes[iso]['mass'] for iso in list_isotopes_for_this_element]
- list_abundance_isotopes = [dict_isotopes[iso]['abundance'] for iso in list_isotopes_for_this_element]
-
+ list_abundance_isotopes = [
+ dict_isotopes[iso]["abundance"] for iso in list_isotopes_for_this_element
+ ]
+
# create a boolean array of the same length as list_isotopes_for_this_element
list_use_it = np.array([False for _ in list_isotopes_for_this_element])
@@ -351,10 +405,12 @@ def _create_and_display_isotope_table(self, element_symbol):
if value > 0:
list_use_it[_index] = True
- temp_dict = {'Isotope': np.array(list_isotopes_for_this_element),
- 'Abundance (%)': np.array(list_abundance_isotopes),
- 'use it': list_use_it}
-
+ temp_dict = {
+ "Isotope": np.array(list_isotopes_for_this_element),
+ "Abundance (%)": np.array(list_abundance_isotopes),
+ "use it": list_use_it,
+ }
+
df = pd.DataFrame(temp_dict)
self.isotope_sheet = from_dataframe(df)
@@ -370,27 +426,39 @@ def on_validate_isotope_selection(self, b):
array = to_array(self.isotope_sheet)
notebook_logging.info(f"Isotope selection as array:\n{array}")
-
+
for _index, row in enumerate(array):
- notebook_logging.info(f"at {_index =}, {row[0] = }, {row[1] = }, {row[2] = }")
+ notebook_logging.info(
+ f"at {_index =}, {row[0] = }, {row[1] = }, {row[2] = }"
+ )
# retrieve the content of the isotope_to_use_sheet
df_to_use = ipysheet.to_dataframe(self.isotope_to_use_sheet)
# remove any row with 'Isotope' = None
- df_to_use = df_to_use[df_to_use['Isotope'].notna()]
+ df_to_use = df_to_use[df_to_use["Isotope"].notna()]
notebook_logging.info(f"Current isotopes to use:\n{df_to_use}")
# add it the new isotopes selected with 'use it' = True
for _index, row in enumerate(array):
notebook_logging.info(f"Processing row {_index}: {row}, {row[2] =}")
- if str(row[2]) == 'True': # 'use it' is True
+ if str(row[2]) == "True": # 'use it' is True
isotope_name = row[0]
abundance = f"{float(str(row[1])):.4f}"
- notebook_logging.info(f"Adding isotope: {isotope_name} with abundance: {abundance}")
- df_to_use = pd.concat([df_to_use, pd.DataFrame({'Isotope': [isotope_name], 'Abundance (%)': [abundance]})], ignore_index=True)
-
- # remove duplicates
- self.df_to_use = df_to_use.drop_duplicates(subset='Isotope')
+ notebook_logging.info(
+ f"Adding isotope: {isotope_name} with abundance: {abundance}"
+ )
+ df_to_use = pd.concat(
+ [
+ df_to_use,
+ pd.DataFrame(
+ {"Isotope": [isotope_name], "Abundance (%)": [abundance]}
+ ),
+ ],
+ ignore_index=True,
+ )
+
+ # remove duplicates
+ self.df_to_use = df_to_use.drop_duplicates(subset="Isotope")
self.isotope_to_use_sheet.close()
self.validate_isotope_button.close()
@@ -400,15 +468,15 @@ def on_validate_isotope_selection(self, b):
# listen to all events in this table
for cell in self.isotope_to_use_sheet.cells:
- cell.observe(self._on_isotope_to_use_table_change, names='value')
+ cell.observe(self._on_isotope_to_use_table_change, names="value")
self._display_tables_and_buttons()
display(self.isotope_to_use_sheet)
-
+
self._update_total_abundance_of_isotopes_to_use()
# disable button (to make sure only 1 element is added at a time)
- # self.validate_isotope_button.disabled = True
+ # self.validate_isotope_button.disabled = True
def _on_isotope_to_use_table_change(self, change):
self._update_total_abundance_of_isotopes_to_use()
@@ -419,10 +487,12 @@ def _update_total_abundance_of_isotopes_to_use(self):
self.horizontal_box.close()
df_to_use = ipysheet.to_dataframe(self.isotope_to_use_sheet)
- list_abundances = df_to_use['Abundance (%)'].tolist()
+ list_abundances = df_to_use["Abundance (%)"].tolist()
list_abundances_float = [float(_value) for _value in list_abundances]
total_abundance = sum(list_abundances_float)
- notebook_logging.info(f"Total abundance of isotopes to use: {total_abundance} %")
+ notebook_logging.info(
+ f"Total abundance of isotopes to use: {total_abundance} %"
+ )
if total_abundance > 100.0:
color = "red"
@@ -436,16 +506,15 @@ def _update_total_abundance_of_isotopes_to_use(self):
display(self.horizontal_box)
def _display_tables_and_buttons(self):
- """display the isotope table. the button to validate the selection as well as the table of isotopes to use
- """
-
+ """display the isotope table. the button to validate the selection as well as the table of isotopes to use"""
+
dict_elements = self.dict_elements
full_name_of_element = self.list_elements_widget.value
- element_symbol = dict_elements[full_name_of_element]['symbol']
+ element_symbol = dict_elements[full_name_of_element]["symbol"]
self._create_and_display_isotope_table(element_symbol=element_symbol)
-
+
self.validate_isotope_button = widgets.Button(
description="Add to list of elements/isotopes to consider",
layout=widgets.Layout(width="100%"),
@@ -464,11 +533,11 @@ def _reformat_list_isotopes(self, list_isotopes):
"""
list_reformatted = []
for _iso in list_isotopes:
- if '-' not in _iso:
+ if "-" not in _iso:
list_reformatted.append(_iso)
continue
-
- parts = _iso.split('-')
+
+ parts = _iso.split("-")
if len(parts) == 2:
reformatted = f"{parts[1]}-{parts[0]}"
list_reformatted.append(reformatted)
@@ -486,10 +555,10 @@ def _create_json_manager(self):
# retrieve isotopes and abundances to use
df_to_use = ipysheet.to_dataframe(self.isotope_to_use_sheet)
- list_isotopes = df_to_use['Isotope'].tolist()
+ list_isotopes = df_to_use["Isotope"].tolist()
list_isotopes_reformatted = self._reformat_list_isotopes(list_isotopes)
- list_abundances = df_to_use['Abundance (%)'].tolist()
- list_abundances_float = [float(_value)*0.01 for _value in list_abundances]
+ list_abundances = df_to_use["Abundance (%)"].tolist()
+ list_abundances_float = [float(_value) * 0.01 for _value in list_abundances]
notebook_logging.info(f"\t{list_isotopes = }")
notebook_logging.info(f"\t{list_isotopes_reformatted =}")
@@ -501,19 +570,29 @@ def _create_json_manager(self):
isotopes=list_isotopes_reformatted,
abundances=list_abundances_float,
working_dir=self.folder_paths.stagging,
- custom_global_settings={"forceRMoore": "yes",
- "purgeSpinGroups": "yes",
- "fudge": "0.7"}
+ custom_global_settings={
+ "forceRMoore": "yes",
+ "purgeSpinGroups": "yes",
+ "fudge": "0.7",
+ },
)
self.files_paths.json_path = json_path
notebook_logging.info(f"Configuration file created at: {json_path}")
- endf_files = [f for f in os.listdir(self.folder_paths.stagging) if f.endswith('.par')]
- notebook_logging.info(f"ENDf files found in working directory: {len(endf_files)} files")
+ endf_files = [
+ f for f in os.listdir(self.folder_paths.stagging) if f.endswith(".par")
+ ]
+ notebook_logging.info(
+ f"ENDf files found in working directory: {len(endf_files)} files"
+ )
for f in sorted(endf_files):
notebook_logging.info(f"\t- {f}")
- display(HTML(f"Configuration file created at: {json_path}"))
+ display(
+ HTML(
+ f"Configuration file created at: {json_path}"
+ )
+ )
notebook_logging.info("")
def _setup_element_manager(self):
@@ -526,88 +605,125 @@ def _setup_element_manager(self):
if _float_abundance > max_abundance:
max_abundance = _float_abundance
most_abundant_isotope = _element
-
- notebook_logging.info(f"Most abundant isotope selected: {most_abundant_isotope}")
- mass_number_str, element_symbol = most_abundant_isotope.split('-')
+ notebook_logging.info(
+ f"Most abundant isotope selected: {most_abundant_isotope}"
+ )
+
+ mass_number_str, element_symbol = most_abundant_isotope.split("-")
my_periodic_table_element = getattr(periodictable, element_symbol)
self.most_abundant_element_symbol = element_symbol
- display(HTML(f"Most Abundant Element Selected: {element_symbol}"))
+ display(
+ HTML(
+ f"Most Abundant Element Selected: {element_symbol}"
+ )
+ )
label_width = "160px"
text_width = "80px"
# mass number of the element selected
- _label_left = widgets.HTML("Mass number:
",
- layout=widgets.Layout(width=label_width))
- self.mass_number_widget = widgets.IntText(value=int(mass_number_str),
- disabled=False,
- layout=widgets.Layout(width=text_width))
- _hori_layout_1 = widgets.HBox([_label_left,
- self.mass_number_widget])
+ _label_left = widgets.HTML(
+ "Mass number:
",
+ layout=widgets.Layout(width=label_width),
+ )
+ self.mass_number_widget = widgets.IntText(
+ value=int(mass_number_str),
+ disabled=False,
+ layout=widgets.Layout(width=text_width),
+ )
+ _hori_layout_1 = widgets.HBox([_label_left, self.mass_number_widget])
display(_hori_layout_1)
# density (g/cm^3)
-
- _label_left = widgets.HTML("Density (g/cm3):
",
- layout=widgets.Layout(width=label_width))
- self.density_widget = widgets.FloatText(value=my_periodic_table_element.density,
- disabled=False,
- layout=widgets.Layout(width=text_width))
+
+ _label_left = widgets.HTML(
+ "Density (g/cm3):
",
+ layout=widgets.Layout(width=label_width),
+ )
+ self.density_widget = widgets.FloatText(
+ value=my_periodic_table_element.density,
+ disabled=False,
+ layout=widgets.Layout(width=text_width),
+ )
_hori_layout_2 = widgets.HBox([_label_left, self.density_widget])
display(_hori_layout_2)
# thickness (mm)
- _label_left = widgets.HTML("Thickness (mm):
",
- layout=widgets.Layout(width=label_width))
- self.thickness_widget = widgets.FloatText(value=0.05,
- disabled=False,
- layout=widgets.Layout(width=text_width))
+ _label_left = widgets.HTML(
+ "Thickness (mm):
",
+ layout=widgets.Layout(width=label_width),
+ )
+ self.thickness_widget = widgets.FloatText(
+ value=0.05, disabled=False, layout=widgets.Layout(width=text_width)
+ )
_hori_layout_3 = widgets.HBox([_label_left, self.thickness_widget])
display(_hori_layout_3)
# atomic mass amu
- _label_left = widgets.HTML("Atomic mass (amu):
",
- layout=widgets.Layout(width=label_width))
- self.atomic_mass_widget = widgets.FloatText(value=my_periodic_table_element.mass,
- disabled=False,
- layout=widgets.Layout(width=text_width))
+ _label_left = widgets.HTML(
+ "Atomic mass (amu):
",
+ layout=widgets.Layout(width=label_width),
+ )
+ self.atomic_mass_widget = widgets.FloatText(
+ value=my_periodic_table_element.mass,
+ disabled=False,
+ layout=widgets.Layout(width=text_width),
+ )
_hori_layout_4 = widgets.HBox([_label_left, self.atomic_mass_widget])
- display(_hori_layout_4)
+ display(_hori_layout_4)
# abundance (%)
- _label_left = widgets.HTML("Abundance (%):
",
- layout=widgets.Layout(width=label_width))
- self.abundance_widget = widgets.FloatSlider(value=100.0, min=0, max=100, step=0.1, disabled=False)
+ _label_left = widgets.HTML(
+ "Abundance (%):
",
+ layout=widgets.Layout(width=label_width),
+ )
+ self.abundance_widget = widgets.FloatSlider(
+ value=100.0, min=0, max=100, step=0.1, disabled=False
+ )
_hori_layout_5 = widgets.HBox([_label_left, self.abundance_widget])
display(_hori_layout_5)
# energy range (ev)
- _label_left = widgets.HTML("Energy range (eV):
",
- layout=widgets.Layout(width=label_width))
- self.energy_range_widget = widgets.FloatRangeSlider(value=[1.0, 200.0], min=0, max=2000, step=0.1, disabled=False)
+ _label_left = widgets.HTML(
+ "Energy range (eV):
",
+ layout=widgets.Layout(width=label_width),
+ )
+ self.energy_range_widget = widgets.FloatRangeSlider(
+ value=[1.0, 200.0], min=0, max=2000, step=0.1, disabled=False
+ )
_hori_layout_6 = widgets.HBox([_label_left, self.energy_range_widget])
display(_hori_layout_6)
# temperature (K)
- _label_left = widgets.HTML("Temperature (K):
",
- layout=widgets.Layout(width=label_width))
- self.temperature_widget = widgets.FloatSlider(value=293.6, min=0, max=1000, step=0.1, disabled=False)
+ _label_left = widgets.HTML(
+ "Temperature (K):
",
+ layout=widgets.Layout(width=label_width),
+ )
+ self.temperature_widget = widgets.FloatSlider(
+ value=293.6, min=0, max=1000, step=0.1, disabled=False
+ )
_hori_layout_7 = widgets.HBox([_label_left, self.temperature_widget])
display(_hori_layout_7)
# title
- _label_left = widgets.HTML("Title:
",
- layout=widgets.Layout(width=label_width))
+ _label_left = widgets.HTML(
+ "Title:
",
+ layout=widgets.Layout(width=label_width),
+ )
o_get = Get(parent=self)
- _element_name = o_get.full_name_of_element_from_abreviation(self.most_abundant_element_symbol)
+ _element_name = o_get.full_name_of_element_from_abreviation(
+ self.most_abundant_element_symbol
+ )
_ipts = self.ipts
_instrument = self.instrument
_title = f"{_element_name} multi-isotope transmission analysis - {_instrument} {_ipts}"
- self.title_widget = widgets.Text(value=_title,
- disabled=False,
- layout=widgets.Layout(width="100%"))
- _hori_layout_8 = widgets.HBox([_label_left, self.title_widget], layout=widgets.Layout(width="100%"))
+ self.title_widget = widgets.Text(
+ value=_title, disabled=False, layout=widgets.Layout(width="100%")
+ )
+ _hori_layout_8 = widgets.HBox(
+ [_label_left, self.title_widget], layout=widgets.Layout(width="100%")
+ )
display(_hori_layout_8)
def _create_multi_isotope_inp(self):
@@ -626,18 +742,19 @@ def _create_multi_isotope_inp(self):
title = self.title_widget.value
material_props = {
- 'element': _element,
- 'mass_number': mass_number,
- 'density_g_cm3': density,
- 'thickness_mm': thickness,
- 'atomic_mass_amu': atomic_mass,
- 'abundance': abundance,
- 'min_energy_eV': min_energy,
- 'max_energy_eV': max_energy,
- 'temperature_K': temperature}
-
- notebook_logging.info(f"calling InpManager.create_multi_isotope_inp ...")
- notebook_logging.info(f"material_props:")
+ "element": _element,
+ "mass_number": mass_number,
+ "density_g_cm3": density,
+ "thickness_mm": thickness,
+ "atomic_mass_amu": atomic_mass,
+ "abundance": abundance,
+ "min_energy_eV": min_energy,
+ "max_energy_eV": max_energy,
+ "temperature_K": temperature,
+ }
+
+ notebook_logging.info("calling InpManager.create_multi_isotope_inp ...")
+ notebook_logging.info("material_props:")
display_dictionary_in_logging(material_props)
inp_file = self.folder_paths.stagging / "hf_fitting.inp"
self.files_paths.inp_file = inp_file
@@ -653,13 +770,18 @@ def _create_multi_isotope_inp(self):
)
notebook_logging.info(f"SAMMY input file created at: {inp_file}")
- notebook_logging.info(f"")
+ notebook_logging.info("")
def _sammy_files_multi_mode(self):
- notebook_logging.info("Creating SAMMY files for multi-isotope resonance fitting ...")
+ notebook_logging.info(
+ "Creating SAMMY files for multi-isotope resonance fitting ..."
+ )
transmission_file_path = self.files_paths.transmission.name
notebook_logging.info(f"\t{transmission_file_path = }")
- data_file = self.folder_paths.twenty / f"{transmission_file_path.replace('.txt', '.twenty')}"
+ data_file = (
+ self.folder_paths.twenty
+ / f"{transmission_file_path.replace('.txt', '.twenty')}"
+ )
notebook_logging.info(f"\t{data_file = }")
notebook_logging.info(f"\tjson-config: {self.files_paths.json_path = }")
@@ -667,11 +789,13 @@ def _sammy_files_multi_mode(self):
input_file=self.files_paths.inp_file,
json_config_file=self.files_paths.json_path,
data_file=data_file,
- endf_directory=self.folder_paths.stagging
+ endf_directory=self.folder_paths.stagging,
)
self.files_paths.sammy_files_multi_mode = files
notebook_logging.info(f"\t{files = }")
- notebook_logging.info("SAMMY files for multi-isotope resonance fitting created.")
+ notebook_logging.info(
+ "SAMMY files for multi-isotope resonance fitting created."
+ )
notebook_logging.info("")
def _local_sammy_config(self):
@@ -683,9 +807,11 @@ def _local_sammy_config(self):
notebook_logging.info(f"\t{working_directory = }")
notebook_logging.info(f"\t{output_directory = }")
- config = LocalSammyConfig(sammy_executable=sammy_executable,
- working_dir=working_directory,
- output_dir=output_directory)
+ config = LocalSammyConfig(
+ sammy_executable=sammy_executable,
+ working_dir=working_directory,
+ output_dir=output_directory,
+ )
notebook_logging.info(f"\t{config = }")
self.runner = LocalSammyRunner(config=config)
@@ -693,22 +819,32 @@ def _local_sammy_config(self):
notebook_logging.info("")
def _multi_isotope_sammy_execution(self):
- notebook_logging.info("Starting multi-isotope SAMMY resonance fitting execution ...")
+ notebook_logging.info(
+ "Starting multi-isotope SAMMY resonance fitting execution ..."
+ )
notebook_logging.info(f"\t{self.files_paths.sammy_files_multi_mode = }")
self.runner.prepare_environment(self.files_paths.sammy_files_multi_mode)
result = self.runner.execute_sammy(self.files_paths.sammy_files_multi_mode)
notebook_logging.info(f"\tresult: {result =}")
-
+
notebook_logging.info("SAMMY resonance fitting execution completed.")
notebook_logging.info(f"Execution status: {result.success}")
notebook_logging.info(f"Runtime: {result.runtime_seconds} seconds")
-
+
if result.error_message:
notebook_logging.error(f"Error message: {result.error_message}")
- display(HTML(f"Error during SAMMY execution: {result.error_message}") )
+ display(
+ HTML(
+ f"Error during SAMMY execution: {result.error_message}"
+ )
+ )
else:
- display(HTML(f"SAMMY execution completed successfully!") )
-
+ display(
+ HTML(
+ f"SAMMY execution completed successfully!"
+ )
+ )
+
self.runner.collect_outputs(result=result)
self.runner.cleanup()
@@ -721,20 +857,33 @@ def _results_analysis(self):
lst_file_path = self.folder_paths.sammy_output / "SAMMY.LST"
self.results_manager = ResultsManager(
- lpt_file_path=lpt_file_path,
- lst_file_path=lst_file_path
+ lpt_file_path=lpt_file_path, lst_file_path=lst_file_path
)
data = self.results_manager.get_data()
# self.results_manager
- notebook_logging.info(f"\t energy range: {data.energy.min():.3e} eV to {data.energy.max():.3e} eV")
+ notebook_logging.info(
+ f"\t energy range: {data.energy.min():.3e} eV to {data.energy.max():.3e} eV"
+ )
notebook_logging.info(f"\t data points: {len(data.energy)}")
- display(HTML(f"Results summary:"))
- display(HTML(f" Energy range: {data.energy.min():.3e} eV to {data.energy.max():.3e} eV"))
- display(HTML(f" Data points: {len(data.energy)}"))
+ display(
+ HTML(
+ f"Results summary:"
+ )
+ )
+ display(
+ HTML(
+ f" Energy range: {data.energy.min():.3e} eV to {data.energy.max():.3e} eV"
+ )
+ )
+ display(
+ HTML(
+ f" Data points: {len(data.energy)}"
+ )
+ )
fig = self.results_manager.plot_transmission(
figsize=(12, 8),
@@ -753,52 +902,69 @@ def _results_analysis(self):
notebook_logging.info("")
def _multi_isotope_fitting_quality_metrics(self):
-
+
results_manager = self.results_manager
-
+
if results_manager.run_results.fit_results:
print(f"Fit iterations: {len(results_manager.run_results.fit_results)}")
-
+
for i, fit_result in enumerate(results_manager.run_results.fit_results):
- print(f"\nIteration {i+1}:")
-
+ print(f"\nIteration {i + 1}:")
+
chi_sq = fit_result.get_chi_squared_results()
if chi_sq.chi_squared is not None:
print(f" Chi-squared: {chi_sq.chi_squared:.4f}")
print(f" Data points: {chi_sq.dof}")
print(f" Reduced chi-squared: {chi_sq.reduced_chi_squared:.6f}")
-
+
physics = fit_result.get_physics_data()
- if hasattr(physics, 'broadening_parameters'):
+ if hasattr(physics, "broadening_parameters"):
broadening = physics.broadening_parameters
- if hasattr(broadening, 'thick') and broadening.thick is not None:
+ if hasattr(broadening, "thick") and broadening.thick is not None:
print(f" Number density: {broadening.thick:.6e} atoms/barn-cm")
print(f" Temperature: {broadening.temp:.2f} K")
-
+
# Multi-isotope abundances
nuclear = fit_result.get_nuclear_data()
- if hasattr(nuclear, 'isotopes') and nuclear.isotopes:
+ if hasattr(nuclear, "isotopes") and nuclear.isotopes:
print("\n Isotopic abundances:")
- hf_isotopes = ["Hf-174", "Hf-176", "Hf-177", "Hf-178", "Hf-179", "Hf-180"]
- natural_abundances = [0.0016, 0.0526, 0.1860, 0.2728, 0.1362, 0.3508]
-
+ hf_isotopes = [
+ "Hf-174",
+ "Hf-176",
+ "Hf-177",
+ "Hf-178",
+ "Hf-179",
+ "Hf-180",
+ ]
+ natural_abundances = [
+ 0.0016,
+ 0.0526,
+ 0.1860,
+ 0.2728,
+ 0.1362,
+ 0.3508,
+ ]
+
for j, isotope in enumerate(nuclear.isotopes):
- if j < len(hf_isotopes) and hasattr(isotope, 'abundance'):
+ if j < len(hf_isotopes) and hasattr(isotope, "abundance"):
fitted = isotope.abundance
natural = natural_abundances[j]
ratio = fitted / natural if natural > 0 else 0
- print(f" {hf_isotopes[j]}: fitted={fitted:.6f}, natural={natural:.4f}, ratio={ratio:.3f}")
+ print(
+ f" {hf_isotopes[j]}: fitted={fitted:.6f}, natural={natural:.4f}, ratio={ratio:.3f}"
+ )
# Final results
if len(results_manager.run_results.fit_results) > 0:
final_fit = results_manager.run_results.fit_results[-1]
final_chi = final_fit.get_chi_squared_results()
final_phys = final_fit.get_physics_data()
-
+
print("\nFinal multi-isotope fit results:")
if final_chi.reduced_chi_squared:
print(f" Reduced chi-squared: {final_chi.reduced_chi_squared:.6f}")
- if hasattr(final_phys, 'broadening_parameters'):
- if hasattr(final_phys.broadening_parameters, 'thick'):
- print(f" Number density: {final_phys.broadening_parameters.thick:.6e} atoms/barn-cm")
-
\ No newline at end of file
+ if hasattr(final_phys, "broadening_parameters"):
+ if hasattr(final_phys.broadening_parameters, "thick"):
+ print(
+ f" Number density: {final_phys.broadening_parameters.thick:.6e} atoms/barn-cm"
+ )
diff --git a/notebooks/__code/resonance_fitting/units.py b/notebooks/__code/resonance_fitting/units.py
index 8acb982f..43c1bc96 100644
--- a/notebooks/__code/resonance_fitting/units.py
+++ b/notebooks/__code/resonance_fitting/units.py
@@ -135,7 +135,9 @@ def convert_to_cross_section(from_unit, to_unit):
return conversion_factors[from_unit] / conversion_factors[to_unit]
-def convert_from_wavelength_to_energy_ev(wavelength, unit_from=DistanceUnitOptions.angstrom):
+def convert_from_wavelength_to_energy_ev(
+ wavelength, unit_from=DistanceUnitOptions.angstrom
+):
"""Convert wavelength to energy based on the given units.
Args:
@@ -177,15 +179,21 @@ def convert_array_from_time_to_lambda(
np.ndarray: Array of wavelength values.
"""
time_array_s = time_array * convert_time_units(time_unit, TimeUnitOptions.s)
- detector_offset_s = detector_offset * convert_time_units(detector_offset_unit, TimeUnitOptions.s)
+ detector_offset_s = detector_offset * convert_time_units(
+ detector_offset_unit, TimeUnitOptions.s
+ )
distance_source_detector_m = distance_source_detector * convert_distance_units(
distance_source_detector_unit, DistanceUnitOptions.m
)
h_over_mn = h / m_n
- lambda_m = h_over_mn * (time_array_s + detector_offset_s) / distance_source_detector_m
+ lambda_m = (
+ h_over_mn * (time_array_s + detector_offset_s) / distance_source_detector_m
+ )
- lambda_converted = lambda_m * convert_distance_units(DistanceUnitOptions.m, lambda_unit)
+ lambda_converted = lambda_m * convert_distance_units(
+ DistanceUnitOptions.m, lambda_unit
+ )
return lambda_converted
@@ -225,13 +233,22 @@ def convert_array_from_time_to_energy(
detector_units_factor = convert_time_units(detector_offset_unit, TimeUnitOptions.s)
detector_offset = detector_units_factor * detector_offset
- distance_source_detector_factor = convert_distance_units(distance_source_detector_unit, DistanceUnitOptions.m)
- distance_source_detector_m = distance_source_detector * distance_source_detector_factor
+ distance_source_detector_factor = convert_distance_units(
+ distance_source_detector_unit, DistanceUnitOptions.m
+ )
+ distance_source_detector_m = (
+ distance_source_detector * distance_source_detector_factor
+ )
# Calculate the energy in eV using the formula E_ev = 1/2 m_n (L/t_tof)^2 / electron_volt
full_time_array_s = time_array_s + detector_offset
- energy_array_ev = 0.5 * m_n * (distance_source_detector_m / full_time_array_s) ** 2 / electron_volt
+ energy_array_ev = (
+ 0.5
+ * m_n
+ * (distance_source_detector_m / full_time_array_s) ** 2
+ / electron_volt
+ )
energy_array_factor = convert_to_energy(EnergyUnitOptions.eV, energy_unit)
energy_array = energy_array_ev * energy_array_factor
diff --git a/notebooks/__code/roi_selection_ui.py b/notebooks/__code/roi_selection_ui.py
index 492ae61a..642bd886 100755
--- a/notebooks/__code/roi_selection_ui.py
+++ b/notebooks/__code/roi_selection_ui.py
@@ -7,7 +7,13 @@
from IPython.display import HTML, display
from NeuNorm.normalization import Normalization
from qtpy import QtGui
-from qtpy.QtWidgets import QMainWindow, QProgressBar, QTableWidgetItem, QTableWidgetSelectionRange, QVBoxLayout
+from qtpy.QtWidgets import (
+ QMainWindow,
+ QProgressBar,
+ QTableWidgetItem,
+ QTableWidgetSelectionRange,
+ QVBoxLayout,
+)
from __code import load_ui
from __code.config import (
@@ -65,7 +71,9 @@ def __init__(
self.list_of_files = list_of_files
if percentage_of_data_to_use is None:
- percentage_of_data_to_use = percentage_of_images_to_use_for_roi_selection
+ percentage_of_data_to_use = (
+ percentage_of_images_to_use_for_roi_selection
+ )
self.percentage_of_data_to_use = percentage_of_data_to_use
# method called when leaving the application, if any
@@ -73,7 +81,8 @@ def __init__(
super(QMainWindow, self).__init__(parent)
ui_full_path = os.path.join(
- os.path.dirname(os.path.dirname(__file__)), os.path.join("ui", "ui_roi_selection.ui")
+ os.path.dirname(os.path.dirname(__file__)),
+ os.path.join("ui", "ui_roi_selection.ui"),
)
self.ui = load_ui(ui_full_path, baseinstance=self)
@@ -134,7 +143,9 @@ def __built_html_table_row_3_columns(self, name, nbr, height, width):
def recap(self):
"""Display nbr of files loaded and size. This can be used to figure why a normalization failed"""
- [nbr_sample, height_sample, width_sample] = self.__get_recap(self.o_norm.data["sample"]["data"])
+ [nbr_sample, height_sample, width_sample] = self.__get_recap(
+ self.o_norm.data["sample"]["data"]
+ )
[nbr_ob, height_ob, width_ob] = self.__get_recap(self.o_norm.data["ob"]["data"])
[nbr_df, height_df, width_df] = self.__get_recap(self.o_norm.data["df"]["data"])
@@ -142,7 +153,9 @@ def recap(self):
'| Type | Number | '
+ "Size (height*width) |
"
)
- html += self.__built_html_table_row_3_columns("sample", nbr_sample, height_sample, width_sample)
+ html += self.__built_html_table_row_3_columns(
+ "sample", nbr_sample, height_sample, width_sample
+ )
html += self.__built_html_table_row_3_columns("ob", nbr_ob, height_ob, width_ob)
html += self.__built_html_table_row_3_columns("df", nbr_df, height_df, width_df)
html += "
"
@@ -169,7 +182,9 @@ def integrate_images(self):
random_list = random.sample(range(0, nbr_files), nbr_files_to_use)
if self.o_norm:
- list_data_to_use = [self.o_norm.data["sample"]["data"][_index] for _index in random_list]
+ list_data_to_use = [
+ self.o_norm.data["sample"]["data"][_index] for _index in random_list
+ ]
else:
o_norm = Normalization()
list_of_files = np.array(self.list_of_files)
@@ -367,7 +382,9 @@ def roi_manually_moved(self):
_roi = list_roi[_row]
roi_id = _roi["id"]
- region = roi_id.getArraySlice(self.integrated_image, self.ui.image_view.imageItem)
+ region = roi_id.getArraySlice(
+ self.integrated_image, self.ui.image_view.imageItem
+ )
x0 = region[0][0].start
x1 = region[0][0].stop
@@ -441,7 +458,9 @@ def add_roi_button_clicked(self):
width_int = np.abs(x0_int - int(_x1))
height_int = np.abs(y0_int - int(_y1))
- _roi_id = self.init_roi(x0=x0_int, y0=y0_int, width=width_int, height=height_int)
+ _roi_id = self.init_roi(
+ x0=x0_int, y0=y0_int, width=width_int, height=height_int
+ )
_roi["id"] = _roi_id
list_roi[_row] = _roi
diff --git a/notebooks/__code/roi_statistics_vs_stack/display.py b/notebooks/__code/roi_statistics_vs_stack/display.py
index 2111f2e4..36b8c1bf 100755
--- a/notebooks/__code/roi_statistics_vs_stack/display.py
+++ b/notebooks/__code/roi_statistics_vs_stack/display.py
@@ -26,7 +26,8 @@ def update_image_view(self, slider_value=0):
if not first_update:
_histo_widget.setLevels(
- self.parent.image_view_histogram_level[0], self.parent.image_view_histogram_level[1]
+ self.parent.image_view_histogram_level[0],
+ self.parent.image_view_histogram_level[1],
)
def get_x_axis(self):
@@ -43,27 +44,37 @@ def update_statistics_plot(self):
nbr_plot = 0
if self.parent.ui.mean_checkBox.isChecked():
y_axis_mean = self.parent.y_axis["mean"]
- self.parent.statistics_plot.axes.plot(x_axis, y_axis_mean, "bv", label="mean")
+ self.parent.statistics_plot.axes.plot(
+ x_axis, y_axis_mean, "bv", label="mean"
+ )
nbr_plot += 1
if self.parent.ui.min_checkBox.isChecked():
y_axis_mean = self.parent.y_axis["min"]
- self.parent.statistics_plot.axes.plot(x_axis, y_axis_mean, "r*", label="min")
+ self.parent.statistics_plot.axes.plot(
+ x_axis, y_axis_mean, "r*", label="min"
+ )
nbr_plot += 1
if self.parent.ui.max_checkBox.isChecked():
y_axis_mean = self.parent.y_axis["max"]
- self.parent.statistics_plot.axes.plot(x_axis, y_axis_mean, "r+", label="max")
+ self.parent.statistics_plot.axes.plot(
+ x_axis, y_axis_mean, "r+", label="max"
+ )
nbr_plot += 1
if self.parent.ui.median_checkBox.isChecked():
y_axis_mean = self.parent.y_axis["median"]
- self.parent.statistics_plot.axes.plot(x_axis, y_axis_mean, "gp", label="median")
+ self.parent.statistics_plot.axes.plot(
+ x_axis, y_axis_mean, "gp", label="median"
+ )
nbr_plot += 1
if self.parent.ui.std_checkBox.isChecked():
y_axis_mean = self.parent.y_axis["std"]
- self.parent.statistics_plot.axes.plot(x_axis, y_axis_mean, "cx", label="std")
+ self.parent.statistics_plot.axes.plot(
+ x_axis, y_axis_mean, "cx", label="std"
+ )
nbr_plot += 1
if nbr_plot > 0:
diff --git a/notebooks/__code/roi_statistics_vs_stack/event_handler.py b/notebooks/__code/roi_statistics_vs_stack/event_handler.py
index f7b08ada..e6c0d976 100755
--- a/notebooks/__code/roi_statistics_vs_stack/event_handler.py
+++ b/notebooks/__code/roi_statistics_vs_stack/event_handler.py
@@ -10,7 +10,9 @@ def __init__(self, parent=None):
self.parent = parent
def recalculate_table(self):
- region = self.parent.ui.roi.getArraySlice(self.parent.live_image, self.parent.ui.image_view.imageItem)
+ region = self.parent.ui.roi.getArraySlice(
+ self.parent.live_image, self.parent.ui.image_view.imageItem
+ )
x0 = region[0][0].start
x1 = region[0][0].stop - 1
@@ -62,10 +64,24 @@ def update_table(self):
o_table = TableHandler(table_ui=self.parent.ui.tableWidget)
for _row in data_dict.keys():
_entry = data_dict[_row]
- o_table.insert_item(row=_row, column=StatisticsColumnIndex.min, value=_entry["min"], editable=False)
- o_table.insert_item(row=_row, column=StatisticsColumnIndex.max, value=_entry["max"], editable=False)
o_table.insert_item(
- row=_row, column=StatisticsColumnIndex.mean, value=_entry["mean"], format_str="{:0.2f}", editable=False
+ row=_row,
+ column=StatisticsColumnIndex.min,
+ value=_entry["min"],
+ editable=False,
+ )
+ o_table.insert_item(
+ row=_row,
+ column=StatisticsColumnIndex.max,
+ value=_entry["max"],
+ editable=False,
+ )
+ o_table.insert_item(
+ row=_row,
+ column=StatisticsColumnIndex.mean,
+ value=_entry["mean"],
+ format_str="{:0.2f}",
+ editable=False,
)
o_table.insert_item(
row=_row,
@@ -75,7 +91,11 @@ def update_table(self):
editable=False,
)
o_table.insert_item(
- row=_row, column=StatisticsColumnIndex.std, value=_entry["std"], format_str="{:0.2f}", editable=False
+ row=_row,
+ column=StatisticsColumnIndex.std,
+ value=_entry["std"],
+ format_str="{:0.2f}",
+ editable=False,
)
def reset_table_plot(self):
diff --git a/notebooks/__code/roi_statistics_vs_stack/export.py b/notebooks/__code/roi_statistics_vs_stack/export.py
index 62373bd8..2430f1cb 100755
--- a/notebooks/__code/roi_statistics_vs_stack/export.py
+++ b/notebooks/__code/roi_statistics_vs_stack/export.py
@@ -14,12 +14,16 @@ def __init__(self, parent=None):
def export(self):
base_folder = os.path.basename(self.parent.working_folder)
_export_folder = QFileDialog.getExistingDirectory(
- self.parent, directory=os.path.dirname(base_folder), caption="Select Output Folder"
+ self.parent,
+ directory=os.path.dirname(base_folder),
+ caption="Select Output Folder",
)
if _export_folder:
output_base_file_name = str(base_folder) + "_statistics.txt"
- full_output_base_file_name = os.path.join(_export_folder, output_base_file_name)
+ full_output_base_file_name = os.path.join(
+ _export_folder, output_base_file_name
+ )
x_axis = self.parent.x_axis
time_offset_array = x_axis["time_offset"]
@@ -37,10 +41,13 @@ def export(self):
metadata = ["# Statistics created with roi_statistics_vs_stack notebook"]
metadata.append(f"# working dir: {self.parent.working_folder}")
metadata.append(
- f"# roi selected: x0:{roi['x0']}, y0:{roi['y0']}, " f"width:{roi['width']}, height:{roi['height']}"
+ f"# roi selected: x0:{roi['x0']}, y0:{roi['y0']}, "
+ f"width:{roi['width']}, height:{roi['height']}"
)
metadata.append("#")
- metadata.append("#file index, file name, time offset (s), min, max, mean, median, standard deviation")
+ metadata.append(
+ "#file index, file name, time offset (s), min, max, mean, median, standard deviation"
+ )
data = []
for _row in np.arange(len(list_of_images)):
@@ -53,12 +60,26 @@ def export(self):
_median = median_array[_row]
_std = std_array[_row]
- _row = [_file_index, _file_name, _time_offset, _min, _max, _mean, _median, _std]
+ _row = [
+ _file_index,
+ _file_name,
+ _time_offset,
+ _min,
+ _max,
+ _mean,
+ _median,
+ _std,
+ ]
_row_str = [str(_entry) for _entry in _row]
_row_str_formatted = ",".join(_row_str)
data.append(_row_str_formatted)
- make_ascii_file(metadata=metadata, data=data, output_file_name=full_output_base_file_name, dim="1d")
+ make_ascii_file(
+ metadata=metadata,
+ data=data,
+ output_file_name=full_output_base_file_name,
+ dim="1d",
+ )
show_status_message(
parent=self.parent,
diff --git a/notebooks/__code/roi_statistics_vs_stack/initialization.py b/notebooks/__code/roi_statistics_vs_stack/initialization.py
index ee192c66..e101bb7f 100755
--- a/notebooks/__code/roi_statistics_vs_stack/initialization.py
+++ b/notebooks/__code/roi_statistics_vs_stack/initialization.py
@@ -36,7 +36,9 @@ def pyqtgraph(self):
y0 = roi["y0"]
width = roi["width"]
height = roi["height"]
- self.parent.ui.roi = pg.ROI([x0, y0], [width, height], pen=(62, 13, 244), scaleSnap=True) # blue
+ self.parent.ui.roi = pg.ROI(
+ [x0, y0], [width, height], pen=(62, 13, 244), scaleSnap=True
+ ) # blue
self.parent.ui.roi.addScaleHandle([1, 1], [0, 0])
self.parent.ui.image_view.addItem(self.parent.ui.roi)
self.parent.ui.roi.sigRegionChanged.connect(self.parent.roi_changed)
@@ -63,7 +65,12 @@ def table(self):
for _row in np.arange(len(self.parent.list_of_images)):
o_table.insert_empty_row(_row)
short_file_name = os.path.basename(self.parent.list_of_images[_row])
- o_table.insert_item(row=_row, column=StatisticsColumnIndex.file_name, value=short_file_name, editable=False)
+ o_table.insert_item(
+ row=_row,
+ column=StatisticsColumnIndex.file_name,
+ value=short_file_name,
+ editable=False,
+ )
o_table.insert_item(
row=_row,
column=StatisticsColumnIndex.time_offset,
@@ -95,4 +102,6 @@ def _matplotlib(parent=None, widget=None):
widget.setLayout(layout)
return sc
- self.parent.statistics_plot = _matplotlib(parent=self.parent, widget=self.parent.ui.plot_widget)
+ self.parent.statistics_plot = _matplotlib(
+ parent=self.parent, widget=self.parent.ui.plot_widget
+ )
diff --git a/notebooks/__code/roi_statistics_vs_stack/load.py b/notebooks/__code/roi_statistics_vs_stack/load.py
index 42adfaa7..55253882 100755
--- a/notebooks/__code/roi_statistics_vs_stack/load.py
+++ b/notebooks/__code/roi_statistics_vs_stack/load.py
@@ -29,7 +29,9 @@ def data(self):
o_norm = Normalization()
o_norm.load(file=_file, auto_gamma_filter=False, manual_gamma_filter=False)
data = np.squeeze(o_norm.data["sample"]["data"][0])
- time_stamp = MetadataHandler.get_time_stamp(file_name=_file, ext=file_extension)
+ time_stamp = MetadataHandler.get_time_stamp(
+ file_name=_file, ext=file_extension
+ )
if acquisition_time_of_first_image == -1:
acquisition_time_of_first_image = time_stamp
time_stamp = 0
diff --git a/notebooks/__code/roi_statistics_vs_stack/main.py b/notebooks/__code/roi_statistics_vs_stack/main.py
index 0dcc9d80..36bd5574 100755
--- a/notebooks/__code/roi_statistics_vs_stack/main.py
+++ b/notebooks/__code/roi_statistics_vs_stack/main.py
@@ -16,13 +16,17 @@
class FileHandler(FileFolderBrowser):
def __init__(self, working_dir=""):
- super(FileHandler, self).__init__(working_dir=working_dir, next_function=self.display_status)
+ super(FileHandler, self).__init__(
+ working_dir=working_dir, next_function=self.display_status
+ )
def get_list_of_files(self):
return self.list_images_ui.selected
def select_folder(self):
- self.select_input_folder(instruction="Select folder containing images to process ...")
+ self.select_input_folder(
+ instruction="Select folder containing images to process ..."
+ )
def display_status(self, folder):
o_list = ListMostDominantExtension(working_dir=folder)
@@ -30,7 +34,13 @@ def display_status(self, folder):
result = o_list.get_files_of_selected_ext()
self.list_of_images = result.list_files
nbr_images = str(len(self.list_of_images))
- display(HTML('You have selected ' + nbr_images + " images "))
+ display(
+ HTML(
+ 'You have selected '
+ + nbr_images
+ + " images "
+ )
+ )
class ImageWindow(QMainWindow):
diff --git a/notebooks/__code/roi_statistics_vs_stack/table.py b/notebooks/__code/roi_statistics_vs_stack/table.py
index 9e0033ae..03e9ad0f 100755
--- a/notebooks/__code/roi_statistics_vs_stack/table.py
+++ b/notebooks/__code/roi_statistics_vs_stack/table.py
@@ -13,8 +13,33 @@ def reset(self):
reset_value = "NaN"
for _row in data_dict.keys():
_entry = data_dict[_row]
- o_table.insert_item(row=_row, column=StatisticsColumnIndex.min, value=reset_value, editable=False)
- o_table.insert_item(row=_row, column=StatisticsColumnIndex.max, value=reset_value, editable=False)
- o_table.insert_item(row=_row, column=StatisticsColumnIndex.mean, value=reset_value, editable=False)
- o_table.insert_item(row=_row, column=StatisticsColumnIndex.median, value=reset_value, editable=False)
- o_table.insert_item(row=_row, column=StatisticsColumnIndex.std, value=reset_value, editable=False)
+ o_table.insert_item(
+ row=_row,
+ column=StatisticsColumnIndex.min,
+ value=reset_value,
+ editable=False,
+ )
+ o_table.insert_item(
+ row=_row,
+ column=StatisticsColumnIndex.max,
+ value=reset_value,
+ editable=False,
+ )
+ o_table.insert_item(
+ row=_row,
+ column=StatisticsColumnIndex.mean,
+ value=reset_value,
+ editable=False,
+ )
+ o_table.insert_item(
+ row=_row,
+ column=StatisticsColumnIndex.median,
+ value=reset_value,
+ editable=False,
+ )
+ o_table.insert_item(
+ row=_row,
+ column=StatisticsColumnIndex.std,
+ value=reset_value,
+ editable=False,
+ )
diff --git a/notebooks/__code/rotate_and_crop_images/rotate_and_crop_images.py b/notebooks/__code/rotate_and_crop_images/rotate_and_crop_images.py
index c728f7fb..8ac49697 100755
--- a/notebooks/__code/rotate_and_crop_images/rotate_and_crop_images.py
+++ b/notebooks/__code/rotate_and_crop_images/rotate_and_crop_images.py
@@ -69,7 +69,8 @@ def __init__(self, parent=None, o_load=None):
QMainWindow.__init__(self, parent=parent)
ui_full_path = os.path.join(
- os.path.dirname(os.path.dirname(os.path.dirname(__file__))), os.path.join("ui", "ui_rotate_and_crop.ui")
+ os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
+ os.path.join("ui", "ui_rotate_and_crop.ui"),
)
self.ui = load_ui(ui_full_path, baseinstance=self)
self.init_statusbar()
@@ -150,7 +151,9 @@ def get_selected_image(self, file_index=None):
file_index = self.ui.file_index_slider.value()
if self.data_dict[file_index][DataDictKeys.data] is None:
- data = RotateAndCropImages.load_data(filename=self.data_dict[file_index][DataDictKeys.filename])
+ data = RotateAndCropImages.load_data(
+ filename=self.data_dict[file_index][DataDictKeys.filename]
+ )
self.data_dict[file_index][DataDictKeys.data] = data
else:
@@ -222,12 +225,20 @@ def display_grid(self):
line_color = (255, 0, 0, 155, 0.2)
lines = np.array(
[line_color for n in np.arange(len(pos))],
- dtype=[("red", np.ubyte), ("green", np.ubyte), ("blue", np.ubyte), ("alpha", np.ubyte), ("width", float)],
+ dtype=[
+ ("red", np.ubyte),
+ ("green", np.ubyte),
+ ("blue", np.ubyte),
+ ("alpha", np.ubyte),
+ ("width", float),
+ ],
)
line_view_binning = pg.GraphItem()
self.ui.image_view.addItem(line_view_binning)
- line_view_binning.setData(pos=pos, adj=adj, pen=lines, symbol=None, pxMode=False)
+ line_view_binning.setData(
+ pos=pos, adj=adj, pen=lines, symbol=None, pxMode=False
+ )
self.line_view_binning = line_view_binning
@@ -244,7 +255,9 @@ def get_or_load_data(self, file_index=0):
array. If it's already there, just return the array
"""
if self.data_dict[file_index][DataDictKeys.data] is None:
- data = RotateAndCropImages.load_data(self.data_dict[file_index][DataDictKeys.filename])
+ data = RotateAndCropImages.load_data(
+ self.data_dict[file_index][DataDictKeys.filename]
+ )
self.data_dict[file_index][DataDictKeys.data] = data
return data
else:
@@ -267,7 +280,9 @@ def rotation_value_changed(self):
def get_crop_region(self):
data = self.get_selected_image()
# data = self.live_data
- region = self.roi.getArraySlice(np.transpose(data), self.ui.image_view.imageItem)
+ region = self.roi.getArraySlice(
+ np.transpose(data), self.ui.image_view.imageItem
+ )
x0 = region[0][0].start
x1 = region[0][0].stop - 1
@@ -295,7 +310,9 @@ def rotate_and_crop_all(self):
rotated_data = data[y0:y1, x0:x1]
self.rotated_data_dict[file_index] = {
- DataDictKeys.filename: self.data_dict[file_index][DataDictKeys.filename],
+ DataDictKeys.filename: self.data_dict[file_index][
+ DataDictKeys.filename
+ ],
DataDictKeys.data: rotated_data,
}
@@ -338,7 +355,10 @@ def select_folder(self):
)
self.output_folder_ui = fileselector.FileSelectorPanel(
- instruction="Select Output Folder ...", start_dir=self.working_dir, type="directory", next=self.export
+ instruction="Select Output Folder ...",
+ start_dir=self.working_dir,
+ type="directory",
+ next=self.export,
)
self.output_folder_ui.show()
@@ -369,4 +389,10 @@ def export(self, output_folder):
w.close()
display(HTML(""))
- display(HTML('Files created in ' + full_output_folder + ""))
+ display(
+ HTML(
+ 'Files created in '
+ + full_output_folder
+ + ""
+ )
+ )
diff --git a/notebooks/__code/sans/extract.py b/notebooks/__code/sans/extract.py
index 4d38f63d..523f8dab 100755
--- a/notebooks/__code/sans/extract.py
+++ b/notebooks/__code/sans/extract.py
@@ -15,7 +15,10 @@
from __code.sans.sans_config import biosans_parameters, gpsans_parameters
STARTING_ENTRIES = ["entry", "DASlogs"]
-LIST_SANS_INSTRUMENTS = {"GP-SANS (CG2)": {"unix_name": "CG2"}, "BIO-SANS (CG3)": {"unix_name": "CG3"}}
+LIST_SANS_INSTRUMENTS = {
+ "GP-SANS (CG2)": {"unix_name": "CG2"},
+ "BIO-SANS (CG3)": {"unix_name": "CG3"},
+}
class Initializer:
@@ -23,8 +26,13 @@ def select_instrument(self):
list_instruments = list(LIST_SANS_INSTRUMENTS.keys())
instrument_ui = widgets.HBox(
[
- widgets.Label("Select your instrument", layout=widgets.Layout(width="15%")),
- widgets.Select(options=list_instruments, layout=widgets.Layout(width="30%", height="50px")),
+ widgets.Label(
+ "Select your instrument", layout=widgets.Layout(width="15%")
+ ),
+ widgets.Select(
+ options=list_instruments,
+ layout=widgets.Layout(width="30%", height="50px"),
+ ),
]
)
display(instrument_ui)
@@ -78,19 +86,30 @@ def display_metadata(self, list_nexus):
self.list_nexus = list_nexus
self.list_keys = self.retrieve_left_widget_list_keys()
- self.list_values = self.retrieve_right_widget_list_keys(left_widget_key_selected=list(self.list_keys)[0])
+ self.list_values = self.retrieve_right_widget_list_keys(
+ left_widget_key_selected=list(self.list_keys)[0]
+ )
# search box
- search_box = widgets.HBox([widgets.Label("Search:"), widgets.Text("", layout=widgets.Layout(width="30%"))])
+ search_box = widgets.HBox(
+ [
+ widgets.Label("Search:"),
+ widgets.Text("", layout=widgets.Layout(width="30%")),
+ ]
+ )
# search_text_widget = search_box.children[1]
# search_text_widget.observe(self.search_text_changed, names='value')
# list of keys
hori_box = widgets.HBox(
[
- widgets.Select(options=self.list_keys, layout=widgets.Layout(width="400px", height=self.widget_height)),
+ widgets.Select(
+ options=self.list_keys,
+ layout=widgets.Layout(width="400px", height=self.widget_height),
+ ),
widgets.SelectMultiple(
- options=self.list_values, layout=widgets.Layout(width="400px", height=self.widget_height)
+ options=self.list_values,
+ layout=widgets.Layout(width="400px", height=self.widget_height),
),
],
)
@@ -99,7 +118,11 @@ def display_metadata(self, list_nexus):
self.left_widget_ui.observe(self.left_widget_changed, names="value")
self.right_widget_ui.observe(self.right_widget_changed, names="value")
- display(widgets.Label("Command + Click: to select more than 1 element in the right widget"))
+ display(
+ widgets.Label(
+ "Command + Click: to select more than 1 element in the right widget"
+ )
+ )
def left_widget_changed(self, new_value):
value_selected = new_value["new"]
@@ -170,10 +193,16 @@ def reformat_dict(full_dict):
return new_full_dict
def extract_all_in_one(self, output_folder):
- display(HTML('Work in progress ... '))
+ display(
+ HTML(
+ 'Work in progress ... '
+ )
+ )
self.output_folder_ui.shortcut_buttons.close()
- output_file_name = Extract.create_output_file_name(output_folder=output_folder, nbr_nexus=len(self.list_nexus))
+ output_file_name = Extract.create_output_file_name(
+ output_folder=output_folder, nbr_nexus=len(self.list_nexus)
+ )
full_list_selected = self.full_list_selected
# get list of path
@@ -194,7 +223,9 @@ def extract_all_in_one(self, output_folder):
if _index == 0:
label_of_columns.append("nexus name")
- reduction_log_dict = Extract.get_entry_value(nexus_file_name=_nexus, list_entry_path=list_entry_path)
+ reduction_log_dict = Extract.get_entry_value(
+ nexus_file_name=_nexus, list_entry_path=list_entry_path
+ )
for _key in reduction_log_dict.keys():
_value = reduction_log_dict[_key]
# print(f"-> _key:{_key}: {_value}")
diff --git a/notebooks/__code/sans/sans_config.py b/notebooks/__code/sans/sans_config.py
index 71f26c5c..5aaef869 100755
--- a/notebooks/__code/sans/sans_config.py
+++ b/notebooks/__code/sans/sans_config.py
@@ -186,7 +186,12 @@
gpsans_parameters = {
"special_parameters": {
- "list": ["sample_transmission", "background_transmission", "beam_center", "transmission_radius_used (mm)"],
+ "list": [
+ "sample_transmission",
+ "background_transmission",
+ "beam_center",
+ "transmission_radius_used (mm)",
+ ],
"path": ["reduction_information", "special_parameters"],
},
"sample_logs": {
diff --git a/notebooks/__code/scale_overlapping_images.py b/notebooks/__code/scale_overlapping_images.py
index 6907276f..7ef2451f 100755
--- a/notebooks/__code/scale_overlapping_images.py
+++ b/notebooks/__code/scale_overlapping_images.py
@@ -141,7 +141,7 @@ def display_profiles(self):
for _row in np.arange(nbr_row):
[x_axis, profile] = self.get_profile(image=image, profile_roi_row=_row)
- _label = f" Profile #{_row+1}"
+ _label = f" Profile #{_row + 1}"
_color = list_rgb_profile_color[_row]
self.ui.profile_view.plot(x_axis, profile, name=_label, pen=_color)
@@ -151,7 +151,9 @@ def update_all_plots(self):
nbr_profile = len(list_index_profile_selected)
nbr_file_selected = len(list_index_file_selected)
color = Color()
- list_rgb_profile_color = color.get_list_rgb(nbr_color=(nbr_profile * nbr_file_selected))
+ list_rgb_profile_color = color.get_list_rgb(
+ nbr_color=(nbr_profile * nbr_file_selected)
+ )
self.ui.all_plots_view.clear()
if nbr_profile == 0:
return
@@ -165,10 +167,16 @@ def update_all_plots(self):
for _color_index_file, _index_file in enumerate(list_index_file_selected):
_data = self.data_dict["data"][_index_file]
- for _color_index_profile, _index_profile in enumerate(list_index_profile_selected):
+ for _color_index_profile, _index_profile in enumerate(
+ list_index_profile_selected
+ ):
legend = f"File #{_index_file} - Profile #{_index_profile}"
- _color = list_rgb_profile_color[_color_index_file + _color_index_profile * nbr_file_selected]
- [x_axis, y_axis] = self.get_profile(image=np.transpose(_data), profile_roi_row=_index_profile)
+ _color = list_rgb_profile_color[
+ _color_index_file + _color_index_profile * nbr_file_selected
+ ]
+ [x_axis, y_axis] = self.get_profile(
+ image=np.transpose(_data), profile_roi_row=_index_profile
+ )
self.ui.all_plots_view.plot(x_axis, y_axis, name=legend, pen=_color)
def display_image(self, recalculate_image=False):
@@ -237,7 +245,9 @@ def is_row_enabled(self, row=-1):
def update_guide_table_using_guide_rois(self):
for _row, _roi in enumerate(self.list_guide_pyqt_roi):
if self.is_row_enabled(row=_row):
- region = _roi.getArraySlice(self.live_image, self.ui.image_view.imageItem)
+ region = _roi.getArraySlice(
+ self.live_image, self.ui.image_view.imageItem
+ )
x0 = region[0][0].start
x1 = region[0][0].stop
@@ -310,7 +320,9 @@ def rename_all_plots_profiles_table(self):
"""rename all the profile name"""
nbr_row = self.ui.tableWidget.rowCount()
for _row in np.arange(nbr_row):
- self.ui.all_plots_profiles_table.item(_row, 0).setText(f"Profile # {_row+1}")
+ self.ui.all_plots_profiles_table.item(_row, 0).setText(
+ f"Profile # {_row + 1}"
+ )
# setter
def set_item_all_plots_profile_table(self, row=0):
@@ -319,12 +331,16 @@ def set_item_all_plots_profile_table(self, row=0):
self.ui.all_plots_profiles_table.setItem(row, 0, item)
def set_item_profile_table(self, row=0):
- spacerItem_left = QtGui.QSpacerItem(408, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
+ spacerItem_left = QtGui.QSpacerItem(
+ 408, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding
+ )
widget = QtGui.QComboBox()
widget.addItems(self.default_profile_width_values)
widget.blockSignals(True)
widget.currentIndexChanged.connect(self.profile_width_changed)
- spacerItem_right = QtGui.QSpacerItem(408, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
+ spacerItem_right = QtGui.QSpacerItem(
+ 408, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding
+ )
hori_layout = QtGui.QHBoxLayout()
hori_layout.addItem(spacerItem_left)
hori_layout.addWidget(widget)
@@ -336,12 +352,16 @@ def set_item_profile_table(self, row=0):
def set_item_main_table(self, row=0, col=0, value=""):
if col == 0:
- spacerItem_left = QtGui.QSpacerItem(408, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
+ spacerItem_left = QtGui.QSpacerItem(
+ 408, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding
+ )
widget = QtGui.QCheckBox()
widget.blockSignals(True)
self.list_table_widget_checkbox.insert(row, widget)
widget.stateChanged.connect(self.guide_state_changed)
- spacerItem_right = QtGui.QSpacerItem(408, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
+ spacerItem_right = QtGui.QSpacerItem(
+ 408, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding
+ )
hori_layout = QtGui.QHBoxLayout()
hori_layout.addItem(spacerItem_left)
hori_layout.addWidget(widget)
@@ -379,7 +399,9 @@ def get_profile_dimensions(self, row=-1):
y_top = y0
y_bottom = y0 + height
- Profile = collections.namedtuple("Profile", ["x_left", "x_right", "y_top", "y_bottom", "profile_center"])
+ Profile = collections.namedtuple(
+ "Profile", ["x_left", "x_right", "y_top", "y_bottom", "profile_center"]
+ )
result = Profile(x_left, x_right, y_top, y_bottom, profile_center)
return result
@@ -400,7 +422,9 @@ def get_profile(self, image=[], profile_roi_row=-1):
mean_axis = 0
x_axis = np.arange(y_top, y_bottom)
- _data = image[x_left:x_right, y_top:y_bottom] # because pyqtgrpah display transpose images
+ _data = image[
+ x_left:x_right, y_top:y_bottom
+ ] # because pyqtgrpah display transpose images
profile = np.mean(_data, axis=mean_axis)
return [x_axis, profile]
@@ -459,7 +483,9 @@ def highlight_guide_profile_pyqt_rois(self, row=-1):
return
try:
- self._highlights_guide_profile_pyqt_roi(row=previous_active_row, status="deactivated")
+ self._highlights_guide_profile_pyqt_roi(
+ row=previous_active_row, status="deactivated"
+ )
self._highlights_guide_profile_pyqt_roi(row=row, status="activated")
except:
pass
@@ -611,7 +637,10 @@ def profile_along_axis_changed(self):
def export_button_clicked(self):
_export_folder = QFileDialog.getExistingDirectory(
- self, directory=self.working_dir, caption="Select Output Folder", options=QFileDialog.ShowDirsOnly
+ self,
+ directory=self.working_dir,
+ caption="Select Output Folder",
+ options=QFileDialog.ShowDirsOnly,
)
if _export_folder:
o_export = ExportProfiles(parent=self, export_folder=_export_folder)
@@ -629,7 +658,9 @@ def next_image_button_clicked(self):
def help_button_clicked(self):
import webbrowser
- webbrowser.open("https://neutronimaging.pages.ornl.gov/en/tutorial/notebooks/profile/")
+ webbrowser.open(
+ "https://neutronimaging.pages.ornl.gov/en/tutorial/notebooks/profile/"
+ )
def closeEvent(self, event=None):
pass
@@ -642,7 +673,9 @@ def __init__(self, parent=None, export_folder=""):
def _create_output_file_name(self, profile_index=0):
base_name = os.path.basename(self.parent.working_dir)
- output_file_name = os.path.join(self.export_folder, f"{base_name}_profile_{profile_index+1}.txt")
+ output_file_name = os.path.join(
+ self.export_folder, f"{base_name}_profile_{profile_index + 1}.txt"
+ )
return output_file_name
def _create_metadata(self, profile_index=0):
@@ -655,7 +688,9 @@ def _create_metadata(self, profile_index=0):
y_top = profile_dimension.y_top
y_bottom = profile_dimension.y_bottom
metadata.append("#Profile dimension:")
- metadata.append(f"# * [x0, y0, x1, y1] = [{x_left}, {y_top}, {x_right}, {y_bottom}]")
+ metadata.append(
+ f"# * [x0, y0, x1, y1] = [{x_left}, {y_top}, {x_right}, {y_bottom}]"
+ )
if is_x_profile_direction:
metadata.append("# * integrated over y_axis")
table_axis = ["#x_axis"]
@@ -665,8 +700,8 @@ def _create_metadata(self, profile_index=0):
nbr_files = len(self.parent.data_dict["file_name"])
metadata.append(f"#List of files ({nbr_files} files)")
for _index, _file in enumerate(self.parent.data_dict["file_name"]):
- metadata.append(f"# * {_file} -> col{_index+1}")
- table_axis.append(f"# col.{_index+1}")
+ metadata.append(f"# * {_file} -> col{_index + 1}")
+ table_axis.append(f"# col.{_index + 1}")
metadata.append("#")
metadata.append("#" + ",".join(table_axis))
return metadata
@@ -675,7 +710,9 @@ def _create_data(self, profile_index=0):
all_profiles = []
x_axis = []
for _data in self.parent.data_dict["data"]:
- [x_axis, profile] = self.parent.get_profile(image=np.transpose(_data), profile_roi_row=profile_index)
+ [x_axis, profile] = self.parent.get_profile(
+ image=np.transpose(_data), profile_roi_row=profile_index
+ )
all_profiles.append(list(profile))
data = []
@@ -688,10 +725,17 @@ def _create_data(self, profile_index=0):
def run(self):
_nbr_profiles = self.parent.ui.tableWidget.rowCount()
for _profile_index in np.arange(_nbr_profiles):
- _output_file_name = self._create_output_file_name(profile_index=_profile_index)
+ _output_file_name = self._create_output_file_name(
+ profile_index=_profile_index
+ )
metadata = self._create_metadata(profile_index=_profile_index)
data = self._create_data(profile_index=_profile_index)
- make_ascii_file(metadata=metadata, data=data, output_file_name=_output_file_name, dim="1d")
+ make_ascii_file(
+ metadata=metadata,
+ data=data,
+ output_file_name=_output_file_name,
+ dim="1d",
+ )
display(HTML(f"Exported Profile file {_output_file_name}"))
@@ -712,14 +756,19 @@ def add(self):
def update(self):
self._define_profile()
- self.parent.ui.image_view.removeItem(self.parent.list_profile_pyqt_roi[self.row])
+ self.parent.ui.image_view.removeItem(
+ self.parent.list_profile_pyqt_roi[self.row]
+ )
self.parent.list_profile_pyqt_roi[self.row] = self.__profile
def _define_guide(self):
"""define the guide"""
guide_roi = pg.RectROI(
[self.parent.default_guide_roi["x0"], self.parent.default_guide_roi["y0"]],
- [self.parent.default_guide_roi["width"], self.parent.default_guide_roi["height"]],
+ [
+ self.parent.default_guide_roi["width"],
+ self.parent.default_guide_roi["height"],
+ ],
pen=self.parent.default_guide_roi["color_activated"],
)
guide_roi.addScaleHandle([1, 1], [0, 0])
@@ -776,7 +825,13 @@ def _define_profile(self):
line_color = tuple(_list_line_color)
lines = np.array(
[line_color for n in np.arange(len(pos))],
- dtype=[("red", np.ubyte), ("green", np.ubyte), ("blue", np.ubyte), ("alpha", np.ubyte), ("width", float)],
+ dtype=[
+ ("red", np.ubyte),
+ ("green", np.ubyte),
+ ("blue", np.ubyte),
+ ("alpha", np.ubyte),
+ ("width", float),
+ ],
)
profile = pg.GraphItem()
@@ -797,20 +852,28 @@ def timestamp_dict(self):
def table(self):
# init the summary table
list_files_full_name = self.parent.data_dict["file_name"]
- list_files_short_name = [os.path.basename(_file) for _file in list_files_full_name]
+ list_files_short_name = [
+ os.path.basename(_file) for _file in list_files_full_name
+ ]
list_time_stamp = self.parent.timestamp_dict["list_time_stamp"]
- list_time_stamp_user_format = self.parent.timestamp_dict["list_time_stamp_user_format"]
+ list_time_stamp_user_format = self.parent.timestamp_dict[
+ "list_time_stamp_user_format"
+ ]
time_0 = list_time_stamp[0]
for _row, _file in enumerate(list_files_short_name):
self.parent.ui.summary_table.insertRow(_row)
self.set_item_summary_table(row=_row, col=0, value=_file)
- self.set_item_summary_table(row=_row, col=1, value=list_time_stamp_user_format[_row])
+ self.set_item_summary_table(
+ row=_row, col=1, value=list_time_stamp_user_format[_row]
+ )
_offset = list_time_stamp[_row] - time_0
self.set_item_summary_table(row=_row, col=2, value=f"{_offset:0.2f}")
self.parent.ui.all_plots_file_name_table.insertRow(_row)
- self.set_item_all_plot_file_name_table(row=_row, value=os.path.basename(_file))
+ self.set_item_all_plot_file_name_table(
+ row=_row, value=os.path.basename(_file)
+ )
def parameters(self):
# init the position of the measurement ROI
@@ -819,7 +882,9 @@ def parameters(self):
self.parent.default_guide_roi["height"] = int(height / 5)
self.parent.default_guide_roi["x0"] = int(width / 2)
self.parent.default_guide_roi["y0"] = int(height / 2)
- self.parent.default_profile_width_values = [str(_value) for _value in self.parent.default_profile_width_values]
+ self.parent.default_profile_width_values = [
+ str(_value) for _value in self.parent.default_profile_width_values
+ ]
def widgets(self):
_file_path = os.path.dirname(__file__)
@@ -827,28 +892,32 @@ def widgets(self):
os.path.join(_file_path, "static/profile/button_rotation_left_fast.png")
)
self.parent.ui.left_rotation_button_fast.setStyleSheet(
- "background-image: " "url('" + left_rotation_fast_file + "'); " + "background-repeat: no-repeat"
+ "background-image: "
+ "url('" + left_rotation_fast_file + "'); " + "background-repeat: no-repeat"
)
right_rotation_fast_file = os.path.abspath(
os.path.join(_file_path, "static/profile/button_rotation_right_fast.png")
)
self.parent.ui.right_rotation_button_fast.setStyleSheet(
- "background-image: " "url('" + right_rotation_fast_file + "'); " + "background-repeat: no-repeat"
+ "background-image: "
+ "url('" + right_rotation_fast_file + "'); " + "background-repeat: no-repeat"
)
left_rotation_slow_file = os.path.abspath(
os.path.join(_file_path, "static/profile/button_rotation_left_slow.png")
)
self.parent.ui.left_rotation_button_slow.setStyleSheet(
- "background-image: " "url('" + left_rotation_slow_file + "'); " + "background-repeat: no-repeat"
+ "background-image: "
+ "url('" + left_rotation_slow_file + "'); " + "background-repeat: no-repeat"
)
right_rotation_slow_file = os.path.abspath(
os.path.join(_file_path, "static/profile/button_rotation_right_slow.png")
)
self.parent.ui.right_rotation_button_slow.setStyleSheet(
- "background-image: " "url('" + right_rotation_slow_file + "'); " + "background-repeat: no-repeat"
+ "background-image: "
+ "url('" + right_rotation_slow_file + "'); " + "background-repeat: no-repeat"
)
self.parent.ui.splitter_2.setSizes([250, 50])
@@ -862,12 +931,16 @@ def widgets(self):
# update size of table columns
nbr_columns = self.parent.ui.tableWidget.columnCount()
for _col in range(nbr_columns):
- self.parent.ui.tableWidget.setColumnWidth(_col, self.parent.guide_table_width[_col])
+ self.parent.ui.tableWidget.setColumnWidth(
+ _col, self.parent.guide_table_width[_col]
+ )
# update size of summary table
nbr_columns = self.parent.ui.summary_table.columnCount()
for _col in range(nbr_columns):
- self.parent.ui.summary_table.setColumnWidth(_col, self.parent.summary_table_width[_col])
+ self.parent.ui.summary_table.setColumnWidth(
+ _col, self.parent.summary_table_width[_col]
+ )
self.parent.display_ui = [
self.parent.ui.display_size_label,
@@ -926,7 +999,8 @@ def get_image_selected(self, recalculate_image=False):
angle = self.parent.rotation_angle
# rotate all images
self.parent.data_dict["data"] = [
- transform.rotate(_image, angle) for _image in self.parent.data_dict_raw["data"]
+ transform.rotate(_image, angle)
+ for _image in self.parent.data_dict_raw["data"]
]
_image = self.parent.data_dict["data"][slider_index]
@@ -950,7 +1024,9 @@ def display_images(self):
_view_box.setState(_state)
if not first_update:
- _histo_widget.setLevels(self.parent.histogram_level[0], self.parent.histogram_level[1])
+ _histo_widget.setLevels(
+ self.parent.histogram_level[0], self.parent.histogram_level[1]
+ )
def calculate_matrix_grid(self, grid_size=1, height=1, width=1):
"""calculate the matrix that defines the vertical and horizontal lines
@@ -1000,12 +1076,17 @@ def display_grid(self):
grid_size = self.parent.ui.grid_size_slider.value()
[height, width] = np.shape(self.parent.live_image)
- pos_adj_dict = self.calculate_matrix_grid(grid_size=grid_size, height=height, width=width)
+ pos_adj_dict = self.calculate_matrix_grid(
+ grid_size=grid_size, height=height, width=width
+ )
pos = pos_adj_dict["pos"]
adj = pos_adj_dict["adj"]
line_color = self.parent.grid_view["color"]
- _transparency_value = 255 - (float(str(self.parent.ui.transparency_slider.value())) / 100) * 255
+ _transparency_value = (
+ 255
+ - (float(str(self.parent.ui.transparency_slider.value())) / 100) * 255
+ )
_list_line_color = list(line_color)
_list_line_color[3] = _transparency_value
line_color = tuple(_list_line_color)
diff --git a/notebooks/__code/select_files_and_folders.py b/notebooks/__code/select_files_and_folders.py
index 066ede30..11b8c7dc 100755
--- a/notebooks/__code/select_files_and_folders.py
+++ b/notebooks/__code/select_files_and_folders.py
@@ -14,7 +14,9 @@ class SelectFiles(FileFolderBrowser):
def __init__(self, system=None):
working_dir = system.System.get_working_dir()
- super(SelectFiles, self).__init__(working_dir=working_dir, next_function=self.retrieve_list_of_files)
+ super(SelectFiles, self).__init__(
+ working_dir=working_dir, next_function=self.retrieve_list_of_files
+ )
filters = {"TIFF": "*.tif"}
default_filter = "TIFF"
@@ -25,7 +27,9 @@ def retrieve_list_of_files(self, list_of_files=""):
class SelectFolderWithDefaultPaths(FileFolderBrowser):
- def __init__(self, system=None, working_dir="", next_function=None, multiple_flag=False):
+ def __init__(
+ self, system=None, working_dir="", next_function=None, multiple_flag=False
+ ):
if working_dir == "":
if system is None:
working_dir = "/"
@@ -33,7 +37,9 @@ def __init__(self, system=None, working_dir="", next_function=None, multiple_fla
working_dir = system.System.get_working_dir()
super(SelectFolderWithDefaultPaths, self).__init__(
- working_dir=working_dir, next_function=next_function, multiple_flag=multiple_flag
+ working_dir=working_dir,
+ next_function=next_function,
+ multiple_flag=multiple_flag,
)
ipts = os.path.basename(self.working_dir)
@@ -43,9 +49,15 @@ def __init__(self, system=None, working_dir="", next_function=None, multiple_fla
hbox = widgets.HBox(
[
widgets.Button(
- description=f"Jump to {ipts} Shared Folder", button_style="success", layout=button_layout
+ description=f"Jump to {ipts} Shared Folder",
+ button_style="success",
+ layout=button_layout,
+ ),
+ widgets.Button(
+ description="Jump to My Home Folder",
+ button_style="success",
+ layout=button_layout,
),
- widgets.Button(description="Jump to My Home Folder", button_style="success", layout=button_layout),
]
)
go_to_shared_button_ui = hbox.children[0]
@@ -83,11 +95,20 @@ def display_file_selector(self, start_dir=""):
class SelectFolder(FileFolderBrowser):
- def __init__(self, system=None, next_function=None, is_input_folder=False, working_dir="", multiple_flags=False):
+ def __init__(
+ self,
+ system=None,
+ next_function=None,
+ is_input_folder=False,
+ working_dir="",
+ multiple_flags=False,
+ ):
if not working_dir:
working_dir = system.System.get_working_dir()
- super(SelectFolder, self).__init__(working_dir=working_dir, next_function=next_function)
+ super(SelectFolder, self).__init__(
+ working_dir=working_dir, next_function=next_function
+ )
if is_input_folder:
self.select_input_folder(multiple_flag=multiple_flags)
else:
@@ -100,15 +121,24 @@ class SelectAsciiFile(FileFolderBrowser):
def __init__(self, system=None, instruction=""):
working_dir = system.System.get_working_dir()
- super(SelectAsciiFile, self).__init__(working_dir=working_dir, next_function=self.done_message)
+ super(SelectAsciiFile, self).__init__(
+ working_dir=working_dir, next_function=self.done_message
+ )
if not instruction:
instruction = "Select ASCII File!"
filters = {"Text": "*.txt"}
default_filter = "Text"
- self.select_images(filters=filters, instruction=instruction, multiple_flag=False, default_filter=default_filter)
+ self.select_images(
+ filters=filters,
+ instruction=instruction,
+ multiple_flag=False,
+ default_filter=default_filter,
+ )
def done_message(self, file_selected):
self.ascii_file = file_selected
- display_html_message(title_message="Selected Ascii File:", message=file_selected)
+ display_html_message(
+ title_message="Selected Ascii File:", message=file_selected
+ )
diff --git a/notebooks/__code/select_metadata_to_display.py b/notebooks/__code/select_metadata_to_display.py
index 42155266..445a2071 100755
--- a/notebooks/__code/select_metadata_to_display.py
+++ b/notebooks/__code/select_metadata_to_display.py
@@ -28,7 +28,11 @@ def display_metadata_list(self):
self.box1 = widgets.HBox(
[
widgets.Label("Select Metadata:", layout=widgets.Layout(width="10%")),
- widgets.Dropdown(options=display_format, value=display_format[0], layout=widgets.Layout(width="50%")),
+ widgets.Dropdown(
+ options=display_format,
+ value=display_format[0],
+ layout=widgets.Layout(width="50%"),
+ ),
]
)
display(self.box1)
@@ -64,7 +68,12 @@ def export(self):
parent_folder = self.list_images[0].split(os.path.sep)[-2]
metadata_name = f"metadata#{self.key}"
- output_file_name = os.path.join(output_folder, f"{parent_folder}_{metadata_name}.txt")
+ output_file_name = os.path.join(
+ output_folder, f"{parent_folder}_{metadata_name}.txt"
+ )
file_handler.make_ascii_file(
- metadata=["#Metadata: " + self.key], data=self.export_txt, dim="1d", output_file_name=output_file_name
+ metadata=["#Metadata: " + self.key],
+ data=self.export_txt,
+ dim="1d",
+ output_file_name=output_file_name,
)
diff --git a/notebooks/__code/sequential_combine_images_using_metadata.py b/notebooks/__code/sequential_combine_images_using_metadata.py
index 754b759c..88c3a4cd 100755
--- a/notebooks/__code/sequential_combine_images_using_metadata.py
+++ b/notebooks/__code/sequential_combine_images_using_metadata.py
@@ -45,7 +45,13 @@ def select_folder(self):
self.files_list_widget.show()
def info_folder_selected(self, selected):
- display(HTML('You selected folder: ' + selected + ""))
+ display(
+ HTML(
+ 'You selected folder: '
+ + selected
+ + ""
+ )
+ )
self.folder_selected = selected
def record_file_extension(self, filename=""):
@@ -107,7 +113,8 @@ def how_to_combine(self):
)
self.combine_method = widgets.RadioButtons(
- options=["add", "arithmetic mean", "geometric mean"], value="arithmetic mean"
+ options=["add", "arithmetic mean", "geometric mean"],
+ value="arithmetic mean",
)
vertical = widgets.VBox([alge_box, geo_box, self.combine_method])
@@ -140,8 +147,15 @@ def create_merging_list(self, list_of_files=[]):
create_list_progress = widgets.HBox(
[
- widgets.Label("Creating Merging List:", layout=widgets.Layout(width="20%")),
- widgets.IntProgress(max=len(self.list_images), min=1, value=1, layout=widgets.Layout(width="80%")),
+ widgets.Label(
+ "Creating Merging List:", layout=widgets.Layout(width="20%")
+ ),
+ widgets.IntProgress(
+ max=len(self.list_images),
+ min=1,
+ value=1,
+ layout=widgets.Layout(width="80%"),
+ ),
]
)
display(create_list_progress)
@@ -164,16 +178,20 @@ def create_merging_list(self, list_of_files=[]):
_list_files = [list_of_files[0]]
_dict_metadata = {}
- _previous_metadata = MetadataHandler.get_metata(filename=list_of_files[0], list_metadata=list_of_tag_selected)
+ _previous_metadata = MetadataHandler.get_metata(
+ filename=list_of_files[0], list_metadata=list_of_tag_selected
+ )
_previous_run = self.isolate_run_text_from_filename(list_of_files[0])
for _index, _file in enumerate(list_of_files[1:]):
- _current_metadata = MetadataHandler.get_metata(filename=_file, list_metadata=list_of_tag_selected)
+ _current_metadata = MetadataHandler.get_metata(
+ filename=_file, list_metadata=list_of_tag_selected
+ )
_current_run = self.isolate_run_text_from_filename(_file)
- if self.are_metadata_within_error_range(_current_metadata, _previous_metadata) and (
- _previous_run == _current_run
- ):
+ if self.are_metadata_within_error_range(
+ _current_metadata, _previous_metadata
+ ) and (_previous_run == _current_run):
_list_files.append(_file)
else:
str_position_counter = f"{position_counter:04d}"
@@ -187,7 +205,9 @@ def create_merging_list(self, list_of_files=[]):
_list_files = [_file]
if _previous_run != _current_run:
- master_list_images_to_combine[_previous_run] = list_images_to_combine
+ master_list_images_to_combine[_previous_run] = (
+ list_images_to_combine
+ )
list_images_to_combine = collections.OrderedDict()
_previous_metadata = _current_metadata
@@ -233,7 +253,9 @@ def isolate_value_from_metadata(self, metadata_string):
def isolate_run_text_from_filename(self, full_file_name):
basename = os.path.basename(full_file_name)
- regular_expression = self.extension_to_regular_expression_dict[self.file_extension]
+ regular_expression = self.extension_to_regular_expression_dict[
+ self.file_extension
+ ]
m = re.search(regular_expression, basename)
if m is not None:
return m.group("run")
@@ -267,7 +289,10 @@ def recap_merging_list(self):
box2 = widgets.VBox(
[
- widgets.Label("List of Files for this position", layout=widgets.Layout(width="100%")),
+ widgets.Label(
+ "List of Files for this position",
+ layout=widgets.Layout(width="100%"),
+ ),
widgets.Select(
options=self.get_list_of_files_for_selected_run_position(),
layout=widgets.Layout(width="100%", height="500px"),
@@ -286,13 +311,19 @@ def recap_merging_list(self):
layout=widgets.Layout(width="300px"),
)
- str_metadata = self.get_str_metadata(metadata_dict=self.get_metadata_for_selected_run_position())
+ str_metadata = self.get_str_metadata(
+ metadata_dict=self.get_metadata_for_selected_run_position()
+ )
self.metadata_recap_textarea = box3.children[1]
self.metadata_recap_textarea.value = str_metadata
- hori_box = widgets.HBox([box0, box1, box2, box3], layout=widgets.Layout(width="100%"))
+ hori_box = widgets.HBox(
+ [box0, box1, box2, box3], layout=widgets.Layout(width="100%")
+ )
- self.list_of_positions_ui.on_trait_change(self.recap_positions_changed, name="value")
+ self.list_of_positions_ui.on_trait_change(
+ self.recap_positions_changed, name="value"
+ )
self.list_of_runs_ui.on_trait_change(self.recap_runs_changed, name="value")
display(hori_box)
@@ -325,10 +356,14 @@ def recap_positions_changed(self):
position_selected = self.list_of_positions_ui.value
run_selected = self.list_of_runs_ui.value
- list_files_of_files = self.master_list_images_to_combine[run_selected][position_selected]["list_of_files"]
+ list_files_of_files = self.master_list_images_to_combine[run_selected][
+ position_selected
+ ]["list_of_files"]
self.list_of_files_ui.options = list_files_of_files
- str_metadata = self.get_str_metadata(metadata_dict=self.get_metadata_for_selected_run_position())
+ str_metadata = self.get_str_metadata(
+ metadata_dict=self.get_metadata_for_selected_run_position()
+ )
self.metadata_recap_textarea.value = str_metadata
def recap_runs_changed(self):
@@ -406,7 +441,9 @@ def merge(self, output_folder):
merging_ui = widgets.HBox(
[
widgets.Label("Merging Progress", layout=widgets.Layout(width="20%")),
- widgets.IntProgress(max=len(merging_list.keys()), layout=widgets.Layout(width="80%")),
+ widgets.IntProgress(
+ max=len(merging_list.keys()), layout=widgets.Layout(width="80%")
+ ),
]
)
display(merging_ui)
@@ -426,14 +463,20 @@ def merge(self, output_folder):
_data = o_load.data["sample"]["data"]
_metadata = o_load.data["sample"]["metadata"][0]
- combined_data = SequentialCombineImagesUsingMetadata._merging_algorithm(algorithm, _data)
+ combined_data = SequentialCombineImagesUsingMetadata._merging_algorithm(
+ algorithm, _data
+ )
_new_name = self._define_merged_file_name(
- output_folder=output_folder, run_label=_run, position_label=_position
+ output_folder=output_folder,
+ run_label=_run,
+ position_label=_position,
)
output_file_name = os.path.join(output_folder, _new_name)
- file_handler.save_data(data=combined_data, filename=output_file_name, metadata=_metadata)
+ file_handler.save_data(
+ data=combined_data, filename=output_file_name, metadata=_metadata
+ )
_run_index += 1
progress_bar_ui.value = _run_index
@@ -442,17 +485,25 @@ def merge(self, output_folder):
del merging_ui
display(
- HTML('Files have been created in : ' + output_folder + "")
+ HTML(
+ 'Files have been created in : '
+ + output_folder
+ + ""
+ )
)
def make_output_folder(self, output_folder):
algorithm_selected = self.__get_formated_merging_algo_name()
folder_selected = os.path.basename(os.path.dirname(self.folder_selected))
- output_folder = os.path.join(output_folder, f"{folder_selected}_{algorithm_selected}")
+ output_folder = os.path.join(
+ output_folder, f"{folder_selected}_{algorithm_selected}"
+ )
file_handler.make_folder(output_folder)
return output_folder
- def _define_merged_file_name(self, output_folder="", run_label="", position_label=""):
+ def _define_merged_file_name(
+ self, output_folder="", run_label="", position_label=""
+ ):
"""Create the new merged file name using the run, position labels
ex: run_label = "run1"
diff --git a/notebooks/__code/shifting_time_offset.py b/notebooks/__code/shifting_time_offset.py
index b97da0b7..2d32cf31 100755
--- a/notebooks/__code/shifting_time_offset.py
+++ b/notebooks/__code/shifting_time_offset.py
@@ -50,7 +50,11 @@ def built_list_of_fits_files(self, input_folder):
)
self.list_of_fits_files = list_of_fits_files
else:
- display(HTML('No FITS files Found!'))
+ display(
+ HTML(
+ 'No FITS files Found!'
+ )
+ )
def retrieve_parent_folder(self, folder):
self.working_dir = Path(folder).parent
@@ -64,7 +68,13 @@ def selected_other_folders(self, list_of_other_folders):
)
)
for _folder in list_of_other_folders:
- display(HTML(' - ' + _folder + " FITS files to process!"))
+ display(
+ HTML(
+ ' - '
+ + _folder
+ + " FITS files to process!"
+ )
+ )
def retrieve_name_of_timestamp_file(self, input_folder):
timestamp_files = list(Path(input_folder).glob("*_Spectra.txt"))
@@ -79,7 +89,11 @@ def retrieve_name_of_timestamp_file(self, input_folder):
)
self.timestamp_file = timestamp_file
else:
- display(HTML('Time stamp not Found'))
+ display(
+ HTML(
+ 'Time stamp not Found'
+ )
+ )
def load_timestamp_file(self, timestamp_file):
counts_vs_time_array = pd.read_csv(timestamp_file, sep="\t")
@@ -104,7 +118,10 @@ def plot_cutoff(index):
return index
self.index_slider = interact(
- plot_cutoff, index=widgets.IntSlider(min=0, max=x_index_axis[-1], value=0, continuous_update=False)
+ plot_cutoff,
+ index=widgets.IntSlider(
+ min=0, max=x_index_axis[-1], value=0, continuous_update=False
+ ),
)
def get_file_prefix(self, file_name):
@@ -125,7 +142,9 @@ def offset_images(self):
nbr_folder = len(list_of_folders)
- progress_bar = widgets.IntProgress(max=nbr_folder, layout=widgets.Layout(width="50%"))
+ progress_bar = widgets.IntProgress(
+ max=nbr_folder, layout=widgets.Layout(width="50%")
+ )
display(progress_bar)
offset_index = self.index_slider.widget.result
@@ -134,7 +153,9 @@ def offset_images(self):
for _index, _current_working_folder in enumerate(list_of_folders):
# get full list of FITS files
- list_of_fits_files = np.array(self.get_list_of_fits_files(_current_working_folder))
+ list_of_fits_files = np.array(
+ self.get_list_of_fits_files(_current_working_folder)
+ )
if list_of_fits_files == []:
continue
@@ -145,7 +166,9 @@ def offset_images(self):
self.retrieve_name_of_timestamp_file(_current_working_folder)
timestamp_file = self.timestamp_file
if not Path(timestamp_file).exists():
- list_folder_with_error.append(f"Error in {_current_working_folder}. Timestamp file missing!")
+ list_folder_with_error.append(
+ f"Error in {_current_working_folder}. Timestamp file missing!"
+ )
continue
# rename all files starting by file at index offset_index which will become index 0
@@ -155,7 +178,9 @@ def offset_images(self):
new_output_dir = current_working_dir + "_timeoffset_corrected"
self.copy_and_renamed_fits_files(
- output_dir=new_output_dir, original_list_of_files=new_list_of_fits_files, prefix=prefix
+ output_dir=new_output_dir,
+ original_list_of_files=new_list_of_fits_files,
+ prefix=prefix,
)
# modify timestamp file
@@ -163,7 +188,9 @@ def offset_images(self):
output_dir=new_output_dir, old_timestamp_filename=timestamp_file
)
self.create_new_timestamp_file(
- timestamp_file=timestamp_file, offset=offset_index, new_timestamp_filename=new_timestamp_filename
+ timestamp_file=timestamp_file,
+ offset=offset_index,
+ new_timestamp_filename=new_timestamp_filename,
)
progress_bar.value = _index + 1
@@ -176,7 +203,9 @@ def create_new_timestamp_filename(self, output_dir="./", old_timestamp_filename=
short_old_timestamp_filename = str(Path(old_timestamp_filename).name)
return str(Path(output_dir).joinpath(short_old_timestamp_filename))
- def create_new_timestamp_file(self, timestamp_file="", offset=0, new_timestamp_filename=""):
+ def create_new_timestamp_file(
+ self, timestamp_file="", offset=0, new_timestamp_filename=""
+ ):
timestamp_array = self.load_timestamp_file(timestamp_file)
time_axis = timestamp_array[:, 0]
new_counts_axis = np.roll(np.array(timestamp_array[:, 1]), -offset)
@@ -188,18 +217,28 @@ def create_new_timestamp_file(self, timestamp_file="", offset=0, new_timestamp_f
# bring back axis together
combined_array = np.stack((new_time_axis, new_counts_axis)).T
# print("new timesamp_filename is {}".format(new_timestamp_filename))
- make_ascii_file(data=combined_array, output_file_name=new_timestamp_filename, sep="\t")
+ make_ascii_file(
+ data=combined_array, output_file_name=new_timestamp_filename, sep="\t"
+ )
def display_errors(self, list_folder_with_error=[]):
for _line in list_folder_with_error:
- display(HTML('' + _line + "!"))
+ display(
+ HTML('' + _line + "!")
+ )
- def copy_and_renamed_fits_files(self, output_dir="./", original_list_of_files=[], prefix="test"):
+ def copy_and_renamed_fits_files(
+ self, output_dir="./", original_list_of_files=[], prefix="test"
+ ):
current_working_dir = str(Path(original_list_of_files[0]).parent)
make_or_reset_folder(output_dir)
log_file = str(Path(output_dir).joinpath("renaming_log.txt"))
- renaming_log_file = [f"Renaming schema of folder {current_working_dir}", "old name -> new name", ""]
+ renaming_log_file = [
+ f"Renaming schema of folder {current_working_dir}",
+ "old name -> new name",
+ "",
+ ]
for index, _file in enumerate(original_list_of_files):
old_name = Path(_file).name
new_name = Path(output_dir).joinpath(prefix + f"_{index:05d}.fits")
diff --git a/notebooks/__code/super_user.py b/notebooks/__code/super_user.py
index b808afed..a4145d2b 100755
--- a/notebooks/__code/super_user.py
+++ b/notebooks/__code/super_user.py
@@ -8,7 +8,9 @@
from .config import debugger_folder as list_debugging_folder
from .config import debugging
from .config import password_to_unlock_config as PASSWORD
-from .config import percentage_of_images_to_use_for_roi_selection as PERCENTAGE_OF_IMAGES
+from .config import (
+ percentage_of_images_to_use_for_roi_selection as PERCENTAGE_OF_IMAGES,
+)
THIS_FILE_PATH = os.path.dirname(__file__)
CONFIG_FILE = os.path.join(THIS_FILE_PATH, "config.py")
@@ -19,15 +21,24 @@ def __init__(self):
self.launch_ui()
def launch_ui(self):
- password = widgets.Password(value="", placeholder="Enter password", description="Password", diabled=False)
+ password = widgets.Password(
+ value="",
+ placeholder="Enter password",
+ description="Password",
+ diabled=False,
+ )
password.observe(self.password_entered, names="value")
# ----
# debugging mode
- self.debugging_mode = widgets.Checkbox(value=debugging, description="Debugging Mode", disabled=True)
+ self.debugging_mode = widgets.Checkbox(
+ value=debugging, description="Debugging Mode", disabled=True
+ )
- self.debugging_folder_label = widgets.HTML("List of folders to look for when running in debugging mode.")
+ self.debugging_folder_label = widgets.HTML(
+ "List of folders to look for when running in debugging mode."
+ )
self.debugging_folder = widgets.Select(
options=list_debugging_folder,
value=list_debugging_folder[0],
@@ -46,21 +57,37 @@ def launch_ui(self):
)
self.remove_entry.on_click(self.remove_entry_clicked)
- self.new_entry_text = widgets.Text(value="", description="New folder", disabled=True)
+ self.new_entry_text = widgets.Text(
+ value="", description="New folder", disabled=True
+ )
self.add_entry = widgets.Button(
- description="", disabled=True, button_style="", icon="plus-square", layout=widgets.Layout(width="95px")
+ description="",
+ disabled=True,
+ button_style="",
+ icon="plus-square",
+ layout=widgets.Layout(width="95px"),
)
self.add_entry.on_click(self.add_entry_clicked)
hori_layout_percentage = widgets.HBox([self.new_entry_text, self.add_entry])
# percentage of images to use for roi selection
- self.percentage_roi_label = widgets.HTML("Percentage of images to use for ROI selection", disabled=True)
+ self.percentage_roi_label = widgets.HTML(
+ "Percentage of images to use for ROI selection", disabled=True
+ )
percentage_of_images = PERCENTAGE_OF_IMAGES * 100
self.percentage_roi_value = widgets.FloatText(
- value=percentage_of_images, disabled=True, layout=widgets.Layout(width="50px")
+ value=percentage_of_images,
+ disabled=True,
+ layout=widgets.Layout(width="50px"),
)
self.percentage_units = widgets.HTML("%", disabled=True)
- hori_layout = widgets.HBox([self.percentage_roi_label, self.percentage_roi_value, self.percentage_units])
+ hori_layout = widgets.HBox(
+ [
+ self.percentage_roi_label,
+ self.percentage_roi_value,
+ self.percentage_units,
+ ]
+ )
# ----
self.save_changes = widgets.Button(
@@ -159,7 +186,9 @@ def save_button_clicked(self, value):
elif "debugger_folder = " in _line:
ascii_after.append(f"debugger_folder = {str_list_folders_formatted}")
elif "percentage_of_images_to_use_for_roi_selection = " in _line:
- ascii_after.append(f"percentage_of_images_to_use_for_roi_selection = {percentage_roi_selection}")
+ ascii_after.append(
+ f"percentage_of_images_to_use_for_roi_selection = {percentage_roi_selection}"
+ )
else:
ascii_after.append(_line)
diff --git a/notebooks/__code/system.py b/notebooks/__code/system.py
index 95288602..ed393498 100755
--- a/notebooks/__code/system.py
+++ b/notebooks/__code/system.py
@@ -45,7 +45,9 @@ def select_working_dir(
""")
)
- full_list_instruments = cls.get_full_list_instrument(instrument_to_exclude=instrument_to_exclude)
+ full_list_instruments = cls.get_full_list_instrument(
+ instrument_to_exclude=instrument_to_exclude
+ )
full_list_instruments.sort()
if instrument in full_list_instruments:
default_instrument = instrument
@@ -53,16 +55,22 @@ def select_working_dir(
default_instrument = full_list_instruments[0]
start_path = cls.get_start_path(
- debugger_folder=debugger_folder, system_folder=system_folder, instrument=default_instrument
+ debugger_folder=debugger_folder,
+ system_folder=system_folder,
+ instrument=default_instrument,
)
cls.start_path = start_path
select_instrument_ui = widgets.HBox(
[
- widgets.Label("Select Instrument", layout=widgets.Layout(width="20%")),
+ widgets.Label(
+ "Select Instrument", layout=widgets.Layout(width="20%")
+ ),
widgets.Select(
- options=full_list_instruments, value=default_instrument, layout=widgets.Layout(width="20%")
+ options=full_list_instruments,
+ value=default_instrument,
+ layout=widgets.Layout(width="20%"),
),
]
)
@@ -76,7 +84,9 @@ def select_working_dir(
[
widgets.Label("IPTS-"),
widgets.Text(value="", layout=widgets.Layout(width="10%")),
- widgets.Label("DOES NOT EXIST!", layout=widgets.Layout(width="20%")),
+ widgets.Label(
+ "DOES NOT EXIST!", layout=widgets.Layout(width="20%")
+ ),
]
)
cls.result_label = top_hbox.children[2]
@@ -92,12 +102,16 @@ def select_working_dir(
[
widgets.Label("Select Folder", layout=widgets.Layout(width="20%")),
widgets.Select(
- options=user_list_folders, value=default_value, layout=widgets.Layout(height="300px")
+ options=user_list_folders,
+ value=default_value,
+ layout=widgets.Layout(height="300px"),
),
]
)
cls.user_list_folders = user_list_folders
- box = widgets.VBox([select_instrument_ui, top_hbox, or_label, bottom_hbox, help_ui])
+ box = widgets.VBox(
+ [select_instrument_ui, top_hbox, or_label, bottom_hbox, help_ui]
+ )
display(box)
cls.working_dir_ui = bottom_hbox.children[1]
@@ -114,7 +128,11 @@ def select_working_dir(
except:
cls.working_dir = os.path.expanduser("~")
display(
- HTML('working dir set to -> ' + cls.working_dir + "")
+ HTML(
+ 'working dir set to -> '
+ + cls.working_dir
+ + ""
+ )
)
cls.log_use(notebook=notebook)
@@ -151,13 +169,21 @@ def get_list_folders(cls, start_path=""):
cls.start_path = start_path
list_folders = sorted(glob.glob(os.path.join(start_path, "*")), reverse=True)
- short_list_folders = [os.path.basename(_folder) for _folder in list_folders if os.path.isdir(_folder)]
+ short_list_folders = [
+ os.path.basename(_folder)
+ for _folder in list_folders
+ if os.path.isdir(_folder)
+ ]
# short_list_folders = sorted(short_list_folders)
# if user mode, only display folder user can access
default_value = ""
if not debugging:
- user_list_folders = [os.path.basename(_folder) for _folder in list_folders if os.access(_folder, os.R_OK)]
+ user_list_folders = [
+ os.path.basename(_folder)
+ for _folder in list_folders
+ if os.access(_folder, os.R_OK)
+ ]
if len(user_list_folders) > 0:
default_value = user_list_folders[0]
else: # debugging
@@ -193,7 +219,9 @@ def get_computer_name(cls):
@classmethod
def get_facility_selected(cls):
- return cls.get_facility_from_instrument(instrument=cls.get_instrument_selected())
+ return cls.get_facility_from_instrument(
+ instrument=cls.get_instrument_selected()
+ )
@classmethod
def get_start_path(cls, debugger_folder="", system_folder="", instrument=""):
@@ -241,7 +269,9 @@ def get_start_path(cls, debugger_folder="", system_folder="", instrument=""):
def select_ipts_help(cls, value):
import webbrowser
- webbrowser.open("https://neutronimaging.pages.ornl.gov/tutorial/notebooks/select_ipts/")
+ webbrowser.open(
+ "https://neutronimaging.pages.ornl.gov/tutorial/notebooks/select_ipts/"
+ )
@classmethod
def check_instrument_input(cls, value_dict):
diff --git a/notebooks/__code/table_handler.py b/notebooks/__code/table_handler.py
index 9be94414..749177c7 100755
--- a/notebooks/__code/table_handler.py
+++ b/notebooks/__code/table_handler.py
@@ -12,7 +12,9 @@ def __init__(self, table_ui=None):
def select_everything(self, state):
nbr_row = self.table_ui.rowCount()
nbr_column = self.table_ui.columnCount()
- selection_range = QtGui.QTableWidgetSelectionRange(0, 0, nbr_row - 1, nbr_column - 1)
+ selection_range = QtGui.QTableWidgetSelectionRange(
+ 0, 0, nbr_row - 1, nbr_column - 1
+ )
self.table_ui.setRangeSelected(selection_range, state)
def select_rows(self, list_of_rows=None):
@@ -21,7 +23,9 @@ def select_rows(self, list_of_rows=None):
nbr_column = self.table_ui.columnCount()
for _row in list_of_rows:
- selection_range = QtGui.QTableWidgetSelectionRange(_row, 0, _row, nbr_column - 1)
+ selection_range = QtGui.QTableWidgetSelectionRange(
+ _row, 0, _row, nbr_column - 1
+ )
self.table_ui.setRangeSelected(selection_range, True)
def remove_all_rows(self):
diff --git a/notebooks/__code/template_ui.py b/notebooks/__code/template_ui.py
index b7c6dd9c..c2a29cf3 100755
--- a/notebooks/__code/template_ui.py
+++ b/notebooks/__code/template_ui.py
@@ -61,7 +61,9 @@ def __init__(self, parent=None, o_norm=None):
self.ui.slider.valueChanged.connect(self.file_index_changed)
# spacer
- spacer = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
+ spacer = QtGui.QSpacerItem(
+ 40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum
+ )
bottom_layout.addWidget(label_1)
bottom_layout.addWidget(self.ui.slider)
diff --git a/notebooks/__code/time_utility.py b/notebooks/__code/time_utility.py
index 725ead85..bb552105 100755
--- a/notebooks/__code/time_utility.py
+++ b/notebooks/__code/time_utility.py
@@ -25,7 +25,13 @@ def format_time_stamp(file_name=None, time_stamp=None):
[hours, minutes, seconds] = hours.split(":")
_dict_time = {"hours": hours, "minutes": minutes, "seconds": seconds}
- _dict_time_stamp = {"week_day": week_day, "month": month, "day": day, "hours": _dict_time, "year": year}
+ _dict_time_stamp = {
+ "week_day": week_day,
+ "month": month,
+ "day": day,
+ "hours": _dict_time,
+ "year": year,
+ }
return [_short_file_name, _dict_time_stamp]
@@ -99,8 +105,10 @@ def __init__(self, folder="", files=[], is_notebook=False):
self.__is_notebook = is_notebook
def _run(self):
- [list_files, ext] = file_handler.retrieve_list_of_most_dominant_extension_from_folder(
- folder=self.folder, files=self.input_list_files
+ [list_files, ext] = (
+ file_handler.retrieve_list_of_most_dominant_extension_from_folder(
+ folder=self.folder, files=self.input_list_files
+ )
)
self.output_list_files = list_files
@@ -114,8 +122,15 @@ def _run(self):
if self.__is_notebook:
box = widgets.HBox(
[
- widgets.Label("Retrieving Time Stamp", layout=widgets.Layout(width="20%")),
- widgets.IntProgress(min=0, max=len(list_files), value=0, layout=widgets.Layout(width="50%")),
+ widgets.Label(
+ "Retrieving Time Stamp", layout=widgets.Layout(width="20%")
+ ),
+ widgets.IntProgress(
+ min=0,
+ max=len(list_files),
+ value=0,
+ layout=widgets.Layout(width="50%"),
+ ),
]
)
progress_bar = box.children[1]
@@ -152,7 +167,12 @@ class TimestampFormatter:
"%Y-%m-%dT%I:%M:%S-",
]
- def __init__(self, timestamp="", input_timestamp_format=None, output_timestamp_format=TIMESTAMP_FORMAT):
+ def __init__(
+ self,
+ timestamp="",
+ input_timestamp_format=None,
+ output_timestamp_format=TIMESTAMP_FORMAT,
+ ):
self.timestamp = timestamp
if input_timestamp_format is None:
self.input_timestamp_format = self.list_input_timestamp
@@ -189,7 +209,9 @@ def convert_timestamp(self, timestamp):
o_time = None
for _input_timestamp_format in input_timestamp_format:
# print("trying this format {} with this {}".format(_input_timestamp_format, timestamp))
- o_time = TimestampFormatter.get_time_dict(timestamp=timestamp, input_time_format=_input_timestamp_format)
+ o_time = TimestampFormatter.get_time_dict(
+ timestamp=timestamp, input_time_format=_input_timestamp_format
+ )
if o_time:
break
@@ -228,11 +250,15 @@ def convert_to_second(timestamp_value, timestamp_format=TIMESTAMP_FORMAT):
class AbsoluteTimeHandler:
def __init__(self, initial_absolute_time=None):
if initial_absolute_time is None:
- raise ValueError("Please provide an initial absolute time format as 'YYYY-MM-DDTHH:MM:SS.SSSSSS-05:00")
+ raise ValueError(
+ "Please provide an initial absolute time format as 'YYYY-MM-DDTHH:MM:SS.SSSSSS-05:00"
+ )
self.formatted_initial_absolute_time = parse(initial_absolute_time)
- def get_absolute_time_for_this_delta_time_array(self, delta_time_array=None, units="seconds"):
+ def get_absolute_time_for_this_delta_time_array(
+ self, delta_time_array=None, units="seconds"
+ ):
"""
:param delta_time_array: list of time offset
@@ -254,7 +280,10 @@ def get_absolute_time_for_this_delta_time_array(self, delta_time_array=None, uni
self.delta_time_formated = delta_time_formated
- absolute_time = [delta_time + self.formatted_initial_absolute_time for delta_time in delta_time_formated]
+ absolute_time = [
+ delta_time + self.formatted_initial_absolute_time
+ for delta_time in delta_time_formated
+ ]
return absolute_time
@@ -268,7 +297,9 @@ class RelativeTimeHandler:
def __init__(self, master_initial_time=None, local_initial_time=None):
if (master_initial_time is None) or (local_initial_time is None):
- raise ValueError("Please provide an initial absolute time format as 'YYYY-MM-DDTHH:MM:SS.SSSSSS-05:00")
+ raise ValueError(
+ "Please provide an initial absolute time format as 'YYYY-MM-DDTHH:MM:SS.SSSSSS-05:00"
+ )
formatted_master_initial_time = parse(master_initial_time)
formatted_local_initial_time = parse(local_initial_time)
@@ -276,7 +307,9 @@ def __init__(self, master_initial_time=None, local_initial_time=None):
if formatted_local_initial_time < formatted_master_initial_time:
raise ValueError("Master time should be before local time!")
- time_offset_calculated = formatted_local_initial_time - formatted_master_initial_time
+ time_offset_calculated = (
+ formatted_local_initial_time - formatted_master_initial_time
+ )
self.time_offset_calculated_s = time_offset_calculated.seconds
def get_relative_time_for_this_time_array(self, time_array=None):
diff --git a/notebooks/__code/timepix3_event_hdf5_he3_detector/timepix3_event_hdf5_he3_detector.py b/notebooks/__code/timepix3_event_hdf5_he3_detector/timepix3_event_hdf5_he3_detector.py
index 53f66e85..77f0d7c7 100755
--- a/notebooks/__code/timepix3_event_hdf5_he3_detector/timepix3_event_hdf5_he3_detector.py
+++ b/notebooks/__code/timepix3_event_hdf5_he3_detector/timepix3_event_hdf5_he3_detector.py
@@ -67,14 +67,20 @@ def rebin_and_display_h3_data(self):
bin_size = hbox.children[1]
- fig, ax = plt.subplots(figsize=(8, 8), nrows=1, ncols=1, num="Histogram of He3 detector")
+ fig, ax = plt.subplots(
+ figsize=(8, 8), nrows=1, ncols=1, num="Histogram of He3 detector"
+ )
- def plot_rebinned_data(x_axis="TOF", nbrs_bins=2, dSD_m=19.855, offset_micros=0, element="Ni"):
+ def plot_rebinned_data(
+ x_axis="TOF", nbrs_bins=2, dSD_m=19.855, offset_micros=0, element="Ni"
+ ):
if element == "Ni":
_handler = BraggEdgeLibrary(material=[element], number_of_bragg_edges=5)
else: # Ta
_handler = BraggEdgeLibrary(
- new_material=[{"name": "Ta", "lattice": 3.3058, "crystal_structure": "BCC"}],
+ new_material=[
+ {"name": "Ta", "lattice": 3.3058, "crystal_structure": "BCC"}
+ ],
number_of_bragg_edges=5,
)
@@ -132,11 +138,20 @@ def plot_rebinned_data(x_axis="TOF", nbrs_bins=2, dSD_m=19.855, offset_micros=0,
options=["TOF", "lambda"],
value="lambda",
),
- nbrs_bins=widgets.IntSlider(value=10000, min=1, max=100000, continuous_update=False),
+ nbrs_bins=widgets.IntSlider(
+ value=10000, min=1, max=100000, continuous_update=False
+ ),
dSD_m=widgets.FloatSlider(
- value=19.855, min=15, max=25, step=0.001, continuous_update=False, readout_format=".3f"
+ value=19.855,
+ min=15,
+ max=25,
+ step=0.001,
+ continuous_update=False,
+ readout_format=".3f",
+ ),
+ offset_micros=widgets.IntSlider(
+ value=0, min=0, max=15000, continuous_update=False
),
- offset_micros=widgets.IntSlider(value=0, min=0, max=15000, continuous_update=False),
element=widgets.RadioButtons(options=["Ni", "Ta"], value="Ni"),
)
display(v)
diff --git a/notebooks/__code/timepix3_from_event_to_histo_hdf5/timepix3_from_event_to_histo_hdf5.py b/notebooks/__code/timepix3_from_event_to_histo_hdf5/timepix3_from_event_to_histo_hdf5.py
index 0b0c3a0f..73f15edb 100755
--- a/notebooks/__code/timepix3_from_event_to_histo_hdf5/timepix3_from_event_to_histo_hdf5.py
+++ b/notebooks/__code/timepix3_from_event_to_histo_hdf5/timepix3_from_event_to_histo_hdf5.py
@@ -103,7 +103,9 @@ def display_infos(self):
vbox = widgets.VBox(
[
widgets.Label("Metadata"),
- widgets.Textarea(value=metadata, disabled=True, layout=widgets.Layout(height="200px")),
+ widgets.Textarea(
+ value=metadata, disabled=True, layout=widgets.Layout(height="200px")
+ ),
]
)
display(vbox)
@@ -111,14 +113,18 @@ def display_infos(self):
def define_detector(self):
self.width_ui = widgets.IntText(value=1024, description="Width")
self.height_ui = widgets.IntText(value=1024, description="Height")
- vbox = widgets.VBox([widgets.Label("MCP detector size:"), self.height_ui, self.width_ui])
+ vbox = widgets.VBox(
+ [widgets.Label("MCP detector size:"), self.height_ui, self.width_ui]
+ )
display(vbox)
def select_binning_parameter(self):
self.nbr_bin_ui = widgets.IntText(value=1000, description="Nbr of bins:")
display(self.nbr_bin_ui)
- self.range_to_use = widgets.IntSlider(value=50, max=100, min=1, description="% to use")
+ self.range_to_use = widgets.IntSlider(
+ value=50, max=100, min=1, description="% to use"
+ )
display(self.range_to_use)
def bins(self):
@@ -227,15 +233,21 @@ def define_output_filename(self):
input_nexus_filename = os.path.basename(self.input_nexus_file_name)
export_id = widgets.HBox(
[
- widgets.Label("Output file name:", layout=widgets.Layout(width="150px")),
- widgets.Text(value=input_nexus_filename, layout=widgets.Layout(width="300px")),
+ widgets.Label(
+ "Output file name:", layout=widgets.Layout(width="150px")
+ ),
+ widgets.Text(
+ value=input_nexus_filename, layout=widgets.Layout(width="300px")
+ ),
]
)
display(export_id)
self.output_file_name_id = export_id.children[1]
def select_output_location(self):
- o_output_folder = FileFolderBrowser(working_dir=self.working_dir, next_function=self.export_h5)
+ o_output_folder = FileFolderBrowser(
+ working_dir=self.working_dir, next_function=self.export_h5
+ )
o_output_folder.select_output_folder(instruction="Select output folder ...")
def export_h5(self, output_folder):
@@ -260,10 +272,16 @@ def export_h5(self, output_folder):
f.create_dataset("entry/histo/number_of_bins", data=self.nbr_bins)
f.create_dataset("entry/histo/tof_ns", data=self.bins_tof)
f.create_group("entry/infos")
- f.create_dataset("entry/infos/input_nexus_filename", data=self.input_nexus_file_name)
+ f.create_dataset(
+ "entry/infos/input_nexus_filename", data=self.input_nexus_file_name
+ )
display(HTML("Writing HDF5 file .... Done!"))
display(
- HTML('hdf5 file created:' + full_output_filename + "!")
+ HTML(
+ 'hdf5 file created:'
+ + full_output_filename
+ + "!"
+ )
)
logging.info(f"hdf5 file created: {full_output_filename}")
diff --git a/notebooks/__code/timepix3_histo_hdf5_mcp_detector/fit_regions.py b/notebooks/__code/timepix3_histo_hdf5_mcp_detector/fit_regions.py
index b7eea468..0c96b232 100755
--- a/notebooks/__code/timepix3_histo_hdf5_mcp_detector/fit_regions.py
+++ b/notebooks/__code/timepix3_histo_hdf5_mcp_detector/fit_regions.py
@@ -140,7 +140,10 @@ def high_lambda(self):
self.fit_dict["a0"] = {"value": a0_value, "error": a0_error}
self.fit_dict["b0"] = {"value": b0_value, "error": b0_error}
- self.fit_dict[FittingRegions.high_lambda] = {"xaxis": xaxis, "yaxis": yaxis_fitted}
+ self.fit_dict[FittingRegions.high_lambda] = {
+ "xaxis": xaxis,
+ "yaxis": yaxis_fitted,
+ }
def low_lambda(self):
logging.info("fitting low lambda:")
@@ -181,12 +184,19 @@ def low_lambda(self):
logging.info(f"\t{bhkl_error =}")
yaxis_fitted = kropff_low_lambda(
- xaxis, self.fit_dict["a0"]["value"], self.fit_dict["b0"]["value"], ahkl_value, bhkl_value
+ xaxis,
+ self.fit_dict["a0"]["value"],
+ self.fit_dict["b0"]["value"],
+ ahkl_value,
+ bhkl_value,
)
self.fit_dict["ahkl"] = {"value": ahkl_value, "error": ahkl_error}
self.fit_dict["bhkl"] = {"value": bhkl_value, "error": bhkl_error}
- self.fit_dict[FittingRegions.low_lambda] = {"xaxis": xaxis, "yaxis": yaxis_fitted}
+ self.fit_dict[FittingRegions.low_lambda] = {
+ "xaxis": xaxis,
+ "yaxis": yaxis_fitted,
+ }
def bragg_peak(self):
self.bragg_peak_fix_lambda()
@@ -285,7 +295,9 @@ def bragg_peak(self):
def bragg_peak_fix_lambda(self):
logging.info("Fitting bragg peak with a fixed initial lambda_hkl:")
- gmodel = Model(kropff_bragg_peak_tof, nan_policy="propagate", independent_vars=["lda"])
+ gmodel = Model(
+ kropff_bragg_peak_tof, nan_policy="propagate", independent_vars=["lda"]
+ )
lambda_hkl = self.lambdahkl
tau = self.tau
@@ -294,8 +306,12 @@ def bragg_peak_fix_lambda(self):
left_peak_index = self.left_edge_index
right_peak_index = self.right_edge_index
- xaxis = copy.deepcopy(self.x_axis_to_fit)[left_peak_index : right_peak_index + 1]
- yaxis = copy.deepcopy(self.y_axis_to_fit)[left_peak_index : right_peak_index + 1]
+ xaxis = copy.deepcopy(self.x_axis_to_fit)[
+ left_peak_index : right_peak_index + 1
+ ]
+ yaxis = copy.deepcopy(self.y_axis_to_fit)[
+ left_peak_index : right_peak_index + 1
+ ]
yaxis = -np.log(yaxis)
logging.info(f"{xaxis =}")
@@ -331,9 +347,14 @@ def bragg_peak_fix_lambda(self):
logging.info(f"\t{tau_value =}")
logging.info(f"\t{tau_error =}")
- yaxis_fitted = kropff_bragg_peak_tof(xaxis, a0, b0, ahkl, bhkl, ldahkl_value, sigma_value, tau_value)
+ yaxis_fitted = kropff_bragg_peak_tof(
+ xaxis, a0, b0, ahkl, bhkl, ldahkl_value, sigma_value, tau_value
+ )
self.fit_dict["lambdahkl"] = {"value": ldahkl_value, "error": ldahkl_error}
self.fit_dict["sigma"] = {"value": sigma_value, "error": sigma_error}
self.fit_dict["tau"] = {"value": tau_value, "error": tau_error}
- self.fit_dict[FittingRegions.bragg_peak] = {"xaxis": xaxis, "yaxis": yaxis_fitted}
+ self.fit_dict[FittingRegions.bragg_peak] = {
+ "xaxis": xaxis,
+ "yaxis": yaxis_fitted,
+ }
diff --git a/notebooks/__code/timepix3_histo_hdf5_mcp_detector/timepix3_histo_hdf5_mcp_detector.py b/notebooks/__code/timepix3_histo_hdf5_mcp_detector/timepix3_histo_hdf5_mcp_detector.py
index e53c6423..ede647cd 100755
--- a/notebooks/__code/timepix3_histo_hdf5_mcp_detector/timepix3_histo_hdf5_mcp_detector.py
+++ b/notebooks/__code/timepix3_histo_hdf5_mcp_detector/timepix3_histo_hdf5_mcp_detector.py
@@ -49,7 +49,9 @@ class Timepix3HistoHdf5McpDetector:
default_parameters = {
JSONKeys.dSD_m: 19.855,
- JSONKeys.rois_selected: {0: {JSONKeys.x0: 467, JSONKeys.y0: 99, JSONKeys.x1: 975, JSONKeys.y1: 429}},
+ JSONKeys.rois_selected: {
+ 0: {JSONKeys.x0: 467, JSONKeys.y0: 99, JSONKeys.x1: 975, JSONKeys.y1: 429}
+ },
JSONKeys.offset_micros: 0,
JSONKeys.time_shift: 0,
JSONKeys.element: "Ni",
@@ -103,7 +105,11 @@ def hdf5_or_config_file_input(self):
)
display(self.toggle_button)
- validate_button = widgets.Button(description="SELECT", icon="folder-open", layout=widgets.Layout(width="310px"))
+ validate_button = widgets.Button(
+ description="SELECT",
+ icon="folder-open",
+ layout=widgets.Layout(width="310px"),
+ )
display(validate_button)
validate_button.on_click(self.input_selection_made)
@@ -174,11 +180,19 @@ def load_config(self, config_file_name):
self.default_parameters[JSONKeys.fitting_parameters][JSONKeys.a0] = float(a0)
self.default_parameters[JSONKeys.fitting_parameters][JSONKeys.b0] = float(b0)
- self.default_parameters[JSONKeys.fitting_parameters][JSONKeys.ahkl] = float(ahkl)
- self.default_parameters[JSONKeys.fitting_parameters][JSONKeys.bhkl] = float(bhkl)
- self.default_parameters[JSONKeys.fitting_parameters][JSONKeys.lambdahkl] = float(lambdahkl)
+ self.default_parameters[JSONKeys.fitting_parameters][JSONKeys.ahkl] = float(
+ ahkl
+ )
+ self.default_parameters[JSONKeys.fitting_parameters][JSONKeys.bhkl] = float(
+ bhkl
+ )
+ self.default_parameters[JSONKeys.fitting_parameters][JSONKeys.lambdahkl] = (
+ float(lambdahkl)
+ )
self.default_parameters[JSONKeys.fitting_parameters][JSONKeys.tau] = float(tau)
- self.default_parameters[JSONKeys.fitting_parameters][JSONKeys.sigma] = float(sigma)
+ self.default_parameters[JSONKeys.fitting_parameters][JSONKeys.sigma] = float(
+ sigma
+ )
display(
HTML(
@@ -197,7 +211,9 @@ def load_nexus(self, nexus_file_name=None):
with h5py.File(nexus_file_name, "r") as f:
self.stack = np.array(f["entry"]["histo"]["stack"])
- self.time_spectra = np.array(f["entry"]["histo"]["tof_ns"]) / 1000 # to convert to micros
+ self.time_spectra = (
+ np.array(f["entry"]["histo"]["tof_ns"]) / 1000
+ ) # to convert to micros
def preview_integrated_stack(self):
self.integrated_stack = self.stack.sum(axis=0)
@@ -260,7 +276,12 @@ def calculate_and_display_profile(self):
total_pixels_in_rois += width * height
_rect = patches.Rectangle(
- (x0, y0), x1 - x0, y1 - y0, linewidth=1, edgecolor=list_matplotlib_colors[_roi_index], facecolor="none"
+ (x0, y0),
+ x1 - x0,
+ y1 - y0,
+ linewidth=1,
+ edgecolor=list_matplotlib_colors[_roi_index],
+ facecolor="none",
)
rect_array.append(_rect)
@@ -273,7 +294,9 @@ def calculate_and_display_profile(self):
x1 = rois_selected[_roi_index]["x1"]
y1 = rois_selected[_roi_index]["y1"]
- total_counts_for_this_image += np.nansum(_image[y0 : y1 + 1, x0 : x1 + 1])
+ total_counts_for_this_image += np.nansum(
+ _image[y0 : y1 + 1, x0 : x1 + 1]
+ )
profile.append(total_counts_for_this_image / total_pixels_in_rois)
@@ -296,7 +319,9 @@ def plot_profile(x_axis, dSD_m, offset_micros, time_shift, element):
_handler = BraggEdgeLibrary(material=[element], number_of_bragg_edges=6)
else: # Ta
_handler = BraggEdgeLibrary(
- new_material=[{"name": "Ta", "lattice": 3.3058, "crystal_structure": "BCC"}],
+ new_material=[
+ {"name": "Ta", "lattice": 3.3058, "crystal_structure": "BCC"}
+ ],
number_of_bragg_edges=6,
)
@@ -363,7 +388,10 @@ def plot_profile(x_axis, dSD_m, offset_micros, time_shift, element):
readout_format=".3f",
),
offset_micros=widgets.IntSlider(
- value=self.default_parameters[JSONKeys.offset_micros], min=0, max=15000, continuous_update=False
+ value=self.default_parameters[JSONKeys.offset_micros],
+ min=0,
+ max=15000,
+ continuous_update=False,
),
time_shift=widgets.IntSlider(
value=self.default_parameters[JSONKeys.time_shift],
@@ -372,7 +400,9 @@ def plot_profile(x_axis, dSD_m, offset_micros, time_shift, element):
step=1,
continuous_update=False,
),
- element=widgets.RadioButtons(options=LIST_ELEMENTS, value=self.default_parameters[JSONKeys.element]),
+ element=widgets.RadioButtons(
+ options=LIST_ELEMENTS, value=self.default_parameters[JSONKeys.element]
+ ),
)
display(self.v)
@@ -382,7 +412,11 @@ def select_peak_to_fit(self):
'Full range of peak to fit (left_range, right_range)'
)
)
- display(HTML('Peak threshold (left_peak, right_peak)'))
+ display(
+ HTML(
+ 'Peak threshold (left_peak, right_peak)'
+ )
+ )
lambda_x_axis, profile_shifted = self.prepare_data()
self.lambda_x_axis = lambda_x_axis
@@ -476,17 +510,25 @@ def prepare_data(self):
def fitting(self):
# setup parameters
- display(HTML('Init parameters'))
+ display(
+ HTML('Init parameters')
+ )
text_width = "80px" # px
display(HTML('High lambda'))
default_a0 = self.default_parameters[JSONKeys.fitting_parameters][JSONKeys.a0]
self.a0_layout = widgets.HBox(
- [widgets.Label("a\u2080"), widgets.IntText(default_a0, layout=widgets.Layout(width=text_width))]
+ [
+ widgets.Label("a\u2080"),
+ widgets.IntText(default_a0, layout=widgets.Layout(width=text_width)),
+ ]
)
default_b0 = self.default_parameters[JSONKeys.fitting_parameters][JSONKeys.b0]
self.b0_layout = widgets.HBox(
- [widgets.Label("b\u2080"), widgets.IntText(default_b0, layout=widgets.Layout(width=text_width))]
+ [
+ widgets.Label("b\u2080"),
+ widgets.IntText(default_b0, layout=widgets.Layout(width=text_width)),
+ ]
)
high_layout = widgets.VBox([self.a0_layout, self.b0_layout])
display(high_layout)
@@ -494,14 +536,18 @@ def fitting(self):
display(HTML(""))
display(HTML('Low lambda'))
- default_ahkl = self.default_parameters[JSONKeys.fitting_parameters][JSONKeys.ahkl]
+ default_ahkl = self.default_parameters[JSONKeys.fitting_parameters][
+ JSONKeys.ahkl
+ ]
self.ahkl_layout = widgets.HBox(
[
widgets.Label("a\u2095\u2096\u2097"),
widgets.IntText(default_ahkl, layout=widgets.Layout(width=text_width)),
]
)
- default_bhkl = self.default_parameters[JSONKeys.fitting_parameters][JSONKeys.bhkl]
+ default_bhkl = self.default_parameters[JSONKeys.fitting_parameters][
+ JSONKeys.bhkl
+ ]
self.bhkl_layout = widgets.HBox(
[
widgets.Label("b\u2095\u2096\u2097"),
@@ -514,27 +560,45 @@ def fitting(self):
display(HTML(""))
display(HTML('Bragg peak'))
- default_lambdahkl = self.default_parameters[JSONKeys.fitting_parameters][JSONKeys.lambdahkl]
+ default_lambdahkl = self.default_parameters[JSONKeys.fitting_parameters][
+ JSONKeys.lambdahkl
+ ]
self.lambdahkl_layout = widgets.HBox(
[
widgets.Label("\u03bb\u2095\u2096\u2097"),
- widgets.FloatText(default_lambdahkl, layout=widgets.Layout(width=text_width)),
+ widgets.FloatText(
+ default_lambdahkl, layout=widgets.Layout(width=text_width)
+ ),
]
)
default_tau = self.default_parameters[JSONKeys.fitting_parameters][JSONKeys.tau]
self.tau_layout = widgets.HBox(
- [widgets.Label("\u03c4"), widgets.FloatText(default_tau, layout=widgets.Layout(width=text_width))]
+ [
+ widgets.Label("\u03c4"),
+ widgets.FloatText(default_tau, layout=widgets.Layout(width=text_width)),
+ ]
)
- default_sigma = self.default_parameters[JSONKeys.fitting_parameters][JSONKeys.sigma]
+ default_sigma = self.default_parameters[JSONKeys.fitting_parameters][
+ JSONKeys.sigma
+ ]
self.sigma_layout = widgets.HBox(
- [widgets.Label("\u03c3"), widgets.FloatText(default_sigma, layout=widgets.Layout(width=text_width))]
+ [
+ widgets.Label("\u03c3"),
+ widgets.FloatText(
+ default_sigma, layout=widgets.Layout(width=text_width)
+ ),
+ ]
+ )
+ bragg_peak_layout = widgets.VBox(
+ [self.lambdahkl_layout, self.tau_layout, self.sigma_layout]
)
- bragg_peak_layout = widgets.VBox([self.lambdahkl_layout, self.tau_layout, self.sigma_layout])
display(bragg_peak_layout)
display(widgets.HTML("
index: {left_peak}")
- logging.info(f"\tpeak right_range: {right_lambda_range}" + "\u212b " + f"-> index: {right_peak}")
- logging.info(f"\tedge left_range: {left_lambda_edge}" + "\u212b " + f"-> index: {left_edge}")
- logging.info(f"\tedge right_range: {right_lambda_edge}" + "\u212b " + f"-> index: {right_edge}")
+ logging.info(
+ f"\tpeak left_range: {left_lambda_range}"
+ + "\u212b "
+ + f"-> index: {left_peak}"
+ )
+ logging.info(
+ f"\tpeak right_range: {right_lambda_range}"
+ + "\u212b "
+ + f"-> index: {right_peak}"
+ )
+ logging.info(
+ f"\tedge left_range: {left_lambda_edge}"
+ + "\u212b "
+ + f"-> index: {left_edge}"
+ )
+ logging.info(
+ f"\tedge right_range: {right_lambda_edge}"
+ + "\u212b "
+ + f"-> index: {right_edge}"
+ )
logging.info(f"\tlambda_x_axis: {lambda_x_axis}")
logging.info(f"\tsize of profile: {len(profile_shifted)}")
@@ -604,7 +684,9 @@ def fit_peak(self, _):
# display full spectrum
list_matplotlib_colors = Color.list_matplotlib
- ax4.plot(x_axis_to_fit, -np.log(y_axis_to_fit), "*", color=list_matplotlib_colors[0])
+ ax4.plot(
+ x_axis_to_fit, -np.log(y_axis_to_fit), "*", color=list_matplotlib_colors[0]
+ )
max_counts = 0
dict_of_fit_dict = {}
@@ -630,13 +712,21 @@ def fit_peak(self, _):
# display fitting
# high lambda
- x_axis_fitted_high_lambda = o_fit_regions.fit_dict[FittingRegions.high_lambda]["xaxis"]
- y_axis_fitted_high_lambda = o_fit_regions.fit_dict[FittingRegions.high_lambda]["yaxis"]
+ x_axis_fitted_high_lambda = o_fit_regions.fit_dict[FittingRegions.high_lambda][
+ "xaxis"
+ ]
+ y_axis_fitted_high_lambda = o_fit_regions.fit_dict[FittingRegions.high_lambda][
+ "yaxis"
+ ]
ax4.plot(x_axis_fitted_high_lambda, y_axis_fitted_high_lambda, "r-")
# low lambda
- x_axis_fitted_low_lambda = o_fit_regions.fit_dict[FittingRegions.low_lambda]["xaxis"]
- y_axis_fitted_low_lambda = o_fit_regions.fit_dict[FittingRegions.low_lambda]["yaxis"]
+ x_axis_fitted_low_lambda = o_fit_regions.fit_dict[FittingRegions.low_lambda][
+ "xaxis"
+ ]
+ y_axis_fitted_low_lambda = o_fit_regions.fit_dict[FittingRegions.low_lambda][
+ "yaxis"
+ ]
ax4.plot(x_axis_fitted_low_lambda, y_axis_fitted_low_lambda, "y-")
# bragg peak
@@ -666,7 +756,10 @@ def fit_peak(self, _):
_handler = BraggEdgeLibrary(material=[element], number_of_bragg_edges=6)
else: # Ta
_handler = BraggEdgeLibrary(
- new_material=[{"name": "Ta", "lattice": 3.3058, "crystal_structure": "BCC"}], number_of_bragg_edges=6
+ new_material=[
+ {"name": "Ta", "lattice": 3.3058, "crystal_structure": "BCC"}
+ ],
+ number_of_bragg_edges=6,
)
self.bragg_edges = _handler.bragg_edges
@@ -688,7 +781,9 @@ def fit_peak(self, _):
def saving_session(self):
# select output location
- o_output_folder = FileFolderBrowser(working_dir=self.working_dir, next_function=self.export_session)
+ o_output_folder = FileFolderBrowser(
+ working_dir=self.working_dir, next_function=self.export_session
+ )
o_output_folder.select_output_folder(instruction="Select output folder ...")
def export_session(self, output_folder=None):
@@ -699,7 +794,9 @@ def export_session(self, output_folder=None):
base, _ = os.path.splitext(os.path.basename(input_nexus_filename))
current_time = get_current_time_in_special_file_name_format()
- output_file_name = os.path.abspath(os.path.join(output_folder, f"config_{base}_{current_time}.cfg"))
+ output_file_name = os.path.abspath(
+ os.path.join(output_folder, f"config_{base}_{current_time}.cfg")
+ )
# record all parameters
rois_selected = self.rois_selected
diff --git a/notebooks/__code/timepix3_image_statistics/main.py b/notebooks/__code/timepix3_image_statistics/main.py
index 7ac3a57e..06e1b403 100644
--- a/notebooks/__code/timepix3_image_statistics/main.py
+++ b/notebooks/__code/timepix3_image_statistics/main.py
@@ -7,13 +7,11 @@
import numpy as np
import logging as notebook_logging
import matplotlib.pyplot as plt
-from matplotlib.patches import Rectangle
from ipywidgets import interactive
from ipywidgets import widgets
from PIL import Image
from __code.ipywe import fileselector
-from __code._utilities.file import get_full_log_file_name
from __code.timepix3_image_statistics import config
# Setup plotting
@@ -24,11 +22,9 @@
class Timepix3ImageStatistics:
-
-
def __init__(self, working_dir=None, debug=False):
self.working_dir = working_dir
- self.debug = debug
+ self.debug = debug
self.initialize()
def initialize(self):
@@ -72,11 +68,11 @@ def load_data(self):
def display_integrated_image(self):
fig, ax = plt.subplots(figsize=(8, 8))
- ax.imshow(self.integrated_image, cmap='viridis', origin='lower')
- ax.set_title('Integrated Image')
- ax.set_xlabel('X (pixels)')
- ax.set_ylabel('Y (pixels)')
- fig.colorbar(ax.images[0], ax=ax, label='Counts')
+ ax.imshow(self.integrated_image, cmap="viridis", origin="lower")
+ ax.set_title("Integrated Image")
+ ax.set_xlabel("X (pixels)")
+ ax.set_ylabel("Y (pixels)")
+ fig.colorbar(ax.images[0], ax=ax, label="Counts")
plt.show()
def display_chips(self):
@@ -84,89 +80,89 @@ def display_chips(self):
self.chip2 = self.integrated_image[0:256, 0:256]
self.chip3 = self.integrated_image[256:, 0:256]
self.chip4 = self.integrated_image[256:, 256:]
-
- cmap = 'viridis' # 'gray', 'viridis', 'plasma', 'inferno', 'magma', 'cividis'
+
+ cmap = "viridis" # 'gray', 'viridis', 'plasma', 'inferno', 'magma', 'cividis'
fig, axs = plt.subplots(2, 2, figsize=(10, 8))
im01 = axs[0, 1].imshow(self.chip1, cmap=cmap, vmin=0)
fig.colorbar(im01, ax=axs[0, 1])
- axs[0, 1].set_title('Chip 1')
+ axs[0, 1].set_title("Chip 1")
im02 = axs[0, 0].imshow(self.chip2, cmap=cmap, vmin=0)
fig.colorbar(im02, ax=axs[0, 0])
- axs[0, 0].set_title('Chip 2')
+ axs[0, 0].set_title("Chip 2")
im03 = axs[1, 0].imshow(self.chip3, cmap=cmap, vmin=0)
fig.colorbar(im03, ax=axs[1, 0])
- axs[1, 0].set_title('Chip 3')
+ axs[1, 0].set_title("Chip 3")
im04 = axs[1, 1].imshow(self.chip4, cmap=cmap, vmin=0)
fig.colorbar(im04, ax=axs[1, 1])
- axs[1, 1].set_title('Chip 4')
+ axs[1, 1].set_title("Chip 4")
fig.tight_layout()
# compare histograms of each chips
fig, ax = plt.subplots(figsize=(8, 6))
- ax.hist(self.chip1.ravel(), bins=256, alpha=0.5, label='Chip 1')
- ax.hist(self.chip2.ravel(), bins=256, alpha=0.5, label='Chip 2')
- ax.hist(self.chip3.ravel(), bins=256, alpha=0.5, label='Chip 3')
- ax.hist(self.chip4.ravel(), bins=256, alpha=0.5, label='Chip 4')
- ax.set_yscale('log')
- ax.set_xlabel('Pixel Value')
- ax.set_ylabel('Frequency')
+ ax.hist(self.chip1.ravel(), bins=256, alpha=0.5, label="Chip 1")
+ ax.hist(self.chip2.ravel(), bins=256, alpha=0.5, label="Chip 2")
+ ax.hist(self.chip3.ravel(), bins=256, alpha=0.5, label="Chip 3")
+ ax.hist(self.chip4.ravel(), bins=256, alpha=0.5, label="Chip 4")
+ ax.set_yscale("log")
+ ax.set_xlabel("Pixel Value")
+ ax.set_ylabel("Frequency")
ax.legend()
plt.show()
def process_chips(self):
- stat = {'min': [], 'max': [], 'mean': [], 'median': [], 'std': [], 'sum': []}
+ stat = {"min": [], "max": [], "mean": [], "median": [], "std": [], "sum": []}
Timepix3ImageStatistics.chip_stats(self.chip1, stat)
Timepix3ImageStatistics.chip_stats(self.chip2, stat)
Timepix3ImageStatistics.chip_stats(self.chip3, stat)
Timepix3ImageStatistics.chip_stats(self.chip4, stat)
fig, axs = plt.subplots(2, 3, figsize=(10, 7))
- axs[0][0].plot(stat['min'], marker='o')
- axs[0][0].set_title('Min')
+ axs[0][0].plot(stat["min"], marker="o")
+ axs[0][0].set_title("Min")
axs[0][0].set_xticks([0, 1, 2, 3])
- axs[0][0].set_xticklabels(['Chip 1', 'Chip 2', 'Chip 3', 'Chip 4'])
+ axs[0][0].set_xticklabels(["Chip 1", "Chip 2", "Chip 3", "Chip 4"])
- axs[0][1].plot(stat['max'], marker='o')
- axs[0][1].set_title('Max')
+ axs[0][1].plot(stat["max"], marker="o")
+ axs[0][1].set_title("Max")
axs[0][1].set_xticks([0, 1, 2, 3])
- axs[0][1].set_xticklabels(['Chip 1', 'Chip 2', 'Chip 3', 'Chip 4'])
+ axs[0][1].set_xticklabels(["Chip 1", "Chip 2", "Chip 3", "Chip 4"])
- axs[0][2].plot(stat['mean'], marker='o')
- axs[0][2].set_title('Mean')
+ axs[0][2].plot(stat["mean"], marker="o")
+ axs[0][2].set_title("Mean")
axs[0][2].set_xticks([0, 1, 2, 3])
- axs[0][2].set_xticklabels(['Chip 1', 'Chip 2', 'Chip 3', 'Chip 4'])
+ axs[0][2].set_xticklabels(["Chip 1", "Chip 2", "Chip 3", "Chip 4"])
- axs[1][0].plot(stat['median'], marker='o')
- axs[1][0].set_title('Median')
+ axs[1][0].plot(stat["median"], marker="o")
+ axs[1][0].set_title("Median")
axs[1][0].set_xticks([0, 1, 2, 3])
- axs[1][0].set_xticklabels(['Chip 1', 'Chip 2', 'Chip 3', 'Chip 4'])
+ axs[1][0].set_xticklabels(["Chip 1", "Chip 2", "Chip 3", "Chip 4"])
- axs[1][1].plot(stat['std'], marker='o')
- axs[1][1].set_title('Standard Deviation')
+ axs[1][1].plot(stat["std"], marker="o")
+ axs[1][1].set_title("Standard Deviation")
axs[1][1].set_xticks([0, 1, 2, 3])
- axs[1][1].set_xticklabels(['Chip 1', 'Chip 2', 'Chip 3', 'Chip 4'])
+ axs[1][1].set_xticklabels(["Chip 1", "Chip 2", "Chip 3", "Chip 4"])
- axs[1][2].plot(stat['sum'], marker='o')
- axs[1][2].set_title('Sum')
+ axs[1][2].plot(stat["sum"], marker="o")
+ axs[1][2].set_title("Sum")
axs[1][2].set_xticks([0, 1, 2, 3])
- axs[1][2].set_xticklabels(['Chip 1', 'Chip 2', 'Chip 3', 'Chip 4'])
+ axs[1][2].set_xticklabels(["Chip 1", "Chip 2", "Chip 3", "Chip 4"])
fig.tight_layout()
# let's get the statistics of each chip
@staticmethod
def chip_stats(chip, stat):
- stat['min'].append(np.min(chip))
- stat['max'].append(np.max(chip))
- stat['mean'].append(np.mean(chip))
- stat['median'].append(np.median(chip))
- stat['std'].append(np.std(chip))
- stat['sum'].append(np.sum(chip))
+ stat["min"].append(np.min(chip))
+ stat["max"].append(np.max(chip))
+ stat["mean"].append(np.mean(chip))
+ stat["median"].append(np.median(chip))
+ stat["std"].append(np.std(chip))
+ stat["sum"].append(np.sum(chip))
def locate_dead_pixels(self):
# locate all the dead pixels (value = 0 )
@@ -175,7 +171,8 @@ def locate_dead_pixels(self):
dead_pixels_chip3 = np.where(self.chip3 == 0)
dead_pixels_chip4 = np.where(self.chip4 == 0)
- display(HTML(f"""
+ display(
+ HTML(f"""
Dead Pixels Information
| Chip | Number of Dead Pixels |
@@ -184,128 +181,161 @@ def locate_dead_pixels(self):
| Chip 3 | {len(dead_pixels_chip3[0])} |
| Chip 4 | {len(dead_pixels_chip4[0])} |
- """))
+ """)
+ )
# highlight the dead pixels in each chip
- cmap = 'viridis'
+ cmap = "viridis"
fig, axs = plt.subplots(2, 2, figsize=(10, 8))
im01 = axs[0, 1].imshow(self.chip1, cmap=cmap)
- axs[0, 1].scatter(dead_pixels_chip1[1], dead_pixels_chip1[0], color='y', s=1)
+ axs[0, 1].scatter(dead_pixels_chip1[1], dead_pixels_chip1[0], color="y", s=1)
fig.colorbar(im01, ax=axs[0, 1])
- axs[0, 1].set_title(f'Chip 1 ({len(dead_pixels_chip1[0])} dead pixels)')
+ axs[0, 1].set_title(f"Chip 1 ({len(dead_pixels_chip1[0])} dead pixels)")
im02 = axs[0, 0].imshow(self.chip2, cmap=cmap)
- axs[0, 0].scatter(dead_pixels_chip2[1], dead_pixels_chip2[0], color='y', s=1)
+ axs[0, 0].scatter(dead_pixels_chip2[1], dead_pixels_chip2[0], color="y", s=1)
fig.colorbar(im02, ax=axs[0, 0])
- axs[0, 0].set_title(f'Chip 2 ({len(dead_pixels_chip2[0])} dead pixels)')
+ axs[0, 0].set_title(f"Chip 2 ({len(dead_pixels_chip2[0])} dead pixels)")
im03 = axs[1, 0].imshow(self.chip3, cmap=cmap)
- axs[1, 0].scatter(dead_pixels_chip3[1], dead_pixels_chip3[0], color='y', s=1)
- fig.colorbar(im03, ax=axs[1, 0])
- axs[1, 0].set_title(f'Chip 3 ({len(dead_pixels_chip3[0])} dead pixels)')
+ axs[1, 0].scatter(dead_pixels_chip3[1], dead_pixels_chip3[0], color="y", s=1)
+ fig.colorbar(im03, ax=axs[1, 0])
+ axs[1, 0].set_title(f"Chip 3 ({len(dead_pixels_chip3[0])} dead pixels)")
im04 = axs[1, 1].imshow(self.chip4, cmap=cmap)
- axs[1, 1].scatter(dead_pixels_chip4[1], dead_pixels_chip4[0], color='y', s=1)
+ axs[1, 1].scatter(dead_pixels_chip4[1], dead_pixels_chip4[0], color="y", s=1)
fig.colorbar(im04, ax=axs[1, 1])
- axs[1, 1].set_title(f'Chip 4 ({len(dead_pixels_chip4[0])} dead pixels)')
+ axs[1, 1].set_title(f"Chip 4 ({len(dead_pixels_chip4[0])} dead pixels)")
plt.show()
def locate_high_pixels(self):
- default_threshold = 0.1 * np.max(self.integrated_image) # 10% of max value
+ default_threshold = 0.1 * np.max(self.integrated_image) # 10% of max value
def display_high_pixels(threshold):
fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(10, 8))
- im1 = axs[0, 1].imshow(self.chip1, cmap='viridis', origin='lower')
+ im1 = axs[0, 1].imshow(self.chip1, cmap="viridis", origin="lower")
high_pixels1 = np.where(self.chip1 >= threshold)
- display(HTML(f"Number of high pixels in chip1 (>= {threshold}): {len(high_pixels1[0])}"))
- axs[0, 1].scatter(high_pixels1[1], high_pixels1[0], color='r', s=1)
- axs[0, 1].set_title(f'High Pixels (>= {threshold})')
- axs[0, 1].set_xlabel('X (pixels)')
- axs[0, 1].set_ylabel('Y (pixels)')
- axs[0, 1].set_title('Chip 1')
+ display(
+ HTML(
+ f"Number of high pixels in chip1 (>= {threshold}): {len(high_pixels1[0])}"
+ )
+ )
+ axs[0, 1].scatter(high_pixels1[1], high_pixels1[0], color="r", s=1)
+ axs[0, 1].set_title(f"High Pixels (>= {threshold})")
+ axs[0, 1].set_xlabel("X (pixels)")
+ axs[0, 1].set_ylabel("Y (pixels)")
+ axs[0, 1].set_title("Chip 1")
fig.colorbar(im1, ax=axs[0, 1])
high_pixels2 = np.where(self.chip2 >= threshold)
- display(HTML(f"Number of high pixels in chip2 (>= {threshold}): {len(high_pixels2[0])}"))
- im2 = axs[0, 0].imshow(self.chip2, cmap='viridis', origin='lower')
- axs[0, 0].scatter(high_pixels2[1], high_pixels2[0], color='r', s=1)
- axs[0, 0].set_title(f'High Pixels (>= {threshold})')
- axs[0, 0].set_xlabel('X (pixels)')
- axs[0, 0].set_ylabel('Y (pixels)')
- axs[0, 0].set_title('Chip 2')
+ display(
+ HTML(
+ f"Number of high pixels in chip2 (>= {threshold}): {len(high_pixels2[0])}"
+ )
+ )
+ im2 = axs[0, 0].imshow(self.chip2, cmap="viridis", origin="lower")
+ axs[0, 0].scatter(high_pixels2[1], high_pixels2[0], color="r", s=1)
+ axs[0, 0].set_title(f"High Pixels (>= {threshold})")
+ axs[0, 0].set_xlabel("X (pixels)")
+ axs[0, 0].set_ylabel("Y (pixels)")
+ axs[0, 0].set_title("Chip 2")
fig.colorbar(im2, ax=axs[0, 0])
- im3 = axs[1, 0].imshow(self.chip3, cmap='viridis', origin='lower')
+ im3 = axs[1, 0].imshow(self.chip3, cmap="viridis", origin="lower")
high_pixels3 = np.where(self.chip3 >= threshold)
- display(HTML(f"Number of high pixels in chip3 (>= {threshold}): {len(high_pixels3[0])}"))
- axs[1, 0].scatter(high_pixels3[1], high_pixels3[0], color='r', s=1)
- axs[1, 0].set_title(f'High Pixels (>= {threshold})')
- axs[1, 0].set_xlabel('X (pixels)')
- axs[1, 0].set_ylabel('Y (pixels)')
- axs[1, 0].set_title('Chip 3')
+ display(
+ HTML(
+ f"Number of high pixels in chip3 (>= {threshold}): {len(high_pixels3[0])}"
+ )
+ )
+ axs[1, 0].scatter(high_pixels3[1], high_pixels3[0], color="r", s=1)
+ axs[1, 0].set_title(f"High Pixels (>= {threshold})")
+ axs[1, 0].set_xlabel("X (pixels)")
+ axs[1, 0].set_ylabel("Y (pixels)")
+ axs[1, 0].set_title("Chip 3")
fig.colorbar(im3, ax=axs[1, 0])
- im4 = axs[1, 1].imshow(self.chip4, cmap='viridis', origin='lower')
+ im4 = axs[1, 1].imshow(self.chip4, cmap="viridis", origin="lower")
high_pixels4 = np.where(self.chip4 >= threshold)
- display(HTML(f"Number of high pixels in chip4 (>= {threshold}): {len(high_pixels4[0])}"))
- axs[1, 1].scatter(high_pixels4[1], high_pixels4[0], color='r', s=1)
- axs[1, 1].set_title(f'High Pixels (>= {threshold})')
- axs[1, 1].set_xlabel('X (pixels)')
- axs[1, 1].set_ylabel('Y (pixels)')
- axs[1, 1].set_title('Chip 4')
+ display(
+ HTML(
+ f"Number of high pixels in chip4 (>= {threshold}): {len(high_pixels4[0])}"
+ )
+ )
+ axs[1, 1].scatter(high_pixels4[1], high_pixels4[0], color="r", s=1)
+ axs[1, 1].set_title(f"High Pixels (>= {threshold})")
+ axs[1, 1].set_xlabel("X (pixels)")
+ axs[1, 1].set_ylabel("Y (pixels)")
+ axs[1, 1].set_title("Chip 4")
fig.colorbar(im4, ax=axs[1, 1])
plt.tight_layout()
plt.show()
- display_plot = interactive(display_high_pixels,
- threshold=widgets.IntSlider(min=0,
- max=default_threshold,
- value=np.max(self.integrated_image),
- ),
- )
+ display_plot = interactive(
+ display_high_pixels,
+ threshold=widgets.IntSlider(
+ min=0,
+ max=default_threshold,
+ value=np.max(self.integrated_image),
+ ),
+ )
display(display_plot)
-
def after_tpx3_file_selection(self, folder_name):
logging.info(f"TPX3 folder selected: {folder_name}")
sub_folder_name = self.make_sure_its_the_correct_folder(folder_name)
- logging.info(f"done running make_sure_its_the_correct_folder, Using folder: {sub_folder_name =}")
- if not (folder_name is None):
- self.get_file_infos(original_folder_name=folder_name,
- sub_folder_name=sub_folder_name)
+ logging.info(
+ f"done running make_sure_its_the_correct_folder, Using folder: {sub_folder_name =}"
+ )
+ if folder_name is not None:
+ self.get_file_infos(
+ original_folder_name=folder_name, sub_folder_name=sub_folder_name
+ )
# self.processing_tpx3(file_name=file_name)
def make_sure_its_the_correct_folder(self, folder_name):
list_of_tif_files = glob.glob(os.path.join(folder_name, "*.tif*"))
if len(list_of_tif_files) > 0:
- logging.info(f"Folder {folder_name} contains .tif files. We are good to go!")
+ logging.info(
+ f"Folder {folder_name} contains .tif files. We are good to go!"
+ )
return folder_name
else:
# trying one folder deeper
- list_of_sub_folders = [f.path for f in os.scandir(folder_name) if f.is_dir()]
+ list_of_sub_folders = [
+ f.path for f in os.scandir(folder_name) if f.is_dir()
+ ]
for sub_folder in list_of_sub_folders:
list_of_tif_files = glob.glob(os.path.join(sub_folder, "*.tif*"))
if len(list_of_tif_files) > 0:
- logging.info(f"Folder {folder_name} does not contain .tif files. Using sub-folder {sub_folder} instead")
- display(HTML(f"Folder {folder_name} does not contain .tif files. Using sub-folder {sub_folder} instead"))
+ logging.info(
+ f"Folder {folder_name} does not contain .tif files. Using sub-folder {sub_folder} instead"
+ )
+ display(
+ HTML(
+ f"Folder {folder_name} does not contain .tif files. Using sub-folder {sub_folder} instead"
+ )
+ )
return sub_folder
- logging.info(f"Folder {folder_name} does not contain .tif files. Please select another folder")
+ logging.info(
+ f"Folder {folder_name} does not contain .tif files. Please select another folder"
+ )
self.select_tpx3_folder()
return None
-
+
def get_file_infos(self, original_folder_name=None, sub_folder_name=None):
-
+
if sub_folder_name:
logging.info(f"Getting folder info for: {sub_folder_name}")
-
+
# Simulate getting file info
self.file_info = {
"original_folder_name": original_folder_name,
"sub_folder_name": sub_folder_name,
"base name": os.path.basename(sub_folder_name),
- "path" : os.path.dirname(sub_folder_name),
- "size": f"{os.path.getsize(sub_folder_name) / (1024*1024):.2f} MB",
+ "path": os.path.dirname(sub_folder_name),
+ "size": f"{os.path.getsize(sub_folder_name) / (1024 * 1024):.2f} MB",
}
# get modified time in human readable format
@@ -318,18 +348,24 @@ def get_file_infos(self, original_folder_name=None, sub_folder_name=None):
self.file_info["number of .tif files"] = len(list_of_tiff_files)
# size of images
total_size = sum(os.path.getsize(f) for f in list_of_tiff_files)
- self.file_info["total size of .tif files"] = f"{total_size / (1024*1024):.2f} MB"
+ self.file_info["total size of .tif files"] = (
+ f"{total_size / (1024 * 1024):.2f} MB"
+ )
# size of first image
if len(list_of_tiff_files) > 0:
- self.file_info["size of each .tif file"] = f"{os.path.getsize(list_of_tiff_files[0]) / (1024*1024):.2f} MB"
+ self.file_info["size of each .tif file"] = (
+ f"{os.path.getsize(list_of_tiff_files[0]) / (1024 * 1024):.2f} MB"
+ )
else:
self.file_info["size of each .tif file"] = "N/A"
- logging.info(f"File info:")
+ logging.info("File info:")
for _key in self.file_info:
logging.info(f"\t{_key}: {self.file_info[_key]}")
- display(HTML("""
+ display(
+ HTML(
+ """
TPX3 Folder Information
| Property | Value |
@@ -343,26 +379,32 @@ def get_file_infos(self, original_folder_name=None, sub_folder_name=None):
| Total size of .tif files | {} |
| Size of each .tif file | {} |
- """.format(self.file_info["original_folder_name"],
- self.file_info["sub_folder_name"],
- self.file_info["base name"],
- self.file_info["path"],
- self.file_info["size"],
- self.file_info["modified"],
- self.file_info["number of .tif files"],
- self.file_info["total size of .tif files"],
- self.file_info["size of each .tif file"])))
+ """.format(
+ self.file_info["original_folder_name"],
+ self.file_info["sub_folder_name"],
+ self.file_info["base name"],
+ self.file_info["path"],
+ self.file_info["size"],
+ self.file_info["modified"],
+ self.file_info["number of .tif files"],
+ self.file_info["total size of .tif files"],
+ self.file_info["size of each .tif file"],
+ )
+ )
+ )
else:
logging.info(f"Folder not found: {sub_folder_name}")
def processing_tpx3(self, file_name=None):
- logging.info(f"Processing TPX3 file: {os.path.basename(file_name)} ... (be patient!)")
+ logging.info(
+ f"Processing TPX3 file: {os.path.basename(file_name)} ... (be patient!)"
+ )
start_time = time.time()
-
+
# loading tpx3 file
- hits_view = tdc.process_tpx3(file_name, parallel=True)
+ hits_view = tdc.process_tpx3(file_name, parallel=True)
hits = np.array(hits_view, copy=False)
self.hits = hits
@@ -372,9 +414,11 @@ def processing_tpx3(self, file_name=None):
display(HTML(f"Processing completed in {processing_time:.2f} seconds."))
# display result as a table
- from_tof = hits['tof'].min() * 25 / 1e6
- to_tof = hits['tof'].max() * 25 / 1e6
- display(HTML("""
+ from_tof = hits["tof"].min() * 25 / 1e6
+ to_tof = hits["tof"].max() * 25 / 1e6
+ display(
+ HTML(
+ """
TPX3 Processing Results
| Infos | Value |
@@ -383,25 +427,35 @@ def processing_tpx3(self, file_name=None):
| Y range | {} - {} |
| TOF range (ms) | {:.3f} - {:.3f} |
- """.format(len(hits), hits['x'].min(), hits['x'].max(), hits['y'].min(), hits['y'].max(),
- from_tof, to_tof)))
+ """.format(
+ len(hits),
+ hits["x"].min(),
+ hits["x"].max(),
+ hits["y"].min(),
+ hits["y"].max(),
+ from_tof,
+ to_tof,
+ )
+ )
+ )
unique_chips, chip_counts = np.unique(hits["chip_id"], return_counts=True)
- _text = 'Chips distribution (hits per chips)
' + \
- ''
+ _text = (
+ "Chips distribution (hits per chips)
"
+ + ''
+ )
for chip, count in zip(unique_chips, chip_counts):
percentage = 100 * count / len(hits)
- _text += f'| Chip {chip} | {count:,} hits ({percentage:.1f}%) |
'
- _text += '
'
+ _text += f"| Chip {chip} | {count:,} hits ({percentage:.1f}%) |
"
+ _text += "
"
display(HTML(_text))
def select_sampling_percentage(self):
if len(self.hits) > 100_000:
label = widgets.Label("Select sampling percentage:")
- self.sampling_percentage_ui = widgets.FloatSlider(min=0.01,
- max=100,
- value=0.1,
- step=0.01)
+ self.sampling_percentage_ui = widgets.FloatSlider(
+ min=0.01, max=100, value=0.1, step=0.01
+ )
hori_layout = widgets.HBox([label, self.sampling_percentage_ui])
self.apply_sampling = True
display(hori_layout)
@@ -410,32 +464,36 @@ def select_sampling_percentage(self):
self.apply_sampling = False
def display_image_with_roi(self):
- self.generate_2d_hit_map()
+ self.generate_2d_hit_map()
def generate_2d_hit_map(self):
- sample_fraction = self.sampling_percentage_ui.value / 100.
+ sample_fraction = self.sampling_percentage_ui.value / 100.0
if self.apply_sampling:
n_sample = int(len(self.hits) * sample_fraction)
- sample_indices = np.random.choice(len(self.hits), size=n_sample, replace=False)
+ sample_indices = np.random.choice(
+ len(self.hits), size=n_sample, replace=False
+ )
hits_for_viz = self.hits[sample_indices]
- display(HTML(f"Using {n_sample:,} sampled hits ({sample_fraction*100:.1f}%) for visualization"))
+ display(
+ HTML(
+ f"Using {n_sample:,} sampled hits ({sample_fraction * 100:.1f}%) for visualization"
+ )
+ )
else:
hits_for_viz = self.hits
display(HTML(f"Using all {len(self.hits):,} hits for visualization"))
-
+
# Create 2D histogram (bin by detector pixels)
x_bins = np.arange(0, 515, 1) # 0 to 514 pixels
y_bins = np.arange(0, 515, 1) # 0 to 514 pixels
self.hist2d, self.x_edges, self.y_edges = np.histogram2d(
- hits_for_viz["x"], hits_for_viz["y"], bins=[x_bins, y_bins])
+ hits_for_viz["x"], hits_for_viz["y"], bins=[x_bins, y_bins]
+ )
def select_roi(self):
pass
-
+
def generate_histogram_and_select_roi(self):
self.generate_2d_hit_map()
self.select_roi()
-
-
-
diff --git a/notebooks/__code/timepix3_raw_to_profile_of_roi/main.py b/notebooks/__code/timepix3_raw_to_profile_of_roi/main.py
index 67acebf7..c45ae11e 100644
--- a/notebooks/__code/timepix3_raw_to_profile_of_roi/main.py
+++ b/notebooks/__code/timepix3_raw_to_profile_of_roi/main.py
@@ -5,8 +5,6 @@
import time
import numpy as np
import matplotlib.pyplot as plt
-from matplotlib.patches import Rectangle
-from ipywidgets import interactive
from ipywidgets import widgets
from __code.ipywe import fileselector
@@ -21,7 +19,6 @@
class Timepix3RawToProfileOfRoi:
-
apply_sampling = False
hist2d = None
@@ -42,7 +39,6 @@ def __init__(self, working_dir=None, debug=False):
logging.info("*** Starting a new session ***")
logging.info(f"Debug mode is {self.debug}")
print(f"log file: {self.log_file_name}")
-
def select_tpx3(self):
if self.debug:
@@ -58,22 +54,22 @@ def select_tpx3(self):
)
self.nexus_ui.show()
- def after_tpx3_file_selection(self, file_name):
+ def after_tpx3_file_selection(self, file_name):
self.get_file_infos(file_name=file_name)
self.processing_tpx3(file_name=file_name)
def get_file_infos(self, file_name=None):
-
+
if file_name:
logging.info(f"Getting file info for: {file_name}")
# Simulate getting file info
self.file_info = {
"base name": os.path.basename(file_name),
- "path" : os.path.dirname(file_name),
- "size": f"{os.path.getsize(file_name) / (1024*1024):.2f} MB",
+ "path": os.path.dirname(file_name),
+ "size": f"{os.path.getsize(file_name) / (1024 * 1024):.2f} MB",
"modified": os.path.getmtime(file_name),
}
- logging.info(f"File info:")
+ logging.info("File info:")
for _key in self.file_info:
logging.info(f"\t{_key}: {self.file_info[_key]}")
else:
@@ -81,11 +77,13 @@ def get_file_infos(self, file_name=None):
def processing_tpx3(self, file_name=None):
- logging.info(f"Processing TPX3 file: {os.path.basename(file_name)} ... (be patient!)")
+ logging.info(
+ f"Processing TPX3 file: {os.path.basename(file_name)} ... (be patient!)"
+ )
start_time = time.time()
-
+
# loading tpx3 file
- hits_view = tdc.process_tpx3(file_name, parallel=True)
+ hits_view = tdc.process_tpx3(file_name, parallel=True)
hits = np.array(hits_view, copy=False)
self.hits = hits
@@ -95,9 +93,11 @@ def processing_tpx3(self, file_name=None):
display(HTML(f"Processing completed in {processing_time:.2f} seconds."))
# display result as a table
- from_tof = hits['tof'].min() * 25 / 1e6
- to_tof = hits['tof'].max() * 25 / 1e6
- display(HTML("""
+ from_tof = hits["tof"].min() * 25 / 1e6
+ to_tof = hits["tof"].max() * 25 / 1e6
+ display(
+ HTML(
+ """
TPX3 Processing Results
| Infos | Value |
@@ -106,25 +106,35 @@ def processing_tpx3(self, file_name=None):
| Y range | {} - {} |
| TOF range (ms) | {:.3f} - {:.3f} |
- """.format(len(hits), hits['x'].min(), hits['x'].max(), hits['y'].min(), hits['y'].max(),
- from_tof, to_tof)))
+ """.format(
+ len(hits),
+ hits["x"].min(),
+ hits["x"].max(),
+ hits["y"].min(),
+ hits["y"].max(),
+ from_tof,
+ to_tof,
+ )
+ )
+ )
unique_chips, chip_counts = np.unique(hits["chip_id"], return_counts=True)
- _text = 'Chips distribution (hits per chips)
' + \
- ''
+ _text = (
+ "Chips distribution (hits per chips)
"
+ + ''
+ )
for chip, count in zip(unique_chips, chip_counts):
percentage = 100 * count / len(hits)
- _text += f'| Chip {chip} | {count:,} hits ({percentage:.1f}%) |
'
- _text += '
'
+ _text += f"| Chip {chip} | {count:,} hits ({percentage:.1f}%) |
"
+ _text += "
"
display(HTML(_text))
def select_sampling_percentage(self):
if len(self.hits) > 100_000:
label = widgets.Label("Select sampling percentage:")
- self.sampling_percentage_ui = widgets.FloatSlider(min=0.01,
- max=100,
- value=0.1,
- step=0.01)
+ self.sampling_percentage_ui = widgets.FloatSlider(
+ min=0.01, max=100, value=0.1, step=0.01
+ )
hori_layout = widgets.HBox([label, self.sampling_percentage_ui])
self.apply_sampling = True
display(hori_layout)
@@ -133,32 +143,36 @@ def select_sampling_percentage(self):
self.apply_sampling = False
def display_image_with_roi(self):
- self.generate_2d_hit_map()
+ self.generate_2d_hit_map()
def generate_2d_hit_map(self):
- sample_fraction = self.sampling_percentage_ui.value / 100.
+ sample_fraction = self.sampling_percentage_ui.value / 100.0
if self.apply_sampling:
n_sample = int(len(self.hits) * sample_fraction)
- sample_indices = np.random.choice(len(self.hits), size=n_sample, replace=False)
+ sample_indices = np.random.choice(
+ len(self.hits), size=n_sample, replace=False
+ )
hits_for_viz = self.hits[sample_indices]
- display(HTML(f"Using {n_sample:,} sampled hits ({sample_fraction*100:.1f}%) for visualization"))
+ display(
+ HTML(
+ f"Using {n_sample:,} sampled hits ({sample_fraction * 100:.1f}%) for visualization"
+ )
+ )
else:
hits_for_viz = self.hits
display(HTML(f"Using all {len(self.hits):,} hits for visualization"))
-
+
# Create 2D histogram (bin by detector pixels)
x_bins = np.arange(0, 515, 1) # 0 to 514 pixels
y_bins = np.arange(0, 515, 1) # 0 to 514 pixels
self.hist2d, self.x_edges, self.y_edges = np.histogram2d(
- hits_for_viz["x"], hits_for_viz["y"], bins=[x_bins, y_bins])
+ hits_for_viz["x"], hits_for_viz["y"], bins=[x_bins, y_bins]
+ )
def select_roi(self):
pass
-
+
def generate_histogram_and_select_roi(self):
self.generate_2d_hit_map()
self.select_roi()
-
-
-
diff --git a/notebooks/__code/timepix_chips_alignment_correction/config.py b/notebooks/__code/timepix_chips_alignment_correction/config.py
index a9590440..cc550ccc 100644
--- a/notebooks/__code/timepix_chips_alignment_correction/config.py
+++ b/notebooks/__code/timepix_chips_alignment_correction/config.py
@@ -18,4 +18,3 @@
"chip3": {"xoffset": 0, "yoffset": 0, "description": "bottom left chip"},
"chip4": {"xoffset": 0, "yoffset": 0, "description": "bottom right chip"},
}
-
\ No newline at end of file
diff --git a/notebooks/__code/timepix_chips_alignment_correction/main.py b/notebooks/__code/timepix_chips_alignment_correction/main.py
index 232741e9..88a95393 100755
--- a/notebooks/__code/timepix_chips_alignment_correction/main.py
+++ b/notebooks/__code/timepix_chips_alignment_correction/main.py
@@ -1,7 +1,6 @@
import glob
import os
-from click import edit
from matplotlib import patches
import numpy as np
import ipywidgets as widgets
@@ -9,12 +8,11 @@
import tqdm
import yaml
import matplotlib.pyplot as plt
-from IPython.display import HTML, display
from ipywidgets import interactive
from tqdm import tqdm
from timepix_geometry_correction.correct import TimepixGeometryCorrection
-
+
from __code._utilities.images import load_data_using_multithreading
from __code._utilities.images import make_tiff
from __code.ipywe import fileselector
@@ -32,7 +30,7 @@ class ChipsLabelPosition:
x_left = 15
x_right = 512 - x_left
y_top = 20
- y_bottom = 512-y_top
+ y_bottom = 512 - y_top
chip1 = (x_right, y_top)
chip2 = (x_left, y_top)
@@ -68,9 +66,13 @@ def select_folder(self):
def load_data(self, folder_selected):
full_list_files = glob.glob(os.path.join(folder_selected, "*.tif*"))
full_list_files.sort()
- working_list_files = [file for file in full_list_files if "_SummedImg.fits" not in file]
- self.working_list_files = working_list_files # full file name of the stack of tif files
-
+ working_list_files = [
+ file for file in full_list_files if "_SummedImg.fits" not in file
+ ]
+ self.working_list_files = (
+ working_list_files # full file name of the stack of tif files
+ )
+
self.working_data = load_data_using_multithreading(list_tif=working_list_files)
self.input_working_folder = folder_selected
self.working_list_files = working_list_files
@@ -79,36 +81,44 @@ def load_data(self, folder_selected):
self.integrated_data = np.sum(self.working_data, axis=0)
with self.out:
- self.out.clear_output()
+ self.out.clear_output()
display(
HTML(
''
+ str(len(working_list_files) + 1)
- + " files have been loaded from " + folder_selected + ""
+ + " files have been loaded from "
+ + folder_selected
+ + ""
)
)
def select_detector(self):
- label = widgets.Label("Select Detector Type:",
- layout=widgets.Layout(width='13%'))
- list_of_detector_types = [DetectorType.__dict__.get(key) for key in DetectorType.__dict__.keys() if not key.startswith('__')]
- self.detector_type_ui = widgets.Dropdown(options=list_of_detector_types,
- value=DetectorType.TIMEPIX1,
- # value=DetectorType.CUSTOM, # DEBUGGING PURPOSE
- # description='Detector Type:',
- disabled=False,
- layout=widgets.Layout(width='20%')
- )
+ label = widgets.Label(
+ "Select Detector Type:", layout=widgets.Layout(width="13%")
+ )
+ list_of_detector_types = [
+ DetectorType.__dict__.get(key)
+ for key in DetectorType.__dict__.keys()
+ if not key.startswith("__")
+ ]
+ self.detector_type_ui = widgets.Dropdown(
+ options=list_of_detector_types,
+ value=DetectorType.TIMEPIX1,
+ # value=DetectorType.CUSTOM, # DEBUGGING PURPOSE
+ # description='Detector Type:',
+ disabled=False,
+ layout=widgets.Layout(width="20%"),
+ )
box = widgets.HBox([label, self.detector_type_ui])
display(box)
-
+
def correction_settings(self):
# if self.detector_type_ui.value == DetectorType.CUSTOM:
# # self.select_config_file()
# # for debugging purpose only
# config_file = "/SNS/VENUS/IPTS-35945/shared/processed_data/jean_test/detector_config.yaml"
# self.load_config_file(config_file)
-
+
# else:
if self.detector_type_ui.value == DetectorType.TIMEPIX1:
_detector_config = config.config_timepix1
@@ -120,7 +130,7 @@ def correction_settings(self):
self.display_detector_config(editable=False)
self.correct_integrated_data()
self.display_correction()
-
+
def select_config_file(self):
select_config = fileselector.FileSelectorPanel(
instruction="Select Detector Configuration File ...",
@@ -132,76 +142,82 @@ def select_config_file(self):
default_filter="YAML files",
)
select_config.show()
-
+
def load_config_file(self, file_selected):
- with open(file_selected, 'r') as f:
+ with open(file_selected, "r") as f:
detector_config = yaml.safe_load(f)
self.default_config_file = file_selected
self.detector_config = detector_config
self.display_detector_config(editable=True)
self.correct_integrated_data()
self.display_correction()
-
+
def correct_integrated_data(self):
- o_corrrector = TimepixGeometryCorrection(raw_images=self.integrated_data,
- config=self.detector_config)
+ o_corrrector = TimepixGeometryCorrection(
+ raw_images=self.integrated_data, config=self.detector_config
+ )
self.corrected_integrated_data = o_corrrector.correct(display=False)[0]
-
+
def save_new_config(self):
"""this method updates the detector_config dictionary with the values from the UI"""
updated_config = {}
children = self.vbox.children
for box in children: # exclude the button and output widget
chip_label = box.children[0].value
- chip_name = chip_label.split(' ')[0][3:] # Extract chip name from label
+ chip_name = chip_label.split(" ")[0][3:] # Extract chip name from label
xoffset_ui = box.children[1]
yoffset_ui = box.children[2]
updated_config[chip_name] = {
- 'description': self.detector_config[chip_name]['description'],
- 'xoffset': float(xoffset_ui.value),
- 'yoffset': float(yoffset_ui.value)
+ "description": self.detector_config[chip_name]["description"],
+ "xoffset": float(xoffset_ui.value),
+ "yoffset": float(yoffset_ui.value),
}
self.detector_config = updated_config
-
+
def on_recalculate_clicked(self, status):
with self.out:
self.out.clear_output()
self.save_new_config()
self.correct_integrated_data()
self.display_correction()
-
+
def display_detector_config(self, editable=False):
items = []
detector_config = self.detector_config
for chip, params in detector_config.items():
-
if editable:
- if 'chip2' in chip:
+ if "chip2" in chip:
disabled_state = True
else:
disabled_state = not editable
else:
disabled_state = True
-
- chip_label = widgets.HTML(value=f"
{chip} ({params['description']})",
- layout=widgets.Layout(width='25%'))
- xoffset_ui = widgets.FloatText(value=params['xoffset'],
- description='X Offset:',
- disabled=disabled_state,
- layout=widgets.Layout(width='15%'))
- yoffset_ui = widgets.FloatText(value=params['yoffset'],
- description='Y Offset:',
- disabled=disabled_state,
- layout=widgets.Layout(width='15%'))
+
+ chip_label = widgets.HTML(
+ value=f"
{chip} ({params['description']})",
+ layout=widgets.Layout(width="25%"),
+ )
+ xoffset_ui = widgets.FloatText(
+ value=params["xoffset"],
+ description="X Offset:",
+ disabled=disabled_state,
+ layout=widgets.Layout(width="15%"),
+ )
+ yoffset_ui = widgets.FloatText(
+ value=params["yoffset"],
+ description="Y Offset:",
+ disabled=disabled_state,
+ layout=widgets.Layout(width="15%"),
+ )
box = widgets.HBox([chip_label, xoffset_ui, yoffset_ui])
-
+
items.append(box)
self.vbox = widgets.VBox(items)
display(self.vbox)
-
+
# if editable:
- # self.recalculate_button = widgets.Button(description="Recalculate Correction",
+ # self.recalculate_button = widgets.Button(description="Recalculate Correction",
# layout=widgets.Layout(margin='10px 0px 0px 0px', width="60%"),
# )
# # display(self.recalculate_button)
@@ -209,114 +225,198 @@ def display_detector_config(self, editable=False):
# display(self.recalculate_button)
# self.out = widgets.Output()
# display(self.out)
-
+
display(HTML("
"))
-
+
def display_correction(self):
-
+
default_size = 25
+
# def preview_correction(x, y, size=5, show_markers=True, recalculate_button=True):
def preview_correction(x, y, size=5, show_markers=True):
-
+
self.fig, axs = plt.subplots(2, 2, figsize=(12, 12))
-
+
# left size, original integrated data
- im00 = axs[0, 0].imshow(self.integrated_data, cmap='viridis')
-
- axs[0, 0].set_title('Original Integrated Data')
- plt.colorbar(im00, ax=axs[0,0], shrink=0.6)
+ im00 = axs[0, 0].imshow(self.integrated_data, cmap="viridis")
+
+ axs[0, 0].set_title("Original Integrated Data")
+ plt.colorbar(im00, ax=axs[0, 0], shrink=0.6)
if show_markers:
-
# add "chips1" in top right corner of the image
- axs[0, 0].text(ChipsLabelPosition.chip3[0], ChipsLabelPosition.chip3[1],
- 'Chips3', color='white', fontsize=12, weight='bold', ha='left', va='bottom')
- axs[0, 0].text(ChipsLabelPosition.chip2[0], ChipsLabelPosition.chip2[1],
- 'Chips2', color='white', fontsize=12, weight='bold', ha='left', va='top')
- axs[0, 0].text(ChipsLabelPosition.chip1[0], ChipsLabelPosition.chip1[1],
- 'Chips1', color='white', fontsize=12, weight='bold', ha='right', va='top')
- axs[0, 0].text(ChipsLabelPosition.chip4[0], ChipsLabelPosition.chip4[1],
- 'Chips4', color='white', fontsize=12, weight='bold', ha='right', va='bottom')
-
- axs[0, 0].axvline(x=x, color='r', linestyle='--', alpha=0.2)
- axs[0, 0].axvline(x=x+size, color='r', linestyle='--', alpha=0.2)
- axs[0, 0].axhline(y=y, color='r', linestyle='--', alpha=0.2)
- axs[0, 0].axhline(y=y+size, color='r', linestyle='--', alpha=0.2)
-
+ axs[0, 0].text(
+ ChipsLabelPosition.chip3[0],
+ ChipsLabelPosition.chip3[1],
+ "Chips3",
+ color="white",
+ fontsize=12,
+ weight="bold",
+ ha="left",
+ va="bottom",
+ )
+ axs[0, 0].text(
+ ChipsLabelPosition.chip2[0],
+ ChipsLabelPosition.chip2[1],
+ "Chips2",
+ color="white",
+ fontsize=12,
+ weight="bold",
+ ha="left",
+ va="top",
+ )
+ axs[0, 0].text(
+ ChipsLabelPosition.chip1[0],
+ ChipsLabelPosition.chip1[1],
+ "Chips1",
+ color="white",
+ fontsize=12,
+ weight="bold",
+ ha="right",
+ va="top",
+ )
+ axs[0, 0].text(
+ ChipsLabelPosition.chip4[0],
+ ChipsLabelPosition.chip4[1],
+ "Chips4",
+ color="white",
+ fontsize=12,
+ weight="bold",
+ ha="right",
+ va="bottom",
+ )
+
+ axs[0, 0].axvline(x=x, color="r", linestyle="--", alpha=0.2)
+ axs[0, 0].axvline(x=x + size, color="r", linestyle="--", alpha=0.2)
+ axs[0, 0].axhline(y=y, color="r", linestyle="--", alpha=0.2)
+ axs[0, 0].axhline(y=y + size, color="r", linestyle="--", alpha=0.2)
+
# show the edge of the chips
- axs[0, 0].axhline(y=255, color='white', linestyle='-', alpha=0.2)
- axs[0, 0].axhline(y=256, color='white', linestyle='-', alpha=0.2)
- axs[0, 0].axvline(x=255, color='white', linestyle='-', alpha=0.2)
- axs[0, 0].axvline(x=256, color='white', linestyle='-', alpha=0.2)
-
- rect_container = patches.Rectangle((x, y), size, size, linewidth=1, edgecolor='yellow', facecolor='none')
+ axs[0, 0].axhline(y=255, color="white", linestyle="-", alpha=0.2)
+ axs[0, 0].axhline(y=256, color="white", linestyle="-", alpha=0.2)
+ axs[0, 0].axvline(x=255, color="white", linestyle="-", alpha=0.2)
+ axs[0, 0].axvline(x=256, color="white", linestyle="-", alpha=0.2)
+
+ rect_container = patches.Rectangle(
+ (x, y), size, size, linewidth=1, edgecolor="yellow", facecolor="none"
+ )
axs[0, 0].add_patch(rect_container)
-
+
# right side, corrected integrated data (placeholder)
corrected_data = self.corrected_integrated_data
- im01 = axs[0, 1].imshow(corrected_data, cmap='viridis')
- plt.colorbar(im01, ax=axs[0,1], shrink=0.6)
- axs[0, 1].set_title('Corrected Integrated Data')
+ im01 = axs[0, 1].imshow(corrected_data, cmap="viridis")
+ plt.colorbar(im01, ax=axs[0, 1], shrink=0.6)
+ axs[0, 1].set_title("Corrected Integrated Data")
if show_markers:
-
- axs[0, 1].text(ChipsLabelPosition.chip3[0], ChipsLabelPosition.chip3[1],
- 'Chips3', color='white', fontsize=12, weight='bold', ha='left', va='bottom')
- axs[0, 1].text(ChipsLabelPosition.chip2[0], ChipsLabelPosition.chip2[1],
- 'Chips2', color='white', fontsize=12, weight='bold', ha='left', va='top')
- axs[0, 1].text(ChipsLabelPosition.chip1[0], ChipsLabelPosition.chip1[1],
- 'Chips1', color='white', fontsize=12, weight='bold', ha='right', va='top')
- axs[0, 1].text(ChipsLabelPosition.chip4[0], ChipsLabelPosition.chip4[1],
- 'Chips4', color='white', fontsize=12, weight='bold', ha='right', va='bottom')
-
- axs[0, 1].axvline(x=x, color='r', linestyle='--', alpha=0.2)
- axs[0, 1].axvline(x=x+size, color='r', linestyle='--', alpha=0.2)
- axs[0, 1].axhline(y=y, color='r', linestyle='--', alpha=0.2)
- axs[0, 1].axhline(y=y+size, color='r', linestyle='--', alpha=0.2)
- rect_container = patches.Rectangle((x, y), size, size, linewidth=1, edgecolor='yellow', facecolor='none')
+ axs[0, 1].text(
+ ChipsLabelPosition.chip3[0],
+ ChipsLabelPosition.chip3[1],
+ "Chips3",
+ color="white",
+ fontsize=12,
+ weight="bold",
+ ha="left",
+ va="bottom",
+ )
+ axs[0, 1].text(
+ ChipsLabelPosition.chip2[0],
+ ChipsLabelPosition.chip2[1],
+ "Chips2",
+ color="white",
+ fontsize=12,
+ weight="bold",
+ ha="left",
+ va="top",
+ )
+ axs[0, 1].text(
+ ChipsLabelPosition.chip1[0],
+ ChipsLabelPosition.chip1[1],
+ "Chips1",
+ color="white",
+ fontsize=12,
+ weight="bold",
+ ha="right",
+ va="top",
+ )
+ axs[0, 1].text(
+ ChipsLabelPosition.chip4[0],
+ ChipsLabelPosition.chip4[1],
+ "Chips4",
+ color="white",
+ fontsize=12,
+ weight="bold",
+ ha="right",
+ va="bottom",
+ )
+
+ axs[0, 1].axvline(x=x, color="r", linestyle="--", alpha=0.2)
+ axs[0, 1].axvline(x=x + size, color="r", linestyle="--", alpha=0.2)
+ axs[0, 1].axhline(y=y, color="r", linestyle="--", alpha=0.2)
+ axs[0, 1].axhline(y=y + size, color="r", linestyle="--", alpha=0.2)
+ rect_container = patches.Rectangle(
+ (x, y), size, size, linewidth=1, edgecolor="yellow", facecolor="none"
+ )
axs[0, 1].add_patch(rect_container)
-
+
# zoom in second row
- im10 = axs[1, 0].imshow(self.integrated_data[y:y+size, x:x+size], cmap='viridis')
- axs[1, 0].set_title(f'Zoomed Original Data (x: {x}, y: {y}, Size: {size}x)')
- plt.colorbar(im10, ax=axs[1,0], shrink=0.6)
-
- im11 = axs[1, 1].imshow(corrected_data[y:y+size, x:x+size], cmap='viridis')
- axs[1, 1].set_title(f'Zoomed Corrected Data (x: {x}, y: {y}, Size: {size}x)')
- plt.colorbar(im11, ax=axs[1,1], shrink=0.6)
-
+ im10 = axs[1, 0].imshow(
+ self.integrated_data[y : y + size, x : x + size], cmap="viridis"
+ )
+ axs[1, 0].set_title(f"Zoomed Original Data (x: {x}, y: {y}, Size: {size}x)")
+ plt.colorbar(im10, ax=axs[1, 0], shrink=0.6)
+
+ im11 = axs[1, 1].imshow(
+ corrected_data[y : y + size, x : x + size], cmap="viridis"
+ )
+ axs[1, 1].set_title(
+ f"Zoomed Corrected Data (x: {x}, y: {y}, Size: {size}x)"
+ )
+ plt.colorbar(im11, ax=axs[1, 1], shrink=0.6)
+
# plt.show()
plt.tight_layout()
-
+
height, width = self.integrated_data.shape
-
+
# if self.detector_type_ui.value == DetectorType.CUSTOM:
recalculate_button_disabled = False
# else:
# recalculate_button_disabled = True
-
+
display_preview_correction = interactive(
preview_correction,
- x=widgets.IntSlider(min=0, max=width-1, step=1,
- value=width//2-default_size//2,
- description='x:',
- layout=widgets.Layout(width='50%')),
- y=widgets.IntSlider(min=0, max=height-1, step=1,
- value=height//2-default_size//2,
- description='y:',
- layout=widgets.Layout(width='50%')),
- size=widgets.IntSlider(min=2, max=100, step=1,
- value=default_size,
- description='Size:',
- layout=widgets.Layout(width='50%')),
- show_markers=widgets.Checkbox(value=True,
- description='Show guides/labels'),
- # recalculate_button=widgets.ToggleButton(description="Recalculate Correction",
- # value=False,
- # disabled=recalculate_button_disabled,
- # layout=widgets.Layout(width="60%"),
+ x=widgets.IntSlider(
+ min=0,
+ max=width - 1,
+ step=1,
+ value=width // 2 - default_size // 2,
+ description="x:",
+ layout=widgets.Layout(width="50%"),
+ ),
+ y=widgets.IntSlider(
+ min=0,
+ max=height - 1,
+ step=1,
+ value=height // 2 - default_size // 2,
+ description="y:",
+ layout=widgets.Layout(width="50%"),
+ ),
+ size=widgets.IntSlider(
+ min=2,
+ max=100,
+ step=1,
+ value=default_size,
+ description="Size:",
+ layout=widgets.Layout(width="50%"),
+ ),
+ show_markers=widgets.Checkbox(value=True, description="Show guides/labels"),
+ # recalculate_button=widgets.ToggleButton(description="Recalculate Correction",
+ # value=False,
+ # disabled=recalculate_button_disabled,
+ # layout=widgets.Layout(width="60%"),
# )
)
display(display_preview_correction)
-
+
def select_output_folder(self):
_ = myfileselector.FileSelectorPanelWithJumpFolders(
instruction="Select Output Folder ...",
@@ -329,13 +429,13 @@ def select_output_folder(self):
)
self.out = widgets.Output()
display(self.out)
-
+
def perform_correction_of_entire_stack(self, folder_selected):
stack_of_images = self.working_data
working_file_names = self.working_list_files
-
+
with self.out:
- self.out.clear_output()
+ self.out.clear_output()
display(
HTML(
'
'
@@ -344,31 +444,33 @@ def perform_correction_of_entire_stack(self, folder_selected):
+ " files..."
)
)
-
+
for idx, img in tqdm(enumerate(stack_of_images)):
- o_corrector = TimepixGeometryCorrection(raw_images=img,
- config=self.detector_config)
+ o_corrector = TimepixGeometryCorrection(
+ raw_images=img, config=self.detector_config
+ )
corrected_image = o_corrector.correct(display=False)
base_name = os.path.basename(working_file_names[idx])
output_file = os.path.join(folder_selected, f"Corrected_{base_name}")
make_tiff(data=corrected_image[0], filename=output_file)
-
+
# o_corrector = TimepixGeometryCorrection(raw_images=stack_of_images,
# config=self.detector_config)
# corrected_images = o_corrector.correct(display=False)
-
+
# for idx, corrected_image in enumerate(corrected_images):
# base_name = os.path.basename(working_file_names[idx])
# output_file = os.path.join(folder_selected, f"Corrected_{base_name}")
# plt.imsave(output_file, corrected_image, cmap='viridis')
-
+
with self.out:
- self.out.clear_output()
+ self.out.clear_output()
display(
HTML(
'
'
+ str(len(stack_of_images))
- + " files have been corrected and saved to " + folder_selected + ""
+ + " files have been corrected and saved to "
+ + folder_selected
+ + ""
)
)
-
\ No newline at end of file
diff --git a/notebooks/__code/truncate_file_names/truncate_file_names.py b/notebooks/__code/truncate_file_names/truncate_file_names.py
index 5738d351..eaac3f9d 100755
--- a/notebooks/__code/truncate_file_names/truncate_file_names.py
+++ b/notebooks/__code/truncate_file_names/truncate_file_names.py
@@ -16,7 +16,9 @@ def __init__(self, working_dir=""):
def select_input_files(self):
self.input_files_ui = fileselector.FileSelectorPanel(
- instruction="Select List of Files", start_dir=self.working_dir, multiple=True
+ instruction="Select List of Files",
+ start_dir=self.working_dir,
+ multiple=True,
)
self.input_files_ui.show()
@@ -39,8 +41,12 @@ def __init__(self, o_truncate=None):
raise ValueError("TruncateFileNames is missing!")
if self.list_of_files:
- _random_input_list = utilities.get_n_random_element(input_list=self.list_of_files, n=10)
- self.random_input_list = [os.path.basename(_file) for _file in _random_input_list]
+ _random_input_list = utilities.get_n_random_element(
+ input_list=self.list_of_files, n=10
+ )
+ self.random_input_list = [
+ os.path.basename(_file) for _file in _random_input_list
+ ]
self.basename = os.path.basename(self.list_of_files[0])
self.working_dir = os.path.dirname(os.path.dirname(self.list_of_files[0]))
@@ -62,28 +68,40 @@ def show(self):
[
widgets.Label("Random Input:", layout=widgets.Layout(width="15%")),
widgets.Dropdown(
- options=self.random_input_list, value=self.random_input_list[0], layout=widgets.Layout(width="50%")
+ options=self.random_input_list,
+ value=self.random_input_list[0],
+ layout=widgets.Layout(width="50%"),
),
]
)
self.random_input_checkbox = self.box1.children[1]
- self.random_input_checkbox.observe(self.random_input_checkbox_value_changed, "value")
+ self.random_input_checkbox.observe(
+ self.random_input_checkbox_value_changed, "value"
+ )
- self.box2 = widgets.HBox([widgets.Label("String to remove:", layout=widgets.Layout(width="30%"))])
+ self.box2 = widgets.HBox(
+ [widgets.Label("String to remove:", layout=widgets.Layout(width="30%"))]
+ )
self.box6 = widgets.HBox(
[
- widgets.Label(value=" On the left:", layout=widgets.Layout(width="40%")),
+ widgets.Label(
+ value=" On the left:", layout=widgets.Layout(width="40%")
+ ),
widgets.Text(value="", layout=widgets.Layout(width="60%")),
]
)
self.box7 = widgets.HBox(
[
- widgets.Label(value=" On the right:", layout=widgets.Layout(width="40%")),
+ widgets.Label(
+ value=" On the right:", layout=widgets.Layout(width="40%")
+ ),
widgets.Text(value="", layout=widgets.Layout(width="60%")),
]
)
- self.box8 = widgets.VBox([self.box6, self.box7], layout=widgets.Layout(width="50%"))
+ self.box8 = widgets.VBox(
+ [self.box6, self.box7], layout=widgets.Layout(width="50%")
+ )
self.left_part_to_remove_text = self.box6.children[1]
self.right_part_to_remove_text = self.box7.children[1]
self.left_part_to_remove_text.observe(self.left_part_text_changed, "value")
@@ -99,7 +117,9 @@ def show(self):
separate_line = widgets.HTML(value="
", layout=widgets.Layout(width="100%"))
- vbox = widgets.VBox([self.box1, separate_line, self.box2, self.box8, separate_line, self.box9])
+ vbox = widgets.VBox(
+ [self.box1, separate_line, self.box2, self.box8, separate_line, self.box9]
+ )
display(vbox)
self.update_new_file_name()
@@ -127,8 +147,14 @@ def update_new_file_name(self):
def check_new_names(self):
dict_old_new_names = self.create_dict_old_new_filenames()
- old_names_new_names = [f"{os.path.basename(_key)} -> {_value}" for _key, _value in dict_old_new_names.items()]
- select_widget = widgets.Select(options=old_names_new_names, layout=widgets.Layout(width="100%", height="400px"))
+ old_names_new_names = [
+ f"{os.path.basename(_key)} -> {_value}"
+ for _key, _value in dict_old_new_names.items()
+ ]
+ select_widget = widgets.Select(
+ options=old_names_new_names,
+ layout=widgets.Layout(width="100%", height="400px"),
+ )
display(select_widget)
def create_dict_old_new_filenames(self):
@@ -165,7 +191,9 @@ def rename_and_export_files(self, output_folder=None):
input_folder = os.path.abspath(self.input_folder)
input_folder_renamed = os.path.basename(input_folder) + "_renamed"
self.output_folder_ui.shortcut_buttons.close()
- new_output_folder = os.path.join(os.path.abspath(output_folder), input_folder_renamed)
+ new_output_folder = os.path.join(
+ os.path.abspath(output_folder), input_folder_renamed
+ )
dict_old_new_names = self.create_dict_old_new_filenames()
utilities.copy_files(
diff --git a/notebooks/__code/ui_addie.py b/notebooks/__code/ui_addie.py
index d72ac030..990f234c 100755
--- a/notebooks/__code/ui_addie.py
+++ b/notebooks/__code/ui_addie.py
@@ -102,7 +102,9 @@ def setupUi(self, MainWindow):
self.verticalLayout_2 = QtWidgets.QVBoxLayout()
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.treeWidget = QtWidgets.QTreeWidget(self.centralwidget)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Expanding)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Expanding
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.treeWidget.sizePolicy().hasHeightForWidth())
@@ -111,7 +113,9 @@ def setupUi(self, MainWindow):
self.treeWidget.setMaximumSize(QtCore.QSize(250, 16777215))
self.treeWidget.setObjectName("treeWidget")
self.verticalLayout_2.addWidget(self.treeWidget)
- spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
+ spacerItem = QtWidgets.QSpacerItem(
+ 20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding
+ )
self.verticalLayout_2.addItem(spacerItem)
self.horizontalLayout.addLayout(self.verticalLayout_2)
MainWindow.setCentralWidget(self.centralwidget)
@@ -124,7 +128,9 @@ def setupUi(self, MainWindow):
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
- self.h3_table.customContextMenuRequested["QPoint"].connect(MainWindow.h3_table_right_click)
+ self.h3_table.customContextMenuRequested["QPoint"].connect(
+ MainWindow.h3_table_right_click
+ )
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
@@ -173,4 +179,6 @@ def retranslateUi(self, MainWindow):
item = self.h3_table.item(0, 7)
item.setText(_translate("MainWindow", "8"))
self.h3_table.setSortingEnabled(__sortingEnabled)
- self.treeWidget.headerItem().setText(0, _translate("MainWindow", "Columns Visibility"))
+ self.treeWidget.headerItem().setText(
+ 0, _translate("MainWindow", "Columns Visibility")
+ )
diff --git a/notebooks/__code/ui_addie_save_config.py b/notebooks/__code/ui_addie_save_config.py
index 44c84d48..0c27ee22 100755
--- a/notebooks/__code/ui_addie_save_config.py
+++ b/notebooks/__code/ui_addie_save_config.py
@@ -11,7 +11,9 @@ class Ui_Dialog:
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(401, 89)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Dialog.sizePolicy().hasHeightForWidth())
@@ -32,7 +34,9 @@ def setupUi(self, Dialog):
self.verticalLayout.addLayout(self.horizontalLayout)
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
- spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_2.addItem(spacerItem)
self.cancel_button = QtWidgets.QPushButton(Dialog)
self.cancel_button.setObjectName("cancel_button")
diff --git a/notebooks/__code/ui_bragg_edge_peak_fitting.py b/notebooks/__code/ui_bragg_edge_peak_fitting.py
index 0cef6be3..d4e91c1d 100755
--- a/notebooks/__code/ui_bragg_edge_peak_fitting.py
+++ b/notebooks/__code/ui_bragg_edge_peak_fitting.py
@@ -22,7 +22,9 @@ def setupUi(self, MainWindow):
self.verticalLayout = QtWidgets.QVBoxLayout(self.tab)
self.verticalLayout.setObjectName("verticalLayout")
self.splitter = QtWidgets.QSplitter(self.tab)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.splitter.sizePolicy().hasHeightForWidth())
@@ -41,7 +43,9 @@ def setupUi(self, MainWindow):
self.label = QtWidgets.QLabel(self.tab)
self.label.setMinimumSize(QtCore.QSize(200, 0))
self.label.setMaximumSize(QtCore.QSize(200, 16777215))
- self.label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
+ self.label.setAlignment(
+ QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter
+ )
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
self.lineEdit = QtWidgets.QLineEdit(self.tab)
@@ -57,7 +61,9 @@ def setupUi(self, MainWindow):
self.label_4 = QtWidgets.QLabel(self.tab)
self.label_4.setMinimumSize(QtCore.QSize(200, 0))
self.label_4.setMaximumSize(QtCore.QSize(200, 16777215))
- self.label_4.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
+ self.label_4.setAlignment(
+ QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter
+ )
self.label_4.setObjectName("label_4")
self.gridLayout.addWidget(self.label_4, 1, 0, 1, 1)
self.lineEdit_2 = QtWidgets.QLineEdit(self.tab)
@@ -71,7 +77,9 @@ def setupUi(self, MainWindow):
self.label_3.setObjectName("label_3")
self.gridLayout.addWidget(self.label_3, 1, 2, 1, 1)
self.horizontalLayout_2.addLayout(self.gridLayout)
- spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_2.addItem(spacerItem)
self.verticalLayout.addLayout(self.horizontalLayout_2)
self.tabWidget.addTab(self.tab, "")
@@ -127,7 +135,9 @@ def setupUi(self, MainWindow):
self.cancel_button = QtWidgets.QPushButton(self.centralwidget)
self.cancel_button.setObjectName("cancel_button")
self.horizontalLayout.addWidget(self.cancel_button)
- spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem1 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout.addItem(spacerItem1)
self.apply_button = QtWidgets.QPushButton(self.centralwidget)
self.apply_button.setObjectName("apply_button")
@@ -155,7 +165,9 @@ def retranslateUi(self, MainWindow):
self.label_2.setText(_translate("MainWindow", "m"))
self.label_4.setText(_translate("MainWindow", "detector offset"))
self.label_3.setText(_translate("MainWindow", "micros"))
- self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Selection"))
+ self.tabWidget.setTabText(
+ self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Selection")
+ )
self.groupBox.setTitle(_translate("MainWindow", "List of algorithms"))
self.radioButton_3.setText(_translate("MainWindow", "algorithm 3"))
self.radioButton_2.setText(_translate("MainWindow", "algorithm 2"))
@@ -170,6 +182,8 @@ def retranslateUi(self, MainWindow):
item.setText(_translate("MainWindow", "coeff2 value"))
item = self.tableWidget.horizontalHeaderItem(4)
item.setText(_translate("MainWindow", "coeff2 error"))
- self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Fitting"))
+ self.tabWidget.setTabText(
+ self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Fitting")
+ )
self.cancel_button.setText(_translate("MainWindow", "Cancel"))
self.apply_button.setText(_translate("MainWindow", "Use this peak"))
diff --git a/notebooks/__code/ui_calibrated_transmission.py b/notebooks/__code/ui_calibrated_transmission.py
index e4881d35..ee05fd2b 100755
--- a/notebooks/__code/ui_calibrated_transmission.py
+++ b/notebooks/__code/ui_calibrated_transmission.py
@@ -38,10 +38,14 @@ def setupUi(self, MainWindow):
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.pyqtgraph_widget = QtWidgets.QWidget(self.layoutWidget)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
- sizePolicy.setHeightForWidth(self.pyqtgraph_widget.sizePolicy().hasHeightForWidth())
+ sizePolicy.setHeightForWidth(
+ self.pyqtgraph_widget.sizePolicy().hasHeightForWidth()
+ )
self.pyqtgraph_widget.setSizePolicy(sizePolicy)
self.pyqtgraph_widget.setObjectName("pyqtgraph_widget")
self.horizontalLayout_2.addWidget(self.pyqtgraph_widget)
@@ -87,7 +91,9 @@ def setupUi(self, MainWindow):
self.use_calibration1_checkbox.setChecked(True)
self.use_calibration1_checkbox.setObjectName("use_calibration1_checkbox")
self.horizontalLayout_12.addWidget(self.use_calibration1_checkbox)
- spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_12.addItem(spacerItem)
self.verticalLayout_5.addLayout(self.horizontalLayout_12)
self.gridLayout = QtWidgets.QGridLayout()
@@ -113,7 +119,9 @@ def setupUi(self, MainWindow):
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
self.calibration1_x0_label.setPalette(palette)
- self.calibration1_x0_label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
+ self.calibration1_x0_label.setAlignment(
+ QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter
+ )
self.calibration1_x0_label.setObjectName("calibration1_x0_label")
self.gridLayout.addWidget(self.calibration1_x0_label, 0, 0, 1, 1)
self.calibration1_x0 = QtWidgets.QLineEdit(self.tab_3)
@@ -202,7 +210,9 @@ def setupUi(self, MainWindow):
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
self.calibration1_y0_label.setPalette(palette)
- self.calibration1_y0_label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
+ self.calibration1_y0_label.setAlignment(
+ QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter
+ )
self.calibration1_y0_label.setObjectName("calibration1_y0_label")
self.gridLayout.addWidget(self.calibration1_y0_label, 1, 0, 1, 1)
self.calibration1_y0 = QtWidgets.QLineEdit(self.tab_3)
@@ -294,9 +304,13 @@ def setupUi(self, MainWindow):
self.calibration1_index.setPalette(palette)
self.calibration1_index.setObjectName("calibration1_index")
self.horizontalLayout_4.addWidget(self.calibration1_index)
- self.calibration1_display_this_file_button = QtWidgets.QPushButton(self.calibration1_groupbox)
+ self.calibration1_display_this_file_button = QtWidgets.QPushButton(
+ self.calibration1_groupbox
+ )
self.calibration1_display_this_file_button.setMinimumSize(QtCore.QSize(0, 40))
- self.calibration1_display_this_file_button.setMaximumSize(QtCore.QSize(16777215, 40))
+ self.calibration1_display_this_file_button.setMaximumSize(
+ QtCore.QSize(16777215, 40)
+ )
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 30, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
@@ -317,7 +331,9 @@ def setupUi(self, MainWindow):
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
self.calibration1_display_this_file_button.setPalette(palette)
- self.calibration1_display_this_file_button.setObjectName("calibration1_display_this_file_button")
+ self.calibration1_display_this_file_button.setObjectName(
+ "calibration1_display_this_file_button"
+ )
self.horizontalLayout_4.addWidget(self.calibration1_display_this_file_button)
self.verticalLayout.addLayout(self.horizontalLayout_4)
self.label_2 = QtWidgets.QLabel(self.calibration1_groupbox)
@@ -349,9 +365,13 @@ def setupUi(self, MainWindow):
self.label_2.setAlignment(QtCore.Qt.AlignCenter)
self.label_2.setObjectName("label_2")
self.verticalLayout.addWidget(self.label_2)
- self.calibration1_use_current_file_button = QtWidgets.QPushButton(self.calibration1_groupbox)
+ self.calibration1_use_current_file_button = QtWidgets.QPushButton(
+ self.calibration1_groupbox
+ )
self.calibration1_use_current_file_button.setMinimumSize(QtCore.QSize(0, 40))
- self.calibration1_use_current_file_button.setMaximumSize(QtCore.QSize(16777215, 40))
+ self.calibration1_use_current_file_button.setMaximumSize(
+ QtCore.QSize(16777215, 40)
+ )
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(26, 30, 220))
brush.setStyle(QtCore.Qt.SolidPattern)
@@ -372,9 +392,13 @@ def setupUi(self, MainWindow):
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
self.calibration1_use_current_file_button.setPalette(palette)
- self.calibration1_use_current_file_button.setObjectName("calibration1_use_current_file_button")
+ self.calibration1_use_current_file_button.setObjectName(
+ "calibration1_use_current_file_button"
+ )
self.verticalLayout.addWidget(self.calibration1_use_current_file_button)
- spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
+ spacerItem1 = QtWidgets.QSpacerItem(
+ 20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding
+ )
self.verticalLayout.addItem(spacerItem1)
self.verticalLayout_5.addWidget(self.calibration1_groupbox)
self.tabWidget_2.addTab(self.tab_3, "")
@@ -388,7 +412,9 @@ def setupUi(self, MainWindow):
self.use_calibration2_checkbox.setChecked(True)
self.use_calibration2_checkbox.setObjectName("use_calibration2_checkbox")
self.horizontalLayout_13.addWidget(self.use_calibration2_checkbox)
- spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem2 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_13.addItem(spacerItem2)
self.verticalLayout_6.addLayout(self.horizontalLayout_13)
self.gridLayout_2 = QtWidgets.QGridLayout()
@@ -405,7 +431,9 @@ def setupUi(self, MainWindow):
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
self.calibration2_x0_label.setPalette(palette)
- self.calibration2_x0_label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
+ self.calibration2_x0_label.setAlignment(
+ QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter
+ )
self.calibration2_x0_label.setObjectName("calibration2_x0_label")
self.gridLayout_2.addWidget(self.calibration2_x0_label, 0, 0, 1, 1)
self.calibration2_x0 = QtWidgets.QLineEdit(self.tab_4)
@@ -467,7 +495,9 @@ def setupUi(self, MainWindow):
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
self.calibration2_y0_label.setPalette(palette)
- self.calibration2_y0_label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
+ self.calibration2_y0_label.setAlignment(
+ QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter
+ )
self.calibration2_y0_label.setObjectName("calibration2_y0_label")
self.gridLayout_2.addWidget(self.calibration2_y0_label, 1, 0, 1, 1)
self.calibration2_y0 = QtWidgets.QLineEdit(self.tab_4)
@@ -532,9 +562,13 @@ def setupUi(self, MainWindow):
self.calibration2_index.setPalette(palette)
self.calibration2_index.setObjectName("calibration2_index")
self.horizontalLayout_5.addWidget(self.calibration2_index)
- self.calibration2_display_this_file_button = QtWidgets.QPushButton(self.calibration2_groupbox)
+ self.calibration2_display_this_file_button = QtWidgets.QPushButton(
+ self.calibration2_groupbox
+ )
self.calibration2_display_this_file_button.setMinimumSize(QtCore.QSize(0, 40))
- self.calibration2_display_this_file_button.setMaximumSize(QtCore.QSize(16777215, 40))
+ self.calibration2_display_this_file_button.setMaximumSize(
+ QtCore.QSize(16777215, 40)
+ )
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(193, 22, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
@@ -546,7 +580,9 @@ def setupUi(self, MainWindow):
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
self.calibration2_display_this_file_button.setPalette(palette)
- self.calibration2_display_this_file_button.setObjectName("calibration2_display_this_file_button")
+ self.calibration2_display_this_file_button.setObjectName(
+ "calibration2_display_this_file_button"
+ )
self.horizontalLayout_5.addWidget(self.calibration2_display_this_file_button)
self.verticalLayout_9.addLayout(self.horizontalLayout_5)
self.label_4 = QtWidgets.QLabel(self.calibration2_groupbox)
@@ -569,9 +605,13 @@ def setupUi(self, MainWindow):
self.label_4.setAlignment(QtCore.Qt.AlignCenter)
self.label_4.setObjectName("label_4")
self.verticalLayout_9.addWidget(self.label_4)
- self.calibration2_use_current_file_button = QtWidgets.QPushButton(self.calibration2_groupbox)
+ self.calibration2_use_current_file_button = QtWidgets.QPushButton(
+ self.calibration2_groupbox
+ )
self.calibration2_use_current_file_button.setMinimumSize(QtCore.QSize(0, 40))
- self.calibration2_use_current_file_button.setMaximumSize(QtCore.QSize(16777215, 40))
+ self.calibration2_use_current_file_button.setMaximumSize(
+ QtCore.QSize(16777215, 40)
+ )
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(193, 22, 45))
brush.setStyle(QtCore.Qt.SolidPattern)
@@ -583,10 +623,14 @@ def setupUi(self, MainWindow):
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)
self.calibration2_use_current_file_button.setPalette(palette)
- self.calibration2_use_current_file_button.setObjectName("calibration2_use_current_file_button")
+ self.calibration2_use_current_file_button.setObjectName(
+ "calibration2_use_current_file_button"
+ )
self.verticalLayout_9.addWidget(self.calibration2_use_current_file_button)
self.verticalLayout_6.addWidget(self.calibration2_groupbox)
- spacerItem3 = QtWidgets.QSpacerItem(20, 305, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
+ spacerItem3 = QtWidgets.QSpacerItem(
+ 20, 305, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding
+ )
self.verticalLayout_6.addItem(spacerItem3)
self.tabWidget_2.addTab(self.tab_4, "")
self.verticalLayout_11.addWidget(self.tabWidget_2)
@@ -619,7 +663,9 @@ def setupUi(self, MainWindow):
self.remove_row.setFont(font)
self.remove_row.setObjectName("remove_row")
self.horizontalLayout_6.addWidget(self.remove_row)
- spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem4 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_6.addItem(spacerItem4)
self.add_row = QtWidgets.QPushButton(self.page_2)
self.add_row.setMinimumSize(QtCore.QSize(50, 40))
@@ -660,7 +706,9 @@ def setupUi(self, MainWindow):
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
self.horizontalLayout.addWidget(self.pushButton)
- spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem5 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout.addItem(spacerItem5)
self.export_button = QtWidgets.QPushButton(self.centralwidget)
self.export_button.setObjectName("export_button")
@@ -699,25 +747,55 @@ def setupUi(self, MainWindow):
self.tabWidget_2.setCurrentIndex(0)
self.file_slider.sliderMoved["int"].connect(MainWindow.slider_file_changed)
self.file_slider.valueChanged["int"].connect(MainWindow.slider_file_changed)
- self.previous_image_button.clicked.connect(MainWindow.previous_image_button_clicked)
+ self.previous_image_button.clicked.connect(
+ MainWindow.previous_image_button_clicked
+ )
self.next_image_button.clicked.connect(MainWindow.next_image_button_clicked)
self.export_button.clicked.connect(MainWindow.export_button_clicked)
- self.use_calibration1_checkbox.clicked.connect(MainWindow.use_calibration1_checked)
+ self.use_calibration1_checkbox.clicked.connect(
+ MainWindow.use_calibration1_checked
+ )
self.remove_row.clicked.connect(MainWindow.remove_row_button_clicked)
self.add_row.clicked.connect(MainWindow.add_row_button_clicked)
- self.calibration1_use_current_file_button.clicked.connect(MainWindow.use_current_calibration1_file)
- self.calibration2_use_current_file_button.clicked.connect(MainWindow.use_current_calibration2_file)
- self.calibration1_display_this_file_button.clicked.connect(MainWindow.display_this_cal1_file)
- self.calibration2_display_this_file_button.clicked.connect(MainWindow.display_this_cal2_file)
- self.calibration1_x0.returnPressed.connect(MainWindow.calibration1_widgets_changed)
- self.calibration1_width.returnPressed.connect(MainWindow.calibration1_widgets_changed)
- self.calibration1_y0.returnPressed.connect(MainWindow.calibration1_widgets_changed)
- self.calibration1_height.returnPressed.connect(MainWindow.calibration1_widgets_changed)
- self.calibration2_x0.returnPressed.connect(MainWindow.calibration2_widgets_changed)
- self.calibration2_width.returnPressed.connect(MainWindow.calibration2_widgets_changed)
- self.calibration2_y0.returnPressed.connect(MainWindow.calibration2_widgets_changed)
- self.calibration2_height.returnPressed.connect(MainWindow.calibration2_widgets_changed)
- self.use_calibration2_checkbox.clicked.connect(MainWindow.use_calibration2_checked)
+ self.calibration1_use_current_file_button.clicked.connect(
+ MainWindow.use_current_calibration1_file
+ )
+ self.calibration2_use_current_file_button.clicked.connect(
+ MainWindow.use_current_calibration2_file
+ )
+ self.calibration1_display_this_file_button.clicked.connect(
+ MainWindow.display_this_cal1_file
+ )
+ self.calibration2_display_this_file_button.clicked.connect(
+ MainWindow.display_this_cal2_file
+ )
+ self.calibration1_x0.returnPressed.connect(
+ MainWindow.calibration1_widgets_changed
+ )
+ self.calibration1_width.returnPressed.connect(
+ MainWindow.calibration1_widgets_changed
+ )
+ self.calibration1_y0.returnPressed.connect(
+ MainWindow.calibration1_widgets_changed
+ )
+ self.calibration1_height.returnPressed.connect(
+ MainWindow.calibration1_widgets_changed
+ )
+ self.calibration2_x0.returnPressed.connect(
+ MainWindow.calibration2_widgets_changed
+ )
+ self.calibration2_width.returnPressed.connect(
+ MainWindow.calibration2_widgets_changed
+ )
+ self.calibration2_y0.returnPressed.connect(
+ MainWindow.calibration2_widgets_changed
+ )
+ self.calibration2_height.returnPressed.connect(
+ MainWindow.calibration2_widgets_changed
+ )
+ self.use_calibration2_checkbox.clicked.connect(
+ MainWindow.use_calibration2_checked
+ )
self.pushButton.clicked.connect(MainWindow.help_button_clicked)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
@@ -727,33 +805,58 @@ def retranslateUi(self, MainWindow):
self.previous_image_button.setText(_translate("MainWindow", "Prev. Image"))
self.image_slider_value.setText(_translate("MainWindow", "0"))
self.next_image_button.setText(_translate("MainWindow", "Next Image"))
- self.use_calibration1_checkbox.setText(_translate("MainWindow", "Use Calibration"))
+ self.use_calibration1_checkbox.setText(
+ _translate("MainWindow", "Use Calibration")
+ )
self.calibration1_x0_label.setText(_translate("MainWindow", "X0"))
self.calibration1_width_label.setText(_translate("MainWindow", "width"))
self.calibration1_value_label.setText(_translate("MainWindow", "Value"))
self.calibration1_y0_label.setText(_translate("MainWindow", "y0"))
self.calibration1_height_label.setText(_translate("MainWindow", "height"))
- self.calibration1_groupbox.setTitle(_translate("MainWindow", "File to Use for this Calibration"))
+ self.calibration1_groupbox.setTitle(
+ _translate("MainWindow", "File to Use for this Calibration")
+ )
self.label_38.setText(_translate("MainWindow", "Index"))
self.calibration1_index.setText(_translate("MainWindow", "0"))
- self.calibration1_display_this_file_button.setText(_translate("MainWindow", "Display This File"))
+ self.calibration1_display_this_file_button.setText(
+ _translate("MainWindow", "Display This File")
+ )
self.label_2.setText(_translate("MainWindow", "or"))
- self.calibration1_use_current_file_button.setText(_translate("MainWindow", "Use Current File"))
- self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_3), _translate("MainWindow", "Calibration 1"))
- self.use_calibration2_checkbox.setText(_translate("MainWindow", "Use Calibration"))
+ self.calibration1_use_current_file_button.setText(
+ _translate("MainWindow", "Use Current File")
+ )
+ self.tabWidget_2.setTabText(
+ self.tabWidget_2.indexOf(self.tab_3),
+ _translate("MainWindow", "Calibration 1"),
+ )
+ self.use_calibration2_checkbox.setText(
+ _translate("MainWindow", "Use Calibration")
+ )
self.calibration2_x0_label.setText(_translate("MainWindow", "X0"))
self.calibration2_width_label.setText(_translate("MainWindow", "width"))
self.calibration2_value_label.setText(_translate("MainWindow", "Value"))
self.calibration2_y0_label.setText(_translate("MainWindow", "y0"))
self.calibration2_height_label.setText(_translate("MainWindow", "height"))
- self.calibration2_groupbox.setTitle(_translate("MainWindow", "File to Use for this Calibration"))
+ self.calibration2_groupbox.setTitle(
+ _translate("MainWindow", "File to Use for this Calibration")
+ )
self.label_45.setText(_translate("MainWindow", "Index"))
self.calibration2_index.setText(_translate("MainWindow", "0"))
- self.calibration2_display_this_file_button.setText(_translate("MainWindow", "Display This File"))
+ self.calibration2_display_this_file_button.setText(
+ _translate("MainWindow", "Display This File")
+ )
self.label_4.setText(_translate("MainWindow", "or"))
- self.calibration2_use_current_file_button.setText(_translate("MainWindow", "Use Current File"))
- self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.tab_4), _translate("MainWindow", "Calibration 2"))
- self.toolBox.setItemText(self.toolBox.indexOf(self.page), _translate("MainWindow", "Calibration Regions"))
+ self.calibration2_use_current_file_button.setText(
+ _translate("MainWindow", "Use Current File")
+ )
+ self.tabWidget_2.setTabText(
+ self.tabWidget_2.indexOf(self.tab_4),
+ _translate("MainWindow", "Calibration 2"),
+ )
+ self.toolBox.setItemText(
+ self.toolBox.indexOf(self.page),
+ _translate("MainWindow", "Calibration Regions"),
+ )
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "X0"))
item = self.tableWidget.horizontalHeaderItem(1)
@@ -764,20 +867,31 @@ def retranslateUi(self, MainWindow):
item.setText(_translate("MainWindow", "Height"))
self.remove_row.setText(_translate("MainWindow", "-"))
self.add_row.setText(_translate("MainWindow", "+"))
- self.toolBox.setItemText(self.toolBox.indexOf(self.page_2), _translate("MainWindow", "Measurement Regions"))
- self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Measurement"))
+ self.toolBox.setItemText(
+ self.toolBox.indexOf(self.page_2),
+ _translate("MainWindow", "Measurement Regions"),
+ )
+ self.tabWidget.setTabText(
+ self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Measurement")
+ )
item = self.summary_table.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "Files Name"))
item = self.summary_table.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Time Stamp"))
item = self.summary_table.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "Relative Time (s)"))
- self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Summary"))
+ self.tabWidget.setTabText(
+ self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Summary")
+ )
self.pushButton.setText(_translate("MainWindow", "Help"))
- self.export_button.setText(_translate("MainWindow", "Export Calibrated Transmission ..."))
+ self.export_button.setText(
+ _translate("MainWindow", "Export Calibrated Transmission ...")
+ )
self.actionExport_Profile.setText(_translate("MainWindow", "Profiles ..."))
self.actionWater_Intake.setText(_translate("MainWindow", "Water Intake ..."))
- self.actionImportedFilesMetadata.setText(_translate("MainWindow", "Imported Files and Metadata ..."))
+ self.actionImportedFilesMetadata.setText(
+ _translate("MainWindow", "Imported Files and Metadata ...")
+ )
self.actionBy_Time_Stamp.setText(_translate("MainWindow", "by Time Stamp"))
self.actionBy_File_Name.setText(_translate("MainWindow", "by File Name"))
self.actionDsc_files.setText(_translate("MainWindow", "dsc files ..."))
diff --git a/notebooks/__code/ui_display_counts_of_region_vs_stack.py b/notebooks/__code/ui_display_counts_of_region_vs_stack.py
index e8da981a..944338b5 100755
--- a/notebooks/__code/ui_display_counts_of_region_vs_stack.py
+++ b/notebooks/__code/ui_display_counts_of_region_vs_stack.py
@@ -17,7 +17,9 @@ def setupUi(self, MainWindow):
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName("verticalLayout")
self.widget = QtWidgets.QWidget(self.centralwidget)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.widget.sizePolicy().hasHeightForWidth())
@@ -49,12 +51,16 @@ def setupUi(self, MainWindow):
self.distance_source_detector_value = QtWidgets.QLineEdit(self.centralwidget)
self.distance_source_detector_value.setMinimumSize(QtCore.QSize(80, 0))
self.distance_source_detector_value.setMaximumSize(QtCore.QSize(80, 16777215))
- self.distance_source_detector_value.setObjectName("distance_source_detector_value")
+ self.distance_source_detector_value.setObjectName(
+ "distance_source_detector_value"
+ )
self.horizontalLayout_2.addWidget(self.distance_source_detector_value)
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setObjectName("label_2")
self.horizontalLayout_2.addWidget(self.label_2)
- spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_2.addItem(spacerItem)
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setObjectName("label_3")
@@ -67,7 +73,9 @@ def setupUi(self, MainWindow):
self.detector_offset_units = QtWidgets.QLabel(self.centralwidget)
self.detector_offset_units.setObjectName("detector_offset_units")
self.horizontalLayout_2.addWidget(self.detector_offset_units)
- spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem1 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_2.addItem(spacerItem1)
self.horizontalLayout_7.addLayout(self.horizontalLayout_2)
self.verticalLayout.addLayout(self.horizontalLayout_7)
@@ -83,7 +91,9 @@ def setupUi(self, MainWindow):
self.time_spectra_file_browse_button = QtWidgets.QPushButton(self.centralwidget)
self.time_spectra_file_browse_button.setMinimumSize(QtCore.QSize(100, 0))
self.time_spectra_file_browse_button.setMaximumSize(QtCore.QSize(100, 16777215))
- self.time_spectra_file_browse_button.setObjectName("time_spectra_file_browse_button")
+ self.time_spectra_file_browse_button.setObjectName(
+ "time_spectra_file_browse_button"
+ )
self.horizontalLayout_3.addWidget(self.time_spectra_file_browse_button)
self.verticalLayout.addLayout(self.horizontalLayout_3)
self.horizontalLayout = QtWidgets.QHBoxLayout()
@@ -103,9 +113,15 @@ def setupUi(self, MainWindow):
self.retranslateUi(MainWindow)
self.done_button.clicked.connect(MainWindow.done_button_clicked)
- self.distance_source_detector_value.editingFinished.connect(MainWindow.distance_source_detector_validated)
- self.detector_offset_value.returnPressed.connect(MainWindow.detector_offset_validated)
- self.time_spectra_file_browse_button.clicked.connect(MainWindow.time_spectra_file_browse_button_clicked)
+ self.distance_source_detector_value.editingFinished.connect(
+ MainWindow.distance_source_detector_validated
+ )
+ self.detector_offset_value.returnPressed.connect(
+ MainWindow.detector_offset_validated
+ )
+ self.time_spectra_file_browse_button.clicked.connect(
+ MainWindow.time_spectra_file_browse_button_clicked
+ )
self.file_index_ratio_button.clicked.connect(MainWindow.radio_button_clicked)
self.tof_radio_button.clicked.connect(MainWindow.radio_button_clicked)
self.lambda_radio_button.clicked.connect(MainWindow.radio_button_clicked)
@@ -124,5 +140,7 @@ def retranslateUi(self, MainWindow):
self.detector_offset_units.setText(_translate("MainWindow", "us"))
self.label_5.setText(_translate("MainWindow", "Time Spectra File:"))
self.time_spectra_file.setText(_translate("MainWindow", "N/A"))
- self.time_spectra_file_browse_button.setText(_translate("MainWindow", "Browse ..."))
+ self.time_spectra_file_browse_button.setText(
+ _translate("MainWindow", "Browse ...")
+ )
self.done_button.setText(_translate("MainWindow", "DONE"))
diff --git a/notebooks/__code/ui_dual_energy.py b/notebooks/__code/ui_dual_energy.py
index f57e15ba..c043ab35 100755
--- a/notebooks/__code/ui_dual_energy.py
+++ b/notebooks/__code/ui_dual_energy.py
@@ -16,7 +16,9 @@ def setupUi(self, MainWindow):
self.verticalLayout = QtWidgets.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName("verticalLayout")
self.widget = QtWidgets.QWidget(self.centralwidget)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.widget.sizePolicy().hasHeightForWidth())
@@ -50,12 +52,16 @@ def setupUi(self, MainWindow):
self.distance_source_detector_value = QtWidgets.QLineEdit(self.groupBox_4)
self.distance_source_detector_value.setMinimumSize(QtCore.QSize(80, 0))
self.distance_source_detector_value.setMaximumSize(QtCore.QSize(80, 16777215))
- self.distance_source_detector_value.setObjectName("distance_source_detector_value")
+ self.distance_source_detector_value.setObjectName(
+ "distance_source_detector_value"
+ )
self.horizontalLayout_4.addWidget(self.distance_source_detector_value)
self.label_2 = QtWidgets.QLabel(self.groupBox_4)
self.label_2.setObjectName("label_2")
self.horizontalLayout_4.addWidget(self.label_2)
- spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_4.addItem(spacerItem)
self.label_3 = QtWidgets.QLabel(self.groupBox_4)
self.label_3.setObjectName("label_3")
@@ -68,7 +74,9 @@ def setupUi(self, MainWindow):
self.detector_offset_units = QtWidgets.QLabel(self.groupBox_4)
self.detector_offset_units.setObjectName("detector_offset_units")
self.horizontalLayout_4.addWidget(self.detector_offset_units)
- spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem1 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_4.addItem(spacerItem1)
self.horizontalLayout_7.addWidget(self.groupBox_4)
self.verticalLayout.addLayout(self.horizontalLayout_7)
@@ -79,17 +87,23 @@ def setupUi(self, MainWindow):
self.horizontalLayout_6 = QtWidgets.QHBoxLayout(self.groupBox_2)
self.horizontalLayout_6.setObjectName("horizontalLayout_6")
self.time_spectra_file = QtWidgets.QLabel(self.groupBox_2)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
- sizePolicy.setHeightForWidth(self.time_spectra_file.sizePolicy().hasHeightForWidth())
+ sizePolicy.setHeightForWidth(
+ self.time_spectra_file.sizePolicy().hasHeightForWidth()
+ )
self.time_spectra_file.setSizePolicy(sizePolicy)
self.time_spectra_file.setObjectName("time_spectra_file")
self.horizontalLayout_6.addWidget(self.time_spectra_file)
self.time_spectra_file_browse_button = QtWidgets.QPushButton(self.groupBox_2)
self.time_spectra_file_browse_button.setMinimumSize(QtCore.QSize(100, 0))
self.time_spectra_file_browse_button.setMaximumSize(QtCore.QSize(100, 16777215))
- self.time_spectra_file_browse_button.setObjectName("time_spectra_file_browse_button")
+ self.time_spectra_file_browse_button.setObjectName(
+ "time_spectra_file_browse_button"
+ )
self.horizontalLayout_6.addWidget(self.time_spectra_file_browse_button)
self.horizontalLayout_5.addWidget(self.groupBox_2)
self.groupBox_3 = QtWidgets.QGroupBox(self.centralwidget)
@@ -128,12 +142,18 @@ def setupUi(self, MainWindow):
self.retranslateUi(MainWindow)
self.done_button.clicked.connect(MainWindow.done_button_clicked)
- self.distance_source_detector_value.editingFinished.connect(MainWindow.distance_source_detector_validated)
- self.detector_offset_value.returnPressed.connect(MainWindow.detector_offset_validated)
+ self.distance_source_detector_value.editingFinished.connect(
+ MainWindow.distance_source_detector_validated
+ )
+ self.detector_offset_value.returnPressed.connect(
+ MainWindow.detector_offset_validated
+ )
self.file_index_ratio_button.clicked.connect(MainWindow.radio_button_clicked)
self.tof_radio_button.clicked.connect(MainWindow.radio_button_clicked)
self.lambda_radio_button.clicked.connect(MainWindow.radio_button_clicked)
- self.time_spectra_file_browse_button.clicked.connect(MainWindow.time_spectra_file_browse_button_clicked)
+ self.time_spectra_file_browse_button.clicked.connect(
+ MainWindow.time_spectra_file_browse_button_clicked
+ )
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
@@ -150,7 +170,9 @@ def retranslateUi(self, MainWindow):
self.detector_offset_units.setText(_translate("MainWindow", "us"))
self.groupBox_2.setTitle(_translate("MainWindow", "Time Spectra File"))
self.time_spectra_file.setText(_translate("MainWindow", "N/A"))
- self.time_spectra_file_browse_button.setText(_translate("MainWindow", "Browse ..."))
+ self.time_spectra_file_browse_button.setText(
+ _translate("MainWindow", "Browse ...")
+ )
self.groupBox_3.setTitle(_translate("MainWindow", "Bin "))
self.label_4.setText(_translate("MainWindow", "Size"))
self.bin_units.setText(_translate("MainWindow", "files"))
diff --git a/notebooks/__code/ui_file_metadata_display.py b/notebooks/__code/ui_file_metadata_display.py
index 67a3ae72..24b5986a 100755
--- a/notebooks/__code/ui_file_metadata_display.py
+++ b/notebooks/__code/ui_file_metadata_display.py
@@ -21,7 +21,9 @@ def setupUi(self, MainWindow):
self.verticalLayout.setObjectName("verticalLayout")
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
- spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_3.addItem(spacerItem)
self.para_1_label = QtWidgets.QLabel(self.centralwidget)
self.para_1_label.setMinimumSize(QtCore.QSize(30, 0))
@@ -39,14 +41,18 @@ def setupUi(self, MainWindow):
self.para_2_value = QtWidgets.QLabel(self.centralwidget)
self.para_2_value.setObjectName("para_2_value")
self.horizontalLayout_3.addWidget(self.para_2_value)
- spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem1 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_3.addItem(spacerItem1)
self.verticalLayout.addLayout(self.horizontalLayout_3)
self.widget_2 = QtWidgets.QWidget(self.centralwidget)
self.widget_2.setObjectName("widget_2")
self.verticalLayout.addWidget(self.widget_2)
self.widget = QtWidgets.QWidget(self.centralwidget)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.widget.sizePolicy().hasHeightForWidth())
@@ -70,7 +76,9 @@ def setupUi(self, MainWindow):
self.tableWidget.setMinimumSize(QtCore.QSize(300, 0))
self.tableWidget.setMaximumSize(QtCore.QSize(300, 16777215))
self.tableWidget.setAlternatingRowColors(True)
- self.tableWidget.setSelectionMode(QtWidgets.QAbstractItemView.ContiguousSelection)
+ self.tableWidget.setSelectionMode(
+ QtWidgets.QAbstractItemView.ContiguousSelection
+ )
self.tableWidget.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(3)
@@ -88,7 +96,9 @@ def setupUi(self, MainWindow):
self.export_button = QtWidgets.QPushButton(self.centralwidget)
self.export_button.setObjectName("export_button")
self.horizontalLayout.addWidget(self.export_button)
- spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem2 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout.addItem(spacerItem2)
self.close_button = QtWidgets.QPushButton(self.centralwidget)
self.close_button.setObjectName("close_button")
@@ -104,7 +114,9 @@ def setupUi(self, MainWindow):
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
- self.tableWidget.itemSelectionChanged.connect(MainWindow.table_widget_selection_changed)
+ self.tableWidget.itemSelectionChanged.connect(
+ MainWindow.table_widget_selection_changed
+ )
self.close_button.clicked.connect(MainWindow.close_clicked)
self.group_slider.sliderMoved["int"].connect(MainWindow.refresh_pyqtgraph)
self.export_button.clicked.connect(MainWindow.export_button_clicked)
diff --git a/notebooks/__code/ui_gamma_filtering_tool.py b/notebooks/__code/ui_gamma_filtering_tool.py
index db940382..cb490e70 100755
--- a/notebooks/__code/ui_gamma_filtering_tool.py
+++ b/notebooks/__code/ui_gamma_filtering_tool.py
@@ -20,7 +20,9 @@ def setupUi(self, MainWindow):
self.splitter.setOrientation(QtCore.Qt.Vertical)
self.splitter.setObjectName("splitter")
self.image_widget = QtWidgets.QWidget(self.splitter)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.image_widget.sizePolicy().hasHeightForWidth())
@@ -49,7 +51,9 @@ def setupUi(self, MainWindow):
self.file_index_value.setObjectName("file_index_value")
self.horizontalLayout_2.addWidget(self.file_index_value)
self.horizontalLayout_4.addLayout(self.horizontalLayout_2)
- spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_4.addItem(spacerItem)
self.label_3 = QtWidgets.QLabel(self.layoutWidget)
self.label_3.setMinimumSize(QtCore.QSize(120, 0))
@@ -65,7 +69,9 @@ def setupUi(self, MainWindow):
self.horizontalLayout_4.addWidget(self.filtering_coefficient_value)
self.verticalLayout.addLayout(self.horizontalLayout_4)
self.tableWidget = QtWidgets.QTableWidget(self.layoutWidget)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tableWidget.sizePolicy().hasHeightForWidth())
@@ -90,7 +96,9 @@ def setupUi(self, MainWindow):
self.cancel_button = QtWidgets.QPushButton(self.layoutWidget)
self.cancel_button.setObjectName("cancel_button")
self.horizontalLayout.addWidget(self.cancel_button)
- spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem1 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout.addItem(spacerItem1)
self.apply_button = QtWidgets.QPushButton(self.layoutWidget)
self.apply_button.setObjectName("apply_button")
@@ -111,7 +119,9 @@ def setupUi(self, MainWindow):
self.apply_button.clicked.connect(MainWindow.apply_clicked)
self.file_index_slider.sliderPressed.connect(MainWindow.slider_clicked)
self.file_index_slider.valueChanged["int"].connect(MainWindow.slider_moved)
- self.filtering_coefficient_value.returnPressed.connect(MainWindow.filtering_coefficient_changed)
+ self.filtering_coefficient_value.returnPressed.connect(
+ MainWindow.filtering_coefficient_changed
+ )
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
diff --git a/notebooks/__code/ui_integrated_roi_counts_vs_file_name_and_time_stamp.py b/notebooks/__code/ui_integrated_roi_counts_vs_file_name_and_time_stamp.py
index 0b497213..b76381d6 100755
--- a/notebooks/__code/ui_integrated_roi_counts_vs_file_name_and_time_stamp.py
+++ b/notebooks/__code/ui_integrated_roi_counts_vs_file_name_and_time_stamp.py
@@ -54,10 +54,14 @@ def setupUi(self, MainWindow):
self.horizontalLayout_6.addWidget(self.display_size_label)
self.grid_size_slider = QtWidgets.QSlider(self.groupBox)
self.grid_size_slider.setEnabled(False)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
- sizePolicy.setHeightForWidth(self.grid_size_slider.sizePolicy().hasHeightForWidth())
+ sizePolicy.setHeightForWidth(
+ self.grid_size_slider.sizePolicy().hasHeightForWidth()
+ )
self.grid_size_slider.setSizePolicy(sizePolicy)
self.grid_size_slider.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.grid_size_slider.setMinimum(1)
@@ -125,7 +129,9 @@ def setupUi(self, MainWindow):
self.verticalLayout_5.setObjectName("verticalLayout_5")
self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
self.horizontalLayout_7.setObjectName("horizontalLayout_7")
- spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_7.addItem(spacerItem)
self.label = QtWidgets.QLabel(self.groupBox_2)
self.label.setObjectName("label")
@@ -215,7 +221,9 @@ def setupUi(self, MainWindow):
self.remove_roi_button.setFont(font)
self.remove_roi_button.setObjectName("remove_roi_button")
self.horizontalLayout_4.addWidget(self.remove_roi_button)
- spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem1 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_4.addItem(spacerItem1)
self.add_roi_button = QtWidgets.QPushButton(self.groupBox_2)
font = QtGui.QFont()
@@ -255,7 +263,9 @@ def setupUi(self, MainWindow):
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
self.horizontalLayout.addWidget(self.pushButton)
- spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem2 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout.addItem(spacerItem2)
self.export_button = QtWidgets.QPushButton(self.centralwidget)
self.export_button.setObjectName("export_button")
@@ -292,7 +302,9 @@ def setupUi(self, MainWindow):
self.tabWidget.setCurrentIndex(0)
self.file_slider.sliderMoved["int"].connect(MainWindow.slider_file_changed)
self.file_slider.valueChanged["int"].connect(MainWindow.slider_file_changed)
- self.previous_image_button.clicked.connect(MainWindow.previous_image_button_clicked)
+ self.previous_image_button.clicked.connect(
+ MainWindow.previous_image_button_clicked
+ )
self.next_image_button.clicked.connect(MainWindow.next_image_button_clicked)
self.export_button.clicked.connect(MainWindow.export_button_clicked)
self.pushButton.clicked.connect(MainWindow.help_button_clicked)
@@ -300,12 +312,24 @@ def setupUi(self, MainWindow):
self.add_roi_button.clicked.connect(MainWindow.add_row_button_clicked)
self.grid_display_checkBox.clicked.connect(MainWindow.display_grid_clicked)
self.grid_size_slider.sliderPressed.connect(MainWindow.grid_size_slider_clicked)
- self.grid_size_slider.sliderMoved["int"].connect(MainWindow.grid_size_slider_moved)
- self.transparency_slider.sliderPressed.connect(MainWindow.transparency_slider_clicked)
- self.transparency_slider.sliderMoved["int"].connect(MainWindow.transparency_slider_moved)
- self.tableWidget.itemSelectionChanged.connect(MainWindow.table_widget_selection_changed)
- self.tableWidget.cellChanged["int", "int"].connect(MainWindow.table_widget_cell_changed)
- self.grid_size_slider.sliderReleased.connect(MainWindow.grid_size_slider_released)
+ self.grid_size_slider.sliderMoved["int"].connect(
+ MainWindow.grid_size_slider_moved
+ )
+ self.transparency_slider.sliderPressed.connect(
+ MainWindow.transparency_slider_clicked
+ )
+ self.transparency_slider.sliderMoved["int"].connect(
+ MainWindow.transparency_slider_moved
+ )
+ self.tableWidget.itemSelectionChanged.connect(
+ MainWindow.table_widget_selection_changed
+ )
+ self.tableWidget.cellChanged["int", "int"].connect(
+ MainWindow.table_widget_cell_changed
+ )
+ self.grid_size_slider.sliderReleased.connect(
+ MainWindow.grid_size_slider_released
+ )
self.tabWidget.currentChanged["int"].connect(MainWindow.tab_changed)
self.add_radioButton.clicked.connect(MainWindow.algo_changed)
self.mean_readioButton.clicked.connect(MainWindow.algo_changed)
@@ -317,7 +341,9 @@ def retranslateUi(self, MainWindow):
self.groupBox.setTitle(_translate("MainWindow", "Grid"))
self.grid_display_checkBox.setText(_translate("MainWindow", "Display"))
self.display_size_label.setText(_translate("MainWindow", "Size"))
- self.display_transparency_label.setText(_translate("MainWindow", "Transparency"))
+ self.display_transparency_label.setText(
+ _translate("MainWindow", "Transparency")
+ )
self.previous_image_button.setText(_translate("MainWindow", "Prev. Image"))
self.image_slider_value.setText(_translate("MainWindow", "0"))
self.next_image_button.setText(_translate("MainWindow", "Next Image"))
@@ -335,22 +361,32 @@ def retranslateUi(self, MainWindow):
item.setText(_translate("MainWindow", "Width"))
item = self.tableWidget.horizontalHeaderItem(4)
item.setText(_translate("MainWindow", "Height"))
- self.label_3.setText(_translate("MainWindow", "ROI of selected row is displayed in RED"))
+ self.label_3.setText(
+ _translate("MainWindow", "ROI of selected row is displayed in RED")
+ )
self.remove_roi_button.setText(_translate("MainWindow", "-"))
self.add_roi_button.setText(_translate("MainWindow", "+"))
- self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Measurement"))
+ self.tabWidget.setTabText(
+ self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Measurement")
+ )
item = self.summary_table.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "Files Name"))
item = self.summary_table.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "Time Stamp"))
item = self.summary_table.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "Relative Time (s)"))
- self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Summary"))
+ self.tabWidget.setTabText(
+ self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Summary")
+ )
self.pushButton.setText(_translate("MainWindow", "Help"))
- self.export_button.setText(_translate("MainWindow", "Export Counts vs File Name and Time Stamp ..."))
+ self.export_button.setText(
+ _translate("MainWindow", "Export Counts vs File Name and Time Stamp ...")
+ )
self.actionExport_Profile.setText(_translate("MainWindow", "Profiles ..."))
self.actionWater_Intake.setText(_translate("MainWindow", "Water Intake ..."))
- self.actionImportedFilesMetadata.setText(_translate("MainWindow", "Imported Files and Metadata ..."))
+ self.actionImportedFilesMetadata.setText(
+ _translate("MainWindow", "Imported Files and Metadata ...")
+ )
self.actionBy_Time_Stamp.setText(_translate("MainWindow", "by Time Stamp"))
self.actionBy_File_Name.setText(_translate("MainWindow", "by File Name"))
self.actionDsc_files.setText(_translate("MainWindow", "dsc files ..."))
diff --git a/notebooks/__code/ui_linear_profile.py b/notebooks/__code/ui_linear_profile.py
index 6c7f37e4..d9c4d8af 100755
--- a/notebooks/__code/ui_linear_profile.py
+++ b/notebooks/__code/ui_linear_profile.py
@@ -19,7 +19,9 @@ def setupUi(self, MainWindow):
self.splitter.setOrientation(QtCore.Qt.Vertical)
self.splitter.setObjectName("splitter")
self.widget = QtWidgets.QWidget(self.splitter)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.widget.sizePolicy().hasHeightForWidth())
@@ -40,7 +42,9 @@ def setupUi(self, MainWindow):
self.file_index_slider.setOrientation(QtCore.Qt.Horizontal)
self.file_index_slider.setObjectName("file_index_slider")
self.horizontalLayout_2.addWidget(self.file_index_slider)
- spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_2.addItem(spacerItem)
self.verticalLayout.addLayout(self.horizontalLayout_2)
self.table_profile = QtWidgets.QTableWidget(self.layoutWidget)
@@ -87,7 +91,9 @@ def setupUi(self, MainWindow):
self.add_profile_2.setFont(font)
self.add_profile_2.setObjectName("add_profile_2")
self.horizontalLayout.addWidget(self.add_profile_2)
- spacerItem1 = QtWidgets.QSpacerItem(408, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem1 = QtWidgets.QSpacerItem(
+ 408, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout.addItem(spacerItem1)
self.pushButton = QtWidgets.QPushButton(self.layoutWidget)
self.pushButton.setMinimumSize(QtCore.QSize(53, 46))
@@ -96,7 +102,9 @@ def setupUi(self, MainWindow):
self.horizontalLayout.addWidget(self.pushButton)
self.verticalLayout.addLayout(self.horizontalLayout)
self.verticalLayout_2.addWidget(self.splitter)
- spacerItem2 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
+ spacerItem2 = QtWidgets.QSpacerItem(
+ 20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding
+ )
self.verticalLayout_2.addItem(spacerItem2)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
@@ -144,4 +152,6 @@ def retranslateUi(self, MainWindow):
self.add_profile_2.setText(_translate("MainWindow", "-"))
self.pushButton.setText(_translate("MainWindow", "OK"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
- self.actionExport_Profile.setText(_translate("MainWindow", "Export Profile ..."))
+ self.actionExport_Profile.setText(
+ _translate("MainWindow", "Export Profile ...")
+ )
diff --git a/notebooks/__code/ui_metadata_overlapping_images.py b/notebooks/__code/ui_metadata_overlapping_images.py
index ae1c6573..5e9b3301 100755
--- a/notebooks/__code/ui_metadata_overlapping_images.py
+++ b/notebooks/__code/ui_metadata_overlapping_images.py
@@ -28,10 +28,14 @@ def setupUi(self, MainWindow):
self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
self.horizontalLayout_7.setObjectName("horizontalLayout_7")
self.pyqtgraph_widget = QtWidgets.QWidget(self.layoutWidget)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
- sizePolicy.setHeightForWidth(self.pyqtgraph_widget.sizePolicy().hasHeightForWidth())
+ sizePolicy.setHeightForWidth(
+ self.pyqtgraph_widget.sizePolicy().hasHeightForWidth()
+ )
self.pyqtgraph_widget.setSizePolicy(sizePolicy)
self.pyqtgraph_widget.setObjectName("pyqtgraph_widget")
self.horizontalLayout_7.addWidget(self.pyqtgraph_widget)
@@ -91,7 +95,9 @@ def setupUi(self, MainWindow):
self.scale_vertical_orientation = QtWidgets.QRadioButton(self.scale_groupbox)
self.scale_vertical_orientation.setObjectName("scale_vertical_orientation")
self.horizontalLayout_2.addWidget(self.scale_vertical_orientation)
- spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_2.addItem(spacerItem)
self.verticalLayout_2.addLayout(self.horizontalLayout_2)
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
@@ -132,7 +138,9 @@ def setupUi(self, MainWindow):
self.scale_color_combobox.addItem("")
self.scale_color_combobox.addItem("")
self.horizontalLayout_5.addWidget(self.scale_color_combobox)
- spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem1 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_5.addItem(spacerItem1)
self.label = QtWidgets.QLabel(self.scale_groupbox)
self.label.setObjectName("label")
@@ -147,7 +155,9 @@ def setupUi(self, MainWindow):
self.horizontalLayout_11.addWidget(self.scale_groupbox)
self.verticalLayout_5 = QtWidgets.QVBoxLayout()
self.verticalLayout_5.setObjectName("verticalLayout_5")
- spacerItem2 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
+ spacerItem2 = QtWidgets.QSpacerItem(
+ 20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding
+ )
self.verticalLayout_5.addItem(spacerItem2)
self.scale_position_label = QtWidgets.QLabel(self.layoutWidget1)
self.scale_position_label.setEnabled(False)
@@ -181,7 +191,9 @@ def setupUi(self, MainWindow):
self.label_9.setAlignment(QtCore.Qt.AlignCenter)
self.label_9.setObjectName("label_9")
self.verticalLayout_5.addWidget(self.scale_position_frame)
- spacerItem3 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
+ spacerItem3 = QtWidgets.QSpacerItem(
+ 20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding
+ )
self.verticalLayout_5.addItem(spacerItem3)
self.horizontalLayout_11.addLayout(self.verticalLayout_5)
self.verticalLayout_4.addLayout(self.horizontalLayout_11)
@@ -259,12 +271,16 @@ def setupUi(self, MainWindow):
self.metadata_color_combobox.addItem("")
self.metadata_color_combobox.addItem("")
self.horizontalLayout_6.addWidget(self.metadata_color_combobox)
- spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem4 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_6.addItem(spacerItem4)
self.verticalLayout.addLayout(self.horizontalLayout_6)
self.horizontalLayout_14 = QtWidgets.QHBoxLayout()
self.horizontalLayout_14.setObjectName("horizontalLayout_14")
- spacerItem5 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem5 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_14.addItem(spacerItem5)
self.import_table_button = QtWidgets.QPushButton(self.metadata_groupbox)
self.import_table_button.setObjectName("import_table_button")
@@ -273,7 +289,9 @@ def setupUi(self, MainWindow):
self.horizontalLayout_13.addWidget(self.metadata_groupbox)
self.verticalLayout_8 = QtWidgets.QVBoxLayout()
self.verticalLayout_8.setObjectName("verticalLayout_8")
- spacerItem6 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
+ spacerItem6 = QtWidgets.QSpacerItem(
+ 20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding
+ )
self.verticalLayout_8.addItem(spacerItem6)
self.metadata_position_label = QtWidgets.QLabel(self.layoutWidget1)
self.metadata_position_label.setEnabled(False)
@@ -311,7 +329,9 @@ def setupUi(self, MainWindow):
self.label_11.setAlignment(QtCore.Qt.AlignCenter)
self.label_11.setObjectName("label_11")
self.verticalLayout_8.addWidget(self.metadata_position_frame)
- spacerItem7 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
+ spacerItem7 = QtWidgets.QSpacerItem(
+ 20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding
+ )
self.verticalLayout_8.addItem(spacerItem7)
self.enable_graph_checkbox = QtWidgets.QCheckBox(self.layoutWidget1)
self.enable_graph_checkbox.setEnabled(False)
@@ -372,7 +392,9 @@ def setupUi(self, MainWindow):
self.graph_color_combobox.addItem("")
self.graph_color_combobox.addItem("")
self.horizontalLayout_10.addWidget(self.graph_color_combobox)
- spacerItem8 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem8 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_10.addItem(spacerItem8)
self.verticalLayout_9.addLayout(self.horizontalLayout_10)
self.horizontalLayout_12 = QtWidgets.QHBoxLayout()
@@ -388,11 +410,15 @@ def setupUi(self, MainWindow):
self.metadata_graph_size_slider.setOrientation(QtCore.Qt.Horizontal)
self.metadata_graph_size_slider.setObjectName("metadata_graph_size_slider")
self.horizontalLayout_12.addWidget(self.metadata_graph_size_slider)
- spacerItem9 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem9 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_12.addItem(spacerItem9)
self.verticalLayout_9.addLayout(self.horizontalLayout_12)
self.verticalLayout_8.addWidget(self.graph_groupBox)
- spacerItem10 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
+ spacerItem10 = QtWidgets.QSpacerItem(
+ 20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding
+ )
self.verticalLayout_8.addItem(spacerItem10)
self.horizontalLayout_13.addLayout(self.verticalLayout_8)
self.verticalLayout_6.addLayout(self.horizontalLayout_13)
@@ -402,7 +428,9 @@ def setupUi(self, MainWindow):
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
self.horizontalLayout.addWidget(self.pushButton)
- spacerItem11 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem11 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout.addItem(spacerItem11)
self.export_button = QtWidgets.QPushButton(self.centralwidget)
self.export_button.setObjectName("export_button")
@@ -439,41 +467,93 @@ def setupUi(self, MainWindow):
self.export_button.clicked.connect(MainWindow.export_button_clicked)
self.pushButton.clicked.connect(MainWindow.help_button_clicked)
self.scale_checkbox.clicked["bool"].connect(MainWindow.scale_checkbox_clicked)
- self.metadata_checkbox.clicked["bool"].connect(MainWindow.metadata_checkbox_clicked)
- self.previous_image_button.clicked.connect(MainWindow.previous_image_button_clicked)
+ self.metadata_checkbox.clicked["bool"].connect(
+ MainWindow.metadata_checkbox_clicked
+ )
+ self.previous_image_button.clicked.connect(
+ MainWindow.previous_image_button_clicked
+ )
self.next_image_button.clicked.connect(MainWindow.next_image_button_clicked)
self.file_slider.sliderPressed.connect(MainWindow.slider_file_clicked)
self.file_slider.valueChanged["int"].connect(MainWindow.slider_file_changed)
- self.select_metadata_checkbox.clicked["bool"].connect(MainWindow.select_metadata_checkbox_clicked)
- self.select_metadata_combobox.currentIndexChanged["int"].connect(MainWindow.metadata_list_changed)
- self.scale_horizontal_orientation.clicked.connect(MainWindow.scale_orientation_clicked)
- self.scale_vertical_orientation.clicked.connect(MainWindow.scale_orientation_clicked)
- self.scale_thickness.valueChanged["int"].connect(MainWindow.scale_thickness_value_changed)
- self.scale_color_combobox.currentIndexChanged["int"].connect(MainWindow.scale_color_changed)
- self.scale_size_spinbox.valueChanged["int"].connect(MainWindow.scale_size_changed)
+ self.select_metadata_checkbox.clicked["bool"].connect(
+ MainWindow.select_metadata_checkbox_clicked
+ )
+ self.select_metadata_combobox.currentIndexChanged["int"].connect(
+ MainWindow.metadata_list_changed
+ )
+ self.scale_horizontal_orientation.clicked.connect(
+ MainWindow.scale_orientation_clicked
+ )
+ self.scale_vertical_orientation.clicked.connect(
+ MainWindow.scale_orientation_clicked
+ )
+ self.scale_thickness.valueChanged["int"].connect(
+ MainWindow.scale_thickness_value_changed
+ )
+ self.scale_color_combobox.currentIndexChanged["int"].connect(
+ MainWindow.scale_color_changed
+ )
+ self.scale_size_spinbox.valueChanged["int"].connect(
+ MainWindow.scale_size_changed
+ )
self.scale_real_size.returnPressed.connect(MainWindow.scale_real_size_changed)
- self.scale_units_combobox.currentIndexChanged["int"].connect(MainWindow.scale_units_changed)
- self.scale_position_x.sliderMoved["int"].connect(MainWindow.scale_position_moved)
+ self.scale_units_combobox.currentIndexChanged["int"].connect(
+ MainWindow.scale_units_changed
+ )
+ self.scale_position_x.sliderMoved["int"].connect(
+ MainWindow.scale_position_moved
+ )
self.scale_position_x.sliderPressed.connect(MainWindow.scale_position_clicked)
- self.metadata_position_x.sliderMoved["int"].connect(MainWindow.metadata_position_moved)
- self.metadata_position_x.sliderPressed.connect(MainWindow.metadata_position_clicked)
- self.metadata_position_y.sliderMoved["int"].connect(MainWindow.metadata_position_moved)
- self.metadata_position_y.sliderPressed.connect(MainWindow.metadata_position_clicked)
- self.scale_position_y.sliderMoved["int"].connect(MainWindow.scale_position_moved)
+ self.metadata_position_x.sliderMoved["int"].connect(
+ MainWindow.metadata_position_moved
+ )
+ self.metadata_position_x.sliderPressed.connect(
+ MainWindow.metadata_position_clicked
+ )
+ self.metadata_position_y.sliderMoved["int"].connect(
+ MainWindow.metadata_position_moved
+ )
+ self.metadata_position_y.sliderPressed.connect(
+ MainWindow.metadata_position_clicked
+ )
+ self.scale_position_y.sliderMoved["int"].connect(
+ MainWindow.scale_position_moved
+ )
self.scale_position_y.sliderPressed.connect(MainWindow.scale_position_clicked)
- self.metadata_color_combobox.currentIndexChanged["int"].connect(MainWindow.metadata_color_changed)
- self.manual_metadata_name.returnPressed.connect(MainWindow.metadata_name_return_pressed)
- self.manual_metadata_units.returnPressed.connect(MainWindow.metadata_name_return_pressed)
- self.metadata_graph_size_slider.sliderPressed.connect(MainWindow.metadata_graph_size_pressed)
- self.metadata_graph_size_slider.sliderMoved["int"].connect(MainWindow.metadata_graph_size_moved)
+ self.metadata_color_combobox.currentIndexChanged["int"].connect(
+ MainWindow.metadata_color_changed
+ )
+ self.manual_metadata_name.returnPressed.connect(
+ MainWindow.metadata_name_return_pressed
+ )
+ self.manual_metadata_units.returnPressed.connect(
+ MainWindow.metadata_name_return_pressed
+ )
+ self.metadata_graph_size_slider.sliderPressed.connect(
+ MainWindow.metadata_graph_size_pressed
+ )
+ self.metadata_graph_size_slider.sliderMoved["int"].connect(
+ MainWindow.metadata_graph_size_moved
+ )
self.import_table_button.clicked.connect(MainWindow.import_table_pressed)
- self.tableWidget.customContextMenuRequested["QPoint"].connect(MainWindow.metadata_table_right_click)
+ self.tableWidget.customContextMenuRequested["QPoint"].connect(
+ MainWindow.metadata_table_right_click
+ )
self.graph_position_y.sliderPressed.connect(MainWindow.graph_position_clicked)
self.graph_position_x.sliderPressed.connect(MainWindow.graph_position_clicked)
- self.graph_position_x.sliderMoved["int"].connect(MainWindow.graph_position_moved)
- self.graph_position_y.sliderMoved["int"].connect(MainWindow.graph_position_moved)
- self.enable_graph_checkbox.stateChanged["int"].connect(MainWindow.enable_graph_button_clicked)
- self.graph_color_combobox.currentIndexChanged["int"].connect(MainWindow.graph_color_changed)
+ self.graph_position_x.sliderMoved["int"].connect(
+ MainWindow.graph_position_moved
+ )
+ self.graph_position_y.sliderMoved["int"].connect(
+ MainWindow.graph_position_moved
+ )
+ self.enable_graph_checkbox.stateChanged["int"].connect(
+ MainWindow.enable_graph_button_clicked
+ )
+ self.graph_color_combobox.currentIndexChanged["int"].connect(
+ MainWindow.graph_color_changed
+ )
self.graph_position_x.sliderReleased.connect(MainWindow.graph_position_clicked)
self.graph_position_y.sliderReleased.connect(MainWindow.graph_position_clicked)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
@@ -486,7 +566,9 @@ def retranslateUi(self, MainWindow):
self.next_image_button.setText(_translate("MainWindow", "Next Image"))
self.scale_checkbox.setText(_translate("MainWindow", "Scale"))
self.label_2.setText(_translate("MainWindow", "Orientation:"))
- self.scale_horizontal_orientation.setText(_translate("MainWindow", "horizontal"))
+ self.scale_horizontal_orientation.setText(
+ _translate("MainWindow", "horizontal")
+ )
self.scale_vertical_orientation.setText(_translate("MainWindow", "vertical"))
self.label_3.setText(_translate("MainWindow", "Size:"))
self.label_4.setText(_translate("MainWindow", "pixels =="))
@@ -502,7 +584,9 @@ def retranslateUi(self, MainWindow):
self.label_8.setText(_translate("MainWindow", "x"))
self.label_9.setText(_translate("MainWindow", "y"))
self.metadata_checkbox.setText(_translate("MainWindow", "Metadata"))
- self.select_metadata_checkbox.setText(_translate("MainWindow", "Select metadata"))
+ self.select_metadata_checkbox.setText(
+ _translate("MainWindow", "Select metadata")
+ )
self.meta_label.setText(_translate("MainWindow", "Legend:"))
self.label_12.setText(_translate("MainWindow", "... [Value] ..."))
item = self.tableWidget.horizontalHeaderItem(0)
@@ -520,7 +604,9 @@ def retranslateUi(self, MainWindow):
self.label_10.setText(_translate("MainWindow", "x"))
self.label_11.setText(_translate("MainWindow", "y"))
self.enable_graph_checkbox.setText(_translate("MainWindow", "Enable Graph"))
- self.metadata_position_label_4.setText(_translate("MainWindow", "Graph Position"))
+ self.metadata_position_label_4.setText(
+ _translate("MainWindow", "Graph Position")
+ )
self.label_15.setText(_translate("MainWindow", "x"))
self.label_16.setText(_translate("MainWindow", "y"))
self.label_13.setText(_translate("MainWindow", "Color:"))
@@ -534,7 +620,9 @@ def retranslateUi(self, MainWindow):
self.export_button.setText(_translate("MainWindow", "Export Images ..."))
self.actionExport_Profile.setText(_translate("MainWindow", "Profiles ..."))
self.actionWater_Intake.setText(_translate("MainWindow", "Water Intake ..."))
- self.actionImportedFilesMetadata.setText(_translate("MainWindow", "Imported Files and Metadata ..."))
+ self.actionImportedFilesMetadata.setText(
+ _translate("MainWindow", "Imported Files and Metadata ...")
+ )
self.actionBy_Time_Stamp.setText(_translate("MainWindow", "by Time Stamp"))
self.actionBy_File_Name.setText(_translate("MainWindow", "by File Name"))
self.actionDsc_files.setText(_translate("MainWindow", "dsc files ..."))
diff --git a/notebooks/__code/ui_metadata_overlapping_images_string_format.py b/notebooks/__code/ui_metadata_overlapping_images_string_format.py
index 33855e32..4683aca2 100755
--- a/notebooks/__code/ui_metadata_overlapping_images_string_format.py
+++ b/notebooks/__code/ui_metadata_overlapping_images_string_format.py
@@ -47,12 +47,16 @@ def setupUi(self, MainWindow):
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setObjectName("pushButton_2")
self.horizontalLayout.addWidget(self.pushButton_2)
- spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout.addItem(spacerItem)
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setObjectName("pushButton_3")
self.horizontalLayout.addWidget(self.pushButton_3)
- spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem1 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout.addItem(spacerItem1)
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
@@ -68,8 +72,12 @@ def setupUi(self, MainWindow):
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
- self.first_part_lineEdit.textChanged["QString"].connect(MainWindow.string_format_changed)
- self.second_part_lineEdit.textChanged["QString"].connect(MainWindow.string_format_changed)
+ self.first_part_lineEdit.textChanged["QString"].connect(
+ MainWindow.string_format_changed
+ )
+ self.second_part_lineEdit.textChanged["QString"].connect(
+ MainWindow.string_format_changed
+ )
self.pushButton_3.clicked.connect(MainWindow.launch_help)
self.pushButton_2.clicked.connect(MainWindow.cancel)
self.pushButton.clicked.connect(MainWindow.ok)
diff --git a/notebooks/__code/ui_panoramic_stitching.py b/notebooks/__code/ui_panoramic_stitching.py
index 3b7986d0..5ca958a0 100755
--- a/notebooks/__code/ui_panoramic_stitching.py
+++ b/notebooks/__code/ui_panoramic_stitching.py
@@ -28,8 +28,12 @@ def setupUi(self, MainWindow):
self.verticalLayout_4.setObjectName("verticalLayout_4")
self.splitter_between_previews_and_table = QtWidgets.QSplitter(self.tab)
self.splitter_between_previews_and_table.setOrientation(QtCore.Qt.Vertical)
- self.splitter_between_previews_and_table.setObjectName("splitter_between_previews_and_table")
- self.splitter_between_previews = QtWidgets.QSplitter(self.splitter_between_previews_and_table)
+ self.splitter_between_previews_and_table.setObjectName(
+ "splitter_between_previews_and_table"
+ )
+ self.splitter_between_previews = QtWidgets.QSplitter(
+ self.splitter_between_previews_and_table
+ )
self.splitter_between_previews.setOrientation(QtCore.Qt.Horizontal)
self.splitter_between_previews.setObjectName("splitter_between_previews")
self.groupBox_2 = QtWidgets.QGroupBox(self.splitter_between_previews)
@@ -52,7 +56,9 @@ def setupUi(self, MainWindow):
self.target_widget.setObjectName("target_widget")
self.horizontalLayout_2.addWidget(self.target_widget)
self.verticalLayout.addLayout(self.horizontalLayout_2)
- self.tableWidget = QtWidgets.QTableWidget(self.splitter_between_previews_and_table)
+ self.tableWidget = QtWidgets.QTableWidget(
+ self.splitter_between_previews_and_table
+ )
self.tableWidget.setMaximumSize(QtCore.QSize(16777215, 200))
self.tableWidget.setAlternatingRowColors(True)
self.tableWidget.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
@@ -108,7 +114,9 @@ def setupUi(self, MainWindow):
self.up_button.setFlat(True)
self.up_button.setObjectName("up_button")
self.gridLayout.addWidget(self.up_button, 1, 3, 1, 1)
- spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.gridLayout.addItem(spacerItem, 2, 0, 1, 1)
self.left_left_button = QtWidgets.QPushButton(self.groupBox_4)
self.left_left_button.setStyleSheet("border: None")
@@ -125,7 +133,9 @@ def setupUi(self, MainWindow):
self.left_button.setFlat(True)
self.left_button.setObjectName("left_button")
self.gridLayout.addWidget(self.left_button, 2, 2, 1, 1)
- spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
+ spacerItem1 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum
+ )
self.gridLayout.addItem(spacerItem1, 2, 3, 1, 1)
self.right_button = QtWidgets.QPushButton(self.groupBox_4)
self.right_button.setStyleSheet("border: None")
@@ -139,7 +149,9 @@ def setupUi(self, MainWindow):
self.right_right_button.setFlat(True)
self.right_right_button.setObjectName("right_right_button")
self.gridLayout.addWidget(self.right_right_button, 2, 5, 1, 1)
- spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem2 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.gridLayout.addItem(spacerItem2, 2, 6, 1, 1)
self.down_button = QtWidgets.QPushButton(self.groupBox_4)
self.down_button.setStyleSheet("border: None")
@@ -157,7 +169,9 @@ def setupUi(self, MainWindow):
self.verticalLayout_7.addWidget(self.groupBox_4)
self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
- spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem3 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_4.addItem(spacerItem3)
self.label_2 = QtWidgets.QLabel(self.tab_2)
self.label_2.setObjectName("label_2")
@@ -202,7 +216,9 @@ def setupUi(self, MainWindow):
self.cancel_button = QtWidgets.QPushButton(self.centralwidget)
self.cancel_button.setObjectName("cancel_button")
self.horizontalLayout.addWidget(self.cancel_button)
- spacerItem4 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem4 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout.addItem(spacerItem4)
self.export_button = QtWidgets.QPushButton(self.centralwidget)
self.export_button.setObjectName("export_button")
@@ -225,8 +241,12 @@ def setupUi(self, MainWindow):
self.tabWidget.setCurrentIndex(0)
self.cancel_button.clicked.connect(MainWindow.cancel_clicked) # type: ignore
self.export_button.clicked.connect(MainWindow.apply_clicked) # type: ignore
- self.tableWidget.itemSelectionChanged.connect(MainWindow.table_widget_selection_changed) # type: ignore
- self.run_stitching_button.clicked.connect(MainWindow.run_stitching_button_clicked) # type: ignore
+ self.tableWidget.itemSelectionChanged.connect(
+ MainWindow.table_widget_selection_changed
+ ) # type: ignore
+ self.run_stitching_button.clicked.connect(
+ MainWindow.run_stitching_button_clicked
+ ) # type: ignore
self.left_button.pressed.connect(MainWindow.left_button_pressed) # type: ignore
self.left_button.released.connect(MainWindow.left_button_released) # type: ignore
self.left_left_button.pressed.connect(MainWindow.left_left_button_pressed) # type: ignore
@@ -257,12 +277,16 @@ def retranslateUi(self, MainWindow):
item = self.tableWidget.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "Status"))
self.run_stitching_button.setText(_translate("MainWindow", "Run Stitching "))
- self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Step 1"))
+ self.tabWidget.setTabText(
+ self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Step 1")
+ )
self.label.setText(_translate("MainWindow", "File Names"))
self.groupBox_4.setTitle(_translate("MainWindow", "Manual Mode"))
self.label_2.setText(_translate("MainWindow", "->"))
self.label_5.setText(_translate("MainWindow", "->>"))
- self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Step 2"))
+ self.tabWidget.setTabText(
+ self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Step 2")
+ )
self.groupBox_3.setTitle(_translate("MainWindow", "Stiched Image"))
self.cancel_button.setText(_translate("MainWindow", "Close"))
self.export_button.setText(_translate("MainWindow", "Export ..."))
diff --git a/notebooks/__code/ui_profile.py b/notebooks/__code/ui_profile.py
index 1b012680..ac144116 100755
--- a/notebooks/__code/ui_profile.py
+++ b/notebooks/__code/ui_profile.py
@@ -55,10 +55,14 @@ def setupUi(self, MainWindow):
self.horizontalLayout_6.addWidget(self.display_size_label)
self.grid_size_slider = QtWidgets.QSlider(self.groupBox)
self.grid_size_slider.setEnabled(False)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
- sizePolicy.setHeightForWidth(self.grid_size_slider.sizePolicy().hasHeightForWidth())
+ sizePolicy.setHeightForWidth(
+ self.grid_size_slider.sizePolicy().hasHeightForWidth()
+ )
self.grid_size_slider.setSizePolicy(sizePolicy)
self.grid_size_slider.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.grid_size_slider.setMinimum(1)
@@ -132,7 +136,9 @@ def setupUi(self, MainWindow):
self.label_6.setObjectName("label_6")
self.horizontalLayout_8.addWidget(self.label_6)
self.filename = QtWidgets.QLabel(self.layoutWidget)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filename.sizePolicy().hasHeightForWidth())
@@ -268,7 +274,9 @@ def setupUi(self, MainWindow):
self.pushButton_4.setFont(font)
self.pushButton_4.setObjectName("pushButton_4")
self.horizontalLayout_4.addWidget(self.pushButton_4)
- spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_4.addItem(spacerItem)
self.groupBox_2 = QtWidgets.QGroupBox(self.layoutWidget1)
self.groupBox_2.setObjectName("groupBox_2")
@@ -283,7 +291,9 @@ def setupUi(self, MainWindow):
self.profile_direction_y_axis.setObjectName("profile_direction_y_axis")
self.horizontalLayout_7.addWidget(self.profile_direction_y_axis)
self.horizontalLayout_4.addWidget(self.groupBox_2)
- spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem1 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout_4.addItem(spacerItem1)
self.pushButton_5 = QtWidgets.QPushButton(self.layoutWidget1)
font = QtGui.QFont()
@@ -316,10 +326,16 @@ def setupUi(self, MainWindow):
self.all_plots_verti_splitter = QtWidgets.QSplitter(self.layoutWidget2)
self.all_plots_verti_splitter.setOrientation(QtCore.Qt.Vertical)
self.all_plots_verti_splitter.setObjectName("all_plots_verti_splitter")
- self.all_plots_file_name_table = QtWidgets.QTableWidget(self.all_plots_verti_splitter)
+ self.all_plots_file_name_table = QtWidgets.QTableWidget(
+ self.all_plots_verti_splitter
+ )
self.all_plots_file_name_table.setAlternatingRowColors(True)
- self.all_plots_file_name_table.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
- self.all_plots_file_name_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
+ self.all_plots_file_name_table.setSelectionMode(
+ QtWidgets.QAbstractItemView.MultiSelection
+ )
+ self.all_plots_file_name_table.setSelectionBehavior(
+ QtWidgets.QAbstractItemView.SelectRows
+ )
self.all_plots_file_name_table.setObjectName("all_plots_file_name_table")
self.all_plots_file_name_table.setColumnCount(1)
self.all_plots_file_name_table.setRowCount(0)
@@ -327,10 +343,16 @@ def setupUi(self, MainWindow):
self.all_plots_file_name_table.setHorizontalHeaderItem(0, item)
self.all_plots_file_name_table.horizontalHeader().setStretchLastSection(True)
self.all_plots_file_name_table.verticalHeader().setStretchLastSection(False)
- self.all_plots_profiles_table = QtWidgets.QTableWidget(self.all_plots_verti_splitter)
+ self.all_plots_profiles_table = QtWidgets.QTableWidget(
+ self.all_plots_verti_splitter
+ )
self.all_plots_profiles_table.setAlternatingRowColors(True)
- self.all_plots_profiles_table.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
- self.all_plots_profiles_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
+ self.all_plots_profiles_table.setSelectionMode(
+ QtWidgets.QAbstractItemView.MultiSelection
+ )
+ self.all_plots_profiles_table.setSelectionBehavior(
+ QtWidgets.QAbstractItemView.SelectRows
+ )
self.all_plots_profiles_table.setObjectName("all_plots_profiles_table")
self.all_plots_profiles_table.setColumnCount(1)
self.all_plots_profiles_table.setRowCount(0)
@@ -366,7 +388,9 @@ def setupUi(self, MainWindow):
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setObjectName("pushButton")
self.horizontalLayout.addWidget(self.pushButton)
- spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem2 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout.addItem(spacerItem2)
self.export_button = QtWidgets.QPushButton(self.centralwidget)
self.export_button.setObjectName("export_button")
@@ -403,7 +427,9 @@ def setupUi(self, MainWindow):
self.tabWidget.setCurrentIndex(0)
self.file_slider.sliderMoved["int"].connect(MainWindow.slider_file_changed) # type: ignore
self.file_slider.valueChanged["int"].connect(MainWindow.slider_file_changed) # type: ignore
- self.previous_image_button.clicked.connect(MainWindow.previous_image_button_clicked) # type: ignore
+ self.previous_image_button.clicked.connect(
+ MainWindow.previous_image_button_clicked
+ ) # type: ignore
self.next_image_button.clicked.connect(MainWindow.next_image_button_clicked) # type: ignore
self.export_button.clicked.connect(MainWindow.export_button_clicked) # type: ignore
self.pushButton.clicked.connect(MainWindow.help_button_clicked) # type: ignore
@@ -411,22 +437,52 @@ def setupUi(self, MainWindow):
self.pushButton_5.clicked.connect(MainWindow.add_row_button_clicked) # type: ignore
self.grid_display_checkBox.clicked.connect(MainWindow.display_grid_clicked) # type: ignore
self.grid_size_slider.sliderPressed.connect(MainWindow.grid_size_slider_clicked) # type: ignore
- self.grid_size_slider.sliderMoved["int"].connect(MainWindow.grid_size_slider_moved) # type: ignore
- self.transparency_slider.sliderPressed.connect(MainWindow.transparency_slider_clicked) # type: ignore
- self.transparency_slider.sliderMoved["int"].connect(MainWindow.transparency_slider_moved) # type: ignore
- self.right_rotation_button_fast.clicked.connect(MainWindow.right_rotation_fast_clicked) # type: ignore
- self.right_rotation_button_slow.clicked.connect(MainWindow.right_rotation_slow_clicked) # type: ignore
- self.left_rotation_button_fast.clicked.connect(MainWindow.left_rotation_fast_clicked) # type: ignore
- self.left_rotation_button_slow.clicked.connect(MainWindow.left_rotation_slow_clicked) # type: ignore
- self.tableWidget.itemSelectionChanged.connect(MainWindow.table_widget_selection_changed) # type: ignore
- self.tableWidget_2.itemSelectionChanged.connect(MainWindow.table_widget_2_selection_changed) # type: ignore
- self.tableWidget.cellChanged["int", "int"].connect(MainWindow.table_widget_cell_changed) # type: ignore
- self.grid_size_slider.sliderReleased.connect(MainWindow.grid_size_slider_released) # type: ignore
- self.profile_direction_x_axis.clicked.connect(MainWindow.profile_along_axis_changed) # type: ignore
- self.profile_direction_y_axis.clicked.connect(MainWindow.profile_along_axis_changed) # type: ignore
+ self.grid_size_slider.sliderMoved["int"].connect(
+ MainWindow.grid_size_slider_moved
+ ) # type: ignore
+ self.transparency_slider.sliderPressed.connect(
+ MainWindow.transparency_slider_clicked
+ ) # type: ignore
+ self.transparency_slider.sliderMoved["int"].connect(
+ MainWindow.transparency_slider_moved
+ ) # type: ignore
+ self.right_rotation_button_fast.clicked.connect(
+ MainWindow.right_rotation_fast_clicked
+ ) # type: ignore
+ self.right_rotation_button_slow.clicked.connect(
+ MainWindow.right_rotation_slow_clicked
+ ) # type: ignore
+ self.left_rotation_button_fast.clicked.connect(
+ MainWindow.left_rotation_fast_clicked
+ ) # type: ignore
+ self.left_rotation_button_slow.clicked.connect(
+ MainWindow.left_rotation_slow_clicked
+ ) # type: ignore
+ self.tableWidget.itemSelectionChanged.connect(
+ MainWindow.table_widget_selection_changed
+ ) # type: ignore
+ self.tableWidget_2.itemSelectionChanged.connect(
+ MainWindow.table_widget_2_selection_changed
+ ) # type: ignore
+ self.tableWidget.cellChanged["int", "int"].connect(
+ MainWindow.table_widget_cell_changed
+ ) # type: ignore
+ self.grid_size_slider.sliderReleased.connect(
+ MainWindow.grid_size_slider_released
+ ) # type: ignore
+ self.profile_direction_x_axis.clicked.connect(
+ MainWindow.profile_along_axis_changed
+ ) # type: ignore
+ self.profile_direction_y_axis.clicked.connect(
+ MainWindow.profile_along_axis_changed
+ ) # type: ignore
self.tabWidget.currentChanged["int"].connect(MainWindow.tab_changed) # type: ignore
- self.all_plots_file_name_table.itemSelectionChanged.connect(MainWindow.update_all_plots) # type: ignore
- self.all_plots_profiles_table.itemSelectionChanged.connect(MainWindow.update_all_plots) # type: ignore
+ self.all_plots_file_name_table.itemSelectionChanged.connect(
+ MainWindow.update_all_plots
+ ) # type: ignore
+ self.all_plots_profiles_table.itemSelectionChanged.connect(
+ MainWindow.update_all_plots
+ ) # type: ignore
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
@@ -435,7 +491,9 @@ def retranslateUi(self, MainWindow):
self.groupBox.setTitle(_translate("MainWindow", "Grid"))
self.grid_display_checkBox.setText(_translate("MainWindow", "Display"))
self.display_size_label.setText(_translate("MainWindow", "Size"))
- self.display_transparency_label.setText(_translate("MainWindow", "Transparency"))
+ self.display_transparency_label.setText(
+ _translate("MainWindow", "Transparency")
+ )
self.previous_image_button.setText(_translate("MainWindow", "Prev. Image"))
self.image_slider_value.setText(_translate("MainWindow", "0"))
self.next_image_button.setText(_translate("MainWindow", "Next Image"))
@@ -455,20 +513,30 @@ def retranslateUi(self, MainWindow):
item.setText(_translate("MainWindow", "Height"))
item = self.tableWidget_2.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "Width"))
- self.label_3.setText(_translate("MainWindow", "ROI of selected row is displayed in RED"))
+ self.label_3.setText(
+ _translate("MainWindow", "ROI of selected row is displayed in RED")
+ )
self.pushButton_4.setText(_translate("MainWindow", "-"))
self.groupBox_2.setTitle(_translate("MainWindow", "Profile Direction"))
self.profile_direction_x_axis.setText(_translate("MainWindow", "x-axis"))
self.profile_direction_y_axis.setText(_translate("MainWindow", "y-axis"))
self.pushButton_5.setText(_translate("MainWindow", "+"))
- self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Measurement"))
- self.label_5.setText(_translate("MainWindow", "Select the FILE(s) and the PROFILE(s) you want to display!"))
+ self.tabWidget.setTabText(
+ self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Measurement")
+ )
+ self.label_5.setText(
+ _translate(
+ "MainWindow",
+ "Select the FILE(s) and the PROFILE(s) you want to display!",
+ )
+ )
item = self.all_plots_file_name_table.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "File Names"))
item = self.all_plots_profiles_table.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "Profiles"))
self.tabWidget.setTabText(
- self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "All Profiles / All Images")
+ self.tabWidget.indexOf(self.tab_3),
+ _translate("MainWindow", "All Profiles / All Images"),
)
item = self.summary_table.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "Files Name"))
@@ -476,12 +544,16 @@ def retranslateUi(self, MainWindow):
item.setText(_translate("MainWindow", "Time Stamp"))
item = self.summary_table.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "Relative Time (s)"))
- self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Summary"))
+ self.tabWidget.setTabText(
+ self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Summary")
+ )
self.pushButton.setText(_translate("MainWindow", "Help"))
self.export_button.setText(_translate("MainWindow", "Export Profiles ..."))
self.actionExport_Profile.setText(_translate("MainWindow", "Profiles ..."))
self.actionWater_Intake.setText(_translate("MainWindow", "Water Intake ..."))
- self.actionImportedFilesMetadata.setText(_translate("MainWindow", "Imported Files and Metadata ..."))
+ self.actionImportedFilesMetadata.setText(
+ _translate("MainWindow", "Imported Files and Metadata ...")
+ )
self.actionBy_Time_Stamp.setText(_translate("MainWindow", "by Time Stamp"))
self.actionBy_File_Name.setText(_translate("MainWindow", "by File Name"))
self.actionDsc_files.setText(_translate("MainWindow", "dsc files ..."))
diff --git a/notebooks/__code/ui_radial_profile.py b/notebooks/__code/ui_radial_profile.py
index fa41659c..0cceda0d 100755
--- a/notebooks/__code/ui_radial_profile.py
+++ b/notebooks/__code/ui_radial_profile.py
@@ -24,7 +24,9 @@ def setupUi(self, MainWindow):
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.widget = QtWidgets.QWidget(self.tab_2)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.widget.sizePolicy().hasHeightForWidth())
@@ -34,7 +36,9 @@ def setupUi(self, MainWindow):
self.verticalLayout_3 = QtWidgets.QVBoxLayout()
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.groupBox_2 = QtWidgets.QGroupBox(self.tab_2)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Preferred)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Preferred
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox_2.sizePolicy().hasHeightForWidth())
@@ -65,7 +69,8 @@ def setupUi(self, MainWindow):
self.verticalLayout_3.addWidget(self.groupBox_2)
self.groupBox_3 = QtWidgets.QGroupBox(self.tab_2)
sizePolicy = QtWidgets.QSizePolicy(
- QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding
+ QtWidgets.QSizePolicy.MinimumExpanding,
+ QtWidgets.QSizePolicy.MinimumExpanding,
)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
@@ -91,7 +96,9 @@ def setupUi(self, MainWindow):
self.sector_from_value.setMinimumSize(QtCore.QSize(30, 0))
self.sector_from_value.setMaximumSize(QtCore.QSize(30, 16777215))
self.sector_from_value.setText("")
- self.sector_from_value.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
+ self.sector_from_value.setAlignment(
+ QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter
+ )
self.sector_from_value.setObjectName("sector_from_value")
self.gridLayout_2.addWidget(self.sector_from_value, 0, 2, 1, 1)
self.sector_to_label = QtWidgets.QLabel(self.groupBox_3)
@@ -102,10 +109,14 @@ def setupUi(self, MainWindow):
self.gridLayout_2.addWidget(self.sector_from_label, 0, 0, 1, 1)
self.from_angle_slider = QtWidgets.QScrollBar(self.groupBox_3)
self.from_angle_slider.setEnabled(False)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
- sizePolicy.setHeightForWidth(self.from_angle_slider.sizePolicy().hasHeightForWidth())
+ sizePolicy.setHeightForWidth(
+ self.from_angle_slider.sizePolicy().hasHeightForWidth()
+ )
self.from_angle_slider.setSizePolicy(sizePolicy)
self.from_angle_slider.setMaximum(360)
self.from_angle_slider.setOrientation(QtCore.Qt.Horizontal)
@@ -113,7 +124,9 @@ def setupUi(self, MainWindow):
self.gridLayout_2.addWidget(self.from_angle_slider, 0, 1, 1, 1)
self.sector_to_value = QtWidgets.QLabel(self.groupBox_3)
self.sector_to_value.setText("")
- self.sector_to_value.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
+ self.sector_to_value.setAlignment(
+ QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter
+ )
self.sector_to_value.setObjectName("sector_to_value")
self.gridLayout_2.addWidget(self.sector_to_value, 1, 2, 1, 1)
self.to_angle_slider = QtWidgets.QScrollBar(self.groupBox_3)
@@ -182,12 +195,16 @@ def setupUi(self, MainWindow):
self.grid_size_slider.setObjectName("grid_size_slider")
self.gridLayout_3.addWidget(self.grid_size_slider, 4, 1, 1, 1)
self.verticalLayout_3.addWidget(self.groupBox_4)
- spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
+ spacerItem = QtWidgets.QSpacerItem(
+ 20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding
+ )
self.verticalLayout_3.addItem(spacerItem)
self.horizontalLayout_2.addLayout(self.verticalLayout_3)
self.verticalLayout_4.addLayout(self.horizontalLayout_2)
self.groupBox = QtWidgets.QGroupBox(self.tab_2)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth())
@@ -200,7 +217,9 @@ def setupUi(self, MainWindow):
self.verticalLayout.setObjectName("verticalLayout")
self.textBrowser = QtWidgets.QTextBrowser(self.groupBox)
self.textBrowser.setEnabled(False)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.textBrowser.sizePolicy().hasHeightForWidth())
@@ -219,10 +238,14 @@ def setupUi(self, MainWindow):
self.calculate_profiles_button.setObjectName("calculate_profiles_button")
self.verticalLayout_6.addWidget(self.calculate_profiles_button)
self.widget_profile = QtWidgets.QWidget(self.tab)
- sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
+ sizePolicy = QtWidgets.QSizePolicy(
+ QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding
+ )
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
- sizePolicy.setHeightForWidth(self.widget_profile.sizePolicy().hasHeightForWidth())
+ sizePolicy.setHeightForWidth(
+ self.widget_profile.sizePolicy().hasHeightForWidth()
+ )
self.widget_profile.setSizePolicy(sizePolicy)
self.widget_profile.setObjectName("widget_profile")
self.verticalLayout_6.addWidget(self.widget_profile)
@@ -237,7 +260,9 @@ def setupUi(self, MainWindow):
self.help_button = QtWidgets.QPushButton(self.centralwidget)
self.help_button.setObjectName("help_button")
self.horizontalLayout.addWidget(self.help_button)
- spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
+ spacerItem1 = QtWidgets.QSpacerItem(
+ 40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum
+ )
self.horizontalLayout.addItem(spacerItem1)
self.cancel_button = QtWidgets.QPushButton(self.centralwidget)
self.cancel_button.setObjectName("cancel_button")
@@ -258,16 +283,30 @@ def setupUi(self, MainWindow):
self.sector_full_circle.clicked.connect(MainWindow.sector_radio_button_changed)
self.sector_sector.clicked.connect(MainWindow.sector_radio_button_changed)
self.guide_red_slider.sliderMoved["int"].connect(MainWindow.guide_color_changed)
- self.guide_green_slider.sliderMoved["int"].connect(MainWindow.guide_color_changed)
- self.guide_blue_slider.sliderMoved["int"].connect(MainWindow.guide_color_changed)
- self.guide_alpha_slider.sliderMoved["int"].connect(MainWindow.guide_color_changed)
+ self.guide_green_slider.sliderMoved["int"].connect(
+ MainWindow.guide_color_changed
+ )
+ self.guide_blue_slider.sliderMoved["int"].connect(
+ MainWindow.guide_color_changed
+ )
+ self.guide_alpha_slider.sliderMoved["int"].connect(
+ MainWindow.guide_color_changed
+ )
self.grid_size_slider.sliderMoved["int"].connect(MainWindow.grid_slider_moved)
self.grid_size_slider.sliderPressed.connect(MainWindow.grid_slider_pressed)
- self.from_angle_slider.sliderMoved["int"].connect(MainWindow.sector_from_angle_moved)
- self.to_angle_slider.sliderMoved["int"].connect(MainWindow.sector_to_angle_moved)
- self.from_angle_slider.sliderPressed.connect(MainWindow.sector_from_angle_clicked)
+ self.from_angle_slider.sliderMoved["int"].connect(
+ MainWindow.sector_from_angle_moved
+ )
+ self.to_angle_slider.sliderMoved["int"].connect(
+ MainWindow.sector_to_angle_moved
+ )
+ self.from_angle_slider.sliderPressed.connect(
+ MainWindow.sector_from_angle_clicked
+ )
self.to_angle_slider.sliderPressed.connect(MainWindow.sector_to_angle_clicked)
- self.from_angle_slider.sliderReleased.connect(MainWindow.sector_from_angle_clicked)
+ self.from_angle_slider.sliderReleased.connect(
+ MainWindow.sector_from_angle_clicked
+ )
self.to_angle_slider.sliderReleased.connect(MainWindow.sector_to_angle_clicked)
self.guide_red_slider.sliderPressed.connect(MainWindow.guide_color_clicked)
self.guide_red_slider.sliderReleased.connect(MainWindow.guide_color_released)
@@ -278,9 +317,15 @@ def setupUi(self, MainWindow):
self.guide_alpha_slider.sliderPressed.connect(MainWindow.guide_color_clicked)
self.guide_alpha_slider.sliderReleased.connect(MainWindow.guide_color_released)
self.grid_size_slider.sliderReleased.connect(MainWindow.grid_slider_pressed)
- self.from_angle_slider.valueChanged["int"].connect(MainWindow.sector_from_angle_moved)
- self.to_angle_slider.valueChanged["int"].connect(MainWindow.sector_to_angle_moved)
- self.calculate_profiles_button.clicked.connect(MainWindow.calculate_profiles_clicked)
+ self.from_angle_slider.valueChanged["int"].connect(
+ MainWindow.sector_from_angle_moved
+ )
+ self.to_angle_slider.valueChanged["int"].connect(
+ MainWindow.sector_to_angle_moved
+ )
+ self.calculate_profiles_button.clicked.connect(
+ MainWindow.calculate_profiles_clicked
+ )
self.export_profiles_button.clicked.connect(MainWindow.export_profiles_clicked)
self.help_button.clicked.connect(MainWindow.help_button_clicked)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
@@ -317,9 +362,18 @@ def retranslateUi(self, MainWindow):
'
* Export profiles