matten 0.13.2

A family car multidimensional array (tensor) library for small numerical trials / PoCs.
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
//! The primary public container, [`Tensor`].
//!
//! M2 adds the full creation and conversion surface from RFC-004: fill
//! constructors, `from_vec`, `into_vec`, `arange`/`try_arange`, and
//! `try_from_rows`. Arithmetic, reshape, and I/O arrive in later milestones.

use crate::convert::flatten_rectangular;
use crate::error::MattenError;
use crate::shape;
use std::fmt;

/// Maximum element count accepted by `arange` / `try_arange` before the
/// allocation limit fires. Set conservatively for Phase 1.
const ARANGE_MAX_ELEMENTS: usize = 1 << 20; // ~1 million (family-car budget: ~8 MiB)

/// A dense, row-major, owned multidimensional array of `f64`.
///
/// Fields are private. The storage layout is never exposed across the public
/// API. A scalar is shape `[]` with one element.
///
/// # Examples
///
/// ```
/// use matten::Tensor;
///
/// // 2×2 matrix
/// let m = Tensor::new(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
/// assert!(m.is_matrix());
///
/// // Fill constructors
/// let z = Tensor::zeros(&[3]);
/// assert_eq!(z.as_slice(), &[0.0, 0.0, 0.0]);
///
/// // Range constructor
/// let r = Tensor::arange(0.0, 5.0, 1.0);
/// assert_eq!(r.len(), 5);
/// ```
#[derive(Clone)]
pub struct Tensor {
    pub(crate) data: Vec<f64>,
    pub(crate) shape: Vec<usize>,
    /// Phase 2 dynamic storage; `None` for Phase 1 numeric tensors.
    #[cfg(feature = "dynamic")]
    pub(crate) dynamic: Option<Box<crate::dynamic::storage::DynamicTensor>>,
}

impl PartialEq for Tensor {
    fn eq(&self, other: &Self) -> bool {
        // Compare Phase 1 fields. Dynamic tensors with same shape and logical
        // data are equal; both dynamic fields must be None or produce the same
        // element sequence.
        if self.shape != other.shape {
            return false;
        }
        #[cfg(feature = "dynamic")]
        {
            match (&self.dynamic, &other.dynamic) {
                (Some(a), Some(b)) => return a.to_vec() == b.to_vec(),
                (None, None) => {}
                _ => return false,
            }
        }
        self.data == other.data
    }
}

// `is_empty` is absent for 0.1.0: zero-sized dims are rejected and a scalar
// has `len() == 1`, so it would always be false. Deferred to a future
// zero-sized-tensor RFC.
#[allow(clippy::len_without_is_empty)]
impl Tensor {
    // ------------------------------------------------------------------ //
    // Core constructors (also implemented in M1; repeated here for clarity)
    // ------------------------------------------------------------------ //

    /// Creates a tensor from row-major `data` and `shape`.
    ///
    /// Panics with an actionable message on any shape violation or data-length
    /// mismatch. Use [`try_new`](Tensor::try_new) for recoverable construction.
    ///
    /// # Panics
    ///
    /// Panics if the shape is invalid or `data.len()` does not equal the shape
    /// product.
    /// Panics with a clear `matten unsupported error` message if this tensor
    /// uses dynamic (`Element`) storage. Used to guard all Phase 1 numeric
    /// accessors and conversions.
    #[cfg(feature = "dynamic")]
    #[inline(always)]
    pub(crate) fn panic_if_dynamic(&self, operation: &'static str) {
        if self.is_dynamic() {
            panic!(
                "matten unsupported error in {operation}: this numeric API is not supported on dynamic tensors; use to_elements() or try_numeric() first"
            );
        }
    }

    #[must_use]
    pub fn new(data: Vec<f64>, shape: &[usize]) -> Tensor {
        Self::try_new(data, shape).unwrap_or_else(|e| panic!("{e}"))
    }

    /// Creates a tensor from row-major `data` and `shape`, returning an error
    /// instead of panicking.
    ///
    /// # Errors
    ///
    /// Returns [`MattenError::Shape`] for a length mismatch or invalid shape,
    /// or [`MattenError::Allocation`] on product overflow.
    pub fn try_new(data: Vec<f64>, shape: &[usize]) -> Result<Tensor, MattenError> {
        let expected = shape::validate_shape(shape, "try_new")?;
        if data.len() != expected {
            return Err(MattenError::Shape {
                operation: "try_new",
                message: format!(
                    "data length {} does not match shape {shape:?}, which requires {expected} elements",
                    data.len()
                ),
            });
        }
        Ok(Tensor {
            data,
            shape: shape.to_vec(),
            #[cfg(feature = "dynamic")]
            dynamic: None,
        })
    }

