sublinear 0.2.0

High-performance sublinear-time solver for asymmetric diagonally dominant systems
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
use std::collections::{HashMap, VecDeque};
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
use crate::core::{SparseMatrix, Vector, Result, SublinearError};
use crate::algorithms::{Precision, ConvergenceMetrics};

/// Configuration for random walk algorithms
#[derive(Debug, Clone)]
pub struct RandomWalkConfig {
    pub max_steps: usize,
    pub step_size: f64,
    pub convergence_tolerance: f64,
    pub variance_reduction: VarianceReduction,
    pub restart_probability: f64,
    pub seed: Option<u64>,
}

impl Default for RandomWalkConfig {
    fn default() -> Self {
        Self {
            max_steps: 10000,
            step_size: 0.85,
            convergence_tolerance: 1e-6,
            variance_reduction: VarianceReduction::Antithetic,
            restart_probability: 0.15,
            seed: None,
        }
    }
}

/// Variance reduction techniques for Monte Carlo estimation
#[derive(Debug, Clone, PartialEq)]
pub enum VarianceReduction {
    None,
    Antithetic,
    ControlVariates,
    ImportanceSampling,
    StratifiedSampling,
}

/// Random walk engine for solving linear systems and optimization problems
pub struct RandomWalkEngine {
    config: RandomWalkConfig,
    rng: ChaCha8Rng,
    convergence_history: Vec<f64>,
    step_count: usize,
}

impl RandomWalkEngine {
    pub fn new(config: RandomWalkConfig) -> Self {
        let rng = match config.seed {
            Some(seed) => ChaCha8Rng::seed_from_u64(seed),
            None => ChaCha8Rng::from_entropy(),
        };

        Self {
            config,
            rng,
            convergence_history: Vec::new(),
            step_count: 0,
        }
    }

    /// Solve linear system Ax = b using Monte Carlo random walks
    pub fn solve_linear_system(&mut self, a: &SparseMatrix, b: &Vector) -> Result<Vector> {
        if a.rows() != a.cols() {
            return Err(SublinearError::InvalidDimensions);
        }
        if a.rows() != b.len() {
            return Err(SublinearError::InvalidDimensions);
        }

        let n = a.rows();
        let mut solution = vec![0.0; n];
        let mut estimates = vec![Vec::new(); n];

        // Monte Carlo estimation with variance reduction
        for iteration in 0..self.config.max_steps {
            for start_vertex in 0..n {
                let estimate = self.random_walk_estimate(a, b, start_vertex)?;
                estimates[start_vertex].push(estimate);

                // Update running average
                let count = estimates[start_vertex].len() as f64;
                solution[start_vertex] = (solution[start_vertex] * (count - 1.0) + estimate) / count;
            }

            // Check convergence every 100 iterations
            if iteration % 100 == 0 && iteration > 0 {
                let convergence = self.compute_convergence(&estimates);
                self.convergence_history.push(convergence);

                if convergence < self.config.convergence_tolerance {
                    break;
                }
            }
        }

        self.step_count = self.convergence_history.len() * 100;
        Ok(solution)
    }

    /// Perform single random walk from start vertex
    fn random_walk_estimate(&mut self, a: &SparseMatrix, b: &Vector, start: usize) -> Result<f64> {
        let mut current = start;
        let mut path_sum = 0.0;
        let mut path_weight = 1.0;
        let mut steps = 0;

        loop {
            // Add contribution from current vertex
            path_sum += path_weight * b[current];

            // Check for restart or termination
            if self.rng.gen::<f64>() < self.config.restart_probability || steps >= self.config.max_steps {
                break;
            }

            // Choose next vertex based on transition probabilities
            let next_vertex = self.choose_next_vertex(a, current)?;
            if let Some(next) = next_vertex {
                // Update path weight based on transition probability
                let transition_prob = self.compute_transition_probability(a, current, next)?;
                path_weight *= transition_prob / self.config.step_size;
                current = next;
                steps += 1;
            } else {
                break;
            }
        }

        // Apply variance reduction if configured
        match self.config.variance_reduction {
            VarianceReduction::Antithetic => {
                let antithetic_estimate = self.antithetic_walk_estimate(a, b, start)?;
                Ok((path_sum + antithetic_estimate) / 2.0)
            }
            _ => Ok(path_sum),
        }
    }

