Skip to main content

smlm_renderer/
lib.rs

1extern crate smlm_imp as imp;
2extern crate smlm_locs as locs;
3extern crate statrs;
4
5pub use self::locs::constants::{PARSE_INSTRUCTIONS};
6pub use self::locs::{AllocatedLocalisation};
7pub use self::render_result::{RenderResult};
8
9pub mod config;
10mod data_properties;
11mod gaussian;
12pub mod io;
13mod patch;
14mod render_result;
15mod render_styles;
16mod utils;
17pub mod widefield;
18
19pub use locs::io::{ParseMethod};
20
21use self::config::{Config};
22pub use self::data_properties::{DataProperties, Properties, ImageDimensions, ImageFrame, NmFrame};
23use self::patch::{SigmaFactory};
24pub use self::render_styles::{RenderPolicy, SinglePointPatchRenderer, IntegralPatchRenderer};
25
26pub use imp::{Image, ImageMut, Pad, Crop, OwnedImage, BorrowedImage};
27
28use locs::{UncertainLocalisation};
29use locs::io::{read_file, ParserFactory, Parser, ThunderStormParserFactory};
30
31use std::fs::{File};
32use std::io::{Write, Error as IoError};
33// use std::ops::AddAssign;
34use std::path::{Path};
35use std::sync::{Arc, Mutex};
36use std::thread;
37
38type DataType = f64;
39
40    
41fn calculate_data_properties<L: UncertainLocalisation>(config: &Config, localisations: &[L]) -> DataProperties
42{
43    let mut min_x = std::f64::MAX;
44    let mut max_x = 0.0;
45    let mut min_y =std::f64::MAX;
46    let mut max_y = 0.0;
47    // idea is if we use the greatest sigma at the furthest point
48    // so that all the blending can occur in the image
49    // let factory = SigmaFactory::new(config.sigma_scale());
50    // let mut max_sigma = 0.0;
51    for l in localisations
52    {
53        let patch_size = 0.0;
54        // this doesn't lock at zero
55        let adjusted_x_min = l.x() - patch_size;
56        let adjusted_x_max = l.x() + patch_size;
57        // this doesn't lock at zero
58        let adjusted_y_min = l.y() - patch_size;
59        let adjusted_y_max = l.y() + patch_size;
60        if adjusted_x_max > max_x
61        {
62            max_x = adjusted_x_max;
63            // adjust_sigma(&mut max_sigma, l.uncertainty())
64        }
65        if adjusted_x_min < min_x
66        {
67            min_x = adjusted_x_min;
68            // adjust_sigma(&mut max_sigma, l.uncertainty())
69        }
70        if adjusted_y_max > max_y
71        {
72            max_y = adjusted_y_max;
73            // adjust_sigma(&mut max_sigma, l.uncertainty())
74        }
75        if adjusted_y_min < min_y
76        {
77            min_y = adjusted_y_min;
78            // adjust_sigma(&mut max_sigma, l.uncertainty())
79        }
80    }
81
82    match config.border()
83    {
84        None => {},
85        Some(border_pixels) => 
86        {
87            let border = border_pixels as f64 * config.pixel_size_nm();
88            min_x -= border;
89            max_x += border;
90            min_y -= border;
91            max_y += border;
92        }
93    }
94    DataProperties::from(min_x, max_x, min_y, max_y)
95}
96
97
98fn sum_values<I: Image<Data=DataType>>(image: I, row: usize, col: usize, step: usize) -> DataType
99{
100    let mut total = 0.0;
101    for r in row..(row + step)
102    {
103        for c in col..(col + step)
104        {
105            total += image.get_at(r, c)
106        }
107    }
108    total
109}
110
111fn down_sample_image<I: Image<Data=DataType>>(zoom_level: usize, image: I) -> OwnedImage<DataType>
112{
113    let (rendered_rows, rendered_cols) = image.shape();
114    let rows = rendered_rows / zoom_level;
115    let cols = rendered_cols / zoom_level;
116    // println!("Image: {rows} x {cols}");
117    let mut down_sampled_image = OwnedImage::zeros((rows, cols));
118    let step_size = zoom_level;
119    for (down_row, row) in (0..rendered_rows).step_by(step_size).enumerate()
120    {
121        for (down_col, col) in (0..rendered_cols).step_by(step_size).enumerate()
122        {
123            let value = sum_values(&image, row, col, step_size);
124            *down_sampled_image.get_at_mut(down_row, down_col) = value;
125        }
126    }
127    down_sampled_image
128
129}
130
131fn get_image_size_from_data_properties(config: &Config, data_properties: &DataProperties) -> ImageDimensions
132{
133    let pixel_size = config.pixel_size_nm();
134    let image_width = data_properties.calculate_image_width(pixel_size);
135    let image_height = data_properties.calculate_image_height(pixel_size);
136    ImageDimensions::new(image_height, image_width)
137}
138
139fn get_data_properties<L: UncertainLocalisation>(config: &Config, localisations: &[L]) -> DataProperties
140{
141    match config.data_frame()
142    {
143        None => calculate_data_properties(config, localisations),
144        Some(nm_frame) => 
145        {
146            // println!("nm frame: {nm_frame} (nm)");
147            DataProperties::new(nm_frame)
148        }
149    }   
150}
151
152fn get_image_size(config: &Config, data_properties: &mut DataProperties) -> ImageDimensions
153{
154    config.final_image_size().unwrap_or_else(|| get_image_size_from_data_properties(config, data_properties))
155}
156
157fn render_with_properties<R: RenderPolicy<L>, L: UncertainLocalisation + std::fmt::Debug, I: Iterator<Item=L>>
158    (
159        renderer: R,
160        properties: &Properties, 
161        image_shape: (usize, usize), 
162        localisations: I
163    ) -> Result<OwnedImage<DataType>, <R as RenderPolicy<L>>::Error>
164{
165    let mut render_image = OwnedImage::zeros(image_shape);
166    // println!("{:?}", properties);
167    for localisation in localisations.filter(|l| properties.within_bounds(l.x(), l.y()))
168    {
169        // println!("{:?}", localisation);
170        // let _ = render_as_patch(&factory, localisation, &mut render_image, &properties)?;
171        let _ = renderer.render(localisation, &mut render_image, &properties)?;
172    }
173    // let t = std::thread::current();
174    // println!("Patch Rendered - {:?}", t.name());
175    Ok(render_image)
176}
177
178fn mt_rendering<R: for<'a> RenderPolicy<&'a L, Error=String> + Clone + std::marker::Send + 'static, L: UncertainLocalisation + Clone + std::marker::Send + 'static + std::fmt::Debug>(n_threads: usize,
179                                                                             renderer: R,
180                                                                             properties: &Properties, 
181                                                                             image_shape: (usize, usize), 
182                                                                             localisations: &[L]) -> Result<OwnedImage<DataType>, String>
183{
184    let render_image = OwnedImage::zeros(image_shape);
185    let safe_image = Arc::new(Mutex::new(render_image));
186    let batch_size = localisations.len() / n_threads;
187    let mut batches = Vec::with_capacity(n_threads);
188    let mut end = 0;
189    for idx in 0..(n_threads - 1)
190    {
191        let start = idx * batch_size;
192        end = start + batch_size;
193        batches.push((start, end));
194    }
195    batches.push((end, localisations.len() - 1));
196    // for (start, end) in &batches
197    // {
198    //     println!("{start} -> {end}");
199    // }
200    let mut threads = Vec::with_capacity(n_threads);
201
202    for idx in 0..n_threads
203    {
204        let name = format!("renderer_{}", idx);
205        let batch = batches[idx];
206        let l = localisations[batch.0..batch.1].to_vec();
207        // println!("{name} rendering: {} -> {}", batch.0, batch.1);
208        let r = renderer.clone();
209        let p = properties.clone();
210        let i = safe_image.clone();
211        let t = thread::Builder::new().name(name).spawn(move || 
212        {
213            let image = render_with_properties(r, &p, image_shape, l.iter());
214            i.lock().unwrap().add_to(image.unwrap());
215        }); 
216        threads.push(t.unwrap());
217    }
218
219    for t in threads
220    {
221        // println!("Waiting for {:?}", t.thread().name());
222        let _ = t.join();
223        // println!("Thread joined");
224    }
225    Arc::into_inner(safe_image).ok_or(format!("could not unwrap image from arc"))
226                               .and_then(|m| m.into_inner().map_err(|e| e.to_string()))
227}
228
229fn write_image_<F: FnOnce() -> Result<(), String>>(writer: F, filename: &str) -> () 
230{
231    match writer()
232    {
233        Ok(_) => {},
234        Err(e) => 
235        {
236            eprintln!("error writing image to {filename} {e}");
237        }
238    }   
239}
240
241fn write_image<I: Image<Data=DataType>>(image: I, filename: Option<&str>, write_as_f32: bool) -> ()
242{
243    match filename
244    {
245        None => {},
246        Some(f) => 
247        {
248            if write_as_f32
249            {
250                let shape = image.shape();
251                // println!("creating new image");
252                // println!("{:?}", image.data());
253                let new_image_data = image.data().iter().map(|v| *v as f32).collect::<Vec<f32>>();
254                // let new_image_data = utils::downstep(image.data_mut());
255                let new_image = BorrowedImage::new(shape, &new_image_data);
256                // println!("{:?}", new_image.data());
257                // println!("sending to writer");
258                // let writer = || new_image.write_big_tiff(f);
259                let writer = || new_image.write_tiff(f);
260                write_image_(writer, f)
261            }
262            else 
263            {
264                // let writer = || image.write_big_tiff(f);
265                let writer = || image.write_tiff(f);
266                write_image_(writer, f)
267            }
268        }
269    };    
270    
271}
272
273fn write_data_file<W: Write>(mut writer: W, config: &Config, n_rows: usize, n_cols: usize, pixel_size_nm: f64) -> Result<(), IoError>
274{
275    let _ = writeln!(writer, "configured with:")?;
276    let _ = config.write_to(&mut writer)?;
277    writeln!(writer, "\n\ncreated:\nrowsxcols={n_rows}x{n_cols}\npixel size (nm)={pixel_size_nm}")
278}
279
280pub fn render_localisations_with<R: for<'a> RenderPolicy<&'a L, Error=String> + std::fmt::Debug + Clone + Send + 'static, L: UncertainLocalisation + std::fmt::Debug + Clone + Send + 'static>(config: &Config, localisations: &[L], renderer: R) -> Result<RenderResult, String>
281{
282    if localisations.is_empty()
283    {
284        return Err("No localisations given".to_string())
285    }
286    println!("{:?}", config);
287    let mut data_properties = get_data_properties(config, localisations);
288    let image_dimensions = get_image_size(config, &mut data_properties);
289    let image_height = image_dimensions.height();
290    let image_width = image_dimensions.width();
291    let pixel_size = config.pixel_size_nm();
292    println!("height x width: {image_height} x {image_width}");
293
294    let zoom_level = config.zoom_level();
295    let render_width = image_width * zoom_level;
296    let render_height = image_height * zoom_level;
297    let rendering_pixel_size = utils::rendering_pixel_size(pixel_size, config.zoom_level());
298    println!("pixel_size: {rendering_pixel_size}");
299    
300    let properties = Properties::new(data_properties, rendering_pixel_size);
301    let n_threads = config.n_threads();
302    
303    let image_shape = (render_height, render_width);
304    let zoom_image = if n_threads > 1
305    {
306        mt_rendering(n_threads, renderer, &properties, image_shape, localisations)?
307    }
308    else 
309    {
310        render_with_properties(renderer, &properties, image_shape, localisations.iter())?
311    };    
312    println!("writing zoom image");
313    write_image(&zoom_image, config.zoom_filename(), config.write_as_f32());
314    println!("writing finished");
315
316    println!("downsampling image");
317    let image = down_sample_image(config.zoom_level(), zoom_image);
318    println!("downsampling complete");
319    if config.write_image()
320    {
321        println!("writing real image");
322        write_image(&image, config.image_filename(), config.write_as_f32());
323    }
324    if config.write_data_file()
325    {
326        // recalculate as we could have just padded / cropped
327        let n_rows = image.n_rows();
328        let n_cols = image.n_cols();
329        let _ = config.data_filename()
330                      .ok_or(format!("data filename not set"))
331                      .and_then(|filename| File::create(filename).and_then(|f| write_data_file(f, config, n_rows, n_cols, pixel_size))
332                                                                 .map_err(|e| e.to_string()))?;
333    }
334
335    Ok(RenderResult::new(image, properties))
336}
337
338pub fn render_localisations<L: UncertainLocalisation + std::fmt::Debug + Clone + Send + 'static>(config: &Config, localisations: &[L]) -> Result<RenderResult, String>
339{    
340    let renderer = SinglePointPatchRenderer::with_sigma(config.sigma_scale());
341    render_localisations_with(config, localisations, renderer)
342}
343
344fn render_and_write_with<R: for<'a> RenderPolicy<&'a <<PA as ParserFactory>::Parser as Parser>::Localisation, Error=String> + std::fmt::Debug + Clone + Send + 'static, P: AsRef<Path>, PA: ParserFactory + 'static>(path: P, config: &Config, parser: PA, renderer: R) -> Result<RenderResult, String> 
345where String: From<<PA as ParserFactory>::Error>, 
346     <<PA as ParserFactory>::Parser as Parser>::Error: std::fmt::Display, 
347     <<PA as ParserFactory>::Parser as Parser>::Localisation: Send + Clone + std::fmt::Debug + UncertainLocalisation 
348{
349    type L<T>= <<T as ParserFactory>::Parser as Parser>::Localisation;
350    let localisations = read_file(path, parser).map_err(|e| e.to_string())?.collect::<Result<Vec<L<PA>>, String>>()?;
351    render_localisations_with(&config, &localisations, renderer)
352}
353
354pub fn render_localisation_file_with<R: for<'a> RenderPolicy<&'a AllocatedLocalisation, Error=String> + std::fmt::Debug + Clone + Send + 'static,  P: AsRef<Path>>(path: P, config: &Config, parse_method: ParseMethod, renderer: R) -> Result<RenderResult, String>
355{    
356    match parse_method
357    {
358        ParseMethod::ThunderStorm => 
359        {
360            render_and_write_with(path, config, ThunderStormParserFactory, renderer)
361        },
362        ParseMethod::Csv(settings) => 
363        {
364            render_and_write_with(path, config, settings, renderer)
365        }
366    }
367}
368
369pub fn render_localisation_file<P: AsRef<Path>>(path: P, config: &Config, parse_method: ParseMethod) -> Result<RenderResult, String>
370{
371    let factory = SigmaFactory::new(config.sigma_scale());
372    let renderer = IntegralPatchRenderer::new(factory);
373    render_localisation_file_with(path, config, parse_method, renderer)
374}
375
376#[cfg(test)]
377mod tests 
378{
379    use super::*;
380    
381    use imp::{OwnedImage};
382
383    use locs::{AllocatedLocalisation};
384
385    #[test]
386    fn can_handle_empty_localisations() 
387    {
388        let localisations : [AllocatedLocalisation; 0] = [];
389        let config = Config::default();
390        let result = render_localisations(&config, &localisations);
391        assert_eq!(result.is_err(), true);
392        assert_eq!(result.unwrap_err(), "No localisations given");
393    }
394
395    #[test]
396    fn down_sample_test() 
397    {
398        let mut image = OwnedImage::<DataType>::zeros((4, 4));
399        for idx in 0..16
400        {
401            image.data_mut()[idx] = idx as DataType;
402        }
403        let new_image = down_sample_image(2, image);
404        let expected = [10.0, 18.0, 42.0, 50.0];
405        assert_eq!(new_image.data(), expected);
406
407    }
408
409    #[test]
410    fn do_not_render_localisation_beyond_image_bounds() 
411    {
412        let factory = SigmaFactory::new(1.0);
413        let renderer = SinglePointPatchRenderer::new(factory);
414        let pixel_size_nm = 1.0;
415        let data_properties = DataProperties::from(10.0, 20.0, 10.0, 20.0);
416        let localisations = [AllocatedLocalisation::new(0, 5.0, 15.0, 1.0, 0.0, 0.0), // past min x
417                             AllocatedLocalisation::new(0, 25.0, 15.0, 1.0, 0.0, 0.0), // past max x
418                             AllocatedLocalisation::new(0, 15.0, 5.0, 1.0, 0.0, 0.0), // past min y
419                             AllocatedLocalisation::new(0, 15.0, 25.0, 1.0, 0.0, 0.0), // past min y
420                             ];
421        for l in &localisations
422        {
423            assert_eq!(data_properties.within_bounds(l.x(), l.y()), false);
424        }
425        let properties = Properties::new(data_properties, pixel_size_nm);
426        let image = render_with_properties(renderer, &properties, (10, 10), localisations.iter()).unwrap();
427        assert_eq!(image.data().iter().all(|x| *x == 0.0), true);
428    }
429
430    #[test]
431    fn render_with_global_reference_frame() 
432    {
433        let pixel_size_nm = 1.0;
434        let global_reference_frame = DataProperties::from(10.0, 20.0, 10.0, 20.0);
435        let factory = SigmaFactory::new(1.0);
436        let renderer = SinglePointPatchRenderer::new(factory);
437        let localisations = [AllocatedLocalisation::new(0, 10.1, 10.1, 0.0, 0.0, 1.0)]; 
438        for l in &localisations
439        {
440            assert_eq!(global_reference_frame.within_bounds(l.x(), l.y()), true);
441        }
442        let properties = Properties::new(global_reference_frame, pixel_size_nm);
443        let image = render_with_properties(renderer, &properties, (10, 10), localisations.iter()).unwrap();
444        assert_eq!(*image.get_at(0, 0), 0.1356228962390294);
445        assert_eq!(*image.get_at(0, 1), 0.055140154776936734);
446        assert_eq!(*image.get_at(1, 0), 0.055140154776936734);
447        assert_eq!(*image.get_at(1, 1), 0.02241831396570313);
448    }
449}