    /// Creates a rank-0 scalar tensor (shape `[]`, length `1`).
    ///
    /// ```
    /// use matten::Tensor;
    /// let s = Tensor::scalar(3.14);
    /// assert!(s.is_scalar());
    /// assert_eq!(s.len(), 1);
    /// ```
    #[must_use]
    pub fn scalar(value: f64) -> Tensor {
        // Shape `[]` is always valid: rank 0, no dims, product 1.
        Tensor {
            data: vec![value],
            shape: Vec::new(),
            #[cfg(feature = "dynamic")]
            dynamic: None,
        }
    }

    // ------------------------------------------------------------------ //
    // Fill constructors
    // ------------------------------------------------------------------ //

    /// Creates a tensor filled with `0.0`.
    ///
    /// # Panics
    ///
    /// Panics on an invalid shape (same rules as [`new`](Tensor::new)).
    ///
    /// ```
    /// use matten::Tensor;
    /// let z = Tensor::zeros(&[2, 3]);
    /// assert_eq!(z.shape(), &[2, 3]);
    /// assert_eq!(z.len(), 6);
    /// assert!(z.as_slice().iter().all(|&v| v == 0.0));
    /// ```
    #[must_use]
    pub fn zeros(shape: &[usize]) -> Tensor {
        let len = shape::validate_shape(shape, "zeros").unwrap_or_else(|e| panic!("{e}"));
        Tensor {
            data: vec![0.0; len],
            shape: shape.to_vec(),
            #[cfg(feature = "dynamic")]
            dynamic: None,
        }
    }

    /// Creates a tensor filled with `1.0`.
    ///
    /// # Panics
    ///
    /// Panics on an invalid shape.
    ///
    /// ```
    /// use matten::Tensor;
    /// let o = Tensor::ones(&[3]);
    /// assert!(o.as_slice().iter().all(|&v| v == 1.0));
    /// ```
    #[must_use]
    pub fn ones(shape: &[usize]) -> Tensor {
        let len = shape::validate_shape(shape, "ones").unwrap_or_else(|e| panic!("{e}"));
        Tensor {
            data: vec![1.0; len],
            shape: shape.to_vec(),
            #[cfg(feature = "dynamic")]
            dynamic: None,
        }
    }

    /// Creates a tensor filled with `value`.
    ///
    /// # Panics
    ///
    /// Panics on an invalid shape.
    ///
    /// ```
    /// use matten::Tensor;
    /// let t = Tensor::full(&[2, 2], 7.0);
    /// assert!(t.as_slice().iter().all(|&v| v == 7.0));
    /// ```
    #[must_use]
    pub fn full(shape: &[usize], value: f64) -> Tensor {
        let len = shape::validate_shape(shape, "full").unwrap_or_else(|e| panic!("{e}"));
        Tensor {
            data: vec![value; len],
            shape: shape.to_vec(),
            #[cfg(feature = "dynamic")]
            dynamic: None,
        }
    }

    /// Creates a 1-D tensor from a flat vector; shape is `[data.len()]`.
    ///
    /// # Panics
    ///
    /// Panics if `data` is empty (zero-sized dimension).
    ///
    /// ```
    /// use matten::Tensor;
    /// let t = Tensor::from_vec(vec![1.0, 2.0, 3.0]);
    /// assert_eq!(t.shape(), &[3]);
    /// ```
    #[must_use]
    pub fn from_vec(data: Vec<f64>) -> Tensor {
        let len = data.len();
        Tensor::new(data, &[len])
    }

    // ------------------------------------------------------------------ //
    // Range constructor
    // ------------------------------------------------------------------ //

