Repository navigation
Expand file tree
/
Copy pathsimulator.py
More file actions
219 lines (183 loc) · 9.38 KB
/
Copy pathsimulator.py
File metadata and controls
219 lines (183 loc) · 9.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import argparse
import numpy as np
import os
import glob
from scipy.signal import fftconvolve
import matplotlib.pyplot as plt
from utils import *
from psf_generator import ScalarSphericalPropagator
# ──────────────── Utility Functions ────────────────
def normalize_psf(psf):
"""Normalize the psf so that the sum of all coefficients equals one."""
psf_sum = np.sum(psf)
if psf_sum != 0:
return psf / psf_sum
return psf
def add_gaussian_noise(data, sigma_g):
"""Adding Gaussian noise to the data."""
noise = np.random.normal(loc=0.0, scale=sigma_g, size=data.shape)
return data + noise
def add_poisson_noise(data, alpha_p):
"""Adding Poisson noise to the data."""
scaled = data * alpha_p
scaled[scaled < 0] = 0 # Clip negative values before Poisson sampling
return np.random.poisson(scaled) / alpha_p
def convolution_sample_psf(data, psf):
"""FFT-based convolution of sample data with PSF."""
return fftconvolve(data, psf, mode='same')
def rescale_intensity(data):
"""Clip negative values and rescale the data to the [0,1] intensity range."""
data = np.clip(data, 0, None)
data = data/ np.max(data) #rescale to [0,1] #we would not need to divide
return data
# ──────────────── Simulation Core ────────────────
def simulate_microscopy_image(data, psf, sigma_g, alpha_p, background):
"""Simulate a microscopy image by convolving 3D data with a PSF and adding noise."""
psf = normalize_psf(psf)
# Print intensity diagnostics
print("Data intensity range: min = {:.4f}, max = {:.4f}".format(data.min(), data.max()))
print("PSF intensity range: min = {:.4f}, max = {:.4f}".format(psf.min(), psf.max()))
print('psf sum', np.sum(psf))
print(data.mean())
# Convolve the data with the PSF
result = convolution_sample_psf(data, psf)
print(result.mean())
print("After convolution: min = {:.4f}, max = {:.4f}".format(result.min(), result.max()))
# Add background as percentage of max intensity
background_value = np.max(result) * (background / 100.0)
print("Background value ({}% of max): {:.4f}".format(background, background_value))
result += background_value
print("After adding background: min = {:.4f}, max = {:.4f}".format(result.min(), result.max()))
# Add Poisson noise if specified
if not alpha_p:
print("No Poisson noise will be added.")
else:
result = add_poisson_noise(result, alpha_p)
print("After Poisson noise: min = {:.4f}, max = {:.4f}".format(result.min(), result.max()))
# Add Gaussian noise if specified
if not sigma_g:
print("No Gaussian noise will be added.")
else:
result = add_gaussian_noise(result, sigma_g)
print("After Gaussian noise: min = {:.4f}, max = {:.4f}".format(result.min(), result.max()))
print("Final intensity range of simulated!!!!!: min = {:.4f}, max = {:.4f}".format(result.min(), result.max()))
return result
def generate_default_psf():
"""Generate a default PSF using the PSF generator using Vasilikis example"""
kwargs = {
'n_pix_pupil': 127, # Number of pixels for the pupil function
'n_pix_psf': 256, # Number of pixels for the PSF
'na': 1.3, # Higher numerical aperture (NA)
'wavelength': 480, # Shorter wavelength (in nm)
'fov': 19712, # Field of view (in nm) (77*256)
'defocus_min': -3759, # Minimum defocus (nm) (269 nm x 14 )
'defocus_max': 3759, # Maximum defocus (nm)
'n_defocus': 29, # Number of defocus slices (29 after removing 1)
}
propagator = ScalarSphericalPropagator(**kwargs)
focus_field = propagator.compute_focus_field()
psf = np.abs(focus_field).squeeze()**2
return psf
# ──────────────── File Handling ────────────────
def process_file(input_file, output_dir, psf, sigma_g, alpha_p, visualize, background, label="degraded"):
"""Process a single OME-TIFF file."""
# Load and prepare data
data = load_ome_tif(input_file)
data = fix_slice_count(data) # Ensure odd number of slices
# Clean up filename
basename = os.path.splitext(os.path.basename(input_file))[0]
basename = basename.replace('.ome', '') # Remove '.ome' part of the name
basename = basename.replace('_measured', '') # Remove '_measured' part
# Define output path
tiff_output_file = os.path.join(output_dir, f"{basename}_{label}.ome.tif")
# Simulate and save
simulated = simulate_microscopy_image(data, psf, sigma_g, alpha_p, background)
save_ome_tiff(tiff_output_file, simulated)
print(f"Simulated OME-TIFF saved to {tiff_output_file}")
# Visualize if requested
if visualize:
visualize_simulation(simulated, basename)
def visualize_simulation(simulated, basename):
"""Visualize the middle slice of the simulated image if requested."""
slice_index = simulated.shape[0] // 2
plt.imshow(simulated[slice_index, :, :], cmap='gray')
plt.title(f"Simulated Image (Slice at index {slice_index}) for {basename}")
plt.colorbar()
plt.show()
def visualize_ome_tiff(filename):
"""Visualize the middle slice of an OME-TIFF"""
data = load_ome_tif(filename)
slice_index = data.shape[0] // 2
plt.imshow(data[slice_index, :, :], cmap='gray')
plt.title(f"OME-TIFF Image (Slice at index {slice_index}) for {filename}")
plt.colorbar()
plt.show()
# ──────────────── CLI Interface ────────────────
def parse_arguments():
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(
description="Simulator to model microscopy images using 3D data. The simulator takes in 3D data (the sample), convolves it with a PSF generated by the PSF generator, and adds Gaussian and Poisson noise using parameters alpha_g and alpha_p."
)
parser.add_argument('--input', type=str,
help='Input one 3D data file (.ome.tif) format).')
parser.add_argument('--input_dir', type=str,
help='Input directory containing OME-TIFF files (.ome.tif). All such files will be processed.')
parser.add_argument('--psf', type=str,
help='PSF file (.npy format). If not provided, a default PSF will be generated using the PSF generator.')
parser.add_argument('--output_dir', type=str, default='simulated_images',
help='Output directory where the simulated images will be saved (used when processing multiple files).')
parser.add_argument('--sigma_g', type=float,
help='Gaussian noise standard deviation (read noise). If not provided, no Gaussian noise will be added.')
parser.add_argument('--alpha_p', type=float,
help='Scaling factor for converting intensities. If not provided, no Poisson noise will be added.')
parser.add_argument('--visualize', action='store_true',
help='Display a middle slice of the simulated image.')
parser.add_argument('--background', type=float, default=10.0,
help='Percent of max intensity value to add to background of the convolved image (simulates baseline detector signal). Default is 10%% of max intensity.')
parser.add_argument('--label', type=str, default='degraded',
help='Label for the output files. Default is "degraded".')
return parser, parser.parse_args()
def main():
parser, args = parse_arguments()
# Show help if no arguments provided
if len(os.sys.argv) == 1:
parser.print_help()
return
# Validate input arguments
if not args.input and not args.input_dir:
print("Error: You must provide either --input or --input_dir.")
parser.print_help()
return
# Create output directory if needed
if args.input_dir or args.input:
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
# Load or generate PSF
if args.psf:
print(f"Loading PSF from {args.psf}")
psf = load_data(args.psf) #expecting .npy file
else:
psf = generate_default_psf()
# Process single file
if args.input:
print("Processing single file as --input argument was provided. Pricessing only one input file")
ext = os.path.splitext(args.input)[1].lower()
if ext not in ['.ome.tif', '.ome.tiff']: #rn only supporting .ome.tif files
print(f"Error: --input file must be an OME-TIFF file (.ome.tif or .ome.tiff). Provided: {ext}")
return
process_file(args.input, args.output_dir, psf, args.sigma_g, args.alpha_p, args.visualize, args.background, args.label)
# Process directory of files
elif args.input_dir:
ome_files = glob.glob(os.path.join(args.input_dir, '*.ome.tif')) #find all files to process
if not ome_files:
print("No .ome.tif files found in the provided directory.")
return
for file in ome_files:
print(f"Processing {file}...")
process_file(file, args.output_dir, psf, args.sigma_g, args.alpha_p, False, args.background, args.label)
return
else:
print("No input file or directory provided!")
return
if __name__ == '__main__':
main()