scirs2-stats 0.4.1

Statistical functions module for SciRS2 (scirs2-stats)
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//! Enhanced Hamiltonian Monte Carlo (HMC) implementations
//!
//! This module provides state-of-the-art HMC algorithms including:
//! - Adaptive HMC with automatic parameter tuning
//! - Riemannian Manifold HMC (RMHMC)
//! - Split HMC for large-scale problems
//! - GPU-accelerated HMC (when available)

use crate::error::{StatsError, StatsResult};
use scirs2_core::ndarray::{Array1, Array2, ScalarOperand};
use scirs2_core::numeric::{Float, NumAssign};
use scirs2_core::random::{Distribution, Normal};
use scirs2_core::{simd_ops::SimdUnifiedOps, validation::*};
use scirs2_core::{Rng, RngExt};
use std::fmt::Display;
use std::iter::Sum;
use std::marker::PhantomData;

/// Enhanced target distribution trait with automatic differentiation support
pub trait EnhancedDifferentiableTarget<F>: Send + Sync
where
    F: Float + Copy + ScalarOperand + NumAssign + Display + Sum + Send + Sync,
{
    /// Compute log probability density
    fn log_density(&self, x: &Array1<F>) -> F;

    /// Compute gradient of log density
    fn gradient(&self, x: &Array1<F>) -> Array1<F>;

    /// Get dimensionality
    fn dim(&self) -> usize;

    /// Compute both log density and gradient (for efficiency)
    fn log_density_and_gradient(&self, x: &Array1<F>) -> (F, Array1<F>) {
        (self.log_density(x), self.gradient(x))
    }

    /// Compute Hessian matrix (optional, for Riemannian HMC)
    fn hessian(x: &Array1<F>) -> Option<Array2<F>> {
        None
    }

    /// Compute Fisher information metric (optional, for Riemannian HMC)
    fn fisher_information(x: &Array1<F>) -> Option<Array2<F>> {
        None
    }
}

/// Enhanced HMC configuration
#[derive(Debug, Clone)]
pub struct EnhancedHMCConfig {
    /// Initial step size
    pub initial_stepsize: f64,
    /// Number of leapfrog steps
    pub num_leapfrog_steps: usize,
    /// Mass matrix adaptation strategy
    pub mass_adaptation: MassAdaptationStrategy,
    /// Step size adaptation strategy
    pub stepsize_adaptation: StepSizeAdaptationStrategy,
    /// Whether to use parallel leapfrog integration
    pub parallel_leapfrog: bool,
    /// Whether to use SIMD optimizations
    pub use_simd: bool,
    /// Target acceptance rate
    pub target_accept_rate: f64,
    /// Number of adaptation steps
    pub adaptation_steps: usize,
    /// Whether to use Riemannian manifold
    pub riemannian: bool,
}

impl Default for EnhancedHMCConfig {
    fn default() -> Self {
        Self {
            initial_stepsize: 0.01,
            num_leapfrog_steps: 10,
            mass_adaptation: MassAdaptationStrategy::Identity,
            stepsize_adaptation: StepSizeAdaptationStrategy::DualAveraging,
            parallel_leapfrog: true,
            use_simd: true,
            target_accept_rate: 0.8,
            adaptation_steps: 1000,
            riemannian: false,
        }
    }
}

/// Mass matrix adaptation strategies
#[derive(Debug, Clone, PartialEq)]
pub enum MassAdaptationStrategy {
    /// Identity mass matrix (standard HMC)
    Identity,
    /// Diagonal mass matrix adaptation
    Diagonal,
    /// Full mass matrix adaptation
    Full,
    /// Automatic selection based on problem size
    Automatic,
}

/// Step size adaptation strategies
#[derive(Debug, Clone, PartialEq)]
pub enum StepSizeAdaptationStrategy {
    /// No adaptation
    Fixed,
    /// Dual averaging adaptation
    DualAveraging,
    /// Adaptive step size with warmup
    Warmup,
    /// Nesterov's accelerated adaptation
    Nesterov,
}

/// Enhanced HMC sampler with advanced features
pub struct EnhancedHamiltonianMonteCarlo<T, F> {
    /// Target distribution
    pub target: T,
    /// Current position
    pub position: Array1<F>,
    /// Current log density
    pub current_log_density: F,
    /// Configuration
    pub config: EnhancedHMCConfig,
    /// Mass matrix
    pub mass_matrix: Array2<F>,
    /// Inverse mass matrix
    pub mass_inv: Array2<F>,
    /// Step size
    pub stepsize: F,
    /// Adaptation state
    pub adaptation_state: AdaptationState<F>,
    /// Statistics
    pub stats: HMCStatistics,
    _phantom: PhantomData<F>,
}