    /// Creates a 1-D tensor with values `start, start + step, ...` (half-open,
    /// so `end` is excluded).
    ///
    /// This is a panic-zone convenience. Use [`try_arange`](Tensor::try_arange)
    /// when `start`/`end`/`step` come from user input.
    ///
    /// # Panics
    ///
    /// Panics if `step == 0.0`, any argument is non-finite, or the computed
    /// element count would exceed the allocation limit.
    ///
    /// ```
    /// use matten::Tensor;
    /// let r = Tensor::arange(0.0, 5.0, 1.0);
    /// assert_eq!(r.as_slice(), &[0.0, 1.0, 2.0, 3.0, 4.0]);
    ///
    /// let r2 = Tensor::arange(1.0, 0.0, -0.5);
    /// assert_eq!(r2.as_slice(), &[1.0, 0.5]);
    /// ```
    #[must_use]
    pub fn arange(start: f64, end: f64, step: f64) -> Tensor {
        arange_impl(start, end, step, "arange").unwrap_or_else(|e| panic!("{e}"))
    }

    /// Creates a 1-D tensor with values `start, start + step, ...` (half-open),
    /// returning an error instead of panicking.
    ///
    /// # Errors
    ///
    /// Returns [`MattenError::Shape`] for a zero or non-finite step/bound, or
    /// [`MattenError::Allocation`] if the computed element count exceeds the
    /// allocation limit.
    pub fn try_arange(start: f64, end: f64, step: f64) -> Result<Tensor, MattenError> {
        arange_impl(start, end, step, "try_arange")
    }

    // ------------------------------------------------------------------ //
    // Nested-row construction
    // ------------------------------------------------------------------ //

    /// Creates a 2-D tensor from rectangular row data; shape is `[rows, cols]`.
    ///
    /// This is the recoverable version of [`From<Vec<Vec<f64>>>`].
    ///
    /// # Errors
    ///
    /// Returns [`MattenError::Shape`] on an empty outer vector, any zero-length
    /// row, or ragged rows.
    pub fn try_from_rows(rows: Vec<Vec<f64>>) -> Result<Tensor, MattenError> {
        let (data, shape) = flatten_rectangular(rows, "try_from_rows")?;
        Ok(Tensor {
            data,
            shape,
            #[cfg(feature = "dynamic")]
            dynamic: None,
        })
    }

    // ------------------------------------------------------------------ //
    // Observational API (also M1; listed here for doc completeness)
    // ------------------------------------------------------------------ //

    /// The shape as a slice of dimension lengths. Non-allocating.
    #[must_use]
    pub fn shape(&self) -> &[usize] {
        &self.shape
    }

    /// The rank (number of dimensions): `shape().len()`.
    #[must_use]
    pub fn ndim(&self) -> usize {
        self.shape.len()
    }

    /// The logical element count: the product of the shape.
    #[must_use]
    pub fn len(&self) -> usize {
        #[cfg(feature = "dynamic")]
        if let Some(dyn_t) = &self.dynamic {
            return dyn_t.len;
        }
        self.data.len()
    }

    /// Returns `true` for a rank-0 scalar tensor (shape `[]`).
    #[must_use]
    pub fn is_scalar(&self) -> bool {
        self.ndim() == 0
    }

    /// Returns `true` for a rank-1 tensor.
    #[must_use]
    pub fn is_vector(&self) -> bool {
        self.ndim() == 1
    }

    /// Returns `true` for a rank-2 tensor.
    #[must_use]
    pub fn is_matrix(&self) -> bool {
        self.ndim() == 2
    }

    /// The flat, row-major data as a slice.
    #[must_use]
    pub fn as_slice(&self) -> &[f64] {
        #[cfg(feature = "dynamic")]
        self.panic_if_dynamic("as_slice");
        &self.data
    }

    /// Returns an owned copy of the flat, row-major data.
    #[must_use]
    pub fn to_vec(&self) -> Vec<f64> {
        #[cfg(feature = "dynamic")]
        self.panic_if_dynamic("to_vec");
        self.data.clone()
    }

    /// Consumes the tensor and returns the flat, row-major data. No copy.
    #[must_use]
    pub fn into_vec(self) -> Vec<f64> {
        #[cfg(feature = "dynamic")]
        self.panic_if_dynamic("into_vec");
        self.data
    }
}

impl fmt::Debug for Tensor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        const MAX: usize = 8;
        #[cfg(feature = "dynamic")]
        if let Some(dyn_t) = &self.dynamic {
            write!(f, "Tensor(shape={:?}, dynamic=[", self.shape)?;
            for i in 0..dyn_t.len.min(MAX) {
                if i > 0 {
                    f.write_str(", ")?;
                }
                if let Some(e) = dyn_t.get_flat(i) {
                    write!(f, "{e:?}")?;
                }
            }
            if dyn_t.len > MAX {
                write!(f, ", ... ({} more)", dyn_t.len - MAX)?;
            }
            return f.write_str("])");
        }
        write!(f, "Tensor(shape={:?}, data=[", self.shape)?;
        for (i, v) in self.data.iter().take(MAX).enumerate() {
            if i > 0 {
                f.write_str(", ")?;
            }
            write!(f, "{v:?}")?;
        }
        if self.data.len() > MAX {
            write!(f, ", ... ({} more)", self.data.len() - MAX)?;
        }
        f.write_str("])")
    }
}

