| 804 | |
| 805 | |
| 806 | def _isin(ar1, ar2, assume_unique=False, invert=False, *, kind=None): |
| 807 | # Ravel both arrays, behavior for the first array could be different |
| 808 | ar1 = np.asarray(ar1).ravel() |
| 809 | ar2 = np.asarray(ar2).ravel() |
| 810 | |
| 811 | # Ensure that iteration through object arrays yields size-1 arrays |
| 812 | if ar2.dtype == object: |
| 813 | ar2 = ar2.reshape(-1, 1) |
| 814 | |
| 815 | if kind not in {None, 'sort', 'table'}: |
| 816 | raise ValueError( |
| 817 | f"Invalid kind: '{kind}'. Please use None, 'sort' or 'table'.") |
| 818 | |
| 819 | # Can use the table method if all arrays are integers or boolean: |
| 820 | is_int_arrays = all(ar.dtype.kind in ("u", "i", "b") for ar in (ar1, ar2)) |
| 821 | use_table_method = is_int_arrays and kind in {None, 'table'} |
| 822 | |
| 823 | if use_table_method: |
| 824 | if ar2.size == 0: |
| 825 | if invert: |
| 826 | return np.ones_like(ar1, dtype=bool) |
| 827 | else: |
| 828 | return np.zeros_like(ar1, dtype=bool) |
| 829 | |
| 830 | # Convert booleans to uint8 so we can use the fast integer algorithm |
| 831 | if ar1.dtype == bool: |
| 832 | ar1 = ar1.astype(np.uint8) |
| 833 | if ar2.dtype == bool: |
| 834 | ar2 = ar2.astype(np.uint8) |
| 835 | |
| 836 | ar2_min = int(np.min(ar2)) |
| 837 | ar2_max = int(np.max(ar2)) |
| 838 | |
| 839 | ar2_range = ar2_max - ar2_min |
| 840 | |
| 841 | # Constraints on whether we can actually use the table method: |
| 842 | # 1. Assert memory usage is not too large |
| 843 | below_memory_constraint = ar2_range <= 6 * (ar1.size + ar2.size) |
| 844 | # 2. Check overflows for (ar2 - ar2_min); dtype=ar2.dtype |
| 845 | range_safe_from_overflow = ar2_range <= np.iinfo(ar2.dtype).max |
| 846 | |
| 847 | # Optimal performance is for approximately |
| 848 | # log10(size) > (log10(range) - 2.27) / 0.927. |
| 849 | # However, here we set the requirement that by default |
| 850 | # the intermediate array can only be 6x |
| 851 | # the combined memory allocation of the original |
| 852 | # arrays. See discussion on |
| 853 | # https://github.com/numpy/numpy/pull/12065. |
| 854 | |
| 855 | if ( |
| 856 | range_safe_from_overflow and |
| 857 | (below_memory_constraint or kind == 'table') |
| 858 | ): |
| 859 | |
| 860 | if invert: |
| 861 | outgoing_array = np.ones_like(ar1, dtype=bool) |
| 862 | else: |
| 863 | outgoing_array = np.zeros_like(ar1, dtype=bool) |