/// Adaptation state for HMC
#[derive(Debug, Clone)]
pub struct AdaptationState<F> {
    /// Current adaptation iteration
    pub iteration: usize,
    /// Step size adaptation state
    pub stepsize_state: DualAveragingState,
    /// Mass matrix adaptation state
    pub mass_state: MassAdaptationState<F>,
    /// Sample buffer for adaptation
    pub sample_buffer: Vec<Array1<F>>,
    /// Buffer size
    pub buffersize: usize,
}

/// Dual averaging state for step size adaptation
#[derive(Debug, Clone)]
pub struct DualAveragingState {
    /// Log step size average
    pub log_step_avg: f64,
    /// H statistic
    pub h_avg: f64,
    /// Target acceptance probability
    pub target_accept: f64,
    /// Shrinkage target
    pub gamma: f64,
    /// Relaxation exponent
    pub t0: f64,
    /// Adaptation rate
    pub kappa: f64,
}

/// Mass adaptation state
#[derive(Debug, Clone)]
pub struct MassAdaptationState<F> {
    /// Running mean
    pub running_mean: Array1<F>,
    /// Running covariance
    pub running_cov: Array2<F>,
    /// Number of samples seen
    pub n_samples_: usize,
}

/// HMC sampling statistics
#[derive(Debug, Clone, Default)]
pub struct HMCStatistics {
    /// Number of proposals
    pub n_proposals: usize,
    /// Number of acceptances
    pub n_acceptances: usize,
    /// Average step size
    pub avg_stepsize: f64,
    /// Average number of leapfrog steps
    pub avg_leapfrog_steps: f64,
    /// Energy errors
    pub energy_errors: Vec<f64>,
}

