Skip to content

Commit

Permalink
Merge pull request #21 from anananacr/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
anananacr authored Apr 9, 2024
2 parents 1a20b4f + a2b45d5 commit 4cc49fe
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 24 deletions.
67 changes: 51 additions & 16 deletions bblib/methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import multiprocessing
import pathlib
from scipy.optimize import curve_fit

from matplotlib.colors import LogNorm

class CenteringMethod(ABC):
@abstractmethod
Expand Down Expand Up @@ -54,6 +54,13 @@ def __init__(self, config: dict, PF8Config: PF8Info, plots_info: dict = None):
"From config you want to save plots, please indicate the information to save the plots."
)

if not config["plots_flag"] and not plots_info:
plots_info = {
"file_name": "",
"folder_name": "",
"root_path": ""
}

def _prep_for_centering(self, data: np.ndarray) -> None:
self.initial_detector_center = self.PF8Config.get_detector_center()
pf8 = PF8(self.PF8Config)
Expand Down Expand Up @@ -113,7 +120,7 @@ def _run_centering(self, **kwargs) -> tuple:
fig, ax1 = plt.subplots(1, 1, figsize=(10, 10))
ax1.imshow(
self.visual_data * self.mask_for_center_of_mass,
vmax=10,
norm=LogNorm(),
cmap="YlGn",
origin="lower",
)
Expand Down Expand Up @@ -153,6 +160,13 @@ def __init__(self, config: dict, PF8Config: PF8Info, plots_info: dict = None):
"From config you want to save plots, please indicate the information to save the plots."
)

if not config["plots_flag"] and not plots_info:
plots_info = {
"file_name": "",
"folder_name": "",
"root_path": ""
}

def _prep_for_centering(self, data: np.ndarray) -> None:
self.initial_detector_center = self.PF8Config.get_detector_center()
## Find peaks
Expand Down Expand Up @@ -245,7 +259,7 @@ def _run_centering(self, **kwargs) -> tuple:
fig, ax1 = plt.subplots(1, 1, figsize=(10, 10))
ax1.imshow(
self.visual_data * self.mask_for_circle_detection,
vmax=10,
norm=LogNorm(),
origin="lower",
cmap="YlGn",
)
Expand Down Expand Up @@ -286,6 +300,14 @@ def __init__(self, config: dict, PF8Config: PF8Info, plots_info: dict = None):
"From config you want to save plots, please indicate the information to save the plots."
)

if not config["plots_flag"] and not plots_info:
plots_info = {
"file_name": "",
"folder_name": "",
"root_path": ""
}


def _calculate_fwhm(self, coordinate: tuple) -> dict:
center_to_radial_average = coordinate
try:
Expand Down Expand Up @@ -375,16 +397,16 @@ def _calculate_fwhm(self, coordinate: tuple) -> dict:
def _prep_for_centering(self, data: np.ndarray, initial_guess: tuple) -> None:
self.initial_guess = initial_guess
self.initial_detector_center = self.PF8Config.get_detector_center()
non_shifted_pixel_maps_for_visualization = self.PF8Config.pixel_maps.copy()
## Find peaks
self.PF8Config.update_pixel_maps(
initial_guess[0] - self.initial_detector_center[0],
initial_guess[1] - self.initial_detector_center[1],
)
pf8 = PF8(self.PF8Config)

# Assemble data and mask
data_visualize = geometry.DataVisualizer(pixel_maps=self.PF8Config.pixel_maps)

data_visualize = geometry.DataVisualizer(pixel_maps=non_shifted_pixel_maps_for_visualization)
with h5py.File(f"{self.PF8Config.bad_pixel_map_filename}", "r") as f:
mask = np.array(f[f"{self.PF8Config.bad_pixel_map_hdf5_path}"])

Expand Down Expand Up @@ -514,7 +536,7 @@ def _run_centering(self, **kwargs) -> tuple:
fig, ax1 = plt.subplots(1, 1, figsize=(10, 10))
ax1.imshow(
self.visual_data * self.mask_for_fwhm_min,
vmax=10,
norm=LogNorm(),
origin="lower",
cmap="YlGn",
)
Expand Down Expand Up @@ -561,7 +583,13 @@ def __init__(self, config: dict, PF8Config: PF8Info, plots_info: dict = None):
raise ValueError(
"From config you want to save plots, please indicate the information to save the plots."
)


