summaryrefslogtreecommitdiff
path: root/numpy/lib/arraypad.py
Commit message (Collapse)AuthorAgeFilesLines
* BUG: fix unexpected return of np.pad with mode=wrap (#22575)LU2022-12-071-13/+18
| | | | | | | | | np.pad with mode="wrap" returns unexpected result that original data is not strictly looped in padding. This may happen in some occassions when padding widths in the same dimension are unbalanced (see added testcase in test_arraypad.py and the related issue). The reason is the function pad makes iterative calls of _set_wrap_both() in the above situation, yet period for padding is not correctly computed in each iteration. The bug is fixed by guaranteeing that period is always a multiple of original data size, and also be the possible maximum for computation efficiency. Closes #22464 Co-authored-by: Lars Grüter <lagru+github@mailbox.org>
* DOC: Update parameter descriptions for np.pad (#22519)Miki Watanabe2022-11-151-17/+18
| | | | | | | | Some parameters like pad_width or stat_length claimed to expect tuples-of-tuples as input, but in practice they also work with single tuples. The parameter descriptions of the relevant parameters are updated in the docstring to reflect this implicit tuple wrapping behavior. Co-authored-by: 渡邉 美希 <miki.watanabe@watanabenoMacBook-Pro.local>
* update numpy/lib/arraypad.py with appropriate chain exception (#16953)Noman Arshad2020-07-281-1/+1
| | | | | * update numpy/lib/arraypad.py with appropriate chain exception Co-authored-by: Noman Arshad <noman.arshad@northbaysolutions.com>
* MAINT: Remove Duplicated Code (function extract rmap) (#16847)Wansoo Kim2020-07-171-16/+13
| | | | | * MAINT: Remove Duplicated Code (function extract rmap) Co-authored-by: Ross Barnowski <rossbar@berkeley.edu>
* DOC: fix typosBrian Wignall2020-01-141-2/+2
|
* MAINT: Remove unnecessary 'from __future__ import ...' statementsJon Dufresne2020-01-031-2/+0
| | | | | As numpy is Python 3 only, these import statements are now unnecessary and don't alter runtime behavior.
* Merge pull request #14209 from lagru/fix-linear-rampCharles Harris2019-09-051-68/+16
|\ | | | | BUG: Fix uint-overflow if padding with linear_ramp and negative gain
| * BUG: Replace _linear_ramp with linspaceLars Grueter2019-08-271-68/+16
| | | | | | | | | | | | | | | | | | | | linspace supports non-scalar values since version 1.16. This can replace the former _linear_ramp method. This removes a bug in the old implementation where certain edge and end values resulted in an integer underflow for unsigned dtypes (see gh-14191). Protect against this regression with a new test for all numeric dtypes.
* | MAINT: Clearer error while padding stat_length=0Lars Grueter2019-08-091-1/+8
|/ | | | | | | | | Provides a clearer error message if stat_length=0 is the cause of an exception (mean and median return nan with warnings) as well as tests covering this behavior. Note: This shouldn't change the behavior/API except for the content of the raised ValueError.
* MAINT: improve efficiency of pad by avoiding use of apply_along_axisGregory Lee2019-04-281-2/+15
| | | | | | | | pad assumed that apply_along_axis was modifying the padded array in-place. In this case, it is more efficient to avoid the overhead of creating an output buffer and just directly iterate the inplace operations instead using transpose and nditer instead. MAINT: use moveaxis in place of transpose to improve clarity
* DOC: correction to numpy.pad docstring (#13149)Gregory R. Lee2019-03-251-5/+3
| | | * DOC: fix mistatement in numpy.pad docstring
* MAINT: Rewrite numpy.pad without concatenate (gh-11358)Lars Grueter2019-03-251-917/+477
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | * ENH: Add support for constant, edge, linear_ramp to new numpy.pad Passes unit tests: - TestConstant - TestEdge - TestZeroPadWidth - TestLegacyVectorFunction - TestNdarrayPadWidth - TestUnicodeInput - TestLinearRamp * MAINT: Simplify diff / change order of functions * MAINT: Revert to old handling of keyword-only arguments * ENH: Add support for stat modes * ENH: Add support for "reflect" mode * MAINT: Remove _slice_column * ENH: Add support for "symmetric" mode * MAINT: Simplify mode "linear_ramp" Creating the linear ramp as an array with 1-sized dimensions except for the one given by `axis` allows implicit broadcasting to the needed shape. This seems to be even a little bit faster that doing this by hand and allows the simplicifaction of the algorithm. Note: Profiling and optimization will be done again at a later stage. * MAINT: Reorder arguments of a sum and fix typo Addresses feedback raised in PR. * ENH: Add support for "wrap" mode This completes the first draft of the complete rewrite meaning all unit tests should pass from this commit onwards. * MAINT: Merge functions for "reflect" and "symmetric" mode The set functions were nearly the same, apart from some index offsets. Merging them reduces code duplication. * TST: Add regression test for gh-11216 The rewrite in past commits fixed this bug. * BUG: Fix edge case for _set_wrap_both when pad_amt contains 0. And include test to protect against regression. * MAINT: Simplify and optimize pad modes Major changes & goals: Don't deal with pad area in the front and back separately. This modularity isn't needed and makes handling of the right edge more awkward. All modes now deal with the left and right side at the same time. Move the creation of the linear ramps fully to its own function which behaves like a vectorized version of linspace. Separate calculation and application of the pad area where possible. This means that _get_edges can be reused for _get_linear_ramps. Combine _normalize_shape and _validate_lengths in a single function which should handles common cases faster. Add new mode "empty" which leaves the padded areas undefined. Add documentation where it was missing. * TST: Don't use np.empty in unit tests * MAINT: Reorder workflow in numpy.pad and deal with empty dimensions Only modes "constant" and "empty" can extend dimensions of size 0. Deal with this edge case gracefully for all other modes either fail or return empty array with padded non-zero dimensions. Handle default values closer to their actual usage. And validate keyword arguments that must be numbers. * MAINT: Add small tweaks to control flow and documentation * BUG: Ensure wrap mode works if right_pad is 0 * ENH: Use reduced region of interest for iterative padding When padding multiple dimensions iteratively corner values are unnecessarily overwritten multiple times. This function reduces the working area for the first dimensions so that corners are excluded. * MAINT: Restore original argument order in _slice_at_axis * MAINT: Keep original error message of broadcast_to * MAINT: Restore old behavior for non-number end_values. * BENCH: Make the pad benchmark pagefault in setup * ENH/TST: Preserve memory layout (order) of the input array and add appropriate unit test. * STY: Revert cosmetical changes to reduce diff * MAINT: Pin dtype to float64 for np.pad's benchmarks * MAINT: Remove redundant code path in _view_roi * MAINT/TST: Provide proper error message for unsupported modes and add appropriate unit test. * STY: Keep docstrings consistent and fix typo. * MAINT: Simplify logical workflow in pad * MAINT: Remove dtype argument from _linear_ramp The responsibility of rounding (but without type conversion) is not really need in _linear_ramp and only makes it a little bit harder to reason about. * DOC: Add version tag to new argument "empty" * MAINT: Default to C-order for padded arrays unless the input is F-contiguous. * MAINT: Name slice of original area consistently for all arguments describing the same thing. * STY: Reduce vertical space * MAINT: Remove shape argument from _slice_at_axis Simplifies calls to this function and the function itself. Using `(...,)` instead should keep this unambiguous. This change is not compatible with Python 2.7 which doesn't support this syntax outside sequence slicing. If that is wanted one could use `(Ellipsis,)` instead. * TST: Test if end_values of linear_ramp are exact which was not given in the old implementation `_arange_ndarray`. * DOC: Improve comments and wrap long line * MAINT: Refactor index_pair to width_pair Calling the right value an index is just plain wrong as it can't be used as such. * MAINT: Make _linear_ramp compatible with size=0 * MAINT: Don't rely on negative indices for slicing Calculating the proper positive index of the start of the right pad area makes it possible to omit the extra code paths for a width of 0. This should make the code easier to reason about. * MAINT: Skip calculation of right_stat if identical If the input area for both sides is the same we don't need to calculate it twice. * TST: Adapt tests from gh-12789 to rewrite of pad * TST: Add tests for mode "empty" * TST: Test dtype persistence for all modes * TST: Test exception for unsupported modes * TST: Test repeated wrapping for each side individually. Reaches some only partially covered if-statments in _set_wrap_both. * TST: Test padding of empty dimension with constant * TST: Test if end_values of linear_ramp are exact which was not given in the old implementation `_arange_ndarray`. (Was accidentally overwritten during the last merge). * TST: Test persistence of memory layout Adapted from an older commit 3ac4d2a1b9b258d65f8d2b5f8f25f88e3a0e8f58 which was accidentally overwritten during the last merge. * MAINT: Simplify branching in _set_reflect_both Reduce branching and try to make the calculation of the various indices easier to understand. * TST: Parametrize TestConditionalShortcuts class * TST: Test empty dimension padding for all modes * TST: Keep test parametrization ordered Keep parametrization ordered, otherwise pytest-xdist might believe that different tests were collected during parallelization causing test failures. * DOC: Describe performance improvement of np.pad as well as the new mode "empty" in release notes (see gh-11358). * DOC: Remove outdated / misleading notes These notes are badly worded or actually misleading. For a better explanation on how these functions work have a look at the context and comments just above the lines calling these functions.
* Merge pull request #13117 from kshyatt/ksh/padMatti Picus2019-03-191-8/+8
|\ | | | | DOC: Fix arg type for np.pad, fix #9489
| * Update parameter description for constant and end valuesKatharine Hyatt2019-03-141-6/+6
| |
| * DOC: fix arg type for np.pad, fix #9489Katharine Hyatt2019-03-131-2/+2
| |
* | Fix array dispatcherStefan van der Walt2019-03-151-1/+1
| |
* | ENH: Make `mode` parameter default to `constant` (padding by zero)Stefan van der Walt2019-03-131-3/+3
|/
* TST, DOC: enable refguide_checkTyler Reddy2018-12-141-2/+2
| | | | | | | | * ported the refguide_check module from SciPy for usage in NumPy docstring execution/ verification; added the refguide_check run to Azure Mac OS CI * adjusted NumPy docstrings such that refguide_check passes
* MAINT: Rewrite shape normalization in pad function (#11966)Lars Grüter2018-11-151-94/+59
|
* MAINT: set preferred __module__ for numpy functionsStephan Hoyer2018-10-231-1/+1
|
* ENH: __array_function__ for np.lib, part 1Stephan Hoyer2018-10-081-0/+6
| | | | np.lib.arraypad through np.lib.nanfunctions
* MAINT: Extract a helper function for prepending and appendingEric Wieser2018-05-221-26/+25
| | | | This makes it a little easier to tell the difference between the prepend and append functions
* MAINT: np.pad: Generalize the helper function to be used in more placesEric Wieser2018-05-221-12/+15
| | | | This makes `_slice_first` almost a factor of two faster
* MAINT: np.pad: Add helper functions for producing slices along axesEric Wieser2018-05-221-52/+32
|
* Merge pull request #11011 from eric-wieser/pad-singletonCharles Harris2018-05-131-109/+34
|\ | | | | MAINT: Simplify dimension-juggling in np.pad
| * MAINT: Use keepdims in favor of re-inserting dimensionsEric Wieser2018-04-291-48/+16
| | | | | | | | This is safe, because the arguments are always base-class ndarrays, so `keepdims` is guaranteed to be supported
| * MAINT: Remove singleton-dimension insertion in np.pad in favor of not losing ↵Eric Wieser2018-04-291-61/+18
| | | | | | | | | | | | the dimension in the first place. `arr[:,:,0,:,:].reshape(arr.shape[:2] + (1,) + arr.shape[3:])` is much more readable as `arr[:,:,0:1,:,:]` (and easier for subclasses to handle)
* | MAINT: Simplify workflow in _append_const and _prepend_constLars G2018-05-021-12/+4
| |
* | BUG: Fix padding with large integersLars G2018-05-021-4/+4
|/ | | | | | | | | | | The old way of creating the padded array padded with wrong values for large integers because the new prepended / appended array was implicitly created with dtype float64: >>> (np.zeros(1) + (2 ** 64 - 1)).astype(np.uint64) array([0], np.uint64) >>> (np.zeros(1) + (2 ** 63 - 1)).astype(np.int64) array([-9223372036854775808])
* MAINT: Stop using non-tuple indices internallyEric Wieser2018-02-161-3/+3
| | | | | | By not using this type of indexing, it becomes easier for subclasses to override indexing in a way that works correctly with numpy functions. These locations were found by deprecating the behavior in question, which is deliberately not part of this commit
* More misc. typosluz.paz2018-01-041-1/+1
| | | Found via `codespell`
* DOC: Update arraypad to use np.pad in examplesHenke Adolfsson2017-10-161-14/+14
|
* DOC: Correct the signature in pad doc for callable mode.Michael Seifert2017-09-101-8/+14
| | | | [skip ci]
* BUG: fix padding an empty array in reflect mode.Iryna Shcherbina2017-09-011-3/+8
| | | | Check that axes with non-zero padding are non-empty.
* BUG: fix infinite loop when creating np.pad on an empty arrayIryna Shcherbina2017-08-241-0/+3
|
* MAINT: replace len(x.shape) with x.ndimEric Wieser2017-02-241-1/+1
|
* BUG: lib: Simplify (and fix) pad's handling of the pad_widthWarren Weckesser2016-09-171-29/+6
| | | | | | | | Simplify the expansion of the pad_width argument by using `broadcast_to()`. This fixes the problem reported in gh-7808, where, for example, `pad_width=((1, 2),)` resulted in an error. Closes gh-7808.
* BUG: constant padding expected wrong type in constant_valueschiffa2016-02-271-1/+1
| | | | | Constant padding on 4 sides of a 2d array expected a numpy ndarray, and not a ndarray like (tuple, list, ...) Detailed description is in the issue #7353
* BUG: mode kwargs passed as unicode to np.pad raises an exceptionbertrand2016-01-301-1/+1
| | | | | isinstance(mode, str) is False in python2.7 when mode is of unicode type, and mode is then mistakenly assumed to be a callable. See #7112
* Clarify signature of numpy.pad.Antony Lee2015-08-071-4/+1
| | | | | `mode` is a required argument so just declare it as such. This does not prevent it from being passed as a keyword argument.
* ENH: Improve arg handling & enhance test suite for np.padJosh Warner (Mac)2015-01-061-56/+78
|
* DOC : do not abuse enum markupThomas A Caswell2014-12-121-5/+5
| | | | | | | | | - {ndarray, bool} -> ndarray or bool - {int, array of ints} -> int or array of ints - {str, function} -> str or function - {sequnce, int} -> sequence or int - {array_like, poly1d} -> array_like or poly1d - {None, list of `m` scalars, scalar} -> list of `m` scalars or scalar
* STY: Make files in numpy/lib PEP8 compliant.Charles Harris2014-07-311-1/+0
| | | | The rules enforced are the same as those used for scipy.
* MAINT: Fixes for problems in numpy/lib revealed by pyflakes.Charles Harris2014-07-311-4/+1
| | | | | | Some of those problems look like potential coding errors. In those cases a Fixme comment was made and the offending code, usually an unused variable, was commented out.
* Avoid overallocating memory in arraypad with user supplied functionJonathan L Long2013-12-171-1/+1
| | | | | | Previously, arraypad used zeros(shape).astype(dtype) instead of zeros(shape, dtype), which could allocate up to eight times more memory than necessary.
* DOC: Change pad mode options to a definition listendolith2013-11-101-23/+33
| | | Current formatting is not part of rst, and is not rendering correctly at http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.pad.html
* BUG: Allow to pad arrays by zero entries.Jostein Bø Fløystad2013-07-051-1/+1
| | | | | np.pad will now accept a pad_width containing zeros. The functionality was already implemented, but validation of input was too strict.
* ENH: improved, faster algorithm for array paddingJosh Warner (Mac)2013-05-191-414/+1087
| | | | | | | | | | | | New padding method which scales much better with dimensionality. This new implementation is fully vectorized, builds each abstracted n-dimensional padding block in a single step, and takes advantage of separability. The API is completely preserved, and the old algorithm is used if a vector function is input for `mode`. The new algorithm is faster for all tested combinations of inputs, and scales much better with dimensionality. Execution time reductions from ~25% for small rank 1 arrays to >99% for rank 4+ arrays observed.
* STY: pep8 and pep257 audit.Josh Warner (Mac)2013-05-071-89/+101
| | | | | | Audit numpy/lib/arraypad.py for pep8 and pep257 compliance. Also fix a few minor docstring corrections converting ] into ) or vice versa.
* 2to3: Apply the `numliterals` fixer and skip the `long` fixer.Charles Harris2013-04-131-0/+1
| | | | | | | | | | | | | | | | | | | The numliterals fixer replaces the old style octal number like '01' by '0o1' removes the 'L' suffix. Octal values were previously mistakenly specified in some dates, those uses have been corrected by removing the leading zeros. Simply Removing the 'L' suffix should not be a problem, but in some testing code it looks neccesary, so in those places the Python long constructor is used instead. The 'long' type is no longer defined in Python 3. Because we need to have it defined for Python 2 it is added to numpy/compat/np3k.py where it is defined as 'int' for Python 3 and 'long' for Python 2. The `long` fixer then needs to be skipped so that it doesn't undo the good work. Closes #3074, #3067.