scirs2-ndimage 0.4.2

N-dimensional image processing module for SciRS2 (scirs2-ndimage)
Documentation
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! # Temporal Causality Analysis Module
//!
//! This module provides advanced temporal causality analysis capabilities for image sequences,
//! enabling the detection and analysis of causal relationships over time. It implements:
//!
//! ## Key Features
//! - **Temporal Pattern Analysis**: Detection of temporal patterns in image sequences
//! - **Granger Causality**: Classical statistical causality detection between temporal signals
//! - **Transfer Entropy**: Information-theoretic causality measurement
//! - **Causal Graph Construction**: Building and maintaining causal relationship graphs
//! - **Multi-scale Temporal Analysis**: Analysis across different temporal windows
//!
//! ## Core Algorithms
//! - Cross-correlation based causal strength measurement
//! - Variance-based entropy approximation
//! - Confidence scoring for causal relationships
//! - Dynamic temporal memory management
//!
//! ## Applications
//! - Video sequence analysis for motion causality
//! - Time-series medical imaging analysis
//! - Dynamic system monitoring in scientific imaging
//! - Predictive analysis in image-based monitoring systems

use scirs2_core::ndarray::{Array2, Array3, ArrayView2};
use scirs2_core::numeric::{Float, FromPrimitive};
use std::cmp::Ordering;
use std::collections::{BTreeMap, VecDeque};

use super::config::*;
use crate::error::NdimageResult;

/// Temporal-Causal Analysis
///
/// Analyzes temporal patterns and causal relationships in image sequences
/// to understand the flow of information and causality over time.
///
/// This function implements a comprehensive temporal causality analysis system that:
/// 1. Converts current image to temporal representation
/// 2. Maintains a sliding window of temporal memory
/// 3. Detects causal relationships using multiple algorithms
/// 4. Builds and updates a causal graph
/// 5. Calculates causal influence for each pixel
///
/// # Arguments
/// * `image` - Current image frame to analyze
/// * `advancedstate` - Mutable state containing temporal memory and causal graph
/// * `config` - Configuration parameters for causality analysis
///
/// # Returns
/// A 2D array representing the causal influence strength for each pixel
#[allow(dead_code)]
pub fn analyze_temporal_causality<T>(
    image: &ArrayView2<T>,
    advancedstate: &mut AdvancedState,
    config: &AdvancedConfig,
) -> NdimageResult<Array2<f64>>
where
    T: Float + FromPrimitive + Copy,
{
    let (height, width) = image.dim();
    let mut causal_output = Array2::zeros((height, width));

    // Convert current image to temporal representation
    let current_temporal = image_to_temporal_representation(image)?;

    // Add to temporal memory
    advancedstate
        .temporal_memory
        .push_back(current_temporal.clone());

    // Maintain temporal window size
    while advancedstate.temporal_memory.len() > config.temporal_window {
        advancedstate.temporal_memory.pop_front();
    }

    // Analyze causal relationships if we have sufficient temporal data
    if advancedstate.temporal_memory.len() >= config.causal_depth {
        for y in 0..height {
            for x in 0..width {
                let pixel_id = y * width + x;

                // Extract temporal sequence for this pixel
                let temporal_sequence =
                    extract_pixel_temporal_sequence(&advancedstate.temporal_memory, (y, x))?;

                // Detect causal relationships
                let causal_relationships =
                    detect_causal_relationships(&temporal_sequence, pixel_id, config)?;

                // Update causal graph
                advancedstate
                    .causal_graph
                    .insert(pixel_id, causal_relationships.clone());

                // Calculate causal influence on current pixel
                let causal_influence = calculate_causal_influence(
                    &causal_relationships,
                    &advancedstate.causal_graph,
                    config,
                )?;

                causal_output[(y, x)] = causal_influence;
            }
        }
    }

    Ok(causal_output)
}