// ---- arange shared implementation ------------------------------------

/// Shared implementation for both `arange` and `try_arange`.
fn arange_impl(
    start: f64,
    end: f64,
    step: f64,
    operation: &'static str,
) -> Result<Tensor, MattenError> {
    // Argument validation (Result zone, so return Err rather than panic).
    if !start.is_finite() || !end.is_finite() {
        return Err(MattenError::Shape {
            operation,
            message: format!("start and end must be finite (got start={start}, end={end})"),
        });
    }
    if step == 0.0 || !step.is_finite() {
        return Err(MattenError::Shape {
            operation,
            message: format!("step must be a non-zero finite value (got {step})"),
        });
    }

    // Compute element count without allocating. The estimate is conservative:
    // we use integer ceiling so floating-point accumulation never drops a value
    // that should be included.
    let raw_count = ((end - start) / step).ceil();
    let count: usize = if raw_count <= 0.0 {
        0
    } else if raw_count > ARANGE_MAX_ELEMENTS as f64 {
        return Err(MattenError::Allocation {
            requested_elements: raw_count as usize,
            message: format!(
                "arange would produce ~{} elements, exceeding the limit of {}",
                raw_count as usize, ARANGE_MAX_ELEMENTS
            ),
        });
    } else {
        raw_count as usize
    };

    // Build the data vector by accumulation. Recompute to avoid drift near
    // `end`, but exclude values that have genuinely crossed `end`.
    let mut data = Vec::with_capacity(count);
    let mut i: usize = 0;
    loop {
        let v = start + step * i as f64;
        // Half-open: stop when we cross `end` in the direction of `step`.
        if (step > 0.0 && v >= end) || (step < 0.0 && v <= end) {
            break;
        }
        data.push(v);
        i += 1;
        // Guard against the estimate being too small (floating-point edge).
        if i > ARANGE_MAX_ELEMENTS {
            return Err(MattenError::Allocation {
                requested_elements: i,
                message: format!("arange exceeded the element limit of {ARANGE_MAX_ELEMENTS}"),
            });
        }
    }

    let len = data.len();
    // A zero-element range is an edge case we permit as an empty 1-D tensor
    // shape would be [0], which the shape module rejects. Return an error
    // so the user knows to adjust their range arguments.
    if len == 0 {
        return Err(MattenError::Shape {
            operation,
            message: format!("arange(start={start}, end={end}, step={step}) produces no elements"),
        });
    }

    Ok(Tensor {
        data,
        shape: vec![len],
        #[cfg(feature = "dynamic")]
        dynamic: None,
    })
}

impl Tensor {
    // ---- Shape operations (M4 / RFC-007) ------------------------------------

    /// Reshapes the tensor to `new_shape`, returning a new owned tensor.
    ///
    /// The total element count must be unchanged. Data order is preserved
    /// (row-major flat order).
    ///
    /// # Panics
    ///
    /// Panics on element-count mismatch or invalid shape. Use
    /// [`try_reshape`](Tensor::try_reshape) for recoverable construction.
    ///
    /// ```
    /// use matten::Tensor;
    /// let t = Tensor::new(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
    /// let flat = t.reshape(&[4]);
    /// assert_eq!(flat.shape(), &[4]);
    /// assert_eq!(flat.as_slice(), &[1.0, 2.0, 3.0, 4.0]);
    /// ```
    #[must_use]
    pub fn reshape(&self, new_shape: &[usize]) -> Tensor {
        crate::reshape::try_reshape_impl(self, new_shape).unwrap_or_else(|e| panic!("{e}"))
    }

    /// Reshapes the tensor, returning an error instead of panicking.
    ///
    /// # Errors
    ///
    /// Returns [`MattenError::Shape`] on element-count mismatch or invalid shape.
    pub fn try_reshape(&self, new_shape: &[usize]) -> Result<Tensor, MattenError> {
        crate::reshape::try_reshape_impl(self, new_shape)
    }

    /// Flattens the tensor to a 1-D tensor, preserving row-major order.
    ///
    /// A scalar (shape `[]`) is returned as shape `[1]`.
    ///
    /// ```
    /// use matten::Tensor;
    /// let t = Tensor::new(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
    /// let flat = t.flatten();
    /// assert_eq!(flat.shape(), &[4]);
    /// ```
    #[must_use]
    pub fn flatten(&self) -> Tensor {
        #[cfg(feature = "dynamic")]
        if self.is_dynamic() {
            panic!(
                "matten unsupported error in flatten: dynamic tensors do not support flatten; call try_numeric() first to convert to a numeric tensor"
            );
        }
        let len = self.data.len();
        Tensor {
            data: self.data.clone(),
            shape: vec![len],
            #[cfg(feature = "dynamic")]
            dynamic: None,
        }
    }

    /// Transposes the tensor by reversing the axis order.
    ///
    /// For a rank-2 tensor this swaps rows and columns. For rank > 2 the axis
    /// order is reversed: `[d0, d1, d2] → [d2, d1, d0]`.
    ///
    /// # Panics
    ///
    /// Panics for a rank-0 scalar (no axes to transpose).
    ///
    /// ```
    /// use matten::Tensor;
    /// let m = Tensor::new(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
    /// let mt = m.transpose();
    /// assert_eq!(mt.shape(), &[3, 2]);
    /// assert_eq!(mt.as_slice(), &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);
    /// ```
    #[must_use]
    pub fn transpose(&self) -> Tensor {
        let ndim = self.ndim();
        if ndim == 0 {
            panic!("matten shape error in transpose: cannot transpose a scalar (rank 0)");
        }
        let perm: Vec<usize> = (0..ndim).rev().collect();
        crate::reshape::permute_axes(self, &perm)
    }

    /// Alias for [`transpose`](Tensor::transpose).
    #[must_use]
    pub fn t(&self) -> Tensor {
        self.transpose()
    }

    /// Returns a new tensor with `axis1` and `axis2` swapped.
    ///
    /// # Panics
    ///
    /// Panics if either axis is out of range.
    ///
    /// ```
    /// use matten::Tensor;
    /// let t = Tensor::new((1..=24).map(|x| x as f64).collect(), &[2, 3, 4]);
    /// let s = t.swap_axes(0, 2);
    /// assert_eq!(s.shape(), &[4, 3, 2]);
    /// ```
    #[must_use]
    pub fn swap_axes(&self, axis1: usize, axis2: usize) -> Tensor {
        crate::reshape::validate_axes(axis1, axis2, self.ndim(), "swap_axes")
            .unwrap_or_else(|e| panic!("{e}"));
        let mut perm: Vec<usize> = (0..self.ndim()).collect();
        perm.swap(axis1, axis2);
        crate::reshape::permute_axes(self, &perm)
    }

    /// Returns the element at the multidimensional `coord`, or `None` if the
    /// coordinate rank doesn't match or any component is out of bounds.
    ///
    /// ```
    /// use matten::Tensor;
    /// let t = Tensor::new(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
    /// assert_eq!(t.get(&[0, 1]), Some(2.0));
    /// assert_eq!(t.get(&[5, 0]), None);
    /// ```
    pub fn get(&self, coord: &[usize]) -> Option<f64> {
        #[cfg(feature = "dynamic")]
        self.panic_if_dynamic("get");
        let flat = crate::shape::coord_to_flat(coord, &self.shape)?;
        self.data.get(flat).copied()
    }

    /// Returns the element at flat row-major `index`, or `None` if out of bounds.
    ///
    /// This is the flat-index companion to [`get`](Tensor::get). The index
    /// follows the same row-major layout as [`as_slice`](Tensor::as_slice).
    ///
    /// ```
    /// use matten::Tensor;
    /// let t = Tensor::new(vec![1.0, 2.0, 3.0, 4.0], &[2, 2]);
    /// assert_eq!(t.get_flat(1), Some(2.0));
    /// assert_eq!(t.get_flat(10), None);
    /// ```
    pub fn get_flat(&self, index: usize) -> Option<f64> {
        #[cfg(feature = "dynamic")]
        self.panic_if_dynamic("get_flat");
        self.data.get(index).copied()
    }

    // ---- Slicing (M4 / RFC-008) ---------------------------------------------

    /// Starts a slice builder for this tensor. The builder is the canonical
    /// slicing API; [`slice_str`](Tensor::slice_str) is a convenience wrapper.
    ///
    /// ```
    /// use matten::Tensor;
    /// let t = Tensor::new(vec![1.0,2.0,3.0,4.0,5.0,6.0], &[2, 3]);
    /// let row = t.slice().index(0).all().build().unwrap();
    /// assert_eq!(row.as_slice(), &[1.0, 2.0, 3.0]);
    /// ```
    pub fn slice(&self) -> crate::slice::SliceBuilder<'_> {
        crate::slice::SliceBuilder::new(self)
    }

    /// Slices this tensor using a NumPy-like string specification.
    ///
    /// This is a convenience wrapper over the builder API. It always returns
    /// `Result` and never panics on malformed input.
    ///
    /// # Errors
    ///
    /// Returns [`MattenError::Slice`] for any parse or bounds error.
    ///
    /// ```
    /// use matten::Tensor;
    /// let t = Tensor::new(vec![1.0,2.0,3.0,4.0,5.0,6.0], &[2, 3]);
    /// let top = t.slice_str("0, :").unwrap();
    /// assert_eq!(top.as_slice(), &[1.0, 2.0, 3.0]);
    /// ```
    pub fn slice_str(&self, spec: &str) -> Result<Tensor, MattenError> {
        let specs = crate::slice::parse_slice_str(spec)?;
        crate::slice::execute_slice(self, &specs, "slice_str")
    }
}

// ---- Boundary integration (M5 / RFC-009) --------------------------------

impl Tensor {
    /// Parses a JSON string into a `Tensor`.
    ///
    /// Accepts the canonical `{"shape":[…],"data":[…]}` object form and the
    /// convenience nested-array form (rank 1 and 2). Returns
    /// [`MattenError::Parse`] for any error; never panics.
    ///
    /// ```
    /// use matten::Tensor;
    ///
    /// // Canonical object form
    /// let t = Tensor::from_json(r#"{"shape":[2,2],"data":[1.0,2.0,3.0,4.0]}"#).unwrap();
    /// assert_eq!(t.shape(), &[2, 2]);
    ///
    /// // Nested-array convenience form
    /// let t = Tensor::from_json("[[1.0,2.0],[3.0,4.0]]").unwrap();
    /// assert_eq!(t.shape(), &[2, 2]);
    /// ```
    #[cfg(feature = "json")]
    pub fn from_json(input: &str) -> Result<Tensor, MattenError> {
        crate::parse::json::from_json_str(input)
    }

    /// Parses a CSV string into a `Tensor` with shape `[rows, cols]`.
    ///
    /// All fields must be valid `f64` values. Returns [`MattenError::Parse`]
    /// for ragged rows or non-numeric fields; never panics.
    ///
    /// ```
    /// use matten::Tensor;
    ///
    /// let t = Tensor::from_csv("1.0,2.0\n3.0,4.0\n").unwrap();
    /// assert_eq!(t.shape(), &[2, 2]);
    /// assert_eq!(t.as_slice(), &[1.0, 2.0, 3.0, 4.0]);
    /// ```
    #[cfg(feature = "csv")]
    pub fn from_csv(input: &str) -> Result<Tensor, MattenError> {
        crate::parse::csv::from_csv_str(input)
    }

    /// Loads and parses a JSON file into a `Tensor`.
    ///
    /// Returns [`MattenError::Io`] for file errors, [`MattenError::Parse`] for
    /// parse errors.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read or the content is invalid.
    #[cfg(feature = "json")]
    pub fn load_json(path: impl AsRef<std::path::Path>) -> Result<Tensor, MattenError> {
        let path = path.as_ref();
        let content = std::fs::read_to_string(path).map_err(|e| MattenError::Io {
            path: path.to_path_buf(),
            source: e,
        })?;
        crate::parse::json::from_json_str(&content)
    }

    /// Loads and parses a CSV file into a `Tensor` with shape `[rows, cols]`.
    ///
    /// Returns [`MattenError::Io`] for file errors, [`MattenError::Parse`] for
    /// parse errors.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read or the content is invalid.
    #[cfg(feature = "csv")]
    pub fn load_csv(path: impl AsRef<std::path::Path>) -> Result<Tensor, MattenError> {
        let path = path.as_ref();
        let content = std::fs::read_to_string(path).map_err(|e| MattenError::Io {
            path: path.to_path_buf(),
            source: e,
        })?;
        crate::parse::csv::from_csv_str(&content)
    }
}