    /// Choose next vertex in random walk based on matrix structure
    fn choose_next_vertex(&mut self, a: &SparseMatrix, current: usize) -> Result<Option<usize>> {
        let row = a.get_row(current);
        if row.is_empty() {
            return Ok(None);
        }

        // Compute cumulative distribution for vertex selection
        let mut cumulative_probs = Vec::new();
        let mut total_weight = 0.0;

        for (col, &weight) in row {
            total_weight += weight.abs();
            cumulative_probs.push((col, total_weight));
        }

        if total_weight == 0.0 {
            return Ok(None);
        }

        // Sample from cumulative distribution
        let sample = self.rng.gen::<f64>() * total_weight;
        for (col, cumulative) in cumulative_probs {
            if sample <= cumulative {
                return Ok(Some(col));
            }
        }

        Ok(None)
    }

    /// Compute transition probability between vertices
    fn compute_transition_probability(&self, a: &SparseMatrix, from: usize, to: usize) -> Result<f64> {
        let row = a.get_row(from);
        let total_weight: f64 = row.iter().map(|(_, &w)| w.abs()).sum();

        if total_weight == 0.0 {
            return Ok(0.0);
        }

        if let Some(&weight) = row.get(&to) {
            Ok(weight.abs() / total_weight)
        } else {
            Ok(0.0)
        }
    }

    /// Antithetic variance reduction technique
    fn antithetic_walk_estimate(&mut self, a: &SparseMatrix, b: &Vector, start: usize) -> Result<f64> {
        // Store current RNG state
        let original_rng = self.rng.clone();

        // Generate antithetic random numbers (1 - u instead of u)
        let mut current = start;
        let mut path_sum = 0.0;
        let mut path_weight = 1.0;
        let mut steps = 0;

        loop {
            path_sum += path_weight * b[current];

            let restart_rand = 1.0 - self.rng.gen::<f64>(); // Antithetic
            if restart_rand < self.config.restart_probability || steps >= self.config.max_steps {
                break;
            }

            let next_vertex = self.choose_next_vertex_antithetic(a, current)?;
            if let Some(next) = next_vertex {
                let transition_prob = self.compute_transition_probability(a, current, next)?;
                path_weight *= transition_prob / self.config.step_size;
                current = next;
                steps += 1;
            } else {
                break;
            }
        }

        // Restore original RNG state
        self.rng = original_rng;
        Ok(path_sum)
    }

    /// Choose next vertex using antithetic sampling
    fn choose_next_vertex_antithetic(&mut self, a: &SparseMatrix, current: usize) -> Result<Option<usize>> {
        let row = a.get_row(current);
        if row.is_empty() {
            return Ok(None);
        }

        let mut cumulative_probs = Vec::new();
        let mut total_weight = 0.0;

        for (col, &weight) in row {
            total_weight += weight.abs();
            cumulative_probs.push((col, total_weight));
        }

        if total_weight == 0.0 {
            return Ok(None);
        }

        // Antithetic sampling: use (1 - u) instead of u
        let sample = (1.0 - self.rng.gen::<f64>()) * total_weight;
        for (col, cumulative) in cumulative_probs {
            if sample <= cumulative {
                return Ok(Some(col));
            }
        }

        Ok(None)
    }

    /// Compute convergence metric across all estimates
    fn compute_convergence(&self, estimates: &[Vec<f64>]) -> f64 {
        let mut max_variance = 0.0;

        for vertex_estimates in estimates {
            if vertex_estimates.len() < 2 {
                continue;
            }

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

            max_variance = max_variance.max(variance.sqrt() / mean.abs().max(1e-10));
        }

        max_variance
    }

    /// Get convergence metrics
    pub fn get_metrics(&self) -> ConvergenceMetrics {
        ConvergenceMetrics {
            iterations: self.step_count,
            residual: self.convergence_history.last().copied().unwrap_or(f64::INFINITY),
            convergence_rate: self.compute_convergence_rate(),
            precision: if self.convergence_history.last().unwrap_or(&f64::INFINITY) < &self.config.convergence_tolerance {
                Precision::High
            } else {
                Precision::Low
            },
        }
    }

