Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/vlab4mic/analysis/_plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def sns_heatmap_pivots(
return_figure=False,
metric_name=None,
decimals="%.4f",
fillna = True,
na_as_zero = True,
**kwargs,
):
conditions = list(df_pivots.keys())
Expand All @@ -23,7 +23,7 @@ def sns_heatmap_pivots(
annot_kws = {"size": 10, "rotation": 45}
else:
annot_kws = kwargs["annot_kws"]
f, axes = plt.subplots(nconditions, 2, figsize=figsize)
f, axes = plt.subplots(nconditions, 2, figsize=figsize, squeeze = False)
plot_num = 0
if cmaps_range == "same":
# min and max here correspond to SSIM
Expand All @@ -37,7 +37,7 @@ def sns_heatmap_pivots(
else:
metric_n = "Metric"
for n, cond in enumerate(conditions):
if fillna:
if na_as_zero:
mask = df_pivots[cond][0].isna()
df_pivots[cond][0][mask] = 0.0
mask2 = df_pivots[cond][1].isna()
Expand Down
2 changes: 1 addition & 1 deletion src/vlab4mic/analysis/sweep.py
Original file line number Diff line number Diff line change
Expand Up @@ -840,7 +840,7 @@ def pivot_dataframes_byCategory(
)
.reset_index()
)
# get mean and std accross parameter combinations of axes_param_names
# get mean and std across parameter combinations of axes_param_names
condition_mean_pivot = summarised_group.pivot(
index=param1, columns=param2, values="Mean_Value"
).round(4)
Expand Down
26 changes: 13 additions & 13 deletions src/vlab4mic/generate/imaging.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def __init__(self):
self.field["reference_point"] = None
self.fluorophore_params = (
dict()
) # contiain its photophysical parameters such as excitation and emission
) # contain its photophysical parameters such as excitation and emission
self.emitters_by_fluorophore = dict()
self.emitters_by_channel = dict()
self.writing_dir = ""
Expand Down Expand Up @@ -101,7 +101,7 @@ def _calculate_roi_ranges(self):
]
self.roi_params["ranges"] = [xrange, yrange, zrange]

def get_absoulte_reference_point(self):
def get_absolute_reference_point(self):
"""
Get the absolute reference point in 3D (including focus plane).

Expand Down Expand Up @@ -403,11 +403,11 @@ def _set_modality_channels(self, modality, fluorophores_in_channel, prints=False
if prints:
print(fluoname)
channel_name = "ch" + str(ch)
fluorophores_in_chanel = []
fluorophores_in_chanel.append(
fluorophores_in_channel = []
fluorophores_in_channel.append(
fluoname
) # this is because a channel can have several fluorophores
filter_dictionary[channel_name] = fluorophores_in_chanel
filter_dictionary[channel_name] = fluorophores_in_channel
ch += 1
self.modalities[modality]["filters"] = filter_dictionary
else:
Expand Down Expand Up @@ -441,7 +441,7 @@ def _set_modality_psf(
if "depth" not in self.modalities[modality]["psf"]:
depth_default = int((psf_stack.shape)[2] / 2)
if prints:
print("No depth parameter found for psf, asigning default")
print("No depth parameter found for psf, assigning default")
self.modalities[modality]["psf"]["depth"] = depth_default

def _set_modality_emission(self, modality, emission):
Expand All @@ -450,7 +450,7 @@ def _set_modality_emission(self, modality, emission):
def _set_modality_detector(
self,
modality,
image_size=[], # decpreciated, image size will only be taken from ROI
image_size=[], # deprecated, image size will only be taken from ROI
pixelsize=None,
bits_pixel=None,
noise_model=None,
Expand Down Expand Up @@ -480,7 +480,7 @@ def _set_modality_detector(

def _calculate_imsize_from_ROIranges(
self, mod_pixelsize
): # THere should be specified the scale of the pixelsize of modality
): # There should be specified the scale of the pixelsize of modality
roi_scale = self.get_roi_params("scale")
xrange = self.get_roi_params("ranges")[0]
yrange = self.get_roi_params("ranges")[1]
Expand Down Expand Up @@ -585,7 +585,7 @@ def generate_imaging(
**kwargs,
):
"""
Master funciton that generates image sequences depending on the modality
Master function that generates image sequences depending on the modality
This function is responsible for
Preparing the coordinates according to ROI (DONE!)
Creating the Photons per frame matrix
Expand All @@ -609,7 +609,7 @@ def generate_imaging(
)
else:
fluonames = list(self.modalities[modality]["filters"][ch])
# prepare a dictionary that conaints the emitters per channel defined
# prepare a dictionary that contains the emitters per channel defined
output_per_fluoname = dict()
writing_notes = self.identifier + "_" + str(modality) + "_" + str(ch) + "_"
for fluo in fluonames: # a channel could capture multiple fluorophores
Expand Down Expand Up @@ -869,8 +869,8 @@ def add_detector_noise(self, modality, stack):

