GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — numpy/numpy/lib/_function_base_impl.py at main · numpy/numpy Expand file tree/ Copy path_function_base_impl.pyMore file actions 5844 lines (4901 loc) · 193 KB / Copy path_function_base_impl.pyFile metadata and controls5844 lines (4901 loc) · 193 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 import builtins import collections.abc import functools import math import operator import re import warnings import numpy as np import numpy._core.numeric as _nx from numpy._core import overrides, transpose from numpy._core._multiarray_umath import _array_converter from numpy._core.fromnumeric import any, mean, nonzero, partition, ravel, sum from numpy._core.multiarray import ( _place, bincount, interp as compiled_interp, interp_complex as compiled_interp_complex, normalize_axis_index, ) from numpy._core.numeric import ( absolute, arange, array, asanyarray, asarray, concatenate, dot, empty, integer, intp, isscalar, ndarray, ones, take, where, zeros_like, ) from numpy._core.numerictypes import typecodes from numpy._core.umath import ( _unwrap, add, arctan2, cos, exp, floor, frompyfunc, less_equal, minimum, mod, not_equal, pi, sin, sqrt, subtract, ) from numpy._utils import set_module # needed in this module for compatibility from numpy.lib._histograms_impl import histogram, histogramdd # noqa: F401 from numpy.lib._twodim_base_impl import diag array_function_dispatch = functools.partial( overrides.array_function_dispatch, module='numpy') __all__ = [ 'select', 'piecewise', 'trim_zeros', 'copy', 'iterable', 'percentile', 'diff', 'gradient', 'angle', 'unwrap', 'sort_complex', 'flip', 'rot90', 'extract', 'place', 'vectorize', 'asarray_chkfinite', 'average', 'bincount', 'digitize', 'cov', 'corrcoef', 'median', 'sinc', 'hamming', 'hanning', 'bartlett', 'blackman', 'kaiser', 'trapezoid', 'i0', 'meshgrid', 'delete', 'insert', 'append', 'interp', 'quantile' ] # _QuantileMethods is a dictionary listing all the supported methods to # compute quantile/percentile. # # Below virtual_index refers to the index of the element where the percentile # would be found in the sorted sample. # When the sample contains exactly the percentile wanted, the virtual_index is # an integer to the index of this element. # When the percentile wanted is in between two elements, the virtual_index # is made of an integer part (a.k.a 'i' or 'left') and a fractional part # (a.k.a 'g' or 'gamma') # # Each method in _QuantileMethods has two properties # get_virtual_index : Callable # The function used to compute the virtual_index. # fix_gamma : Callable # A function used for discrete methods to force the index to a specific value. _QuantileMethods = { # --- HYNDMAN and FAN METHODS # Discrete methods 'inverted_cdf': { 'get_virtual_index': lambda n, quantiles: _inverted_cdf(n, quantiles), 'fix_gamma': None, # should never be called }, 'averaged_inverted_cdf': { 'get_virtual_index': lambda n, quantiles: (n * quantiles) - 1, 'fix_gamma': lambda gamma, _: _get_gamma_mask( shape=gamma.shape, default_value=1., conditioned_value=0.5, where=gamma == 0), }, 'closest_observation': { 'get_virtual_index': lambda n, quantiles: _closest_observation(n, quantiles), 'fix_gamma': None, # should never be called }, # Continuous methods 'interpolated_inverted_cdf': { 'get_virtual_index': lambda n, quantiles: _compute_virtual_index(n, quantiles, 0, 1), 'fix_gamma': lambda gamma, _: gamma, }, 'hazen': { 'get_virtual_index': lambda n, quantiles: _compute_virtual_index(n, quantiles, 0.5, 0.5), 'fix_gamma': lambda gamma, _: gamma, }, 'weibull': { 'get_virtual_index': lambda n, quantiles: _compute_virtual_index(n, quantiles, 0, 0), 'fix_gamma': lambda gamma, _: gamma, }, # Default method. # To avoid some rounding issues, `(n-1) * quantiles` is preferred to # `_compute_virtual_index(n, quantiles, 1, 1)`. # They are mathematically equivalent. 'linear': { 'get_virtual_index': lambda n, quantiles: (n - 1) * quantiles, 'fix_gamma': lambda gamma, _: gamma, }, 'median_unbiased': { 'get_virtual_index': lambda n, quantiles: _compute_virtual_index(n, quantiles, 1 / 3.0, 1 / 3.0), 'fix_gamma': lambda gamma, _: gamma, }, 'normal_unbiased': { 'get_virtual_index': lambda n, quantiles: _compute_virtual_index(n, quantiles, 3 / 8.0, 3 / 8.0), 'fix_gamma': lambda gamma, _: gamma, }, # --- OTHER METHODS 'lower': { 'get_virtual_index': lambda n, quantiles: np.floor( (n - 1) * quantiles).astype(np.intp), 'fix_gamma': None, # should never be called, index dtype is int }, 'higher': { 'get_virtual_index': lambda n, quantiles: np.ceil( (n - 1) * quantiles).astype(np.intp), 'fix_gamma': None, # should never be called, index dtype is int }, 'midpoint': { 'get_virtual_index': lambda n, quantiles: 0.5 * ( np.floor((n - 1) * quantiles) + np.ceil((n - 1) * quantiles)), 'fix_gamma': lambda gamma, index: _get_gamma_mask( shape=gamma.shape, default_value=0.5, conditioned_value=0., where=index % 1 == 0), }, 'nearest': { 'get_virtual_index': lambda n, quantiles: np.around( (n - 1) * quantiles).astype(np.intp), 'fix_gamma': None, # should never be called, index dtype is int }} def _rot90_dispatcher(m, k=None, axes=None): return (m,) @array_function_dispatch(_rot90_dispatcher) def rot90(m, k=1, axes=(0, 1)): """ Rotate an array by 90 degrees in the plane specified by axes. Rotation direction is from the first towards the second axis. This means for a 2D array with the default `k` and `axes`, the rotation will be counterclockwise. Parameters ---------- m : array_like Array of two or more dimensions. k : integer Number of times the array is rotated by 90 degrees. axes : (2,) array_like The array is rotated in the plane defined by the axes. Axes must be different. Returns ------- y : ndarray A rotated view of `m`. See Also -------- flip : Reverse the order of elements in an array along the given axis. fliplr : Flip an array horizontally. flipud : Flip an array vertically. Notes ----- ``rot90(m, k=1, axes=(1,0))`` is the reverse of ``rot90(m, k=1, axes=(0,1))`` ``rot90(m, k=1, axes=(1,0))`` is equivalent to ``rot90(m, k=-1, axes=(0,1))`` Examples -------- >>> import numpy as np >>> m = np.array([[1,2],[3,4]], int) >>> m array([[1, 2], [3, 4]]) >>> np.rot90(m) array([[2, 4], [1, 3]]) >>> np.rot90(m, 2) array([[4, 3], [2, 1]]) >>> m = np.arange(8).reshape((2,2,2)) >>> np.rot90(m, 1, (1,2)) array([[[1, 3], [0, 2]], [[5, 7], [4, 6]]]) """ axes = tuple(axes) if len(axes) != 2: raise ValueError("len(axes) must be 2.") m = asanyarray(m) if axes[0] == axes[1] or absolute(axes[0] - axes[1]) == m.ndim: raise ValueError("Axes must be different.") if (axes[0] >= m.ndim or axes[0] < -m.ndim or axes[1] >= m.ndim or axes[1] < -m.ndim): raise ValueError(f"Axes={axes} out of range for array of ndim={m.ndim}.") try: k = operator.index(k) except TypeError: # DEPRECATED 2026-04-27, NumPy 2.5 msg = (f"Passing a value for k ({k!r}) that is not an integer type has been " "deprecated in NumPy 2.5. The value will be cast to an integer. In " "the future this will be an error.") warnings.warn(msg, DeprecationWarning, stacklevel=2) k = int(k) k %= 4 if k == 0: return m[:] if k == 2: return flip(flip(m, axes[0]), axes[1]) axes_list = arange(0, m.ndim) (axes_list[axes[0]], axes_list[axes[1]]) = (axes_list[axes[1]], axes_list[axes[0]]) if k == 1: return transpose(flip(m, axes[1]), axes_list) else: # k == 3 return flip(transpose(m, axes_list), axes[1]) def _flip_dispatcher(m, axis=None): return (m,) @array_function_dispatch(_flip_dispatcher) def flip(m, axis=None): """ Reverse the order of elements in an array along the given axis. The shape of the array is preserved, but the elements are reordered. Parameters ---------- m : array_like Input array. axis : None or int or tuple of ints, optional Axis or axes along which to flip over. The default, axis=None, will flip over all of the axes of the input array. If axis is negative it counts from the last to the first axis. If axis is a tuple of ints, flipping is performed on all of the axes specified in the tuple. Returns ------- out : array_like A view of `m` with the entries of axis reversed. Since a view is returned, this operation is done in constant time. See Also -------- flipud : Flip an array vertically (axis=0). fliplr : Flip an array horizontally (axis=1). Notes ----- flip(m, 0) is equivalent to flipud(m). flip(m, 1) is equivalent to fliplr(m). flip(m, n) corresponds to ``m[...,::-1,...]`` with ``::-1`` at position n. flip(m) corresponds to ``m[::-1,::-1,...,::-1]`` with ``::-1`` at all positions. flip(m, (0, 1)) corresponds to ``m[::-1,::-1,...]`` with ``::-1`` at position 0 and position 1. Examples -------- >>> import numpy as np >>> A = np.arange(8).reshape((2,2,2)) >>> A array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> np.flip(A, 0) array([[[4, 5], [6, 7]], [[0, 1], [2, 3]]]) >>> np.flip(A, 1) array([[[2, 3], [0, 1]], [[6, 7], [4, 5]]]) >>> np.flip(A) array([[[7, 6], [5, 4]], [[3, 2], [1, 0]]]) >>> np.flip(A, (0, 2)) array([[[5, 4], [7, 6]], [[1, 0], [3, 2]]]) >>> rng = np.random.default_rng() >>> A = rng.normal(size=(3,4,5)) >>> np.all(np.flip(A,2) == A[:,:,::-1,...]) True """ if not hasattr(m, 'ndim'): m = asarray(m) if axis is None: indexer = (np.s_[::-1],) * m.ndim else: axis = _nx.normalize_axis_tuple(axis, m.ndim) indexer = [np.s_[:]] * m.ndim for ax in axis: indexer[ax] = np.s_[::-1] indexer = tuple(indexer) return m[indexer] @set_module('numpy') def iterable(y): """ Check whether or not an object can be iterated over. Parameters ---------- y : object Input object. Returns ------- b : bool Return ``True`` if the object has an iterator method or is a sequence and ``False`` otherwise. Examples -------- >>> import numpy as np >>> np.iterable([1, 2, 3]) True >>> np.iterable(2) False Notes ----- In most cases, the results of ``np.iterable(obj)`` are consistent with ``isinstance(obj, collections.abc.Iterable)``. One notable exception is the treatment of 0-dimensional arrays:: >>> from collections.abc import Iterable >>> a = np.array(1.0) # 0-dimensional numpy array >>> isinstance(a, Iterable) True >>> np.iterable(a) False """ try: iter(y) except TypeError: return False return True def _weights_are_valid(weights, a, axis): """Validate weights array. We assume, weights is not None. """ wgt = np.asanyarray(weights) # Sanity checks if a.shape != wgt.shape: if axis is None: raise TypeError( "Axis must be specified when shapes of a and weights " "differ.") if wgt.shape != tuple(a.shape[ax] for ax in axis): raise ValueError( "Shape of weights must be consistent with " "shape of a along specified axis.") # setup wgt to broadcast along axis wgt = wgt.transpose(np.argsort(axis)) wgt = wgt.reshape(tuple((s if ax in axis else 1) for ax, s in enumerate(a.shape))) return wgt def _average_dispatcher(a, axis=None, weights=None, returned=None, *, keepdims=None): return (a, weights) @array_function_dispatch(_average_dispatcher) def average(a, axis=None, weights=None, returned=False, *, keepdims=np._NoValue): """ Compute the weighted average along the specified axis. Parameters ---------- a : array_like Array containing data to be averaged. If `a` is not an array, a conversion is attempted. axis : None or int or tuple of ints, optional Axis or axes along which to average `a`. The default, `axis=None`, will average over all of the elements of the input array. If axis is negative it counts from the last to the first axis. If axis is a tuple of ints, averaging is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before. weights : array_like, optional An array of weights associated with the values in `a`. Each value in `a` contributes to the average according to its associated weight. The array of weights must be the same shape as `a` if no axis is specified, otherwise the weights must have dimensions and shape consistent with `a` along the specified axis. If `weights=None`, then all data in `a` are assumed to have a weight equal to one. The calculation is:: avg = sum(a * weights) / sum(weights) where the sum is over all included elements. The only constraint on the values of `weights` is that `sum(weights)` must not be 0. returned : bool, optional Default is `False`. If `True`, the tuple (`average`, `sum_of_weights`) is returned, otherwise only the average is returned. If `weights=None`, `sum_of_weights` is equivalent to the number of elements over which the average is taken. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original `a`. *Note:* `keepdims` will not work with instances of `numpy.matrix` or other classes whose methods do not support `keepdims`. .. versionadded:: 1.23.0 Returns ------- retval, [sum_of_weights] : array_type or double Return the average along the specified axis. When `returned` is `True`, return a tuple with the average as the first element and the sum of the weights as the second element. `sum_of_weights` is of the same type as `retval`. The result dtype follows a general pattern. If `weights` is None, the result dtype will be that of `a` , or ``float64`` if `a` is integral. Otherwise, if `weights` is not None and `a` is non- integral, the result type will be the type of lowest precision capable of representing values of both `a` and `weights`. If `a` happens to be integral, the previous rules still applies but the result dtype will at least be ``float64``. Raises ------ ZeroDivisionError When all weights along axis are zero. See `numpy.ma.average` for a version robust to this type of error. TypeError When `weights` does not have the same shape as `a`, and `axis=None`. ValueError When `weights` does not have dimensions and shape consistent with `a` along specified `axis`. See Also -------- mean ma.average : average for masked arrays -- useful if your data contains "missing" values numpy.result_type : Returns the type that results from applying the numpy type promotion rules to the arguments. Examples -------- >>> import numpy as np >>> data = np.arange(1, 5) >>> data array([1, 2, 3, 4]) >>> np.average(data) 2.5 >>> np.average(np.arange(1, 11), weights=np.arange(10, 0, -1)) 4.0 >>> data = np.arange(6).reshape((3, 2)) >>> data array([[0, 1], [2, 3], [4, 5]]) >>> np.average(data, axis=1, weights=[1./4, 3./4]) array([0.75, 2.75, 4.75]) >>> np.average(data, weights=[1./4, 3./4]) Traceback (most recent call last): ... TypeError: Axis must be specified when shapes of a and weights differ. With ``keepdims=True``, the following result has shape (3, 1). >>> np.average(data, axis=1, keepdims=True) array([[0.5], [2.5], [4.5]]) >>> data = np.arange(8).reshape((2, 2, 2)) >>> data array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> np.average(data, axis=(0, 1), weights=[[1./4, 3./4], [1., 1./2]]) array([3.4, 4.4]) >>> np.average(data, axis=0, weights=[[1./4, 3./4], [1., 1./2]]) Traceback (most recent call last): ... ValueError: Shape of weights must be consistent with shape of a along specified axis. """ a = np.asanyarray(a) if axis is not None: axis = _nx.normalize_axis_tuple(axis, a.ndim, argname="axis") if keepdims is np._NoValue: # Don't pass on the keepdims argument if one wasn't given. keepdims_kw = {} else: keepdims_kw = {'keepdims': keepdims} if weights is None: avg = a.mean(axis, **keepdims_kw) avg_as_array = np.asanyarray(avg) scl = avg_as_array.dtype.type(a.size / avg_as_array.size) else: wgt = _weights_are_valid(weights=weights, a=a, axis=axis) if issubclass(a.dtype.type, (np.integer, np.bool)): result_dtype = np.result_type(a.dtype, wgt.dtype, 'f8') else: result_dtype = np.result_type(a.dtype, wgt.dtype) scl = wgt.sum(axis=axis, dtype=result_dtype, **keepdims_kw) if np.any(scl == 0.0): raise ZeroDivisionError( "Weights sum to zero, can't be normalized") avg = avg_as_array = np.multiply(a, wgt, dtype=result_dtype).sum(axis, **keepdims_kw) / scl if returned: if scl.shape != avg_as_array.shape: scl = np.broadcast_to(scl, avg_as_array.shape, subok=True).copy() return avg, scl else: return avg @set_module('numpy') def asarray_chkfinite(a, dtype=None, order=None): """Convert the input to an array, checking for NaNs or Infs. Parameters ---------- a : array_like Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. Success requires no NaNs or Infs. dtype : data-type, optional By default, the data-type is inferred from the input data. order : {'C', 'F', 'A', 'K'}, optional The memory layout of the output. 'C' gives a row-major layout (C-style), 'F' gives a column-major layout (Fortran-style). 'C' and 'F' will copy if needed to ensure the output format. 'A' (any) is equivalent to 'F' if input a is non-contiguous or Fortran-contiguous, otherwise, it is equivalent to 'C'. Unlike 'C' or 'F', 'A' does not ensure that the result is contiguous. 'K' (keep) preserves the input order for the output. 'C' is the default. Returns ------- out : ndarray Array interpretation of `a`. No copy is performed if the input is already an ndarray. If `a` is a subclass of ndarray, a base class ndarray is returned. Raises ------ ValueError Raises ValueError if `a` contains NaN (Not a Number) or Inf (Infinity). See Also -------- asarray : Create and array. asanyarray : Similar function which passes through subclasses. ascontiguousarray : Convert input to a contiguous array. asfortranarray : Convert input to an ndarray with column-major memory order. fromiter : Create an array from an iterator. fromfunction : Construct an array by executing a function on grid positions. Examples -------- >>> import numpy as np Convert a list into an array. If all elements are finite, then ``asarray_chkfinite`` is identical to ``asarray``. >>> a = [1, 2] >>> np.asarray_chkfinite(a, dtype=np.float64) array([1., 2.]) Raises ValueError if array_like contains Nans or Infs. >>> a = [1, 2, np.inf] >>> try: ... np.asarray_chkfinite(a) ... except ValueError: ... print('ValueError') ... ValueError """ a = asarray(a, dtype=dtype, order=order) if a.dtype.char in typecodes['AllFloat'] and not np.isfinite(a).all(): raise ValueError( "array must not contain infs or NaNs") return a def _piecewise_dispatcher(x, condlist, funclist, *args, **kw): yield x # support the undocumented behavior of allowing scalars if np.iterable(condlist): yield from condlist @array_function_dispatch(_piecewise_dispatcher) def piecewise(x, condlist, funclist, *args, **kw): """ Evaluate a piecewise-defined function. Given a set of conditions and corresponding functions, evaluate each function on the input data wherever its condition is true. Parameters ---------- x : ndarray or scalar The input domain. condlist : list of bool arrays or bool scalars Each boolean array corresponds to a function in `funclist`. Wherever `condlist[i]` is True, `funclist[i](x)` is used as the output value. Each boolean array in `condlist` selects a piece of `x`, and should therefore be of the same shape as `x`. The length of `condlist` must correspond to that of `funclist`. If one extra function is given, i.e. if ``len(funclist) == len(condlist) + 1``, then that extra function is the default value, used wherever all conditions are false. funclist : list of callables, f(x,*args,**kw), or scalars Each function is evaluated over `x` wherever its corresponding condition is True. It should take a 1d array as input and give a 1d array or a scalar value as output. If, instead of a callable, a scalar is provided then a constant function (``lambda x: scalar``) is assumed. args : tuple, optional Any further arguments given to `piecewise` are passed to the functions upon execution, i.e., if called ``piecewise(..., ..., 1, 'a')``, then each function is called as ``f(x, 1, 'a')``. kw : dict, optional Keyword arguments used in calling `piecewise` are passed to the functions upon execution, i.e., if called ``piecewise(..., ..., alpha=1)``, then each function is called as ``f(x, alpha=1)``. Returns ------- out : ndarray The output is the same shape and type as x and is found by calling the functions in `funclist` on the appropriate portions of `x`, as defined by the boolean arrays in `condlist`. Portions not covered by any condition have a default value of 0. See Also -------- choose, select, where Notes ----- This is similar to choose or select, except that functions are evaluated on elements of `x` that satisfy the corresponding condition from `condlist`. The result is:: |-- |funclist[0](x[condlist[0]]) out = |funclist[1](x[condlist[1]]) |... |funclist[n2](x[condlist[n2]]) |-- Examples -------- >>> import numpy as np Define the signum function, which is -1 for ``x < 0`` and +1 for ``x >= 0``. >>> x = np.linspace(-2.5, 2.5, 6) >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) array([-1., -1., -1., 1., 1., 1.]) Define the absolute value, which is ``-x`` for ``x <0`` and ``x`` for ``x >= 0``. >>> np.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x]) array([2.5, 1.5, 0.5, 0.5, 1.5, 2.5]) Apply the same function to a scalar value. >>> y = -2 >>> np.piecewise(y, [y < 0, y >= 0], [lambda x: -x, lambda x: x]) array(2) """ x = asanyarray(x) n2 = len(funclist) # undocumented: single condition is promoted to a list of one condition if isscalar(condlist) or ( not isinstance(condlist[0], (list, ndarray)) and x.ndim != 0): condlist = [condlist] condlist = asarray(condlist, dtype=bool) n = len(condlist) if n == n2 - 1: # compute the "otherwise" condition. condelse = ~np.any(condlist, axis=0, keepdims=True) condlist = np.concatenate([condlist, condelse], axis=0) n += 1 elif n != n2: raise ValueError( f"with {n} condition(s), either {n} or {n + 1} functions are expected" ) y = zeros_like(x) for cond, func in zip(condlist, funclist): if not isinstance(func, collections.abc.Callable): y[cond] = func else: vals = x[cond] if vals.size > 0: y[cond] = func(vals, *args, **kw) return y def _select_dispatcher(condlist, choicelist, default=None): yield from condlist yield from choicelist @array_function_dispatch(_select_dispatcher) def select(condlist, choicelist, default=0): """ Return an array drawn from elements in choicelist, depending on conditions. Parameters ---------- condlist : list of bool ndarrays The list of conditions which determine from which array in `choicelist` the output elements are taken. When multiple conditions are satisfied, the first one encountered in `condlist` is used. choicelist : list of ndarrays The list of arrays from which the output elements are taken. It has to be of the same length as `condlist`. default : array_like, optional The element inserted in `output` when all conditions evaluate to False. Returns ------- output : ndarray The output at position m is the m-th element of the array in `choicelist` where the m-th element of the corresponding array in `condlist` is True. See Also -------- where : Return elements from one of two arrays depending on condition. take, choose, compress, diag, diagonal Examples -------- >>> import numpy as np Beginning with an array of integers from 0 to 5 (inclusive), elements less than ``3`` are negated, elements greater than ``3`` are squared, and elements not meeting either of these conditions (exactly ``3``) are replaced with a `default` value of ``42``. >>> x = np.arange(6) >>> condlist = [x<3, x>3] >>> choicelist = [-x, x**2] >>> np.select(condlist, choicelist, 42) array([ 0, -1, -2, 42, 16, 25]) When multiple conditions are satisfied, the first one encountered in `condlist` is used. >>> condlist = [x<=4, x>3] >>> choicelist = [x, x**2] >>> np.select(condlist, choicelist, 55) array([ 0, 1, 2, 3, 4, 25]) """ # Check the size of condlist and choicelist are the same, or abort. if len(condlist) != len(choicelist): raise ValueError( 'list of cases must be same length as list of conditions') # Now that the dtype is known, handle the deprecated select([], []) case if len(condlist) == 0: raise ValueError("select with an empty condition list is not possible") # TODO: This preserves the Python int, float, complex manually to get the # right `result_type` with NEP 50. Most likely we will grow a better # way to spell this (and this can be replaced). choicelist = [ choice if type(choice) in (int, float, complex) else np.asarray(choice) for choice in choicelist] choicelist.append(default if type(default) in (int, float, complex) else np.asarray(default)) try: dtype = np.result_type(*choicelist) except TypeError as e: msg = f'Choicelist and default value do not have a common dtype: {e}' raise TypeError(msg) from None # Convert conditions to arrays and broadcast conditions and choices # as the shape is needed for the result. Doing it separately optimizes # for example when all choices are scalars. condlist = np.broadcast_arrays(*condlist) choicelist = np.broadcast_arrays(*choicelist) # If cond array is not an ndarray in boolean format or scalar bool, abort. for i, cond in enumerate(condlist): if cond.dtype.type is not np.bool: raise TypeError( f'invalid entry {i} in condlist: should be boolean ndarray') if choicelist[0].ndim == 0: # This may be common, so avoid the call. result_shape = condlist[0].shape else: result_shape = np.broadcast_arrays(condlist[0], choicelist[0])[0].shape result = np.full(result_shape, choicelist[-1], dtype) # Use np.copyto to burn each choicelist array onto result, using the # corresponding condlist as a boolean mask. This is done in reverse # order since the first choice should take precedence. choicelist = choicelist[-2::-1] condlist = condlist[::-1] for choice, cond in zip(choicelist, condlist): np.copyto(result, choice, where=cond) return result def _copy_dispatcher(a, order=None, subok=None): return (a,) @array_function_dispatch(_copy_dispatcher) def copy(a, order='K', subok=False): """ Return an array copy of the given object. Parameters ---------- a : array_like Input data. order : {'C', 'F', 'A', 'K'}, optional Controls the memory layout of the copy. 'C' means C-order, 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. (Note that this function and :meth:`ndarray.copy` are very similar, but have different default values for their order= arguments.) subok : bool, optional If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (defaults to False). Returns ------- arr : ndarray Array interpretation of `a`. See Also -------- ndarray.copy : Preferred method for creating an array copy Notes ----- This is equivalent to: >>> np.array(a, copy=True) #doctest: +SKIP The copy made of the data is shallow, i.e., for arrays with object dtype, the new array will point to the same objects. See Examples from `ndarray.copy`. Examples -------- >>> import numpy as np Create an array x, with a reference y and a copy z: >>> x = np.array([1, 2, 3]) >>> y = x >>> z = np.copy(x) Note that, when we modify x, y changes, but not z: >>> x[0] = 10 >>> x[0] == y[0] True >>> x[0] == z[0] False Note that, np.copy clears previously set WRITEABLE=False flag. >>> a = np.array([1, 2, 3]) >>> a.flags["WRITEABLE"] = False >>> b = np.copy(a) >>> b.flags["WRITEABLE"] True >>> b[0] = 3 |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |