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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
//! Public `Array`-level wrappers for the kernels in this folder, re-exported from the crate root.
//!
//! Signature conventions (same as `np::unique(&a)` and `np::linalg::outer(&a, &b)` in API.md): the
//! main array arguments are `&Array<T>`, not `impl IntoArray<T>`, so the element type is always
//! inferred without turbofish. Output is `Array<f64>` for the statistics functions (NumPy returns
//! float64 for integer input); `T` is preserved for `convolve`, `correlate`, `diff`, `cross`,
//! `kron`, `einsum`, the set functions, and for `gradient` / `trapezoid` (floats only).
use ;
use normalize_axis;
use set_kernels as setk;
use ;
use ;
use crate::;
// ------------------------------------------------------------------ small public types
/// Output size of [`convolve`] and [`correlate`], like NumPy's `mode="full" | "same" | "valid"`.
///
/// ```
/// use rustnum as np;
/// let a = np::array![1.0, 2.0, 3.0];
/// let v = np::array![1.0, 1.0];
/// assert_eq!(np::convolve(&a, &v, np::ConvolveMode::Full).to_vec(), vec![1.0, 3.0, 5.0, 3.0]);
/// assert_eq!(np::convolve(&a, &v, np::ConvolveMode::Valid).to_vec(), vec![3.0, 5.0]);
/// assert_eq!(np::ConvolveMode::default(), np::ConvolveMode::Full);
/// ```
/// The `bins` argument of [`histogram`]: a number of equal-width bins or explicit bin edges.
///
/// Convert with `.into()`: `10usize`, `vec![0.0, 1.0, 5.0]` and `&Array<f64>` all work.
/// (NumPy's string rules such as `"auto"` are not supported.)
///
/// ```
/// use rustnum as np;
/// assert_eq!(np::Bins::from(4usize), np::Bins::Count(4));
/// assert_eq!(np::Bins::from(vec![0.0, 1.0]), np::Bins::Edges(vec![0.0, 1.0]));
/// ```
/// Sample spacing for [`gradient_axis`] and [`trapezoid`]: a constant step or the sample coordinates.
///
/// Convert with `.into()`: `0.5f64`, `vec![0.0, 1.0, 3.0]` and `&Array<f64>` all work.
///
/// ```
/// use rustnum as np;
/// assert_eq!(np::Spacing::from(0.5), np::Spacing::Uniform(0.5));
/// assert_eq!(np::Spacing::from(vec![0.0, 1.0]), np::Spacing::Coords(vec![0.0, 1.0]));
/// ```
// ------------------------------------------------------------------ private helpers
/// Shape of an axis-reduction result: `shape` without `axis`.
/// Variables x observations split of an array for `cov` / `corrcoef`.
// ------------------------------------------------------------------ statistics
/// Covariance matrix of the rows of `m`, like `np.cov(m, bias=bias, ddof=ddof)`.
///
/// Each row of a 2-d `m` is a variable and each column an observation; the result is
/// `[nvars, nvars]`. A 1-d `m` is one variable and gives a 0-d result. `ddof` defaults to 1
/// (0 when `bias` is true); an explicit `ddof` wins over `bias`. NumPy's `y`, `rowvar`,
/// `fweights` and `aweights` arguments are not supported (stack `y` with `vstack`, transpose
/// for `rowvar=False`).
///
/// ```
/// use rustnum as np;
/// let m = np::array![[0.0, 1.0, 2.0], [2.0, 1.0, 0.0]];
/// let c = np::cov(&m, false, None);
/// assert!(c.allclose(&np::array![[1.0, -1.0], [-1.0, 1.0]], 1e-12, 1e-12));
/// ```
/// Pearson correlation matrix of the rows of `x`, like `np.corrcoef(x)`.
///
/// Same layout as [`cov`]; entries are clipped to `[-1, 1]`. A constant row gives NaN. A 1-d
/// input gives a 0-d result.
///
/// ```
/// use rustnum as np;
/// let x = np::array![[0.0, 1.0, 2.0], [2.0, 1.0, 0.0]];
/// let r = np::corrcoef(&x);
/// assert!(r.allclose(&np::array![[1.0, -1.0], [-1.0, 1.0]], 1e-12, 1e-12));
/// ```
/// Histogram of the flattened data, like `np.histogram(a, bins, range, density, weights)`.
///
/// Returns `(counts, bin_edges)`. The last bin is closed on the right, all others are half
/// open; NaN and out-of-range values are ignored. Differences from NumPy: counts are `f64`
/// (integer valued when unweighted) and the string bin rules are not supported.
///
/// ```
/// use rustnum as np;
/// let a = np::array![1.0, 2.0, 1.0];
/// let (counts, edges) = np::histogram(&a, vec![0.0, 1.0, 2.0, 3.0], None, false, None);
/// assert_eq!(counts.to_vec(), vec![0.0, 2.0, 1.0]);
/// assert_eq!(edges.to_vec(), vec![0.0, 1.0, 2.0, 3.0]);
/// // two equal-width bins over the data range, as a density
/// let (counts, _) = np::histogram(&a, 2usize, None, true, None);
/// assert_eq!(counts.to_vec(), vec![1.3333333333333333, 0.6666666666666666]);
/// ```
/// Bin edges that [`histogram`] would use, like `np.histogram_bin_edges(a, bins, range)`.
///
/// ```
/// use rustnum as np;
/// let a = np::array![0.0, 4.0];
/// assert_eq!(np::histogram_bin_edges(&a, 2usize, None).to_vec(), vec![0.0, 2.0, 4.0]);
/// ```
/// Count occurrences of each non-negative integer, like `np.bincount(x, weights, minlength)`.
///
/// The result has length `max(x) + 1` (at least `minlength`). With `weights` each occurrence adds
/// its weight instead of 1. Difference from NumPy: the result is always `f64`
/// (use `.astype::<usize>()` for integer counts). Panics on negative values.
///
/// ```
/// use rustnum as np;
/// let x = np::array![0i64, 1, 1, 3];
/// assert_eq!(np::bincount(&x, None, 0).to_vec(), vec![1.0, 2.0, 0.0, 1.0]);
/// let w = np::array![0.5, 1.0, 2.0, 1.0];
/// assert_eq!(np::bincount(&x, Some(&w), 5).to_vec(), vec![0.5, 3.0, 0.0, 1.0, 0.0]);
/// ```
/// Index of the bin each value falls into, like `np.digitize(x, bins, right)`.
///
/// `bins` must be monotonic. With increasing bins and `right == false`, `i` satisfies
/// `bins[i-1] <= x < bins[i]`; with `right == true`, `bins[i-1] < x <= bins[i]`. Values below
/// the first bin give 0, above the last give `bins.len()`; NaN gives `bins.len()`.
/// The output has the shape of `x`.
///
/// ```
/// use rustnum as np;
/// let x = np::array![0.2, 6.4, 3.0, 1.6];
/// let bins = np::array![0.0, 1.0, 2.5, 4.0, 10.0];
/// assert_eq!(np::digitize(&x, &bins, false).to_vec(), vec![1, 4, 3, 2]);
/// ```
/// Weighted mean of all elements, like `np.average(a, weights=weights)`.
///
/// `weights` must have the same size as `a`; they need not be normalised. Panics if the weights
/// sum to zero. Without weights this is the plain mean.
///
/// ```
/// use rustnum as np;
/// let a = np::array![1.0, 2.0, 3.0, 4.0];
/// let w = np::array![4.0, 3.0, 2.0, 1.0];
/// assert_eq!(np::average(&a, Some(&w)), 2.0);
/// ```
/// Weighted mean along an axis, like `np.average(a, axis=axis, weights=weights)`.
///
/// `weights` is either the shape of `a` or 1-d with length `a.shape()[axis]`.
///
/// ```
/// use rustnum as np;
/// let a = np::array![[1.0, 2.0], [3.0, 4.0]];
/// let w = np::array![1.0, 3.0];
/// assert_eq!(np::average_axis(&a, Some(&w), 0).to_vec(), vec![2.5, 3.5]);
/// ```
/// The `q`-th quantile of all elements (linear interpolation), like `np.quantile(a, q)`.
///
/// `q` is in `[0, 1]` (panics otherwise). NaN in `a` gives NaN. For several quantiles call it
/// once per `q` (NumPy's array-valued `q` and the other interpolation methods are not supported).
///
/// ```
/// use rustnum as np;
/// let a = np::array![1.0, 2.0, 3.0, 4.0];
/// assert_eq!(np::quantile(&a, 0.5), 2.5);
/// assert_eq!(np::quantile(&a, 0.0), 1.0);
/// ```
/// Quantile along an axis, like `np.quantile(a, q, axis=axis)`.
///
/// ```
/// use rustnum as np;
/// let a = np::array![[1.0, 2.0], [3.0, 4.0]];
/// assert_eq!(np::quantile_axis(&a, 0.5, 0).to_vec(), vec![2.0, 3.0]);
/// ```
/// Quantile ignoring NaNs, like `np.nanquantile(a, q)`.
///
/// All-NaN or empty input gives NaN.
///
/// ```
/// use rustnum as np;
/// let a = np::array![1.0, f64::NAN, 3.0];
/// assert_eq!(np::nanquantile(&a, 0.5), 2.0);
/// ```
/// NaN-ignoring quantile along an axis, like `np.nanquantile(a, q, axis=axis)`.
///
/// ```
/// use rustnum as np;
/// let a = np::array![[1.0, f64::NAN], [3.0, 4.0]];
/// assert_eq!(np::nanquantile_axis(&a, 0.5, 0).to_vec(), vec![2.0, 4.0]);
/// ```
// ------------------------------------------------------------------ signal / numeric
/// Discrete linear convolution of two 1-d arrays, like `np.convolve(a, v, mode)`.
///
/// If `v` is longer than `a` the two are swapped first, exactly as NumPy does (the result is
/// symmetric in the arguments anyway). Panics if either input is empty.
///
/// ```
/// use rustnum as np;
/// let a = np::array![1.0, 2.0, 3.0];
/// let v = np::array![0.0, 1.0, 0.5];
/// assert_eq!(np::convolve(&a, &v, np::ConvolveMode::Full).to_vec(), vec![0.0, 1.0, 2.5, 4.0, 1.5]);
/// assert_eq!(np::convolve(&a, &v, np::ConvolveMode::Same).to_vec(), vec![1.0, 2.5, 4.0]);
/// assert_eq!(np::convolve(&a, &v, np::ConvolveMode::Valid).to_vec(), vec![2.5]);
/// ```
/// Cross-correlation of two 1-d arrays, like `np.correlate(a, v, mode)`.
///
/// `c[k] = sum_n a[n + k] * v[n]` (real input, so no conjugation). If `v` is longer than `a` the
/// arguments are swapped and the result reversed, as in NumPy. Note that NumPy's default mode here
/// is `"valid"`; this function has no default, pass the mode explicitly.
///
/// ```
/// use rustnum as np;
/// let a = np::array![1.0, 2.0, 3.0];
/// let v = np::array![0.0, 1.0, 0.5];
/// assert_eq!(np::correlate(&a, &v, np::ConvolveMode::Full).to_vec(), vec![0.5, 2.0, 3.5, 3.0, 0.0]);
/// ```
/// The `n`-th discrete difference along `axis`, like `np.diff(a, n, axis)`.
///
/// The axis shrinks by `n` (to length 0 if `n` is larger). `n == 0` returns a copy.
/// `prepend` / `append` are not supported. Unsigned element types panic on underflow in debug builds
/// (NumPy wraps), so convert with `astype` first.
///
/// ```
/// use rustnum as np;
/// let a = np::array![1i64, 4, 9, 16];
/// assert_eq!(np::diff(&a, 1, -1).to_vec(), vec![3, 5, 7]);
/// assert_eq!(np::diff(&a, 2, -1).to_vec(), vec![2, 2]);
/// ```
/// Numerical gradient along every axis with constant spacing `dx`, like `np.gradient(f, dx)`.
///
/// Interior points use second-order central differences, the two ends first-order one-sided
/// differences. Returns one array per axis (a one-element `Vec` for 1-d input, where NumPy returns
/// the array itself). Needs at least 2 samples along every axis.
///
/// ```
/// use rustnum as np;
/// let f = np::array![1.0, 2.0, 4.0, 7.0, 11.0, 16.0];
/// let g = np::gradient(&f, 1.0);
/// assert_eq!(g[0].to_vec(), vec![1.0, 1.5, 2.5, 3.5, 4.5, 5.0]);
/// ```
/// Gradient along one axis, like `np.gradient(f, spacing, axis=axis, edge_order=edge_order)`.
///
/// `spacing` is a constant step or the sample coordinates (`0.5f64`, `vec![0.0, 1.0, 3.0]`,
/// `&coords`). `edge_order` is 1 or 2 (order of the one-sided differences at the ends; 2 needs
/// at least 3 samples).
///
/// ```
/// use rustnum as np;
/// let f = np::array![1.0, 2.0, 4.0, 8.0];
/// let g = np::gradient_axis(&f, vec![0.0, 1.0, 3.0, 7.0], 0, 1);
/// assert_eq!(g.to_vec(), vec![1.0, 1.0, 1.0, 1.0]);
/// let g2 = np::gradient_axis(&f, 1.0, 0, 2);
/// assert_eq!(g2.to_vec(), vec![0.5, 1.5, 3.0, 5.0]);
/// ```
/// One-dimensional piecewise-linear interpolation, like `np.interp(x, xp, fp, left, right)`.
///
/// `xp` must be increasing (not checked). Values of `x` below `xp[0]` give `left` and above
/// `xp[last]` give `right`; both default to `fp[0]` and `fp[last]`. NaN in `x` gives NaN. The
/// `period` argument is not supported. The output has the shape of `x`.
///
/// ```
/// use rustnum as np;
/// let xp = np::array![1.0, 2.0, 3.0];
/// let fp = np::array![3.0, 2.0, 0.0];
/// let x = np::array![0.0, 1.5, 3.2];
/// assert_eq!(np::interp(&x, &xp, &fp, None, None).to_vec(), vec![3.0, 2.5, 0.0]);
/// assert_eq!(np::interp(&x, &xp, &fp, Some(-1.0), Some(9.0)).to_vec(), vec![-1.0, 2.5, 9.0]);
/// ```
/// Integrate with the trapezoidal rule along `axis`, like `np.trapezoid(y, x_or_dx, axis=axis)`.
///
/// `spacing` is a constant `dx` or the sample coordinates `x` (length `y.shape()[axis]`). The
/// result has `axis` removed (a 0-d array for 1-d `y`; use `.item()`). Fewer than 2 samples gives 0.
///
/// ```
/// use rustnum as np;
/// let y = np::array![1.0, 2.0, 3.0];
/// assert_eq!(np::trapezoid(&y, 1.0, -1).item(), 4.0);
/// assert_eq!(np::trapezoid(&y, vec![0.0, 1.0, 3.0], -1).item(), 6.5);
/// ```
/// Cross product of 3-vectors (or 2-vectors) along the last axis, like `np.cross(a, b)`.
///
/// The last axis of each input has length 2 or 3; leading axes broadcast. A 2-vector is a
/// 3-vector with `z = 0`. Two 2-vectors give only the z component, so the last axis disappears
/// (a 0-d result for two plain 2-vectors). `axisa`, `axisb`, `axisc` are not supported.
///
/// ```
/// use rustnum as np;
/// let a = np::array![1, 2, 3];
/// let b = np::array![4, 5, 6];
/// assert_eq!(np::cross(&a, &b).to_vec(), vec![-3, 6, -3]);
/// ```
/// Kronecker product, like `np.kron(a, b)`.
///
/// The result has shape `a.shape()[i] * b.shape()[i]` per axis; the array with fewer dimensions
/// gets leading axes of length 1.
///
/// ```
/// use rustnum as np;
/// let a = np::array![1, 10, 100];
/// let b = np::array![5, 6, 7];
/// assert_eq!(np::kron(&a, &b).to_vec(), vec![5, 6, 7, 50, 60, 70, 500, 600, 700]);
/// ```
// ------------------------------------------------------------------ sets
/// Sorted values present in both arrays, like `np.intersect1d(a, b)`.
///
/// Inputs are flattened; the result is 1-d, sorted and without duplicates. NaN is never in the
/// intersection (NaN != NaN). `return_indices` is not supported.
///
/// ```
/// use rustnum as np;
/// let a = np::array![1, 3, 4, 3];
/// let b = np::array![3, 1, 2, 1];
/// assert_eq!(np::intersect1d(&a, &b).to_vec(), vec![1, 3]);
/// ```
/// Sorted distinct values present in either array, like `np.union1d(a, b)`.
///
/// ```
/// use rustnum as np;
/// let a = np::array![-1, 0];
/// let b = np::array![-2, 0, 2];
/// assert_eq!(np::union1d(&a, &b).to_vec(), vec![-2, -1, 0, 2]);
/// ```
/// Sorted distinct values of `a` that are not in `b`, like `np.setdiff1d(a, b)`.
///
/// ```
/// use rustnum as np;
/// let a = np::array![1, 2, 3, 2, 4, 1];
/// let b = np::array![3, 4, 5, 6];
/// assert_eq!(np::setdiff1d(&a, &b).to_vec(), vec![1, 2]);
/// ```
/// Sorted values that are in exactly one of the arrays, like `np.setxor1d(a, b)`.
///
/// ```
/// use rustnum as np;
/// let a = np::array![1, 2, 3, 2, 4];
/// let b = np::array![2, 3, 5, 7, 5];
/// assert_eq!(np::setxor1d(&a, &b).to_vec(), vec![1, 4, 5, 7]);
/// ```
/// Membership test, like `np.isin(element, test_elements)`.
///
/// The result has the shape of `element`. NaN is never found (NaN != NaN).
///
/// ```
/// use rustnum as np;
/// let element = np::array![[1, 2], [3, 4]];
/// let test = np::array![1, 3];
/// assert_eq!(np::isin(&element, &test).to_vec(), vec![true, false, true, false]);
/// ```
// ------------------------------------------------------------------ einsum
/// Einstein summation, like `np.einsum(subscripts, *operands)`.
///
/// Supports explicit (`"ij,jk->ik"`) and implicit (`"ij,jk"`) output, summed labels
/// (`"i,i->"`), repeated labels in one operand for diagonals and traces (`"ii->i"`, `"ii"`),
/// any number of operands, size-1 broadcasting, spaces, and `...` ellipsis (right-aligned and
/// broadcast like NumPy). Panics with NumPy's messages on malformed subscripts or mismatched
/// sizes. Not supported: `optimize=`, `out=`, the sublist calling form. Cost is the product of
/// all label sizes (no contraction-order optimisation).
///
/// ```
/// use rustnum as np;
/// let a = np::array![[1, 2], [3, 4]];
/// let b = np::array![[5, 6], [7, 8]];
/// assert_eq!(np::einsum("ij,jk->ik", &[&a, &b]).to_vec(), vec![19, 22, 43, 50]);
/// assert_eq!(np::einsum("ii", &[&a]).item(), 5); // trace
/// assert_eq!(np::einsum("ij->ji", &[&a]).to_vec(), vec![1, 3, 2, 4]);
/// ```