def _adjust_to_pixel_depth(self, modality, stack):
bits = self.modalities[modality]["detector"]["bits_pixel"]
saturaton = (2**bits) - 1
stack[stack > saturaton] == saturaton
saturation = (2**bits) - 1
stack[stack > saturation] == saturation
return stack

def _save_timeseries_with_beads(self, timeseries_stack, beads_stack, notes):
Expand Down Expand Up @@ -1212,7 +1212,7 @@ def show_field(
ax.plot_surface(xx, yy, zz, alpha=0.2)
# show ROI reference point
if reference_pt:
ref_pt = self.get_absoulte_reference_point() * factor
ref_pt = self.get_absolute_reference_point() * factor
add_ax_scatter(ax, format_coordinates(ref_pt))
# EMITTERS PER FLUOROPHORE SPECIES
if self.emitters_by_fluorophore is not None:
Expand Down
2 changes: 1 addition & 1 deletion src/vlab4mic/generate/molecular_structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -597,7 +597,7 @@ def gen_targets_by_sequence(self, target_name, sequence, **kwargs):
**kwargs
Additional keyword arguments (e.g., fluorophore, labeling_efficiency, method).
"""
# only the first appearance of the epitope in every chain is retreived
# only the first appearance of the epitope in every chain is retrieved
# if a chain has more than one epitope, only the first one is returned
target_seq = sequence
method = "average"
Expand Down
98 changes: 90 additions & 8 deletions src/vlab4mic/sweep_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ def __init__(self):
self.plot_parameters["lineplots"]["style"] = None
self.plot_parameters["lineplots"]["estimator"] = "mean"
self.plot_parameters["lineplots"]["errorbar"] = "ci"
self.plot_parameters["general"] = {}
self.plot_parameters["general"]["na_as_zero"] = True
self.structures_info_list = self.experiment.structures_info_list
# Use the directly loaded parameter_settings instead of experiment.param_settings
# to ensure all parameter groups (including particle_defect) are available
Expand Down Expand Up @@ -753,6 +755,22 @@ def set_plot_parameters(self, plot_type, **kwargs):
for key, val in kwargs.items():
self.plot_parameters[plot_type][key] = val

def set_na_as_zero_in_plots(self, na_as_zero: bool = True):
"""
Set whether to treat NaN values as zero in plots.

Parameters
----------
:param na_as_zero: bool, optional
If True, NaN values will be treated as zero in plots. Defaults to True.
This does not affect the underlying data, only the visualization.

Returns
-------
None
"""
self.plot_parameters["general"]["na_as_zero"] = na_as_zero

def run_analysis(
self,
save=True,
Expand Down Expand Up @@ -818,6 +836,7 @@ def run_analysis(
return_figure=True,
metric_name=metric_name,
filter_dictionary=None,
na_as_zero=self.plot_parameters["general"]["na_as_zero"],
)
if save:
self.save_analysis(
Expand Down Expand Up @@ -876,6 +895,7 @@ def generate_analysis_plots(
decimals: int = None,
return_figure=True,
filter_dictionary=None,
na_as_zero = True,
**kwargs,
):
"""
Expand Down Expand Up @@ -918,6 +938,7 @@ def generate_analysis_plots(
return_figure=return_figure,
decimals=decimals,
filter_dictionary=filter_dictionary,
na_as_zero = na_as_zero,
**plot_params,
**kwargs
)
Expand All @@ -929,6 +950,7 @@ def generate_analysis_plots(
decimals=decimals,
return_figure=return_figure,
filter_dictionary=filter_dictionary,
na_as_zero = na_as_zero,
**plot_params,
**kwargs
)
Expand All @@ -945,6 +967,7 @@ def _gen_heatmaps(
filter_dictionary=None,
annotations=False,
palette=None,
na_as_zero = False,
**kwargs,
):
"""
Expand Down Expand Up @@ -1016,6 +1039,7 @@ def _gen_heatmaps(
metric_name=metric_name,
conditions_cmaps=[cmap_palette]*nconditions,
decimals=decimals,
na_as_zero = na_as_zero,
**kwargs
)
return plot
Expand All @@ -1034,6 +1058,7 @@ def _gen_lineplots(
decimals="%.4f",
return_figure=True,
filter_dictionary=None,
na_as_zero = False,
**kwargs,
):
"""
Expand Down Expand Up @@ -1079,8 +1104,13 @@ def _gen_lineplots(
if style is None and len(self.parameters_with_set_values) > 1:
style = self.parameters_with_set_values[1]
fig, axes = plt.subplots(figsize=figsize)
if na_as_zero:
data_to_plot = data.copy(deep=True)
data_to_plot.fillna(0, inplace=True)
else:
data_to_plot = data
sns.lineplot(
data=data,
data=data_to_plot,
x=x_param,
y=metric_name,
hue=hue,
Expand All @@ -1095,7 +1125,7 @@ def _gen_lineplots(
axes.xaxis.set_major_formatter(FormatStrFormatter(decimals))
title = estimator + " " + metric_name + " for " + x_param
if style is not None:
title = title + "per " + style
title = title + " per " + style
plt.title(title)
plt.close()
return fig
Expand Down Expand Up @@ -1140,6 +1170,17 @@ def save_analysis(
if keyname == "dataframes":
df = self.get_analysis_output(keyname)
df_name = output_name + "_dataframe.csv"
files_indir = os.listdir(output_directory)
if df_name in files_indir:
count = 1
df_name = (
output_name + "_dataframe_" + str(count) + ".csv"
)
while df_name in files_indir:
count += 1
df_name = (
output_name + "_dataframe_" + str(count) + ".csv"
)
df.to_csv(os.path.join(output_directory, df_name), index=False)
elif keyname == "plots":
plots_dictionary = self.get_analysis_output(keyname)
Expand All @@ -1153,6 +1194,31 @@ def save_analysis(
+ plot_type
+ ".png"
)
current_files = os.listdir(output_directory)
if figure_name in current_files:
count = 1
figure_name = (
output_name
+ "_"
+ metric
+ "_"
+ plot_type
+ "_"
+ str(count)
+ ".png"
)
while figure_name in current_files:
dt_string = dt_string + "_1"
figure_name = (
output_name
+ "_"
+ metric
+ "_"
+ plot_type
+ "_"
+ str(count)
+ ".png"
)
plot.savefig(
os.path.join(output_directory, figure_name)
)
Expand Down Expand Up @@ -1182,11 +1248,21 @@ def save_images(self, output_name=None, output_directory=None, floats_as=float):
- If `self.reference_image` is present, saves it as "reference.tiff" in the output directory.
- Saves acquisition parameters as a YAML file in the output directory.
"""
now = datetime.now() # dd/mm/YY H:M:S
dt_string = now.strftime("%Y%m%d")
if output_name is None:
output_name = "vLab4mic_images_"
if output_directory is None:
foldername = "simulated_images_" + dt_string
filesindir = os.listdir(self.output_directory)
if foldername in filesindir:
count = 1
foldername = "simulated_images_" + dt_string + "_" + str(count)
while foldername in filesindir:
count+=1
foldername = "simulated_images_" + dt_string + "_" + str(count)
output_directory = os.path.join(
self.output_directory, "simulated_images", ""
self.output_directory, foldername
)
if not os.path.exists(output_directory):
os.makedirs(output_directory)
Expand All @@ -1198,8 +1274,9 @@ def save_images(self, output_name=None, output_directory=None, floats_as=float):
image = replicates[0]
for i in range(1, nreps):
image = np.concatenate((image, replicates[i]))
name = output_directory + param_combination_id + ".tiff"
tiff.imwrite(name, image)
name = param_combination_id + ".tiff"
dir_name = os.path.join(output_directory, name)
tiff.imwrite(dir_name, image)
if floats_as is not None and callable(floats_as):
copy_of_params = copy.deepcopy(self.acquisition_outputs_parameters)
for combination_id, list_of_parameters in copy_of_params.items():
Expand All @@ -1221,8 +1298,10 @@ def save_images(self, output_name=None, output_directory=None, floats_as=float):
)
if self.reference_image is not None:
# save reference image
name_ref = output_directory + "reference.tiff"
tiff.imwrite(name_ref, self.reference_image)
name_ref = param_combination_id + ".tiff"
dir_name_ref = os.path.join(output_directory, name_ref)
#name_ref = output_directory + "reference.tiff"
tiff.imwrite(dir_name_ref, self.reference_image)


def run_parameter_sweep(
Expand Down Expand Up @@ -1271,6 +1350,8 @@ def run_parameter_sweep(
psf_voxel_nm = None,
depth_of_field_nm = None,
exp_time = None,
# for plot generation
na_as_zero = True,
# Add more as needed for your sweep
):
"""
Expand Down Expand Up @@ -1369,7 +1450,7 @@ def run_parameter_sweep(
sweep_gen.select_modalities(modalities=modalities)
sweep_gen.set_output_directory(output_directory=output_directory)
sweep_gen.set_number_of_repetitions(sweep_repetitions)
# number of particles accross sweep
# number of particles across sweep
if particle_positions is not None:
# set those positions
sweep_gen.experiment.set_virtualsample_params(
Expand Down Expand Up @@ -1416,6 +1497,7 @@ def run_parameter_sweep(
reference_structure=reference_structure,
reference_probe=reference_probe,
**reference_parameters)
sweep_gen.set_na_as_zero_in_plots(na_as_zero=na_as_zero)
if run_analysis:
sweep_gen.run_analysis(
save=save_analysis_results,
Expand Down
6 changes: 3 additions & 3 deletions src/vlab4mic/utils/data_format/configuration_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,11 @@ def compile_modality_parameters(
if prints:
print(fluoname)
channel_name = "ch" + str(ch)
fluorophores_in_chanel = []
fluorophores_in_chanel.append(
fluorophores_in_channel = []
fluorophores_in_channel.append(
fluoname
) # this is because a channel can have several fluorophores
filter_dictionary[channel_name] = fluorophores_in_chanel
filter_dictionary[channel_name] = fluorophores_in_channel
ch += 1
else:
filter_dictionary = mod_pars["filters"]
Expand Down
Loading