/// Converts a 2D image to temporal representation
///
/// Creates a 3D temporal representation of the input image by analyzing
/// spatial gradients, edge patterns, and local statistics that can be
/// tracked over time.
///
/// # Arguments
/// * `image` - Input 2D image
///
/// # Returns
/// A 3D array containing temporal features for the image
#[allow(dead_code)]
fn image_to_temporal_representation<T>(image: &ArrayView2<T>) -> NdimageResult<Array3<f64>>
where
    T: Float + FromPrimitive + Copy,
{
    let (height, width) = image.dim();
    let mut temporal_features = Array3::zeros((height, width, 4));

    for y in 0..height {
        for x in 0..width {
            let pixel_val = image[(y, x)].to_f64().unwrap_or(0.0);

            // Basic intensity feature
            temporal_features[(y, x, 0)] = pixel_val;

            // Horizontal gradient
            let h_grad = if x > 0 && x < width - 1 {
                let left = image[(y, x - 1)].to_f64().unwrap_or(0.0);
                let right = image[(y, x + 1)].to_f64().unwrap_or(0.0);
                (right - left) / 2.0
            } else {
                0.0
            };
            temporal_features[(y, x, 1)] = h_grad;

            // Vertical gradient
            let v_grad = if y > 0 && y < height - 1 {
                let up = image[(y - 1, x)].to_f64().unwrap_or(0.0);
                let down = image[(y + 1, x)].to_f64().unwrap_or(0.0);
                (down - up) / 2.0
            } else {
                0.0
            };
            temporal_features[(y, x, 2)] = v_grad;

            // Local variance feature
            let mut local_vals = Vec::new();
            for dy in -1..=1i32 {
                for dx in -1..=1i32 {
                    let ny = y as i32 + dy;
                    let nx = x as i32 + dx;
                    if ny >= 0 && ny < height as i32 && nx >= 0 && nx < width as i32 {
                        let val = image[(ny as usize, nx as usize)].to_f64().unwrap_or(0.0);
                        local_vals.push(val);
                    }
                }
            }

            let local_variance = if local_vals.len() > 1 {
                let mean = local_vals.iter().sum::<f64>() / local_vals.len() as f64;
                local_vals.iter().map(|&v| (v - mean).powi(2)).sum::<f64>()
                    / local_vals.len() as f64
            } else {
                0.0
            };
            temporal_features[(y, x, 3)] = local_variance;
        }
    }

    Ok(temporal_features)
}

/// Extracts temporal sequence for a specific pixel from temporal memory
///
/// Retrieves the temporal evolution of features for a specific pixel position
/// across all frames in the temporal memory.
///
/// # Arguments
/// * `temporal_memory` - Queue of temporal feature arrays
/// * `position` - (y, x) coordinates of the pixel to extract
///
/// # Returns
/// Vector containing the temporal sequence of feature values for the pixel
#[allow(dead_code)]
fn extract_pixel_temporal_sequence(
    temporal_memory: &VecDeque<Array3<f64>>,
    position: (usize, usize),
) -> NdimageResult<Vec<f64>> {
    let (y, x) = position;
    let mut sequence = Vec::new();

    for frame in temporal_memory {
        if y < frame.shape()[0] && x < frame.shape()[1] {
            // Extract all temporal features for this pixel and combine them
            let mut pixel_features = Vec::new();
            for feature_idx in 0..frame.shape()[2] {
                pixel_features.push(frame[(y, x, feature_idx)]);
            }

            // Combine features into a single temporal value (weighted average)
            let combined_value = pixel_features
                .iter()
                .enumerate()
                .map(|(i, &val)| val * (i as f64 + 1.0) / pixel_features.len() as f64)
                .sum::<f64>();

            sequence.push(combined_value);
        }
    }

    // If sequence is too short, pad with zeros
    while sequence.len() < 8 {
        sequence.push(0.0);
    }

    Ok(sequence)
}

