summaryrefslogtreecommitdiff
path: root/numpy/lib/arraysetops.py
blob: 27092732124a06eda3b9de729e6aa0e4c4df7c17 (plain)
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
"""
Set operations for 1D numeric arrays based on sorting.

:Contains:
  ediff1d,
  unique1d,
  intersect1d,
  intersect1d_nu,
  setxor1d,
  setmember1d,
  union1d,
  setdiff1d

:Notes:

All functions work best with integer numerical arrays on input (e.g. indices).
For floating point arrays, innacurate results may appear due to usual round-off
and floating point comparison issues.

Except unique1d, union1d and intersect1d_nu, all functions expect inputs with
unique elements. Speed could be gained in some operations by an implementaion of
sort(), that can provide directly the permutation vectors, avoiding thus calls
to argsort().

Run _test_unique1d_speed() to compare performance of numpy.unique1d() and
numpy.unique() - it should be the same.

To do: Optionally return indices analogously to unique1d for all functions.

created:       01.11.2005
last revision: 07.01.2007

:Author: Robert Cimrman
"""
__all__ = ['ediff1d', 'unique1d', 'intersect1d', 'intersect1d_nu', 'setxor1d',
           'setmember1d', 'union1d', 'setdiff1d']

import numpy as np

def ediff1d(ary, to_end=None, to_begin=None):
    """
    The differences between consecutive elements of an array.

    Parameters
    ----------
    ary : array
        This array will be flattened before the difference is taken.
    to_end : number, optional
        If provided, this number will be tacked onto the end of the returned
        differences.
    to_begin : number, optional
        If provided, this number will be taked onto the beginning of the
        returned differences.

    Returns
    -------
    ed : array
        The differences. Loosely, this will be (ary[1:] - ary[:-1]).

    """
    ary = np.asarray(ary).flat
    ed = ary[1:] - ary[:-1]
    arrays = [ed]
    if to_begin is not None:
        arrays.insert(0, to_begin)
    if to_end is not None:
        arrays.append(to_end)

    if len(arrays) != 1:
        # We'll save ourselves a copy of a potentially large array in the common
        # case where neither to_begin or to_end was given.
        ed = np.hstack(arrays)

    return ed

def unique1d(ar1, return_index=False, return_inverse=False):
    """
    Find the unique elements of an array.

    Parameters
    ----------
    ar1 : array-like
        This array will be flattened if it is not already 1-D.
    return_index : bool, optional
        If True, also return the indices against `ar1` that result in the
        unique array.
    return_inverse : bool, optional
        If True, also return the indices against the unique array that
        result in `ar1`.

    Returns
    -------
    unique : ndarray
        The unique values.
    unique_indices : ndarray, optional
        The indices of the unique values. Only provided if `return_index` is
        True.
    unique_inverse : ndarray, optional
        The indices to reconstruct the original array. Only provided if
        `return_inverse` is True.

    See Also
    --------
      numpy.lib.arraysetops : Module with a number of other functions
                              for performing set operations on arrays.

    Examples
    --------
    >>> np.unique1d([1, 1, 2, 2, 3, 3])
    array([1, 2, 3])
    >>> a = np.array([[1, 1], [2, 3]])
    >>> np.unique1d(a)
    array([1, 2, 3])

    Reconstruct the input from unique values:

    >>> np.unique1d([1,2,6,4,2,3,2], return_index=True)
    >>> x = [1,2,6,4,2,3,2]
    >>> u, i = np.unique1d(x, return_inverse=True)
    >>> u
    array([1, 2, 3, 4, 6])
    >>> i
    array([0, 1, 4, 3, 1, 2, 1])
    >>> [u[p] for p in i]
    [1, 2, 6, 4, 2, 3, 2]

    """
    if return_index:
        import warnings
        warnings.warn("The order of the output arguments for "
                      "`return_index` has changed.  Before, "
                      "the output was (indices, unique_arr), but "
                      "has now been reversed to be more consistent.")

    ar = np.asarray(ar1).flatten()
    if ar.size == 0:
        if return_inverse and return_index:
            return ar, np.empty(0, np.bool), np.empty(0, np.bool)
        elif return_inverse or return_index:
            return ar, np.empty(0, np.bool)
        else:
            return ar

    if return_inverse or return_index:
        perm = ar.argsort()
        aux = ar[perm]
        flag = np.concatenate(([True], aux[1:] != aux[:-1]))
        if return_inverse:
            iflag = np.cumsum(flag) - 1
            iperm = perm.argsort()
            if return_index:
                return aux[flag], perm[flag], iflag[iperm]
            else:
                return aux[flag], iflag[iperm]
        else:
            return aux[flag], perm[flag]

    else:
        ar.sort()
        flag = np.concatenate(([True], ar[1:] != ar[:-1]))
        return ar[flag]

