Repository navigation
Expand file tree
/
Copy path_sorting.py
More file actions
206 lines (172 loc) · 6.48 KB
/
Copy path_sorting.py
File metadata and controls
206 lines (172 loc) · 6.48 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
"""Delegation layer for sorting functions."""
from . import _agnostic
from ._lib import _compat, _helpers
from ._lib._typing import Array, ArrayNamespace
__all__ = ["argpartition", "partition"]
def partition(
a: Array,
kth: int,
/,
axis: int | None = -1,
*,
xp: ArrayNamespace | None = None,
) -> Array:
"""
Return a partitioned copy of an array.
Creates a copy of the array and partially sorts it in such a way that the value
of the element in k-th position is in the position it would be in a sorted array.
In the output array, all elements smaller than the k-th element are located to
the left of this element and all equal or greater are located to its right.
The ordering of the elements in the two partitions on the either side of
the k-th element in the output array is undefined.
Parameters
----------
a : Array
Input array.
kth : int
Element index to partition by.
axis : int, optional
Axis along which to partition. The default is ``-1`` (the last axis).
If ``None``, the flattened array is used.
xp : array_namespace, optional
The standard-compatible namespace for `x`. Default: infer.
Returns
-------
partitioned_array
Array of the same type and shape as `a`.
Notes
-----
If `xp` implements ``partition`` or an equivalent function
(e.g. ``topk`` for torch), complexity will likely be O(n).
If not, this function simply calls ``xp.sort`` and complexity is O(n log n).
"""
# Validate inputs.
if xp is None:
xp = _compat.array_namespace(a)
if a.ndim < 1:
msg = "`a` must be at least 1-dimensional"
raise TypeError(msg)
if axis is None:
return partition(xp.reshape(a, (-1,)), kth, axis=0, xp=xp)
(size,) = _helpers.eager_shape(a, axis)
if not (0 <= kth < size):
msg = f"kth(={kth}) out of bounds [0 {size})"
raise ValueError(msg)
# Delegate where possible.
if (
_compat.is_numpy_namespace(xp)
or _compat.is_cupy_namespace(xp)
or _compat.is_jax_namespace(xp)
):
return xp.partition(a, kth, axis=axis)
# Use top-k when possible:
if _compat.is_torch_namespace(xp):
if not (axis == -1 or axis == a.ndim - 1):
a = xp.transpose(a, axis, -1)
out = xp.empty_like(a)
ranks = xp.arange(a.shape[-1]).expand_as(a)
split_value, indices = xp.kthvalue(a, kth + 1, keepdim=True)
del indices # indices won't be used => del ASAP to reduce peak memory usage
# fill the left-side of the partition
mask_src = a < split_value
n_left = mask_src.sum(dim=-1, keepdim=True)
mask_dest = ranks < n_left
out[mask_dest] = a[mask_src]
# fill the middle of the partition
mask_src = a == split_value
n_left += mask_src.sum(dim=-1, keepdim=True)
mask_dest ^= ranks < n_left
out[mask_dest] = a[mask_src]
# fill the right-side of the partition
mask_src = a > split_value
mask_dest = ranks >= n_left
out[mask_dest] = a[mask_src]
if not (axis == -1 or axis == a.ndim - 1):
out = xp.transpose(out, axis, -1)
return out
# Note: dask topk/argtopk sort the return values, so it's
# not much more efficient than sorting everything when
# kth is not small compared to x.size
return _agnostic._sorting.partition(a, kth, axis=axis, xp=xp)
def argpartition(
a: Array,
kth: int,
/,
axis: int | None = -1,
*,
xp: ArrayNamespace | None = None,
) -> Array:
"""
Perform an indirect partition along the given axis.
It returns an array of indices of the same shape as `a` that
index data along the given axis in partitioned order.
Parameters
----------
a : Array
Input array.
kth : int
Element index to partition by.
axis : int, optional
Axis along which to partition. The default is ``-1`` (the last axis).
If ``None``, the flattened array is used.
xp : array_namespace, optional
The standard-compatible namespace for `x`. Default: infer.
Returns
-------
index_array
Array of indices that partition `a` along the specified axis.
Notes
-----
If `xp` implements ``argpartition`` or an equivalent function
e.g. ``topk`` for torch), complexity will likely be O(n).
If not, this function simply calls ``xp.argsort`` and complexity is O(n log n).
"""
# Validate inputs.
if xp is None:
xp = _compat.array_namespace(a)
if _compat.is_pydata_sparse_namespace(xp):
msg = "Not implemented for sparse backend: no argsort"
raise NotImplementedError(msg)
if a.ndim < 1:
msg = "`a` must be at least 1-dimensional"
raise TypeError(msg)
if axis is None:
return argpartition(xp.reshape(a, (-1,)), kth, axis=0, xp=xp)
(size,) = _helpers.eager_shape(a, axis)
if not (0 <= kth < size):
msg = f"kth(={kth}) out of bounds [0 {size})"
raise ValueError(msg)
# Delegate where possible.
if (
_compat.is_numpy_namespace(xp)
or _compat.is_cupy_namespace(xp)
or _compat.is_jax_namespace(xp)
):
return xp.argpartition(a, kth, axis=axis)
# Use top-k when possible:
if _compat.is_torch_namespace(xp):
# see `partition` above for commented details of those steps:
if not (axis == -1 or axis == a.ndim - 1):
a = xp.transpose(a, axis, -1)
ranks = xp.arange(a.shape[-1]).expand_as(a)
out = xp.empty_like(ranks)
split_value, indices = xp.kthvalue(a, kth + 1, keepdim=True)
del indices # indices won't be used => del ASAP to reduce peak memory usage
mask_src = a < split_value
n_left = mask_src.sum(dim=-1, keepdim=True)
mask_dest = ranks < n_left
out[mask_dest] = ranks[mask_src]
mask_src = a == split_value
n_left += mask_src.sum(dim=-1, keepdim=True)
mask_dest ^= ranks < n_left
out[mask_dest] = ranks[mask_src]
mask_src = a > split_value
mask_dest = ranks >= n_left
out[mask_dest] = ranks[mask_src]
if not (axis == -1 or axis == a.ndim - 1):
out = xp.transpose(out, axis, -1)
return out
# Note: dask topk/argtopk sort the return values, so it's
# not much more efficient than sorting everything when
# kth is not small compared to x.size
return _agnostic._sorting.argpartition(a, kth, axis=axis, xp=xp)