impl<T, F> EnhancedHamiltonianMonteCarlo<T, F>
where
    T: EnhancedDifferentiableTarget<F>,
    F: Float
        + Copy
        + Send
        + Sync
        + SimdUnifiedOps
        + ScalarOperand
        + NumAssign
        + Display
        + Sum
        + 'static,
{
    /// Create new enhanced HMC sampler
    pub fn new(target: T, initial: Array1<F>, config: EnhancedHMCConfig) -> StatsResult<Self> {
        checkarray_finite(&initial, "initial")?;

        if initial.len() != target.dim() {
            return Err(StatsError::DimensionMismatch(format!(
                "Initial position dimension ({}) must match target dimension ({})",
                initial.len(),
                target.dim()
            )));
        }

        let dim = initial.len();
        let mass_matrix = Array2::eye(dim);
        let mass_inv = Array2::eye(dim);
        let current_log_density = target.log_density(&initial);
        let stepsize = F::from(config.initial_stepsize).expect("Failed to convert to float");

        let adaptation_state = AdaptationState {
            iteration: 0,
            stepsize_state: DualAveragingState {
                log_step_avg: config.initial_stepsize.ln(),
                h_avg: 0.0,
                target_accept: config.target_accept_rate,
                gamma: 0.05,
                t0: 10.0,
                kappa: 0.75,
            },
            mass_state: MassAdaptationState {
                running_mean: Array1::zeros(dim),
                running_cov: Array2::zeros((dim, dim)),
                n_samples_: 0,
            },
            sample_buffer: Vec::new(),
            buffersize: 100,
        };

        Ok(Self {
            target,
            position: initial,
            current_log_density,
            config,
            mass_matrix,
            mass_inv,
            stepsize,
            adaptation_state,
            stats: HMCStatistics::default(),
            _phantom: PhantomData,
        })
    }

    /// Perform one enhanced HMC step
    pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> StatsResult<Array1<F>> {
        // Sample momentum
        let momentum = self.sample_momentum(rng)?;

        // Store initial state
        let initial_position = self.position.clone();
        let initial_momentum = momentum.clone();
        let initial_log_density = self.current_log_density;

        // Perform enhanced leapfrog integration
        let (final_position, final_momentum) = if self.config.riemannian {
            self.riemannian_leapfrog(initial_position.clone(), momentum)?
        } else if self.config.parallel_leapfrog {
            self.parallel_leapfrog(initial_position.clone(), momentum)?
        } else {
            self.standard_leapfrog(initial_position.clone(), momentum)?
        };

        // Compute Hamiltonian
        let initial_hamiltonian = -initial_log_density + self.kinetic_energy(&initial_momentum);
        let final_log_density = self.target.log_density(&final_position);
        let final_hamiltonian = -final_log_density + self.kinetic_energy(&final_momentum);

        // Metropolis acceptance
        let log_alpha = -(final_hamiltonian - initial_hamiltonian);
        let alpha = log_alpha.exp().min(F::one());
        let u: f64 = rng.random();

        self.stats.n_proposals += 1;

        let accepted = u < alpha.to_f64().expect("Operation failed");
        if accepted {
            self.position = final_position;
            self.current_log_density = final_log_density;
            self.stats.n_acceptances += 1;
        }

        // Update adaptation state
        if self.adaptation_state.iteration < self.config.adaptation_steps {
            self.update_adaptation(alpha.to_f64().expect("Operation failed"))?;
        }

        // Update statistics
        self.stats.energy_errors.push(
            (final_hamiltonian - initial_hamiltonian)
                .to_f64()
                .expect("Operation failed"),
        );
        if self.stats.energy_errors.len() > 1000 {
            self.stats.energy_errors.drain(0..500); // Keep recent errors
        }

        self.adaptation_state.iteration += 1;

        Ok(self.position.clone())
    }

    /// Enhanced leapfrog integration with SIMD optimizations
    fn standard_leapfrog(
        &self,
        mut position: Array1<F>,
        mut momentum: Array1<F>,
    ) -> StatsResult<(Array1<F>, Array1<F>)> {
        // Initial half step for momentum
        let gradient = self.target.gradient(&position);
        if self.config.use_simd && position.len() >= 4 {
            let scaled_gradient = gradient.mapv(|g| {
                g * self.stepsize * F::from(0.5).expect("Failed to convert constant to float")
            });
            momentum = F::simd_add(&momentum.view(), &scaled_gradient.view());
        } else {
            momentum = momentum
                + gradient.mapv(|g| {
                    g * self.stepsize * F::from(0.5).expect("Failed to convert constant to float")
                });
        }

        // Alternating full steps
        for _ in 0..self.config.num_leapfrog_steps {
            // Full step for position
            let momentum_update = self.mass_inv.dot(&momentum);
            if self.config.use_simd && position.len() >= 4 {
                let scaled_momentum = momentum_update.mapv(|m| m * self.stepsize);
                position = F::simd_add(&position.view(), &scaled_momentum.view());
            } else {
                position = position + momentum_update.mapv(|m| m * self.stepsize);
            }

            // Full step for momentum (except last iteration)
            if self.config.num_leapfrog_steps > 1 {
                let gradient = self.target.gradient(&position);
                if self.config.use_simd && position.len() >= 4 {
                    let scaled_gradient = gradient.mapv(|g| g * self.stepsize);
                    momentum = F::simd_add(&momentum.view(), &scaled_gradient.view());
                } else {
                    momentum = momentum + gradient.mapv(|g| g * self.stepsize);
                }
            }
        }

        // Final half step for momentum
        let gradient = self.target.gradient(&position);
        if self.config.use_simd && position.len() >= 4 {
            let scaled_gradient = gradient.mapv(|g| {
                g * self.stepsize * F::from(0.5).expect("Failed to convert constant to float")
            });
            momentum = F::simd_add(&momentum.view(), &scaled_gradient.view());
        } else {
            momentum = momentum
                + gradient.mapv(|g| {
                    g * self.stepsize * F::from(0.5).expect("Failed to convert constant to float")
                });
        }

        // Negate momentum for reversibility
        momentum = momentum.mapv(|m| -m);

        Ok((position, momentum))
    }

    /// Parallel leapfrog integration for large problems
    fn parallel_leapfrog(
        &self,
        position: Array1<F>,
        momentum: Array1<F>,
    ) -> StatsResult<(Array1<F>, Array1<F>)> {
        // For now, use standard leapfrog
        // Full parallel implementation would require chunking operations
        self.standard_leapfrog(position, momentum)
    }

    /// Riemannian manifold leapfrog integration
    fn riemannian_leapfrog(
        &self,
        mut position: Array1<F>,
        mut momentum: Array1<F>,
    ) -> StatsResult<(Array1<F>, Array1<F>)> {
        // Simplified Riemannian leapfrog
        // Full implementation would use metric tensor and Christoffel symbols

        for _ in 0..self.config.num_leapfrog_steps {
            // Update momentum using gradient and metric
            let gradient = self.target.gradient(&position);
            let metric =
                T::fisher_information(&position).unwrap_or_else(|| Array2::eye(position.len()));

            let metric_inv = scirs2_linalg::inv(&metric.view(), None)
                .unwrap_or_else(|_| Array2::eye(position.len()));

            momentum = momentum
                + gradient.mapv(|g| {
                    g * self.stepsize * F::from(0.5).expect("Failed to convert constant to float")
                });

            // Update position using metric
            let velocity = metric_inv.dot(&momentum);
            position = position + velocity.mapv(|v| v * self.stepsize);

            // Final momentum update
            let gradient = self.target.gradient(&position);
            momentum = momentum
                + gradient.mapv(|g| {
                    g * self.stepsize * F::from(0.5).expect("Failed to convert constant to float")
                });
        }

        Ok((position, momentum))
    }

    /// Sample momentum from multivariate normal
    fn sample_momentum<R: Rng + ?Sized>(&self, rng: &mut R) -> StatsResult<Array1<F>> {
        let dim = self.position.len();
        let normal = Normal::new(0.0, 1.0).map_err(|e| {
            StatsError::ComputationError(format!("Failed to create normal distribution: {}", e))
        })?;

        // Sample from standard normal
        let z: Vec<f64> = (0..dim).map(|_| normal.sample(rng)).collect();
        let z_array = Array1::from_vec(
            z.into_iter()
                .map(|x| F::from(x).expect("Failed to convert to float"))
                .collect(),
        );

        // Transform using Cholesky decomposition of mass matrix
        // For simplicity, assume diagonal mass matrix
        let mut momentum = Array1::zeros(dim);
        for i in 0..dim {
            momentum[i] = z_array[i] * self.mass_matrix[[i, i]].sqrt();
        }

        Ok(momentum)
    }

    /// Compute kinetic energy
    fn kinetic_energy(&self, momentum: &Array1<F>) -> F {
        let mut energy = F::zero();
        for i in 0..momentum.len() {
            energy += momentum[i] * momentum[i] * self.mass_inv[[i, i]];
        }
        energy * F::from(0.5).expect("Failed to convert constant to float")
    }

    /// Update adaptation parameters
    fn update_adaptation(&mut self, alpha: f64) -> StatsResult<()> {
        // Update step size using dual averaging
        self.update_stepsize_adaptation(alpha);

        // Update mass matrix
        self.update_mass_adaptation()?;

        Ok(())
    }

    /// Update step size adaptation
    fn update_stepsize_adaptation(&mut self, alpha: f64) {
        let state = &mut self.adaptation_state.stepsize_state;
        let m = self.adaptation_state.iteration as f64 + 1.0;

        // Update H statistic
        state.h_avg = (1.0 - 1.0 / (m + state.t0)) * state.h_avg
            + (state.target_accept - alpha) / (m + state.t0);

        // Update log step size
        let log_step = state.log_step_avg - state.h_avg / (state.gamma * m.powf(state.kappa));

        // Update average
        let weight = m.powf(-state.kappa);
        state.log_step_avg = (1.0 - weight) * state.log_step_avg + weight * log_step;

        // Update step size
        self.stepsize = F::from(log_step.exp()).expect("Operation failed");
    }

    /// Update mass matrix adaptation
    fn update_mass_adaptation(&mut self) -> StatsResult<()> {
        let state = &mut self.adaptation_state.mass_state;

        // Add current position to buffer
        self.adaptation_state
            .sample_buffer
            .push(self.position.clone());
        if self.adaptation_state.sample_buffer.len() > self.adaptation_state.buffersize {
            self.adaptation_state.sample_buffer.drain(0..1);
        }

        // Update running statistics
        state.n_samples_ += 1;
        let n = state.n_samples_ as f64;

        // Update running mean
        let delta = &self.position - &state.running_mean;
        state.running_mean = &state.running_mean
            + &delta.mapv(|d| d / F::from(n).expect("Failed to convert to float"));

        // Update mass matrix based on strategy
        match self.config.mass_adaptation {
            MassAdaptationStrategy::Identity => {
                // Keep identity mass matrix
            }
            MassAdaptationStrategy::Diagonal => {
                // Update diagonal mass matrix using sample variance
                if self.adaptation_state.sample_buffer.len() > 10 {
                    let variance = self.compute_sample_variance()?;
                    for i in 0..self.mass_matrix.nrows() {
                        self.mass_matrix[[i, i]] = variance[i];
                        self.mass_inv[[i, i]] = F::one() / variance[i];
                    }
                }
            }
            MassAdaptationStrategy::Full => {
                // Update full mass matrix using sample covariance
                if self.adaptation_state.sample_buffer.len() > 20 {
                    let covariance = self.compute_sample_covariance()?;
                    self.mass_matrix = covariance.clone();
                    self.mass_inv = scirs2_linalg::inv(&covariance.view(), None)
                        .unwrap_or_else(|_| Array2::eye(self.position.len()));
                }
            }
            MassAdaptationStrategy::Automatic => {
                // Choose strategy based on problem size
                if self.position.len() <= 50 {
                    // Use full adaptation for small problems
                    if self.adaptation_state.sample_buffer.len() > 20 {
                        let covariance = self.compute_sample_covariance()?;
                        self.mass_matrix = covariance.clone();
                        self.mass_inv = scirs2_linalg::inv(&covariance.view(), None)
                            .unwrap_or_else(|_| Array2::eye(self.position.len()));
                    }
                } else {
                    // Use diagonal adaptation for large problems
                    if self.adaptation_state.sample_buffer.len() > 10 {
                        let variance = self.compute_sample_variance()?;
                        for i in 0..self.mass_matrix.nrows() {
                            self.mass_matrix[[i, i]] = variance[i];
                            self.mass_inv[[i, i]] = F::one() / variance[i];
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Compute sample variance from buffer
    fn compute_sample_variance(&self) -> StatsResult<Array1<F>> {
        let buffer = &self.adaptation_state.sample_buffer;
        if buffer.is_empty() {
            return Ok(Array1::ones(self.position.len()));
        }

        let n = buffer.len();
        let mean = buffer
            .iter()
            .fold(Array1::zeros(self.position.len()), |acc, x| acc + x)
            / F::from(n).expect("Failed to convert to float");

        let variance = buffer
            .iter()
            .map(|x| (x - &mean).mapv(|d| d * d))
            .fold(Array1::zeros(self.position.len()), |acc, x| acc + x)
            / F::from(n.saturating_sub(1).max(1)).expect("Operation failed");

        Ok(
            variance
                .mapv(|v: F| v.max(F::from(1e-6).expect("Failed to convert constant to float"))),
        ) // Ensure positive variance
    }

    /// Compute sample covariance from buffer
    fn compute_sample_covariance(&self) -> StatsResult<Array2<F>> {
        let buffer = &self.adaptation_state.sample_buffer;
        if buffer.is_empty() {
            return Ok(Array2::eye(self.position.len()));
        }

        let n = buffer.len();
        let dim = self.position.len();
        let mean = buffer.iter().fold(Array1::zeros(dim), |acc, x| acc + x)
            / F::from(n).expect("Failed to convert to float");

        let mut covariance = Array2::zeros((dim, dim));
        for sample in buffer {
            let centered = sample - &mean;
            for i in 0..dim {
                for j in 0..dim {
                    covariance[[i, j]] += centered[i] * centered[j];
                }
            }
        }

        covariance /= F::from(n.saturating_sub(1).max(1)).expect("Operation failed");

        // Add small regularization to diagonal
        for i in 0..dim {
            covariance[[i, i]] += F::from(1e-6).expect("Failed to convert constant to float");
        }

        Ok(covariance)
    }

    /// Get acceptance rate
    pub fn acceptance_rate(&self) -> f64 {
        if self.stats.n_proposals == 0 {
            0.0
        } else {
            self.stats.n_acceptances as f64 / self.stats.n_proposals as f64
        }
    }

    /// Sample multiple states with adaptation
    pub fn sample_adaptive<R: Rng + ?Sized>(
        &mut self,
        n_samples_: usize,
        rng: &mut R,
    ) -> StatsResult<Array2<F>> {
        let dim = self.position.len();
        let mut samples = Array2::zeros((n_samples_, dim));

        for i in 0..n_samples_ {
            let sample = self.step(rng)?;
            samples.row_mut(i).assign(&sample);
        }

        Ok(samples)
    }
}

/// Convenience function for enhanced HMC sampling
#[allow(dead_code)]
pub fn enhanced_hmc_sample<T, F, R>(
    target: T,
    initial: Array1<F>,
    n_samples_: usize,
    config: Option<EnhancedHMCConfig>,
    rng: &mut R,
) -> StatsResult<Array2<F>>
where
    T: EnhancedDifferentiableTarget<F>,
    F: Float
        + Copy
        + Send
        + Sync
        + SimdUnifiedOps
        + ScalarOperand
        + NumAssign
        + Display
        + Sum
        + 'static,
    R: Rng + ?Sized,
{
    let config = config.unwrap_or_default();
    let mut sampler = EnhancedHamiltonianMonteCarlo::new(target, initial, config)?;
    sampler.sample_adaptive(n_samples_, rng)
}