_axis_nan_policy.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. # Many scipy.stats functions support `axis` and `nan_policy` parameters.
  2. # When the two are combined, it can be tricky to get all the behavior just
  3. # right. This file contains utility functions useful for scipy.stats functions
  4. # that support `axis` and `nan_policy`, including a decorator that
  5. # automatically adds `axis` and `nan_policy` arguments to a function.
  6. import numpy as np
  7. from functools import wraps
  8. from scipy._lib._docscrape import FunctionDoc, Parameter
  9. from scipy._lib._util import _contains_nan
  10. import inspect
  11. def _broadcast_arrays(arrays, axis=None):
  12. """
  13. Broadcast shapes of arrays, ignoring incompatibility of specified axes
  14. """
  15. new_shapes = _broadcast_array_shapes(arrays, axis=axis)
  16. if axis is None:
  17. new_shapes = [new_shapes]*len(arrays)
  18. return [np.broadcast_to(array, new_shape)
  19. for array, new_shape in zip(arrays, new_shapes)]
  20. def _broadcast_array_shapes(arrays, axis=None):
  21. """
  22. Broadcast shapes of arrays, ignoring incompatibility of specified axes
  23. """
  24. shapes = [np.asarray(arr).shape for arr in arrays]
  25. return _broadcast_shapes(shapes, axis)
  26. def _broadcast_shapes(shapes, axis=None):
  27. """
  28. Broadcast shapes, ignoring incompatibility of specified axes
  29. """
  30. if not shapes:
  31. return shapes
  32. # input validation
  33. if axis is not None:
  34. axis = np.atleast_1d(axis)
  35. axis_int = axis.astype(int)
  36. if not np.array_equal(axis_int, axis):
  37. raise np.AxisError('`axis` must be an integer, a '
  38. 'tuple of integers, or `None`.')
  39. axis = axis_int
  40. # First, ensure all shapes have same number of dimensions by prepending 1s.
  41. n_dims = max([len(shape) for shape in shapes])
  42. new_shapes = np.ones((len(shapes), n_dims), dtype=int)
  43. for row, shape in zip(new_shapes, shapes):
  44. row[len(row)-len(shape):] = shape # can't use negative indices (-0:)
  45. # Remove the shape elements of the axes to be ignored, but remember them.
  46. if axis is not None:
  47. axis[axis < 0] = n_dims + axis[axis < 0]
  48. axis = np.sort(axis)
  49. if axis[-1] >= n_dims or axis[0] < 0:
  50. message = (f"`axis` is out of bounds "
  51. f"for array of dimension {n_dims}")
  52. raise np.AxisError(message)
  53. if len(np.unique(axis)) != len(axis):
  54. raise np.AxisError("`axis` must contain only distinct elements")
  55. removed_shapes = new_shapes[:, axis]
  56. new_shapes = np.delete(new_shapes, axis, axis=1)
  57. # If arrays are broadcastable, shape elements that are 1 may be replaced
  58. # with a corresponding non-1 shape element. Assuming arrays are
  59. # broadcastable, that final shape element can be found with:
  60. new_shape = np.max(new_shapes, axis=0)
  61. # except in case of an empty array:
  62. new_shape *= new_shapes.all(axis=0)
  63. # Among all arrays, there can only be one unique non-1 shape element.
  64. # Therefore, if any non-1 shape element does not match what we found
  65. # above, the arrays must not be broadcastable after all.
  66. if np.any(~((new_shapes == 1) | (new_shapes == new_shape))):
  67. raise ValueError("Array shapes are incompatible for broadcasting.")
  68. if axis is not None:
  69. # Add back the shape elements that were ignored
  70. new_axis = axis - np.arange(len(axis))
  71. new_shapes = [tuple(np.insert(new_shape, new_axis, removed_shape))
  72. for removed_shape in removed_shapes]
  73. return new_shapes
  74. else:
  75. return tuple(new_shape)
  76. def _broadcast_array_shapes_remove_axis(arrays, axis=None):
  77. """
  78. Broadcast shapes of arrays, dropping specified axes
  79. Given a sequence of arrays `arrays` and an integer or tuple `axis`, find
  80. the shape of the broadcast result after consuming/dropping `axis`.
  81. In other words, return output shape of a typical hypothesis test on
  82. `arrays` vectorized along `axis`.
  83. Examples
  84. --------
  85. >>> import numpy as np
  86. >>> a = np.zeros((5, 2, 1))
  87. >>> b = np.zeros((9, 3))
  88. >>> _broadcast_array_shapes((a, b), 1)
  89. (5, 3)
  90. """
  91. # Note that here, `axis=None` means do not consume/drop any axes - _not_
  92. # ravel arrays before broadcasting.
  93. shapes = [arr.shape for arr in arrays]
  94. return _broadcast_shapes_remove_axis(shapes, axis)
  95. def _broadcast_shapes_remove_axis(shapes, axis=None):
  96. """
  97. Broadcast shapes, dropping specified axes
  98. Same as _broadcast_array_shapes, but given a sequence
  99. of array shapes `shapes` instead of the arrays themselves.
  100. """
  101. shapes = _broadcast_shapes(shapes, axis)
  102. shape = shapes[0]
  103. if axis is not None:
  104. shape = np.delete(shape, axis)
  105. return tuple(shape)
  106. def _broadcast_concatenate(arrays, axis):
  107. """Concatenate arrays along an axis with broadcasting."""
  108. arrays = _broadcast_arrays(arrays, axis)
  109. res = np.concatenate(arrays, axis=axis)
  110. return res
  111. # TODO: add support for `axis` tuples
  112. def _remove_nans(samples, paired):
  113. "Remove nans from paired or unpaired 1D samples"
  114. # potential optimization: don't copy arrays that don't contain nans
  115. if not paired:
  116. return [sample[~np.isnan(sample)] for sample in samples]
  117. # for paired samples, we need to remove the whole pair when any part
  118. # has a nan
  119. nans = np.isnan(samples[0])
  120. for sample in samples[1:]:
  121. nans = nans | np.isnan(sample)
  122. not_nans = ~nans
  123. return [sample[not_nans] for sample in samples]
  124. def _remove_sentinel(samples, paired, sentinel):
  125. "Remove sentinel values from paired or unpaired 1D samples"
  126. # could consolidate with `_remove_nans`, but it's not quite as simple as
  127. # passing `sentinel=np.nan` because `(np.nan == np.nan) is False`
  128. # potential optimization: don't copy arrays that don't contain sentinel
  129. if not paired:
  130. return [sample[sample != sentinel] for sample in samples]
  131. # for paired samples, we need to remove the whole pair when any part
  132. # has a nan
  133. sentinels = (samples[0] == sentinel)
  134. for sample in samples[1:]:
  135. sentinels = sentinels | (sample == sentinel)
  136. not_sentinels = ~sentinels
  137. return [sample[not_sentinels] for sample in samples]
  138. def _masked_arrays_2_sentinel_arrays(samples):
  139. # masked arrays in `samples` are converted to regular arrays, and values
  140. # corresponding with masked elements are replaced with a sentinel value
  141. # return without modifying arrays if none have a mask
  142. has_mask = False
  143. for sample in samples:
  144. mask = getattr(sample, 'mask', False)
  145. has_mask = has_mask or np.any(mask)
  146. if not has_mask:
  147. return samples, None # None means there is no sentinel value
  148. # Choose a sentinel value. We can't use `np.nan`, because sentinel (masked)
  149. # values are always omitted, but there are different nan policies.
  150. dtype = np.result_type(*samples)
  151. dtype = dtype if np.issubdtype(dtype, np.number) else np.float64
  152. for i in range(len(samples)):
  153. # Things get more complicated if the arrays are of different types.
  154. # We could have different sentinel values for each array, but
  155. # the purpose of this code is convenience, not efficiency.
  156. samples[i] = samples[i].astype(dtype, copy=False)
  157. inexact = np.issubdtype(dtype, np.inexact)
  158. info = np.finfo if inexact else np.iinfo
  159. max_possible, min_possible = info(dtype).max, info(dtype).min
  160. nextafter = np.nextafter if inexact else (lambda x, _: x - 1)
  161. sentinel = max_possible
  162. # For simplicity, min_possible/np.infs are not candidate sentinel values
  163. while sentinel > min_possible:
  164. for sample in samples:
  165. if np.any(sample == sentinel): # choose a new sentinel value
  166. sentinel = nextafter(sentinel, -np.inf)
  167. break
  168. else: # when sentinel value is OK, break the while loop
  169. break
  170. else:
  171. message = ("This function replaces masked elements with sentinel "
  172. "values, but the data contains all distinct values of this "
  173. "data type. Consider promoting the dtype to `np.float64`.")
  174. raise ValueError(message)
  175. # replace masked elements with sentinel value
  176. out_samples = []
  177. for sample in samples:
  178. mask = getattr(sample, 'mask', None)
  179. if mask is not None: # turn all masked arrays into sentinel arrays
  180. mask = np.broadcast_to(mask, sample.shape)
  181. sample = sample.data.copy() if np.any(mask) else sample.data
  182. sample = np.asarray(sample) # `sample.data` could be a memoryview?
  183. sample[mask] = sentinel
  184. out_samples.append(sample)
  185. return out_samples, sentinel
  186. def _check_empty_inputs(samples, axis):
  187. """
  188. Check for empty sample; return appropriate output for a vectorized hypotest
  189. """
  190. # if none of the samples are empty, we need to perform the test
  191. if not any((sample.size == 0 for sample in samples)):
  192. return None
  193. # otherwise, the statistic and p-value will be either empty arrays or
  194. # arrays with NaNs. Produce the appropriate array and return it.
  195. output_shape = _broadcast_array_shapes_remove_axis(samples, axis)
  196. output = np.ones(output_shape) * np.nan
  197. return output
  198. def _add_reduced_axes(res, reduced_axes, keepdims):
  199. """
  200. Add reduced axes back to all the arrays in the result object
  201. if keepdims = True.
  202. """
  203. return ([np.expand_dims(output, reduced_axes) for output in res]
  204. if keepdims else res)
  205. # Standard docstring / signature entries for `axis`, `nan_policy`, `keepdims`
  206. _name = 'axis'
  207. _desc = (
  208. """If an int, the axis of the input along which to compute the statistic.
  209. The statistic of each axis-slice (e.g. row) of the input will appear in a
  210. corresponding element of the output.
  211. If ``None``, the input will be raveled before computing the statistic."""
  212. .split('\n'))
  213. def _get_axis_params(default_axis=0, _name=_name, _desc=_desc): # bind NOW
  214. _type = f"int or None, default: {default_axis}"
  215. _axis_parameter_doc = Parameter(_name, _type, _desc)
  216. _axis_parameter = inspect.Parameter(_name,
  217. inspect.Parameter.KEYWORD_ONLY,
  218. default=default_axis)
  219. return _axis_parameter_doc, _axis_parameter
  220. _name = 'nan_policy'
  221. _type = "{'propagate', 'omit', 'raise'}"
  222. _desc = (
  223. """Defines how to handle input NaNs.
  224. - ``propagate``: if a NaN is present in the axis slice (e.g. row) along
  225. which the statistic is computed, the corresponding entry of the output
  226. will be NaN.
  227. - ``omit``: NaNs will be omitted when performing the calculation.
  228. If insufficient data remains in the axis slice along which the
  229. statistic is computed, the corresponding entry of the output will be
  230. NaN.
  231. - ``raise``: if a NaN is present, a ``ValueError`` will be raised."""
  232. .split('\n'))
  233. _nan_policy_parameter_doc = Parameter(_name, _type, _desc)
  234. _nan_policy_parameter = inspect.Parameter(_name,
  235. inspect.Parameter.KEYWORD_ONLY,
  236. default='propagate')
  237. _name = 'keepdims'
  238. _type = "bool, default: False"
  239. _desc = (
  240. """If this is set to True, the axes which are reduced are left
  241. in the result as dimensions with size one. With this option,
  242. the result will broadcast correctly against the input array."""
  243. .split('\n'))
  244. _keepdims_parameter_doc = Parameter(_name, _type, _desc)
  245. _keepdims_parameter = inspect.Parameter(_name,
  246. inspect.Parameter.KEYWORD_ONLY,
  247. default=False)
  248. _standard_note_addition = (
  249. """\nBeginning in SciPy 1.9, ``np.matrix`` inputs (not recommended for new
  250. code) are converted to ``np.ndarray`` before the calculation is performed. In
  251. this case, the output will be a scalar or ``np.ndarray`` of appropriate shape
  252. rather than a 2D ``np.matrix``. Similarly, while masked elements of masked
  253. arrays are ignored, the output will be a scalar or ``np.ndarray`` rather than a
  254. masked array with ``mask=False``.""").split('\n')
  255. def _axis_nan_policy_factory(tuple_to_result, default_axis=0,
  256. n_samples=1, paired=False,
  257. result_to_tuple=None, too_small=0,
  258. n_outputs=2, kwd_samples=[]):
  259. """Factory for a wrapper that adds axis/nan_policy params to a function.
  260. Parameters
  261. ----------
  262. tuple_to_result : callable
  263. Callable that returns an object of the type returned by the function
  264. being wrapped (e.g. the namedtuple or dataclass returned by a
  265. statistical test) provided the separate components (e.g. statistic,
  266. pvalue).
  267. default_axis : int, default: 0
  268. The default value of the axis argument. Standard is 0 except when
  269. backwards compatibility demands otherwise (e.g. `None`).
  270. n_samples : int or callable, default: 1
  271. The number of data samples accepted by the function
  272. (e.g. `mannwhitneyu`), a callable that accepts a dictionary of
  273. parameters passed into the function and returns the number of data
  274. samples (e.g. `wilcoxon`), or `None` to indicate an arbitrary number
  275. of samples (e.g. `kruskal`).
  276. paired : {False, True}
  277. Whether the function being wrapped treats the samples as paired (i.e.
  278. corresponding elements of each sample should be considered as different
  279. components of the same sample.)
  280. result_to_tuple : callable, optional
  281. Function that unpacks the results of the function being wrapped into
  282. a tuple. This is essentially the inverse of `tuple_to_result`. Default
  283. is `None`, which is appropriate for statistical tests that return a
  284. statistic, pvalue tuple (rather than, e.g., a non-iterable datalass).
  285. too_small : int, default: 0
  286. The largest unnacceptably small sample for the function being wrapped.
  287. For example, some functions require samples of size two or more or they
  288. raise an error. This argument prevents the error from being raised when
  289. input is not 1D and instead places a NaN in the corresponding element
  290. of the result.
  291. n_outputs : int or callable, default: 2
  292. The number of outputs produced by the function given 1d sample(s). For
  293. example, hypothesis tests that return a namedtuple or result object
  294. with attributes ``statistic`` and ``pvalue`` use the default
  295. ``n_outputs=2``; summary statistics with scalar output use
  296. ``n_outputs=1``. Alternatively, may be a callable that accepts a
  297. dictionary of arguments passed into the wrapped function and returns
  298. the number of outputs corresponding with those arguments.
  299. kwd_samples : sequence, default: []
  300. The names of keyword parameters that should be treated as samples. For
  301. example, `gmean` accepts as its first argument a sample `a` but
  302. also `weights` as a fourth, optional keyword argument. In this case, we
  303. use `n_samples=1` and kwd_samples=['weights'].
  304. """
  305. if result_to_tuple is None:
  306. def result_to_tuple(res):
  307. return res
  308. def is_too_small(samples):
  309. for sample in samples:
  310. if len(sample) <= too_small:
  311. return True
  312. return False
  313. def axis_nan_policy_decorator(hypotest_fun_in):
  314. @wraps(hypotest_fun_in)
  315. def axis_nan_policy_wrapper(*args, _no_deco=False, **kwds):
  316. if _no_deco: # for testing, decorator does nothing
  317. return hypotest_fun_in(*args, **kwds)
  318. # We need to be flexible about whether position or keyword
  319. # arguments are used, but we need to make sure users don't pass
  320. # both for the same parameter. To complicate matters, some
  321. # functions accept samples with *args, and some functions already
  322. # accept `axis` and `nan_policy` as positional arguments.
  323. # The strategy is to make sure that there is no duplication
  324. # between `args` and `kwds`, combine the two into `kwds`, then
  325. # the samples, `nan_policy`, and `axis` from `kwds`, as they are
  326. # dealt with separately.
  327. # Check for intersection between positional and keyword args
  328. params = list(inspect.signature(hypotest_fun_in).parameters)
  329. if n_samples is None:
  330. # Give unique names to each positional sample argument
  331. # Note that *args can't be provided as a keyword argument
  332. params = [f"arg{i}" for i in range(len(args))] + params[1:]
  333. d_args = dict(zip(params, args))
  334. intersection = set(d_args) & set(kwds)
  335. if intersection:
  336. message = (f"{hypotest_fun_in.__name__}() got multiple values "
  337. f"for argument '{list(intersection)[0]}'")
  338. raise TypeError(message)
  339. # Consolidate other positional and keyword args into `kwds`
  340. kwds.update(d_args)
  341. # rename avoids UnboundLocalError
  342. if callable(n_samples):
  343. # Future refactoring idea: no need for callable n_samples.
  344. # Just replace `n_samples` and `kwd_samples` with a single
  345. # list of the names of all samples, and treat all of them
  346. # as `kwd_samples` are treated below.
  347. n_samp = n_samples(kwds)
  348. else:
  349. n_samp = n_samples or len(args)
  350. # get the number of outputs
  351. n_out = n_outputs # rename to avoid UnboundLocalError
  352. if callable(n_out):
  353. n_out = n_out(kwds)
  354. # If necessary, rearrange function signature: accept other samples
  355. # as positional args right after the first n_samp args
  356. kwd_samp = [name for name in kwd_samples
  357. if kwds.get(name, None) is not None]
  358. n_kwd_samp = len(kwd_samp)
  359. if not kwd_samp:
  360. hypotest_fun_out = hypotest_fun_in
  361. else:
  362. def hypotest_fun_out(*samples, **kwds):
  363. new_kwds = dict(zip(kwd_samp, samples[n_samp:]))
  364. kwds.update(new_kwds)
  365. return hypotest_fun_in(*samples[:n_samp], **kwds)
  366. # Extract the things we need here
  367. samples = [np.atleast_1d(kwds.pop(param))
  368. for param in (params[:n_samp] + kwd_samp)]
  369. vectorized = True if 'axis' in params else False
  370. axis = kwds.pop('axis', default_axis)
  371. nan_policy = kwds.pop('nan_policy', 'propagate')
  372. keepdims = kwds.pop("keepdims", False)
  373. del args # avoid the possibility of passing both `args` and `kwds`
  374. # convert masked arrays to regular arrays with sentinel values
  375. samples, sentinel = _masked_arrays_2_sentinel_arrays(samples)
  376. # standardize to always work along last axis
  377. reduced_axes = axis
  378. if axis is None:
  379. if samples:
  380. # when axis=None, take the maximum of all dimensions since
  381. # all the dimensions are reduced.
  382. n_dims = np.max([sample.ndim for sample in samples])
  383. reduced_axes = tuple(range(n_dims))
  384. samples = [np.asarray(sample.ravel()) for sample in samples]
  385. else:
  386. samples = _broadcast_arrays(samples, axis=axis)
  387. axis = np.atleast_1d(axis)
  388. n_axes = len(axis)
  389. # move all axes in `axis` to the end to be raveled
  390. samples = [np.moveaxis(sample, axis, range(-len(axis), 0))
  391. for sample in samples]
  392. shapes = [sample.shape for sample in samples]
  393. # New shape is unchanged for all axes _not_ in `axis`
  394. # At the end, we append the product of the shapes of the axes
  395. # in `axis`. Appending -1 doesn't work for zero-size arrays!
  396. new_shapes = [shape[:-n_axes] + (np.prod(shape[-n_axes:]),)
  397. for shape in shapes]
  398. samples = [sample.reshape(new_shape)
  399. for sample, new_shape in zip(samples, new_shapes)]
  400. axis = -1 # work over the last axis
  401. # if axis is not needed, just handle nan_policy and return
  402. ndims = np.array([sample.ndim for sample in samples])
  403. if np.all(ndims <= 1):
  404. # Addresses nan_policy == "raise"
  405. contains_nans = []
  406. for sample in samples:
  407. contains_nan, _ = _contains_nan(sample, nan_policy)
  408. contains_nans.append(contains_nan)
  409. # Addresses nan_policy == "propagate"
  410. # Consider adding option to let function propagate nans, but
  411. # currently the hypothesis tests this is applied to do not
  412. # propagate nans in a sensible way
  413. if any(contains_nans) and nan_policy == 'propagate':
  414. res = np.full(n_out, np.nan)
  415. res = _add_reduced_axes(res, reduced_axes, keepdims)
  416. return tuple_to_result(*res)
  417. # Addresses nan_policy == "omit"
  418. if any(contains_nans) and nan_policy == 'omit':
  419. # consider passing in contains_nans
  420. samples = _remove_nans(samples, paired)
  421. # ideally, this is what the behavior would be:
  422. # if is_too_small(samples):
  423. # return tuple_to_result(np.nan, np.nan)
  424. # but some existing functions raise exceptions, and changing
  425. # behavior of those would break backward compatibility.
  426. if sentinel:
  427. samples = _remove_sentinel(samples, paired, sentinel)
  428. res = hypotest_fun_out(*samples, **kwds)
  429. res = result_to_tuple(res)
  430. res = _add_reduced_axes(res, reduced_axes, keepdims)
  431. return tuple_to_result(*res)
  432. # check for empty input
  433. # ideally, move this to the top, but some existing functions raise
  434. # exceptions for empty input, so overriding it would break
  435. # backward compatibility.
  436. empty_output = _check_empty_inputs(samples, axis)
  437. if empty_output is not None:
  438. res = [empty_output.copy() for i in range(n_out)]
  439. res = _add_reduced_axes(res, reduced_axes, keepdims)
  440. return tuple_to_result(*res)
  441. # otherwise, concatenate all samples along axis, remembering where
  442. # each separate sample begins
  443. lengths = np.array([sample.shape[axis] for sample in samples])
  444. split_indices = np.cumsum(lengths)
  445. x = _broadcast_concatenate(samples, axis)
  446. # Addresses nan_policy == "raise"
  447. contains_nan, _ = _contains_nan(x, nan_policy)
  448. if vectorized and not contains_nan and not sentinel:
  449. res = hypotest_fun_out(*samples, axis=axis, **kwds)
  450. res = result_to_tuple(res)
  451. res = _add_reduced_axes(res, reduced_axes, keepdims)
  452. return tuple_to_result(*res)
  453. # Addresses nan_policy == "omit"
  454. if contains_nan and nan_policy == 'omit':
  455. def hypotest_fun(x):
  456. samples = np.split(x, split_indices)[:n_samp+n_kwd_samp]
  457. samples = _remove_nans(samples, paired)
  458. if sentinel:
  459. samples = _remove_sentinel(samples, paired, sentinel)
  460. if is_too_small(samples):
  461. return np.full(n_out, np.nan)
  462. return result_to_tuple(hypotest_fun_out(*samples, **kwds))
  463. # Addresses nan_policy == "propagate"
  464. elif contains_nan and nan_policy == 'propagate':
  465. def hypotest_fun(x):
  466. if np.isnan(x).any():
  467. return np.full(n_out, np.nan)
  468. samples = np.split(x, split_indices)[:n_samp+n_kwd_samp]
  469. if sentinel:
  470. samples = _remove_sentinel(samples, paired, sentinel)
  471. if is_too_small(samples):
  472. return np.full(n_out, np.nan)
  473. return result_to_tuple(hypotest_fun_out(*samples, **kwds))
  474. else:
  475. def hypotest_fun(x):
  476. samples = np.split(x, split_indices)[:n_samp+n_kwd_samp]
  477. if sentinel:
  478. samples = _remove_sentinel(samples, paired, sentinel)
  479. if is_too_small(samples):
  480. return np.full(n_out, np.nan)
  481. return result_to_tuple(hypotest_fun_out(*samples, **kwds))
  482. x = np.moveaxis(x, axis, 0)
  483. res = np.apply_along_axis(hypotest_fun, axis=0, arr=x)
  484. res = _add_reduced_axes(res, reduced_axes, keepdims)
  485. return tuple_to_result(*res)
  486. _axis_parameter_doc, _axis_parameter = _get_axis_params(default_axis)
  487. doc = FunctionDoc(axis_nan_policy_wrapper)
  488. parameter_names = [param.name for param in doc['Parameters']]
  489. if 'axis' in parameter_names:
  490. doc['Parameters'][parameter_names.index('axis')] = (
  491. _axis_parameter_doc)
  492. else:
  493. doc['Parameters'].append(_axis_parameter_doc)
  494. if 'nan_policy' in parameter_names:
  495. doc['Parameters'][parameter_names.index('nan_policy')] = (
  496. _nan_policy_parameter_doc)
  497. else:
  498. doc['Parameters'].append(_nan_policy_parameter_doc)
  499. if 'keepdims' in parameter_names:
  500. doc['Parameters'][parameter_names.index('keepdims')] = (
  501. _keepdims_parameter_doc)
  502. else:
  503. doc['Parameters'].append(_keepdims_parameter_doc)
  504. doc['Notes'] += _standard_note_addition
  505. doc = str(doc).split("\n", 1)[1] # remove signature
  506. axis_nan_policy_wrapper.__doc__ = str(doc)
  507. sig = inspect.signature(axis_nan_policy_wrapper)
  508. parameters = sig.parameters
  509. parameter_list = list(parameters.values())
  510. if 'axis' not in parameters:
  511. parameter_list.append(_axis_parameter)
  512. if 'nan_policy' not in parameters:
  513. parameter_list.append(_nan_policy_parameter)
  514. if 'keepdims' not in parameters:
  515. parameter_list.append(_keepdims_parameter)
  516. sig = sig.replace(parameters=parameter_list)
  517. axis_nan_policy_wrapper.__signature__ = sig
  518. return axis_nan_policy_wrapper
  519. return axis_nan_policy_decorator