/// Detects causal relationships in temporal sequences
///
/// Implements multiple causality detection algorithms:
/// 1. Granger causality using cross-correlation analysis
/// 2. Transfer entropy approximation using variance-based entropy
///
/// # Arguments
/// * `temporal_sequence` - Temporal sequence of feature values
/// * `pixel_id` - Unique identifier for the source pixel
/// * `config` - Configuration parameters for causality analysis
///
/// # Returns
/// Vector of detected causal relationships with confidence scores
#[allow(dead_code)]
fn detect_causal_relationships(
    temporal_sequence: &[f64],
    pixel_id: usize,
    config: &AdvancedConfig,
) -> NdimageResult<Vec<CausalRelation>> {
    let mut causal_relations = Vec::new();

    if temporal_sequence.len() < config.causal_depth {
        return Ok(causal_relations);
    }

    // Granger causality-inspired analysis
    for delay in 1..config.causal_depth.min(temporal_sequence.len() / 2) {
        let mut cause_values = Vec::new();
        let mut effect_values = Vec::new();

        for i in delay..temporal_sequence.len() {
            cause_values.push(temporal_sequence[i - delay]);
            effect_values.push(temporal_sequence[i]);
        }

        if cause_values.len() < 3 {
            continue;
        }

        // Calculate correlation coefficient
        let cause_mean = cause_values.iter().sum::<f64>() / cause_values.len() as f64;
        let effect_mean = effect_values.iter().sum::<f64>() / effect_values.len() as f64;

        let numerator: f64 = cause_values
            .iter()
            .zip(effect_values.iter())
            .map(|(&c, &e)| (c - cause_mean) * (e - effect_mean))
            .sum();

        let cause_var: f64 = cause_values.iter().map(|&c| (c - cause_mean).powi(2)).sum();

        let effect_var: f64 = effect_values
            .iter()
            .map(|&e| (e - effect_mean).powi(2))
            .sum();

        let denominator = (cause_var * effect_var).sqrt();

        if denominator > 1e-10 {
            let correlation = numerator / denominator;
            let causal_strength = correlation.abs();

            // Threshold for significant causal relationship
            if causal_strength > 0.3 {
                // Calculate confidence based on sample size and strength
                let confidence =
                    (causal_strength * (cause_values.len() as f64).ln() / 10.0).min(1.0);

                // Determine target pixel (simplified for demonstration)
                let target_id = if correlation > 0.0 {
                    pixel_id + delay // Positive influence on neighboring pixel
                } else {
                    if pixel_id >= delay {
                        pixel_id - delay
                    } else {
                        pixel_id
                    } // Negative influence
                };

                causal_relations.push(CausalRelation {
                    source: pixel_id,
                    target: target_id,
                    strength: causal_strength,
                    delay,
                    confidence,
                });
            }
        }
    }

    // Transfer entropy-based causality detection
    for window_size in 2..=(config.causal_depth / 2).min(temporal_sequence.len() / 4) {
        if temporal_sequence.len() < window_size * 2 {
            continue;
        }

        // Simplified transfer entropy calculation
        let mut entropy_source = 0.0;
        let mut entropy_target = 0.0;
        let mut mutual_entropy = 0.0;

        for i in window_size..temporal_sequence.len() - window_size {
            let source_window = &temporal_sequence[i - window_size..i];
            let target_window = &temporal_sequence[i..i + window_size];

            // Simplified entropy calculation using variance
            let source_var = calculate_window_variance(source_window);
            let target_var = calculate_window_variance(target_window);

            entropy_source += source_var;
            entropy_target += target_var;

            // Cross-correlation as proxy for mutual information
            let cross_corr = source_window
                .iter()
                .zip(target_window.iter())
                .map(|(&s, &t)| s * t)
                .sum::<f64>()
                / window_size as f64;

            mutual_entropy += cross_corr.abs();
        }

        let n_windows = (temporal_sequence.len() - window_size * 2) as f64;
        if n_windows > 0.0 {
            entropy_source /= n_windows;
            entropy_target /= n_windows;
            mutual_entropy /= n_windows;

            // Transfer entropy approximation
            let transfer_entropy = mutual_entropy / (entropy_source + entropy_target + 1e-10);

            if transfer_entropy > 0.2 {
                let confidence = (transfer_entropy * n_windows.ln() / 5.0).min(1.0);

                causal_relations.push(CausalRelation {
                    source: pixel_id,
                    target: pixel_id + window_size, // Simplified target determination
                    strength: transfer_entropy,
                    delay: window_size,
                    confidence,
                });
            }
        }
    }

    // Sort by strength and keep only the strongest relationships
    causal_relations.sort_by(|a, b| {
        b.strength
            .partial_cmp(&a.strength)
            .unwrap_or(Ordering::Equal)
    });
    causal_relations.truncate(config.causal_depth / 2);

    Ok(causal_relations)
}

/// Calculates the overall causal influence on a pixel
///
/// Computes the aggregate causal influence on a pixel based on all detected
/// causal relationships in the graph. Takes into account both direct and
/// indirect causal pathways.
///
/// # Arguments
/// * `relationships` - Direct causal relationships for the pixel
/// * `causal_graph` - Complete causal relationship graph
/// * `config` - Configuration parameters for influence calculation
///
/// # Returns
/// Normalized causal influence score (0.0 to 1.0)
#[allow(dead_code)]
fn calculate_causal_influence(
    relationships: &[CausalRelation],
    causal_graph: &BTreeMap<usize, Vec<CausalRelation>>,
    _config: &AdvancedConfig,
) -> NdimageResult<f64> {
    if relationships.is_empty() {
        return Ok(0.0);
    }

    // Calculate direct influence
    let direct_influence: f64 = relationships
        .iter()
        .map(|rel| rel.strength * rel.confidence)
        .sum();

    // Calculate indirect influence through the causal graph
    let mut indirect_influence = 0.0;
    for relation in relationships {
        if let Some(target_relations) = causal_graph.get(&relation.target) {
            for target_rel in target_relations {
                // Weight indirect influence by distance and confidence
                let distance_weight = 1.0 / (relation.delay as f64 + 1.0);
                indirect_influence +=
                    target_rel.strength * target_rel.confidence * distance_weight * 0.5;
            }
        }
    }

    // Combine direct and indirect influences
    let total_influence = direct_influence + indirect_influence;

    // Normalize to [0, 1] range using a sigmoid-like function
    let normalized_influence = total_influence / (1.0 + total_influence);

    Ok(normalized_influence)
}