if not config["plots_flag"] and not plots_info:
plots_info = {
"file_name": "",
"folder_name": "",
"root_path": ""
}
def _remove_repeated_pairs(self, pairs_list: list) -> list:
x_vector = []
y_vector = []
Expand Down Expand Up @@ -650,6 +678,8 @@ def _prep_for_centering(self, data: np.ndarray, initial_guess: tuple) -> None:

self.initial_guess = initial_guess
self.initial_detector_center = self.PF8Config.get_detector_center()
non_shifted_pixel_maps_for_visualization = self.PF8Config.pixel_maps.copy()

## Find peaks
self.PF8Config.update_pixel_maps(
initial_guess[0] - self.initial_detector_center[0],
Expand All @@ -659,7 +689,7 @@ def _prep_for_centering(self, data: np.ndarray, initial_guess: tuple) -> None:
pf8 = PF8(self.PF8Config)

# Assemble data and mask
data_visualize = geometry.DataVisualizer(pixel_maps=self.PF8Config.pixel_maps)
data_visualize = geometry.DataVisualizer(pixel_maps=non_shifted_pixel_maps_for_visualization)

with h5py.File(f"{self.PF8Config.bad_pixel_map_filename}", "r") as f:
mask = np.array(f[f"{self.PF8Config.bad_pixel_map_hdf5_path}"])
Expand Down Expand Up @@ -720,9 +750,11 @@ def _prep_for_centering(self, data: np.ndarray, initial_guess: tuple) -> None:
)

peak_list_in_slab = pf8.peak_list_in_slab(peak_list)
#print(peak_list_in_slab)
self.peak_list_x_in_frame, self.peak_list_y_in_frame = peak_list_in_slab

def _run_centering(self, **kwargs) -> tuple:

peak_list_x_in_frame = self.peak_list_x_in_frame.copy()
peak_list_y_in_frame = self.peak_list_y_in_frame.copy()

Expand Down Expand Up @@ -773,13 +805,14 @@ def _run_centering(self, **kwargs) -> tuple:
self.config["plots_flag"],
)


if self.config["plots_flag"] and self.centering_converged(center):
shift_x = 2 * (center[0] - self.initial_guess[0])
shift_y = 2 * (center[1] - self.initial_guess[1])

fig, ax = plt.subplots(1, 1, figsize=(8, 8))
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
pos = ax.imshow(
self.visual_data, vmin=0, vmax=100, cmap="YlGn", origin="lower"
self.visual_data, norm=LogNorm(), cmap="YlGn", origin="lower"
)
ax.scatter(
self.initial_detector_center[0],
Expand Down Expand Up @@ -807,7 +840,7 @@ def _run_centering(self, **kwargs) -> tuple:
label=f"Refined detector center:({np.round(center[0],1)}, {np.round(center[1],1)})",
)
ax.set_xlim(200, 900)
ax.set_ylim(900, 200)
ax.set_ylim(200, 900)
plt.title("Center refinement: autocorrelation of Friedel pairs")
fig.colorbar(pos, shrink=0.6)
ax.legend()
Expand All @@ -819,7 +852,7 @@ def _run_centering(self, **kwargs) -> tuple:
f'{self.plots_info["root_path"]}/center_refinement/plots/{self.plots_info["folder_name"]}/centered_friedel/{self.plots_info["file_name"]}.png'
)
plt.close("all")

original_peaks_x = [
np.round(k + self.initial_guess[0]) for k in peak_list_x_in_frame
]
Expand All @@ -841,9 +874,9 @@ def _run_centering(self, **kwargs) -> tuple:
]

## Check pairs alignement
fig, ax = plt.subplots(1, 1, figsize=(8, 8))
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
pos = ax.imshow(
self.visual_data, vmin=0, vmax=100, cmap="YlGn", origin="lower"
self.visual_data, norm=LogNorm(), cmap="YlGn", origin="lower"
)
ax.scatter(
original_peaks_x,
Expand All @@ -855,6 +888,7 @@ def _run_centering(self, **kwargs) -> tuple:
linewidth=1.5,
label="original peaks",
)

ax.scatter(
inverted_non_shifted_peaks_x,
inverted_non_shifted_peaks_y,
Expand All @@ -877,8 +911,9 @@ def _run_centering(self, **kwargs) -> tuple:
edgecolor="blue",
label="shift of inverted peaks",
)

