We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
OverflowError in resample_poly (upfirdn)
scipy.signal.resample_poly fails if the output vector length would be greater than 2^31-1.

```
Traceback (most recent call last):

  File "<ipython-input-1-ac5d2b0a1632>", line 11, in <module>
    yy = resample_poly(y, 128, 1)

  File "F:\Programs\Miniconda3\lib\site-packages\scipy\signal\signaltools.py", line 2424, in resample_poly
    y = upfirdn(h, x, up, down, axis=axis)

  File "F:\Programs\Miniconda3\lib\site-packages\scipy\signal\_upfirdn.py", line 183, in upfirdn
    return ufd.apply_filter(x, axis)

  File "F:\Programs\Miniconda3\lib\site-packages\scipy\signal\_upfirdn.py", line 82, in apply_filter
    output_shape[axis] = output_len

OverflowError: Python int too large to convert to C long
```

output_shape is created on the previous line (81):
`output_shape = np.asarray(x.shape)`

With an unspecified dtype it appears to get np.int32 by default, which is inadequate for specifying large array shapes.

This could be fixed by explicitly specifying the dtype:
`output_shape = np.asarray(x.shape, dtype=np.int64)`

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `scipy/signal/_upfirdn.py`
Content:
```
1 # Code adapted from "upfirdn" python library with permission:
2 #
3 # Copyright (c) 2009, Motorola, Inc
4 #
5 # All Rights Reserved.
6 #
7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions are
9 # met:
10 #
11 # * Redistributions of source code must retain the above copyright notice,
12 # this list of conditions and the following disclaimer.
13 #
14 # * Redistributions in binary form must reproduce the above copyright
15 # notice, this list of conditions and the following disclaimer in the
16 # documentation and/or other materials provided with the distribution.
17 #
18 # * Neither the name of Motorola nor the names of its contributors may be
19 # used to endorse or promote products derived from this software without
20 # specific prior written permission.
21 #
22 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
23 # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
24 # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
26 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
27 # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
29 # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
30 # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
31 # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 
34 import numpy as np
35 
36 from ._upfirdn_apply import _output_len, _apply, mode_enum
37 
38 __all__ = ['upfirdn', '_output_len']
39 
40 _upfirdn_modes = [
41     'constant', 'wrap', 'edge', 'smooth', 'symmetric', 'reflect',
42     'antisymmetric', 'antireflect', 'line',
43 ]
44 
45 
46 def _pad_h(h, up):
47     """Store coefficients in a transposed, flipped arrangement.
48 
49     For example, suppose upRate is 3, and the
50     input number of coefficients is 10, represented as h[0], ..., h[9].
51 
52     Then the internal buffer will look like this::
53 
54        h[9], h[6], h[3], h[0],   // flipped phase 0 coefs
55        0,    h[7], h[4], h[1],   // flipped phase 1 coefs (zero-padded)
56        0,    h[8], h[5], h[2],   // flipped phase 2 coefs (zero-padded)
57 
58     """
59     h_padlen = len(h) + (-len(h) % up)
60     h_full = np.zeros(h_padlen, h.dtype)
61     h_full[:len(h)] = h
62     h_full = h_full.reshape(-1, up).T[:, ::-1].ravel()
63     return h_full
64 
65 
66 def _check_mode(mode):
67     mode = mode.lower()
68     enum = mode_enum(mode)
69     return enum
70 
71 
72 class _UpFIRDn(object):
73     def __init__(self, h, x_dtype, up, down):
74         """Helper for resampling"""
75         h = np.asarray(h)
76         if h.ndim != 1 or h.size == 0:
77             raise ValueError('h must be 1-D with non-zero length')
78         self._output_type = np.result_type(h.dtype, x_dtype, np.float32)
79         h = np.asarray(h, self._output_type)
80         self._up = int(up)
81         self._down = int(down)
82         if self._up < 1 or self._down < 1:
83             raise ValueError('Both up and down must be >= 1')
84         # This both transposes, and "flips" each phase for filtering
85         self._h_trans_flip = _pad_h(h, self._up)
86         self._h_trans_flip = np.ascontiguousarray(self._h_trans_flip)
87 
88     def apply_filter(self, x, axis=-1, mode='constant', cval=0):
89         """Apply the prepared filter to the specified axis of a N-D signal x"""
90         output_len = _output_len(len(self._h_trans_flip), x.shape[axis],
91                                  self._up, self._down)
92         output_shape = np.asarray(x.shape)
93         output_shape[axis] = output_len
94         out = np.zeros(output_shape, dtype=self._output_type, order='C')
95         axis = axis % x.ndim
96         mode = _check_mode(mode)
97         _apply(np.asarray(x, self._output_type),
98                self._h_trans_flip, out,
99                self._up, self._down, axis, mode, cval)
100         return out
101 
102 
103 def upfirdn(h, x, up=1, down=1, axis=-1, mode='constant', cval=0):
104     """Upsample, FIR filter, and downsample
105 
106     Parameters
107     ----------
108     h : array_like
109         1-D FIR (finite-impulse response) filter coefficients.
110     x : array_like
111         Input signal array.
112     up : int, optional
113         Upsampling rate. Default is 1.
114     down : int, optional
115         Downsampling rate. Default is 1.
116     axis : int, optional
117         The axis of the input data array along which to apply the
118         linear filter. The filter is applied to each subarray along
119         this axis. Default is -1.
120     mode : str, optional
121         The signal extension mode to use. The set
122         ``{"constant", "symmetric", "reflect", "edge", "wrap"}`` correspond to
123         modes provided by `numpy.pad`. ``"smooth"`` implements a smooth
124         extension by extending based on the slope of the last 2 points at each
125         end of the array. ``"antireflect"`` and ``"antisymmetric"`` are
126         anti-symmetric versions of ``"reflect"`` and ``"symmetric"``. The mode
127         `"line"` extends the signal based on a linear trend defined by the
128         first and last points along the ``axis``.
129 
130         .. versionadded:: 1.4.0
131     cval : float, optional
132         The constant value to use when ``mode == "constant"``.
133 
134         .. versionadded:: 1.4.0
135 
136     Returns
137     -------
138     y : ndarray
139         The output signal array. Dimensions will be the same as `x` except
140         for along `axis`, which will change size according to the `h`,
141         `up`,  and `down` parameters.
142 
143     Notes
144     -----
145     The algorithm is an implementation of the block diagram shown on page 129
146     of the Vaidyanathan text [1]_ (Figure 4.3-8d).
147 
148     .. [1] P. P. Vaidyanathan, Multirate Systems and Filter Banks,
149        Prentice Hall, 1993.
150 
151     The direct approach of upsampling by factor of P with zero insertion,
152     FIR filtering of length ``N``, and downsampling by factor of Q is
153     O(N*Q) per output sample. The polyphase implementation used here is
154     O(N/P).
155 
156     .. versionadded:: 0.18
157 
158     Examples
159     --------
160     Simple operations:
161 
162     >>> from scipy.signal import upfirdn
163     >>> upfirdn([1, 1, 1], [1, 1, 1])   # FIR filter
164     array([ 1.,  2.,  3.,  2.,  1.])
165     >>> upfirdn([1], [1, 2, 3], 3)  # upsampling with zeros insertion
166     array([ 1.,  0.,  0.,  2.,  0.,  0.,  3.,  0.,  0.])
167     >>> upfirdn([1, 1, 1], [1, 2, 3], 3)  # upsampling with sample-and-hold
168     array([ 1.,  1.,  1.,  2.,  2.,  2.,  3.,  3.,  3.])
169     >>> upfirdn([.5, 1, .5], [1, 1, 1], 2)  # linear interpolation
170     array([ 0.5,  1. ,  1. ,  1. ,  1. ,  1. ,  0.5,  0. ])
171     >>> upfirdn([1], np.arange(10), 1, 3)  # decimation by 3
172     array([ 0.,  3.,  6.,  9.])
173     >>> upfirdn([.5, 1, .5], np.arange(10), 2, 3)  # linear interp, rate 2/3
174     array([ 0. ,  1. ,  2.5,  4. ,  5.5,  7. ,  8.5,  0. ])
175 
176     Apply a single filter to multiple signals:
177 
178     >>> x = np.reshape(np.arange(8), (4, 2))
179     >>> x
180     array([[0, 1],
181            [2, 3],
182            [4, 5],
183            [6, 7]])
184 
185     Apply along the last dimension of ``x``:
186 
187     >>> h = [1, 1]
188     >>> upfirdn(h, x, 2)
189     array([[ 0.,  0.,  1.,  1.],
190            [ 2.,  2.,  3.,  3.],
191            [ 4.,  4.,  5.,  5.],
192            [ 6.,  6.,  7.,  7.]])
193 
194     Apply along the 0th dimension of ``x``:
195 
196     >>> upfirdn(h, x, 2, axis=0)
197     array([[ 0.,  1.],
198            [ 0.,  1.],
199            [ 2.,  3.],
200            [ 2.,  3.],
201            [ 4.,  5.],
202            [ 4.,  5.],
203            [ 6.,  7.],
204            [ 6.,  7.]])
205 
206     """
207     x = np.asarray(x)
208     ufd = _UpFIRDn(h, x.dtype, up, down)
209     # This is equivalent to (but faster than) using np.apply_along_axis
210     return ufd.apply_filter(x, axis, mode, cval)
211
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/scipy/signal/_upfirdn.py b/scipy/signal/_upfirdn.py
--- a/scipy/signal/_upfirdn.py
+++ b/scipy/signal/_upfirdn.py
@@ -89,7 +89,9 @@
         """Apply the prepared filter to the specified axis of a N-D signal x"""
         output_len = _output_len(len(self._h_trans_flip), x.shape[axis],
                                  self._up, self._down)
-        output_shape = np.asarray(x.shape)
+        # Explicit use of np.int64 for output_shape dtype avoids OverflowError
+        # when allocating large array on platforms where np.int_ is 32 bits
+        output_shape = np.asarray(x.shape, dtype=np.int64)
         output_shape[axis] = output_len
         out = np.zeros(output_shape, dtype=self._output_type, order='C')
         axis = axis % x.ndim

{"golden_diff": "diff --git a/scipy/signal/_upfirdn.py b/scipy/signal/_upfirdn.py\n--- a/scipy/signal/_upfirdn.py\n+++ b/scipy/signal/_upfirdn.py\n@@ -89,7 +89,9 @@\n         \"\"\"Apply the prepared filter to the specified axis of a N-D signal x\"\"\"\n         output_len = _output_len(len(self._h_trans_flip), x.shape[axis],\n                                  self._up, self._down)\n-        output_shape = np.asarray(x.shape)\n+        # Explicit use of np.int64 for output_shape dtype avoids OverflowError\n+        # when allocating large array on platforms where np.int_ is 32 bits\n+        output_shape = np.asarray(x.shape, dtype=np.int64)\n         output_shape[axis] = output_len\n         out = np.zeros(output_shape, dtype=self._output_type, order='C')\n         axis = axis % x.ndim\n", "issue": "OverflowError in resample_poly (upfirdn)\nscipy.signal.resample_poly fails if the output vector length would be greater than 2^31-1.\r\n\r\n```\r\nTraceback (most recent call last):\r\n\r\n  File \"<ipython-input-1-ac5d2b0a1632>\", line 11, in <module>\r\n    yy = resample_poly(y, 128, 1)\r\n\r\n  File \"F:\\Programs\\Miniconda3\\lib\\site-packages\\scipy\\signal\\signaltools.py\", line 2424, in resample_poly\r\n    y = upfirdn(h, x, up, down, axis=axis)\r\n\r\n  File \"F:\\Programs\\Miniconda3\\lib\\site-packages\\scipy\\signal\\_upfirdn.py\", line 183, in upfirdn\r\n    return ufd.apply_filter(x, axis)\r\n\r\n  File \"F:\\Programs\\Miniconda3\\lib\\site-packages\\scipy\\signal\\_upfirdn.py\", line 82, in apply_filter\r\n    output_shape[axis] = output_len\r\n\r\nOverflowError: Python int too large to convert to C long\r\n```\r\n\r\noutput_shape is created on the previous line (81):\r\n`output_shape = np.asarray(x.shape)`\r\n\r\nWith an unspecified dtype it appears to get np.int32 by default, which is inadequate for specifying large array shapes.\r\n\r\nThis could be fixed by explicitly specifying the dtype:\r\n`output_shape = np.asarray(x.shape, dtype=np.int64)`\n", "before_files": [{"content": "# Code adapted from \"upfirdn\" python library with permission:\n#\n# Copyright (c) 2009, Motorola, Inc\n#\n# All Rights Reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# * Neither the name of Motorola nor the names of its contributors may be\n# used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport numpy as np\n\nfrom ._upfirdn_apply import _output_len, _apply, mode_enum\n\n__all__ = ['upfirdn', '_output_len']\n\n_upfirdn_modes = [\n    'constant', 'wrap', 'edge', 'smooth', 'symmetric', 'reflect',\n    'antisymmetric', 'antireflect', 'line',\n]\n\n\ndef _pad_h(h, up):\n    \"\"\"Store coefficients in a transposed, flipped arrangement.\n\n    For example, suppose upRate is 3, and the\n    input number of coefficients is 10, represented as h[0], ..., h[9].\n\n    Then the internal buffer will look like this::\n\n       h[9], h[6], h[3], h[0],   // flipped phase 0 coefs\n       0,    h[7], h[4], h[1],   // flipped phase 1 coefs (zero-padded)\n       0,    h[8], h[5], h[2],   // flipped phase 2 coefs (zero-padded)\n\n    \"\"\"\n    h_padlen = len(h) + (-len(h) % up)\n    h_full = np.zeros(h_padlen, h.dtype)\n    h_full[:len(h)] = h\n    h_full = h_full.reshape(-1, up).T[:, ::-1].ravel()\n    return h_full\n\n\ndef _check_mode(mode):\n    mode = mode.lower()\n    enum = mode_enum(mode)\n    return enum\n\n\nclass _UpFIRDn(object):\n    def __init__(self, h, x_dtype, up, down):\n        \"\"\"Helper for resampling\"\"\"\n        h = np.asarray(h)\n        if h.ndim != 1 or h.size == 0:\n            raise ValueError('h must be 1-D with non-zero length')\n        self._output_type = np.result_type(h.dtype, x_dtype, np.float32)\n        h = np.asarray(h, self._output_type)\n        self._up = int(up)\n        self._down = int(down)\n        if self._up < 1 or self._down < 1:\n            raise ValueError('Both up and down must be >= 1')\n        # This both transposes, and \"flips\" each phase for filtering\n        self._h_trans_flip = _pad_h(h, self._up)\n        self._h_trans_flip = np.ascontiguousarray(self._h_trans_flip)\n\n    def apply_filter(self, x, axis=-1, mode='constant', cval=0):\n        \"\"\"Apply the prepared filter to the specified axis of a N-D signal x\"\"\"\n        output_len = _output_len(len(self._h_trans_flip), x.shape[axis],\n                                 self._up, self._down)\n        output_shape = np.asarray(x.shape)\n        output_shape[axis] = output_len\n        out = np.zeros(output_shape, dtype=self._output_type, order='C')\n        axis = axis % x.ndim\n        mode = _check_mode(mode)\n        _apply(np.asarray(x, self._output_type),\n               self._h_trans_flip, out,\n               self._up, self._down, axis, mode, cval)\n        return out\n\n\ndef upfirdn(h, x, up=1, down=1, axis=-1, mode='constant', cval=0):\n    \"\"\"Upsample, FIR filter, and downsample\n\n    Parameters\n    ----------\n    h : array_like\n        1-D FIR (finite-impulse response) filter coefficients.\n    x : array_like\n        Input signal array.\n    up : int, optional\n        Upsampling rate. Default is 1.\n    down : int, optional\n        Downsampling rate. Default is 1.\n    axis : int, optional\n        The axis of the input data array along which to apply the\n        linear filter. The filter is applied to each subarray along\n        this axis. Default is -1.\n    mode : str, optional\n        The signal extension mode to use. The set\n        ``{\"constant\", \"symmetric\", \"reflect\", \"edge\", \"wrap\"}`` correspond to\n        modes provided by `numpy.pad`. ``\"smooth\"`` implements a smooth\n        extension by extending based on the slope of the last 2 points at each\n        end of the array. ``\"antireflect\"`` and ``\"antisymmetric\"`` are\n        anti-symmetric versions of ``\"reflect\"`` and ``\"symmetric\"``. The mode\n        `\"line\"` extends the signal based on a linear trend defined by the\n        first and last points along the ``axis``.\n\n        .. versionadded:: 1.4.0\n    cval : float, optional\n        The constant value to use when ``mode == \"constant\"``.\n\n        .. versionadded:: 1.4.0\n\n    Returns\n    -------\n    y : ndarray\n        The output signal array. Dimensions will be the same as `x` except\n        for along `axis`, which will change size according to the `h`,\n        `up`,  and `down` parameters.\n\n    Notes\n    -----\n    The algorithm is an implementation of the block diagram shown on page 129\n    of the Vaidyanathan text [1]_ (Figure 4.3-8d).\n\n    .. [1] P. P. Vaidyanathan, Multirate Systems and Filter Banks,\n       Prentice Hall, 1993.\n\n    The direct approach of upsampling by factor of P with zero insertion,\n    FIR filtering of length ``N``, and downsampling by factor of Q is\n    O(N*Q) per output sample. The polyphase implementation used here is\n    O(N/P).\n\n    .. versionadded:: 0.18\n\n    Examples\n    --------\n    Simple operations:\n\n    >>> from scipy.signal import upfirdn\n    >>> upfirdn([1, 1, 1], [1, 1, 1])   # FIR filter\n    array([ 1.,  2.,  3.,  2.,  1.])\n    >>> upfirdn([1], [1, 2, 3], 3)  # upsampling with zeros insertion\n    array([ 1.,  0.,  0.,  2.,  0.,  0.,  3.,  0.,  0.])\n    >>> upfirdn([1, 1, 1], [1, 2, 3], 3)  # upsampling with sample-and-hold\n    array([ 1.,  1.,  1.,  2.,  2.,  2.,  3.,  3.,  3.])\n    >>> upfirdn([.5, 1, .5], [1, 1, 1], 2)  # linear interpolation\n    array([ 0.5,  1. ,  1. ,  1. ,  1. ,  1. ,  0.5,  0. ])\n    >>> upfirdn([1], np.arange(10), 1, 3)  # decimation by 3\n    array([ 0.,  3.,  6.,  9.])\n    >>> upfirdn([.5, 1, .5], np.arange(10), 2, 3)  # linear interp, rate 2/3\n    array([ 0. ,  1. ,  2.5,  4. ,  5.5,  7. ,  8.5,  0. ])\n\n    Apply a single filter to multiple signals:\n\n    >>> x = np.reshape(np.arange(8), (4, 2))\n    >>> x\n    array([[0, 1],\n           [2, 3],\n           [4, 5],\n           [6, 7]])\n\n    Apply along the last dimension of ``x``:\n\n    >>> h = [1, 1]\n    >>> upfirdn(h, x, 2)\n    array([[ 0.,  0.,  1.,  1.],\n           [ 2.,  2.,  3.,  3.],\n           [ 4.,  4.,  5.,  5.],\n           [ 6.,  6.,  7.,  7.]])\n\n    Apply along the 0th dimension of ``x``:\n\n    >>> upfirdn(h, x, 2, axis=0)\n    array([[ 0.,  1.],\n           [ 0.,  1.],\n           [ 2.,  3.],\n           [ 2.,  3.],\n           [ 4.,  5.],\n           [ 4.,  5.],\n           [ 6.,  7.],\n           [ 6.,  7.]])\n\n    \"\"\"\n    x = np.asarray(x)\n    ufd = _UpFIRDn(h, x.dtype, up, down)\n    # This is equivalent to (but faster than) using np.apply_along_axis\n    return ufd.apply_filter(x, axis, mode, cval)\n", "path": "scipy/signal/_upfirdn.py"}], "after_files": [{"content": "# Code adapted from \"upfirdn\" python library with permission:\n#\n# Copyright (c) 2009, Motorola, Inc\n#\n# All Rights Reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# * Neither the name of Motorola nor the names of its contributors may be\n# used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport numpy as np\n\nfrom ._upfirdn_apply import _output_len, _apply, mode_enum\n\n__all__ = ['upfirdn', '_output_len']\n\n_upfirdn_modes = [\n    'constant', 'wrap', 'edge', 'smooth', 'symmetric', 'reflect',\n    'antisymmetric', 'antireflect', 'line',\n]\n\n\ndef _pad_h(h, up):\n    \"\"\"Store coefficients in a transposed, flipped arrangement.\n\n    For example, suppose upRate is 3, and the\n    input number of coefficients is 10, represented as h[0], ..., h[9].\n\n    Then the internal buffer will look like this::\n\n       h[9], h[6], h[3], h[0],   // flipped phase 0 coefs\n       0,    h[7], h[4], h[1],   // flipped phase 1 coefs (zero-padded)\n       0,    h[8], h[5], h[2],   // flipped phase 2 coefs (zero-padded)\n\n    \"\"\"\n    h_padlen = len(h) + (-len(h) % up)\n    h_full = np.zeros(h_padlen, h.dtype)\n    h_full[:len(h)] = h\n    h_full = h_full.reshape(-1, up).T[:, ::-1].ravel()\n    return h_full\n\n\ndef _check_mode(mode):\n    mode = mode.lower()\n    enum = mode_enum(mode)\n    return enum\n\n\nclass _UpFIRDn(object):\n    def __init__(self, h, x_dtype, up, down):\n        \"\"\"Helper for resampling\"\"\"\n        h = np.asarray(h)\n        if h.ndim != 1 or h.size == 0:\n            raise ValueError('h must be 1-D with non-zero length')\n        self._output_type = np.result_type(h.dtype, x_dtype, np.float32)\n        h = np.asarray(h, self._output_type)\n        self._up = int(up)\n        self._down = int(down)\n        if self._up < 1 or self._down < 1:\n            raise ValueError('Both up and down must be >= 1')\n        # This both transposes, and \"flips\" each phase for filtering\n        self._h_trans_flip = _pad_h(h, self._up)\n        self._h_trans_flip = np.ascontiguousarray(self._h_trans_flip)\n\n    def apply_filter(self, x, axis=-1, mode='constant', cval=0):\n        \"\"\"Apply the prepared filter to the specified axis of a N-D signal x\"\"\"\n        output_len = _output_len(len(self._h_trans_flip), x.shape[axis],\n                                 self._up, self._down)\n        # Explicit use of np.int64 for output_shape dtype avoids OverflowError\n        # when allocating large array on platforms where np.int_ is 32 bits\n        output_shape = np.asarray(x.shape, dtype=np.int64)\n        output_shape[axis] = output_len\n        out = np.zeros(output_shape, dtype=self._output_type, order='C')\n        axis = axis % x.ndim\n        mode = _check_mode(mode)\n        _apply(np.asarray(x, self._output_type),\n               self._h_trans_flip, out,\n               self._up, self._down, axis, mode, cval)\n        return out\n\n\ndef upfirdn(h, x, up=1, down=1, axis=-1, mode='constant', cval=0):\n    \"\"\"Upsample, FIR filter, and downsample\n\n    Parameters\n    ----------\n    h : array_like\n        1-D FIR (finite-impulse response) filter coefficients.\n    x : array_like\n        Input signal array.\n    up : int, optional\n        Upsampling rate. Default is 1.\n    down : int, optional\n        Downsampling rate. Default is 1.\n    axis : int, optional\n        The axis of the input data array along which to apply the\n        linear filter. The filter is applied to each subarray along\n        this axis. Default is -1.\n    mode : str, optional\n        The signal extension mode to use. The set\n        ``{\"constant\", \"symmetric\", \"reflect\", \"edge\", \"wrap\"}`` correspond to\n        modes provided by `numpy.pad`. ``\"smooth\"`` implements a smooth\n        extension by extending based on the slope of the last 2 points at each\n        end of the array. ``\"antireflect\"`` and ``\"antisymmetric\"`` are\n        anti-symmetric versions of ``\"reflect\"`` and ``\"symmetric\"``. The mode\n        `\"line\"` extends the signal based on a linear trend defined by the\n        first and last points along the ``axis``.\n\n        .. versionadded:: 1.4.0\n    cval : float, optional\n        The constant value to use when ``mode == \"constant\"``.\n\n        .. versionadded:: 1.4.0\n\n    Returns\n    -------\n    y : ndarray\n        The output signal array. Dimensions will be the same as `x` except\n        for along `axis`, which will change size according to the `h`,\n        `up`,  and `down` parameters.\n\n    Notes\n    -----\n    The algorithm is an implementation of the block diagram shown on page 129\n    of the Vaidyanathan text [1]_ (Figure 4.3-8d).\n\n    .. [1] P. P. Vaidyanathan, Multirate Systems and Filter Banks,\n       Prentice Hall, 1993.\n\n    The direct approach of upsampling by factor of P with zero insertion,\n    FIR filtering of length ``N``, and downsampling by factor of Q is\n    O(N*Q) per output sample. The polyphase implementation used here is\n    O(N/P).\n\n    .. versionadded:: 0.18\n\n    Examples\n    --------\n    Simple operations:\n\n    >>> from scipy.signal import upfirdn\n    >>> upfirdn([1, 1, 1], [1, 1, 1])   # FIR filter\n    array([ 1.,  2.,  3.,  2.,  1.])\n    >>> upfirdn([1], [1, 2, 3], 3)  # upsampling with zeros insertion\n    array([ 1.,  0.,  0.,  2.,  0.,  0.,  3.,  0.,  0.])\n    >>> upfirdn([1, 1, 1], [1, 2, 3], 3)  # upsampling with sample-and-hold\n    array([ 1.,  1.,  1.,  2.,  2.,  2.,  3.,  3.,  3.])\n    >>> upfirdn([.5, 1, .5], [1, 1, 1], 2)  # linear interpolation\n    array([ 0.5,  1. ,  1. ,  1. ,  1. ,  1. ,  0.5,  0. ])\n    >>> upfirdn([1], np.arange(10), 1, 3)  # decimation by 3\n    array([ 0.,  3.,  6.,  9.])\n    >>> upfirdn([.5, 1, .5], np.arange(10), 2, 3)  # linear interp, rate 2/3\n    array([ 0. ,  1. ,  2.5,  4. ,  5.5,  7. ,  8.5,  0. ])\n\n    Apply a single filter to multiple signals:\n\n    >>> x = np.reshape(np.arange(8), (4, 2))\n    >>> x\n    array([[0, 1],\n           [2, 3],\n           [4, 5],\n           [6, 7]])\n\n    Apply along the last dimension of ``x``:\n\n    >>> h = [1, 1]\n    >>> upfirdn(h, x, 2)\n    array([[ 0.,  0.,  1.,  1.],\n           [ 2.,  2.,  3.,  3.],\n           [ 4.,  4.,  5.,  5.],\n           [ 6.,  6.,  7.,  7.]])\n\n    Apply along the 0th dimension of ``x``:\n\n    >>> upfirdn(h, x, 2, axis=0)\n    array([[ 0.,  1.],\n           [ 0.,  1.],\n           [ 2.,  3.],\n           [ 2.,  3.],\n           [ 4.,  5.],\n           [ 4.,  5.],\n           [ 6.,  7.],\n           [ 6.,  7.]])\n\n    \"\"\"\n    x = np.asarray(x)\n    ufd = _UpFIRDn(h, x.dtype, up, down)\n    # This is equivalent to (but faster than) using np.apply_along_axis\n    return ufd.apply_filter(x, axis, mode, cval)\n", "path": "scipy/signal/_upfirdn.py"}]}