/// Calculates variance of values in a temporal window
///
/// Computes the statistical variance of a window of temporal values,
/// used as a proxy for entropy in causality analysis.
///
/// # Arguments
/// * `window` - Slice of temporal values
///
/// # Returns
/// Variance of the window values
#[allow(dead_code)]
fn calculate_window_variance(window: &[f64]) -> f64 {
    if window.is_empty() {
        return 0.0;
    }

    let mean = window.iter().sum::<f64>() / window.len() as f64;
    let variance = window.iter().map(|&x| (x - mean).powi(2)).sum::<f64>() / window.len() as f64;

    variance
}

/// Analyzes temporal causality patterns across multiple scales
///
/// Performs multi-scale temporal analysis to detect causal patterns
/// at different temporal resolutions.
///
/// # Arguments
/// * `temporal_memory` - Complete temporal memory buffer
/// * `config` - Configuration parameters
///
/// # Returns
/// Multi-scale causality analysis results
#[allow(dead_code)]
pub fn analyze_multiscale_temporal_causality(
    temporal_memory: &VecDeque<Array3<f64>>,
    config: &AdvancedConfig,
) -> NdimageResult<Vec<Array2<f64>>> {
    let mut scales_results = Vec::new();

    if temporal_memory.is_empty() {
        return Ok(scales_results);
    }

    let (height, width, _) = temporal_memory[0].dim();

    // Analyze at different temporal scales
    for scale in 1..=3 {
        let mut scale_result = Array2::zeros((height, width));
        let step_size = scale * 2;

        // Sample temporal memory at different scales
        let mut scaled_memory = VecDeque::new();
        for (i, frame) in temporal_memory.iter().enumerate() {
            if i % step_size == 0 {
                scaled_memory.push_back(frame.clone());
            }
        }

        if scaled_memory.len() >= config.causal_depth / scale {
            for y in 0..height {
                for x in 0..width {
                    // Extract temporal sequence at this scale
                    if let Ok(temporal_sequence) =
                        extract_pixel_temporal_sequence(&scaled_memory, (y, x))
                    {
                        let pixel_id = y * width + x;

                        // Detect causal relationships at this scale
                        if let Ok(relationships) =
                            detect_causal_relationships(&temporal_sequence, pixel_id, config)
                        {
                            let causal_strength: f64 = relationships
                                .iter()
                                .map(|rel| rel.strength * rel.confidence)
                                .sum();

                            scale_result[(y, x)] = causal_strength / (scale as f64);
                        }
                    }
                }
            }
        }

        scales_results.push(scale_result);
    }

    Ok(scales_results)
}

#[cfg(test)]
mod tests {
    use super::*;
    use scirs2_core::ndarray::Array2;

    #[test]
    fn test_calculate_window_variance() {
        let window = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        let variance = calculate_window_variance(&window);
        assert!(variance > 0.0);

        // Test empty window
        let empty_window = vec![];
        let zero_variance = calculate_window_variance(&empty_window);
        assert_eq!(zero_variance, 0.0);
    }

    #[test]
    fn test_image_to_temporal_representation() {
        let image = Array2::<f64>::zeros((10, 10));
        let result = image_to_temporal_representation(&image.view());
        assert!(result.is_ok());

        let temporal_features = result.expect("Operation failed");
        assert_eq!(temporal_features.dim(), (10, 10, 4));
    }

    #[test]
    fn test_extract_pixel_temporal_sequence() {
        let mut temporal_memory = VecDeque::new();
        let frame1 = Array3::<f64>::zeros((5, 5, 4));
        let frame2 = Array3::<f64>::ones((5, 5, 4));

        temporal_memory.push_back(frame1);
        temporal_memory.push_back(frame2);

        let result = extract_pixel_temporal_sequence(&temporal_memory, (2, 2));
        assert!(result.is_ok());

        let sequence = result.expect("Operation failed");
        assert!(!sequence.is_empty());
    }
}