_arraysetops_impl.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  1. """
  2. Set operations for arrays based on sorting.
  3. Notes
  4. -----
  5. For floating point arrays, inaccurate results may appear due to usual round-off
  6. and floating point comparison issues.
  7. Speed could be gained in some operations by an implementation of
  8. `numpy.sort`, that can provide directly the permutation vectors, thus avoiding
  9. calls to `numpy.argsort`.
  10. Original author: Robert Cimrman
  11. """
  12. import functools
  13. from typing import NamedTuple
  14. import numpy as np
  15. from numpy._core import overrides
  16. from numpy._core._multiarray_umath import _array_converter, _unique_hash
  17. from numpy.lib.array_utils import normalize_axis_index
  18. array_function_dispatch = functools.partial(
  19. overrides.array_function_dispatch, module='numpy')
  20. __all__ = [
  21. "ediff1d", "intersect1d", "isin", "setdiff1d", "setxor1d",
  22. "union1d", "unique", "unique_all", "unique_counts", "unique_inverse",
  23. "unique_values"
  24. ]
  25. def _ediff1d_dispatcher(ary, to_end=None, to_begin=None):
  26. return (ary, to_end, to_begin)
  27. @array_function_dispatch(_ediff1d_dispatcher)
  28. def ediff1d(ary, to_end=None, to_begin=None):
  29. """
  30. The differences between consecutive elements of an array.
  31. Parameters
  32. ----------
  33. ary : array_like
  34. If necessary, will be flattened before the differences are taken.
  35. to_end : array_like, optional
  36. Number(s) to append at the end of the returned differences.
  37. to_begin : array_like, optional
  38. Number(s) to prepend at the beginning of the returned differences.
  39. Returns
  40. -------
  41. ediff1d : ndarray
  42. The differences. Loosely, this is ``ary.flat[1:] - ary.flat[:-1]``.
  43. See Also
  44. --------
  45. diff, gradient
  46. Notes
  47. -----
  48. When applied to masked arrays, this function drops the mask information
  49. if the `to_begin` and/or `to_end` parameters are used.
  50. Examples
  51. --------
  52. >>> import numpy as np
  53. >>> x = np.array([1, 2, 4, 7, 0])
  54. >>> np.ediff1d(x)
  55. array([ 1, 2, 3, -7])
  56. >>> np.ediff1d(x, to_begin=-99, to_end=np.array([88, 99]))
  57. array([-99, 1, 2, ..., -7, 88, 99])
  58. The returned array is always 1D.
  59. >>> y = [[1, 2, 4], [1, 6, 24]]
  60. >>> np.ediff1d(y)
  61. array([ 1, 2, -3, 5, 18])
  62. """
  63. conv = _array_converter(ary)
  64. # Convert to (any) array and ravel:
  65. ary = conv[0].ravel()
  66. # enforce that the dtype of `ary` is used for the output
  67. dtype_req = ary.dtype
  68. # fast track default case
  69. if to_begin is None and to_end is None:
  70. return ary[1:] - ary[:-1]
  71. if to_begin is None:
  72. l_begin = 0
  73. else:
  74. to_begin = np.asanyarray(to_begin)
  75. if not np.can_cast(to_begin, dtype_req, casting="same_kind"):
  76. raise TypeError("dtype of `to_begin` must be compatible "
  77. "with input `ary` under the `same_kind` rule.")
  78. to_begin = to_begin.ravel()
  79. l_begin = len(to_begin)
  80. if to_end is None:
  81. l_end = 0
  82. else:
  83. to_end = np.asanyarray(to_end)
  84. if not np.can_cast(to_end, dtype_req, casting="same_kind"):
  85. raise TypeError("dtype of `to_end` must be compatible "
  86. "with input `ary` under the `same_kind` rule.")
  87. to_end = to_end.ravel()
  88. l_end = len(to_end)
  89. # do the calculation in place and copy to_begin and to_end
  90. l_diff = max(len(ary) - 1, 0)
  91. result = np.empty_like(ary, shape=l_diff + l_begin + l_end)
  92. if l_begin > 0:
  93. result[:l_begin] = to_begin
  94. if l_end > 0:
  95. result[l_begin + l_diff:] = to_end
  96. np.subtract(ary[1:], ary[:-1], result[l_begin:l_begin + l_diff])
  97. return conv.wrap(result)
  98. def _unpack_tuple(x):
  99. """ Unpacks one-element tuples for use as return values """
  100. if len(x) == 1:
  101. return x[0]
  102. else:
  103. return x
  104. def _unique_dispatcher(ar, return_index=None, return_inverse=None,
  105. return_counts=None, axis=None, *, equal_nan=None,
  106. sorted=True):
  107. return (ar,)
  108. @array_function_dispatch(_unique_dispatcher)
  109. def unique(ar, return_index=False, return_inverse=False,
  110. return_counts=False, axis=None, *, equal_nan=True,
  111. sorted=True):
  112. """
  113. Find the unique elements of an array.
  114. Returns the sorted unique elements of an array. There are three optional
  115. outputs in addition to the unique elements:
  116. * the indices of the input array that give the unique values
  117. * the indices of the unique array that reconstruct the input array
  118. * the number of times each unique value comes up in the input array
  119. Parameters
  120. ----------
  121. ar : array_like
  122. Input array. Unless `axis` is specified, this will be flattened if it
  123. is not already 1-D.
  124. return_index : bool, optional
  125. If True, also return the indices of `ar` (along the specified axis,
  126. if provided, or in the flattened array) that result in the unique array.
  127. return_inverse : bool, optional
  128. If True, also return the indices of the unique array (for the specified
  129. axis, if provided) that can be used to reconstruct `ar`.
  130. return_counts : bool, optional
  131. If True, also return the number of times each unique item appears
  132. in `ar`.
  133. axis : int or None, optional
  134. The axis to operate on. If None, `ar` will be flattened. If an integer,
  135. the subarrays indexed by the given axis will be flattened and treated
  136. as the elements of a 1-D array with the dimension of the given axis,
  137. see the notes for more details. Object arrays or structured arrays
  138. that contain objects are not supported if the `axis` kwarg is used. The
  139. default is None.
  140. equal_nan : bool, optional
  141. If True, collapses multiple NaN values in the return array into one.
  142. .. versionadded:: 1.24
  143. sorted : bool, optional
  144. If True, the unique elements are sorted. Elements may be sorted in
  145. practice even if ``sorted=False``, but this could change without
  146. notice.
  147. .. versionadded:: 2.3
  148. Returns
  149. -------
  150. unique : ndarray
  151. The sorted unique values.
  152. unique_indices : ndarray, optional
  153. The indices of the first occurrences of the unique values in the
  154. original array. Only provided if `return_index` is True.
  155. unique_inverse : ndarray, optional
  156. The indices to reconstruct the original array from the
  157. unique array. Only provided if `return_inverse` is True.
  158. unique_counts : ndarray, optional
  159. The number of times each of the unique values comes up in the
  160. original array. Only provided if `return_counts` is True.
  161. See Also
  162. --------
  163. repeat : Repeat elements of an array.
  164. sort : Return a sorted copy of an array.
  165. Notes
  166. -----
  167. When an axis is specified the subarrays indexed by the axis are sorted.
  168. This is done by making the specified axis the first dimension of the array
  169. (move the axis to the first dimension to keep the order of the other axes)
  170. and then flattening the subarrays in C order. The flattened subarrays are
  171. then viewed as a structured type with each element given a label, with the
  172. effect that we end up with a 1-D array of structured types that can be
  173. treated in the same way as any other 1-D array. The result is that the
  174. flattened subarrays are sorted in lexicographic order starting with the
  175. first element.
  176. .. versionchanged:: 1.21
  177. Like np.sort, NaN will sort to the end of the values.
  178. For complex arrays all NaN values are considered equivalent
  179. (no matter whether the NaN is in the real or imaginary part).
  180. As the representant for the returned array the smallest one in the
  181. lexicographical order is chosen - see np.sort for how the lexicographical
  182. order is defined for complex arrays.
  183. .. versionchanged:: 2.0
  184. For multi-dimensional inputs, ``unique_inverse`` is reshaped
  185. such that the input can be reconstructed using
  186. ``np.take(unique, unique_inverse, axis=axis)``. The result is
  187. now not 1-dimensional when ``axis=None``.
  188. Note that in NumPy 2.0.0 a higher dimensional array was returned also
  189. when ``axis`` was not ``None``. This was reverted, but
  190. ``inverse.reshape(-1)`` can be used to ensure compatibility with both
  191. versions.
  192. Examples
  193. --------
  194. >>> import numpy as np
  195. >>> np.unique([1, 1, 2, 2, 3, 3])
  196. array([1, 2, 3])
  197. >>> a = np.array([[1, 1], [2, 3]])
  198. >>> np.unique(a)
  199. array([1, 2, 3])
  200. Return the unique rows of a 2D array
  201. >>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
  202. >>> np.unique(a, axis=0)
  203. array([[1, 0, 0], [2, 3, 4]])
  204. Return the indices of the original array that give the unique values:
  205. >>> a = np.array(['a', 'b', 'b', 'c', 'a'])
  206. >>> u, indices = np.unique(a, return_index=True)
  207. >>> u
  208. array(['a', 'b', 'c'], dtype='<U1')
  209. >>> indices
  210. array([0, 1, 3])
  211. >>> a[indices]
  212. array(['a', 'b', 'c'], dtype='<U1')
  213. Reconstruct the input array from the unique values and inverse:
  214. >>> a = np.array([1, 2, 6, 4, 2, 3, 2])
  215. >>> u, indices = np.unique(a, return_inverse=True)
  216. >>> u
  217. array([1, 2, 3, 4, 6])
  218. >>> indices
  219. array([0, 1, 4, 3, 1, 2, 1])
  220. >>> u[indices]
  221. array([1, 2, 6, 4, 2, 3, 2])
  222. Reconstruct the input values from the unique values and counts:
  223. >>> a = np.array([1, 2, 6, 4, 2, 3, 2])
  224. >>> values, counts = np.unique(a, return_counts=True)
  225. >>> values
  226. array([1, 2, 3, 4, 6])
  227. >>> counts
  228. array([1, 3, 1, 1, 1])
  229. >>> np.repeat(values, counts)
  230. array([1, 2, 2, 2, 3, 4, 6]) # original order not preserved
  231. """
  232. ar = np.asanyarray(ar)
  233. if axis is None or ar.ndim == 1:
  234. if axis is not None:
  235. normalize_axis_index(axis, ar.ndim)
  236. ret = _unique1d(ar, return_index, return_inverse, return_counts,
  237. equal_nan=equal_nan, inverse_shape=ar.shape, axis=None,
  238. sorted=sorted)
  239. return _unpack_tuple(ret)
  240. # axis was specified and not None
  241. try:
  242. ar = np.moveaxis(ar, axis, 0)
  243. except np.exceptions.AxisError:
  244. # this removes the "axis1" or "axis2" prefix from the error message
  245. raise np.exceptions.AxisError(axis, ar.ndim) from None
  246. inverse_shape = [1] * ar.ndim
  247. inverse_shape[axis] = ar.shape[0]
  248. # Must reshape to a contiguous 2D array for this to work...
  249. orig_shape, orig_dtype = ar.shape, ar.dtype
  250. ar = ar.reshape(orig_shape[0], np.prod(orig_shape[1:], dtype=np.intp))
  251. ar = np.ascontiguousarray(ar)
  252. dtype = [(f'f{i}', ar.dtype) for i in range(ar.shape[1])]
  253. # At this point, `ar` has shape `(n, m)`, and `dtype` is a structured
  254. # data type with `m` fields where each field has the data type of `ar`.
  255. # In the following, we create the array `consolidated`, which has
  256. # shape `(n,)` with data type `dtype`.
  257. try:
  258. if ar.shape[1] > 0:
  259. consolidated = ar.view(dtype)
  260. else:
  261. # If ar.shape[1] == 0, then dtype will be `np.dtype([])`, which is
  262. # a data type with itemsize 0, and the call `ar.view(dtype)` will
  263. # fail. Instead, we'll use `np.empty` to explicitly create the
  264. # array with shape `(len(ar),)`. Because `dtype` in this case has
  265. # itemsize 0, the total size of the result is still 0 bytes.
  266. consolidated = np.empty(len(ar), dtype=dtype)
  267. except TypeError as e:
  268. # There's no good way to do this for object arrays, etc...
  269. msg = 'The axis argument to unique is not supported for dtype {dt}'
  270. raise TypeError(msg.format(dt=ar.dtype)) from e
  271. def reshape_uniq(uniq):
  272. n = len(uniq)
  273. uniq = uniq.view(orig_dtype)
  274. uniq = uniq.reshape(n, *orig_shape[1:])
  275. uniq = np.moveaxis(uniq, 0, axis)
  276. return uniq
  277. output = _unique1d(consolidated, return_index,
  278. return_inverse, return_counts,
  279. equal_nan=equal_nan, inverse_shape=inverse_shape,
  280. axis=axis, sorted=sorted)
  281. output = (reshape_uniq(output[0]),) + output[1:]
  282. return _unpack_tuple(output)
  283. def _unique1d(ar, return_index=False, return_inverse=False,
  284. return_counts=False, *, equal_nan=True, inverse_shape=None,
  285. axis=None, sorted=True):
  286. """
  287. Find the unique elements of an array, ignoring shape.
  288. Uses a hash table to find the unique elements if possible.
  289. """
  290. ar = np.asanyarray(ar).flatten()
  291. if len(ar.shape) != 1:
  292. # np.matrix, and maybe some other array subclasses, insist on keeping
  293. # two dimensions for all operations. Coerce to an ndarray in such cases.
  294. ar = np.asarray(ar).flatten()
  295. optional_indices = return_index or return_inverse
  296. # masked arrays are not supported yet.
  297. if not optional_indices and not return_counts and not np.ma.is_masked(ar):
  298. # First we convert the array to a numpy array, later we wrap it back
  299. # in case it was a subclass of numpy.ndarray.
  300. conv = _array_converter(ar)
  301. ar_, = conv
  302. if (hash_unique := _unique_hash(ar_, equal_nan=equal_nan)) \
  303. is not NotImplemented:
  304. if sorted:
  305. hash_unique.sort()
  306. # We wrap the result back in case it was a subclass of numpy.ndarray.
  307. return (conv.wrap(hash_unique),)
  308. # If we don't use the hash map, we use the slower sorting method.
  309. if optional_indices:
  310. perm = ar.argsort(kind='mergesort' if return_index else 'quicksort')
  311. aux = ar[perm]
  312. else:
  313. ar.sort()
  314. aux = ar
  315. mask = np.empty(aux.shape, dtype=np.bool)
  316. mask[:1] = True
  317. if (equal_nan and aux.shape[0] > 0 and aux.dtype.kind in "cfmM" and
  318. np.isnan(aux[-1])):
  319. if aux.dtype.kind == "c": # for complex all NaNs are considered equivalent
  320. aux_firstnan = np.searchsorted(np.isnan(aux), True, side='left')
  321. else:
  322. aux_firstnan = np.searchsorted(aux, aux[-1], side='left')
  323. if aux_firstnan > 0:
  324. mask[1:aux_firstnan] = (
  325. aux[1:aux_firstnan] != aux[:aux_firstnan - 1])
  326. mask[aux_firstnan] = True
  327. mask[aux_firstnan + 1:] = False
  328. else:
  329. mask[1:] = aux[1:] != aux[:-1]
  330. ret = (aux[mask],)
  331. if return_index:
  332. ret += (perm[mask],)
  333. if return_inverse:
  334. imask = np.cumsum(mask) - 1
  335. inv_idx = np.empty(mask.shape, dtype=np.intp)
  336. inv_idx[perm] = imask
  337. ret += (inv_idx.reshape(inverse_shape) if axis is None else inv_idx,)
  338. if return_counts:
  339. idx = np.concatenate(np.nonzero(mask) + ([mask.size],))
  340. ret += (np.diff(idx),)
  341. return ret
  342. # Array API set functions
  343. class UniqueAllResult(NamedTuple):
  344. values: np.ndarray
  345. indices: np.ndarray
  346. inverse_indices: np.ndarray
  347. counts: np.ndarray
  348. class UniqueCountsResult(NamedTuple):
  349. values: np.ndarray
  350. counts: np.ndarray
  351. class UniqueInverseResult(NamedTuple):
  352. values: np.ndarray
  353. inverse_indices: np.ndarray
  354. def _unique_all_dispatcher(x, /):
  355. return (x,)
  356. @array_function_dispatch(_unique_all_dispatcher)
  357. def unique_all(x):
  358. """
  359. Find the unique elements of an array, and counts, inverse, and indices.
  360. This function is an Array API compatible alternative to::
  361. np.unique(x, return_index=True, return_inverse=True,
  362. return_counts=True, equal_nan=False, sorted=False)
  363. but returns a namedtuple for easier access to each output.
  364. .. note::
  365. This function currently always returns a sorted result, however,
  366. this could change in any NumPy minor release.
  367. Parameters
  368. ----------
  369. x : array_like
  370. Input array. It will be flattened if it is not already 1-D.
  371. Returns
  372. -------
  373. out : namedtuple
  374. The result containing:
  375. * values - The unique elements of an input array.
  376. * indices - The first occurring indices for each unique element.
  377. * inverse_indices - The indices from the set of unique elements
  378. that reconstruct `x`.
  379. * counts - The corresponding counts for each unique element.
  380. See Also
  381. --------
  382. unique : Find the unique elements of an array.
  383. Examples
  384. --------
  385. >>> import numpy as np
  386. >>> x = [1, 1, 2]
  387. >>> uniq = np.unique_all(x)
  388. >>> uniq.values
  389. array([1, 2])
  390. >>> uniq.indices
  391. array([0, 2])
  392. >>> uniq.inverse_indices
  393. array([0, 0, 1])
  394. >>> uniq.counts
  395. array([2, 1])
  396. """
  397. result = unique(
  398. x,
  399. return_index=True,
  400. return_inverse=True,
  401. return_counts=True,
  402. equal_nan=False,
  403. )
  404. return UniqueAllResult(*result)
  405. def _unique_counts_dispatcher(x, /):
  406. return (x,)
  407. @array_function_dispatch(_unique_counts_dispatcher)
  408. def unique_counts(x):
  409. """
  410. Find the unique elements and counts of an input array `x`.
  411. This function is an Array API compatible alternative to::
  412. np.unique(x, return_counts=True, equal_nan=False, sorted=False)
  413. but returns a namedtuple for easier access to each output.
  414. .. note::
  415. This function currently always returns a sorted result, however,
  416. this could change in any NumPy minor release.
  417. Parameters
  418. ----------
  419. x : array_like
  420. Input array. It will be flattened if it is not already 1-D.
  421. Returns
  422. -------
  423. out : namedtuple
  424. The result containing:
  425. * values - The unique elements of an input array.
  426. * counts - The corresponding counts for each unique element.
  427. See Also
  428. --------
  429. unique : Find the unique elements of an array.
  430. Examples
  431. --------
  432. >>> import numpy as np
  433. >>> x = [1, 1, 2]
  434. >>> uniq = np.unique_counts(x)
  435. >>> uniq.values
  436. array([1, 2])
  437. >>> uniq.counts
  438. array([2, 1])
  439. """
  440. result = unique(
  441. x,
  442. return_index=False,
  443. return_inverse=False,
  444. return_counts=True,
  445. equal_nan=False,
  446. )
  447. return UniqueCountsResult(*result)
  448. def _unique_inverse_dispatcher(x, /):
  449. return (x,)
  450. @array_function_dispatch(_unique_inverse_dispatcher)
  451. def unique_inverse(x):
  452. """
  453. Find the unique elements of `x` and indices to reconstruct `x`.
  454. This function is an Array API compatible alternative to::
  455. np.unique(x, return_inverse=True, equal_nan=False, sorted=False)
  456. but returns a namedtuple for easier access to each output.
  457. .. note::
  458. This function currently always returns a sorted result, however,
  459. this could change in any NumPy minor release.
  460. Parameters
  461. ----------
  462. x : array_like
  463. Input array. It will be flattened if it is not already 1-D.
  464. Returns
  465. -------
  466. out : namedtuple
  467. The result containing:
  468. * values - The unique elements of an input array.
  469. * inverse_indices - The indices from the set of unique elements
  470. that reconstruct `x`.
  471. See Also
  472. --------
  473. unique : Find the unique elements of an array.
  474. Examples
  475. --------
  476. >>> import numpy as np
  477. >>> x = [1, 1, 2]
  478. >>> uniq = np.unique_inverse(x)
  479. >>> uniq.values
  480. array([1, 2])
  481. >>> uniq.inverse_indices
  482. array([0, 0, 1])
  483. """
  484. result = unique(
  485. x,
  486. return_index=False,
  487. return_inverse=True,
  488. return_counts=False,
  489. equal_nan=False,
  490. )
  491. return UniqueInverseResult(*result)
  492. def _unique_values_dispatcher(x, /):
  493. return (x,)
  494. @array_function_dispatch(_unique_values_dispatcher)
  495. def unique_values(x):
  496. """
  497. Returns the unique elements of an input array `x`.
  498. This function is an Array API compatible alternative to::
  499. np.unique(x, equal_nan=False, sorted=False)
  500. .. versionchanged:: 2.3
  501. The algorithm was changed to a faster one that does not rely on
  502. sorting, and hence the results are no longer implicitly sorted.
  503. Parameters
  504. ----------
  505. x : array_like
  506. Input array. It will be flattened if it is not already 1-D.
  507. Returns
  508. -------
  509. out : ndarray
  510. The unique elements of an input array.
  511. See Also
  512. --------
  513. unique : Find the unique elements of an array.
  514. Examples
  515. --------
  516. >>> import numpy as np
  517. >>> np.unique_values([1, 1, 2])
  518. array([1, 2]) # may vary
  519. """
  520. return unique(
  521. x,
  522. return_index=False,
  523. return_inverse=False,
  524. return_counts=False,
  525. equal_nan=False,
  526. sorted=False,
  527. )
  528. def _intersect1d_dispatcher(
  529. ar1, ar2, assume_unique=None, return_indices=None):
  530. return (ar1, ar2)
  531. @array_function_dispatch(_intersect1d_dispatcher)
  532. def intersect1d(ar1, ar2, assume_unique=False, return_indices=False):
  533. """
  534. Find the intersection of two arrays.
  535. Return the sorted, unique values that are in both of the input arrays.
  536. Parameters
  537. ----------
  538. ar1, ar2 : array_like
  539. Input arrays. Will be flattened if not already 1D.
  540. assume_unique : bool
  541. If True, the input arrays are both assumed to be unique, which
  542. can speed up the calculation. If True but ``ar1`` or ``ar2`` are not
  543. unique, incorrect results and out-of-bounds indices could result.
  544. Default is False.
  545. return_indices : bool
  546. If True, the indices which correspond to the intersection of the two
  547. arrays are returned. The first instance of a value is used if there are
  548. multiple. Default is False.
  549. Returns
  550. -------
  551. intersect1d : ndarray
  552. Sorted 1D array of common and unique elements.
  553. comm1 : ndarray
  554. The indices of the first occurrences of the common values in `ar1`.
  555. Only provided if `return_indices` is True.
  556. comm2 : ndarray
  557. The indices of the first occurrences of the common values in `ar2`.
  558. Only provided if `return_indices` is True.
  559. Examples
  560. --------
  561. >>> import numpy as np
  562. >>> np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1])
  563. array([1, 3])
  564. To intersect more than two arrays, use functools.reduce:
  565. >>> from functools import reduce
  566. >>> reduce(np.intersect1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))
  567. array([3])
  568. To return the indices of the values common to the input arrays
  569. along with the intersected values:
  570. >>> x = np.array([1, 1, 2, 3, 4])
  571. >>> y = np.array([2, 1, 4, 6])
  572. >>> xy, x_ind, y_ind = np.intersect1d(x, y, return_indices=True)
  573. >>> x_ind, y_ind
  574. (array([0, 2, 4]), array([1, 0, 2]))
  575. >>> xy, x[x_ind], y[y_ind]
  576. (array([1, 2, 4]), array([1, 2, 4]), array([1, 2, 4]))
  577. """
  578. ar1 = np.asanyarray(ar1)
  579. ar2 = np.asanyarray(ar2)
  580. if not assume_unique:
  581. if return_indices:
  582. ar1, ind1 = unique(ar1, return_index=True)
  583. ar2, ind2 = unique(ar2, return_index=True)
  584. else:
  585. ar1 = unique(ar1)
  586. ar2 = unique(ar2)
  587. else:
  588. ar1 = ar1.ravel()
  589. ar2 = ar2.ravel()
  590. aux = np.concatenate((ar1, ar2))
  591. if return_indices:
  592. aux_sort_indices = np.argsort(aux, kind='mergesort')
  593. aux = aux[aux_sort_indices]
  594. else:
  595. aux.sort()
  596. mask = aux[1:] == aux[:-1]
  597. int1d = aux[:-1][mask]
  598. if return_indices:
  599. ar1_indices = aux_sort_indices[:-1][mask]
  600. ar2_indices = aux_sort_indices[1:][mask] - ar1.size
  601. if not assume_unique:
  602. ar1_indices = ind1[ar1_indices]
  603. ar2_indices = ind2[ar2_indices]
  604. return int1d, ar1_indices, ar2_indices
  605. else:
  606. return int1d
  607. def _setxor1d_dispatcher(ar1, ar2, assume_unique=None):
  608. return (ar1, ar2)
  609. @array_function_dispatch(_setxor1d_dispatcher)
  610. def setxor1d(ar1, ar2, assume_unique=False):
  611. """
  612. Find the set exclusive-or of two arrays.
  613. Return the sorted, unique values that are in only one (not both) of the
  614. input arrays.
  615. Parameters
  616. ----------
  617. ar1, ar2 : array_like
  618. Input arrays.
  619. assume_unique : bool
  620. If True, the input arrays are both assumed to be unique, which
  621. can speed up the calculation. Default is False.
  622. Returns
  623. -------
  624. setxor1d : ndarray
  625. Sorted 1D array of unique values that are in only one of the input
  626. arrays.
  627. Examples
  628. --------
  629. >>> import numpy as np
  630. >>> a = np.array([1, 2, 3, 2, 4])
  631. >>> b = np.array([2, 3, 5, 7, 5])
  632. >>> np.setxor1d(a,b)
  633. array([1, 4, 5, 7])
  634. """
  635. if not assume_unique:
  636. ar1 = unique(ar1)
  637. ar2 = unique(ar2)
  638. aux = np.concatenate((ar1, ar2), axis=None)
  639. if aux.size == 0:
  640. return aux
  641. aux.sort()
  642. flag = np.concatenate(([True], aux[1:] != aux[:-1], [True]))
  643. return aux[flag[1:] & flag[:-1]]
  644. def _isin(ar1, ar2, assume_unique=False, invert=False, *, kind=None):
  645. # Ravel both arrays, behavior for the first array could be different
  646. ar1 = np.asarray(ar1).ravel()
  647. ar2 = np.asarray(ar2).ravel()
  648. # Ensure that iteration through object arrays yields size-1 arrays
  649. if ar2.dtype == object:
  650. ar2 = ar2.reshape(-1, 1)
  651. if kind not in {None, 'sort', 'table'}:
  652. raise ValueError(
  653. f"Invalid kind: '{kind}'. Please use None, 'sort' or 'table'.")
  654. # Can use the table method if all arrays are integers or boolean:
  655. is_int_arrays = all(ar.dtype.kind in ("u", "i", "b") for ar in (ar1, ar2))
  656. use_table_method = is_int_arrays and kind in {None, 'table'}
  657. if use_table_method:
  658. if ar2.size == 0:
  659. if invert:
  660. return np.ones_like(ar1, dtype=bool)
  661. else:
  662. return np.zeros_like(ar1, dtype=bool)
  663. # Convert booleans to uint8 so we can use the fast integer algorithm
  664. if ar1.dtype == bool:
  665. ar1 = ar1.astype(np.uint8)
  666. if ar2.dtype == bool:
  667. ar2 = ar2.astype(np.uint8)
  668. ar2_min = int(np.min(ar2))
  669. ar2_max = int(np.max(ar2))
  670. ar2_range = ar2_max - ar2_min
  671. # Constraints on whether we can actually use the table method:
  672. # 1. Assert memory usage is not too large
  673. below_memory_constraint = ar2_range <= 6 * (ar1.size + ar2.size)
  674. # 2. Check overflows for (ar2 - ar2_min); dtype=ar2.dtype
  675. range_safe_from_overflow = ar2_range <= np.iinfo(ar2.dtype).max
  676. # Optimal performance is for approximately
  677. # log10(size) > (log10(range) - 2.27) / 0.927.
  678. # However, here we set the requirement that by default
  679. # the intermediate array can only be 6x
  680. # the combined memory allocation of the original
  681. # arrays. See discussion on
  682. # https://github.com/numpy/numpy/pull/12065.
  683. if (
  684. range_safe_from_overflow and
  685. (below_memory_constraint or kind == 'table')
  686. ):
  687. if invert:
  688. outgoing_array = np.ones_like(ar1, dtype=bool)
  689. else:
  690. outgoing_array = np.zeros_like(ar1, dtype=bool)
  691. # Make elements 1 where the integer exists in ar2
  692. if invert:
  693. isin_helper_ar = np.ones(ar2_range + 1, dtype=bool)
  694. isin_helper_ar[ar2 - ar2_min] = 0
  695. else:
  696. isin_helper_ar = np.zeros(ar2_range + 1, dtype=bool)
  697. isin_helper_ar[ar2 - ar2_min] = 1
  698. # Mask out elements we know won't work
  699. basic_mask = (ar1 <= ar2_max) & (ar1 >= ar2_min)
  700. in_range_ar1 = ar1[basic_mask]
  701. if in_range_ar1.size == 0:
  702. # Nothing more to do, since all values are out of range.
  703. return outgoing_array
  704. # Unfortunately, ar2_min can be out of range for `intp` even
  705. # if the calculation result must fit in range (and be positive).
  706. # In that case, use ar2.dtype which must work for all unmasked
  707. # values.
  708. try:
  709. ar2_min = np.array(ar2_min, dtype=np.intp)
  710. dtype = np.intp
  711. except OverflowError:
  712. dtype = ar2.dtype
  713. out = np.empty_like(in_range_ar1, dtype=np.intp)
  714. outgoing_array[basic_mask] = isin_helper_ar[
  715. np.subtract(in_range_ar1, ar2_min, dtype=dtype,
  716. out=out, casting="unsafe")]
  717. return outgoing_array
  718. elif kind == 'table': # not range_safe_from_overflow
  719. raise RuntimeError(
  720. "You have specified kind='table', "
  721. "but the range of values in `ar2` or `ar1` exceed the "
  722. "maximum integer of the datatype. "
  723. "Please set `kind` to None or 'sort'."
  724. )
  725. elif kind == 'table':
  726. raise ValueError(
  727. "The 'table' method is only "
  728. "supported for boolean or integer arrays. "
  729. "Please select 'sort' or None for kind."
  730. )
  731. # Check if one of the arrays may contain arbitrary objects
  732. contains_object = ar1.dtype.hasobject or ar2.dtype.hasobject
  733. # This code is run when
  734. # a) the first condition is true, making the code significantly faster
  735. # b) the second condition is true (i.e. `ar1` or `ar2` may contain
  736. # arbitrary objects), since then sorting is not guaranteed to work
  737. if len(ar2) < 10 * len(ar1) ** 0.145 or contains_object:
  738. if invert:
  739. mask = np.ones(len(ar1), dtype=bool)
  740. for a in ar2:
  741. mask &= (ar1 != a)
  742. else:
  743. mask = np.zeros(len(ar1), dtype=bool)
  744. for a in ar2:
  745. mask |= (ar1 == a)
  746. return mask
  747. # Otherwise use sorting
  748. if not assume_unique:
  749. ar1, rev_idx = np.unique(ar1, return_inverse=True)
  750. ar2 = np.unique(ar2)
  751. ar = np.concatenate((ar1, ar2))
  752. # We need this to be a stable sort, so always use 'mergesort'
  753. # here. The values from the first array should always come before
  754. # the values from the second array.
  755. order = ar.argsort(kind='mergesort')
  756. sar = ar[order]
  757. if invert:
  758. bool_ar = (sar[1:] != sar[:-1])
  759. else:
  760. bool_ar = (sar[1:] == sar[:-1])
  761. flag = np.concatenate((bool_ar, [invert]))
  762. ret = np.empty(ar.shape, dtype=bool)
  763. ret[order] = flag
  764. if assume_unique:
  765. return ret[:len(ar1)]
  766. else:
  767. return ret[rev_idx]
  768. def _isin_dispatcher(element, test_elements, assume_unique=None, invert=None,
  769. *, kind=None):
  770. return (element, test_elements)
  771. @array_function_dispatch(_isin_dispatcher)
  772. def isin(element, test_elements, assume_unique=False, invert=False, *,
  773. kind=None):
  774. """
  775. Calculates ``element in test_elements``, broadcasting over `element` only.
  776. Returns a boolean array of the same shape as `element` that is True
  777. where an element of `element` is in `test_elements` and False otherwise.
  778. Parameters
  779. ----------
  780. element : array_like
  781. Input array.
  782. test_elements : array_like
  783. The values against which to test each value of `element`.
  784. This argument is flattened if it is an array or array_like.
  785. See notes for behavior with non-array-like parameters.
  786. assume_unique : bool, optional
  787. If True, the input arrays are both assumed to be unique, which
  788. can speed up the calculation. Default is False.
  789. invert : bool, optional
  790. If True, the values in the returned array are inverted, as if
  791. calculating `element not in test_elements`. Default is False.
  792. ``np.isin(a, b, invert=True)`` is equivalent to (but faster
  793. than) ``np.invert(np.isin(a, b))``.
  794. kind : {None, 'sort', 'table'}, optional
  795. The algorithm to use. This will not affect the final result,
  796. but will affect the speed and memory use. The default, None,
  797. will select automatically based on memory considerations.
  798. * If 'sort', will use a mergesort-based approach. This will have
  799. a memory usage of roughly 6 times the sum of the sizes of
  800. `element` and `test_elements`, not accounting for size of dtypes.
  801. * If 'table', will use a lookup table approach similar
  802. to a counting sort. This is only available for boolean and
  803. integer arrays. This will have a memory usage of the
  804. size of `element` plus the max-min value of `test_elements`.
  805. `assume_unique` has no effect when the 'table' option is used.
  806. * If None, will automatically choose 'table' if
  807. the required memory allocation is less than or equal to
  808. 6 times the sum of the sizes of `element` and `test_elements`,
  809. otherwise will use 'sort'. This is done to not use
  810. a large amount of memory by default, even though
  811. 'table' may be faster in most cases. If 'table' is chosen,
  812. `assume_unique` will have no effect.
  813. Returns
  814. -------
  815. isin : ndarray, bool
  816. Has the same shape as `element`. The values `element[isin]`
  817. are in `test_elements`.
  818. Notes
  819. -----
  820. `isin` is an element-wise function version of the python keyword `in`.
  821. ``isin(a, b)`` is roughly equivalent to
  822. ``np.array([item in b for item in a])`` if `a` and `b` are 1-D sequences.
  823. `element` and `test_elements` are converted to arrays if they are not
  824. already. If `test_elements` is a set (or other non-sequence collection)
  825. it will be converted to an object array with one element, rather than an
  826. array of the values contained in `test_elements`. This is a consequence
  827. of the `array` constructor's way of handling non-sequence collections.
  828. Converting the set to a list usually gives the desired behavior.
  829. Using ``kind='table'`` tends to be faster than `kind='sort'` if the
  830. following relationship is true:
  831. ``log10(len(test_elements)) >
  832. (log10(max(test_elements)-min(test_elements)) - 2.27) / 0.927``,
  833. but may use greater memory. The default value for `kind` will
  834. be automatically selected based only on memory usage, so one may
  835. manually set ``kind='table'`` if memory constraints can be relaxed.
  836. Examples
  837. --------
  838. >>> import numpy as np
  839. >>> element = 2*np.arange(4).reshape((2, 2))
  840. >>> element
  841. array([[0, 2],
  842. [4, 6]])
  843. >>> test_elements = [1, 2, 4, 8]
  844. >>> mask = np.isin(element, test_elements)
  845. >>> mask
  846. array([[False, True],
  847. [ True, False]])
  848. >>> element[mask]
  849. array([2, 4])
  850. The indices of the matched values can be obtained with `nonzero`:
  851. >>> np.nonzero(mask)
  852. (array([0, 1]), array([1, 0]))
  853. The test can also be inverted:
  854. >>> mask = np.isin(element, test_elements, invert=True)
  855. >>> mask
  856. array([[ True, False],
  857. [False, True]])
  858. >>> element[mask]
  859. array([0, 6])
  860. Because of how `array` handles sets, the following does not
  861. work as expected:
  862. >>> test_set = {1, 2, 4, 8}
  863. >>> np.isin(element, test_set)
  864. array([[False, False],
  865. [False, False]])
  866. Casting the set to a list gives the expected result:
  867. >>> np.isin(element, list(test_set))
  868. array([[False, True],
  869. [ True, False]])
  870. """
  871. element = np.asarray(element)
  872. return _isin(element, test_elements, assume_unique=assume_unique,
  873. invert=invert, kind=kind).reshape(element.shape)
  874. def _union1d_dispatcher(ar1, ar2):
  875. return (ar1, ar2)
  876. @array_function_dispatch(_union1d_dispatcher)
  877. def union1d(ar1, ar2):
  878. """
  879. Find the union of two arrays.
  880. Return the unique, sorted array of values that are in either of the two
  881. input arrays.
  882. Parameters
  883. ----------
  884. ar1, ar2 : array_like
  885. Input arrays. They are flattened if they are not already 1D.
  886. Returns
  887. -------
  888. union1d : ndarray
  889. Unique, sorted union of the input arrays.
  890. Examples
  891. --------
  892. >>> import numpy as np
  893. >>> np.union1d([-1, 0, 1], [-2, 0, 2])
  894. array([-2, -1, 0, 1, 2])
  895. To find the union of more than two arrays, use functools.reduce:
  896. >>> from functools import reduce
  897. >>> reduce(np.union1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))
  898. array([1, 2, 3, 4, 6])
  899. """
  900. return unique(np.concatenate((ar1, ar2), axis=None))
  901. def _setdiff1d_dispatcher(ar1, ar2, assume_unique=None):
  902. return (ar1, ar2)
  903. @array_function_dispatch(_setdiff1d_dispatcher)
  904. def setdiff1d(ar1, ar2, assume_unique=False):
  905. """
  906. Find the set difference of two arrays.
  907. Return the unique values in `ar1` that are not in `ar2`.
  908. Parameters
  909. ----------
  910. ar1 : array_like
  911. Input array.
  912. ar2 : array_like
  913. Input comparison array.
  914. assume_unique : bool
  915. If True, the input arrays are both assumed to be unique, which
  916. can speed up the calculation. Default is False.
  917. Returns
  918. -------
  919. setdiff1d : ndarray
  920. 1D array of values in `ar1` that are not in `ar2`. The result
  921. is sorted when `assume_unique=False`, but otherwise only sorted
  922. if the input is sorted.
  923. Examples
  924. --------
  925. >>> import numpy as np
  926. >>> a = np.array([1, 2, 3, 2, 4, 1])
  927. >>> b = np.array([3, 4, 5, 6])
  928. >>> np.setdiff1d(a, b)
  929. array([1, 2])
  930. """
  931. if assume_unique:
  932. ar1 = np.asarray(ar1).ravel()
  933. else:
  934. ar1 = unique(ar1)
  935. ar2 = unique(ar2)
  936. return ar1[_isin(ar1, ar2, assume_unique=True, invert=True)]