Repository navigation
Expand file tree
/
Copy path_base.py
More file actions
1766 lines (1409 loc) · 54.8 KB
/
Copy path_base.py
File metadata and controls
1766 lines (1409 loc) · 54.8 KB
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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# ----------------------------------------------------------------------------
from __future__ import annotations
from sys import modules
from warnings import warn
from typing import Any, TYPE_CHECKING
import numpy as np
from skbio.util._decorator import (
aliased,
register_aliases,
params_aliased,
array_api_doc,
)
from skbio.util._array import ingest_array
if TYPE_CHECKING: # pragma: no cover
from types import ModuleType
from skbio.util._typing import ArrayLike, StdArray
def _check_composition(
xp: ModuleType,
mat: StdArray,
axis: int = -1,
nozero: bool = False,
maxdim: int | None = None,
allnum: bool = True,
):
r"""Check if the input matrix contain valid compositions.
Parameters
----------
xp : namespace
The array API compatible namespace corresponding ``mat``.
mat : array of shape (..., n_components, ...)
A matrix of proportions.
axis : int, optional
Axis that represents each composition. Default is the last axis (-1).
nozero : bool, optional
If True, matrix must contain only positive values.
maxdim : int, optional
Maximum number of dimensions allowed. Default is None.
allnum : bool, optional
If True, matrix cannot have NaN values.
Raises
------
TypeError
If the matrix is not numeric.
ValueError
If the matrix contains NaN (allnum=True) or infinite values.
ValueError
If any values in the matrix are zero (nozero=True) or negative.
ValueError
If there are compositions full of zeros or NaNs (no observation).
ValueError
If the matrix has more than maximum number of dimensions.
"""
if not xp.isdtype(mat.dtype, "numeric"):
raise TypeError("Input matrix must have a numeric data type.")
if maxdim is not None and mat.ndim > maxdim:
raise ValueError(f"Input matrix can only have {maxdim} dimensions or less.")
if allnum:
if not xp.all(xp.isfinite(mat)):
raise ValueError("Input matrix cannot have infinite or NaN values.")
else:
if xp.any(xp.isinf(mat)):
raise ValueError("Input matrix cannot have infinite values.")
if nozero:
if xp.any(mat <= 0):
raise ValueError("Input matrix must have strictly positive components.")
else:
if xp.any(mat < 0):
raise ValueError("Input matrix cannot have negative components.")
if allnum:
observed = xp.any(mat, axis=axis)
else:
observed = xp.any(mat > 0, axis=axis)
if xp.any(~observed):
raise ValueError(
"Input matrix cannot have compositions without observed components."
)
@array_api_doc(
backends=["numpy", "cupy", "torch", "jax", "dask"],
devices=["cpu", "gpu"],
)
def closure(mat: ArrayLike, axis: int = -1, validate: bool = True) -> StdArray:
r"""Perform closure to ensure that all components of each composition sum to 1.
.. versionchanged:: 0.7.0
The function now works on any dimension in arrays of any number of dimensions.
Parameters
----------
mat : array_like of shape (..., n_components, ...)
A matrix of compositions.
axis : int, optional
Axis along which closure will be performed. That is, each vector along this
axis is considered as a composition. Default is the last axis (-1).
.. versionadded:: 0.7.0
validate : bool, default True
Check if the compositions are legitimate.
.. versionadded:: 0.7.0
Returns
-------
ndarray of shape (..., n_components, ...)
The matrix where all components of each composition sum to 1.
Examples
--------
>>> import numpy as np
>>> from skbio.stats.composition import closure
>>> X = np.array([[2, 2, 6], [4, 4, 2]])
>>> closure(X)
array([[ 0.2, 0.2, 0.6],
[ 0.4, 0.4, 0.2]])
"""
xp, mat = ingest_array(mat)
if validate:
_check_composition(xp, mat, axis)
return _closure(xp, mat, axis)
def _closure(xp: ModuleType, mat: StdArray, axis: int = -1) -> StdArray:
"""Perform closure."""
return mat / xp.sum(mat, axis=axis, keepdims=True)
@aliased("multiplicative_replacement", "0.6.0", True)
def multi_replace(mat, delta=None):
r"""Replace all zeros with small non-zero values.
It uses the multiplicative replacement strategy [1]_, replacing zeros with
a small positive :math:`\delta` and ensuring that the compositions still
add up to 1.
Parameters
----------
mat : array_like of shape (n_compositions, n_components)
A matrix of proportions.
delta : float, optional
A small number to be used to replace zeros. If not specified, the
default value is :math:`\delta = \frac{1}{N^2}` where :math:`N` is the
number of components.
Returns
-------
ndarray of shape (n_compositions, n_components)
The matrix where all of the values are non-zero and each composition
(row) adds up to 1.
Raises
------
ValueError
If negative proportions are created due to a large ``delta``.
Notes
-----
This method will result in negative proportions if a large delta is chosen.
References
----------
.. [1] J. A. Martin-Fernandez. "Dealing With Zeros and Missing Values in
Compositional Data Sets Using Nonparametric Imputation"
Examples
--------
>>> import numpy as np
>>> from skbio.stats.composition import multi_replace
>>> X = np.array([[.2, .4, .4, 0], [0, .5, .5, 0]])
>>> multi_replace(X)
array([[ 0.1875, 0.375 , 0.375 , 0.0625],
[ 0.0625, 0.4375, 0.4375, 0.0625]])
"""
mat = closure(mat)
z_mat = mat == 0
num_feats = mat.shape[-1]
tot = z_mat.sum(axis=-1, keepdims=True)
if delta is None:
delta = (1.0 / num_feats) ** 2
zcnts = 1 - tot * delta
if (zcnts < 0).any():
raise ValueError(
"Multiplicative replacement created negative proportions. Consider "
"using a smaller `delta`."
)
mat = np.where(z_mat, delta, zcnts * mat)
return mat.squeeze()
def _closure_two(x, y, validate):
xp, x, y = ingest_array(x, y)
if validate:
_check_composition(xp, x)
_check_composition(xp, y)
return xp, _closure(xp, x), _closure(xp, y)
def perturb(x: ArrayLike, y: ArrayLike, validate: bool = True) -> StdArray:
r"""Perform the perturbation operation.
This operation is defined as:
.. math::
x \oplus y = C[x_1 y_1, \ldots, x_D y_D]
:math:`C[x]` is the closure operation defined as:
.. math::
C[x] = \left[\frac{x_1}{\sum_{i=1}^{D} x_i},\ldots,
\frac{x_D}{\sum_{i=1}^{D} x_i} \right]
for some :math:`D` dimensional real vector :math:`x` and
:math:`D` is the number of components for every composition.
Parameters
----------
x : array_like of shape (n_compositions, n_components)
A matrix of proportions.
y : array_like of shape (n_compositions, n_components)
A matrix of proportions.
validate : bool, default True
Check if the compositions are legitimate.
.. versionadded:: 0.7.0
Returns
-------
ndarray of shape (n_compositions, n_components)
A matrix of proportions where all of the values are non-zero and each
composition (row) adds up to 1.
Examples
--------
>>> import numpy as np
>>> from skbio.stats.composition import perturb
Consider a very simple environment with only three species. The species in
the environment are evenly distributed and their proportions are equal:
>>> before = np.array([1/3, 1/3, 1/3])
Suppose that an antibiotic kills off half of the population for the first
two species, but doesn't harm the third species. Then the perturbation
vector would be as follows:
>>> after = np.array([1/2, 1/2, 1])
And the resulting perturbation would be:
>>> perturb(before, after)
array([ 0.25, 0.25, 0.5 ])
"""
xp, cx, cy = _closure_two(x, y, validate)
return _closure(xp, cx * cy)
def perturb_inv(x: ArrayLike, y: ArrayLike, validate: bool = True) -> StdArray:
r"""Perform the inverse perturbation operation.
This operation is defined as:
.. math::
x \ominus y = C[x_1 y_1^{-1}, \ldots, x_D y_D^{-1}]
:math:`C[x]` is the closure operation defined as:
.. math::
C[x] = \left[\frac{x_1}{\sum_{i=1}^{D} x_i},\ldots,
\frac{x_D}{\sum_{i=1}^{D} x_i} \right]
for some :math:`D` dimensional real vector :math:`x` and :math:`D` is the
number of components for every composition.
Parameters
----------
x : array_like of shape (n_compositions, n_components)
A matrix of proportions.
y : array_like of shape (n_compositions, n_components)
A matrix of proportions.
validate : bool, default True
Check if the compositions are legitimate.
.. versionadded:: 0.7.0
Returns
-------
ndarray of shape (n_compositions, n_components)
A matrix of proportions where all of the values are non-zero and each
composition (row) adds up to 1.
Examples
--------
>>> import numpy as np
>>> from skbio.stats.composition import perturb_inv
>>> x = np.array([.1, .3, .4, .2])
>>> y = np.array([1/6, 1/6, 1/3, 1/3])
>>> perturb_inv(x, y)
array([ 0.14285714, 0.42857143, 0.28571429, 0.14285714])
"""
xp, cx, cy = _closure_two(x, y, validate)
return _closure(xp, cx / cy)
def power(x: ArrayLike, a: float, validate: bool = True) -> StdArray:
r"""Perform the power operation.
This operation is defined as follows:
.. math::
`x \odot a = C[x_1^a, \ldots, x_D^a]
:math:`C[x]` is the closure operation defined as:
.. math::
C[x] = \left[\frac{x_1}{\sum_{i=1}^{D} x_i},\ldots,
\frac{x_D}{\sum_{i=1}^{D} x_i} \right]
for some :math:`D` dimensional real vector :math:`x` and
:math:`D` is the number of components for every composition.
Parameters
----------
x : array_like of shape (n_compositions, n_components)
A matrix of proportions.
a : float
A scalar exponent.
validate : bool, default True
Check if the compositions are legitimate.
.. versionadded:: 0.7.0
Returns
-------
ndarray of shape (n_compositions, n_components)
The matrix where all of the values are non-zero and each composition
(row) adds up to 1.
Examples
--------
>>> import numpy as np
>>> from skbio.stats.composition import power
>>> x = np.array([.1, .3, .4, .2])
>>> power(x, .1)
array([ 0.23059566, 0.25737316, 0.26488486, 0.24714631])
"""
xp, x = ingest_array(x)
if validate:
_check_composition(xp, x)
cx = _closure(xp, x)
return _closure(xp, cx**a).squeeze()
def inner(x: ArrayLike, y: ArrayLike, validate: bool = True) -> StdArray:
r"""Calculate the Aitchson inner product.
This inner product is defined as follows:
.. math::
\langle x, y \rangle_a =
\frac{1}{2D} \sum\limits_{i=1}^{D} \sum\limits_{j=1}^{D}
\ln\left(\frac{x_i}{x_j}\right) \ln\left(\frac{y_i}{y_j}\right)
Parameters
----------
x : array_like of shape (n_compositions, n_components)
A matrix of proportions.
y : array_like of shape (n_compositions, n_components)
A matrix of proportions.
validate : bool, default True
Check if the compositions are legitimate.
.. versionadded:: 0.7.0
Returns
-------
ndarray or scalar of shape (n_compositions, n_compositions)
Inner product result.
Examples
--------
>>> import numpy as np
>>> from skbio.stats.composition import inner
>>> x = np.array([.1, .3, .4, .2])
>>> y = np.array([.2, .4, .2, .2])
>>> inner(x, y) # doctest: +ELLIPSIS
0.2107852473...
"""
xp, cx, cy = _closure_two(x, y, validate)
clrx, clry = _clr(xp, cx, axis=-1), _clr(xp, cy, axis=-1)
return xp.matmul(clrx, clry.T)
@array_api_doc(
backends=["numpy", "cupy", "torch", "jax", "dask"],
devices=["cpu", "gpu"],
)
def clr(mat: ArrayLike, axis: int = -1, validate: bool = True) -> StdArray:
r"""Perform centre log ratio (CLR) transformation.
This function transforms compositions from Aitchison geometry to the real
space. The :math:`clr` transform is both an isometry and an isomorphism
defined on the following spaces:
.. math::
clr: S^D \rightarrow U
where :math:`U=
\{x :\sum\limits_{i=1}^D x = 0 \; \forall x \in \mathbb{R}^D\}`
It is defined for a composition :math:`x` as follows:
.. math::
clr(x) = \ln\left[\frac{x_1}{g_m(x)}, \ldots, \frac{x_D}{g_m(x)}\right]
where :math:`g_m(x) = (\prod\limits_{i=1}^{D} x_i)^{1/D}` is the geometric
mean of :math:`x`.
.. versionchanged:: 0.7.0
The function now works on any dimension in arrays of any number of dimensions.
Parameters
----------
mat : array_like of shape (..., n_components, ...)
A matrix of positive proportions.
axis : int, optional
Axis along which CLR transformation will be performed. Each vector on this axis
is considered as a composition. Default is the last axis (-1).
.. versionadded:: 0.7.0
validate : bool, default True
Check if the matrix consists of strictly positive values.
.. versionadded:: 0.7.0
Returns
-------
ndarray of shape (..., n_components, ...)
CLR-transformed matrix.
See Also
--------
clr_inv
Examples
--------
>>> import numpy as np
>>> from skbio.stats.composition import clr
>>> x = np.array([.1, .3, .4, .2])
>>> clr(x)
array([-0.79451346, 0.30409883, 0.5917809 , -0.10136628])
"""
xp, mat = ingest_array(mat)
if validate:
_check_composition(xp, mat, nozero=True)
return _clr(xp, mat, axis)
def _clr(xp: ModuleType, mat: StdArray, axis: int) -> StdArray:
"""Perform CLR transform."""
return (lmat := xp.log(mat)) - xp.mean(lmat, axis=axis, keepdims=True)
@array_api_doc(
backends=["numpy", "cupy", "torch", "jax", "dask"],
devices=["cpu", "gpu"],
)
def clr_inv(mat: ArrayLike, axis: int = -1, validate: bool = True) -> StdArray:
r"""Perform inverse centre log ratio (CLR) transformation.
This function transforms compositions from the real space to Aitchison
geometry. The :math:`clr^{-1}` transform is both an isometry, and an
isomorphism defined on the following spaces:
.. math::
clr^{-1}: U \rightarrow S^D
where :math:`U=
\{x :\sum\limits_{i=1}^D x = 0 \; \forall x \in \mathbb{R}^D\}`
This transformation is defined as follows:
.. math::
clr^{-1}(x) = C[\exp( x_1, \ldots, x_D)]
.. versionchanged:: 0.7.0
The function now works on any dimension in arrays of any number of dimensions.
Parameters
----------
mat : array_like of shape (..., n_components, ...)
A matrix of CLR-transformed data.
axis : int, optional
Axis along which inverse CLR transformation will be performed. Each vector on
this axis is considered as a CLR-transformed composition. Default is the last
axis (-1).
.. versionadded:: 0.7.0
validate: bool, optional
Check if the matrix has been centered at 0. Violation will result in a warning
rather than an error, for backward compatibility. Defaults to True.
.. versionadded:: 0.7.0
Returns
-------
ndarray of shape (..., n_components, ...)
Inverse CLR-transformed matrix.
See Also
--------
clr
Notes
-----
The output of ``clr_inv`` is guaranteed to have each composition sum to 1. But this
property isn't required for the input for ``clr``. Therefore, ``clr_inv`` does not
completely invert ``clr``. Instead, ``clr_inv(clr(mat))`` and ``closure(mat)`` are
equal.
Examples
--------
>>> import numpy as np
>>> from skbio.stats.composition import clr_inv
>>> x = np.array([-0.4, 0.3, 0.2, -0.1])
>>> clr_inv(x)
array([ 0.1616624 , 0.32554809, 0.2945681 , 0.21822141])
"""
xp, mat = ingest_array(mat)
if validate and _not_centered(xp, mat, axis):
warn(
"The input matrix is not in the CLR range, which requires the sum of "
"values per composition equals to 0.",
UserWarning,
)
return _clr_inv(xp, mat, axis)
def _not_centered(xp: ModuleType, mat: StdArray, axis: int):
"""Check if any composition is not centered to 0."""
# `1e-8` is taken from `np.allclose`. It's not guaranteed that `xp` has `allclose`,
# therefore it is manually written here.
return xp.any(xp.abs(xp.sum(mat, axis=axis)) > 1e-08)
def _clr_inv(xp: ModuleType, mat: StdArray, axis: int) -> StdArray:
"""Perform inverse CLR transform."""
# for numerical stability, shift the values < 1
diff = xp.exp(mat - xp.max(mat, axis=axis, keepdims=True))
return _closure(xp, diff, axis)
@array_api_doc(
backends=["numpy", "cupy", "torch", "jax", "dask"],
devices=["cpu", "gpu"],
)
def rclr(mat: ArrayLike, axis: int = -1, validate: bool = True) -> StdArray:
r"""Perform robust centre log ratio (RCLR) transformation.
.. versionadded:: 0.7.3
The robust CLR transformation is similar to the standard CLR transformation, but it
only operates on observed (non-zero) values [1]_. This makes it suitable for sparse
compositional data.
For each composition, the transformation computes:
.. math::
rclr(x_i) = \ln(x_i) - \frac{1}{|S|} \sum_{j \in S} \ln(x_j)
where :math:`S` is the set of indices with non-zero values, and :math:`|S|` is the
number of non-zero values.
Parameters
----------
mat : array_like of shape (..., n_components, ...)
A matrix of non-negative values. Zeros are allowed and will become NaN in the
output. NaN values in the input are preserved (representing missing entries).
axis : int, optional
Axis along which rclr transformation will be performed. Each vector on this
axis is considered as a composition. Default is the last axis (-1).
validate : bool, default True
Check if the matrix consists of non-negative, finite values. NaN values are
allowed as missing entries.
Returns
-------
ndarray of shape (..., n_components, ...)
rclr-transformed matrix. Zero values in the input become NaN.
See Also
--------
clr
rclr_inv
Notes
-----
The rclr transformation has several advantages for sparse compositional data:
1. It does not require pseudocount addition, which can bias results.
2. It preserves the zero/non-zero structure of the data.
3. It allows for matrix completion methods to be applied.
The geometric mean is computed only over non-zero values in each composition,
making it "robust" to the presence of zeros.
References
----------
.. [1] Martino, C., Morton, J. T., Marotz, C. A., Thompson, L. R., Tripathi, A.,
Knight, R., & Zengler, K. (2019). A novel sparse compositional technique reveals
microbial perturbations. MSystems, 4(1), 10-1128.
Examples
--------
>>> import numpy as np
>>> from skbio.stats.composition import rclr
>>> x = np.array([[1, 2, 0, 4],
... [0, 3, 3, 0],
... [2, 2, 2, 2]])
>>> rclr(x).round(3)
array([[-0.693, 0. , nan, 0.693],
[ nan, 0. , 0. , nan],
[ 0. , 0. , 0. , 0. ]])
"""
xp, mat = ingest_array(mat)
if validate:
_check_composition(xp, mat, axis=axis, allnum=False)
return _rclr(xp, mat, axis)
def _rclr(xp: ModuleType, mat: StdArray, axis: int) -> StdArray:
"""Perform rclr transform."""
# Mask observed values (excluding zero and NaN) in the input matrix.
# observed_mask = (mat != 0) & ~xp.isnan(mat)
obs_mask = mat > 0
# Safe logarithm on observed values, while unobserved values (zero and NaN) become
# zeros. The use of Python scalar 1 ensures that the output of `where` matches the
# data type of `mat`. This behavior is compliant with array API.
safe_mat = xp.where(obs_mask, mat, 1)
log_safe = xp.log(safe_mat)
# Alternatively, one can do the following, which however will raise a warning.
# log_safe = xp.where(observed_mask, xp.log(mat), 0.0)
# Count observed values from mask
n_obs = xp.sum(obs_mask, axis=axis, keepdims=True)
# Replace 0 (all-missing compositions) with 1 for safe division.
# This shouldn't happen if input has been validated.
# n_obs = xp.where(n_obs > 0, n_obs, 1)
# Sum logs for observed values only
log_sum = xp.sum(log_safe, axis=axis, keepdims=True)
# Calculate geometric mean
geo_mean_log = log_sum / n_obs
# Center by geometric mean
centered = log_safe - geo_mean_log
# Replace unobserved values with NaN
result = xp.where(obs_mask, centered, xp.nan)
return result
@array_api_doc(
backends=["numpy", "cupy", "torch", "jax", "dask"],
devices=["cpu", "gpu"],
)
def rclr_inv(mat: ArrayLike, axis: int = -1, validate: bool = True) -> StdArray:
r"""Perform inverse robust centre log ratio (RCLR) transformation.
.. versionadded:: 0.7.4
This function transforms RCLR-transformed data back to compositional
space. Non-NaN values are exponentiated and closed to sum to 1, while
NaN values are interpreted as unobserved components and become zeros
in the output.
For a transformed composition :math:`x`, let :math:`S` be the set of
observed (non-NaN) components. The inverse transformation is
.. math::
rclr^{-1}(x)_i =
\begin{cases}
\displaystyle
\frac{\exp(x_i)}{\sum_{j \in S} \exp(x_j)}, & i \in S, \\
0, & i \notin S.
\end{cases}
Parameters
----------
mat : array_like of shape (..., n_components, ...)
A matrix of RCLR-transformed data. NaN values represent unobserved components.
axis : int, optional
Axis along which inverse RCLR transformation will be performed. Each vector on
this axis is considered as an RCLR-transformed composition. Default is the last
axis (-1).
validate : bool, optional
Check that each composition contains at least one observed value
and that its observed values are centered at zero. Violation of
the centering condition results in a warning. Default is True.
Returns
-------
ndarray of shape (..., n_components, ...)
Inverse RCLR-transformed compositions. NaN values in the input become zeros,
and each composition sums to 1.
See Also
--------
rclr
clr_inv
Notes
-----
RCLR converts both zeros and missing (NaN) values to NaN. Therefore, the original
distinction between zeros and missing values cannot be recovered from inverse RCLR
transformation. This function considers all NaNs as unobserved zero components.
As with CLR, RCLR is scale invariant. Therefore ``rclr_inv(rclr(mat))`` recovers
``closure(mat)``, rather than the original scale of ``mat``.
Examples
--------
>>> import numpy as np
>>> from skbio.stats.composition import rclr_inv
>>> x = np.array([-0.3, np.nan, 0.2, 0.1])
>>> rclr_inv(x)
array([ 0.24151404, 0. , 0.39818934, 0.36029662])
"""
xp, mat = ingest_array(mat)
# Calculate these anyway because they are needed by `_rclr_inv`.
observed = ~xp.isnan(mat)
safe_mat = xp.where(observed, mat, 0)
if validate:
if xp.any(~xp.any(observed, axis=axis)):
raise ValueError(
"Input matrix cannot have compositions without observed components."
)
if _not_centered(xp, safe_mat, axis):
warn(
"The input matrix is not in the RCLR range, which requires the sum of "
"observed values per composition to equal 0.",
UserWarning,
)
return _rclr_inv(xp, mat, axis, observed, safe_mat)
def _rclr_inv(
xp: ModuleType,
mat: StdArray,
axis: int,
observed: StdArray | None = None,
safe_mat: StdArray | None = None,
) -> StdArray:
"""Perform inverse RCLR transform."""
if observed is None:
observed = ~xp.isnan(mat)
if safe_mat is None:
safe_mat = xp.where(observed, mat, 0) # replace NaNs with zeros
shift = xp.max(safe_mat, axis=axis, keepdims=True)
diff = xp.where(observed, xp.exp(safe_mat - shift), 0)
return _closure(xp, diff, axis)
@params_aliased([("validate", "check", "0.7.0", True)])
@array_api_doc(
backends=["numpy", "cupy", "torch", "jax", "dask"],
devices=["cpu", "gpu"],
)
def ilr(
mat: ArrayLike,
basis: ArrayLike | None = None,
axis: int = -1,
validate: bool = True,
) -> StdArray:
r"""Perform isometric log ratio (ILR) transformation.
This function transforms compositions from Aitchison simplex to the real
space. The :math:`ilr` transform is both an isometry, and an isomorphism
defined on the following spaces:
.. math::
ilr: S^D \rightarrow \mathbb{R}^{D-1}
The ilr transformation is defined as follows:
.. math::
ilr(x) =
[\langle x, e_1 \rangle_a, \ldots, \langle x, e_{D-1} \rangle_a]
where :math:`[e_1,\ldots,e_{D-1}]` is an orthonormal basis in the simplex.
If an orthornormal basis isn't specified, the J. J. Egozcue orthonormal basis
derived from Gram-Schmidt orthogonalization [1]_ will be used by default.
.. versionchanged:: 0.7.0
The function now works on any dimension in arrays of any number of dimensions.
Parameters
----------
mat : array_like of shape (..., n_components, ...)
A matrix of positive proportions.
basis : ndarray or sparse matrix, optional
Orthonormal basis for Aitchison simplex. Defaults to J. J. Egozcue
orthonormal basis.
axis : int, optional
Axis along which ILR transformation will be performed. That is, each vector
along this axis is considered as a composition. Default is the last axis (-1).
.. versionadded:: 0.7.0
validate : bool, default True
Check if i) the matrix is compositional, ii) the basis is orthonormal,
2-dimensional, and the dimensions are matched.
Returns
-------
ndarray of shape (..., n_components - 1,...)
ILR-transformed matrix.
See Also
--------
ilr_inv
Notes
-----
If the ``basis`` parameter is specified, it is expected to be a basis in
the Aitchison simplex. If there are :math:`D - 1` elements specified in
``mat``, then the dimensions of the basis needs be :math:`(D-1) \times D`,
where rows represent basis vectors, and the columns represent proportions.
References
----------
.. [1] Egozcue, J. J., Pawlowsky-Glahn, V., Mateu-Figueras, G., & Barcelo-Vidal,
C. (2003). Isometric logratio transformations for compositional data analysis.
Mathematical geology, 35(3), 279-300.
Examples
--------
>>> import numpy as np
>>> from skbio.stats.composition import ilr
>>> x = np.array([.1, .3, .4, .2])
>>> ilr(x)
array([-0.7768362 , -0.68339802, 0.11704769])
"""
xp, mat = ingest_array(mat)
if validate:
_check_composition(xp, mat, nozero=True)
N = mat.shape[axis]
if basis is None:
# NOTE: acc.device(mat) would be nicer
basis = xp.asarray(
_gram_schmidt_basis(N), device=mat.device, dtype=xp.float64
) # dimension (N-1) x N
else:
xp_, basis = ingest_array(basis)
if validate:
# the following maybe redundant
if basis.ndim != 2:
raise ValueError(
f"Basis needs to be a 2-D matrix, not a {basis.ndim}-D matrix."
)
_check_basis(xp_, basis, orthonormal=True, subspace_dim=N - 1)
basis = xp.asarray(basis, device=mat.device, dtype=xp.float64)
axis %= mat.ndim
return _ilr(xp, mat, basis, axis)
def _swap_axis(ndim, axis):
"""Create a list of axis indices with one axis swapped with the last axis."""
res = list(range(ndim))
res[axis] = ndim - 1
res[ndim - 1] = axis
return res
def _ilr(xp: ModuleType, mat: StdArray, basis: StdArray, axis: int) -> StdArray:
"""Perform ILR transform."""
mat = _clr(xp, mat, axis)
# tensordot return's shape consists of the non-contracted axes (dimensions) of
# the first array x1, followed by the non-contracted axes (dimensions) of the
# second array x2
prod = xp.tensordot(mat, basis, axes=([axis], [1]))
return xp.permute_dims(prod, axes=_swap_axis(mat.ndim, axis))
@params_aliased([("validate", "check", "0.7.0", True)])
@array_api_doc(
backends=["numpy", "cupy", "torch", "jax", "dask"],
devices=["cpu", "gpu"],
)
def ilr_inv(
mat: ArrayLike,
basis: ArrayLike | None = None,
axis: int = -1,
validate: bool = True,
) -> StdArray:
r"""Perform inverse isometric log ratio (ILR) transformation.
This function transforms compositions from the real space to Aitchison
geometry. The :math:`ilr^{-1}` transform is both an isometry, and an
isomorphism defined on the following spaces:
.. math::
ilr^{-1}: \mathbb{R}^{D-1} \rightarrow S^D
The inverse ilr transformation is defined as follows:
.. math::
ilr^{-1}(x) = \bigoplus\limits_{i=1}^{D-1} x \odot e_i
where :math:`[e_1,\ldots, e_{D-1}]` is an orthonormal basis in the simplex.
If an orthonormal basis isn't specified, the J. J. Egozcue orthonormal basis
derived from Gram-Schmidt orthogonalization [1]_ will be used by default.
.. versionchanged:: 0.7.0
The function now works on any dimension in arrays of any number of dimensions.
Parameters
----------
mat : array_like of shape (..., n_components - 1, ...)
A matrix of ILR-transformed data.
basis : ndarray or sparse matrix, optional
Orthonormal basis for Aitchison simplex. Defaults to J. J. Egozcue
orthonormal basis.
axis : int, optional
Axis along which ILR transformation will be performed. That is, each vector
along this axis is considered as a ILR transformed composition data.
Default is the last axis (-1).
.. versionadded:: 0.7.0
validate : bool, default True
Check to see if basis is orthonormal and dimension matches.
Returns
-------
ndarray of shape (..., n_components, ...)
Inverse ILR-transformed matrix.
See Also
--------
ilr
Notes
-----
If the ``basis`` parameter is specified, it is expected to be a basis in
the Aitchison simplex. If there are :math:`D - 1` elements specified in
``mat``, then the dimensions of the basis needs be :math:`(D-1) \times D`,
where rows represent basis vectors, and the columns represent proportions.
References
----------
.. [1] Egozcue, J. J., Pawlowsky-Glahn, V., Mateu-Figueras, G., & Barcelo-Vidal,
C. (2003). Isometric logratio transformations for compositional data analysis.