    fn compute_convergence_rate(&self) -> f64 {
        if self.convergence_history.len() < 2 {
            return 0.0;
        }

        let n = self.convergence_history.len();
        let recent_slope = (self.convergence_history[n-1] - self.convergence_history[n-2]).abs();
        recent_slope.max(1e-12)
    }
}

/// Bidirectional random walk for improved convergence
pub struct BidirectionalWalk {
    forward_engine: RandomWalkEngine,
    backward_engine: RandomWalkEngine,
}

impl BidirectionalWalk {
    pub fn new(config: RandomWalkConfig) -> Self {
        let mut backward_config = config.clone();
        backward_config.seed = config.seed.map(|s| s.wrapping_add(1));

        Self {
            forward_engine: RandomWalkEngine::new(config),
            backward_engine: RandomWalkEngine::new(backward_config),
        }
    }

    /// Solve using bidirectional random walks
    pub fn solve_linear_system(&mut self, a: &SparseMatrix, b: &Vector) -> Result<Vector> {
        // Solve forward problem: Ax = b
        let forward_solution = self.forward_engine.solve_linear_system(a, b)?;

        // Solve backward problem: A^T y = x, then use for refinement
        let a_transpose = a.transpose();
        let backward_solution = self.backward_engine.solve_linear_system(&a_transpose, &forward_solution)?;

        // Combine solutions with optimal weighting
        let alpha = self.compute_optimal_weight(&forward_solution, &backward_solution);
        let mut combined = vec![0.0; forward_solution.len()];

        for i in 0..combined.len() {
            combined[i] = alpha * forward_solution[i] + (1.0 - alpha) * backward_solution[i];
        }

        Ok(combined)
    }

    fn compute_optimal_weight(&self, forward: &Vector, backward: &Vector) -> f64 {
        let forward_metrics = self.forward_engine.get_metrics();
        let backward_metrics = self.backward_engine.get_metrics();

        // Weight based on convergence quality
        let forward_quality = 1.0 / (forward_metrics.residual + 1e-10);
        let backward_quality = 1.0 / (backward_metrics.residual + 1e-10);

        forward_quality / (forward_quality + backward_quality)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::*;

    #[test]
    fn test_random_walk_engine_creation() {
        let config = RandomWalkConfig::default();
        let engine = RandomWalkEngine::new(config);
        assert_eq!(engine.step_count, 0);
    }

    #[test]
    fn test_simple_linear_system() {
        let mut config = RandomWalkConfig::default();
        config.max_steps = 1000;
        config.seed = Some(42);

        let mut engine = RandomWalkEngine::new(config);

        // Simple 2x2 system: [2, -1; -1, 2] * x = [1; 1]
        let mut matrix = SparseMatrix::new(2, 2);
        matrix.insert(0, 0, 2.0);
        matrix.insert(0, 1, -1.0);
        matrix.insert(1, 0, -1.0);
        matrix.insert(1, 1, 2.0);

        let b = vec![1.0, 1.0];
        let solution = engine.solve_linear_system(&matrix, &b).unwrap();

        // Expected solution is approximately [1, 1]
        assert!((solution[0] - 1.0).abs() < 0.1);
        assert!((solution[1] - 1.0).abs() < 0.1);
    }

    #[test]
    fn test_bidirectional_walk() {
        let mut config = RandomWalkConfig::default();
        config.max_steps = 500;
        config.seed = Some(123);

        let mut bidirectional = BidirectionalWalk::new(config);

        let mut matrix = SparseMatrix::new(3, 3);
        matrix.insert(0, 0, 3.0);
        matrix.insert(0, 1, -1.0);
        matrix.insert(1, 0, -1.0);
        matrix.insert(1, 1, 3.0);
        matrix.insert(1, 2, -1.0);
        matrix.insert(2, 1, -1.0);
        matrix.insert(2, 2, 3.0);

        let b = vec![2.0, 1.0, 2.0];
        let solution = bidirectional.solve_linear_system(&matrix, &b).unwrap();

        assert_eq!(solution.len(), 3);
        // Verify solution quality by checking residual
        let residual = compute_residual(&matrix, &solution, &b);
        assert!(residual < 0.5);
    }
}