Skip to main content

scirs2_ndimage/documentation/
tutorials.rs

1//! Tutorial Generation System
2//!
3//! This module contains functions to build comprehensive tutorials and examples
4//! for the SciRS2 NDImage library documentation.
5
6use crate::documentation::types::{DocumentationSite, Example, Result, Tutorial};
7
8impl DocumentationSite {
9    /// Build comprehensive tutorials for the documentation
10    pub fn build_tutorials(&mut self) -> Result<()> {
11        self.tutorials = vec![
12            build_getting_started_tutorial(),
13            build_advanced_filtering_tutorial(),
14            build_morphological_operations_tutorial(),
15            build_performance_optimization_tutorial(),
16        ];
17        Ok(())
18    }
19
20    /// Build comprehensive examples for the documentation
21    pub fn build_examples(&mut self) -> Result<()> {
22        self.examples = vec![
23            build_medical_imaging_example(),
24            build_satellite_analysis_example(),
25            build_realtime_video_example(),
26            build_scientific_analysis_example(),
27        ];
28        Ok(())
29    }
30}
31
32/// Build the "Getting Started" tutorial
33pub fn build_getting_started_tutorial() -> Tutorial {
34    let content = r#"
35# Getting Started with SciRS2 NDImage
36
37## Introduction
38
39SciRS2 NDImage is a comprehensive n-dimensional image processing library for Rust that provides
40high-performance implementations of common image processing operations. This tutorial will guide
41you through the basics of using the library.
42
43## Installation
44
45Add the following to your `Cargo.toml`:
46
47```toml
48[dependencies]
49scirs2-ndimage = "0.1.0"
50ndarray = "0.16"
51```
52
53## Basic Usage
54
55### Creating Arrays
56
57```rust
58use scirs2_core::ndarray::{Array2, Array3};
59
60// Create a 2D array (image)
61let image = Array2::from_elem((100, 100), 0.5f64);
62
63// Create a 3D array (volume)
64let volume = Array3::from_elem((50, 50, 50), 1.0f64);
65```
66
67### Applying Filters
68
69```rust
70use scirs2_ndimage::filters::gaussian_filter;
71
72let filtered = gaussian_filter(&image, 2.0);
73```
74
75## Next Steps
76
77- Learn about morphological operations
78- Explore geometric transformations
79- Try advanced filtering techniques
80"#;
81
82    let mut tutorial = Tutorial::beginner(
83        "Getting Started with SciRS2 NDImage",
84        "Introduction to n-dimensional image processing in Rust",
85        content,
86    );
87
88    tutorial.add_code_example("Basic array creation and manipulation");
89    tutorial.add_code_example("Simple filtering operations");
90
91    tutorial
92}
93
94/// Build the "Advanced Filtering Techniques" tutorial
95pub fn build_advanced_filtering_tutorial() -> Tutorial {
96    let content = r#"
97# Advanced Filtering Techniques
98
99## Edge Detection
100
101Edge detection is crucial for feature extraction and object recognition.
102
103### Sobel Filter
104
105```rust
106use scirs2_ndimage::filters::sobel_filter;
107
108let edges = sobel_filter(&image);
109```
110
111### Canny Edge Detection
112
113```rust
114use scirs2_ndimage::filters::canny_edge_detector;
115
116let edges = canny_edge_detector(&image, 0.1, 0.2);
117```
118
119## Noise Reduction
120
121### Bilateral Filter
122
123Preserves edges while reducing noise:
124
125```rust
126use scirs2_ndimage::filters::bilateral_filter;
127
128let denoised = bilateral_filter(&noisyimage, 5.0, 10.0);
129```
130
131### Non-local Means
132
133Advanced denoising technique:
134
135```rust
136use scirs2_ndimage::filters::non_local_means;
137
138let denoised = non_local_means(&noisyimage, 0.1, 7, 21);
139```
140"#;
141
142    let mut tutorial = Tutorial::intermediate(
143        "Advanced Filtering Techniques",
144        "Master advanced filtering operations for noise reduction and feature enhancement",
145        content,
146    );
147
148    tutorial.add_code_example("Edge detection pipeline");
149    tutorial.add_code_example("Noise reduction comparison");
150
151    tutorial
152}
153
154/// Build the "Morphological Operations" tutorial
155pub fn build_morphological_operations_tutorial() -> Tutorial {
156    let content = r#"
157# Morphological Operations
158
159## Understanding Mathematical Morphology
160
161Mathematical morphology is a theory and technique for analyzing shapes and structures
162in images. It's particularly useful for binary images but can be extended to grayscale.
163
164## Basic Operations
165
166### Erosion and Dilation
167
168```rust
169use scirs2_ndimage::morphology::{binary_erosion, binary_dilation};
170use scirs2_core::ndarray::Array2;
171
172let structure = Array2::from_elem((3, 3), true);
173let eroded = binary_erosion(&binary_image, &structure);
174let dilated = binary_dilation(&binary_image, &structure);
175```
176
177### Opening and Closing
178
179```rust
180use scirs2_ndimage::morphology::{binary_opening, binary_closing};
181
182let opened = binary_opening(&binary_image, &structure);
183let closed = binary_closing(&binary_image, &structure);
184```
185
186## Advanced Applications
187
188### Skeletonization
189
190```rust
191use scirs2_ndimage::morphology::skeletonize;
192
193let skeleton = skeletonize(&binary_image);
194```
195
196### Distance Transform
197
198```rust
199use scirs2_ndimage::morphology::distance_transform_edt;
200
201let distances = distance_transform_edt(&binary_image);
202```
203"#;
204
205    let mut tutorial = Tutorial::intermediate(
206        "Morphological Operations",
207        "Shape analysis and morphological transformations",
208        content,
209    );
210
211    tutorial.add_code_example("Shape analysis pipeline");
212    tutorial.add_code_example("Binary image processing");
213
214    tutorial
215}
216
217/// Build the "Performance Optimization" tutorial
218pub fn build_performance_optimization_tutorial() -> Tutorial {
219    let content = r#"
220# Performance Optimization
221
222## SIMD Acceleration
223
224SciRS2 NDImage automatically uses SIMD instructions when available:
225
226```rust
227// Enable SIMD features
228use scirs2_ndimage::filters::gaussian_filter_simd;
229
230let filtered = gaussian_filter_simd(&largeimage, 2.0);
231```
232
233## Parallel Processing
234
235Large arrays are automatically processed in parallel:
236
237```rust
238use scirs2_ndimage::parallel::ParallelConfig;
239
240// Configure parallel processing
241ParallelConfig::set_num_threads(8);
242
243// Operations automatically use parallel processing for large arrays
244let result = expensive_operation(&hugeimage);
245```
246
247## GPU Acceleration
248
249For supported operations, GPU acceleration provides significant speedup:
250
251```rust
252use scirs2_ndimage::gpu::{GpuContext, gpu_gaussian_filter};
253
254let gpu_ctx = GpuContext::new()?;
255let gpu_result = gpu_gaussian_filter(&gpu_ctx, &image, 2.0)?;
256```
257
258## Memory Optimization
259
260### Streaming Processing
261
262For very large datasets that don't fit in memory:
263
264```rust
265use scirs2_ndimage::streaming::StreamProcessor;
266
267let processor = StreamProcessor::new("largeimage.tiff")?;
268let result = processor.apply_filter(gaussian_filter, 2.0)?;
269```
270
271### In-place Operations
272
273Reduce memory usage with in-place operations:
274
275```rust
276use scirs2_ndimage::filters::gaussian_filter_inplace;
277
278gaussian_filter_inplace(&mut image, 2.0);
279```
280"#;
281
282    let mut tutorial = Tutorial::advanced(
283        "Performance Optimization",
284        "Optimize performance with SIMD, parallel processing, and GPU acceleration",
285        content,
286    );
287
288    tutorial.add_code_example("Performance benchmarking");
289    tutorial.add_code_example("Memory-efficient processing");
290
291    tutorial
292}
293
294/// Build medical imaging example
295pub fn build_medical_imaging_example() -> Example {
296    let code = r#"
297use scirs2_ndimage::domain_specific::medical::*;
298use scirs2_core::ndarray::Array3;
299
300// Load medical volume (e.g., CT scan)
301let ct_volume = Array3::from_elem((256, 256, 100), 1000.0f64);
302
303// Apply Frangi vesselness filter for blood vessel detection
304let vessels = frangi_vesselness_filter(&ct_volume, &FrangiParams::default());
305
306// Segment bones using threshold and morphology
307let bones = bone_enhancement_filter(&ct_volume, 400.0);
308
309// Detect lung nodules
310let nodules = lung_nodule_detector(&ct_volume, &NoduleDetectionParams::default());
311
312println!("Detected {} potential nodules", nodules.len());
313"#;
314
315    Example::with_output(
316        "Medical Image Processing",
317        "Process medical images with specialized filters and analysis",
318        code,
319        "Medical",
320        "Medical image processing completed successfully",
321    )
322}
323
324/// Build satellite analysis example
325pub fn build_satellite_analysis_example() -> Example {
326    let code = r#"
327use scirs2_ndimage::domain_specific::satellite::*;
328use scirs2_core::ndarray::Array3;
329
330// Multi-spectral satellite image (bands: R, G, B, NIR)
331let satelliteimage = Array3::from_elem((1000, 1000, 4), 0.5f64);
332
333// Calculate vegetation indices
334let ndvi = compute_ndvi(&satelliteimage);
335let ndwi = compute_ndwi(&satelliteimage);
336
337// Water body detection
338let water_mask = detect_water_bodies(&satelliteimage, 0.3);
339
340// Cloud detection and removal
341let cloud_mask = detect_clouds(&satelliteimage, &CloudDetectionParams::default());
342let cloud_free = remove_clouds(&satelliteimage, &cloud_mask);
343
344// Pan-sharpening for higher resolution
345let panchromatic = Array3::from_elem((4000, 4000, 1), 0.7f64);
346let sharpened = pan_sharpen(&satelliteimage, &panchromatic);
347
348println!("Processed satellite image with {} water pixels", water_mask.iter().filter(|&&x| x).count());
349"#;
350
351    Example::with_output(
352        "Satellite Image Analysis",
353        "Analyze satellite imagery for environmental monitoring",
354        code,
355        "Remote Sensing",
356        "Satellite image analysis completed",
357    )
358}
359
360/// Build real-time video processing example
361pub fn build_realtime_video_example() -> Example {
362    let code = r#"
363use scirs2_ndimage::streaming::*;
364use scirs2_ndimage::features::*;
365use scirs2_core::ndarray::Array3;
366
367// Setup streaming video processor
368let mut video_processor = StreamProcessor::new_video("input.mp4")?;
369
370// Configure real-time processing pipeline
371let pipeline = ProcessingPipeline::new()
372    .add_filter(gaussian_filter, 1.0)
373    .add_detector(corner_detector, &CornerParams::default())
374    .add_tracker(object_tracker, &TrackerParams::default());
375
376// Process frames in real-time
377while let Some(frame) = video_processor.next_frame()? {
378    let processed = pipeline.process(&frame)?;
379
380    // Extract features
381    let corners = detect_corners(&processed, &CornerParams::default());
382    let edges = detect_edges(&processed, &EdgeParams::default());
383
384    // Track objects across frames
385    let tracked_objects = update_tracking(&corners, &edges);
386
387    // Output processed frame
388    video_processor.write_frame(&processed)?;
389
390    println!("Frame processed: {} corners, {} edges", corners.len(), edges.len());
391}
392"#;
393
394    Example::with_output(
395        "Real-time Video Processing",
396        "Process video frames in real-time with optimized algorithms",
397        code,
398        "Computer Vision",
399        "Real-time video processing pipeline completed",
400    )
401}
402
403/// Build scientific analysis example
404pub fn build_scientific_analysis_example() -> Example {
405    let code = r#"
406use scirs2_ndimage::measurements::*;
407use scirs2_ndimage::segmentation::*;
408use scirs2_core::ndarray::Array2;
409
410// Scientific image (e.g., microscopy, astronomy)
411let scientificimage = Array2::from_elem((2048, 2048), 0.0f64);
412
413// Advanced segmentation using watershed
414let markers = find_local_maxima(&scientificimage, 10);
415let segmented = watershed_segmentation(&scientificimage, &markers);
416
417// Measure region properties
418let regions = analyze_regions(&segmented);
419for region in &regions {
420    println!("Region {}: area={}, centroid={:?}, eccentricity={:.3}",
421             region.label, region.area, region.centroid, region.eccentricity);
422}
423
424// Statistical analysis
425let moments = compute_moments(&scientificimage);
426let hu_moments = compute_hu_moments(&moments);
427
428// Feature extraction for classification
429let texturefeatures = extracttexturefeatures(&scientificimage);
430let shapefeatures = extractshapefeatures(&segmented);
431
432println!("Analysis complete: {} regions found", regions.len());
433"#;
434
435    Example::with_output(
436        "Scientific Image Analysis",
437        "Advanced analysis techniques for scientific imaging",
438        code,
439        "Scientific",
440        "Scientific image analysis completed with region measurements",
441    )
442}
443
444/// Helper function to create a comprehensive tutorial with common sections
445pub fn create_comprehensive_tutorial(title: &str, description: &str, difficulty: &str) -> Tutorial {
446    let mut tutorial = Tutorial::new(title, description, "", difficulty);
447
448    // Add common sections that most tutorials would have
449    let common_content = format!(
450        r#"
451# {}
452
453## Overview
454
455{}
456
457## Prerequisites
458
459- Basic knowledge of Rust programming
460- Familiarity with the ndarray crate
461- Understanding of image processing concepts
462
463## Learning Objectives
464
465By the end of this tutorial, you will:
466- Understand the core concepts
467- Be able to apply the techniques in practice
468- Know how to optimize performance
469- Understand common pitfalls and how to avoid them
470
471"#,
472        title, description
473    );
474
475    tutorial.content = common_content;
476    tutorial
477}
478
479/// Helper function to add common examples to tutorials
480pub fn add_common_tutorial_examples(tutorial: &mut Tutorial) {
481    tutorial.add_code_example("Step-by-step implementation");
482    tutorial.add_code_example("Performance considerations");
483    tutorial.add_code_example("Common use cases");
484    tutorial.add_code_example("Error handling patterns");
485}
486
487#[cfg(test)]
488mod tests {
489    use super::*;
490
491    #[test]
492    fn test_getting_started_tutorial() {
493        let tutorial = build_getting_started_tutorial();
494        assert_eq!(tutorial.title, "Getting Started with SciRS2 NDImage");
495        assert_eq!(tutorial.difficulty, "Beginner");
496        assert!(!tutorial.content.is_empty());
497        assert!(!tutorial.code_examples.is_empty());
498    }
499
500    #[test]
501    fn test_advanced_filtering_tutorial() {
502        let tutorial = build_advanced_filtering_tutorial();
503        assert_eq!(tutorial.title, "Advanced Filtering Techniques");
504        assert_eq!(tutorial.difficulty, "Intermediate");
505        assert!(tutorial.content.contains("Edge Detection"));
506        assert!(tutorial.content.contains("Noise Reduction"));
507    }
508
509    #[test]
510    fn test_morphological_operations_tutorial() {
511        let tutorial = build_morphological_operations_tutorial();
512        assert_eq!(tutorial.title, "Morphological Operations");
513        assert_eq!(tutorial.difficulty, "Intermediate");
514        assert!(tutorial.content.contains("Mathematical Morphology"));
515    }
516
517    #[test]
518    fn test_performance_optimization_tutorial() {
519        let tutorial = build_performance_optimization_tutorial();
520        assert_eq!(tutorial.title, "Performance Optimization");
521        assert_eq!(tutorial.difficulty, "Advanced");
522        assert!(tutorial.content.contains("SIMD"));
523        assert!(tutorial.content.contains("GPU"));
524    }
525
526    #[test]
527    fn test_medical_imaging_example() {
528        let example = build_medical_imaging_example();
529        assert_eq!(example.title, "Medical Image Processing");
530        assert_eq!(example.category, "Medical");
531        assert!(example.expected_output.is_some());
532        assert!(example.code.contains("ct_volume"));
533    }
534
535    #[test]
536    fn test_satellite_analysis_example() {
537        let example = build_satellite_analysis_example();
538        assert_eq!(example.title, "Satellite Image Analysis");
539        assert_eq!(example.category, "Remote Sensing");
540        assert!(example.code.contains("ndvi"));
541        assert!(example.code.contains("water_mask"));
542    }
543
544    #[test]
545    fn test_tutorial_builder() {
546        let mut site = DocumentationSite::new();
547        let result = site.build_tutorials();
548
549        assert!(result.is_ok());
550        assert_eq!(site.tutorials.len(), 4);
551
552        // Check tutorial difficulties
553        let difficulties: Vec<_> = site.tutorials.iter().map(|t| &t.difficulty).collect();
554        assert!(difficulties.contains(&&"Beginner".to_string()));
555        assert!(difficulties.contains(&&"Intermediate".to_string()));
556        assert!(difficulties.contains(&&"Advanced".to_string()));
557    }
558
559    #[test]
560    fn test_examples_builder() {
561        let mut site = DocumentationSite::new();
562        let result = site.build_examples();
563
564        assert!(result.is_ok());
565        assert_eq!(site.examples.len(), 4);
566
567        // Check example categories
568        let categories: Vec<_> = site.examples.iter().map(|e| &e.category).collect();
569        assert!(categories.contains(&&"Medical".to_string()));
570        assert!(categories.contains(&&"Remote Sensing".to_string()));
571        assert!(categories.contains(&&"Computer Vision".to_string()));
572        assert!(categories.contains(&&"Scientific".to_string()));
573    }
574
575    #[test]
576    fn test_comprehensive_tutorial_creation() {
577        let tutorial = create_comprehensive_tutorial(
578            "Test Tutorial",
579            "A test tutorial for validation",
580            "Beginner",
581        );
582
583        assert_eq!(tutorial.title, "Test Tutorial");
584        assert_eq!(tutorial.difficulty, "Beginner");
585        assert!(tutorial.content.contains("Prerequisites"));
586        assert!(tutorial.content.contains("Learning Objectives"));
587    }
588}