ax.set_xlim(200, 900)
ax.set_ylim(900, 200)
ax.set_ylim(200, 900)
plt.title("Bragg peaks alignement")
fig.colorbar(pos, shrink=0.6)
ax.legend()
Expand Down
21 changes: 15 additions & 6 deletions bblib/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class PF8Info:
pixel_maps: TypePixelMaps = None
pixel_resolution: float = None
_shifted_pixel_maps: bool = False
geometry_txt: list = None

def update_pixel_maps(self, detector_shift_x: int, detector_shift_y: int):
if not self._shifted_pixel_maps:
Expand All @@ -41,24 +42,30 @@ def update_pixel_maps(self, detector_shift_x: int, detector_shift_y: int):
self.pixel_maps["radius"] = np.sqrt(
np.square(self.pixel_maps["x"]) + np.square(self.pixel_maps["y"])
).reshape(self._data_shape)
self.pixel_maps["phi"] = np.arctan2(self.pixel_maps["y"], self.pixel_maps["x"])
else:
raise ValueError(
f"Pixel maps have been moved once before, to avoid errors reset the geometry before moving it again."
)

def set_geometry_from_file(self, geometry_filename: str):
geometry_txt = open(geometry_filename, "r").readlines()
def set_geometry_from_file(self, geometry_filename: str = None):
if geometry_filename:
self.geometry_txt = open(geometry_filename, "r").readlines()
else:
if not self.geometry_txt:
raise ValueError("Please, specify the detector geometry in CrystFEL format.")

self.bad_pixel_map_filename = [
x.split(" = ")[-1][:-1]
for x in geometry_txt
for x in self.geometry_txt
if x.split(" = ")[0] == "mask_file"
][0]
self.bad_pixel_map_hdf5_path = [
x.split(" = ")[-1][:-1] for x in geometry_txt if x.split(" = ")[0] == "mask"
x.split(" = ")[-1][:-1] for x in self.geometry_txt if x.split(" = ")[0] == "mask"
][0]

geom = GeometryInformation(
geometry_description=geometry_txt, geometry_format="crystfel"
geometry_description=self.geometry_txt, geometry_format="crystfel"
)
self.pixel_resolution = 1 / geom.get_pixel_size()
self.pixel_maps = geom.get_pixel_maps()
Expand All @@ -73,7 +80,7 @@ def set_geometry_from_file(self, geometry_filename: str):
) == 1:
## Get single panel transformation matrix from the geometry file
### Warning! Check carefully if the visualized data after reorientation of the panel makes sense, e.g. if it is equal to the real experimental data geometry.
detector, _, _ = _read_crystfel_geometry_from_text(text_lines=geometry_txt)
detector, _, _ = _read_crystfel_geometry_from_text(text_lines=self.geometry_txt)
detector_panels = dict(detector["panels"])
panel_name = list(detector_panels.keys())[0]
frame_dim_structure = [
Expand Down Expand Up @@ -132,6 +139,7 @@ def get(self, parameter: str):

def get_detector_center(self) -> list:
if not self._shifted_pixel_maps:

if (
self.pf8_detector_info["nasics_x"] * self.pf8_detector_info["nasics_y"]
> 1
Expand Down Expand Up @@ -167,6 +175,7 @@ def get_detector_center(self) -> list:
_img_center_x = int(abs(np.min(self.pixel_maps["x"])))
_img_center_y = int(abs(np.min(self.pixel_maps["y"])))
else:
print("Warning! The detector center was moved by a previous operation, the detector center is not the same as in the geometry file.")
_img_center_x = self.detector_center_from_geom[0] + self._detector_shift_x
_img_center_y = self.detector_center_from_geom[1] + self._detector_shift_y
return [_img_center_x, _img_center_y]
Expand Down
8 changes: 6 additions & 2 deletions bblib/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,12 @@ def center_of_mass(data: np.ndarray, mask: np.ndarray = None) -> list[int]:
mask = np.ones_like(data)
data = data * mask
indexes = np.where(data > 0)
xc = np.sum(data[indexes] * indexes[1]) / np.sum(data[indexes])
yc = np.sum(data[indexes] * indexes[0]) / np.sum(data[indexes])
if np.sum(data[indexes])>1e-7:
xc = np.sum(data[indexes] * indexes[1]) / np.sum(data[indexes])
yc = np.sum(data[indexes] * indexes[0]) / np.sum(data[indexes])
else:
xc = -1
yc = -1

if np.isnan(xc) or np.isnan(yc):
xc = -1
Expand Down

0 comments on commit 4cc49fe

Please sign in to comment.