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
//! Type-safe manifold abstractions with phantom types
//!
//! This module provides compile-time type safety for manifold learning algorithms
//! using phantom types to encode manifold structure, dimensionality, and properties
//! at the type level. This prevents many runtime errors and improves API safety.
use scirs2_core::ndarray::{Array2, ArrayView2};
/// Phantom type markers for manifold structure types
use sklears_core::{
error::{Result as SklResult, SklearsError},
types::Float,
};
use std::marker::PhantomData;
pub mod structure {
/// Marker for Euclidean manifolds (flat geometry)
pub struct Euclidean;
/// Marker for Riemannian manifolds (curved geometry)
pub struct Riemannian;
/// Marker for topological manifolds (general topology)
pub struct Topological;
/// Marker for discrete manifolds (graph-like structures)
pub struct Discrete;
/// Marker for unknown/generic manifold structure
pub struct Unknown;
}
/// Phantom type markers for manifold properties
pub mod properties {
/// Marker for manifolds with known curvature
pub struct HasCurvature;
/// Marker for manifolds without curvature (flat)
pub struct NoCurvature;
/// Marker for orientable manifolds
pub struct Orientable;
/// Marker for non-orientable manifolds
pub struct NonOrientable;
/// Marker for compact manifolds
pub struct Compact;
/// Marker for non-compact manifolds
pub struct NonCompact;
/// Marker for connected manifolds
pub struct Connected;
/// Marker for disconnected manifolds
pub struct Disconnected;
}
/// Phantom type markers for dimensionality
pub mod dimension {
use std::marker::PhantomData;
/// Compile-time dimension representation
pub struct Dim<const N: usize>(PhantomData<[(); N]>);
/// Dynamic dimension (unknown at compile time)
pub struct Dynamic;
/// Type alias for common dimensions
pub type Dim1 = Dim<1>;
pub type Dim2 = Dim<2>;
pub type Dim3 = Dim<3>;
pub type Dim4 = Dim<4>;
pub type DimN<const N: usize> = Dim<N>;
}
/// Type-safe manifold wrapper that encodes structure and properties
///
/// This struct uses phantom types to encode manifold characteristics at compile time,
/// providing type safety and preventing invalid operations.
///
/// # Type Parameters
///
/// * `S` - Structure type (Euclidean, Riemannian, etc.)
/// * `P` - Properties type (HasCurvature, Orientable, etc.)
/// * `D` - Dimension type (`Dim<N>` or Dynamic)
///
/// # Examples
///
/// ```
/// use sklears_manifold::type_safe_manifolds::*;
/// use scirs2_core::ndarray::{array, ArrayView2};
///
/// // Create a 2D Euclidean manifold
/// let data = array![[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]];
/// let manifold = TypeSafeManifold::<structure::Euclidean, properties::NoCurvature, dimension::Dim2>::new(data);
/// ```
#[derive(Debug, Clone)]
pub struct TypeSafeManifold<S, P, D> {
data: Array2<Float>,
_structure: PhantomData<S>,
_properties: PhantomData<P>,
_dimension: PhantomData<D>,
}
impl<S, P, D> TypeSafeManifold<S, P, D> {
/// Create a new type-safe manifold
///
/// # Arguments
///
/// * `data` - The manifold data matrix
///
/// # Returns
///
/// A type-safe manifold wrapper
pub fn new(data: Array2<Float>) -> Self {
Self {
data,
_structure: PhantomData,
_properties: PhantomData,
_dimension: PhantomData,
}
}
/// Get a reference to the underlying data
pub fn data(&self) -> &Array2<Float> {
&self.data
}
/// Get a view of the underlying data
pub fn view(&self) -> ArrayView2<'_, Float> {
self.data.view()
}
/// Get the number of points on the manifold
pub fn n_points(&self) -> usize {
self.data.nrows()
}
/// Get the ambient dimension of the manifold
pub fn ambient_dim(&self) -> usize {
self.data.ncols()
}
}
/// Implementation for manifolds with compile-time known dimensions
impl<S, P, const N: usize> TypeSafeManifold<S, P, dimension::Dim<N>> {
/// Get the compile-time known dimension
pub const fn intrinsic_dim() -> usize {
N
}
/// Validate that the data has the correct dimension
pub fn validate_dimension(&self) -> SklResult<()> {
if self.ambient_dim() < N {
return Err(SklearsError::InvalidParameter {
name: "ambient_dimension".to_string(),
reason: format!(
"Ambient dimension {} is less than intrinsic dimension {}",
self.ambient_dim(),
N
),
});
}
Ok(())
}
}
/// Implementation for dynamic dimension manifolds
impl<S, P> TypeSafeManifold<S, P, dimension::Dynamic> {
/// Set the intrinsic dimension dynamically
pub fn with_intrinsic_dim(self, intrinsic_dim: usize) -> SklResult<Self> {
if intrinsic_dim > self.ambient_dim() {
return Err(SklearsError::InvalidParameter {
name: "intrinsic_dimension".to_string(),
reason: format!(
"Intrinsic dimension {} exceeds ambient dimension {}",
intrinsic_dim,
self.ambient_dim()
),
});
}
Ok(self)
}
}
/// Euclidean manifold specific operations
impl<P, D> TypeSafeManifold<structure::Euclidean, P, D> {
/// Compute Euclidean distances between points
pub fn euclidean_distances(&self) -> Array2<Float> {
let n = self.n_points();
let mut distances = Array2::zeros((n, n));
for i in 0..n {
for j in i..n {
let dist = self.euclidean_distance_pair(i, j);
distances[[i, j]] = dist;
distances[[j, i]] = dist;
}
}
distances
}
/// Compute Euclidean distance between two points
fn euclidean_distance_pair(&self, i: usize, j: usize) -> Float {
let row_i = self.data.row(i);
let row_j = self.data.row(j);
row_i
.iter()
.zip(row_j.iter())
.map(|(a, b)| (a - b).powi(2))
.sum::<Float>()
.sqrt()
}
/// Project onto a linear subspace (valid for Euclidean manifolds)
pub fn linear_projection(&self, target_dim: usize) -> SklResult<Array2<Float>> {
if target_dim > self.ambient_dim() {
return Err(SklearsError::InvalidParameter {
name: "target_dimension".to_string(),
reason: format!(
"Target dimension {} exceeds ambient dimension {}",
target_dim,
self.ambient_dim()
),
});
}
// Simple projection by taking the first target_dim columns
Ok(self
.data
.slice(scirs2_core::ndarray::s![.., ..target_dim])
.to_owned())
}
}
/// Riemannian manifold specific operations
impl<P, D> TypeSafeManifold<structure::Riemannian, P, D> {
/// Estimate geodesic distances (placeholder implementation)
pub fn geodesic_distances(&self) -> SklResult<Array2<Float>> {
// This would implement geodesic distance computation
// For now, we'll use Euclidean as an approximation
Ok(self.euclidean_approximation())
}
/// Compute metric tensor at a point (placeholder)
pub fn metric_tensor(&self, point_idx: usize) -> SklResult<Array2<Float>> {
if point_idx >= self.n_points() {
return Err(SklearsError::InvalidParameter {
name: "point_index".to_string(),
reason: format!("Point index {} out of bounds", point_idx),
});
}
// Placeholder: return identity matrix as metric tensor
let dim = self.ambient_dim();
Ok(Array2::eye(dim))
}
/// Euclidean approximation for Riemannian distances
fn euclidean_approximation(&self) -> Array2<Float> {
let n = self.n_points();
let mut distances = Array2::zeros((n, n));
for i in 0..n {
for j in i..n {
let row_i = self.data.row(i);
let row_j = self.data.row(j);
let dist = row_i
.iter()
.zip(row_j.iter())
.map(|(a, b)| (a - b).powi(2))
.sum::<Float>()
.sqrt();
distances[[i, j]] = dist;
distances[[j, i]] = dist;
}
}
distances
}
}
/// Discrete manifold operations (for graph-like structures)
impl<P, D> TypeSafeManifold<structure::Discrete, P, D> {
/// Build adjacency matrix based on k-nearest neighbors
pub fn knn_adjacency(&self, k: usize) -> SklResult<Array2<Float>> {
if k >= self.n_points() {
return Err(SklearsError::InvalidParameter {
name: "k".to_string(),
reason: format!(
"k={} must be less than number of points {}",
k,
self.n_points()
),
});
}
let n = self.n_points();
let mut adjacency = Array2::zeros((n, n));
// Compute distances and find k-nearest neighbors
for i in 0..n {
let mut distances: Vec<(Float, usize)> = Vec::new();
for j in 0..n {
if i != j {
let row_i = self.data.row(i);
let row_j = self.data.row(j);
let dist = row_i
.iter()
.zip(row_j.iter())
.map(|(a, b)| (a - b).powi(2))
.sum::<Float>()
.sqrt();
distances.push((dist, j));
}
}
// Sort by distance and take k nearest
distances.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("operation should succeed"));
for (_dist, neighbor) in distances.iter().take(k) {
adjacency[[i, *neighbor]] = 1.0;
adjacency[[*neighbor, i]] = 1.0; // Make symmetric
}
}
Ok(adjacency)
}
/// Compute shortest path distances using Floyd-Warshall
pub fn shortest_path_distances(&self, adjacency: &Array2<Float>) -> SklResult<Array2<Float>> {
let n = self.n_points();
if adjacency.shape() != [n, n] {
return Err(SklearsError::InvalidParameter {
name: "adjacency_shape".to_string(),
reason: format!(
"Adjacency matrix shape {:?} doesn't match data shape [{}x{}]",
adjacency.shape(),
n,
n
),
});
}
let mut distances = adjacency.clone();
// Initialize with large values for non-connected pairs
for i in 0..n {
for j in 0..n {
if i != j && distances[[i, j]] == 0.0 {
distances[[i, j]] = Float::INFINITY;
}
}
}
// Floyd-Warshall algorithm
for k in 0..n {
for i in 0..n {
for j in 0..n {
let through_k = distances[[i, k]] + distances[[k, j]];
if through_k < distances[[i, j]] {
distances[[i, j]] = through_k;
}
}
}
}
Ok(distances)
}
}
/// Type conversion utilities
impl<S, P, D> TypeSafeManifold<S, P, D> {
/// Convert to a different structure type
pub fn cast_structure<NewS>(self) -> TypeSafeManifold<NewS, P, D> {
TypeSafeManifold {
data: self.data,
_structure: PhantomData,
_properties: PhantomData,
_dimension: PhantomData,
}
}
/// Convert to a different property type
pub fn cast_properties<NewP>(self) -> TypeSafeManifold<S, NewP, D> {
TypeSafeManifold {
data: self.data,
_structure: PhantomData,
_properties: PhantomData,
_dimension: PhantomData,
}
}
/// Convert to dynamic dimension
pub fn to_dynamic_dim(self) -> TypeSafeManifold<S, P, dimension::Dynamic> {
TypeSafeManifold {
data: self.data,
_structure: PhantomData,
_properties: PhantomData,
_dimension: PhantomData,
}
}
}
/// Manifold builder for constructing type-safe manifolds
#[derive(Debug)]
pub struct ManifoldBuilder<S, P, D> {
_structure: PhantomData<S>,
_properties: PhantomData<P>,
_dimension: PhantomData<D>,
}
impl Default for ManifoldBuilder<structure::Unknown, properties::NoCurvature, dimension::Dynamic> {
fn default() -> Self {
Self::new()
}
}
impl ManifoldBuilder<structure::Unknown, properties::NoCurvature, dimension::Dynamic> {
/// Create a new manifold builder
pub fn new() -> Self {
Self {
_structure: PhantomData,
_properties: PhantomData,
_dimension: PhantomData,
}
}
}
impl<S, P, D> ManifoldBuilder<S, P, D> {
/// Set the structure type
pub fn structure<NewS>(self) -> ManifoldBuilder<NewS, P, D> {
ManifoldBuilder {
_structure: PhantomData,
_properties: PhantomData,
_dimension: PhantomData,
}
}
/// Set the properties type
pub fn properties<NewP>(self) -> ManifoldBuilder<S, NewP, D> {
ManifoldBuilder {
_structure: PhantomData,
_properties: PhantomData,
_dimension: PhantomData,
}
}
/// Set the dimension type
pub fn dimension<NewD>(self) -> ManifoldBuilder<S, P, NewD> {
ManifoldBuilder {
_structure: PhantomData,
_properties: PhantomData,
_dimension: PhantomData,
}
}
/// Build the manifold with the given data
pub fn build(self, data: Array2<Float>) -> TypeSafeManifold<S, P, D> {
TypeSafeManifold::new(data)
}
}
/// Trait for validating manifold properties at compile time
pub trait ManifoldValidator<S, P, D> {
/// Validate manifold structure and properties
fn validate(&self) -> SklResult<()>;
}
/// Default validation for dynamic dimension manifolds
impl<S, P> ManifoldValidator<S, P, dimension::Dynamic>
for TypeSafeManifold<S, P, dimension::Dynamic>
{
fn validate(&self) -> SklResult<()> {
if self.n_points() == 0 {
return Err(SklearsError::InvalidParameter {
name: "n_points".to_string(),
reason: "Manifold must have at least one point".to_string(),
});
}
if self.ambient_dim() == 0 {
return Err(SklearsError::InvalidParameter {
name: "ambient_dimension".to_string(),
reason: "Manifold must have positive ambient dimension".to_string(),
});
}
Ok(())
}
}
/// Specialized validation for fixed-dimension manifolds
impl<S, P, const N: usize> ManifoldValidator<S, P, dimension::Dim<N>>
for TypeSafeManifold<S, P, dimension::Dim<N>>
{
fn validate(&self) -> SklResult<()> {
// Basic validation
if self.n_points() == 0 {
return Err(SklearsError::InvalidParameter {
name: "n_points".to_string(),
reason: "Manifold must have at least one point".to_string(),
});
}
if self.ambient_dim() == 0 {
return Err(SklearsError::InvalidParameter {
name: "ambient_dimension".to_string(),
reason: "Manifold must have positive ambient dimension".to_string(),
});
}
// Additional dimension validation
self.validate_dimension()?;
Ok(())
}
}
/// Type alias helpers for common manifold types
pub type EuclideanManifold2D =
TypeSafeManifold<structure::Euclidean, properties::NoCurvature, dimension::Dim2>;
pub type EuclideanManifold3D =
TypeSafeManifold<structure::Euclidean, properties::NoCurvature, dimension::Dim3>;
pub type RiemannianManifold<const N: usize> =
TypeSafeManifold<structure::Riemannian, properties::HasCurvature, dimension::Dim<N>>;
pub type DiscreteManifold =
TypeSafeManifold<structure::Discrete, properties::Disconnected, dimension::Dynamic>;
#[allow(non_snake_case)]
#[cfg(test)]
mod tests {
use super::*;
use approx::assert_abs_diff_eq;
use scirs2_core::ndarray::array;
#[test]
fn test_euclidean_manifold_creation() {
let data = array![[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]];
let manifold = EuclideanManifold2D::new(data);
assert_eq!(manifold.n_points(), 3);
assert_eq!(manifold.ambient_dim(), 2);
assert_eq!(EuclideanManifold2D::intrinsic_dim(), 2);
}
#[test]
fn test_euclidean_distances() {
let data = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
let manifold = EuclideanManifold2D::new(data);
let distances = manifold.euclidean_distances();
assert_abs_diff_eq!(distances[[0, 1]], 1.0, epsilon = 1e-10);
assert_abs_diff_eq!(distances[[0, 2]], 1.0, epsilon = 1e-10);
assert_abs_diff_eq!(distances[[1, 2]], 2.0_f64.sqrt(), epsilon = 1e-10);
}
#[test]
fn test_manifold_builder() {
let data = array![[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]];
let manifold = ManifoldBuilder::new()
.structure::<structure::Euclidean>()
.properties::<properties::NoCurvature>()
.dimension::<dimension::Dim3>()
.build(data);
assert_eq!(manifold.n_points(), 2);
assert_eq!(manifold.ambient_dim(), 3);
}
#[test]
fn test_dimension_validation() {
let data = array![[1.0, 2.0], [3.0, 4.0]]; // 2D data
let manifold = TypeSafeManifold::<
structure::Euclidean,
properties::NoCurvature,
dimension::Dim3,
>::new(data);
// Should fail because data is 2D but we claim it's 3D
assert!(manifold.validate_dimension().is_err());
}
#[test]
fn test_discrete_manifold_adjacency() {
let data = array![[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [3.0, 0.0]];
let manifold = DiscreteManifold::new(data);
let adjacency = manifold.knn_adjacency(2).expect("operation should succeed");
// Each point should be connected to its 2 nearest neighbors
// For 4 points in a line: [0,0], [1,0], [2,0], [3,0] with k=2
// Point 0 → neighbors 1,2
// Point 1 → neighbors 0,2
// Point 2 → neighbors 1,3
// Point 3 → neighbors 2,1
// This creates 10 total connections (5 unique edges × 2 for symmetry)
assert_eq!(adjacency.sum(), 10.0);
}
#[test]
fn test_type_conversion() {
let data = array![[1.0, 2.0], [3.0, 4.0]];
let euclidean_manifold = TypeSafeManifold::<
structure::Euclidean,
properties::NoCurvature,
dimension::Dim2,
>::new(data);
// Convert to Riemannian manifold
let riemannian_manifold = euclidean_manifold.cast_structure::<structure::Riemannian>();
assert_eq!(riemannian_manifold.n_points(), 2);
assert_eq!(riemannian_manifold.ambient_dim(), 2);
}
#[test]
fn test_validation() {
let data = array![[1.0, 2.0], [3.0, 4.0]];
let manifold = EuclideanManifold2D::new(data);
assert!(manifold.validate().is_ok());
}
#[test]
fn test_empty_manifold_validation() {
let data = Array2::zeros((0, 2));
let manifold = EuclideanManifold2D::new(data);
assert!(manifold.validate().is_err());
}
}