def intersect1d(ar1, ar2):
    """
    Intersection returning repeated or unique elements common to both arrays.

    Parameters
    ----------
    ar1,ar2 : array_like
        Input arrays.

    Returns
    -------
    out : ndarray, shape(N,)
        Sorted 1D array of common elements with repeating elements.

    See Also
    --------
    intersect1d_nu : Returns only unique common elements.
    numpy.lib.arraysetops : Module with a number of other functions for
                            performing set operations on arrays.

    Examples
    --------
    >>> np.intersect1d([1,3,3],[3,1,1])
    array([1, 1, 3, 3])

    """
    aux = np.concatenate((ar1,ar2))
    aux.sort()
    return aux[aux[1:] == aux[:-1]]

def intersect1d_nu(ar1, ar2):
    """
    Intersection returning unique elements common to both arrays.

    Parameters
    ----------
    ar1,ar2 : array_like
        Input arrays.

    Returns
    -------
    out : ndarray, shape(N,)
        Sorted 1D array of common and unique elements.

    See Also
    --------
    intersect1d : Returns repeated or unique common elements.
    numpy.lib.arraysetops : Module with a number of other functions for
                            performing set operations on arrays.

    Examples
    --------
    >>> np.intersect1d_nu([1,3,3],[3,1,1])
    array([1, 3])

    """
    # Might be faster than unique1d( intersect1d( ar1, ar2 ) )?
    aux = np.concatenate((unique1d(ar1), unique1d(ar2)))
    aux.sort()
    return aux[aux[1:] == aux[:-1]]

def setxor1d(ar1, ar2):
    """
    Set exclusive-or of 1D arrays with unique elements.

    Use unique1d() to generate arrays with only unique elements to use as
    inputs to this function.

    Parameters
    ----------
    ar1 : array
        Input array.
    ar2 : array
        Input array.

    Returns
    -------
    xor : array
        The values that are only in one, but not both, of the input arrays.

    See Also
    --------
    numpy.lib.arraysetops : Module with a number of other functions for
                            performing set operations on arrays.

    """
    aux = np.concatenate((ar1, ar2))
    if aux.size == 0:
        return aux

    aux.sort()
#    flag = ediff1d( aux, to_end = 1, to_begin = 1 ) == 0
    flag = np.concatenate( ([True], aux[1:] != aux[:-1], [True] ) )
#    flag2 = ediff1d( flag ) == 0
    flag2 = flag[1:] == flag[:-1]
    return aux[flag2]

def setmember1d(ar1, ar2):
    """
    Return a boolean array set True where first element is in second array.

    Boolean array is the shape of `ar1` containing True where the elements
    of `ar1` are in `ar2` and False otherwise.

    Use unique1d() to generate arrays with only unique elements to use as
    inputs to this function.

    Parameters
    ----------
    ar1 : array
        Input array.
    ar2 : array
        Input array.

    Returns
    -------
    mask : bool-array
        The values ar1[mask] are in ar2.

    See Also
    --------
    numpy.lib.arraysetops : Module with a number of other functions for
                            performing set operations on arrays.

    """
    ar1 = np.asarray( ar1 )
    ar2 = np.asarray( ar2 )
    ar = np.concatenate( (ar1, ar2 ) )
    b1 = np.zeros( ar1.shape, dtype = np.int8 )
    b2 = np.ones( ar2.shape, dtype = np.int8 )
    tt = np.concatenate( (b1, b2) )

    # We need this to be a stable sort, so always use 'mergesort' here. The
    # values from the first array should always come before the values from the
    # second array.
    perm = ar.argsort(kind='mergesort')
    aux = ar[perm]
    aux2 = tt[perm]
#    flag = ediff1d( aux, 1 ) == 0
    flag = np.concatenate( (aux[1:] == aux[:-1], [False] ) )
    ii = np.where( flag * aux2 )[0]
    aux = perm[ii+1]
    perm[ii+1] = perm[ii]
    perm[ii] = aux

    indx = perm.argsort(kind='mergesort')[:len( ar1 )]

    return flag[indx]

def union1d(ar1, ar2):
    """
    Union of 1D arrays with unique elements.

    Use unique1d() to generate arrays with only unique elements to use as
    inputs to this function.

    Parameters
    ----------
    ar1 : array_like, shape(M,)
        Input array.
    ar2 : array_like, shape(N,)
        Input array.

    Returns
    -------
    union : array
        Unique union of input arrays.

    See also
    --------
    numpy.lib.arraysetops : Module with a number of other functions for
                            performing set operations on arrays.

    """
    return unique1d( np.concatenate( (ar1, ar2) ) )

def setdiff1d(ar1, ar2):
    """
    Set difference of 1D arrays with unique elements.

    Use unique1d() to generate arrays with only unique elements to use as
    inputs to this function.

    Parameters
    ----------
    ar1 : array
        Input array.
    ar2 : array
        Input comparison array.

    Returns
    -------
    difference : array
        The values in ar1 that are not in ar2.

    See Also
    --------
    numpy.lib.arraysetops : Module with a number of other functions for
                            performing set operations on arrays.

    """
    aux = setmember1d(ar1,ar2)
    if aux.size == 0:
        return aux
    else:
        return np.asarray(ar1)[aux == 0]