Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- vglm/bin/python +3 -0
- videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_log2_native.h +25 -0
- videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sqrt_native.h +25 -0
- videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/grid_sampler_native.h +21 -0
- videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/hstack_ops.h +39 -0
- videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/native_layer_norm_cpu_dispatch.h +24 -0
- videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/renorm_meta.h +27 -0
- videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sinh_cuda_dispatch.h +26 -0
- videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sparse_resize_and_clear_ops.h +50 -0
- vllm/lib/python3.10/site-packages/cupyx/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/__pycache__/_rsqrt.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/__pycache__/_runtime.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/__pycache__/_scatter.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/__pycache__/time.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/__init__.py +35 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/_lib/__init__.py +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/_lib/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/_lib/__pycache__/_util.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/_lib/_util.py +73 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/fftpack/__init__.py +9 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/fftpack/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/fftpack/__pycache__/_fft.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/fftpack/_fft.py +508 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__init__.py +175 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_czt.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_filter_design.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_iir_filter_conversions.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_iir_filter_design.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_iir_utils.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_lti_conversion.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_ltisys.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_max_len_seq.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_resample.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_signaltools.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_signaltools_core.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_spectral_impl.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_splines.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_upfirdn.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_arraytools.py +272 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_bsplines.py +596 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_czt.py +451 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_filter_design.py +811 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_fir_filter_design.py +918 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_iir_filter_conversions.py +2364 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_iir_filter_design.py +994 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_iir_utils.py +737 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_lti_conversion.py +82 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_ltisys.py +0 -0
- vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_max_len_seq.py +119 -0
.gitattributes
CHANGED
|
@@ -1438,3 +1438,4 @@ parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_numeric.c
|
|
| 1438 |
parrot/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_function_base.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1439 |
vllm/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__pycache__/_async_client.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1440 |
vllm/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_client.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 1438 |
parrot/lib/python3.10/site-packages/numpy/lib/tests/__pycache__/test_function_base.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1439 |
vllm/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__pycache__/_async_client.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1440 |
vllm/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_client.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1441 |
+
vglm/bin/python filter=lfs diff=lfs merge=lfs -text
|
vglm/bin/python
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a5893c715ba63b749ab2bb330a28cd17a9e1f8ab65c7b580e714da9cec0caee3
|
| 3 |
+
size 17225608
|
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_log2_native.h
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API void _foreach_log2_out(at::TensorList self, at::TensorList out);
|
| 20 |
+
TORCH_API ::std::vector<at::Tensor> foreach_tensor_log2_slow(at::TensorList self);
|
| 21 |
+
TORCH_API void foreach_tensor_log2_slow_(at::TensorList self);
|
| 22 |
+
TORCH_API ::std::vector<at::Tensor> foreach_tensor_log2_cuda(at::TensorList self);
|
| 23 |
+
TORCH_API void foreach_tensor_log2_cuda_(at::TensorList self);
|
| 24 |
+
} // namespace native
|
| 25 |
+
} // namespace at
|
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sqrt_native.h
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API void _foreach_sqrt_out(at::TensorList self, at::TensorList out);
|
| 20 |
+
TORCH_API ::std::vector<at::Tensor> foreach_tensor_sqrt_slow(at::TensorList self);
|
| 21 |
+
TORCH_API void foreach_tensor_sqrt_slow_(at::TensorList self);
|
| 22 |
+
TORCH_API ::std::vector<at::Tensor> foreach_tensor_sqrt_cuda(at::TensorList self);
|
| 23 |
+
TORCH_API void foreach_tensor_sqrt_cuda_(at::TensorList self);
|
| 24 |
+
} // namespace native
|
| 25 |
+
} // namespace at
|
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/grid_sampler_native.h
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API at::Tensor grid_sampler(const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners);
|
| 20 |
+
} // namespace native
|
| 21 |
+
} // namespace at
|
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/hstack_ops.h
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <tuple>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 9 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 10 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 11 |
+
#include <ATen/core/ATen_fwd.h>
|
| 12 |
+
|
| 13 |
+
namespace at {
|
| 14 |
+
namespace _ops {
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
struct TORCH_API hstack {
|
| 18 |
+
using schema = at::Tensor (at::TensorList);
|
| 19 |
+
using ptr_schema = schema*;
|
| 20 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 21 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::hstack")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "hstack(Tensor[] tensors) -> Tensor")
|
| 24 |
+
static at::Tensor call(at::TensorList tensors);
|
| 25 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList tensors);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct TORCH_API hstack_out {
|
| 29 |
+
using schema = at::Tensor & (at::TensorList, at::Tensor &);
|
| 30 |
+
using ptr_schema = schema*;
|
| 31 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 32 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::hstack")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "hstack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!)")
|
| 35 |
+
static at::Tensor & call(at::TensorList tensors, at::Tensor & out);
|
| 36 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList tensors, at::Tensor & out);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
}} // namespace at::_ops
|
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/native_layer_norm_cpu_dispatch.h
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace cpu {
|
| 19 |
+
|
| 20 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> native_layer_norm(const at::Tensor & input, at::IntArrayRef normalized_shape, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & bias, double eps);
|
| 21 |
+
TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> native_layer_norm_symint(const at::Tensor & input, c10::SymIntArrayRef normalized_shape, const c10::optional<at::Tensor> & weight, const c10::optional<at::Tensor> & bias, double eps);
|
| 22 |
+
|
| 23 |
+
} // namespace cpu
|
| 24 |
+
} // namespace at
|
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/renorm_meta.h
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeMetaFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/TensorIterator.h>
|
| 13 |
+
#include <ATen/TensorMeta.h>
|
| 14 |
+
#include <tuple>
|
| 15 |
+
#include <vector>
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace meta {
|
| 19 |
+
|
| 20 |
+
struct TORCH_API structured_renorm : public at::impl::MetaBase {
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
void meta(const at::Tensor & self, const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm);
|
| 24 |
+
};
|
| 25 |
+
|
| 26 |
+
} // namespace native
|
| 27 |
+
} // namespace at
|
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sinh_cuda_dispatch.h
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace cuda {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor sinh(const at::Tensor & self);
|
| 21 |
+
TORCH_API at::Tensor & sinh_out(at::Tensor & out, const at::Tensor & self);
|
| 22 |
+
TORCH_API at::Tensor & sinh_outf(const at::Tensor & self, at::Tensor & out);
|
| 23 |
+
TORCH_API at::Tensor & sinh_(at::Tensor & self);
|
| 24 |
+
|
| 25 |
+
} // namespace cuda
|
| 26 |
+
} // namespace at
|
videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sparse_resize_and_clear_ops.h
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <tuple>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 9 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 10 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 11 |
+
#include <ATen/core/ATen_fwd.h>
|
| 12 |
+
|
| 13 |
+
namespace at {
|
| 14 |
+
namespace _ops {
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
struct TORCH_API sparse_resize_and_clear_ {
|
| 18 |
+
using schema = const at::Tensor & (const at::Tensor &, at::IntArrayRef, int64_t, int64_t);
|
| 19 |
+
using ptr_schema = schema*;
|
| 20 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 21 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::sparse_resize_and_clear_")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "sparse_resize_and_clear_(Tensor(a!) self, int[] size, int sparse_dim, int dense_dim) -> Tensor(a!)")
|
| 24 |
+
static const at::Tensor & call(const at::Tensor & self, at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim);
|
| 25 |
+
static const at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
struct TORCH_API sparse_resize_and_clear_out {
|
| 29 |
+
using schema = const at::Tensor & (const at::Tensor &, at::IntArrayRef, int64_t, int64_t, const at::Tensor &);
|
| 30 |
+
using ptr_schema = schema*;
|
| 31 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 32 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::sparse_resize_and_clear")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "sparse_resize_and_clear.out(Tensor self, int[] size, int sparse_dim, int dense_dim, *, Tensor(a!) out) -> Tensor(a!)")
|
| 35 |
+
static const at::Tensor & call(const at::Tensor & self, at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim, const at::Tensor & out);
|
| 36 |
+
static const at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim, const at::Tensor & out);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
struct TORCH_API sparse_resize_and_clear {
|
| 40 |
+
using schema = at::Tensor (const at::Tensor &, at::IntArrayRef, int64_t, int64_t);
|
| 41 |
+
using ptr_schema = schema*;
|
| 42 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 43 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::sparse_resize_and_clear")
|
| 44 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 45 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "sparse_resize_and_clear(Tensor self, int[] size, int sparse_dim, int dense_dim) -> Tensor")
|
| 46 |
+
static at::Tensor call(const at::Tensor & self, at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim);
|
| 47 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef size, int64_t sparse_dim, int64_t dense_dim);
|
| 48 |
+
};
|
| 49 |
+
|
| 50 |
+
}} // namespace at::_ops
|
vllm/lib/python3.10/site-packages/cupyx/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.19 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/__pycache__/_rsqrt.cpython-310.pyc
ADDED
|
Binary file (347 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/__pycache__/_runtime.cpython-310.pyc
ADDED
|
Binary file (8.4 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/__pycache__/_scatter.cpython-310.pyc
ADDED
|
Binary file (5.27 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/__pycache__/time.cpython-310.pyc
ADDED
|
Binary file (3.39 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys as _sys
|
| 2 |
+
|
| 3 |
+
from cupy._core import ndarray as _ndarray
|
| 4 |
+
from cupyx.scipy.sparse._base import spmatrix as _spmatrix
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
import scipy as _scipy
|
| 9 |
+
_scipy_available = True
|
| 10 |
+
except ImportError:
|
| 11 |
+
_scipy_available = False
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
_cupyx_scipy = _sys.modules[__name__]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_array_module(*args):
|
| 18 |
+
"""Returns the array module for arguments.
|
| 19 |
+
|
| 20 |
+
This function is used to implement CPU/GPU generic code. If at least one of
|
| 21 |
+
the arguments is a :class:`cupy.ndarray` object, the :mod:`cupyx.scipy`
|
| 22 |
+
module is returned.
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
args: Values to determine whether NumPy or CuPy should be used.
|
| 26 |
+
|
| 27 |
+
Returns:
|
| 28 |
+
module: :mod:`cupyx.scipy` or :mod:`scipy` is returned based on the
|
| 29 |
+
types of the arguments.
|
| 30 |
+
|
| 31 |
+
"""
|
| 32 |
+
for arg in args:
|
| 33 |
+
if isinstance(arg, (_ndarray, _spmatrix)):
|
| 34 |
+
return _cupyx_scipy
|
| 35 |
+
return _scipy
|
vllm/lib/python3.10/site-packages/cupyx/scipy/_lib/__init__.py
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/cupyx/scipy/_lib/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (166 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/_lib/__pycache__/_util.cpython-310.pyc
ADDED
|
Binary file (2.17 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/_lib/_util.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import cupy
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def float_factorial(n):
|
| 7 |
+
"""Compute the factorial and return as a float
|
| 8 |
+
|
| 9 |
+
Returns infinity when result is too large for a double
|
| 10 |
+
"""
|
| 11 |
+
return float(math.factorial(n)) if n < 171 else cupy.inf
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _asarray_validated(a, check_finite=True,
|
| 15 |
+
sparse_ok=False, objects_ok=False, mask_ok=False,
|
| 16 |
+
as_inexact=False):
|
| 17 |
+
"""Helper function for SciPy argument validation.
|
| 18 |
+
|
| 19 |
+
Many CuPy linear algebra functions do support arbitrary array-like
|
| 20 |
+
input arguments. Examples of commonly unsupported inputs include
|
| 21 |
+
matrices containing inf/nan, sparse matrix representations, and
|
| 22 |
+
matrices with complicated elements.
|
| 23 |
+
|
| 24 |
+
Parameters
|
| 25 |
+
----------
|
| 26 |
+
a : array-like
|
| 27 |
+
The array-like input
|
| 28 |
+
check_finite : bool, optional
|
| 29 |
+
By default True. To check whether the input matrices contain
|
| 30 |
+
only finite numbers. Disabling may give a performance gain,
|
| 31 |
+
but may result in problems (crashes, non-termination) if the
|
| 32 |
+
inputs do contain infinites or NaNs
|
| 33 |
+
sparse_ok : bool, optional
|
| 34 |
+
By default False. True if cupy sparse matrices are allowed
|
| 35 |
+
objects_ok : bool, optional
|
| 36 |
+
By default False. True if arrays with dype('O') are allowed
|
| 37 |
+
mask_ok : bool, optional
|
| 38 |
+
By default False. True if masked arrays are allowed.
|
| 39 |
+
as_inexact : bool, optional
|
| 40 |
+
By default False. True to convert the input array to a
|
| 41 |
+
cupy.inexact dtype
|
| 42 |
+
|
| 43 |
+
Returns
|
| 44 |
+
-------
|
| 45 |
+
ret : cupy.ndarray
|
| 46 |
+
The converted validated array
|
| 47 |
+
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
if not sparse_ok:
|
| 51 |
+
import cupyx.scipy.sparse
|
| 52 |
+
if cupyx.scipy.sparse.issparse(a):
|
| 53 |
+
msg = ('Sparse matrices are not supported by this function. '
|
| 54 |
+
'Perhaps one of the cupyx.scipy.sparse.linalg functions '
|
| 55 |
+
'would work instead.')
|
| 56 |
+
raise ValueError(msg)
|
| 57 |
+
|
| 58 |
+
# TODO: remove these comments when CuPy supports masked arrays
|
| 59 |
+
# Ref Issue: https://github.com/cupy/cupy/issues/2225
|
| 60 |
+
# if not mask_ok:
|
| 61 |
+
# if cupy.ma.isMaskedArray(a):
|
| 62 |
+
# raise ValueError('masked arrays are not supported')
|
| 63 |
+
|
| 64 |
+
# TODO: remove these comments when CuPy supports 'object' dtype
|
| 65 |
+
# if not objects_ok:
|
| 66 |
+
# if a.dtype is cupy.dtype('O'):
|
| 67 |
+
# raise ValueError('object arrays are not supported')
|
| 68 |
+
|
| 69 |
+
if as_inexact:
|
| 70 |
+
if not cupy.issubdtype(a, cupy.inexact):
|
| 71 |
+
a = a.astype(dtype=cupy.float64)
|
| 72 |
+
|
| 73 |
+
return a
|
vllm/lib/python3.10/site-packages/cupyx/scipy/fftpack/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from cupyx.scipy.fftpack._fft import fft # NOQA
|
| 2 |
+
from cupyx.scipy.fftpack._fft import fft2 # NOQA
|
| 3 |
+
from cupyx.scipy.fftpack._fft import fftn # NOQA
|
| 4 |
+
from cupyx.scipy.fftpack._fft import ifft # NOQA
|
| 5 |
+
from cupyx.scipy.fftpack._fft import ifft2 # NOQA
|
| 6 |
+
from cupyx.scipy.fftpack._fft import ifftn # NOQA
|
| 7 |
+
from cupyx.scipy.fftpack._fft import irfft # NOQA
|
| 8 |
+
from cupyx.scipy.fftpack._fft import rfft # NOQA
|
| 9 |
+
from cupyx.scipy.fftpack._fft import get_fft_plan # NOQA
|
vllm/lib/python3.10/site-packages/cupyx/scipy/fftpack/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (448 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/fftpack/__pycache__/_fft.cpython-310.pyc
ADDED
|
Binary file (16.8 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/fftpack/_fft.py
ADDED
|
@@ -0,0 +1,508 @@
|
|
|
|
|
|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
| 3 |
+
import cupy
|
| 4 |
+
from cupy.fft import config
|
| 5 |
+
from cupy.fft._fft import (_convert_fft_type, _default_fft_func, _fft,
|
| 6 |
+
_get_cufft_plan_nd, _get_fftn_out_size,
|
| 7 |
+
_output_dtype)
|
| 8 |
+
from cupy.fft._cache import get_plan_cache
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def get_fft_plan(a, shape=None, axes=None, value_type='C2C'):
|
| 12 |
+
""" Generate a CUDA FFT plan for transforming up to three axes.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
a (cupy.ndarray): Array to be transform, assumed to be either C- or
|
| 16 |
+
F- contiguous.
|
| 17 |
+
shape (None or tuple of ints): Shape of the transformed axes of the
|
| 18 |
+
output. If ``shape`` is not given, the lengths of the input along
|
| 19 |
+
the axes specified by ``axes`` are used.
|
| 20 |
+
axes (None or int or tuple of int): The axes of the array to
|
| 21 |
+
transform. If `None`, it is assumed that all axes are transformed.
|
| 22 |
+
|
| 23 |
+
Currently, for performing N-D transform these must be a set of up
|
| 24 |
+
to three adjacent axes, and must include either the first or the
|
| 25 |
+
last axis of the array.
|
| 26 |
+
value_type (str): The FFT type to perform. Acceptable values are:
|
| 27 |
+
|
| 28 |
+
* 'C2C': complex-to-complex transform (default)
|
| 29 |
+
* 'R2C': real-to-complex transform
|
| 30 |
+
* 'C2R': complex-to-real transform
|
| 31 |
+
|
| 32 |
+
Returns:
|
| 33 |
+
a cuFFT plan for either 1D transform (``cupy.cuda.cufft.Plan1d``) or
|
| 34 |
+
N-D transform (``cupy.cuda.cufft.PlanNd``).
|
| 35 |
+
|
| 36 |
+
.. note::
|
| 37 |
+
The returned plan can not only be passed as one of the arguments of
|
| 38 |
+
the functions in ``cupyx.scipy.fftpack``, but also be used as a
|
| 39 |
+
context manager for both ``cupy.fft`` and ``cupyx.scipy.fftpack``
|
| 40 |
+
functions:
|
| 41 |
+
|
| 42 |
+
.. code-block:: python
|
| 43 |
+
|
| 44 |
+
x = cupy.random.random(16).reshape(4, 4).astype(complex)
|
| 45 |
+
plan = cupyx.scipy.fftpack.get_fft_plan(x)
|
| 46 |
+
with plan:
|
| 47 |
+
y = cupy.fft.fftn(x)
|
| 48 |
+
# alternatively:
|
| 49 |
+
y = cupyx.scipy.fftpack.fftn(x) # no explicit plan is given!
|
| 50 |
+
# alternatively:
|
| 51 |
+
y = cupyx.scipy.fftpack.fftn(x, plan=plan) # pass plan explicitly
|
| 52 |
+
|
| 53 |
+
In the first case, no cuFFT plan will be generated automatically,
|
| 54 |
+
even if ``cupy.fft.config.enable_nd_planning = True`` is set.
|
| 55 |
+
|
| 56 |
+
.. note::
|
| 57 |
+
If this function is called under the context of
|
| 58 |
+
:func:`~cupy.fft.config.set_cufft_callbacks`, the generated plan will
|
| 59 |
+
have callbacks enabled.
|
| 60 |
+
|
| 61 |
+
.. warning::
|
| 62 |
+
This API is a deviation from SciPy's, is currently experimental, and
|
| 63 |
+
may be changed in the future version.
|
| 64 |
+
"""
|
| 65 |
+
from cupy.cuda import cufft
|
| 66 |
+
|
| 67 |
+
# check input array
|
| 68 |
+
if a.flags.c_contiguous:
|
| 69 |
+
order = 'C'
|
| 70 |
+
elif a.flags.f_contiguous:
|
| 71 |
+
order = 'F'
|
| 72 |
+
else:
|
| 73 |
+
raise ValueError('Input array a must be contiguous')
|
| 74 |
+
|
| 75 |
+
if isinstance(shape, int):
|
| 76 |
+
shape = (shape,)
|
| 77 |
+
if isinstance(axes, int):
|
| 78 |
+
axes = (axes,)
|
| 79 |
+
if (shape is not None) and (axes is not None) and len(shape) != len(axes):
|
| 80 |
+
raise ValueError('Shape and axes have different lengths.')
|
| 81 |
+
|
| 82 |
+
# check axes
|
| 83 |
+
# n=1: 1d (need axis1D); n>1: Nd
|
| 84 |
+
if axes is None:
|
| 85 |
+
n = a.ndim if shape is None else len(shape)
|
| 86 |
+
axes = tuple(i for i in range(-n, 0))
|
| 87 |
+
if n == 1:
|
| 88 |
+
axis1D = 0
|
| 89 |
+
else: # axes is a tuple
|
| 90 |
+
n = len(axes)
|
| 91 |
+
if n == 1:
|
| 92 |
+
axis1D = axes[0]
|
| 93 |
+
if axis1D >= a.ndim or axis1D < -a.ndim:
|
| 94 |
+
err = 'The chosen axis ({0}) exceeds the number of '\
|
| 95 |
+
'dimensions of a ({1})'.format(axis1D, a.ndim)
|
| 96 |
+
raise ValueError(err)
|
| 97 |
+
elif n > 3:
|
| 98 |
+
raise ValueError('Only up to three axes is supported')
|
| 99 |
+
|
| 100 |
+
# Note that "shape" here refers to the shape along transformed axes, not
|
| 101 |
+
# the shape of the output array, and we need to convert it to the latter.
|
| 102 |
+
# The result is as if "a=_cook_shape(a); return a.shape" is called.
|
| 103 |
+
# Because of this, we need to use (possibly unsorted) axes.
|
| 104 |
+
transformed_shape = shape
|
| 105 |
+
shape = list(a.shape)
|
| 106 |
+
if transformed_shape is not None:
|
| 107 |
+
for s, axis in zip(transformed_shape, axes):
|
| 108 |
+
if s is not None:
|
| 109 |
+
if axis == axes[-1] and value_type == 'C2R':
|
| 110 |
+
s = s // 2 + 1
|
| 111 |
+
shape[axis] = s
|
| 112 |
+
shape = tuple(shape)
|
| 113 |
+
|
| 114 |
+
# check value_type
|
| 115 |
+
out_dtype = _output_dtype(a.dtype, value_type)
|
| 116 |
+
fft_type = _convert_fft_type(out_dtype, value_type)
|
| 117 |
+
# TODO(leofang): figure out if we really have to skip F-order?
|
| 118 |
+
if n > 1 and value_type != 'C2C' and a.flags.f_contiguous:
|
| 119 |
+
raise ValueError('C2R/R2C PlanNd for F-order arrays is not supported')
|
| 120 |
+
|
| 121 |
+
# generate plan
|
| 122 |
+
# (load from cache if it exists, otherwise create one but don't cache it)
|
| 123 |
+
if n > 1: # ND transform
|
| 124 |
+
if cupy.cuda.runtime.is_hip and value_type == 'C2R':
|
| 125 |
+
raise RuntimeError("hipFFT's C2R PlanNd is buggy and unsupported")
|
| 126 |
+
out_size = _get_fftn_out_size(
|
| 127 |
+
shape, transformed_shape, axes[-1], value_type)
|
| 128 |
+
# _get_cufft_plan_nd interacts with plan cache and callback
|
| 129 |
+
plan = _get_cufft_plan_nd(
|
| 130 |
+
shape, fft_type, axes=axes, order=order, out_size=out_size,
|
| 131 |
+
to_cache=False)
|
| 132 |
+
else: # 1D transform
|
| 133 |
+
# prepare plan arguments
|
| 134 |
+
if value_type != 'C2R':
|
| 135 |
+
out_size = shape[axis1D]
|
| 136 |
+
else:
|
| 137 |
+
out_size = _get_fftn_out_size(
|
| 138 |
+
shape, transformed_shape, axis1D, value_type)
|
| 139 |
+
batch = prod(shape) // shape[axis1D]
|
| 140 |
+
devices = None if not config.use_multi_gpus else config._devices
|
| 141 |
+
|
| 142 |
+
keys = (out_size, fft_type, batch, devices)
|
| 143 |
+
mgr = config.get_current_callback_manager()
|
| 144 |
+
if mgr is not None:
|
| 145 |
+
# to avoid a weird segfault, we generate and cache distinct plans
|
| 146 |
+
# for every possible (load_aux, store_aux) pairs; the plans are
|
| 147 |
+
# still generated from the same external Python module
|
| 148 |
+
load_aux = mgr.cb_load_aux_arr
|
| 149 |
+
store_aux = mgr.cb_store_aux_arr
|
| 150 |
+
keys += (mgr.cb_load, mgr.cb_store,
|
| 151 |
+
0 if load_aux is None else load_aux.data.ptr,
|
| 152 |
+
0 if store_aux is None else store_aux.data.ptr)
|
| 153 |
+
cache = get_plan_cache()
|
| 154 |
+
cached_plan = cache.get(keys)
|
| 155 |
+
if cached_plan is not None:
|
| 156 |
+
plan = cached_plan
|
| 157 |
+
elif mgr is None:
|
| 158 |
+
plan = cufft.Plan1d(out_size, fft_type, batch, devices=devices)
|
| 159 |
+
else: # has callback
|
| 160 |
+
# TODO(leofang): support multi-GPU callback (devices is ignored)
|
| 161 |
+
if devices:
|
| 162 |
+
raise NotImplementedError('multi-GPU cuFFT callbacks are not '
|
| 163 |
+
'yet supported')
|
| 164 |
+
plan = mgr.create_plan(('Plan1d', keys[:-3]))
|
| 165 |
+
mgr.set_callbacks(plan)
|
| 166 |
+
|
| 167 |
+
return plan
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def fft(x, n=None, axis=-1, overwrite_x=False, plan=None):
|
| 171 |
+
"""Compute the one-dimensional FFT.
|
| 172 |
+
|
| 173 |
+
Args:
|
| 174 |
+
x (cupy.ndarray): Array to be transformed.
|
| 175 |
+
n (None or int): Length of the transformed axis of the output. If ``n``
|
| 176 |
+
is not given, the length of the input along the axis specified by
|
| 177 |
+
``axis`` is used.
|
| 178 |
+
axis (int): Axis over which to compute the FFT.
|
| 179 |
+
overwrite_x (bool): If True, the contents of ``x`` can be destroyed.
|
| 180 |
+
plan (:class:`cupy.cuda.cufft.Plan1d` or ``None``): a cuFFT plan for
|
| 181 |
+
transforming ``x`` over ``axis``, which can be obtained using::
|
| 182 |
+
|
| 183 |
+
plan = cupyx.scipy.fftpack.get_fft_plan(x, axis)
|
| 184 |
+
|
| 185 |
+
Note that `plan` is defaulted to None, meaning CuPy will use an
|
| 186 |
+
auto-generated plan behind the scene.
|
| 187 |
+
|
| 188 |
+
Returns:
|
| 189 |
+
cupy.ndarray:
|
| 190 |
+
The transformed array which shape is specified by ``n`` and type
|
| 191 |
+
will convert to complex if that of the input is another.
|
| 192 |
+
|
| 193 |
+
.. note::
|
| 194 |
+
The argument `plan` is currently experimental and the interface may be
|
| 195 |
+
changed in the future version.
|
| 196 |
+
|
| 197 |
+
.. seealso:: :func:`scipy.fftpack.fft`
|
| 198 |
+
"""
|
| 199 |
+
from cupy.cuda import cufft
|
| 200 |
+
return _fft(x, (n,), (axis,), None, cufft.CUFFT_FORWARD,
|
| 201 |
+
overwrite_x=overwrite_x, plan=plan)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def ifft(x, n=None, axis=-1, overwrite_x=False, plan=None):
|
| 205 |
+
"""Compute the one-dimensional inverse FFT.
|
| 206 |
+
|
| 207 |
+
Args:
|
| 208 |
+
x (cupy.ndarray): Array to be transformed.
|
| 209 |
+
n (None or int): Length of the transformed axis of the output. If ``n``
|
| 210 |
+
is not given, the length of the input along the axis specified by
|
| 211 |
+
``axis`` is used.
|
| 212 |
+
axis (int): Axis over which to compute the FFT.
|
| 213 |
+
overwrite_x (bool): If True, the contents of ``x`` can be destroyed.
|
| 214 |
+
plan (:class:`cupy.cuda.cufft.Plan1d` or ``None``): a cuFFT plan for
|
| 215 |
+
transforming ``x`` over ``axis``, which can be obtained using::
|
| 216 |
+
|
| 217 |
+
plan = cupyx.scipy.fftpack.get_fft_plan(x, axis)
|
| 218 |
+
|
| 219 |
+
Note that `plan` is defaulted to None, meaning CuPy will use an
|
| 220 |
+
auto-generated plan behind the scene.
|
| 221 |
+
|
| 222 |
+
Returns:
|
| 223 |
+
cupy.ndarray:
|
| 224 |
+
The transformed array which shape is specified by ``n`` and type
|
| 225 |
+
will convert to complex if that of the input is another.
|
| 226 |
+
|
| 227 |
+
.. note::
|
| 228 |
+
The argument `plan` is currently experimental and the interface may be
|
| 229 |
+
changed in the future version.
|
| 230 |
+
|
| 231 |
+
.. seealso:: :func:`scipy.fftpack.ifft`
|
| 232 |
+
"""
|
| 233 |
+
from cupy.cuda import cufft
|
| 234 |
+
return _fft(x, (n,), (axis,), None, cufft.CUFFT_INVERSE,
|
| 235 |
+
overwrite_x=overwrite_x, plan=plan)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def fft2(x, shape=None, axes=(-2, -1), overwrite_x=False, plan=None):
|
| 239 |
+
"""Compute the two-dimensional FFT.
|
| 240 |
+
|
| 241 |
+
Args:
|
| 242 |
+
x (cupy.ndarray): Array to be transformed.
|
| 243 |
+
shape (None or tuple of ints): Shape of the transformed axes of the
|
| 244 |
+
output. If ``shape`` is not given, the lengths of the input along
|
| 245 |
+
the axes specified by ``axes`` are used.
|
| 246 |
+
axes (tuple of ints): Axes over which to compute the FFT.
|
| 247 |
+
overwrite_x (bool): If True, the contents of ``x`` can be destroyed.
|
| 248 |
+
plan (:class:`cupy.cuda.cufft.PlanNd` or ``None``): a cuFFT plan for
|
| 249 |
+
transforming ``x`` over ``axes``, which can be obtained using::
|
| 250 |
+
|
| 251 |
+
plan = cupyx.scipy.fftpack.get_fft_plan(x, axes)
|
| 252 |
+
|
| 253 |
+
Note that `plan` is defaulted to None, meaning CuPy will either
|
| 254 |
+
use an auto-generated plan behind the scene if cupy.fft.config.
|
| 255 |
+
enable_nd_planning = True, or use no cuFFT plan if it is set to
|
| 256 |
+
False.
|
| 257 |
+
|
| 258 |
+
Returns:
|
| 259 |
+
cupy.ndarray:
|
| 260 |
+
The transformed array which shape is specified by ``shape`` and
|
| 261 |
+
type will convert to complex if that of the input is another.
|
| 262 |
+
|
| 263 |
+
.. seealso:: :func:`scipy.fftpack.fft2`
|
| 264 |
+
|
| 265 |
+
.. note::
|
| 266 |
+
The argument `plan` is currently experimental and the interface may be
|
| 267 |
+
changed in the future version.
|
| 268 |
+
"""
|
| 269 |
+
from cupy.cuda import cufft
|
| 270 |
+
|
| 271 |
+
func = _default_fft_func(x, shape, axes, plan)
|
| 272 |
+
return func(x, shape, axes, None, cufft.CUFFT_FORWARD,
|
| 273 |
+
overwrite_x=overwrite_x, plan=plan)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def ifft2(x, shape=None, axes=(-2, -1), overwrite_x=False, plan=None):
|
| 277 |
+
"""Compute the two-dimensional inverse FFT.
|
| 278 |
+
|
| 279 |
+
Args:
|
| 280 |
+
x (cupy.ndarray): Array to be transformed.
|
| 281 |
+
shape (None or tuple of ints): Shape of the transformed axes of the
|
| 282 |
+
output. If ``shape`` is not given, the lengths of the input along
|
| 283 |
+
the axes specified by ``axes`` are used.
|
| 284 |
+
axes (tuple of ints): Axes over which to compute the FFT.
|
| 285 |
+
overwrite_x (bool): If True, the contents of ``x`` can be destroyed.
|
| 286 |
+
plan (:class:`cupy.cuda.cufft.PlanNd` or ``None``): a cuFFT plan for
|
| 287 |
+
transforming ``x`` over ``axes``, which can be obtained using::
|
| 288 |
+
|
| 289 |
+
plan = cupyx.scipy.fftpack.get_fft_plan(x, axes)
|
| 290 |
+
|
| 291 |
+
Note that `plan` is defaulted to None, meaning CuPy will either
|
| 292 |
+
use an auto-generated plan behind the scene if cupy.fft.config.
|
| 293 |
+
enable_nd_planning = True, or use no cuFFT plan if it is set to
|
| 294 |
+
False.
|
| 295 |
+
|
| 296 |
+
Returns:
|
| 297 |
+
cupy.ndarray:
|
| 298 |
+
The transformed array which shape is specified by ``shape`` and
|
| 299 |
+
type will convert to complex if that of the input is another.
|
| 300 |
+
|
| 301 |
+
.. seealso:: :func:`scipy.fftpack.ifft2`
|
| 302 |
+
|
| 303 |
+
.. note::
|
| 304 |
+
The argument `plan` is currently experimental and the interface may be
|
| 305 |
+
changed in the future version.
|
| 306 |
+
"""
|
| 307 |
+
from cupy.cuda import cufft
|
| 308 |
+
|
| 309 |
+
func = _default_fft_func(x, shape, axes, plan)
|
| 310 |
+
return func(x, shape, axes, None, cufft.CUFFT_INVERSE,
|
| 311 |
+
overwrite_x=overwrite_x, plan=plan)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def fftn(x, shape=None, axes=None, overwrite_x=False, plan=None):
|
| 315 |
+
"""Compute the N-dimensional FFT.
|
| 316 |
+
|
| 317 |
+
Args:
|
| 318 |
+
x (cupy.ndarray): Array to be transformed.
|
| 319 |
+
shape (None or tuple of ints): Shape of the transformed axes of the
|
| 320 |
+
output. If ``shape`` is not given, the lengths of the input along
|
| 321 |
+
the axes specified by ``axes`` are used.
|
| 322 |
+
axes (tuple of ints): Axes over which to compute the FFT.
|
| 323 |
+
overwrite_x (bool): If True, the contents of ``x`` can be destroyed.
|
| 324 |
+
plan (:class:`cupy.cuda.cufft.PlanNd` or ``None``): a cuFFT plan for
|
| 325 |
+
transforming ``x`` over ``axes``, which can be obtained using::
|
| 326 |
+
|
| 327 |
+
plan = cupyx.scipy.fftpack.get_fft_plan(x, axes)
|
| 328 |
+
|
| 329 |
+
Note that `plan` is defaulted to None, meaning CuPy will either
|
| 330 |
+
use an auto-generated plan behind the scene if cupy.fft.config.
|
| 331 |
+
enable_nd_planning = True, or use no cuFFT plan if it is set to
|
| 332 |
+
False.
|
| 333 |
+
|
| 334 |
+
Returns:
|
| 335 |
+
cupy.ndarray:
|
| 336 |
+
The transformed array which shape is specified by ``shape`` and
|
| 337 |
+
type will convert to complex if that of the input is another.
|
| 338 |
+
|
| 339 |
+
.. seealso:: :func:`scipy.fftpack.fftn`
|
| 340 |
+
|
| 341 |
+
.. note::
|
| 342 |
+
The argument `plan` is currently experimental and the interface may be
|
| 343 |
+
changed in the future version.
|
| 344 |
+
"""
|
| 345 |
+
from cupy.cuda import cufft
|
| 346 |
+
|
| 347 |
+
func = _default_fft_func(x, shape, axes, plan)
|
| 348 |
+
return func(x, shape, axes, None, cufft.CUFFT_FORWARD,
|
| 349 |
+
overwrite_x=overwrite_x, plan=plan)
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def ifftn(x, shape=None, axes=None, overwrite_x=False, plan=None):
|
| 353 |
+
"""Compute the N-dimensional inverse FFT.
|
| 354 |
+
|
| 355 |
+
Args:
|
| 356 |
+
x (cupy.ndarray): Array to be transformed.
|
| 357 |
+
shape (None or tuple of ints): Shape of the transformed axes of the
|
| 358 |
+
output. If ``shape`` is not given, the lengths of the input along
|
| 359 |
+
the axes specified by ``axes`` are used.
|
| 360 |
+
axes (tuple of ints): Axes over which to compute the FFT.
|
| 361 |
+
overwrite_x (bool): If True, the contents of ``x`` can be destroyed.
|
| 362 |
+
plan (:class:`cupy.cuda.cufft.PlanNd` or ``None``): a cuFFT plan for
|
| 363 |
+
transforming ``x`` over ``axes``, which can be obtained using::
|
| 364 |
+
|
| 365 |
+
plan = cupyx.scipy.fftpack.get_fft_plan(x, axes)
|
| 366 |
+
|
| 367 |
+
Note that `plan` is defaulted to None, meaning CuPy will either
|
| 368 |
+
use an auto-generated plan behind the scene if cupy.fft.config.
|
| 369 |
+
enable_nd_planning = True, or use no cuFFT plan if it is set to
|
| 370 |
+
False.
|
| 371 |
+
|
| 372 |
+
Returns:
|
| 373 |
+
cupy.ndarray:
|
| 374 |
+
The transformed array which shape is specified by ``shape`` and
|
| 375 |
+
type will convert to complex if that of the input is another.
|
| 376 |
+
|
| 377 |
+
.. seealso:: :func:`scipy.fftpack.ifftn`
|
| 378 |
+
|
| 379 |
+
.. note::
|
| 380 |
+
The argument `plan` is currently experimental and the interface may be
|
| 381 |
+
changed in the future version.
|
| 382 |
+
"""
|
| 383 |
+
from cupy.cuda import cufft
|
| 384 |
+
|
| 385 |
+
func = _default_fft_func(x, shape, axes, plan)
|
| 386 |
+
return func(x, shape, axes, None, cufft.CUFFT_INVERSE,
|
| 387 |
+
overwrite_x=overwrite_x, plan=plan)
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def rfft(x, n=None, axis=-1, overwrite_x=False, plan=None):
|
| 391 |
+
"""Compute the one-dimensional FFT for real input.
|
| 392 |
+
|
| 393 |
+
The returned real array contains
|
| 394 |
+
|
| 395 |
+
.. code-block:: python
|
| 396 |
+
|
| 397 |
+
[y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))] # if n is even
|
| 398 |
+
[y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))] # if n is odd
|
| 399 |
+
|
| 400 |
+
Args:
|
| 401 |
+
x (cupy.ndarray): Array to be transformed.
|
| 402 |
+
n (None or int): Length of the transformed axis of the output. If ``n``
|
| 403 |
+
is not given, the length of the input along the axis specified by
|
| 404 |
+
``axis`` is used.
|
| 405 |
+
axis (int): Axis over which to compute the FFT.
|
| 406 |
+
overwrite_x (bool): If True, the contents of ``x`` can be destroyed.
|
| 407 |
+
plan (:class:`cupy.cuda.cufft.Plan1d` or ``None``): a cuFFT plan for
|
| 408 |
+
transforming ``x`` over ``axis``, which can be obtained using::
|
| 409 |
+
|
| 410 |
+
plan = cupyx.scipy.fftpack.get_fft_plan(
|
| 411 |
+
x, axes, value_type='R2C')
|
| 412 |
+
|
| 413 |
+
Note that `plan` is defaulted to None, meaning CuPy will either
|
| 414 |
+
use an auto-generated plan behind the scene if cupy.fft.config.
|
| 415 |
+
enable_nd_planning = True, or use no cuFFT plan if it is set to
|
| 416 |
+
False.
|
| 417 |
+
|
| 418 |
+
Returns:
|
| 419 |
+
cupy.ndarray:
|
| 420 |
+
The transformed array.
|
| 421 |
+
|
| 422 |
+
.. seealso:: :func:`scipy.fftpack.rfft`
|
| 423 |
+
|
| 424 |
+
.. note::
|
| 425 |
+
The argument `plan` is currently experimental and the interface may be
|
| 426 |
+
changed in the future version.
|
| 427 |
+
"""
|
| 428 |
+
from cupy.cuda import cufft
|
| 429 |
+
|
| 430 |
+
if n is None:
|
| 431 |
+
n = x.shape[axis]
|
| 432 |
+
|
| 433 |
+
shape = list(x.shape)
|
| 434 |
+
shape[axis] = n
|
| 435 |
+
f = _fft(x, (n,), (axis,), None, cufft.CUFFT_FORWARD, 'R2C',
|
| 436 |
+
overwrite_x=overwrite_x, plan=plan)
|
| 437 |
+
z = cupy.empty(shape, f.real.dtype)
|
| 438 |
+
|
| 439 |
+
slice_z = [slice(None)] * x.ndim
|
| 440 |
+
slice_f = [slice(None)] * x.ndim
|
| 441 |
+
|
| 442 |
+
slice_z[axis] = slice(1)
|
| 443 |
+
slice_f[axis] = slice(1)
|
| 444 |
+
z[tuple(slice_z)] = f[tuple(slice_f)].real
|
| 445 |
+
|
| 446 |
+
slice_z[axis] = slice(1, None, 2)
|
| 447 |
+
slice_f[axis] = slice(1, None)
|
| 448 |
+
z[tuple(slice_z)] = f[tuple(slice_f)].real
|
| 449 |
+
|
| 450 |
+
slice_z[axis] = slice(2, None, 2)
|
| 451 |
+
slice_f[axis] = slice(1, n - f.shape[axis] + 1)
|
| 452 |
+
z[tuple(slice_z)] = f[tuple(slice_f)].imag
|
| 453 |
+
|
| 454 |
+
return z
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def irfft(x, n=None, axis=-1, overwrite_x=False):
|
| 458 |
+
"""Compute the one-dimensional inverse FFT for real input.
|
| 459 |
+
|
| 460 |
+
Args:
|
| 461 |
+
x (cupy.ndarray): Array to be transformed.
|
| 462 |
+
n (None or int): Length of the transformed axis of the output. If ``n``
|
| 463 |
+
is not given, the length of the input along the axis specified by
|
| 464 |
+
``axis`` is used.
|
| 465 |
+
axis (int): Axis over which to compute the FFT.
|
| 466 |
+
overwrite_x (bool): If True, the contents of ``x`` can be destroyed.
|
| 467 |
+
|
| 468 |
+
Returns:
|
| 469 |
+
cupy.ndarray:
|
| 470 |
+
The transformed array.
|
| 471 |
+
|
| 472 |
+
.. seealso:: :func:`scipy.fftpack.irfft`
|
| 473 |
+
|
| 474 |
+
.. note::
|
| 475 |
+
This function does not support a precomputed `plan`. If you need this
|
| 476 |
+
capability, please consider using :func:`cupy.fft.irfft` or :func:`
|
| 477 |
+
cupyx.scipy.fft.irfft`.
|
| 478 |
+
"""
|
| 479 |
+
from cupy.cuda import cufft
|
| 480 |
+
|
| 481 |
+
if n is None:
|
| 482 |
+
n = x.shape[axis]
|
| 483 |
+
m = min(n, x.shape[axis])
|
| 484 |
+
|
| 485 |
+
shape = list(x.shape)
|
| 486 |
+
shape[axis] = n // 2 + 1
|
| 487 |
+
if x.dtype in (cupy.float16, cupy.float32):
|
| 488 |
+
z = cupy.zeros(shape, dtype=cupy.complex64)
|
| 489 |
+
else:
|
| 490 |
+
z = cupy.zeros(shape, dtype=cupy.complex128)
|
| 491 |
+
|
| 492 |
+
slice_x = [slice(None)] * x.ndim
|
| 493 |
+
slice_z = [slice(None)] * x.ndim
|
| 494 |
+
|
| 495 |
+
slice_x[axis] = slice(1)
|
| 496 |
+
slice_z[axis] = slice(1)
|
| 497 |
+
z[tuple(slice_z)].real = x[tuple(slice_x)]
|
| 498 |
+
|
| 499 |
+
slice_x[axis] = slice(1, m, 2)
|
| 500 |
+
slice_z[axis] = slice(1, m // 2 + 1)
|
| 501 |
+
z[tuple(slice_z)].real = x[tuple(slice_x)]
|
| 502 |
+
|
| 503 |
+
slice_x[axis] = slice(2, m, 2)
|
| 504 |
+
slice_z[axis] = slice(1, (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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from cupyx.scipy.signal._signaltools import convolve # NOQA
|
| 2 |
+
from cupyx.scipy.signal._signaltools import correlate # NOQA
|
| 3 |
+
from cupyx.scipy.signal._signaltools import deconvolve # NOQA
|
| 4 |
+
from cupyx.scipy.signal._signaltools import fftconvolve # NOQA
|
| 5 |
+
from cupyx.scipy.signal._signaltools import choose_conv_method # NOQA
|
| 6 |
+
from cupyx.scipy.signal._signaltools import oaconvolve # NOQA
|
| 7 |
+
from cupyx.scipy.signal._signaltools import convolve2d # NOQA
|
| 8 |
+
from cupyx.scipy.signal._signaltools import correlate2d # NOQA
|
| 9 |
+
from cupyx.scipy.signal._signaltools import correlation_lags # NOQA
|
| 10 |
+
from cupyx.scipy.signal._signaltools import wiener # NOQA
|
| 11 |
+
from cupyx.scipy.signal._signaltools import order_filter # NOQA
|
| 12 |
+
from cupyx.scipy.signal._signaltools import medfilt # NOQA
|
| 13 |
+
from cupyx.scipy.signal._signaltools import medfilt2d # NOQA
|
| 14 |
+
from cupyx.scipy.signal._signaltools import lfilter # NOQA
|
| 15 |
+
from cupyx.scipy.signal._signaltools import lfiltic # NOQA
|
| 16 |
+
from cupyx.scipy.signal._signaltools import lfilter_zi # NOQA
|
| 17 |
+
from cupyx.scipy.signal._signaltools import detrend # NOQA
|
| 18 |
+
from cupyx.scipy.signal._signaltools import filtfilt # NOQA
|
| 19 |
+
from cupyx.scipy.signal._signaltools import sosfilt # NOQA
|
| 20 |
+
from cupyx.scipy.signal._signaltools import sosfilt_zi # NOQA
|
| 21 |
+
from cupyx.scipy.signal._signaltools import sosfiltfilt # NOQA
|
| 22 |
+
from cupyx.scipy.signal._signaltools import hilbert # NOQA
|
| 23 |
+
from cupyx.scipy.signal._signaltools import hilbert2 # NOQA
|
| 24 |
+
|
| 25 |
+
from cupyx.scipy.signal._resample import resample # NOQA
|
| 26 |
+
from cupyx.scipy.signal._resample import resample_poly # NOQA
|
| 27 |
+
from cupyx.scipy.signal._resample import decimate # NOQA
|
| 28 |
+
|
| 29 |
+
from cupyx.scipy.signal._polyutils import unique_roots # NOQA
|
| 30 |
+
from cupyx.scipy.signal._polyutils import invres # NOQA
|
| 31 |
+
from cupyx.scipy.signal._polyutils import invresz # NOQA
|
| 32 |
+
from cupyx.scipy.signal._polyutils import residue # NOQA
|
| 33 |
+
from cupyx.scipy.signal._polyutils import residuez # NOQA
|
| 34 |
+
|
| 35 |
+
from cupyx.scipy.signal._bsplines import sepfir2d # NOQA
|
| 36 |
+
from cupyx.scipy.signal._bsplines import cspline1d # NOQA
|
| 37 |
+
from cupyx.scipy.signal._bsplines import qspline1d # NOQA
|
| 38 |
+
from cupyx.scipy.signal._bsplines import cspline2d # NOQA
|
| 39 |
+
from cupyx.scipy.signal._bsplines import qspline2d # NOQA
|
| 40 |
+
from cupyx.scipy.signal._bsplines import cspline1d_eval # NOQA
|
| 41 |
+
from cupyx.scipy.signal._bsplines import qspline1d_eval # NOQA
|
| 42 |
+
from cupyx.scipy.signal._bsplines import spline_filter # NOQA
|
| 43 |
+
from cupyx.scipy.signal._bsplines import gauss_spline # NOQA
|
| 44 |
+
|
| 45 |
+
from cupyx.scipy.signal._splines import symiirorder1 # NOQA
|
| 46 |
+
from cupyx.scipy.signal._splines import symiirorder2 # NOQA
|
| 47 |
+
|
| 48 |
+
from cupyx.scipy.signal._savitzky_golay import savgol_coeffs, savgol_filter # NOQA
|
| 49 |
+
|
| 50 |
+
from cupyx.scipy.signal._filter_design import gammatone # NOQA
|
| 51 |
+
from cupyx.scipy.signal._filter_design import group_delay # NOQA
|
| 52 |
+
|
| 53 |
+
from cupyx.scipy.signal._fir_filter_design import kaiser_atten # NOQA
|
| 54 |
+
from cupyx.scipy.signal._fir_filter_design import kaiser_beta # NOQA
|
| 55 |
+
from cupyx.scipy.signal._fir_filter_design import kaiserord # NOQA
|
| 56 |
+
|
| 57 |
+
from cupyx.scipy.signal._iir_filter_conversions import BadCoefficients # NOQA
|
| 58 |
+
from cupyx.scipy.signal._iir_filter_conversions import normalize # NOQA
|
| 59 |
+
|
| 60 |
+
from cupyx.scipy.signal._iir_filter_conversions import bilinear # NOQA
|
| 61 |
+
from cupyx.scipy.signal._iir_filter_conversions import lp2lp # NOQA
|
| 62 |
+
from cupyx.scipy.signal._iir_filter_conversions import lp2hp # NOQA
|
| 63 |
+
from cupyx.scipy.signal._iir_filter_conversions import lp2bp # NOQA
|
| 64 |
+
from cupyx.scipy.signal._iir_filter_conversions import lp2bs # NOQA
|
| 65 |
+
|
| 66 |
+
from cupyx.scipy.signal._iir_filter_conversions import bilinear_zpk # NOQA
|
| 67 |
+
from cupyx.scipy.signal._iir_filter_conversions import lp2lp_zpk # NOQA
|
| 68 |
+
from cupyx.scipy.signal._iir_filter_conversions import lp2hp_zpk # NOQA
|
| 69 |
+
from cupyx.scipy.signal._iir_filter_conversions import lp2bp_zpk # NOQA
|
| 70 |
+
from cupyx.scipy.signal._iir_filter_conversions import lp2bs_zpk # NOQA
|
| 71 |
+
|
| 72 |
+
from cupyx.scipy.signal._iir_filter_conversions import zpk2tf # NOQA
|
| 73 |
+
from cupyx.scipy.signal._iir_filter_conversions import zpk2sos # NOQA
|
| 74 |
+
from cupyx.scipy.signal._iir_filter_conversions import zpk2ss # NOQA
|
| 75 |
+
from cupyx.scipy.signal._iir_filter_conversions import tf2zpk # NOQA
|
| 76 |
+
from cupyx.scipy.signal._iir_filter_conversions import tf2sos # NOQA
|
| 77 |
+
from cupyx.scipy.signal._iir_filter_conversions import tf2ss # NOQA
|
| 78 |
+
from cupyx.scipy.signal._iir_filter_conversions import ss2tf # NOQA
|
| 79 |
+
from cupyx.scipy.signal._iir_filter_conversions import ss2zpk # NOQA
|
| 80 |
+
from cupyx.scipy.signal._iir_filter_conversions import sos2tf # NOQA
|
| 81 |
+
from cupyx.scipy.signal._iir_filter_conversions import sos2zpk # NOQA
|
| 82 |
+
|
| 83 |
+
from cupyx.scipy.signal._iir_filter_conversions import band_stop_obj # NOQA
|
| 84 |
+
from cupyx.scipy.signal.windows._windows import get_window # NOQA
|
| 85 |
+
|
| 86 |
+
from cupyx.scipy.signal._iir_filter_conversions import buttap # NOQA
|
| 87 |
+
from cupyx.scipy.signal._iir_filter_conversions import cheb1ap # NOQA
|
| 88 |
+
from cupyx.scipy.signal._iir_filter_conversions import cheb2ap # NOQA
|
| 89 |
+
from cupyx.scipy.signal._iir_filter_conversions import ellipap # NOQA
|
| 90 |
+
|
| 91 |
+
from cupyx.scipy.signal._iir_filter_conversions import buttord # NOQA
|
| 92 |
+
from cupyx.scipy.signal._iir_filter_conversions import cheb1ord # NOQA
|
| 93 |
+
from cupyx.scipy.signal._iir_filter_conversions import cheb2ord # NOQA
|
| 94 |
+
from cupyx.scipy.signal._iir_filter_conversions import ellipord # NOQA
|
| 95 |
+
|
| 96 |
+
from cupyx.scipy.signal._iir_filter_design import iirfilter # NOQA
|
| 97 |
+
from cupyx.scipy.signal._iir_filter_design import butter # NOQA
|
| 98 |
+
from cupyx.scipy.signal._iir_filter_design import cheby1 # NOQA
|
| 99 |
+
from cupyx.scipy.signal._iir_filter_design import cheby2 # NOQA
|
| 100 |
+
from cupyx.scipy.signal._iir_filter_design import ellip # NOQA
|
| 101 |
+
from cupyx.scipy.signal._iir_filter_design import iirdesign # NOQA
|
| 102 |
+
from cupyx.scipy.signal._iir_filter_design import iircomb # NOQA
|
| 103 |
+
from cupyx.scipy.signal._iir_filter_design import iirnotch # NOQA
|
| 104 |
+
from cupyx.scipy.signal._iir_filter_design import iirpeak # NOQA
|
| 105 |
+
|
| 106 |
+
from cupyx.scipy.signal._fir_filter_design import firwin # NOQA
|
| 107 |
+
from cupyx.scipy.signal._fir_filter_design import firwin2 # NOQA
|
| 108 |
+
from cupyx.scipy.signal._fir_filter_design import firls # NOQA
|
| 109 |
+
from cupyx.scipy.signal._fir_filter_design import minimum_phase # NOQA
|
| 110 |
+
|
| 111 |
+
from cupyx.scipy.signal._filter_design import findfreqs # NOQA
|
| 112 |
+
from cupyx.scipy.signal._filter_design import freqs # NOQA
|
| 113 |
+
from cupyx.scipy.signal._filter_design import freqs_zpk # NOQA
|
| 114 |
+
|
| 115 |
+
from cupyx.scipy.signal._filter_design import freqz # NOQA
|
| 116 |
+
from cupyx.scipy.signal._filter_design import freqz_zpk # NOQA
|
| 117 |
+
from cupyx.scipy.signal._filter_design import sosfreqz # NOQA
|
| 118 |
+
|
| 119 |
+
from cupyx.scipy.signal._waveforms import chirp # NOQA
|
| 120 |
+
from cupyx.scipy.signal._waveforms import gausspulse # NOQA
|
| 121 |
+
from cupyx.scipy.signal._waveforms import sawtooth # NOQA
|
| 122 |
+
from cupyx.scipy.signal._waveforms import square # NOQA
|
| 123 |
+
from cupyx.scipy.signal._waveforms import unit_impulse # NOQA
|
| 124 |
+
from cupyx.scipy.signal._max_len_seq import max_len_seq # NOQA
|
| 125 |
+
|
| 126 |
+
from cupyx.scipy.signal._czt import * # NOQA
|
| 127 |
+
|
| 128 |
+
from cupyx.scipy.signal._wavelets import morlet # NOQA
|
| 129 |
+
from cupyx.scipy.signal._wavelets import qmf # NOQA
|
| 130 |
+
from cupyx.scipy.signal._wavelets import ricker # NOQA
|
| 131 |
+
from cupyx.scipy.signal._wavelets import morlet2 # NOQA
|
| 132 |
+
from cupyx.scipy.signal._wavelets import cwt # NOQA
|
| 133 |
+
|
| 134 |
+
from cupyx.scipy.signal._lti_conversion import abcd_normalize # NOQA
|
| 135 |
+
|
| 136 |
+
from cupyx.scipy.signal._upfirdn import upfirdn # NOQA
|
| 137 |
+
|
| 138 |
+
from cupyx.scipy.signal._peak_finding import find_peaks # NOQA
|
| 139 |
+
from cupyx.scipy.signal._peak_finding import peak_prominences # NOQA
|
| 140 |
+
from cupyx.scipy.signal._peak_finding import peak_widths # NOQA
|
| 141 |
+
|
| 142 |
+
from cupyx.scipy.signal._ltisys import lti # NOQA
|
| 143 |
+
from cupyx.scipy.signal._ltisys import lsim # NOQA
|
| 144 |
+
from cupyx.scipy.signal._ltisys import impulse # NOQA
|
| 145 |
+
from cupyx.scipy.signal._ltisys import step # NOQA
|
| 146 |
+
from cupyx.scipy.signal._ltisys import freqresp # NOQA
|
| 147 |
+
from cupyx.scipy.signal._ltisys import bode # NOQA
|
| 148 |
+
|
| 149 |
+
from cupyx.scipy.signal._ltisys import dlti # NOQA
|
| 150 |
+
from cupyx.scipy.signal._ltisys import dlsim # NOQA
|
| 151 |
+
from cupyx.scipy.signal._ltisys import dstep # NOQA
|
| 152 |
+
from cupyx.scipy.signal._ltisys import dimpulse # NOQA
|
| 153 |
+
from cupyx.scipy.signal._ltisys import dbode # NOQA
|
| 154 |
+
from cupyx.scipy.signal._ltisys import dfreqresp # NOQA
|
| 155 |
+
from cupyx.scipy.signal._ltisys import StateSpace # NOQA
|
| 156 |
+
from cupyx.scipy.signal._ltisys import TransferFunction # NOQA
|
| 157 |
+
from cupyx.scipy.signal._ltisys import ZerosPolesGain # NOQA
|
| 158 |
+
from cupyx.scipy.signal._ltisys import cont2discrete # NOQA
|
| 159 |
+
from cupyx.scipy.signal._ltisys import place_poles # NOQA
|
| 160 |
+
|
| 161 |
+
from cupyx.scipy.signal._spectral import lombscargle # NOQA
|
| 162 |
+
from cupyx.scipy.signal._spectral import periodogram # NOQA
|
| 163 |
+
from cupyx.scipy.signal._spectral import welch # NOQA
|
| 164 |
+
from cupyx.scipy.signal._spectral import csd # NOQA
|
| 165 |
+
from cupyx.scipy.signal._spectral import check_COLA # NOQA
|
| 166 |
+
from cupyx.scipy.signal._spectral import check_NOLA # NOQA
|
| 167 |
+
from cupyx.scipy.signal._spectral import stft # NOQA
|
| 168 |
+
from cupyx.scipy.signal._spectral import istft # NOQA
|
| 169 |
+
from cupyx.scipy.signal._spectral import spectrogram # NOQA
|
| 170 |
+
from cupyx.scipy.signal._spectral import vectorstrength # NOQA
|
| 171 |
+
from cupyx.scipy.signal._spectral import coherence # NOQA
|
| 172 |
+
|
| 173 |
+
from cupyx.scipy.signal._peak_finding import argrelextrema # NOQA
|
| 174 |
+
from cupyx.scipy.signal._peak_finding import argrelmin # NOQA
|
| 175 |
+
from cupyx.scipy.signal._peak_finding import argrelmax # NOQA
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_czt.cpython-310.pyc
ADDED
|
Binary file (15.3 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_filter_design.cpython-310.pyc
ADDED
|
Binary file (23.9 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_iir_filter_conversions.cpython-310.pyc
ADDED
|
Binary file (60.3 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_iir_filter_design.cpython-310.pyc
ADDED
|
Binary file (31.6 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_iir_utils.cpython-310.pyc
ADDED
|
Binary file (19.4 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_lti_conversion.cpython-310.pyc
ADDED
|
Binary file (2.21 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_ltisys.cpython-310.pyc
ADDED
|
Binary file (83.7 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_max_len_seq.cpython-310.pyc
ADDED
|
Binary file (4.15 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_resample.cpython-310.pyc
ADDED
|
Binary file (16.5 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_signaltools.cpython-310.pyc
ADDED
|
Binary file (54.3 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_signaltools_core.cpython-310.pyc
ADDED
|
Binary file (8.66 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_spectral_impl.cpython-310.pyc
ADDED
|
Binary file (19 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_splines.cpython-310.pyc
ADDED
|
Binary file (12.1 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/__pycache__/_upfirdn.cpython-310.pyc
ADDED
|
Binary file (19.7 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_arraytools.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Functions for acting on a axis of an array.
|
| 3 |
+
"""
|
| 4 |
+
import cupy
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def axis_slice(a, start=None, stop=None, step=None, axis=-1):
|
| 8 |
+
"""Take a slice along axis 'axis' from 'a'.
|
| 9 |
+
|
| 10 |
+
Parameters
|
| 11 |
+
----------
|
| 12 |
+
a : cupy.ndarray
|
| 13 |
+
The array to be sliced.
|
| 14 |
+
start, stop, step : int or None
|
| 15 |
+
The slice parameters.
|
| 16 |
+
axis : int, optional
|
| 17 |
+
The axis of `a` to be sliced.
|
| 18 |
+
|
| 19 |
+
Examples
|
| 20 |
+
--------
|
| 21 |
+
>>> a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
| 22 |
+
>>> axis_slice(a, start=0, stop=1, axis=1)
|
| 23 |
+
array([[1],
|
| 24 |
+
[4],
|
| 25 |
+
[7]])
|
| 26 |
+
>>> axis_slice(a, start=1, axis=0)
|
| 27 |
+
array([[4, 5, 6],
|
| 28 |
+
[7, 8, 9]])
|
| 29 |
+
|
| 30 |
+
Notes
|
| 31 |
+
-----
|
| 32 |
+
The keyword arguments start, stop and step are used by calling
|
| 33 |
+
slice(start, stop, step). This implies axis_slice() does not
|
| 34 |
+
handle its arguments the exactly the same as indexing. To select
|
| 35 |
+
a single index k, for example, use
|
| 36 |
+
axis_slice(a, start=k, stop=k+1)
|
| 37 |
+
In this case, the length of the axis 'axis' in the result will
|
| 38 |
+
be 1; the trivial dimension is not removed. (Use cupy.squeeze()
|
| 39 |
+
to remove trivial axes.)
|
| 40 |
+
"""
|
| 41 |
+
a_slice = [slice(None)] * a.ndim
|
| 42 |
+
a_slice[axis] = slice(start, stop, step)
|
| 43 |
+
b = a[tuple(a_slice)]
|
| 44 |
+
return b
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def axis_assign(a, b, start=None, stop=None, step=None, axis=-1):
|
| 48 |
+
"""Take a slice along axis 'axis' from 'a' and set it to 'b' in-place.
|
| 49 |
+
|
| 50 |
+
Parameters
|
| 51 |
+
----------
|
| 52 |
+
a : numpy.ndarray
|
| 53 |
+
The array to be sliced.
|
| 54 |
+
b : cupy.ndarray
|
| 55 |
+
The array to be assigned.
|
| 56 |
+
start, stop, step : int or None
|
| 57 |
+
The slice parameters.
|
| 58 |
+
axis : int, optional
|
| 59 |
+
The axis of `a` to be sliced.
|
| 60 |
+
|
| 61 |
+
Examples
|
| 62 |
+
--------
|
| 63 |
+
>>> a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
|
| 64 |
+
>>> b1 = array([[-1], [-4], [-7]])
|
| 65 |
+
>>> axis_assign(a, b1, start=0, stop=1, axis=1)
|
| 66 |
+
array([[-1, 2, 3],
|
| 67 |
+
[-4, 5, 6],
|
| 68 |
+
[-7, 8, 9]])
|
| 69 |
+
|
| 70 |
+
Notes
|
| 71 |
+
-----
|
| 72 |
+
The keyword arguments start, stop and step are used by calling
|
| 73 |
+
slice(start, stop, step). This implies axis_assign() does not
|
| 74 |
+
handle its arguments the exactly the same as indexing. To assign
|
| 75 |
+
a single index k, for example, use
|
| 76 |
+
axis_assign(a, start=k, stop=k+1)
|
| 77 |
+
In this case, the length of the axis 'axis' in the result will
|
| 78 |
+
be 1; the trivial dimension is not removed. (Use numpy.squeeze()
|
| 79 |
+
to remove trivial axes.)
|
| 80 |
+
|
| 81 |
+
This function works in-place and will modify the values contained in `a`
|
| 82 |
+
"""
|
| 83 |
+
a_slice = [slice(None)] * a.ndim
|
| 84 |
+
a_slice[axis] = slice(start, stop, step)
|
| 85 |
+
a[tuple(a_slice)] = b
|
| 86 |
+
return a
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def axis_reverse(a, axis=-1):
|
| 90 |
+
"""Reverse the 1-D slices of `a` along axis `axis`.
|
| 91 |
+
|
| 92 |
+
Returns axis_slice(a, step=-1, axis=axis).
|
| 93 |
+
"""
|
| 94 |
+
return axis_slice(a, step=-1, axis=axis)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def odd_ext(x, n, axis=-1):
|
| 98 |
+
"""
|
| 99 |
+
Odd extension at the boundaries of an array
|
| 100 |
+
|
| 101 |
+
Generate a new ndarray by making an odd extension of `x` along an axis.
|
| 102 |
+
|
| 103 |
+
Parameters
|
| 104 |
+
----------
|
| 105 |
+
x : ndarray
|
| 106 |
+
The array to be extended.
|
| 107 |
+
n : int
|
| 108 |
+
The number of elements by which to extend `x` at each end of the axis.
|
| 109 |
+
axis : int, optional
|
| 110 |
+
The axis along which to extend `x`. Default is -1.
|
| 111 |
+
|
| 112 |
+
Examples
|
| 113 |
+
--------
|
| 114 |
+
>>> from cupyx.scipy.signal._arraytools import odd_ext
|
| 115 |
+
>>> a = cupy.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]])
|
| 116 |
+
>>> odd_ext(a, 2)
|
| 117 |
+
array([[-1, 0, 1, 2, 3, 4, 5, 6, 7],
|
| 118 |
+
[-4, -1, 0, 1, 4, 9, 16, 23, 28]])
|
| 119 |
+
"""
|
| 120 |
+
if n < 1:
|
| 121 |
+
return x
|
| 122 |
+
if n > x.shape[axis] - 1:
|
| 123 |
+
raise ValueError(("The extension length n (%d) is too big. " +
|
| 124 |
+
"It must not exceed x.shape[axis]-1, which is %d.")
|
| 125 |
+
% (n, x.shape[axis] - 1))
|
| 126 |
+
left_end = axis_slice(x, start=0, stop=1, axis=axis)
|
| 127 |
+
left_ext = axis_slice(x, start=n, stop=0, step=-1, axis=axis)
|
| 128 |
+
right_end = axis_slice(x, start=-1, axis=axis)
|
| 129 |
+
right_ext = axis_slice(x, start=-2, stop=-(n + 2), step=-1, axis=axis)
|
| 130 |
+
ext = cupy.concatenate((2 * left_end - left_ext, x,
|
| 131 |
+
2 * right_end - right_ext), axis=axis)
|
| 132 |
+
return ext
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def even_ext(x, n, axis=-1):
|
| 136 |
+
"""
|
| 137 |
+
Even extension at the boundaries of an array
|
| 138 |
+
|
| 139 |
+
Generate a new ndarray by making an even extension of `x` along an axis.
|
| 140 |
+
|
| 141 |
+
Parameters
|
| 142 |
+
----------
|
| 143 |
+
x : ndarray
|
| 144 |
+
The array to be extended.
|
| 145 |
+
n : int
|
| 146 |
+
The number of elements by which to extend `x` at each end of the axis.
|
| 147 |
+
axis : int, optional
|
| 148 |
+
The axis along which to extend `x`. Default is -1.
|
| 149 |
+
|
| 150 |
+
Examples
|
| 151 |
+
--------
|
| 152 |
+
>>> from cupyx.scipy.signal._arraytools import even_ext
|
| 153 |
+
>>> a = cupy.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]])
|
| 154 |
+
>>> even_ext(a, 2)
|
| 155 |
+
array([[ 3, 2, 1, 2, 3, 4, 5, 4, 3],
|
| 156 |
+
[ 4, 1, 0, 1, 4, 9, 16, 9, 4]])
|
| 157 |
+
|
| 158 |
+
"""
|
| 159 |
+
if n < 1:
|
| 160 |
+
return x
|
| 161 |
+
if n > x.shape[axis] - 1:
|
| 162 |
+
raise ValueError(("The extension length n (%d) is too big. " +
|
| 163 |
+
"It must not exceed x.shape[axis]-1, which is %d.")
|
| 164 |
+
% (n, x.shape[axis] - 1))
|
| 165 |
+
left_ext = axis_slice(x, start=n, stop=0, step=-1, axis=axis)
|
| 166 |
+
right_ext = axis_slice(x, start=-2, stop=-(n + 2), step=-1, axis=axis)
|
| 167 |
+
ext = cupy.concatenate((left_ext, x, right_ext), axis=axis)
|
| 168 |
+
return ext
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def const_ext(x, n, axis=-1):
|
| 172 |
+
"""
|
| 173 |
+
Constant extension at the boundaries of an array
|
| 174 |
+
|
| 175 |
+
Generate a new ndarray that is a constant extension of `x` along an axis.
|
| 176 |
+
The extension repeats the values at the first and last element of
|
| 177 |
+
the axis.
|
| 178 |
+
|
| 179 |
+
Parameters
|
| 180 |
+
----------
|
| 181 |
+
x : ndarray
|
| 182 |
+
The array to be extended.
|
| 183 |
+
n : int
|
| 184 |
+
The number of elements by which to extend `x` at each end of the axis.
|
| 185 |
+
axis : int, optional
|
| 186 |
+
The axis along which to extend `x`. Default is -1.
|
| 187 |
+
|
| 188 |
+
Examples
|
| 189 |
+
--------
|
| 190 |
+
>>> from cupyx.scipy.signal._arraytools import const_ext
|
| 191 |
+
>>> a = cupy.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]])
|
| 192 |
+
>>> const_ext(a, 2)
|
| 193 |
+
array([[ 1, 1, 1, 2, 3, 4, 5, 5, 5],
|
| 194 |
+
[ 0, 0, 0, 1, 4, 9, 16, 16, 16]])
|
| 195 |
+
"""
|
| 196 |
+
if n < 1:
|
| 197 |
+
return x
|
| 198 |
+
left_end = axis_slice(x, start=0, stop=1, axis=axis)
|
| 199 |
+
ones_shape = [1] * x.ndim
|
| 200 |
+
ones_shape[axis] = n
|
| 201 |
+
ones = cupy.ones(ones_shape, dtype=x.dtype)
|
| 202 |
+
left_ext = ones * left_end
|
| 203 |
+
right_end = axis_slice(x, start=-1, axis=axis)
|
| 204 |
+
right_ext = ones * right_end
|
| 205 |
+
ext = cupy.concatenate((left_ext, x, right_ext), axis=axis)
|
| 206 |
+
return ext
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def zero_ext(x, n, axis=-1):
|
| 210 |
+
"""
|
| 211 |
+
Zero padding at the boundaries of an array
|
| 212 |
+
|
| 213 |
+
Generate a new ndarray that is a zero-padded extension of `x` along
|
| 214 |
+
an axis.
|
| 215 |
+
|
| 216 |
+
Parameters
|
| 217 |
+
----------
|
| 218 |
+
x : ndarray
|
| 219 |
+
The array to be extended.
|
| 220 |
+
n : int
|
| 221 |
+
The number of elements by which to extend `x` at each end of the
|
| 222 |
+
axis.
|
| 223 |
+
axis : int, optional
|
| 224 |
+
The axis along which to extend `x`. Default is -1.
|
| 225 |
+
|
| 226 |
+
Examples
|
| 227 |
+
--------
|
| 228 |
+
>>> from cupyx.scipy.signal._arraytools import zero_ext
|
| 229 |
+
>>> a = cupy.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]])
|
| 230 |
+
>>> zero_ext(a, 2)
|
| 231 |
+
array([[ 0, 0, 1, 2, 3, 4, 5, 0, 0],
|
| 232 |
+
[ 0, 0, 0, 1, 4, 9, 16, 0, 0]])
|
| 233 |
+
"""
|
| 234 |
+
if n < 1:
|
| 235 |
+
return x
|
| 236 |
+
zeros_shape = list(x.shape)
|
| 237 |
+
zeros_shape[axis] = n
|
| 238 |
+
zeros = cupy.zeros(zeros_shape, dtype=x.dtype)
|
| 239 |
+
ext = cupy.concatenate((zeros, x, zeros), axis=axis)
|
| 240 |
+
return ext
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def _as_strided(x, shape=None, strides=None):
|
| 244 |
+
"""
|
| 245 |
+
Create a view into the array with the given shape and strides.
|
| 246 |
+
.. warning:: This function has to be used with extreme care, see notes.
|
| 247 |
+
|
| 248 |
+
Parameters
|
| 249 |
+
----------
|
| 250 |
+
x : ndarray
|
| 251 |
+
Array to create a new.
|
| 252 |
+
shape : sequence of int, optional
|
| 253 |
+
The shape of the new array. Defaults to ``x.shape``.
|
| 254 |
+
strides : sequence of int, optional
|
| 255 |
+
The strides of the new array. Defaults to ``x.strides``.
|
| 256 |
+
|
| 257 |
+
Returns
|
| 258 |
+
-------
|
| 259 |
+
view : ndarray
|
| 260 |
+
|
| 261 |
+
Notes
|
| 262 |
+
-----
|
| 263 |
+
``as_strided`` creates a view into the array given the exact strides
|
| 264 |
+
and shape. This means it manipulates the internal data structure of
|
| 265 |
+
ndarray and, if done incorrectly, the array elements can point to
|
| 266 |
+
invalid memory and can corrupt results or crash your program.
|
| 267 |
+
"""
|
| 268 |
+
shape = x.shape if shape is None else tuple(shape)
|
| 269 |
+
strides = x.strides if strides is None else tuple(strides)
|
| 270 |
+
|
| 271 |
+
return cupy.ndarray(
|
| 272 |
+
shape=shape, dtype=x.dtype, memptr=x.data, strides=strides)
|
vllm/lib/python3.10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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
"""
|
| 3 |
+
Signal processing B-Splines
|
| 4 |
+
|
| 5 |
+
Some of the functions defined here were ported directly from CuSignal under
|
| 6 |
+
terms of the MIT license, under the following notice:
|
| 7 |
+
|
| 8 |
+
Copyright (c) 2019-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 9 |
+
|
| 10 |
+
Permission is hereby granted, free of charge, to any person obtaining a
|
| 11 |
+
copy of this software and associated documentation files (the "Software"),
|
| 12 |
+
to deal in the Software without restriction, including without limitation
|
| 13 |
+
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
| 14 |
+
and/or sell copies of the Software, and to permit persons to whom the
|
| 15 |
+
Software is furnished to do so, subject to the following conditions:
|
| 16 |
+
|
| 17 |
+
The above copyright notice and this permission notice shall be included in
|
| 18 |
+
all copies or substantial portions of the Software.
|
| 19 |
+
|
| 20 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 21 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 22 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
| 23 |
+
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 24 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 25 |
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
| 26 |
+
DEALINGS IN THE SOFTWARE.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
import cupy
|
| 30 |
+
import cupyx.scipy.ndimage
|
| 31 |
+
|
| 32 |
+
from cupyx.scipy.signal._iir_utils import apply_iir_sos
|
| 33 |
+
from cupyx.scipy.signal._splines import _symiirorder1_nd, _symiirorder2_nd
|
| 34 |
+
from cupyx.scipy.interpolate._bspline import BSpline
|
| 35 |
+
|
| 36 |
+
import numpy as np
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def sepfir2d(input, hrow, hcol):
|
| 40 |
+
"""Convolve with a 2-D separable FIR filter.
|
| 41 |
+
|
| 42 |
+
Convolve the rank-2 input array with the separable filter defined by the
|
| 43 |
+
rank-1 arrays hrow, and hcol. Mirror symmetric boundary conditions are
|
| 44 |
+
assumed. This function can be used to find an image given its B-spline
|
| 45 |
+
representation.
|
| 46 |
+
|
| 47 |
+
The arguments `hrow` and `hcol` must be 1-dimensional and of off length.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
input (cupy.ndarray): The input signal
|
| 51 |
+
hrow (cupy.ndarray): Row direction filter
|
| 52 |
+
hcol (cupy.ndarray): Column direction filter
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
cupy.ndarray: The filtered signal
|
| 56 |
+
|
| 57 |
+
.. seealso:: :func:`scipy.signal.sepfir2d`
|
| 58 |
+
"""
|
| 59 |
+
if any(x.ndim != 1 or x.size % 2 == 0 for x in (hrow, hcol)):
|
| 60 |
+
raise ValueError('hrow and hcol must be 1 dimensional and odd length')
|
| 61 |
+
dtype = input.dtype
|
| 62 |
+
if dtype.kind == 'c':
|
| 63 |
+
dtype = cupy.complex64 if dtype == cupy.complex64 else cupy.complex128
|
| 64 |
+
elif dtype == cupy.float32 or dtype.itemsize <= 2:
|
| 65 |
+
dtype = cupy.float32
|
| 66 |
+
else:
|
| 67 |
+
dtype = cupy.float64
|
| 68 |
+
input = input.astype(dtype, copy=False)
|
| 69 |
+
hrow = hrow.astype(dtype, copy=False)
|
| 70 |
+
hcol = hcol.astype(dtype, copy=False)
|
| 71 |
+
filters = (hcol[::-1].conj(), hrow[::-1].conj())
|
| 72 |
+
return cupyx.scipy.ndimage._filters._run_1d_correlates(
|
| 73 |
+
input, (0, 1), lambda i: filters[i], None, 'reflect', 0)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _quadratic(x):
|
| 77 |
+
x = abs(cupy.asarray(x, dtype=float))
|
| 78 |
+
b = BSpline.basis_element(
|
| 79 |
+
cupy.asarray([-1.5, -0.5, 0.5, 1.5]), extrapolate=False)
|
| 80 |
+
out = b(x)
|
| 81 |
+
out[(x < -1.5) | (x > 1.5)] = 0
|
| 82 |
+
return out
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _cubic(x):
|
| 86 |
+
x = cupy.asarray(x, dtype=float)
|
| 87 |
+
b = BSpline.basis_element(
|
| 88 |
+
cupy.asarray([-2, -1, 0, 1, 2]), extrapolate=False)
|
| 89 |
+
out = b(x)
|
| 90 |
+
out[(x < -2) | (x > 2)] = 0
|
| 91 |
+
return out
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@cupy.fuse()
|
| 95 |
+
def _coeff_smooth(lam):
|
| 96 |
+
xi = 1 - 96 * lam + 24 * lam * cupy.sqrt(3 + 144 * lam)
|
| 97 |
+
omeg = cupy.arctan2(cupy.sqrt(144 * lam - 1), cupy.sqrt(xi))
|
| 98 |
+
rho = (24 * lam - 1 - cupy.sqrt(xi)) / (24 * lam)
|
| 99 |
+
rho = rho * cupy.sqrt(
|
| 100 |
+
(48 * lam + 24 * lam * cupy.sqrt(3 + 144 * lam)) / xi)
|
| 101 |
+
return rho, omeg
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@cupy.fuse()
|
| 105 |
+
def _hc(k, cs, rho, omega):
|
| 106 |
+
return (cs / cupy.sin(omega) * (rho ** k) * cupy.sin(omega * (k + 1)) *
|
| 107 |
+
cupy.greater(k, -1))
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@cupy.fuse()
|
| 111 |
+
def _hs(k, cs, rho, omega):
|
| 112 |
+
c0 = (cs * cs * (1 + rho * rho) / (1 - rho * rho) /
|
| 113 |
+
(1 - 2 * rho * rho * cupy.cos(2 * omega) + rho ** 4))
|
| 114 |
+
gamma = (1 - rho * rho) / (1 + rho * rho) / cupy.tan(omega)
|
| 115 |
+
ak = cupy.abs(k)
|
| 116 |
+
return c0 * rho ** ak * (
|
| 117 |
+
cupy.cos(omega * ak) + gamma * cupy.sin(omega * ak))
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _cubic_smooth_coeff(signal, lamb):
|
| 121 |
+
rho, omega = _coeff_smooth(lamb)
|
| 122 |
+
cs = 1 - 2 * rho * cupy.cos(omega) + rho * rho
|
| 123 |
+
K = len(signal)
|
| 124 |
+
yp = cupy.zeros((K,), signal.dtype.char)
|
| 125 |
+
k = cupy.arange(K)
|
| 126 |
+
|
| 127 |
+
state_0 = (_hc(0, cs, rho, omega) * signal[0] +
|
| 128 |
+
cupy.sum(_hc(k + 1, cs, rho, omega) * signal))
|
| 129 |
+
state_1 = (_hc(0, cs, rho, omega) * signal[0] +
|
| 130 |
+
_hc(1, cs, rho, omega) * signal[1] +
|
| 131 |
+
cupy.sum(_hc(k + 2, cs, rho, omega) * signal))
|
| 132 |
+
|
| 133 |
+
zi = cupy.r_[0, 0, state_0, state_1]
|
| 134 |
+
zi = cupy.atleast_2d(zi)
|
| 135 |
+
|
| 136 |
+
coef = cupy.r_[cs, 0, 0, 1, -2 * rho * cupy.cos(omega), rho * rho]
|
| 137 |
+
coef = cupy.atleast_2d(coef)
|
| 138 |
+
|
| 139 |
+
# Forward pass:
|
| 140 |
+
#
|
| 141 |
+
# yp[0] = (_hc(0, cs, rho, omega) * signal[0] +
|
| 142 |
+
# cupy.sum(_hc(k + 1, cs, rho, omega) * signal))
|
| 143 |
+
# yp[1] = (_hc(0, cs, rho, omega) * signal[0] +
|
| 144 |
+
# _hc(1, cs, rho, omega) * signal[1] +
|
| 145 |
+
# cupy.sum(_hc(k + 2, cs, rho, omega) * signal))
|
| 146 |
+
# for n in range(2, K):
|
| 147 |
+
# yp[n] = (cs * signal[n] + 2 * rho * cupy.cos(omega) * yp[n - 1] -
|
| 148 |
+
# rho * rho * yp[n - 2])
|
| 149 |
+
|
| 150 |
+
yp, _ = apply_iir_sos(signal[2:], coef, zi=zi, dtype=signal.dtype)
|
| 151 |
+
yp = cupy.r_[state_0, state_1, yp]
|
| 152 |
+
|
| 153 |
+
# Reverse pass:
|
| 154 |
+
#
|
| 155 |
+
# y[K - 1] = cupy.sum((_hs(k, cs, rho, omega) +
|
| 156 |
+
# _hs(k + 1, cs, rho, omega)) * signal[::-1])
|
| 157 |
+
# y[K - 2] = cupy.sum((_hs(k - 1, cs, rho, omega) +
|
| 158 |
+
# _hs(k + 2, cs, rho, omega)) * signal[::-1])
|
| 159 |
+
# for n in range(K - 3, -1, -1):
|
| 160 |
+
# y[n] = (cs * yp[n] + 2 * rho * cupy.cos(omega) * y[n + 1] -
|
| 161 |
+
# rho * rho * y[n + 2])
|
| 162 |
+
|
| 163 |
+
state_0 = cupy.sum((_hs(k, cs, rho, omega) +
|
| 164 |
+
_hs(k + 1, cs, rho, omega)) * signal[::-1])
|
| 165 |
+
state_1 = cupy.sum((_hs(k - 1, cs, rho, omega) +
|
| 166 |
+
_hs(k + 2, cs, rho, omega)) * signal[::-1])
|
| 167 |
+
|
| 168 |
+
zi = cupy.r_[0, 0, state_0, state_1]
|
| 169 |
+
zi = cupy.atleast_2d(zi)
|
| 170 |
+
|
| 171 |
+
y, _ = apply_iir_sos(yp[-3::-1], coef, zi=zi, dtype=signal.dtype)
|
| 172 |
+
y = cupy.r_[y[::-1], state_1, state_0]
|
| 173 |
+
return y
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _cubic_coeff(signal):
|
| 177 |
+
zi = -2 + cupy.sqrt(3)
|
| 178 |
+
K = len(signal)
|
| 179 |
+
powers = zi ** cupy.arange(K)
|
| 180 |
+
|
| 181 |
+
if K == 1:
|
| 182 |
+
yplus = signal[0] + zi * cupy.sum(powers * signal)
|
| 183 |
+
output = zi / (zi - 1) * yplus
|
| 184 |
+
return cupy.atleast_1d(output)
|
| 185 |
+
|
| 186 |
+
state = cupy.r_[0, 0, 0, cupy.sum(powers * signal)]
|
| 187 |
+
state = cupy.atleast_2d(state)
|
| 188 |
+
coef = cupy.r_[1, 0, 0, 1, -zi, 0]
|
| 189 |
+
coef = cupy.atleast_2d(coef)
|
| 190 |
+
|
| 191 |
+
# yplus[0] = signal[0] + zi * sum(powers * signal)
|
| 192 |
+
# for k in range(1, K):
|
| 193 |
+
# yplus[k] = signal[k] + zi * yplus[k - 1]
|
| 194 |
+
yplus, _ = apply_iir_sos(signal, coef, zi=state, apply_fir=False,
|
| 195 |
+
dtype=signal.dtype)
|
| 196 |
+
|
| 197 |
+
out_last = zi / (zi - 1) * yplus[K - 1]
|
| 198 |
+
state = cupy.r_[0, 0, 0, out_last]
|
| 199 |
+
state = cupy.atleast_2d(state)
|
| 200 |
+
|
| 201 |
+
coef = cupy.r_[-zi, 0, 0, 1, -zi, 0]
|
| 202 |
+
coef = cupy.atleast_2d(coef)
|
| 203 |
+
|
| 204 |
+
# output[K - 1] = zi / (zi - 1) * yplus[K - 1]
|
| 205 |
+
# for k in range(K - 2, -1, -1):
|
| 206 |
+
# output[k] = zi * (output[k + 1] - yplus[k])
|
| 207 |
+
output, _ = apply_iir_sos(
|
| 208 |
+
yplus[-2::-1], coef, zi=state, dtype=signal.dtype)
|
| 209 |
+
output = cupy.r_[output[::-1], out_last]
|
| 210 |
+
return output * 6.0
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _quadratic_coeff(signal):
|
| 214 |
+
zi = -3 + 2 * cupy.sqrt(2.0)
|
| 215 |
+
K = len(signal)
|
| 216 |
+
powers = zi ** cupy.arange(K)
|
| 217 |
+
|
| 218 |
+
if K == 1:
|
| 219 |
+
yplus = signal[0] + zi * cupy.sum(powers * signal)
|
| 220 |
+
output = zi / (zi - 1) * yplus
|
| 221 |
+
return cupy.atleast_1d(output)
|
| 222 |
+
|
| 223 |
+
state = cupy.r_[0, 0, 0, cupy.sum(powers * signal)]
|
| 224 |
+
state = cupy.atleast_2d(state)
|
| 225 |
+
coef = cupy.r_[1, 0, 0, 1, -zi, 0]
|
| 226 |
+
coef = cupy.atleast_2d(coef)
|
| 227 |
+
|
| 228 |
+
# yplus[0] = signal[0] + zi * cupy.sum(powers * signal)
|
| 229 |
+
# for k in range(1, K):
|
| 230 |
+
# yplus[k] = signal[k] + zi * yplus[k - 1]
|
| 231 |
+
yplus, _ = apply_iir_sos(signal, coef, zi=state, apply_fir=False,
|
| 232 |
+
dtype=signal.dtype)
|
| 233 |
+
|
| 234 |
+
out_last = zi / (zi - 1) * yplus[K - 1]
|
| 235 |
+
state = cupy.r_[0, 0, 0, out_last]
|
| 236 |
+
state = cupy.atleast_2d(state)
|
| 237 |
+
|
| 238 |
+
coef = cupy.r_[-zi, 0, 0, 1, -zi, 0]
|
| 239 |
+
coef = cupy.atleast_2d(coef)
|
| 240 |
+
|
| 241 |
+
# output[K - 1] = zi / (zi - 1) * yplus[K - 1]
|
| 242 |
+
# for k in range(K - 2, -1, -1):
|
| 243 |
+
# output[k] = zi * (output[k + 1] - yplus[k])
|
| 244 |
+
output, _ = apply_iir_sos(
|
| 245 |
+
yplus[-2::-1], coef, zi=state, dtype=signal.dtype)
|
| 246 |
+
output = cupy.r_[output[::-1], out_last]
|
| 247 |
+
return output * 8.0
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def compute_root_from_lambda(lamb):
|
| 251 |
+
tmp = np.sqrt(3 + 144 * lamb)
|
| 252 |
+
xi = 1 - 96 * lamb + 24 * lamb * tmp
|
| 253 |
+
omega = np.arctan(np.sqrt((144 * lamb - 1.0) / xi))
|
| 254 |
+
tmp2 = np.sqrt(xi)
|
| 255 |
+
r = ((24 * lamb - 1 - tmp2) / (24 * lamb) *
|
| 256 |
+
np.sqrt((48*lamb + 24 * lamb * tmp)) / tmp2)
|
| 257 |
+
return r, omega
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def cspline1d(signal, lamb=0.0):
|
| 261 |
+
"""
|
| 262 |
+
Compute cubic spline coefficients for rank-1 array.
|
| 263 |
+
|
| 264 |
+
Find the cubic spline coefficients for a 1-D signal assuming
|
| 265 |
+
mirror-symmetric boundary conditions. To obtain the signal back from the
|
| 266 |
+
spline representation mirror-symmetric-convolve these coefficients with a
|
| 267 |
+
length 3 FIR window [1.0, 4.0, 1.0]/ 6.0 .
|
| 268 |
+
|
| 269 |
+
Parameters
|
| 270 |
+
----------
|
| 271 |
+
signal : ndarray
|
| 272 |
+
A rank-1 array representing samples of a signal.
|
| 273 |
+
lamb : float, optional
|
| 274 |
+
Smoothing coefficient, default is 0.0.
|
| 275 |
+
|
| 276 |
+
Returns
|
| 277 |
+
-------
|
| 278 |
+
c : ndarray
|
| 279 |
+
Cubic spline coefficients.
|
| 280 |
+
|
| 281 |
+
See Also
|
| 282 |
+
--------
|
| 283 |
+
cspline1d_eval : Evaluate a cubic spline at the new set of points.
|
| 284 |
+
|
| 285 |
+
"""
|
| 286 |
+
if lamb != 0.0:
|
| 287 |
+
return _cubic_smooth_coeff(signal, lamb)
|
| 288 |
+
else:
|
| 289 |
+
return _cubic_coeff(signal)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def qspline1d(signal, lamb=0.0):
|
| 293 |
+
"""Compute quadratic spline coefficients for rank-1 array.
|
| 294 |
+
|
| 295 |
+
Parameters
|
| 296 |
+
----------
|
| 297 |
+
signal : ndarray
|
| 298 |
+
A rank-1 array representing samples of a signal.
|
| 299 |
+
lamb : float, optional
|
| 300 |
+
Smoothing coefficient (must be zero for now).
|
| 301 |
+
|
| 302 |
+
Returns
|
| 303 |
+
-------
|
| 304 |
+
c : ndarray
|
| 305 |
+
Quadratic spline coefficients.
|
| 306 |
+
|
| 307 |
+
See Also
|
| 308 |
+
--------
|
| 309 |
+
qspline1d_eval : Evaluate a quadratic spline at the new set of points.
|
| 310 |
+
|
| 311 |
+
Notes
|
| 312 |
+
-----
|
| 313 |
+
Find the quadratic spline coefficients for a 1-D signal assuming
|
| 314 |
+
mirror-symmetric boundary conditions. To obtain the signal back from the
|
| 315 |
+
spline representation mirror-symmetric-convolve these coefficients with a
|
| 316 |
+
length 3 FIR window [1.0, 6.0, 1.0]/ 8.0 .
|
| 317 |
+
|
| 318 |
+
"""
|
| 319 |
+
if lamb != 0.0:
|
| 320 |
+
raise ValueError("Smoothing quadratic splines not supported yet.")
|
| 321 |
+
else:
|
| 322 |
+
return _quadratic_coeff(signal)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def cspline1d_eval(cj, newx, dx=1.0, x0=0):
|
| 326 |
+
"""Evaluate a cubic spline at the new set of points.
|
| 327 |
+
|
| 328 |
+
`dx` is the old sample-spacing while `x0` was the old origin. In
|
| 329 |
+
other-words the old-sample points (knot-points) for which the `cj`
|
| 330 |
+
represent spline coefficients were at equally-spaced points of:
|
| 331 |
+
|
| 332 |
+
oldx = x0 + j*dx j=0...N-1, with N=len(cj)
|
| 333 |
+
|
| 334 |
+
Edges are handled using mirror-symmetric boundary conditions.
|
| 335 |
+
|
| 336 |
+
Parameters
|
| 337 |
+
----------
|
| 338 |
+
cj : ndarray
|
| 339 |
+
cublic spline coefficients
|
| 340 |
+
newx : ndarray
|
| 341 |
+
New set of points.
|
| 342 |
+
dx : float, optional
|
| 343 |
+
Old sample-spacing, the default value is 1.0.
|
| 344 |
+
x0 : int, optional
|
| 345 |
+
Old origin, the default value is 0.
|
| 346 |
+
|
| 347 |
+
Returns
|
| 348 |
+
-------
|
| 349 |
+
res : ndarray
|
| 350 |
+
Evaluated a cubic spline points.
|
| 351 |
+
|
| 352 |
+
See Also
|
| 353 |
+
--------
|
| 354 |
+
cspline1d : Compute cubic spline coefficients for rank-1 array.
|
| 355 |
+
|
| 356 |
+
"""
|
| 357 |
+
newx = (cupy.asarray(newx) - x0) / float(dx)
|
| 358 |
+
res = cupy.zeros_like(newx, dtype=cj.dtype)
|
| 359 |
+
if res.size == 0:
|
| 360 |
+
return res
|
| 361 |
+
N = len(cj)
|
| 362 |
+
cond1 = newx < 0
|
| 363 |
+
cond2 = newx > (N - 1)
|
| 364 |
+
cond3 = ~(cond1 | cond2)
|
| 365 |
+
# handle general mirror-symmetry
|
| 366 |
+
res[cond1] = cspline1d_eval(cj, -newx[cond1])
|
| 367 |
+
res[cond2] = cspline1d_eval(cj, 2 * (N - 1) - newx[cond2])
|
| 368 |
+
newx = newx[cond3]
|
| 369 |
+
if newx.size == 0:
|
| 370 |
+
return res
|
| 371 |
+
result = cupy.zeros_like(newx, dtype=cj.dtype)
|
| 372 |
+
jlower = cupy.floor(newx - 2).astype(int) + 1
|
| 373 |
+
for i in range(4):
|
| 374 |
+
thisj = jlower + i
|
| 375 |
+
indj = thisj.clip(0, N - 1) # handle edge cases
|
| 376 |
+
result += cj[indj] * _cubic(newx - thisj)
|
| 377 |
+
res[cond3] = result
|
| 378 |
+
return res
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def qspline1d_eval(cj, newx, dx=1.0, x0=0):
|
| 382 |
+
"""Evaluate a quadratic spline at the new set of points.
|
| 383 |
+
|
| 384 |
+
Parameters
|
| 385 |
+
----------
|
| 386 |
+
cj : ndarray
|
| 387 |
+
Quadratic spline coefficients
|
| 388 |
+
newx : ndarray
|
| 389 |
+
New set of points.
|
| 390 |
+
dx : float, optional
|
| 391 |
+
Old sample-spacing, the default value is 1.0.
|
| 392 |
+
x0 : int, optional
|
| 393 |
+
Old origin, the default value is 0.
|
| 394 |
+
|
| 395 |
+
Returns
|
| 396 |
+
-------
|
| 397 |
+
res : ndarray
|
| 398 |
+
Evaluated a quadratic spline points.
|
| 399 |
+
|
| 400 |
+
See Also
|
| 401 |
+
--------
|
| 402 |
+
qspline1d : Compute quadratic spline coefficients for rank-1 array.
|
| 403 |
+
|
| 404 |
+
Notes
|
| 405 |
+
-----
|
| 406 |
+
`dx` is the old sample-spacing while `x0` was the old origin. In
|
| 407 |
+
other-words the old-sample points (knot-points) for which the `cj`
|
| 408 |
+
represent spline coefficients were at equally-spaced points of::
|
| 409 |
+
|
| 410 |
+
oldx = x0 + j*dx j=0...N-1, with N=len(cj)
|
| 411 |
+
|
| 412 |
+
Edges are handled using mirror-symmetric boundary conditions.
|
| 413 |
+
|
| 414 |
+
"""
|
| 415 |
+
newx = (cupy.asarray(newx) - x0) / dx
|
| 416 |
+
res = cupy.zeros_like(newx)
|
| 417 |
+
if res.size == 0:
|
| 418 |
+
return res
|
| 419 |
+
N = len(cj)
|
| 420 |
+
cond1 = newx < 0
|
| 421 |
+
cond2 = newx > (N - 1)
|
| 422 |
+
cond3 = ~(cond1 | cond2)
|
| 423 |
+
# handle general mirror-symmetry
|
| 424 |
+
res[cond1] = qspline1d_eval(cj, -newx[cond1])
|
| 425 |
+
res[cond2] = qspline1d_eval(cj, 2 * (N - 1) - newx[cond2])
|
| 426 |
+
newx = newx[cond3]
|
| 427 |
+
if newx.size == 0:
|
| 428 |
+
return res
|
| 429 |
+
result = cupy.zeros_like(newx)
|
| 430 |
+
jlower = cupy.floor(newx - 1.5).astype(int) + 1
|
| 431 |
+
for i in range(3):
|
| 432 |
+
thisj = jlower + i
|
| 433 |
+
indj = thisj.clip(0, N - 1) # handle edge cases
|
| 434 |
+
result += cj[indj] * _quadratic(newx - thisj)
|
| 435 |
+
res[cond3] = result
|
| 436 |
+
return res
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def cspline2d(signal, lamb=0.0, precision=-1.0):
|
| 440 |
+
"""
|
| 441 |
+
Coefficients for 2-D cubic (3rd order) B-spline.
|
| 442 |
+
|
| 443 |
+
Return the third-order B-spline coefficients over a regularly spaced
|
| 444 |
+
input grid for the two-dimensional input image.
|
| 445 |
+
|
| 446 |
+
Parameters
|
| 447 |
+
----------
|
| 448 |
+
input : ndarray
|
| 449 |
+
The input signal.
|
| 450 |
+
lamb : float
|
| 451 |
+
Specifies the amount of smoothing in the transfer function.
|
| 452 |
+
precision : float
|
| 453 |
+
Specifies the precision for computing the infinite sum needed to apply
|
| 454 |
+
mirror-symmetric boundary conditions.
|
| 455 |
+
|
| 456 |
+
Returns
|
| 457 |
+
-------
|
| 458 |
+
output : ndarray
|
| 459 |
+
The filtered signal.
|
| 460 |
+
"""
|
| 461 |
+
if lamb <= 1 / 144.0:
|
| 462 |
+
# Normal cubic spline
|
| 463 |
+
r = -2 + np.sqrt(3.0)
|
| 464 |
+
out = _symiirorder1_nd(signal, -r * 6.0, r, precision=precision,
|
| 465 |
+
axis=-1)
|
| 466 |
+
out = _symiirorder1_nd(out, -r * 6.0, r, precision=precision,
|
| 467 |
+
axis=0)
|
| 468 |
+
return out
|
| 469 |
+
|
| 470 |
+
r, omega = compute_root_from_lambda(lamb)
|
| 471 |
+
out = _symiirorder2_nd(signal, r, omega, precision=precision, axis=-1)
|
| 472 |
+
out = _symiirorder2_nd(out, r, omega, precision=precision, axis=0)
|
| 473 |
+
return out
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def qspline2d(signal, lamb=0.0, precision=-1.0):
|
| 477 |
+
"""
|
| 478 |
+
Coefficients for 2-D quadratic (2nd order) B-spline.
|
| 479 |
+
|
| 480 |
+
Return the second-order B-spline coefficients over a regularly spaced
|
| 481 |
+
input grid for the two-dimensional input image.
|
| 482 |
+
|
| 483 |
+
Parameters
|
| 484 |
+
----------
|
| 485 |
+
input : ndarray
|
| 486 |
+
The input signal.
|
| 487 |
+
lamb : float
|
| 488 |
+
Specifies the amount of smoothing in the transfer function.
|
| 489 |
+
precision : float
|
| 490 |
+
Specifies the precision for computing the infinite sum needed to apply
|
| 491 |
+
mirror-symmetric boundary conditions.
|
| 492 |
+
|
| 493 |
+
Returns
|
| 494 |
+
-------
|
| 495 |
+
output : ndarray
|
| 496 |
+
The filtered signal.
|
| 497 |
+
"""
|
| 498 |
+
|
| 499 |
+
if lamb > 0:
|
| 500 |
+
raise ValueError('lambda must be negative or zero')
|
| 501 |
+
|
| 502 |
+
# normal quadratic spline
|
| 503 |
+
r = -3 + 2 * np.sqrt(2.0)
|
| 504 |
+
|
| 505 |
+
out = _symiirorder1_nd(signal, -r * 8.0, r, precision=precision, axis=-1)
|
| 506 |
+
out = _symiirorder1_nd(out, -r * 8.0, r, precision=precision, axis=0)
|
| 507 |
+
return out
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
def spline_filter(Iin, lmbda=5.0):
|
| 511 |
+
"""Smoothing spline (cubic) filtering of a rank-2 array.
|
| 512 |
+
|
| 513 |
+
Filter an input data set, `Iin`, using a (cubic) smoothing spline of
|
| 514 |
+
fall-off `lmbda`.
|
| 515 |
+
|
| 516 |
+
Parameters
|
| 517 |
+
----------
|
| 518 |
+
Iin : array_like
|
| 519 |
+
input data set
|
| 520 |
+
lmbda : float, optional
|
| 521 |
+
spline smooghing fall-off value, default is `5.0`.
|
| 522 |
+
|
| 523 |
+
Returns
|
| 524 |
+
-------
|
| 525 |
+
res : ndarray
|
| 526 |
+
filtered input data
|
| 527 |
+
|
| 528 |
+
"""
|
| 529 |
+
intype = Iin.dtype.char
|
| 530 |
+
hcol = cupy.asarray([1.0, 4.0, 1.0], 'f') / 6.0
|
| 531 |
+
if intype in ['F', 'D']:
|
| 532 |
+
Iin = Iin.astype('F')
|
| 533 |
+
ckr = cspline2d(Iin.real, lmbda)
|
| 534 |
+
cki = cspline2d(Iin.imag, lmbda)
|
| 535 |
+
outr = sepfir2d(ckr, hcol, hcol)
|
| 536 |
+
outi = sepfir2d(cki, hcol, hcol)
|
| 537 |
+
out = (outr + 1j * outi).astype(intype)
|
| 538 |
+
elif intype in ['f', 'd']:
|
| 539 |
+
ckr = cspline2d(Iin, lmbda)
|
| 540 |
+
out = sepfir2d(ckr, hcol, hcol)
|
| 541 |
+
out = out.astype(intype)
|
| 542 |
+
else:
|
| 543 |
+
raise TypeError("Invalid data type for Iin")
|
| 544 |
+
return out
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
_gauss_spline_kernel = cupy.ElementwiseKernel(
|
| 548 |
+
"T x, int32 n",
|
| 549 |
+
"T output",
|
| 550 |
+
"""
|
| 551 |
+
output = 1 / sqrt( 2.0 * M_PI * signsq ) * exp( -( x * x ) * r_signsq );
|
| 552 |
+
""",
|
| 553 |
+
"_gauss_spline_kernel",
|
| 554 |
+
options=("-std=c++11",),
|
| 555 |
+
loop_prep="const double signsq { ( n + 1 ) / 12.0 }; \
|
| 556 |
+
const double r_signsq { 0.5 / signsq };",
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def gauss_spline(x, n):
|
| 561 |
+
r"""Gaussian approximation to B-spline basis function of order n.
|
| 562 |
+
|
| 563 |
+
Parameters
|
| 564 |
+
----------
|
| 565 |
+
x : array_like
|
| 566 |
+
a knot vector
|
| 567 |
+
n : int
|
| 568 |
+
The order of the spline. Must be nonnegative, i.e. n >= 0
|
| 569 |
+
|
| 570 |
+
Returns
|
| 571 |
+
-------
|
| 572 |
+
res : ndarray
|
| 573 |
+
B-spline basis function values approximated by a zero-mean Gaussian
|
| 574 |
+
function.
|
| 575 |
+
|
| 576 |
+
Notes
|
| 577 |
+
-----
|
| 578 |
+
The B-spline basis function can be approximated well by a zero-mean
|
| 579 |
+
Gaussian function with standard-deviation equal to :math:`\sigma=(n+1)/12`
|
| 580 |
+
for large `n` :
|
| 581 |
+
|
| 582 |
+
.. math:: \frac{1}{\sqrt {2\pi\sigma^2}}exp(-\frac{x^2}{2\sigma})
|
| 583 |
+
|
| 584 |
+
See [1]_, [2]_ for more information.
|
| 585 |
+
|
| 586 |
+
References
|
| 587 |
+
----------
|
| 588 |
+
.. [1] Bouma H., Vilanova A., Bescos J.O., ter Haar Romeny B.M., Gerritsen
|
| 589 |
+
F.A. (2007) Fast and Accurate Gaussian Derivatives Based on B-Splines.
|
| 590 |
+
In: Sgallari F., Murli A., Paragios N. (eds) Scale Space and Variational
|
| 591 |
+
Methods in Computer Vision. SSVM 2007. Lecture Notes in Computer
|
| 592 |
+
Science, vol 4485. Springer, Berlin, Heidelberg
|
| 593 |
+
.. [2] http://folk.uio.no/inf3330/scripting/doc/python/SciPy/tutorial/old/node24.html
|
| 594 |
+
""" # NOQA
|
| 595 |
+
x = cupy.asarray(x)
|
| 596 |
+
return _gauss_spline_kernel(x, n)
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_czt.py
ADDED
|
@@ -0,0 +1,451 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This program is public domain
|
| 2 |
+
# Authors: Paul Kienzle, Nadav Horesh
|
| 3 |
+
#
|
| 4 |
+
# Adapted from scipy 1.10.1.
|
| 5 |
+
#
|
| 6 |
+
"""
|
| 7 |
+
Chirp z-transform.
|
| 8 |
+
|
| 9 |
+
We provide two interfaces to the chirp z-transform: an object interface
|
| 10 |
+
which precalculates part of the transform and can be applied efficiently
|
| 11 |
+
to many different data sets, and a functional interface which is applied
|
| 12 |
+
only to the given data set.
|
| 13 |
+
|
| 14 |
+
Transforms
|
| 15 |
+
----------
|
| 16 |
+
|
| 17 |
+
CZT : callable (x, axis=-1) -> array
|
| 18 |
+
Define a chirp z-transform that can be applied to different signals.
|
| 19 |
+
ZoomFFT : callable (x, axis=-1) -> array
|
| 20 |
+
Define a Fourier transform on a range of frequencies.
|
| 21 |
+
|
| 22 |
+
Functions
|
| 23 |
+
---------
|
| 24 |
+
|
| 25 |
+
czt : array
|
| 26 |
+
Compute the chirp z-transform for a signal.
|
| 27 |
+
zoom_fft : array
|
| 28 |
+
Compute the Fourier transform on a range of frequencies.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
import cmath
|
| 32 |
+
import numbers
|
| 33 |
+
import cupy
|
| 34 |
+
from numpy import pi
|
| 35 |
+
from cupyx.scipy.fft import fft, ifft, next_fast_len
|
| 36 |
+
|
| 37 |
+
__all__ = ['czt', 'zoom_fft', 'CZT', 'ZoomFFT', 'czt_points']
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _validate_sizes(n, m):
|
| 41 |
+
if n < 1 or not isinstance(n, numbers.Integral):
|
| 42 |
+
raise ValueError('Invalid number of CZT data '
|
| 43 |
+
f'points ({n}) specified. '
|
| 44 |
+
'n must be positive and integer type.')
|
| 45 |
+
|
| 46 |
+
if m is None:
|
| 47 |
+
m = n
|
| 48 |
+
elif m < 1 or not isinstance(m, numbers.Integral):
|
| 49 |
+
raise ValueError('Invalid number of CZT output '
|
| 50 |
+
f'points ({m}) specified. '
|
| 51 |
+
'm must be positive and integer type.')
|
| 52 |
+
|
| 53 |
+
return m
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def czt_points(m, w=None, a=1+0j):
|
| 57 |
+
"""
|
| 58 |
+
Return the points at which the chirp z-transform is computed.
|
| 59 |
+
|
| 60 |
+
Parameters
|
| 61 |
+
----------
|
| 62 |
+
m : int
|
| 63 |
+
The number of points desired.
|
| 64 |
+
w : complex, optional
|
| 65 |
+
The ratio between points in each step.
|
| 66 |
+
Defaults to equally spaced points around the entire unit circle.
|
| 67 |
+
a : complex, optional
|
| 68 |
+
The starting point in the complex plane. Default is 1+0j.
|
| 69 |
+
|
| 70 |
+
Returns
|
| 71 |
+
-------
|
| 72 |
+
out : ndarray
|
| 73 |
+
The points in the Z plane at which `CZT` samples the z-transform,
|
| 74 |
+
when called with arguments `m`, `w`, and `a`, as complex numbers.
|
| 75 |
+
|
| 76 |
+
See Also
|
| 77 |
+
--------
|
| 78 |
+
CZT : Class that creates a callable chirp z-transform function.
|
| 79 |
+
czt : Convenience function for quickly calculating CZT.
|
| 80 |
+
scipy.signal.czt_points
|
| 81 |
+
|
| 82 |
+
"""
|
| 83 |
+
m = _validate_sizes(1, m)
|
| 84 |
+
|
| 85 |
+
k = cupy.arange(m)
|
| 86 |
+
|
| 87 |
+
a = 1.0 * a # at least float
|
| 88 |
+
|
| 89 |
+
if w is None:
|
| 90 |
+
# Nothing specified, default to FFT
|
| 91 |
+
return a * cupy.exp(2j * pi * k / m)
|
| 92 |
+
else:
|
| 93 |
+
# w specified
|
| 94 |
+
w = 1.0 * w # at least float
|
| 95 |
+
return a * w**-k
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class CZT:
|
| 99 |
+
"""
|
| 100 |
+
Create a callable chirp z-transform function.
|
| 101 |
+
|
| 102 |
+
Transform to compute the frequency response around a spiral.
|
| 103 |
+
Objects of this class are callables which can compute the
|
| 104 |
+
chirp z-transform on their inputs. This object precalculates the constant
|
| 105 |
+
chirps used in the given transform.
|
| 106 |
+
|
| 107 |
+
Parameters
|
| 108 |
+
----------
|
| 109 |
+
n : int
|
| 110 |
+
The size of the signal.
|
| 111 |
+
m : int, optional
|
| 112 |
+
The number of output points desired. Default is `n`.
|
| 113 |
+
w : complex, optional
|
| 114 |
+
The ratio between points in each step. This must be precise or the
|
| 115 |
+
accumulated error will degrade the tail of the output sequence.
|
| 116 |
+
Defaults to equally spaced points around the entire unit circle.
|
| 117 |
+
a : complex, optional
|
| 118 |
+
The starting point in the complex plane. Default is 1+0j.
|
| 119 |
+
|
| 120 |
+
Returns
|
| 121 |
+
-------
|
| 122 |
+
f : CZT
|
| 123 |
+
Callable object ``f(x, axis=-1)`` for computing the chirp z-transform
|
| 124 |
+
on `x`.
|
| 125 |
+
|
| 126 |
+
See Also
|
| 127 |
+
--------
|
| 128 |
+
czt : Convenience function for quickly calculating CZT.
|
| 129 |
+
ZoomFFT : Class that creates a callable partial FFT function.
|
| 130 |
+
scipy.signal.CZT
|
| 131 |
+
|
| 132 |
+
Notes
|
| 133 |
+
-----
|
| 134 |
+
The defaults are chosen such that ``f(x)`` is equivalent to
|
| 135 |
+
``fft.fft(x)`` and, if ``m > len(x)``, that ``f(x, m)`` is equivalent to
|
| 136 |
+
``fft.fft(x, m)``.
|
| 137 |
+
|
| 138 |
+
If `w` does not lie on the unit circle, then the transform will be
|
| 139 |
+
around a spiral with exponentially-increasing radius. Regardless,
|
| 140 |
+
angle will increase linearly.
|
| 141 |
+
|
| 142 |
+
For transforms that do lie on the unit circle, accuracy is better when
|
| 143 |
+
using `ZoomFFT`, since any numerical error in `w` is
|
| 144 |
+
accumulated for long data lengths, drifting away from the unit circle.
|
| 145 |
+
|
| 146 |
+
The chirp z-transform can be faster than an equivalent FFT with
|
| 147 |
+
zero padding. Try it with your own array sizes to see.
|
| 148 |
+
|
| 149 |
+
However, the chirp z-transform is considerably less precise than the
|
| 150 |
+
equivalent zero-padded FFT.
|
| 151 |
+
|
| 152 |
+
As this CZT is implemented using the Bluestein algorithm [1]_, it can
|
| 153 |
+
compute large prime-length Fourier transforms in O(N log N) time, rather
|
| 154 |
+
than the O(N**2) time required by the direct DFT calculation.
|
| 155 |
+
(`scipy.fft` also uses Bluestein's algorithm'.)
|
| 156 |
+
|
| 157 |
+
(The name "chirp z-transform" comes from the use of a chirp in the
|
| 158 |
+
Bluestein algorithm [2]_. It does not decompose signals into chirps, like
|
| 159 |
+
other transforms with "chirp" in the name.)
|
| 160 |
+
|
| 161 |
+
References
|
| 162 |
+
----------
|
| 163 |
+
.. [1] Leo I. Bluestein, "A linear filtering approach to the computation
|
| 164 |
+
of the discrete Fourier transform," Northeast Electronics Research
|
| 165 |
+
and Engineering Meeting Record 10, 218-219 (1968).
|
| 166 |
+
.. [2] Rabiner, Schafer, and Rader, "The chirp z-transform algorithm and
|
| 167 |
+
its application," Bell Syst. Tech. J. 48, 1249-1292 (1969).
|
| 168 |
+
|
| 169 |
+
"""
|
| 170 |
+
|
| 171 |
+
def __init__(self, n, m=None, w=None, a=1+0j):
|
| 172 |
+
m = _validate_sizes(n, m)
|
| 173 |
+
|
| 174 |
+
k = cupy.arange(max(m, n), dtype=cupy.min_scalar_type(-max(m, n)**2))
|
| 175 |
+
|
| 176 |
+
if w is None:
|
| 177 |
+
# Nothing specified, default to FFT-like
|
| 178 |
+
w = cmath.exp(-2j*pi/m)
|
| 179 |
+
wk2 = cupy.exp(-(1j * pi * ((k**2) % (2*m))) / m)
|
| 180 |
+
else:
|
| 181 |
+
# w specified
|
| 182 |
+
wk2 = w**(k**2/2.)
|
| 183 |
+
|
| 184 |
+
a = 1.0 * a # at least float
|
| 185 |
+
|
| 186 |
+
self.w, self.a = w, a
|
| 187 |
+
self.m, self.n = m, n
|
| 188 |
+
|
| 189 |
+
nfft = next_fast_len(n + m - 1)
|
| 190 |
+
self._Awk2 = a**-k[:n] * wk2[:n]
|
| 191 |
+
self._nfft = nfft
|
| 192 |
+
self._Fwk2 = fft(1/cupy.hstack((wk2[n-1:0:-1], wk2[:m])), nfft)
|
| 193 |
+
self._wk2 = wk2[:m]
|
| 194 |
+
self._yidx = slice(n-1, n+m-1)
|
| 195 |
+
|
| 196 |
+
def __call__(self, x, *, axis=-1):
|
| 197 |
+
"""
|
| 198 |
+
Calculate the chirp z-transform of a signal.
|
| 199 |
+
|
| 200 |
+
Parameters
|
| 201 |
+
----------
|
| 202 |
+
x : array
|
| 203 |
+
The signal to transform.
|
| 204 |
+
axis : int, optional
|
| 205 |
+
Axis over which to compute the FFT. If not given, the last axis is
|
| 206 |
+
used.
|
| 207 |
+
|
| 208 |
+
Returns
|
| 209 |
+
-------
|
| 210 |
+
out : ndarray
|
| 211 |
+
An array of the same dimensions as `x`, but with the length of the
|
| 212 |
+
transformed axis set to `m`.
|
| 213 |
+
"""
|
| 214 |
+
x = cupy.asarray(x)
|
| 215 |
+
if x.shape[axis] != self.n:
|
| 216 |
+
raise ValueError(f"CZT defined for length {self.n}, not "
|
| 217 |
+
f"{x.shape[axis]}")
|
| 218 |
+
# Calculate transpose coordinates, to allow operation on any given axis
|
| 219 |
+
trnsp = list(range(x.ndim))
|
| 220 |
+
trnsp[axis], trnsp[-1] = trnsp[-1], trnsp[axis]
|
| 221 |
+
x = x.transpose(*trnsp)
|
| 222 |
+
y = ifft(self._Fwk2 * fft(x*self._Awk2, self._nfft))
|
| 223 |
+
y = y[..., self._yidx] * self._wk2
|
| 224 |
+
return y.transpose(*trnsp)
|
| 225 |
+
|
| 226 |
+
def points(self):
|
| 227 |
+
"""
|
| 228 |
+
Return the points at which the chirp z-transform is computed.
|
| 229 |
+
"""
|
| 230 |
+
return czt_points(self.m, self.w, self.a)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
class ZoomFFT(CZT):
|
| 234 |
+
"""
|
| 235 |
+
Create a callable zoom FFT transform function.
|
| 236 |
+
|
| 237 |
+
This is a specialization of the chirp z-transform (`CZT`) for a set of
|
| 238 |
+
equally-spaced frequencies around the unit circle, used to calculate a
|
| 239 |
+
section of the FFT more efficiently than calculating the entire FFT and
|
| 240 |
+
truncating. [1]_
|
| 241 |
+
|
| 242 |
+
Parameters
|
| 243 |
+
----------
|
| 244 |
+
n : int
|
| 245 |
+
The size of the signal.
|
| 246 |
+
fn : array_like
|
| 247 |
+
A length-2 sequence [`f1`, `f2`] giving the frequency range, or a
|
| 248 |
+
scalar, for which the range [0, `fn`] is assumed.
|
| 249 |
+
m : int, optional
|
| 250 |
+
The number of points to evaluate. Default is `n`.
|
| 251 |
+
fs : float, optional
|
| 252 |
+
The sampling frequency. If ``fs=10`` represented 10 kHz, for example,
|
| 253 |
+
then `f1` and `f2` would also be given in kHz.
|
| 254 |
+
The default sampling frequency is 2, so `f1` and `f2` should be
|
| 255 |
+
in the range [0, 1] to keep the transform below the Nyquist
|
| 256 |
+
frequency.
|
| 257 |
+
endpoint : bool, optional
|
| 258 |
+
If True, `f2` is the last sample. Otherwise, it is not included.
|
| 259 |
+
Default is False.
|
| 260 |
+
|
| 261 |
+
Returns
|
| 262 |
+
-------
|
| 263 |
+
f : ZoomFFT
|
| 264 |
+
Callable object ``f(x, axis=-1)`` for computing the zoom FFT on `x`.
|
| 265 |
+
|
| 266 |
+
See Also
|
| 267 |
+
--------
|
| 268 |
+
zoom_fft : Convenience function for calculating a zoom FFT.
|
| 269 |
+
scipy.signal.ZoomFFT
|
| 270 |
+
|
| 271 |
+
Notes
|
| 272 |
+
-----
|
| 273 |
+
The defaults are chosen such that ``f(x, 2)`` is equivalent to
|
| 274 |
+
``fft.fft(x)`` and, if ``m > len(x)``, that ``f(x, 2, m)`` is equivalent to
|
| 275 |
+
``fft.fft(x, m)``.
|
| 276 |
+
|
| 277 |
+
Sampling frequency is 1/dt, the time step between samples in the
|
| 278 |
+
signal `x`. The unit circle corresponds to frequencies from 0 up
|
| 279 |
+
to the sampling frequency. The default sampling frequency of 2
|
| 280 |
+
means that `f1`, `f2` values up to the Nyquist frequency are in the
|
| 281 |
+
range [0, 1). For `f1`, `f2` values expressed in radians, a sampling
|
| 282 |
+
frequency of 2*pi should be used.
|
| 283 |
+
|
| 284 |
+
Remember that a zoom FFT can only interpolate the points of the existing
|
| 285 |
+
FFT. It cannot help to resolve two separate nearby frequencies.
|
| 286 |
+
Frequency resolution can only be increased by increasing acquisition
|
| 287 |
+
time.
|
| 288 |
+
|
| 289 |
+
These functions are implemented using Bluestein's algorithm (as is
|
| 290 |
+
`scipy.fft`). [2]_
|
| 291 |
+
|
| 292 |
+
References
|
| 293 |
+
----------
|
| 294 |
+
.. [1] Steve Alan Shilling, "A study of the chirp z-transform and its
|
| 295 |
+
applications", pg 29 (1970)
|
| 296 |
+
https://krex.k-state.edu/dspace/bitstream/handle/2097/7844/LD2668R41972S43.pdf
|
| 297 |
+
.. [2] Leo I. Bluestein, "A linear filtering approach to the computation
|
| 298 |
+
of the discrete Fourier transform," Northeast Electronics Research
|
| 299 |
+
and Engineering Meeting Record 10, 218-219 (1968).
|
| 300 |
+
"""
|
| 301 |
+
|
| 302 |
+
def __init__(self, n, fn, m=None, *, fs=2, endpoint=False):
|
| 303 |
+
m = _validate_sizes(n, m)
|
| 304 |
+
|
| 305 |
+
k = cupy.arange(max(m, n), dtype=cupy.min_scalar_type(-max(m, n)**2))
|
| 306 |
+
|
| 307 |
+
fn = cupy.asarray(fn)
|
| 308 |
+
if cupy.size(fn) == 2:
|
| 309 |
+
f1, f2 = fn
|
| 310 |
+
elif cupy.size(fn) == 1:
|
| 311 |
+
f1, f2 = 0.0, fn
|
| 312 |
+
else:
|
| 313 |
+
raise ValueError('fn must be a scalar or 2-length sequence')
|
| 314 |
+
|
| 315 |
+
self.f1, self.f2, self.fs = f1, f2, fs
|
| 316 |
+
|
| 317 |
+
if endpoint:
|
| 318 |
+
scale = ((f2 - f1) * m) / (fs * (m - 1))
|
| 319 |
+
else:
|
| 320 |
+
scale = (f2 - f1) / fs
|
| 321 |
+
a = cmath.exp(2j * pi * f1/fs)
|
| 322 |
+
wk2 = cupy.exp(-(1j * pi * scale * k**2) / m)
|
| 323 |
+
|
| 324 |
+
self.w = cmath.exp(-2j*pi/m * scale)
|
| 325 |
+
self.a = a
|
| 326 |
+
self.m, self.n = m, n
|
| 327 |
+
|
| 328 |
+
ak = cupy.exp(-2j * pi * f1/fs * k[:n])
|
| 329 |
+
self._Awk2 = ak * wk2[:n]
|
| 330 |
+
|
| 331 |
+
nfft = next_fast_len(n + m - 1)
|
| 332 |
+
self._nfft = nfft
|
| 333 |
+
self._Fwk2 = fft(1/cupy.hstack((wk2[n-1:0:-1], wk2[:m])), nfft)
|
| 334 |
+
self._wk2 = wk2[:m]
|
| 335 |
+
self._yidx = slice(n-1, n+m-1)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def czt(x, m=None, w=None, a=1+0j, *, axis=-1):
|
| 339 |
+
"""
|
| 340 |
+
Compute the frequency response around a spiral in the Z plane.
|
| 341 |
+
|
| 342 |
+
Parameters
|
| 343 |
+
----------
|
| 344 |
+
x : array
|
| 345 |
+
The signal to transform.
|
| 346 |
+
m : int, optional
|
| 347 |
+
The number of output points desired. Default is the length of the
|
| 348 |
+
input data.
|
| 349 |
+
w : complex, optional
|
| 350 |
+
The ratio between points in each step. This must be precise or the
|
| 351 |
+
accumulated error will degrade the tail of the output sequence.
|
| 352 |
+
Defaults to equally spaced points around the entire unit circle.
|
| 353 |
+
a : complex, optional
|
| 354 |
+
The starting point in the complex plane. Default is 1+0j.
|
| 355 |
+
axis : int, optional
|
| 356 |
+
Axis over which to compute the FFT. If not given, the last axis is
|
| 357 |
+
used.
|
| 358 |
+
|
| 359 |
+
Returns
|
| 360 |
+
-------
|
| 361 |
+
out : ndarray
|
| 362 |
+
An array of the same dimensions as `x`, but with the length of the
|
| 363 |
+
transformed axis set to `m`.
|
| 364 |
+
|
| 365 |
+
See Also
|
| 366 |
+
--------
|
| 367 |
+
CZT : Class that creates a callable chirp z-transform function.
|
| 368 |
+
zoom_fft : Convenience function for partial FFT calculations.
|
| 369 |
+
scipy.signal.czt
|
| 370 |
+
|
| 371 |
+
Notes
|
| 372 |
+
-----
|
| 373 |
+
The defaults are chosen such that ``signal.czt(x)`` is equivalent to
|
| 374 |
+
``fft.fft(x)`` and, if ``m > len(x)``, that ``signal.czt(x, m)`` is
|
| 375 |
+
equivalent to ``fft.fft(x, m)``.
|
| 376 |
+
|
| 377 |
+
If the transform needs to be repeated, use `CZT` to construct a
|
| 378 |
+
specialized transform function which can be reused without
|
| 379 |
+
recomputing constants.
|
| 380 |
+
|
| 381 |
+
An example application is in system identification, repeatedly evaluating
|
| 382 |
+
small slices of the z-transform of a system, around where a pole is
|
| 383 |
+
expected to exist, to refine the estimate of the pole's true location. [1]_
|
| 384 |
+
|
| 385 |
+
References
|
| 386 |
+
----------
|
| 387 |
+
.. [1] Steve Alan Shilling, "A study of the chirp z-transform and its
|
| 388 |
+
applications", pg 20 (1970)
|
| 389 |
+
https://krex.k-state.edu/dspace/bitstream/handle/2097/7844/LD2668R41972S43.pdf
|
| 390 |
+
|
| 391 |
+
"""
|
| 392 |
+
x = cupy.asarray(x)
|
| 393 |
+
transform = CZT(x.shape[axis], m=m, w=w, a=a)
|
| 394 |
+
return transform(x, axis=axis)
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def zoom_fft(x, fn, m=None, *, fs=2, endpoint=False, axis=-1):
|
| 398 |
+
"""
|
| 399 |
+
Compute the DFT of `x` only for frequencies in range `fn`.
|
| 400 |
+
|
| 401 |
+
Parameters
|
| 402 |
+
----------
|
| 403 |
+
x : array
|
| 404 |
+
The signal to transform.
|
| 405 |
+
fn : array_like
|
| 406 |
+
A length-2 sequence [`f1`, `f2`] giving the frequency range, or a
|
| 407 |
+
scalar, for which the range [0, `fn`] is assumed.
|
| 408 |
+
m : int, optional
|
| 409 |
+
The number of points to evaluate. The default is the length of `x`.
|
| 410 |
+
fs : float, optional
|
| 411 |
+
The sampling frequency. If ``fs=10`` represented 10 kHz, for example,
|
| 412 |
+
then `f1` and `f2` would also be given in kHz.
|
| 413 |
+
The default sampling frequency is 2, so `f1` and `f2` should be
|
| 414 |
+
in the range [0, 1] to keep the transform below the Nyquist
|
| 415 |
+
frequency.
|
| 416 |
+
endpoint : bool, optional
|
| 417 |
+
If True, `f2` is the last sample. Otherwise, it is not included.
|
| 418 |
+
Default is False.
|
| 419 |
+
axis : int, optional
|
| 420 |
+
Axis over which to compute the FFT. If not given, the last axis is
|
| 421 |
+
used.
|
| 422 |
+
|
| 423 |
+
Returns
|
| 424 |
+
-------
|
| 425 |
+
out : ndarray
|
| 426 |
+
The transformed signal. The Fourier transform will be calculated
|
| 427 |
+
at the points f1, f1+df, f1+2df, ..., f2, where df=(f2-f1)/m.
|
| 428 |
+
|
| 429 |
+
See Also
|
| 430 |
+
--------
|
| 431 |
+
ZoomFFT : Class that creates a callable partial FFT function.
|
| 432 |
+
scipy.signal.zoom_fft
|
| 433 |
+
|
| 434 |
+
Notes
|
| 435 |
+
-----
|
| 436 |
+
The defaults are chosen such that ``signal.zoom_fft(x, 2)`` is equivalent
|
| 437 |
+
to ``fft.fft(x)`` and, if ``m > len(x)``, that ``signal.zoom_fft(x, 2, m)``
|
| 438 |
+
is equivalent to ``fft.fft(x, m)``.
|
| 439 |
+
|
| 440 |
+
To graph the magnitude of the resulting transform, use::
|
| 441 |
+
|
| 442 |
+
plot(linspace(f1, f2, m, endpoint=False),
|
| 443 |
+
abs(zoom_fft(x, [f1, f2], m)))
|
| 444 |
+
|
| 445 |
+
If the transform needs to be repeated, use `ZoomFFT` to construct
|
| 446 |
+
a specialized transform function which can be reused without
|
| 447 |
+
recomputing constants.
|
| 448 |
+
"""
|
| 449 |
+
x = cupy.asarray(x)
|
| 450 |
+
transform = ZoomFFT(x.shape[axis], fn, m=m, fs=fs, endpoint=endpoint)
|
| 451 |
+
return transform(x, axis=axis)
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_filter_design.py
ADDED
|
@@ -0,0 +1,811 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
import warnings
|
| 4 |
+
|
| 5 |
+
import cupy
|
| 6 |
+
from cupy.polynomial.polynomial import (
|
| 7 |
+
polyval as npp_polyval, polyvalfromroots as npp_polyvalfromroots)
|
| 8 |
+
import cupyx.scipy.fft as sp_fft
|
| 9 |
+
from cupyx import jit
|
| 10 |
+
from cupyx.scipy._lib._util import float_factorial
|
| 11 |
+
from cupyx.scipy.signal._polyutils import roots
|
| 12 |
+
|
| 13 |
+
EPSILON = 2e-16
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _try_convert_to_int(x):
|
| 17 |
+
"""Return an integer for ``5`` and ``array(5)``, fail if not an
|
| 18 |
+
integer scalar.
|
| 19 |
+
|
| 20 |
+
NB: would be easier if ``operator.index(cupy.array(5))`` worked
|
| 21 |
+
(numpy.array(5) does)
|
| 22 |
+
"""
|
| 23 |
+
if isinstance(x, cupy.ndarray):
|
| 24 |
+
if x.ndim == 0:
|
| 25 |
+
value = x.item()
|
| 26 |
+
else:
|
| 27 |
+
return x, False
|
| 28 |
+
else:
|
| 29 |
+
value = x
|
| 30 |
+
try:
|
| 31 |
+
return operator.index(value), True
|
| 32 |
+
except TypeError:
|
| 33 |
+
return value, False
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def findfreqs(num, den, N, kind='ba'):
|
| 37 |
+
"""
|
| 38 |
+
Find array of frequencies for computing the response of an analog filter.
|
| 39 |
+
|
| 40 |
+
Parameters
|
| 41 |
+
----------
|
| 42 |
+
num, den : array_like, 1-D
|
| 43 |
+
The polynomial coefficients of the numerator and denominator of the
|
| 44 |
+
transfer function of the filter or LTI system, where the coefficients
|
| 45 |
+
are ordered from highest to lowest degree. Or, the roots of the
|
| 46 |
+
transfer function numerator and denominator (i.e., zeroes and poles).
|
| 47 |
+
N : int
|
| 48 |
+
The length of the array to be computed.
|
| 49 |
+
kind : str {'ba', 'zp'}, optional
|
| 50 |
+
Specifies whether the numerator and denominator are specified by their
|
| 51 |
+
polynomial coefficients ('ba'), or their roots ('zp').
|
| 52 |
+
|
| 53 |
+
Returns
|
| 54 |
+
-------
|
| 55 |
+
w : (N,) ndarray
|
| 56 |
+
A 1-D array of frequencies, logarithmically spaced.
|
| 57 |
+
|
| 58 |
+
Warning
|
| 59 |
+
-------
|
| 60 |
+
This function may synchronize the device.
|
| 61 |
+
|
| 62 |
+
See Also
|
| 63 |
+
--------
|
| 64 |
+
scipy.signal.find_freqs
|
| 65 |
+
|
| 66 |
+
Examples
|
| 67 |
+
--------
|
| 68 |
+
Find a set of nine frequencies that span the "interesting part" of the
|
| 69 |
+
frequency response for the filter with the transfer function
|
| 70 |
+
|
| 71 |
+
H(s) = s / (s^2 + 8s + 25)
|
| 72 |
+
|
| 73 |
+
>>> from scipy import signal
|
| 74 |
+
>>> signal.findfreqs([1, 0], [1, 8, 25], N=9)
|
| 75 |
+
array([ 1.00000000e-02, 3.16227766e-02, 1.00000000e-01,
|
| 76 |
+
3.16227766e-01, 1.00000000e+00, 3.16227766e+00,
|
| 77 |
+
1.00000000e+01, 3.16227766e+01, 1.00000000e+02])
|
| 78 |
+
"""
|
| 79 |
+
if kind == 'ba':
|
| 80 |
+
ep = cupy.atleast_1d(roots(den)) + 0j
|
| 81 |
+
tz = cupy.atleast_1d(roots(num)) + 0j
|
| 82 |
+
elif kind == 'zp':
|
| 83 |
+
ep = cupy.atleast_1d(den) + 0j
|
| 84 |
+
tz = cupy.atleast_1d(num) + 0j
|
| 85 |
+
else:
|
| 86 |
+
raise ValueError("input must be one of {'ba', 'zp'}")
|
| 87 |
+
|
| 88 |
+
if len(ep) == 0:
|
| 89 |
+
ep = cupy.atleast_1d(-1000) + 0j
|
| 90 |
+
|
| 91 |
+
ez = cupy.r_[
|
| 92 |
+
cupy.compress(ep.imag >= 0, ep, axis=-1),
|
| 93 |
+
cupy.compress((abs(tz) < 1e5) & (tz.imag >= 0), tz, axis=-1)]
|
| 94 |
+
|
| 95 |
+
integ = cupy.abs(ez) < 1e-10
|
| 96 |
+
hfreq = cupy.around(cupy.log10(cupy.max(3 * cupy.abs(ez.real + integ) +
|
| 97 |
+
1.5 * ez.imag)) + 0.5)
|
| 98 |
+
lfreq = cupy.around(cupy.log10(0.1 * cupy.min(cupy.abs((ez + integ).real) +
|
| 99 |
+
2 * ez.imag)) - 0.5)
|
| 100 |
+
w = cupy.logspace(lfreq, hfreq, N)
|
| 101 |
+
return w
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def freqs(b, a, worN=200, plot=None):
|
| 105 |
+
"""
|
| 106 |
+
Compute frequency response of analog filter.
|
| 107 |
+
|
| 108 |
+
Given the M-order numerator `b` and N-order denominator `a` of an analog
|
| 109 |
+
filter, compute its frequency response::
|
| 110 |
+
|
| 111 |
+
b[0]*(jw)**M + b[1]*(jw)**(M-1) + ... + b[M]
|
| 112 |
+
H(w) = ----------------------------------------------
|
| 113 |
+
a[0]*(jw)**N + a[1]*(jw)**(N-1) + ... + a[N]
|
| 114 |
+
|
| 115 |
+
Parameters
|
| 116 |
+
----------
|
| 117 |
+
b : array_like
|
| 118 |
+
Numerator of a linear filter.
|
| 119 |
+
a : array_like
|
| 120 |
+
Denominator of a linear filter.
|
| 121 |
+
worN : {None, int, array_like}, optional
|
| 122 |
+
If None, then compute at 200 frequencies around the interesting parts
|
| 123 |
+
of the response curve (determined by pole-zero locations). If a single
|
| 124 |
+
integer, then compute at that many frequencies. Otherwise, compute the
|
| 125 |
+
response at the angular frequencies (e.g., rad/s) given in `worN`.
|
| 126 |
+
plot : callable, optional
|
| 127 |
+
A callable that takes two arguments. If given, the return parameters
|
| 128 |
+
`w` and `h` are passed to plot. Useful for plotting the frequency
|
| 129 |
+
response inside `freqs`.
|
| 130 |
+
|
| 131 |
+
Returns
|
| 132 |
+
-------
|
| 133 |
+
w : ndarray
|
| 134 |
+
The angular frequencies at which `h` was computed.
|
| 135 |
+
h : ndarray
|
| 136 |
+
The frequency response.
|
| 137 |
+
|
| 138 |
+
See Also
|
| 139 |
+
--------
|
| 140 |
+
scipy.signal.freqs
|
| 141 |
+
freqz : Compute the frequency response of a digital filter.
|
| 142 |
+
|
| 143 |
+
"""
|
| 144 |
+
if worN is None:
|
| 145 |
+
# For backwards compatibility
|
| 146 |
+
w = findfreqs(b, a, 200)
|
| 147 |
+
|
| 148 |
+
else:
|
| 149 |
+
N, _is_int = _try_convert_to_int(worN)
|
| 150 |
+
if _is_int:
|
| 151 |
+
w = findfreqs(b, a, N)
|
| 152 |
+
else:
|
| 153 |
+
w = cupy.atleast_1d(worN)
|
| 154 |
+
|
| 155 |
+
s = 1j * w
|
| 156 |
+
h = cupy.polyval(b, s) / cupy.polyval(a, s)
|
| 157 |
+
|
| 158 |
+
if plot is not None:
|
| 159 |
+
plot(w, h)
|
| 160 |
+
|
| 161 |
+
return w, h
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def freqs_zpk(z, p, k, worN=200):
|
| 165 |
+
"""
|
| 166 |
+
Compute frequency response of analog filter.
|
| 167 |
+
|
| 168 |
+
Given the zeros `z`, poles `p`, and gain `k` of a filter, compute its
|
| 169 |
+
frequency response::
|
| 170 |
+
|
| 171 |
+
(jw-z[0]) * (jw-z[1]) * ... * (jw-z[-1])
|
| 172 |
+
H(w) = k * ----------------------------------------
|
| 173 |
+
(jw-p[0]) * (jw-p[1]) * ... * (jw-p[-1])
|
| 174 |
+
|
| 175 |
+
Parameters
|
| 176 |
+
----------
|
| 177 |
+
z : array_like
|
| 178 |
+
Zeroes of a linear filter
|
| 179 |
+
p : array_like
|
| 180 |
+
Poles of a linear filter
|
| 181 |
+
k : scalar
|
| 182 |
+
Gain of a linear filter
|
| 183 |
+
worN : {None, int, array_like}, optional
|
| 184 |
+
If None, then compute at 200 frequencies around the interesting parts
|
| 185 |
+
of the response curve (determined by pole-zero locations). If a single
|
| 186 |
+
integer, then compute at that many frequencies. Otherwise, compute the
|
| 187 |
+
response at the angular frequencies (e.g., rad/s) given in `worN`.
|
| 188 |
+
|
| 189 |
+
Returns
|
| 190 |
+
-------
|
| 191 |
+
w : ndarray
|
| 192 |
+
The angular frequencies at which `h` was computed.
|
| 193 |
+
h : ndarray
|
| 194 |
+
The frequency response.
|
| 195 |
+
|
| 196 |
+
See Also
|
| 197 |
+
--------
|
| 198 |
+
scipy.signal.freqs_zpk
|
| 199 |
+
|
| 200 |
+
"""
|
| 201 |
+
k = cupy.asarray(k)
|
| 202 |
+
if k.size > 1:
|
| 203 |
+
raise ValueError('k must be a single scalar gain')
|
| 204 |
+
|
| 205 |
+
if worN is None:
|
| 206 |
+
# For backwards compatibility
|
| 207 |
+
w = findfreqs(z, p, 200, kind='zp')
|
| 208 |
+
else:
|
| 209 |
+
N, _is_int = _try_convert_to_int(worN)
|
| 210 |
+
if _is_int:
|
| 211 |
+
w = findfreqs(z, p, worN, kind='zp')
|
| 212 |
+
else:
|
| 213 |
+
w = worN
|
| 214 |
+
|
| 215 |
+
w = cupy.atleast_1d(w)
|
| 216 |
+
s = 1j * w
|
| 217 |
+
num = npp_polyvalfromroots(s, z)
|
| 218 |
+
den = npp_polyvalfromroots(s, p)
|
| 219 |
+
h = k * num/den
|
| 220 |
+
return w, h
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def _is_int_type(x):
|
| 224 |
+
"""
|
| 225 |
+
Check if input is of a scalar integer type (so ``5`` and ``array(5)`` will
|
| 226 |
+
pass, while ``5.0`` and ``array([5])`` will fail.
|
| 227 |
+
"""
|
| 228 |
+
if cupy.ndim(x) != 0:
|
| 229 |
+
# Older versions of NumPy did not raise for np.array([1]).__index__()
|
| 230 |
+
# This is safe to remove when support for those versions is dropped
|
| 231 |
+
return False
|
| 232 |
+
try:
|
| 233 |
+
operator.index(x)
|
| 234 |
+
except TypeError:
|
| 235 |
+
return False
|
| 236 |
+
else:
|
| 237 |
+
return True
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def group_delay(system, w=512, whole=False, fs=2 * cupy.pi):
|
| 241 |
+
r"""Compute the group delay of a digital filter.
|
| 242 |
+
|
| 243 |
+
The group delay measures by how many samples amplitude envelopes of
|
| 244 |
+
various spectral components of a signal are delayed by a filter.
|
| 245 |
+
It is formally defined as the derivative of continuous (unwrapped) phase::
|
| 246 |
+
|
| 247 |
+
d jw
|
| 248 |
+
D(w) = - -- arg H(e)
|
| 249 |
+
dw
|
| 250 |
+
|
| 251 |
+
Parameters
|
| 252 |
+
----------
|
| 253 |
+
system : tuple of array_like (b, a)
|
| 254 |
+
Numerator and denominator coefficients of a filter transfer function.
|
| 255 |
+
w : {None, int, array_like}, optional
|
| 256 |
+
If a single integer, then compute at that many frequencies (default is
|
| 257 |
+
N=512).
|
| 258 |
+
|
| 259 |
+
If an array_like, compute the delay at the frequencies given. These
|
| 260 |
+
are in the same units as `fs`.
|
| 261 |
+
whole : bool, optional
|
| 262 |
+
Normally, frequencies are computed from 0 to the Nyquist frequency,
|
| 263 |
+
fs/2 (upper-half of unit-circle). If `whole` is True, compute
|
| 264 |
+
frequencies from 0 to fs. Ignored if w is array_like.
|
| 265 |
+
fs : float, optional
|
| 266 |
+
The sampling frequency of the digital system. Defaults to 2*pi
|
| 267 |
+
radians/sample (so w is from 0 to pi).
|
| 268 |
+
|
| 269 |
+
Returns
|
| 270 |
+
-------
|
| 271 |
+
w : ndarray
|
| 272 |
+
The frequencies at which group delay was computed, in the same units
|
| 273 |
+
as `fs`. By default, `w` is normalized to the range [0, pi)
|
| 274 |
+
(radians/sample).
|
| 275 |
+
gd : ndarray
|
| 276 |
+
The group delay.
|
| 277 |
+
|
| 278 |
+
See Also
|
| 279 |
+
--------
|
| 280 |
+
freqz : Frequency response of a digital filter
|
| 281 |
+
|
| 282 |
+
Notes
|
| 283 |
+
-----
|
| 284 |
+
The similar function in MATLAB is called `grpdelay`.
|
| 285 |
+
|
| 286 |
+
If the transfer function :math:`H(z)` has zeros or poles on the unit
|
| 287 |
+
circle, the group delay at corresponding frequencies is undefined.
|
| 288 |
+
When such a case arises the warning is raised and the group delay
|
| 289 |
+
is set to 0 at those frequencies.
|
| 290 |
+
|
| 291 |
+
For the details of numerical computation of the group delay refer to [1]_.
|
| 292 |
+
|
| 293 |
+
References
|
| 294 |
+
----------
|
| 295 |
+
.. [1] Richard G. Lyons, "Understanding Digital Signal Processing,
|
| 296 |
+
3rd edition", p. 830.
|
| 297 |
+
|
| 298 |
+
"""
|
| 299 |
+
if w is None:
|
| 300 |
+
# For backwards compatibility
|
| 301 |
+
w = 512
|
| 302 |
+
|
| 303 |
+
if _is_int_type(w):
|
| 304 |
+
if whole:
|
| 305 |
+
w = cupy.linspace(0, 2 * cupy.pi, w, endpoint=False)
|
| 306 |
+
else:
|
| 307 |
+
w = cupy.linspace(0, cupy.pi, w, endpoint=False)
|
| 308 |
+
else:
|
| 309 |
+
w = cupy.atleast_1d(w)
|
| 310 |
+
w = 2 * cupy.pi * w / fs
|
| 311 |
+
|
| 312 |
+
b, a = map(cupy.atleast_1d, system)
|
| 313 |
+
c = cupy.convolve(b, a[::-1])
|
| 314 |
+
cr = c * cupy.arange(c.size)
|
| 315 |
+
z = cupy.exp(-1j * w)
|
| 316 |
+
num = cupy.polyval(cr[::-1], z)
|
| 317 |
+
den = cupy.polyval(c[::-1], z)
|
| 318 |
+
gd = cupy.real(num / den) - a.size + 1
|
| 319 |
+
singular = ~cupy.isfinite(gd)
|
| 320 |
+
gd[singular] = 0
|
| 321 |
+
|
| 322 |
+
w = w * fs / (2 * cupy.pi)
|
| 323 |
+
return w, gd
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def freqz(b, a=1, worN=512, whole=False, plot=None, fs=2*pi,
|
| 327 |
+
include_nyquist=False):
|
| 328 |
+
"""
|
| 329 |
+
Compute the frequency response of a digital filter.
|
| 330 |
+
|
| 331 |
+
Given the M-order numerator `b` and N-order denominator `a` of a digital
|
| 332 |
+
filter, compute its frequency response::
|
| 333 |
+
|
| 334 |
+
jw -jw -jwM
|
| 335 |
+
jw B(e ) b[0] + b[1]e + ... + b[M]e
|
| 336 |
+
H(e ) = ------ = -----------------------------------
|
| 337 |
+
jw -jw -jwN
|
| 338 |
+
A(e ) a[0] + a[1]e + ... + a[N]e
|
| 339 |
+
|
| 340 |
+
Parameters
|
| 341 |
+
----------
|
| 342 |
+
b : array_like
|
| 343 |
+
Numerator of a linear filter. If `b` has dimension greater than 1,
|
| 344 |
+
it is assumed that the coefficients are stored in the first dimension,
|
| 345 |
+
and ``b.shape[1:]``, ``a.shape[1:]``, and the shape of the frequencies
|
| 346 |
+
array must be compatible for broadcasting.
|
| 347 |
+
a : array_like
|
| 348 |
+
Denominator of a linear filter. If `b` has dimension greater than 1,
|
| 349 |
+
it is assumed that the coefficients are stored in the first dimension,
|
| 350 |
+
and ``b.shape[1:]``, ``a.shape[1:]``, and the shape of the frequencies
|
| 351 |
+
array must be compatible for broadcasting.
|
| 352 |
+
worN : {None, int, array_like}, optional
|
| 353 |
+
If a single integer, then compute at that many frequencies (default is
|
| 354 |
+
N=512). This is a convenient alternative to::
|
| 355 |
+
|
| 356 |
+
cupy.linspace(0, fs if whole else fs/2, N,
|
| 357 |
+
endpoint=include_nyquist)
|
| 358 |
+
|
| 359 |
+
Using a number that is fast for FFT computations can result in
|
| 360 |
+
faster computations (see Notes).
|
| 361 |
+
|
| 362 |
+
If an array_like, compute the response at the frequencies given.
|
| 363 |
+
These are in the same units as `fs`.
|
| 364 |
+
whole : bool, optional
|
| 365 |
+
Normally, frequencies are computed from 0 to the Nyquist frequency,
|
| 366 |
+
fs/2 (upper-half of unit-circle). If `whole` is True, compute
|
| 367 |
+
frequencies from 0 to fs. Ignored if worN is array_like.
|
| 368 |
+
plot : callable
|
| 369 |
+
A callable that takes two arguments. If given, the return parameters
|
| 370 |
+
`w` and `h` are passed to plot. Useful for plotting the frequency
|
| 371 |
+
response inside `freqz`.
|
| 372 |
+
fs : float, optional
|
| 373 |
+
The sampling frequency of the digital system. Defaults to 2*pi
|
| 374 |
+
radians/sample (so w is from 0 to pi).
|
| 375 |
+
include_nyquist : bool, optional
|
| 376 |
+
If `whole` is False and `worN` is an integer, setting `include_nyquist`
|
| 377 |
+
to True will include the last frequency (Nyquist frequency) and is
|
| 378 |
+
otherwise ignored.
|
| 379 |
+
|
| 380 |
+
Returns
|
| 381 |
+
-------
|
| 382 |
+
w : ndarray
|
| 383 |
+
The frequencies at which `h` was computed, in the same units as `fs`.
|
| 384 |
+
By default, `w` is normalized to the range [0, pi) (radians/sample).
|
| 385 |
+
h : ndarray
|
| 386 |
+
The frequency response, as complex numbers.
|
| 387 |
+
|
| 388 |
+
See Also
|
| 389 |
+
--------
|
| 390 |
+
freqz_zpk
|
| 391 |
+
sosfreqz
|
| 392 |
+
scipy.signal.freqz
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
Notes
|
| 396 |
+
-----
|
| 397 |
+
Using Matplotlib's :func:`matplotlib.pyplot.plot` function as the callable
|
| 398 |
+
for `plot` produces unexpected results, as this plots the real part of the
|
| 399 |
+
complex transfer function, not the magnitude.
|
| 400 |
+
Try ``lambda w, h: plot(w, cupy.abs(h))``.
|
| 401 |
+
|
| 402 |
+
A direct computation via (R)FFT is used to compute the frequency response
|
| 403 |
+
when the following conditions are met:
|
| 404 |
+
|
| 405 |
+
1. An integer value is given for `worN`.
|
| 406 |
+
2. `worN` is fast to compute via FFT (i.e.,
|
| 407 |
+
`next_fast_len(worN) <scipy.fft.next_fast_len>` equals `worN`).
|
| 408 |
+
3. The denominator coefficients are a single value (``a.shape[0] == 1``).
|
| 409 |
+
4. `worN` is at least as long as the numerator coefficients
|
| 410 |
+
(``worN >= b.shape[0]``).
|
| 411 |
+
5. If ``b.ndim > 1``, then ``b.shape[-1] == 1``.
|
| 412 |
+
|
| 413 |
+
For long FIR filters, the FFT approach can have lower error and be much
|
| 414 |
+
faster than the equivalent direct polynomial calculation.
|
| 415 |
+
"""
|
| 416 |
+
b = cupy.atleast_1d(b)
|
| 417 |
+
a = cupy.atleast_1d(a)
|
| 418 |
+
|
| 419 |
+
if worN is None:
|
| 420 |
+
# For backwards compatibility
|
| 421 |
+
worN = 512
|
| 422 |
+
|
| 423 |
+
h = None
|
| 424 |
+
|
| 425 |
+
N, _is_int = _try_convert_to_int(worN)
|
| 426 |
+
if _is_int:
|
| 427 |
+
if N < 0:
|
| 428 |
+
raise ValueError(f'worN must be nonnegative, got {N}')
|
| 429 |
+
lastpoint = 2 * pi if whole else pi
|
| 430 |
+
|
| 431 |
+
# if include_nyquist is true and whole is false, w should
|
| 432 |
+
# include end point
|
| 433 |
+
w = cupy.linspace(
|
| 434 |
+
0, lastpoint, N, endpoint=include_nyquist and not whole)
|
| 435 |
+
|
| 436 |
+
use_fft = (a.size == 1 and
|
| 437 |
+
N >= b.shape[0] and
|
| 438 |
+
sp_fft.next_fast_len(N) == N and
|
| 439 |
+
(b.ndim == 1 or (b.shape[-1] == 1))
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
if use_fft:
|
| 443 |
+
# if N is fast, 2 * N will be fast, too, so no need to check
|
| 444 |
+
n_fft = N if whole else N * 2
|
| 445 |
+
if cupy.isrealobj(b) and cupy.isrealobj(a):
|
| 446 |
+
fft_func = sp_fft.rfft
|
| 447 |
+
else:
|
| 448 |
+
fft_func = sp_fft.fft
|
| 449 |
+
|
| 450 |
+
h = fft_func(b, n=n_fft, axis=0)[:N]
|
| 451 |
+
h /= a
|
| 452 |
+
if fft_func is sp_fft.rfft and whole:
|
| 453 |
+
# exclude DC and maybe Nyquist (no need to use axis_reverse
|
| 454 |
+
# here because we can build reversal with the truncation)
|
| 455 |
+
stop = -1 if n_fft % 2 == 1 else -2
|
| 456 |
+
h_flip = slice(stop, 0, -1)
|
| 457 |
+
h = cupy.concatenate((h, h[h_flip].conj()))
|
| 458 |
+
if b.ndim > 1:
|
| 459 |
+
# Last axis of h has length 1, so drop it.
|
| 460 |
+
h = h[..., 0]
|
| 461 |
+
# Move the first axis of h to the end.
|
| 462 |
+
h = cupy.moveaxis(h, 0, -1)
|
| 463 |
+
else:
|
| 464 |
+
w = cupy.atleast_1d(worN)
|
| 465 |
+
w = 2 * pi * w / fs
|
| 466 |
+
|
| 467 |
+
if h is None: # still need to compute using freqs w
|
| 468 |
+
zm1 = cupy.exp(-1j * w)
|
| 469 |
+
h = (npp_polyval(zm1, b, tensor=False) /
|
| 470 |
+
npp_polyval(zm1, a, tensor=False))
|
| 471 |
+
|
| 472 |
+
w = w * fs / (2 * pi)
|
| 473 |
+
|
| 474 |
+
if plot is not None:
|
| 475 |
+
plot(w, h)
|
| 476 |
+
|
| 477 |
+
return w, h
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
def freqz_zpk(z, p, k, worN=512, whole=False, fs=2*pi):
|
| 481 |
+
r"""
|
| 482 |
+
Compute the frequency response of a digital filter in ZPK form.
|
| 483 |
+
|
| 484 |
+
Given the Zeros, Poles and Gain of a digital filter, compute its frequency
|
| 485 |
+
response:
|
| 486 |
+
|
| 487 |
+
:math:`H(z)=k \prod_i (z - Z[i]) / \prod_j (z - P[j])`
|
| 488 |
+
|
| 489 |
+
where :math:`k` is the `gain`, :math:`Z` are the `zeros` and :math:`P` are
|
| 490 |
+
the `poles`.
|
| 491 |
+
|
| 492 |
+
Parameters
|
| 493 |
+
----------
|
| 494 |
+
z : array_like
|
| 495 |
+
Zeroes of a linear filter
|
| 496 |
+
p : array_like
|
| 497 |
+
Poles of a linear filter
|
| 498 |
+
k : scalar
|
| 499 |
+
Gain of a linear filter
|
| 500 |
+
worN : {None, int, array_like}, optional
|
| 501 |
+
If a single integer, then compute at that many frequencies (default is
|
| 502 |
+
N=512).
|
| 503 |
+
|
| 504 |
+
If an array_like, compute the response at the frequencies given.
|
| 505 |
+
These are in the same units as `fs`.
|
| 506 |
+
whole : bool, optional
|
| 507 |
+
Normally, frequencies are computed from 0 to the Nyquist frequency,
|
| 508 |
+
fs/2 (upper-half of unit-circle). If `whole` is True, compute
|
| 509 |
+
frequencies from 0 to fs. Ignored if w is array_like.
|
| 510 |
+
fs : float, optional
|
| 511 |
+
The sampling frequency of the digital system. Defaults to 2*pi
|
| 512 |
+
radians/sample (so w is from 0 to pi).
|
| 513 |
+
|
| 514 |
+
Returns
|
| 515 |
+
-------
|
| 516 |
+
w : ndarray
|
| 517 |
+
The frequencies at which `h` was computed, in the same units as `fs`.
|
| 518 |
+
By default, `w` is normalized to the range [0, pi) (radians/sample).
|
| 519 |
+
h : ndarray
|
| 520 |
+
The frequency response, as complex numbers.
|
| 521 |
+
|
| 522 |
+
See Also
|
| 523 |
+
--------
|
| 524 |
+
freqs : Compute the frequency response of an analog filter in TF form
|
| 525 |
+
freqs_zpk : Compute the frequency response of an analog filter in ZPK form
|
| 526 |
+
freqz : Compute the frequency response of a digital filter in TF form
|
| 527 |
+
scipy.signal.freqz_zpk
|
| 528 |
+
|
| 529 |
+
"""
|
| 530 |
+
z, p = map(cupy.atleast_1d, (z, p))
|
| 531 |
+
|
| 532 |
+
if whole:
|
| 533 |
+
lastpoint = 2 * pi
|
| 534 |
+
else:
|
| 535 |
+
lastpoint = pi
|
| 536 |
+
|
| 537 |
+
if worN is None:
|
| 538 |
+
# For backwards compatibility
|
| 539 |
+
w = cupy.linspace(0, lastpoint, 512, endpoint=False)
|
| 540 |
+
else:
|
| 541 |
+
N, _is_int = _try_convert_to_int(worN)
|
| 542 |
+
if _is_int:
|
| 543 |
+
w = cupy.linspace(0, lastpoint, N, endpoint=False)
|
| 544 |
+
else:
|
| 545 |
+
w = cupy.atleast_1d(worN)
|
| 546 |
+
w = 2 * pi * w / fs
|
| 547 |
+
|
| 548 |
+
zm1 = cupy.exp(1j * w)
|
| 549 |
+
h = k * npp_polyvalfromroots(zm1, z) / npp_polyvalfromroots(zm1, p)
|
| 550 |
+
|
| 551 |
+
w = w * fs / (2 * pi)
|
| 552 |
+
|
| 553 |
+
return w, h
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def _validate_sos(sos):
|
| 557 |
+
"""Helper to validate a SOS input"""
|
| 558 |
+
sos = cupy.atleast_2d(sos)
|
| 559 |
+
if sos.ndim != 2:
|
| 560 |
+
raise ValueError('sos array must be 2D')
|
| 561 |
+
n_sections, m = sos.shape
|
| 562 |
+
if m != 6:
|
| 563 |
+
raise ValueError('sos array must be shape (n_sections, 6)')
|
| 564 |
+
if ((sos[:, 3] - 1) > 1e-15).any():
|
| 565 |
+
raise ValueError('sos[:, 3] should be all ones')
|
| 566 |
+
return sos, n_sections
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def sosfreqz(sos, worN=512, whole=False, fs=2*pi):
|
| 570 |
+
r"""
|
| 571 |
+
Compute the frequency response of a digital filter in SOS format.
|
| 572 |
+
|
| 573 |
+
Given `sos`, an array with shape (n, 6) of second order sections of
|
| 574 |
+
a digital filter, compute the frequency response of the system function::
|
| 575 |
+
|
| 576 |
+
B0(z) B1(z) B{n-1}(z)
|
| 577 |
+
H(z) = ----- * ----- * ... * ---------
|
| 578 |
+
A0(z) A1(z) A{n-1}(z)
|
| 579 |
+
|
| 580 |
+
for z = exp(omega*1j), where B{k}(z) and A{k}(z) are numerator and
|
| 581 |
+
denominator of the transfer function of the k-th second order section.
|
| 582 |
+
|
| 583 |
+
Parameters
|
| 584 |
+
----------
|
| 585 |
+
sos : array_like
|
| 586 |
+
Array of second-order filter coefficients, must have shape
|
| 587 |
+
``(n_sections, 6)``. Each row corresponds to a second-order
|
| 588 |
+
section, with the first three columns providing the numerator
|
| 589 |
+
coefficients and the last three providing the denominator
|
| 590 |
+
coefficients.
|
| 591 |
+
worN : {None, int, array_like}, optional
|
| 592 |
+
If a single integer, then compute at that many frequencies (default is
|
| 593 |
+
N=512). Using a number that is fast for FFT computations can result
|
| 594 |
+
in faster computations (see Notes of `freqz`).
|
| 595 |
+
|
| 596 |
+
If an array_like, compute the response at the frequencies given (must
|
| 597 |
+
be 1-D). These are in the same units as `fs`.
|
| 598 |
+
whole : bool, optional
|
| 599 |
+
Normally, frequencies are computed from 0 to the Nyquist frequency,
|
| 600 |
+
fs/2 (upper-half of unit-circle). If `whole` is True, compute
|
| 601 |
+
frequencies from 0 to fs.
|
| 602 |
+
fs : float, optional
|
| 603 |
+
The sampling frequency of the digital system. Defaults to 2*pi
|
| 604 |
+
radians/sample (so w is from 0 to pi).
|
| 605 |
+
|
| 606 |
+
.. versionadded:: 1.2.0
|
| 607 |
+
|
| 608 |
+
Returns
|
| 609 |
+
-------
|
| 610 |
+
w : ndarray
|
| 611 |
+
The frequencies at which `h` was computed, in the same units as `fs`.
|
| 612 |
+
By default, `w` is normalized to the range [0, pi) (radians/sample).
|
| 613 |
+
h : ndarray
|
| 614 |
+
The frequency response, as complex numbers.
|
| 615 |
+
|
| 616 |
+
See Also
|
| 617 |
+
--------
|
| 618 |
+
freqz, sosfilt
|
| 619 |
+
scipy.signal.sosfreqz
|
| 620 |
+
"""
|
| 621 |
+
sos, n_sections = _validate_sos(sos)
|
| 622 |
+
if n_sections == 0:
|
| 623 |
+
raise ValueError('Cannot compute frequencies with no sections')
|
| 624 |
+
h = 1.
|
| 625 |
+
for row in sos:
|
| 626 |
+
w, rowh = freqz(row[:3], row[3:], worN=worN, whole=whole, fs=fs)
|
| 627 |
+
h *= rowh
|
| 628 |
+
return w, h
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def _hz_to_erb(hz):
|
| 632 |
+
"""
|
| 633 |
+
Utility for converting from frequency (Hz) to the
|
| 634 |
+
Equivalent Rectangular Bandwidth (ERB) scale
|
| 635 |
+
ERB = frequency / EarQ + minBW
|
| 636 |
+
"""
|
| 637 |
+
EarQ = 9.26449
|
| 638 |
+
minBW = 24.7
|
| 639 |
+
return hz / EarQ + minBW
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
@jit.rawkernel()
|
| 643 |
+
def _gammatone_iir_kernel(fs, freq, b, a):
|
| 644 |
+
tid = jit.blockIdx.x * jit.blockDim.x + jit.threadIdx.x
|
| 645 |
+
|
| 646 |
+
EarQ = 9.26449
|
| 647 |
+
minBW = 24.7
|
| 648 |
+
erb = freq / EarQ + minBW
|
| 649 |
+
|
| 650 |
+
T = 1./fs
|
| 651 |
+
bw = 2 * cupy.pi * 1.019 * erb
|
| 652 |
+
fr = 2 * freq * cupy.pi * T
|
| 653 |
+
bwT = bw * T
|
| 654 |
+
|
| 655 |
+
# Calculate the gain to normalize the volume at the center frequency
|
| 656 |
+
g1 = -2 * cupy.exp(2j * fr) * T
|
| 657 |
+
g2 = 2 * cupy.exp(-(bwT) + 1j * fr) * T
|
| 658 |
+
g3 = cupy.sqrt(3 + 2 ** (3 / 2)) * cupy.sin(fr)
|
| 659 |
+
g4 = cupy.sqrt(3 - 2 ** (3 / 2)) * cupy.sin(fr)
|
| 660 |
+
g5 = cupy.exp(2j * fr)
|
| 661 |
+
|
| 662 |
+
g = g1 + g2 * (cupy.cos(fr) - g4)
|
| 663 |
+
g *= (g1 + g2 * (cupy.cos(fr) + g4))
|
| 664 |
+
g *= (g1 + g2 * (cupy.cos(fr) - g3))
|
| 665 |
+
g *= (g1 + g2 * (cupy.cos(fr) + g3))
|
| 666 |
+
g /= ((-2 / cupy.exp(2 * bwT) - 2 * g5 + 2 * (1 + g5) /
|
| 667 |
+
cupy.exp(bwT)) ** 4)
|
| 668 |
+
g_act = cupy.abs(g)
|
| 669 |
+
|
| 670 |
+
# Calculate the numerator coefficients
|
| 671 |
+
if tid == 0:
|
| 672 |
+
b[tid] = (T ** 4) / g_act
|
| 673 |
+
a[tid] = 1
|
| 674 |
+
elif tid == 1:
|
| 675 |
+
b[tid] = -4 * T ** 4 * cupy.cos(fr) / cupy.exp(bw * T) / g_act
|
| 676 |
+
a[tid] = -8 * cupy.cos(fr) / cupy.exp(bw * T)
|
| 677 |
+
elif tid == 2:
|
| 678 |
+
b[tid] = 6 * T ** 4 * cupy.cos(2 * fr) / cupy.exp(2 * bw * T) / g_act
|
| 679 |
+
a[tid] = 4 * (4 + 3 * cupy.cos(2 * fr)) / cupy.exp(2 * bw * T)
|
| 680 |
+
elif tid == 3:
|
| 681 |
+
b[tid] = -4 * T ** 4 * cupy.cos(3 * fr) / cupy.exp(3 * bw * T) / g_act
|
| 682 |
+
a[tid] = -8 * (6 * cupy.cos(fr) + cupy.cos(3 * fr))
|
| 683 |
+
a[tid] /= cupy.exp(3 * bw * T)
|
| 684 |
+
elif tid == 4:
|
| 685 |
+
b[tid] = T ** 4 * cupy.cos(4 * fr) / cupy.exp(4 * bw * T) / g_act
|
| 686 |
+
a[tid] = 2 * (18 + 16 * cupy.cos(2 * fr) + cupy.cos(4 * fr))
|
| 687 |
+
a[tid] /= cupy.exp(4 * bw * T)
|
| 688 |
+
elif tid == 5:
|
| 689 |
+
a[tid] = -8 * (6 * cupy.cos(fr) + cupy.cos(3 * fr))
|
| 690 |
+
a[tid] /= cupy.exp(5 * bw * T)
|
| 691 |
+
elif tid == 6:
|
| 692 |
+
a[tid] = 4 * (4 + 3 * cupy.cos(2 * fr)) / cupy.exp(6 * bw * T)
|
| 693 |
+
elif tid == 7:
|
| 694 |
+
a[tid] = -8 * cupy.cos(fr) / cupy.exp(7 * bw * T)
|
| 695 |
+
elif tid == 8:
|
| 696 |
+
a[tid] = cupy.exp(-8 * bw * T)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
def gammatone(freq, ftype, order=None, numtaps=None, fs=None):
|
| 700 |
+
"""
|
| 701 |
+
Gammatone filter design.
|
| 702 |
+
|
| 703 |
+
This function computes the coefficients of an FIR or IIR gammatone
|
| 704 |
+
digital filter [1]_.
|
| 705 |
+
|
| 706 |
+
Parameters
|
| 707 |
+
----------
|
| 708 |
+
freq : float
|
| 709 |
+
Center frequency of the filter (expressed in the same units
|
| 710 |
+
as `fs`).
|
| 711 |
+
ftype : {'fir', 'iir'}
|
| 712 |
+
The type of filter the function generates. If 'fir', the function
|
| 713 |
+
will generate an Nth order FIR gammatone filter. If 'iir', the
|
| 714 |
+
function will generate an 8th order digital IIR filter, modeled as
|
| 715 |
+
as 4th order gammatone filter.
|
| 716 |
+
order : int, optional
|
| 717 |
+
The order of the filter. Only used when ``ftype='fir'``.
|
| 718 |
+
Default is 4 to model the human auditory system. Must be between
|
| 719 |
+
0 and 24.
|
| 720 |
+
numtaps : int, optional
|
| 721 |
+
Length of the filter. Only used when ``ftype='fir'``.
|
| 722 |
+
Default is ``fs*0.015`` if `fs` is greater than 1000,
|
| 723 |
+
15 if `fs` is less than or equal to 1000.
|
| 724 |
+
fs : float, optional
|
| 725 |
+
The sampling frequency of the signal. `freq` must be between
|
| 726 |
+
0 and ``fs/2``. Default is 2.
|
| 727 |
+
|
| 728 |
+
Returns
|
| 729 |
+
-------
|
| 730 |
+
b, a : ndarray, ndarray
|
| 731 |
+
Numerator (``b``) and denominator (``a``) polynomials of the filter.
|
| 732 |
+
|
| 733 |
+
Raises
|
| 734 |
+
------
|
| 735 |
+
ValueError
|
| 736 |
+
If `freq` is less than or equal to 0 or greater than or equal to
|
| 737 |
+
``fs/2``, if `ftype` is not 'fir' or 'iir', if `order` is less than
|
| 738 |
+
or equal to 0 or greater than 24 when ``ftype='fir'``
|
| 739 |
+
|
| 740 |
+
See Also
|
| 741 |
+
--------
|
| 742 |
+
firwin
|
| 743 |
+
iirfilter
|
| 744 |
+
|
| 745 |
+
References
|
| 746 |
+
----------
|
| 747 |
+
.. [1] Slaney, Malcolm, "An Efficient Implementation of the
|
| 748 |
+
Patterson-Holdsworth Auditory Filter Bank", Apple Computer
|
| 749 |
+
Technical Report 35, 1993, pp.3-8, 34-39.
|
| 750 |
+
"""
|
| 751 |
+
# Converts freq to float
|
| 752 |
+
freq = float(freq)
|
| 753 |
+
|
| 754 |
+
# Set sampling rate if not passed
|
| 755 |
+
if fs is None:
|
| 756 |
+
fs = 2
|
| 757 |
+
fs = float(fs)
|
| 758 |
+
|
| 759 |
+
# Check for invalid cutoff frequency or filter type
|
| 760 |
+
ftype = ftype.lower()
|
| 761 |
+
filter_types = ['fir', 'iir']
|
| 762 |
+
if not 0 < freq < fs / 2:
|
| 763 |
+
raise ValueError("The frequency must be between 0 and {}"
|
| 764 |
+
" (nyquist), but given {}.".format(fs / 2, freq))
|
| 765 |
+
if ftype not in filter_types:
|
| 766 |
+
raise ValueError('ftype must be either fir or iir.')
|
| 767 |
+
|
| 768 |
+
# Calculate FIR gammatone filter
|
| 769 |
+
if ftype == 'fir':
|
| 770 |
+
# Set order and numtaps if not passed
|
| 771 |
+
if order is None:
|
| 772 |
+
order = 4
|
| 773 |
+
order = operator.index(order)
|
| 774 |
+
|
| 775 |
+
if numtaps is None:
|
| 776 |
+
numtaps = max(int(fs * 0.015), 15)
|
| 777 |
+
numtaps = operator.index(numtaps)
|
| 778 |
+
|
| 779 |
+
# Check for invalid order
|
| 780 |
+
if not 0 < order <= 24:
|
| 781 |
+
raise ValueError("Invalid order: order must be > 0 and <= 24.")
|
| 782 |
+
|
| 783 |
+
# Gammatone impulse response settings
|
| 784 |
+
t = cupy.arange(numtaps) / fs
|
| 785 |
+
bw = 1.019 * _hz_to_erb(freq)
|
| 786 |
+
|
| 787 |
+
# Calculate the FIR gammatone filter
|
| 788 |
+
b = (t ** (order - 1)) * cupy.exp(-2 * cupy.pi * bw * t)
|
| 789 |
+
b *= cupy.cos(2 * cupy.pi * freq * t)
|
| 790 |
+
|
| 791 |
+
# Scale the FIR filter so the frequency response is 1 at cutoff
|
| 792 |
+
scale_factor = 2 * (2 * cupy.pi * bw) ** (order)
|
| 793 |
+
scale_factor /= float_factorial(order - 1)
|
| 794 |
+
scale_factor /= fs
|
| 795 |
+
b *= scale_factor
|
| 796 |
+
a = [1.0]
|
| 797 |
+
|
| 798 |
+
# Calculate IIR gammatone filter
|
| 799 |
+
elif ftype == 'iir':
|
| 800 |
+
# Raise warning if order and/or numtaps is passed
|
| 801 |
+
if order is not None:
|
| 802 |
+
warnings.warn('order is not used for IIR gammatone filter.')
|
| 803 |
+
if numtaps is not None:
|
| 804 |
+
warnings.warn('numtaps is not used for IIR gammatone filter.')
|
| 805 |
+
|
| 806 |
+
# Create empty filter coefficient lists
|
| 807 |
+
b = cupy.empty(5)
|
| 808 |
+
a = cupy.empty(9)
|
| 809 |
+
_gammatone_iir_kernel((9,), (1,), (fs, freq, b, a))
|
| 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Functions for FIR filter design."""
|
| 2 |
+
import math
|
| 3 |
+
|
| 4 |
+
from cupy.fft import fft, ifft
|
| 5 |
+
from cupy.linalg import solve, lstsq, LinAlgError
|
| 6 |
+
from cupyx.scipy.linalg import toeplitz, hankel
|
| 7 |
+
import cupyx
|
| 8 |
+
from cupyx.scipy.signal.windows import get_window
|
| 9 |
+
|
| 10 |
+
import cupy
|
| 11 |
+
import numpy
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = ["firls", "minimum_phase"]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def kaiser_beta(a):
|
| 18 |
+
"""Compute the Kaiser parameter `beta`, given the attenuation `a`.
|
| 19 |
+
|
| 20 |
+
Parameters
|
| 21 |
+
----------
|
| 22 |
+
a : float
|
| 23 |
+
The desired attenuation in the stopband and maximum ripple in
|
| 24 |
+
the passband, in dB. This should be a *positive* number.
|
| 25 |
+
|
| 26 |
+
Returns
|
| 27 |
+
-------
|
| 28 |
+
beta : float
|
| 29 |
+
The `beta` parameter to be used in the formula for a Kaiser window.
|
| 30 |
+
|
| 31 |
+
References
|
| 32 |
+
----------
|
| 33 |
+
Oppenheim, Schafer, "Discrete-Time Signal Processing", p.475-476.
|
| 34 |
+
|
| 35 |
+
See Also
|
| 36 |
+
--------
|
| 37 |
+
scipy.signal.kaiser_beta
|
| 38 |
+
|
| 39 |
+
"""
|
| 40 |
+
if a > 50:
|
| 41 |
+
beta = 0.1102 * (a - 8.7)
|
| 42 |
+
elif a > 21:
|
| 43 |
+
beta = 0.5842 * (a - 21) ** 0.4 + 0.07886 * (a - 21)
|
| 44 |
+
else:
|
| 45 |
+
beta = 0.0
|
| 46 |
+
return beta
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def kaiser_atten(numtaps, width):
|
| 50 |
+
"""Compute the attenuation of a Kaiser FIR filter.
|
| 51 |
+
|
| 52 |
+
Given the number of taps `N` and the transition width `width`, compute the
|
| 53 |
+
attenuation `a` in dB, given by Kaiser's formula:
|
| 54 |
+
|
| 55 |
+
a = 2.285 * (N - 1) * pi * width + 7.95
|
| 56 |
+
|
| 57 |
+
Parameters
|
| 58 |
+
----------
|
| 59 |
+
numtaps : int
|
| 60 |
+
The number of taps in the FIR filter.
|
| 61 |
+
width : float
|
| 62 |
+
The desired width of the transition region between passband and
|
| 63 |
+
stopband (or, in general, at any discontinuity) for the filter,
|
| 64 |
+
expressed as a fraction of the Nyquist frequency.
|
| 65 |
+
|
| 66 |
+
Returns
|
| 67 |
+
-------
|
| 68 |
+
a : float
|
| 69 |
+
The attenuation of the ripple, in dB.
|
| 70 |
+
|
| 71 |
+
See Also
|
| 72 |
+
--------
|
| 73 |
+
scipy.signal.kaiser_atten
|
| 74 |
+
"""
|
| 75 |
+
a = 2.285 * (numtaps - 1) * cupy.pi * width + 7.95
|
| 76 |
+
return a
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def kaiserord(ripple, width):
|
| 80 |
+
"""
|
| 81 |
+
Determine the filter window parameters for the Kaiser window method.
|
| 82 |
+
|
| 83 |
+
The parameters returned by this function are generally used to create
|
| 84 |
+
a finite impulse response filter using the window method, with either
|
| 85 |
+
`firwin` or `firwin2`.
|
| 86 |
+
|
| 87 |
+
Parameters
|
| 88 |
+
----------
|
| 89 |
+
ripple : float
|
| 90 |
+
Upper bound for the deviation (in dB) of the magnitude of the
|
| 91 |
+
filter's frequency response from that of the desired filter (not
|
| 92 |
+
including frequencies in any transition intervals). That is, if w
|
| 93 |
+
is the frequency expressed as a fraction of the Nyquist frequency,
|
| 94 |
+
A(w) is the actual frequency response of the filter and D(w) is the
|
| 95 |
+
desired frequency response, the design requirement is that::
|
| 96 |
+
|
| 97 |
+
abs(A(w) - D(w))) < 10**(-ripple/20)
|
| 98 |
+
|
| 99 |
+
for 0 <= w <= 1 and w not in a transition interval.
|
| 100 |
+
width : float
|
| 101 |
+
Width of transition region, normalized so that 1 corresponds to pi
|
| 102 |
+
radians / sample. That is, the frequency is expressed as a fraction
|
| 103 |
+
of the Nyquist frequency.
|
| 104 |
+
|
| 105 |
+
Returns
|
| 106 |
+
-------
|
| 107 |
+
numtaps : int
|
| 108 |
+
The length of the Kaiser window.
|
| 109 |
+
beta : float
|
| 110 |
+
The beta parameter for the Kaiser window.
|
| 111 |
+
|
| 112 |
+
See Also
|
| 113 |
+
--------
|
| 114 |
+
scipy.signal.kaiserord
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
"""
|
| 118 |
+
A = abs(ripple) # in case somebody is confused as to what's meant
|
| 119 |
+
if A < 8:
|
| 120 |
+
# Formula for N is not valid in this range.
|
| 121 |
+
raise ValueError("Requested maximum ripple attenuation %f is too "
|
| 122 |
+
"small for the Kaiser formula." % A)
|
| 123 |
+
beta = kaiser_beta(A)
|
| 124 |
+
|
| 125 |
+
# Kaiser's formula (as given in Oppenheim and Schafer) is for the filter
|
| 126 |
+
# order, so we have to add 1 to get the number of taps.
|
| 127 |
+
numtaps = (A - 7.95) / 2.285 / (cupy.pi * width) + 1
|
| 128 |
+
|
| 129 |
+
return int(numpy.ceil(numtaps)), beta
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
_firwin_kernel = cupy.ElementwiseKernel(
|
| 133 |
+
"float64 win, int32 numtaps, raw float64 bands, int32 steps, bool scale",
|
| 134 |
+
"float64 h, float64 hc",
|
| 135 |
+
"""
|
| 136 |
+
const double m { static_cast<double>( i ) - alpha ?
|
| 137 |
+
static_cast<double>( i ) - alpha : 1.0e-20 };
|
| 138 |
+
|
| 139 |
+
double temp {};
|
| 140 |
+
double left {};
|
| 141 |
+
double right {};
|
| 142 |
+
|
| 143 |
+
for ( int s = 0; s < steps; s++ ) {
|
| 144 |
+
left = bands[s * 2 + 0] ? bands[s * 2 + 0] : 1.0e-20;
|
| 145 |
+
right = bands[s * 2 + 1] ? bands[s * 2 + 1] : 1.0e-20;
|
| 146 |
+
|
| 147 |
+
temp += right * ( sin( right * m * M_PI ) / ( right * m * M_PI ) );
|
| 148 |
+
temp -= left * ( sin( left * m * M_PI ) / ( left * m * M_PI ) );
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
temp *= win;
|
| 152 |
+
h = temp;
|
| 153 |
+
|
| 154 |
+
double scale_frequency {};
|
| 155 |
+
|
| 156 |
+
if ( scale ) {
|
| 157 |
+
left = bands[0];
|
| 158 |
+
right = bands[1];
|
| 159 |
+
|
| 160 |
+
if ( left == 0 ) {
|
| 161 |
+
scale_frequency = 0.0;
|
| 162 |
+
} else if ( right == 1 ) {
|
| 163 |
+
scale_frequency = 1.0;
|
| 164 |
+
} else {
|
| 165 |
+
scale_frequency = 0.5 * ( left + right );
|
| 166 |
+
}
|
| 167 |
+
double c { cos( M_PI * m * scale_frequency ) };
|
| 168 |
+
hc = temp * c;
|
| 169 |
+
}
|
| 170 |
+
""",
|
| 171 |
+
"_firwin_kernel",
|
| 172 |
+
options=("-std=c++11",),
|
| 173 |
+
loop_prep="const double alpha { 0.5 * ( numtaps - 1 ) };",
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
# Scipy <= 1.12 has a deprecated `nyq` argument (nyq = fs/2).
|
| 178 |
+
# Remove it here, to be forward-looking.
|
| 179 |
+
def firwin(
|
| 180 |
+
numtaps,
|
| 181 |
+
cutoff,
|
| 182 |
+
width=None,
|
| 183 |
+
window="hamming",
|
| 184 |
+
pass_zero=True,
|
| 185 |
+
scale=True,
|
| 186 |
+
fs=2,
|
| 187 |
+
):
|
| 188 |
+
"""
|
| 189 |
+
FIR filter design using the window method.
|
| 190 |
+
|
| 191 |
+
This function computes the coefficients of a finite impulse response
|
| 192 |
+
filter. The filter will have linear phase; it will be Type I if
|
| 193 |
+
`numtaps` is odd and Type II if `numtaps` is even.
|
| 194 |
+
|
| 195 |
+
Type II filters always have zero response at the Nyquist frequency, so a
|
| 196 |
+
ValueError exception is raised if firwin is called with `numtaps` even and
|
| 197 |
+
having a passband whose right end is at the Nyquist frequency.
|
| 198 |
+
|
| 199 |
+
Parameters
|
| 200 |
+
----------
|
| 201 |
+
numtaps : int
|
| 202 |
+
Length of the filter (number of coefficients, i.e. the filter
|
| 203 |
+
order + 1). `numtaps` must be odd if a passband includes the
|
| 204 |
+
Nyquist frequency.
|
| 205 |
+
cutoff : float or 1D array_like
|
| 206 |
+
Cutoff frequency of filter (expressed in the same units as `fs`)
|
| 207 |
+
OR an array of cutoff frequencies (that is, band edges). In the
|
| 208 |
+
latter case, the frequencies in `cutoff` should be positive and
|
| 209 |
+
monotonically increasing between 0 and `fs/2`. The values 0 and
|
| 210 |
+
`fs/2` must not be included in `cutoff`.
|
| 211 |
+
width : float or None, optional
|
| 212 |
+
If `width` is not None, then assume it is the approximate width
|
| 213 |
+
of the transition region (expressed in the same units as `fs`)
|
| 214 |
+
for use in Kaiser FIR filter design. In this case, the `window`
|
| 215 |
+
argument is ignored.
|
| 216 |
+
window : string or tuple of string and parameter values, optional
|
| 217 |
+
Desired window to use. See `cusignal.get_window` for a list
|
| 218 |
+
of windows and required parameters.
|
| 219 |
+
pass_zero : {True, False, 'bandpass', 'lowpass', 'highpass', 'bandstop'},
|
| 220 |
+
optional
|
| 221 |
+
If True, the gain at the frequency 0 (i.e. the "DC gain") is 1.
|
| 222 |
+
If False, the DC gain is 0. Can also be a string argument for the
|
| 223 |
+
desired filter type (equivalent to ``btype`` in IIR design functions).
|
| 224 |
+
scale : bool, optional
|
| 225 |
+
Set to True to scale the coefficients so that the frequency
|
| 226 |
+
response is exactly unity at a certain frequency.
|
| 227 |
+
That frequency is either:
|
| 228 |
+
|
| 229 |
+
- 0 (DC) if the first passband starts at 0 (i.e. pass_zero
|
| 230 |
+
is True)
|
| 231 |
+
- `fs/2` (the Nyquist frequency) if the first passband ends at
|
| 232 |
+
`fs/2` (i.e the filter is a single band highpass filter);
|
| 233 |
+
center of first passband otherwise
|
| 234 |
+
fs : float, optional
|
| 235 |
+
The sampling frequency of the signal. Each frequency in `cutoff`
|
| 236 |
+
must be between 0 and ``fs/2``. Default is 2.
|
| 237 |
+
|
| 238 |
+
Returns
|
| 239 |
+
-------
|
| 240 |
+
h : (numtaps,) ndarray
|
| 241 |
+
Coefficients of length `numtaps` FIR filter.
|
| 242 |
+
|
| 243 |
+
Raises
|
| 244 |
+
------
|
| 245 |
+
ValueError
|
| 246 |
+
If any value in `cutoff` is less than or equal to 0 or greater
|
| 247 |
+
than or equal to ``fs/2``, if the values in `cutoff` are not strictly
|
| 248 |
+
monotonically increasing, or if `numtaps` is even but a passband
|
| 249 |
+
includes the Nyquist frequency.
|
| 250 |
+
|
| 251 |
+
See Also
|
| 252 |
+
--------
|
| 253 |
+
firwin2
|
| 254 |
+
firls
|
| 255 |
+
minimum_phase
|
| 256 |
+
remez
|
| 257 |
+
|
| 258 |
+
Examples
|
| 259 |
+
--------
|
| 260 |
+
Low-pass from 0 to f:
|
| 261 |
+
|
| 262 |
+
>>> import cusignal
|
| 263 |
+
>>> numtaps = 3
|
| 264 |
+
>>> f = 0.1
|
| 265 |
+
>>> cusignal.firwin(numtaps, f)
|
| 266 |
+
array([ 0.06799017, 0.86401967, 0.06799017])
|
| 267 |
+
|
| 268 |
+
Use a specific window function:
|
| 269 |
+
|
| 270 |
+
>>> cusignal.firwin(numtaps, f, window='nuttall')
|
| 271 |
+
array([ 3.56607041e-04, 9.99286786e-01, 3.56607041e-04])
|
| 272 |
+
|
| 273 |
+
High-pass ('stop' from 0 to f):
|
| 274 |
+
|
| 275 |
+
>>> cusignal.firwin(numtaps, f, pass_zero=False)
|
| 276 |
+
array([-0.00859313, 0.98281375, -0.00859313])
|
| 277 |
+
|
| 278 |
+
Band-pass:
|
| 279 |
+
|
| 280 |
+
>>> f1, f2 = 0.1, 0.2
|
| 281 |
+
>>> cusignal.firwin(numtaps, [f1, f2], pass_zero=False)
|
| 282 |
+
array([ 0.06301614, 0.88770441, 0.06301614])
|
| 283 |
+
|
| 284 |
+
Band-stop:
|
| 285 |
+
|
| 286 |
+
>>> cusignal.firwin(numtaps, [f1, f2])
|
| 287 |
+
array([-0.00801395, 1.0160279 , -0.00801395])
|
| 288 |
+
|
| 289 |
+
Multi-band (passbands are [0, f1], [f2, f3] and [f4, 1]):
|
| 290 |
+
|
| 291 |
+
>>> f3, f4 = 0.3, 0.4
|
| 292 |
+
>>> cusignal.firwin(numtaps, [f1, f2, f3, f4])
|
| 293 |
+
array([-0.01376344, 1.02752689, -0.01376344])
|
| 294 |
+
|
| 295 |
+
Multi-band (passbands are [f1, f2] and [f3,f4]):
|
| 296 |
+
|
| 297 |
+
>>> cusignal.firwin(numtaps, [f1, f2, f3, f4], pass_zero=False)
|
| 298 |
+
array([ 0.04890915, 0.91284326, 0.04890915])
|
| 299 |
+
|
| 300 |
+
"""
|
| 301 |
+
|
| 302 |
+
nyq = 0.5 * fs
|
| 303 |
+
|
| 304 |
+
cutoff = cupy.atleast_1d(cutoff) / float(nyq)
|
| 305 |
+
|
| 306 |
+
# Check for invalid input.
|
| 307 |
+
if cutoff.ndim > 1:
|
| 308 |
+
raise ValueError(
|
| 309 |
+
"The cutoff argument must be at most " "one-dimensional.")
|
| 310 |
+
if cutoff.size == 0:
|
| 311 |
+
raise ValueError("At least one cutoff frequency must be given.")
|
| 312 |
+
if cutoff.min() <= 0 or cutoff.max() >= 1:
|
| 313 |
+
raise ValueError(
|
| 314 |
+
"Invalid cutoff frequency: frequencies must be "
|
| 315 |
+
"greater than 0 and less than nyq."
|
| 316 |
+
)
|
| 317 |
+
if cupy.any(cupy.diff(cutoff) <= 0):
|
| 318 |
+
raise ValueError(
|
| 319 |
+
"Invalid cutoff frequencies: the frequencies "
|
| 320 |
+
"must be strictly increasing."
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
if width is not None:
|
| 324 |
+
# A width was given. Find the beta parameter of the Kaiser window
|
| 325 |
+
# and set `window`. This overrides the value of `window` passed in.
|
| 326 |
+
atten = kaiser_atten(numtaps, float(width) / nyq)
|
| 327 |
+
beta = kaiser_beta(atten)
|
| 328 |
+
window = ("kaiser", beta)
|
| 329 |
+
|
| 330 |
+
if isinstance(pass_zero, str):
|
| 331 |
+
if pass_zero in ("bandstop", "lowpass"):
|
| 332 |
+
if pass_zero == "lowpass":
|
| 333 |
+
if cutoff.size != 1:
|
| 334 |
+
raise ValueError(
|
| 335 |
+
"cutoff must have one element if "
|
| 336 |
+
'pass_zero=="lowpass", got %s' % (cutoff.shape,)
|
| 337 |
+
)
|
| 338 |
+
elif cutoff.size <= 1:
|
| 339 |
+
raise ValueError(
|
| 340 |
+
"cutoff must have at least two elements if "
|
| 341 |
+
'pass_zero=="bandstop", got %s' % (cutoff.shape,)
|
| 342 |
+
)
|
| 343 |
+
pass_zero = True
|
| 344 |
+
elif pass_zero in ("bandpass", "highpass"):
|
| 345 |
+
if pass_zero == "highpass":
|
| 346 |
+
if cutoff.size != 1:
|
| 347 |
+
raise ValueError(
|
| 348 |
+
"cutoff must have one element if "
|
| 349 |
+
'pass_zero=="highpass", got %s' % (cutoff.shape,)
|
| 350 |
+
)
|
| 351 |
+
elif cutoff.size <= 1:
|
| 352 |
+
raise ValueError(
|
| 353 |
+
"cutoff must have at least two elements if "
|
| 354 |
+
'pass_zero=="bandpass", got %s' % (cutoff.shape,)
|
| 355 |
+
)
|
| 356 |
+
pass_zero = False
|
| 357 |
+
else:
|
| 358 |
+
raise ValueError(
|
| 359 |
+
'pass_zero must be True, False, "bandpass", '
|
| 360 |
+
'"lowpass", "highpass", or "bandstop", got '
|
| 361 |
+
"{}".format(pass_zero)
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
pass_nyquist = bool(cutoff.size & 1) ^ pass_zero
|
| 365 |
+
|
| 366 |
+
if pass_nyquist and numtaps % 2 == 0:
|
| 367 |
+
raise ValueError(
|
| 368 |
+
"A filter with an even number of coefficients must "
|
| 369 |
+
"have zero response at the Nyquist rate."
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
# Insert 0 and/or 1 at the ends of cutoff so that the length of cutoff
|
| 373 |
+
# is even, and each pair in cutoff corresponds to passband.
|
| 374 |
+
cutoff = cupy.hstack(([0.0] * pass_zero, cutoff, [1.0] * pass_nyquist))
|
| 375 |
+
|
| 376 |
+
# `bands` is a 2D array; each row gives the left and right edges of
|
| 377 |
+
# a passband.
|
| 378 |
+
bands = cutoff.reshape(-1, 2)
|
| 379 |
+
|
| 380 |
+
win = get_window(window, numtaps, fftbins=False)
|
| 381 |
+
h, hc = _firwin_kernel(win, numtaps, bands, bands.shape[0], scale)
|
| 382 |
+
if scale:
|
| 383 |
+
s = cupy.sum(hc)
|
| 384 |
+
h /= s
|
| 385 |
+
|
| 386 |
+
# Build up the coefficients.
|
| 387 |
+
alpha = 0.5 * (numtaps - 1)
|
| 388 |
+
m = cupy.arange(0, numtaps) - alpha
|
| 389 |
+
h = 0
|
| 390 |
+
for left, right in bands:
|
| 391 |
+
h += right * cupy.sinc(right * m)
|
| 392 |
+
h -= left * cupy.sinc(left * m)
|
| 393 |
+
|
| 394 |
+
h *= win
|
| 395 |
+
|
| 396 |
+
# Now handle scaling if desired.
|
| 397 |
+
if scale:
|
| 398 |
+
# Get the first passband.
|
| 399 |
+
left, right = bands[0]
|
| 400 |
+
if left == 0:
|
| 401 |
+
scale_frequency = 0.0
|
| 402 |
+
elif right == 1:
|
| 403 |
+
scale_frequency = 1.0
|
| 404 |
+
else:
|
| 405 |
+
scale_frequency = 0.5 * (left + right)
|
| 406 |
+
c = cupy.cos(cupy.pi * m * scale_frequency)
|
| 407 |
+
s = cupy.sum(h * c)
|
| 408 |
+
h /= s
|
| 409 |
+
|
| 410 |
+
return h
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def firwin2(
|
| 414 |
+
numtaps,
|
| 415 |
+
freq,
|
| 416 |
+
gain,
|
| 417 |
+
nfreqs=None,
|
| 418 |
+
window="hamming",
|
| 419 |
+
nyq=None,
|
| 420 |
+
antisymmetric=False,
|
| 421 |
+
fs=2.0,
|
| 422 |
+
):
|
| 423 |
+
"""
|
| 424 |
+
FIR filter design using the window method.
|
| 425 |
+
|
| 426 |
+
From the given frequencies `freq` and corresponding gains `gain`,
|
| 427 |
+
this function constructs an FIR filter with linear phase and
|
| 428 |
+
(approximately) the given frequency response.
|
| 429 |
+
|
| 430 |
+
Parameters
|
| 431 |
+
----------
|
| 432 |
+
numtaps : int
|
| 433 |
+
The number of taps in the FIR filter. `numtaps` must be less than
|
| 434 |
+
`nfreqs`.
|
| 435 |
+
freq : array_like, 1-D
|
| 436 |
+
The frequency sampling points. Typically 0.0 to 1.0 with 1.0 being
|
| 437 |
+
Nyquist. The Nyquist frequency is half `fs`.
|
| 438 |
+
The values in `freq` must be nondecreasing. A value can be repeated
|
| 439 |
+
once to implement a discontinuity. The first value in `freq` must
|
| 440 |
+
be 0, and the last value must be ``fs/2``. Values 0 and ``fs/2`` must
|
| 441 |
+
not be repeated.
|
| 442 |
+
gain : array_like
|
| 443 |
+
The filter gains at the frequency sampling points. Certain
|
| 444 |
+
constraints to gain values, depending on the filter type, are applied,
|
| 445 |
+
see Notes for details.
|
| 446 |
+
nfreqs : int, optional
|
| 447 |
+
The size of the interpolation mesh used to construct the filter.
|
| 448 |
+
For most efficient behavior, this should be a power of 2 plus 1
|
| 449 |
+
(e.g, 129, 257, etc). The default is one more than the smallest
|
| 450 |
+
power of 2 that is not less than `numtaps`. `nfreqs` must be greater
|
| 451 |
+
than `numtaps`.
|
| 452 |
+
window : string or (string, float) or float, or None, optional
|
| 453 |
+
Window function to use. Default is "hamming". See
|
| 454 |
+
`scipy.signal.get_window` for the complete list of possible values.
|
| 455 |
+
If None, no window function is applied.
|
| 456 |
+
antisymmetric : bool, optional
|
| 457 |
+
Whether resulting impulse response is symmetric/antisymmetric.
|
| 458 |
+
See Notes for more details.
|
| 459 |
+
fs : float, optional
|
| 460 |
+
The sampling frequency of the signal. Each frequency in `cutoff`
|
| 461 |
+
must be between 0 and ``fs/2``. Default is 2.
|
| 462 |
+
|
| 463 |
+
Returns
|
| 464 |
+
-------
|
| 465 |
+
taps : ndarray
|
| 466 |
+
The filter coefficients of the FIR filter, as a 1-D array of length
|
| 467 |
+
`numtaps`.
|
| 468 |
+
|
| 469 |
+
See Also
|
| 470 |
+
--------
|
| 471 |
+
scipy.signal.firwin2
|
| 472 |
+
firls
|
| 473 |
+
firwin
|
| 474 |
+
minimum_phase
|
| 475 |
+
remez
|
| 476 |
+
|
| 477 |
+
Notes
|
| 478 |
+
-----
|
| 479 |
+
From the given set of frequencies and gains, the desired response is
|
| 480 |
+
constructed in the frequency domain. The inverse FFT is applied to the
|
| 481 |
+
desired response to create the associated convolution kernel, and the
|
| 482 |
+
first `numtaps` coefficients of this kernel, scaled by `window`, are
|
| 483 |
+
returned.
|
| 484 |
+
The FIR filter will have linear phase. The type of filter is determined by
|
| 485 |
+
the value of 'numtaps` and `antisymmetric` flag.
|
| 486 |
+
There are four possible combinations:
|
| 487 |
+
|
| 488 |
+
- odd `numtaps`, `antisymmetric` is False, type I filter is produced
|
| 489 |
+
- even `numtaps`, `antisymmetric` is False, type II filter is produced
|
| 490 |
+
- odd `numtaps`, `antisymmetric` is True, type III filter is produced
|
| 491 |
+
- even `numtaps`, `antisymmetric` is True, type IV filter is produced
|
| 492 |
+
|
| 493 |
+
Magnitude response of all but type I filters are subjects to following
|
| 494 |
+
constraints:
|
| 495 |
+
|
| 496 |
+
- type II -- zero at the Nyquist frequency
|
| 497 |
+
- type III -- zero at zero and Nyquist frequencies
|
| 498 |
+
- type IV -- zero at zero frequency
|
| 499 |
+
"""
|
| 500 |
+
nyq = 0.5 * fs
|
| 501 |
+
|
| 502 |
+
if len(freq) != len(gain):
|
| 503 |
+
raise ValueError("freq and gain must be of same length.")
|
| 504 |
+
|
| 505 |
+
if nfreqs is not None and numtaps >= nfreqs:
|
| 506 |
+
raise ValueError(
|
| 507 |
+
(
|
| 508 |
+
"ntaps must be less than nfreqs, but firwin2 was "
|
| 509 |
+
"called with ntaps=%d and nfreqs=%s"
|
| 510 |
+
)
|
| 511 |
+
% (numtaps, nfreqs)
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
if freq[0] != 0 or freq[-1] != nyq:
|
| 515 |
+
raise ValueError("freq must start with 0 and end with fs/2.")
|
| 516 |
+
d = cupy.diff(freq)
|
| 517 |
+
if (d < 0).any():
|
| 518 |
+
raise ValueError("The values in freq must be nondecreasing.")
|
| 519 |
+
d2 = d[:-1] + d[1:]
|
| 520 |
+
if (d2 == 0).any():
|
| 521 |
+
raise ValueError("A value in freq must not occur more than twice.")
|
| 522 |
+
if freq[1] == 0:
|
| 523 |
+
raise ValueError("Value 0 must not be repeated in freq")
|
| 524 |
+
if freq[-2] == nyq:
|
| 525 |
+
raise ValueError("Value fs/2 must not be repeated in freq")
|
| 526 |
+
|
| 527 |
+
if antisymmetric:
|
| 528 |
+
if numtaps % 2 == 0:
|
| 529 |
+
ftype = 4
|
| 530 |
+
else:
|
| 531 |
+
ftype = 3
|
| 532 |
+
else:
|
| 533 |
+
if numtaps % 2 == 0:
|
| 534 |
+
ftype = 2
|
| 535 |
+
else:
|
| 536 |
+
ftype = 1
|
| 537 |
+
|
| 538 |
+
if ftype == 2 and gain[-1] != 0.0:
|
| 539 |
+
raise ValueError(
|
| 540 |
+
"A Type II filter must have zero gain at the " "Nyquist frequency."
|
| 541 |
+
)
|
| 542 |
+
elif ftype == 3 and (gain[0] != 0.0 or gain[-1] != 0.0):
|
| 543 |
+
raise ValueError(
|
| 544 |
+
"A Type III filter must have zero gain at zero "
|
| 545 |
+
"and Nyquist frequencies."
|
| 546 |
+
)
|
| 547 |
+
elif ftype == 4 and gain[0] != 0.0:
|
| 548 |
+
raise ValueError(
|
| 549 |
+
"A Type IV filter must have zero gain at zero " "frequency.")
|
| 550 |
+
|
| 551 |
+
if nfreqs is None:
|
| 552 |
+
nfreqs = 1 + 2 ** int(math.ceil(math.log(numtaps, 2)))
|
| 553 |
+
|
| 554 |
+
if (d == 0).any():
|
| 555 |
+
# Tweak any repeated values in freq so that interp works.
|
| 556 |
+
freq = cupy.array(freq, copy=True)
|
| 557 |
+
eps = cupy.finfo(float).eps * nyq
|
| 558 |
+
for k in range(len(freq) - 1):
|
| 559 |
+
if freq[k] == freq[k + 1]:
|
| 560 |
+
freq[k] = freq[k] - eps
|
| 561 |
+
freq[k + 1] = freq[k + 1] + eps
|
| 562 |
+
# Check if freq is strictly increasing after tweak
|
| 563 |
+
d = cupy.diff(freq)
|
| 564 |
+
if (d <= 0).any():
|
| 565 |
+
raise ValueError(
|
| 566 |
+
"freq cannot contain numbers that are too close "
|
| 567 |
+
"(within eps * (fs/2): "
|
| 568 |
+
"{}) to a repeated value".format(eps)
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
# Linearly interpolate the desired response on a uniform mesh `x`.
|
| 572 |
+
x = cupy.linspace(0.0, nyq, nfreqs)
|
| 573 |
+
fx = cupy.interp(x, freq, gain)
|
| 574 |
+
|
| 575 |
+
# Adjust the phases of the coefficients so that the first `ntaps` of the
|
| 576 |
+
# inverse FFT are the desired filter coefficients.
|
| 577 |
+
shift = cupy.exp(-(numtaps - 1) / 2.0 * 1.0j * math.pi * x / nyq)
|
| 578 |
+
if ftype > 2:
|
| 579 |
+
shift *= 1j
|
| 580 |
+
|
| 581 |
+
fx2 = fx * shift
|
| 582 |
+
|
| 583 |
+
# Use irfft to compute the inverse FFT.
|
| 584 |
+
out_full = cupy.fft.irfft(fx2)
|
| 585 |
+
|
| 586 |
+
if window is not None:
|
| 587 |
+
# Create the window to apply to the filter coefficients.
|
| 588 |
+
wind = get_window(window, numtaps, fftbins=False)
|
| 589 |
+
else:
|
| 590 |
+
wind = 1
|
| 591 |
+
|
| 592 |
+
# Keep only the first `numtaps` coefficients in `out`, and multiply by
|
| 593 |
+
# the window.
|
| 594 |
+
out = out_full[:numtaps] * wind
|
| 595 |
+
|
| 596 |
+
if ftype == 3:
|
| 597 |
+
out[out.size // 2] = 0.0
|
| 598 |
+
|
| 599 |
+
return out
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
# Scipy <= 1.12 has a deprecated `nyq` argument (nyq = fs/2).
|
| 603 |
+
# Remove it here, to be forward-looking.
|
| 604 |
+
def firls(numtaps, bands, desired, weight=None, fs=2):
|
| 605 |
+
"""
|
| 606 |
+
FIR filter design using least-squares error minimization.
|
| 607 |
+
|
| 608 |
+
Calculate the filter coefficients for the linear-phase finite
|
| 609 |
+
impulse response (FIR) filter which has the best approximation
|
| 610 |
+
to the desired frequency response described by `bands` and
|
| 611 |
+
`desired` in the least squares sense (i.e., the integral of the
|
| 612 |
+
weighted mean-squared error within the specified bands is
|
| 613 |
+
minimized).
|
| 614 |
+
|
| 615 |
+
Parameters
|
| 616 |
+
----------
|
| 617 |
+
numtaps : int
|
| 618 |
+
The number of taps in the FIR filter. `numtaps` must be odd.
|
| 619 |
+
bands : array_like
|
| 620 |
+
A monotonic nondecreasing sequence containing the band edges in
|
| 621 |
+
Hz. All elements must be non-negative and less than or equal to
|
| 622 |
+
the Nyquist frequency given by `fs`/2. The bands are specified as
|
| 623 |
+
frequency pairs, thus, if using a 1D array, its length must be
|
| 624 |
+
even, e.g., `cupy.array([0, 1, 2, 3, 4, 5])`. Alternatively, the
|
| 625 |
+
bands can be specified as an nx2 sized 2D array, where n is the
|
| 626 |
+
number of bands, e.g, `cupy.array([[0, 1], [2, 3], [4, 5]])`.
|
| 627 |
+
All elements of `bands` must be monotonically nondecreasing, have
|
| 628 |
+
width > 0, and must not overlap. (This is not checked by the routine).
|
| 629 |
+
desired : array_like
|
| 630 |
+
A sequence the same size as `bands` containing the desired gain
|
| 631 |
+
at the start and end point of each band.
|
| 632 |
+
All elements must be non-negative (this is not checked by the routine).
|
| 633 |
+
weight : array_like, optional
|
| 634 |
+
A relative weighting to give to each band region when solving
|
| 635 |
+
the least squares problem. `weight` has to be half the size of
|
| 636 |
+
`bands`.
|
| 637 |
+
All elements must be non-negative (this is not checked by the routine).
|
| 638 |
+
fs : float, optional
|
| 639 |
+
The sampling frequency of the signal. Each frequency in `bands`
|
| 640 |
+
must be between 0 and ``fs/2`` (inclusive). Default is 2.
|
| 641 |
+
|
| 642 |
+
Returns
|
| 643 |
+
-------
|
| 644 |
+
coeffs : ndarray
|
| 645 |
+
Coefficients of the optimal (in a least squares sense) FIR filter.
|
| 646 |
+
|
| 647 |
+
See Also
|
| 648 |
+
--------
|
| 649 |
+
firwin
|
| 650 |
+
firwin2
|
| 651 |
+
minimum_phase
|
| 652 |
+
remez
|
| 653 |
+
scipy.signal.firls
|
| 654 |
+
"""
|
| 655 |
+
nyq = 0.5 * fs
|
| 656 |
+
|
| 657 |
+
numtaps = int(numtaps)
|
| 658 |
+
if numtaps % 2 == 0 or numtaps < 1:
|
| 659 |
+
raise ValueError("numtaps must be odd and >= 1")
|
| 660 |
+
M = (numtaps-1) // 2
|
| 661 |
+
|
| 662 |
+
# normalize bands 0->1 and make it 2 columns
|
| 663 |
+
nyq = float(nyq)
|
| 664 |
+
if nyq <= 0:
|
| 665 |
+
raise ValueError('nyq must be positive, got %s <= 0.' % nyq)
|
| 666 |
+
bands = cupy.asarray(bands).flatten() / nyq
|
| 667 |
+
if len(bands) % 2 != 0:
|
| 668 |
+
raise ValueError("bands must contain frequency pairs.")
|
| 669 |
+
if (bands < 0).any() or (bands > 1).any():
|
| 670 |
+
raise ValueError("bands must be between 0 and 1 relative to Nyquist")
|
| 671 |
+
bands.shape = (-1, 2)
|
| 672 |
+
|
| 673 |
+
# check remaining params
|
| 674 |
+
desired = cupy.asarray(desired).flatten()
|
| 675 |
+
if bands.size != desired.size:
|
| 676 |
+
raise ValueError("desired must have one entry per frequency, got %s "
|
| 677 |
+
"gains for %s frequencies."
|
| 678 |
+
% (desired.size, bands.size))
|
| 679 |
+
desired.shape = (-1, 2)
|
| 680 |
+
# if (cupy.diff(bands) <= 0).any() or (cupy.diff(bands[:, 0]) < 0).any():
|
| 681 |
+
# raise ValueError("bands must be monotonically nondecreasing and have"
|
| 682 |
+
# " width > 0.")
|
| 683 |
+
# if (bands[:-1, 1] > bands[1:, 0]).any():
|
| 684 |
+
# raise ValueError("bands must not overlap.")
|
| 685 |
+
# if (desired < 0).any():
|
| 686 |
+
# raise ValueError("desired must be non-negative.")
|
| 687 |
+
if weight is None:
|
| 688 |
+
weight = cupy.ones(len(desired))
|
| 689 |
+
weight = cupy.asarray(weight).flatten()
|
| 690 |
+
if len(weight) != len(desired):
|
| 691 |
+
raise ValueError("weight must be the same size as the number of "
|
| 692 |
+
"band pairs ({}).".format(len(bands)))
|
| 693 |
+
# if (weight < 0).any():
|
| 694 |
+
# raise ValueError("weight must be non-negative.")
|
| 695 |
+
|
| 696 |
+
# Set up the linear matrix equation to be solved, Qa = b
|
| 697 |
+
|
| 698 |
+
# We can express Q(k,n) = 0.5 Q1(k,n) + 0.5 Q2(k,n)
|
| 699 |
+
# where Q1(k,n)=q(k-n) and Q2(k,n)=q(k+n), i.e. a Toeplitz plus Hankel.
|
| 700 |
+
|
| 701 |
+
# We omit the factor of 0.5 above, instead adding it during coefficient
|
| 702 |
+
# calculation.
|
| 703 |
+
|
| 704 |
+
# We also omit the 1/π from both Q and b equations, as they cancel
|
| 705 |
+
# during solving.
|
| 706 |
+
|
| 707 |
+
# We have that:
|
| 708 |
+
# q(n) = 1/π ∫W(ω)cos(nω)dω (over 0->π)
|
| 709 |
+
# Using our normalization ω=πf and with a constant weight W over each
|
| 710 |
+
# interval f1->f2 we get:
|
| 711 |
+
# q(n) = W∫cos(πnf)df (0->1) = Wf sin(πnf)/πnf
|
| 712 |
+
# integrated over each f1->f2 pair (i.e., value at f2 - value at f1).
|
| 713 |
+
n = cupy.arange(numtaps)[:, cupy.newaxis, cupy.newaxis]
|
| 714 |
+
q = cupy.dot(cupy.diff(cupy.sinc(bands * n) *
|
| 715 |
+
bands, axis=2)[:, :, 0], weight)
|
| 716 |
+
|
| 717 |
+
# Now we assemble our sum of Toeplitz and Hankel
|
| 718 |
+
Q1 = toeplitz(q[:M+1])
|
| 719 |
+
Q2 = hankel(q[:M+1], q[M:])
|
| 720 |
+
Q = Q1 + Q2
|
| 721 |
+
|
| 722 |
+
# Now for b(n) we have that:
|
| 723 |
+
# b(n) = 1/π ∫ W(ω)D(ω)cos(nω)dω (over 0->π)
|
| 724 |
+
# Using our normalization ω=πf and with a constant weight W over each
|
| 725 |
+
# interval and a linear term for D(ω) we get (over each f1->f2 interval):
|
| 726 |
+
# b(n) = W ∫ (mf+c)cos(πnf)df
|
| 727 |
+
# = f(mf+c)sin(πnf)/πnf + mf**2 cos(nπf)/(πnf)**2
|
| 728 |
+
# integrated over each f1->f2 pair (i.e., value at f2 - value at f1).
|
| 729 |
+
n = n[:M + 1] # only need this many coefficients here
|
| 730 |
+
# Choose m and c such that we are at the start and end weights
|
| 731 |
+
m = (cupy.diff(desired, axis=1) / cupy.diff(bands, axis=1))
|
| 732 |
+
c = desired[:, [0]] - bands[:, [0]] * m
|
| 733 |
+
b = bands * (m*bands + c) * cupy.sinc(bands * n)
|
| 734 |
+
# Use L'Hospital's rule here for cos(nπf)/(πnf)**2 @ n=0
|
| 735 |
+
b[0] -= m * bands * bands / 2.
|
| 736 |
+
b[1:] += m * cupy.cos(n[1:] * cupy.pi * bands) / (cupy.pi * n[1:]) ** 2
|
| 737 |
+
b = cupy.diff(b, axis=2)[:, :, 0] @ weight
|
| 738 |
+
|
| 739 |
+
# Now we can solve the equation : XXX CuPy failure modes (?)
|
| 740 |
+
with cupyx.errstate(linalg="raise"):
|
| 741 |
+
try:
|
| 742 |
+
a = solve(Q, b)
|
| 743 |
+
except LinAlgError:
|
| 744 |
+
# in case Q is rank deficient
|
| 745 |
+
a = lstsq(Q, b, rcond=None)[0]
|
| 746 |
+
|
| 747 |
+
# XXX: scipy.signal does this:
|
| 748 |
+
# try: # try the fast way
|
| 749 |
+
# with warnings.catch_warnings(record=True) as w:
|
| 750 |
+
# warnings.simplefilter('always')
|
| 751 |
+
# a = solve(Q, b)
|
| 752 |
+
# for ww in w:
|
| 753 |
+
# if (ww.category == LinAlgWarning and
|
| 754 |
+
# str(ww.message).startswith('Ill-conditioned matrix')):
|
| 755 |
+
# raise LinAlgError(str(ww.message))
|
| 756 |
+
# except LinAlgError: # in case Q is rank deficient
|
| 757 |
+
# a = lstsq(Q, b)[0]
|
| 758 |
+
|
| 759 |
+
# make coefficients symmetric (linear phase)
|
| 760 |
+
coeffs = cupy.hstack((a[:0:-1], 2 * a[0], a[1:]))
|
| 761 |
+
return coeffs
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
def _dhtm(mag):
|
| 765 |
+
"""Compute the modified 1-D discrete Hilbert transform
|
| 766 |
+
|
| 767 |
+
Parameters
|
| 768 |
+
----------
|
| 769 |
+
mag : ndarray
|
| 770 |
+
The magnitude spectrum. Should be 1-D with an even length, and
|
| 771 |
+
preferably a fast length for FFT/IFFT.
|
| 772 |
+
"""
|
| 773 |
+
# Adapted based on code by Niranjan Damera-Venkata,
|
| 774 |
+
# Brian L. Evans and Shawn R. McCaslin (see refs for `minimum_phase`)
|
| 775 |
+
sig = cupy.zeros(len(mag))
|
| 776 |
+
# Leave Nyquist and DC at 0, knowing np.abs(fftfreq(N)[midpt]) == 0.5
|
| 777 |
+
midpt = len(mag) // 2
|
| 778 |
+
sig[1:midpt] = 1
|
| 779 |
+
sig[midpt + 1:] = -1
|
| 780 |
+
# eventually if we want to support complex filters, we will need a
|
| 781 |
+
# cupy.abs() on the mag inside the log, and should remove the .real
|
| 782 |
+
recon = ifft(mag * cupy.exp(fft(sig * ifft(cupy.log(mag))))).real
|
| 783 |
+
return recon
|
| 784 |
+
|
| 785 |
+
|
| 786 |
+
def minimum_phase(h, method='homomorphic', n_fft=None):
|
| 787 |
+
"""Convert a linear-phase FIR filter to minimum phase
|
| 788 |
+
|
| 789 |
+
Parameters
|
| 790 |
+
----------
|
| 791 |
+
h : array
|
| 792 |
+
Linear-phase FIR filter coefficients.
|
| 793 |
+
method : {'hilbert', 'homomorphic'}
|
| 794 |
+
The method to use:
|
| 795 |
+
|
| 796 |
+
'homomorphic' (default)
|
| 797 |
+
This method [4]_ [5]_ works best with filters with an
|
| 798 |
+
odd number of taps, and the resulting minimum phase filter
|
| 799 |
+
will have a magnitude response that approximates the square
|
| 800 |
+
root of the original filter's magnitude response.
|
| 801 |
+
|
| 802 |
+
'hilbert'
|
| 803 |
+
This method [1]_ is designed to be used with equiripple
|
| 804 |
+
filters (e.g., from `remez`) with unity or zero gain
|
| 805 |
+
regions.
|
| 806 |
+
|
| 807 |
+
n_fft : int
|
| 808 |
+
The number of points to use for the FFT. Should be at least a
|
| 809 |
+
few times larger than the signal length (see Notes).
|
| 810 |
+
|
| 811 |
+
Returns
|
| 812 |
+
-------
|
| 813 |
+
h_minimum : array
|
| 814 |
+
The minimum-phase version of the filter, with length
|
| 815 |
+
``(length(h) + 1) // 2``.
|
| 816 |
+
|
| 817 |
+
See Also
|
| 818 |
+
--------
|
| 819 |
+
scipy.signal.minimum_phase
|
| 820 |
+
|
| 821 |
+
Notes
|
| 822 |
+
-----
|
| 823 |
+
Both the Hilbert [1]_ or homomorphic [4]_ [5]_ methods require selection
|
| 824 |
+
of an FFT length to estimate the complex cepstrum of the filter.
|
| 825 |
+
|
| 826 |
+
In the case of the Hilbert method, the deviation from the ideal
|
| 827 |
+
spectrum ``epsilon`` is related to the number of stopband zeros
|
| 828 |
+
``n_stop`` and FFT length ``n_fft`` as::
|
| 829 |
+
|
| 830 |
+
epsilon = 2. * n_stop / n_fft
|
| 831 |
+
|
| 832 |
+
For example, with 100 stopband zeros and a FFT length of 2048,
|
| 833 |
+
``epsilon = 0.0976``. If we conservatively assume that the number of
|
| 834 |
+
stopband zeros is one less than the filter length, we can take the FFT
|
| 835 |
+
length to be the next power of 2 that satisfies ``epsilon=0.01`` as::
|
| 836 |
+
|
| 837 |
+
n_fft = 2 ** int(np.ceil(np.log2(2 * (len(h) - 1) / 0.01)))
|
| 838 |
+
|
| 839 |
+
This gives reasonable results for both the Hilbert and homomorphic
|
| 840 |
+
methods, and gives the value used when ``n_fft=None``.
|
| 841 |
+
|
| 842 |
+
Alternative implementations exist for creating minimum-phase filters,
|
| 843 |
+
including zero inversion [2]_ and spectral factorization [3]_ [4]_ [5]_.
|
| 844 |
+
For more information, see:
|
| 845 |
+
|
| 846 |
+
http://dspguru.com/dsp/howtos/how-to-design-minimum-phase-fir-filters
|
| 847 |
+
|
| 848 |
+
References
|
| 849 |
+
----------
|
| 850 |
+
.. [1] N. Damera-Venkata and B. L. Evans, "Optimal design of real and
|
| 851 |
+
complex minimum phase digital FIR filters," Acoustics, Speech,
|
| 852 |
+
and Signal Processing, 1999. Proceedings., 1999 IEEE International
|
| 853 |
+
Conference on, Phoenix, AZ, 1999, pp. 1145-1148 vol.3.
|
| 854 |
+
DOI:10.1109/ICASSP.1999.756179
|
| 855 |
+
.. [2] X. Chen and T. W. Parks, "Design of optimal minimum phase FIR
|
| 856 |
+
filters by direct factorization," Signal Processing,
|
| 857 |
+
vol. 10, no. 4, pp. 369-383, Jun. 1986.
|
| 858 |
+
.. [3] T. Saramaki, "Finite Impulse Response Filter Design," in
|
| 859 |
+
Handbook for Digital Signal Processing, chapter 4,
|
| 860 |
+
New York: Wiley-Interscience, 1993.
|
| 861 |
+
.. [4] J. S. Lim, Advanced Topics in Signal Processing.
|
| 862 |
+
Englewood Cliffs, N.J.: Prentice Hall, 1988.
|
| 863 |
+
.. [5] A. V. Oppenheim, R. W. Schafer, and J. R. Buck,
|
| 864 |
+
"Discrete-Time Signal Processing," 2nd edition.
|
| 865 |
+
Upper Saddle River, N.J.: Prentice Hall, 1999.
|
| 866 |
+
|
| 867 |
+
""" # noqa
|
| 868 |
+
if cupy.iscomplexobj(h):
|
| 869 |
+
raise ValueError('Complex filters not supported')
|
| 870 |
+
if h.ndim != 1 or h.size <= 2:
|
| 871 |
+
raise ValueError('h must be 1-D and at least 2 samples long')
|
| 872 |
+
n_half = len(h) // 2
|
| 873 |
+
if not cupy.allclose(h[-n_half:][::-1], h[:n_half]):
|
| 874 |
+
import warnings
|
| 875 |
+
warnings.warn('h does not appear to by symmetric, conversion may '
|
| 876 |
+
'fail', RuntimeWarning)
|
| 877 |
+
if not isinstance(method, str) or method not in \
|
| 878 |
+
('homomorphic', 'hilbert',):
|
| 879 |
+
raise ValueError('method must be "homomorphic" or "hilbert", got %r'
|
| 880 |
+
% (method,))
|
| 881 |
+
if n_fft is None:
|
| 882 |
+
n_fft = 2 ** int(cupy.ceil(cupy.log2(2 * (len(h) - 1) / 0.01)))
|
| 883 |
+
n_fft = int(n_fft)
|
| 884 |
+
if n_fft < len(h):
|
| 885 |
+
raise ValueError('n_fft must be at least len(h)==%s' % len(h))
|
| 886 |
+
if method == 'hilbert':
|
| 887 |
+
w = cupy.arange(n_fft) * (2 * cupy.pi / n_fft * n_half)
|
| 888 |
+
H = cupy.real(fft(h, n_fft) * cupy.exp(1j * w))
|
| 889 |
+
dp = max(H) - 1
|
| 890 |
+
ds = 0 - min(H)
|
| 891 |
+
S = 4. / (cupy.sqrt(1 + dp + ds) + cupy.sqrt(1 - dp + ds)) ** 2
|
| 892 |
+
H += ds
|
| 893 |
+
H *= S
|
| 894 |
+
H = cupy.sqrt(H, out=H)
|
| 895 |
+
H += 1e-10 # ensure that the log does not explode
|
| 896 |
+
h_minimum = _dhtm(H)
|
| 897 |
+
else: # method == 'homomorphic'
|
| 898 |
+
# zero-pad; calculate the DFT
|
| 899 |
+
h_temp = cupy.abs(fft(h, n_fft))
|
| 900 |
+
# take 0.25*log(|H|**2) = 0.5*log(|H|)
|
| 901 |
+
h_temp += 1e-7 * h_temp[h_temp > 0].min() # don't let log blow up
|
| 902 |
+
cupy.log(h_temp, out=h_temp)
|
| 903 |
+
h_temp *= 0.5
|
| 904 |
+
# IDFT
|
| 905 |
+
h_temp = ifft(h_temp).real
|
| 906 |
+
# multiply pointwise by the homomorphic filter
|
| 907 |
+
# lmin[n] = 2u[n] - d[n]
|
| 908 |
+
win = cupy.zeros(n_fft)
|
| 909 |
+
win[0] = 1
|
| 910 |
+
stop = (len(h) + 1) // 2
|
| 911 |
+
win[1:stop] = 2
|
| 912 |
+
if len(h) % 2:
|
| 913 |
+
win[stop] = 1
|
| 914 |
+
h_temp *= win
|
| 915 |
+
h_temp = ifft(cupy.exp(fft(h_temp)))
|
| 916 |
+
h_minimum = h_temp.real
|
| 917 |
+
n_out = n_half + len(h) % 2
|
| 918 |
+
return h_minimum[:n_out]
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_iir_filter_conversions.py
ADDED
|
@@ -0,0 +1,2364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" IIR filter conversion utilities.
|
| 2 |
+
|
| 3 |
+
Split off _filter_design.py
|
| 4 |
+
"""
|
| 5 |
+
import warnings
|
| 6 |
+
import math
|
| 7 |
+
from math import pi, prod
|
| 8 |
+
|
| 9 |
+
import cupy
|
| 10 |
+
from cupyx.scipy.special import binom as comb
|
| 11 |
+
import cupyx.scipy.special as special
|
| 12 |
+
from cupyx.scipy.signal import _optimize
|
| 13 |
+
|
| 14 |
+
from cupyx.scipy.signal._polyutils import roots, poly
|
| 15 |
+
from cupyx.scipy.signal._lti_conversion import abcd_normalize
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class BadCoefficients(UserWarning):
|
| 19 |
+
"""Warning about badly conditioned filter coefficients"""
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _trim_zeros(filt, trim='fb'):
|
| 24 |
+
# https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/function_base.py#L1800-L1850
|
| 25 |
+
|
| 26 |
+
first = 0
|
| 27 |
+
if 'f' in trim:
|
| 28 |
+
for i in filt:
|
| 29 |
+
if i != 0.:
|
| 30 |
+
break
|
| 31 |
+
else:
|
| 32 |
+
first = first + 1
|
| 33 |
+
|
| 34 |
+
last = len(filt)
|
| 35 |
+
if 'b' in trim:
|
| 36 |
+
for i in filt[::-1]:
|
| 37 |
+
if i != 0.:
|
| 38 |
+
break
|
| 39 |
+
else:
|
| 40 |
+
last = last - 1
|
| 41 |
+
return filt[first:last]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _align_nums(nums):
|
| 45 |
+
"""Aligns the shapes of multiple numerators.
|
| 46 |
+
|
| 47 |
+
Given an array of numerator coefficient arrays [[a_1, a_2,...,
|
| 48 |
+
a_n],..., [b_1, b_2,..., b_m]], this function pads shorter numerator
|
| 49 |
+
arrays with zero's so that all numerators have the same length. Such
|
| 50 |
+
alignment is necessary for functions like 'tf2ss', which needs the
|
| 51 |
+
alignment when dealing with SIMO transfer functions.
|
| 52 |
+
|
| 53 |
+
Parameters
|
| 54 |
+
----------
|
| 55 |
+
nums: array_like
|
| 56 |
+
Numerator or list of numerators. Not necessarily with same length.
|
| 57 |
+
|
| 58 |
+
Returns
|
| 59 |
+
-------
|
| 60 |
+
nums: array
|
| 61 |
+
The numerator. If `nums` input was a list of numerators then a 2-D
|
| 62 |
+
array with padded zeros for shorter numerators is returned. Otherwise
|
| 63 |
+
returns ``np.asarray(nums)``.
|
| 64 |
+
"""
|
| 65 |
+
try:
|
| 66 |
+
# The statement can throw a ValueError if one
|
| 67 |
+
# of the numerators is a single digit and another
|
| 68 |
+
# is array-like e.g. if nums = [5, [1, 2, 3]]
|
| 69 |
+
nums = cupy.asarray(nums)
|
| 70 |
+
return nums
|
| 71 |
+
|
| 72 |
+
except ValueError:
|
| 73 |
+
nums = [cupy.atleast_1d(num) for num in nums]
|
| 74 |
+
max_width = max(num.size for num in nums)
|
| 75 |
+
|
| 76 |
+
# pre-allocate
|
| 77 |
+
aligned_nums = cupy.zeros((len(nums), max_width))
|
| 78 |
+
|
| 79 |
+
# Create numerators with padded zeros
|
| 80 |
+
for index, num in enumerate(nums):
|
| 81 |
+
aligned_nums[index, -num.size:] = num
|
| 82 |
+
|
| 83 |
+
return aligned_nums
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _polycoeffs_from_zeros(zeros, tol=10):
|
| 87 |
+
# a clone of numpy.poly, simplified
|
| 88 |
+
dtyp = (cupy.complex128
|
| 89 |
+
if cupy.issubdtype(zeros.dtype, cupy.complexfloating)
|
| 90 |
+
else cupy.float64)
|
| 91 |
+
a = cupy.ones(1, dtype=dtyp)
|
| 92 |
+
for z in zeros:
|
| 93 |
+
a = cupy.convolve(a, cupy.r_[1, -z], mode='full')
|
| 94 |
+
|
| 95 |
+
# Use real output if possible.
|
| 96 |
+
if dtyp == cupy.complex128:
|
| 97 |
+
mask = cupy.abs(a.imag) < tol * cupy.finfo(a.dtype).eps
|
| 98 |
+
a.imag[mask] = 0.0
|
| 99 |
+
if mask.shape[0] == a.shape[0]:
|
| 100 |
+
# all imag parts were fp noise
|
| 101 |
+
a = a.real.copy()
|
| 102 |
+
else:
|
| 103 |
+
# if all cmplx roots are complex conj, the coefficients are real
|
| 104 |
+
pos_roots = z[z.imag > 0]
|
| 105 |
+
neg_roots = z[z.imag < 0]
|
| 106 |
+
if pos_roots.shape[0] == neg_roots.shape[0]:
|
| 107 |
+
neg_roots = neg_roots.copy()
|
| 108 |
+
neg_roots.sort()
|
| 109 |
+
pos_roots = pos_roots.copy()
|
| 110 |
+
pos_roots.sort()
|
| 111 |
+
if (neg_roots == pos_roots.conj()).all():
|
| 112 |
+
a = a.real.copy()
|
| 113 |
+
return a
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _nearest_real_complex_idx(fro, to, which):
|
| 117 |
+
"""Get the next closest real or complex element based on distance"""
|
| 118 |
+
assert which in ('real', 'complex', 'any')
|
| 119 |
+
order = cupy.argsort(cupy.abs(fro - to))
|
| 120 |
+
if which == 'any':
|
| 121 |
+
return order[0]
|
| 122 |
+
else:
|
| 123 |
+
mask = cupy.isreal(fro[order])
|
| 124 |
+
if which == 'complex':
|
| 125 |
+
mask = ~mask
|
| 126 |
+
return order[cupy.nonzero(mask)[0][0]]
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _single_zpksos(z, p, k):
|
| 130 |
+
"""Create one second-order section from up to two zeros and poles"""
|
| 131 |
+
sos = cupy.zeros(6)
|
| 132 |
+
b, a = zpk2tf(cupy.asarray(z), cupy.asarray(p), k)
|
| 133 |
+
sos[3-len(b):3] = b
|
| 134 |
+
sos[6-len(a):6] = a
|
| 135 |
+
return sos
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def zpk2sos(z, p, k, pairing=None, *, analog=False):
|
| 139 |
+
"""Return second-order sections from zeros, poles, and gain of a system
|
| 140 |
+
|
| 141 |
+
Parameters
|
| 142 |
+
----------
|
| 143 |
+
z : array_like
|
| 144 |
+
Zeros of the transfer function.
|
| 145 |
+
p : array_like
|
| 146 |
+
Poles of the transfer function.
|
| 147 |
+
k : float
|
| 148 |
+
System gain.
|
| 149 |
+
pairing : {None, 'nearest', 'keep_odd', 'minimal'}, optional
|
| 150 |
+
The method to use to combine pairs of poles and zeros into sections.
|
| 151 |
+
If analog is False and pairing is None, pairing is set to 'nearest';
|
| 152 |
+
if analog is True, pairing must be 'minimal', and is set to that if
|
| 153 |
+
it is None.
|
| 154 |
+
analog : bool, optional
|
| 155 |
+
If True, system is analog, otherwise discrete.
|
| 156 |
+
|
| 157 |
+
Returns
|
| 158 |
+
-------
|
| 159 |
+
sos : ndarray
|
| 160 |
+
Array of second-order filter coefficients, with shape
|
| 161 |
+
``(n_sections, 6)``. See `sosfilt` for the SOS filter format
|
| 162 |
+
specification.
|
| 163 |
+
|
| 164 |
+
See Also
|
| 165 |
+
--------
|
| 166 |
+
sosfilt
|
| 167 |
+
scipy.signal.zpk2sos
|
| 168 |
+
|
| 169 |
+
"""
|
| 170 |
+
if pairing is None:
|
| 171 |
+
pairing = 'minimal' if analog else 'nearest'
|
| 172 |
+
|
| 173 |
+
valid_pairings = ['nearest', 'keep_odd', 'minimal']
|
| 174 |
+
if pairing not in valid_pairings:
|
| 175 |
+
raise ValueError('pairing must be one of %s, not %s'
|
| 176 |
+
% (valid_pairings, pairing))
|
| 177 |
+
|
| 178 |
+
if analog and pairing != 'minimal':
|
| 179 |
+
raise ValueError('for analog zpk2sos conversion, '
|
| 180 |
+
'pairing must be "minimal"')
|
| 181 |
+
|
| 182 |
+
if len(z) == len(p) == 0:
|
| 183 |
+
if not analog:
|
| 184 |
+
return cupy.array([[k, 0., 0., 1., 0., 0.]])
|
| 185 |
+
else:
|
| 186 |
+
return cupy.array([[0., 0., k, 0., 0., 1.]])
|
| 187 |
+
|
| 188 |
+
if pairing != 'minimal':
|
| 189 |
+
# ensure we have the same number of poles and zeros, and make copies
|
| 190 |
+
p = cupy.concatenate((p, cupy.zeros(max(len(z) - len(p), 0))))
|
| 191 |
+
z = cupy.concatenate((z, cupy.zeros(max(len(p) - len(z), 0))))
|
| 192 |
+
n_sections = (max(len(p), len(z)) + 1) // 2
|
| 193 |
+
|
| 194 |
+
if len(p) % 2 == 1 and pairing == 'nearest':
|
| 195 |
+
p = cupy.concatenate((p, cupy.zeros(1)))
|
| 196 |
+
z = cupy.concatenate((z, cupy.zeros(1)))
|
| 197 |
+
assert len(p) == len(z)
|
| 198 |
+
else:
|
| 199 |
+
if len(p) < len(z):
|
| 200 |
+
raise ValueError('for analog zpk2sos conversion, '
|
| 201 |
+
'must have len(p)>=len(z)')
|
| 202 |
+
|
| 203 |
+
n_sections = (len(p) + 1) // 2
|
| 204 |
+
|
| 205 |
+
# Ensure we have complex conjugate pairs
|
| 206 |
+
# (note that _cplxreal only gives us one element of each complex pair):
|
| 207 |
+
z = cupy.concatenate(_cplxreal(z))
|
| 208 |
+
p = cupy.concatenate(_cplxreal(p))
|
| 209 |
+
if not cupy.isreal(k):
|
| 210 |
+
raise ValueError('k must be real')
|
| 211 |
+
k = k.real
|
| 212 |
+
|
| 213 |
+
if not analog:
|
| 214 |
+
# digital: "worst" is the closest to the unit circle
|
| 215 |
+
def idx_worst(p):
|
| 216 |
+
return cupy.argmin(cupy.abs(1 - cupy.abs(p)))
|
| 217 |
+
else:
|
| 218 |
+
# analog: "worst" is the closest to the imaginary axis
|
| 219 |
+
def idx_worst(p):
|
| 220 |
+
return cupy.argmin(cupy.abs(cupy.real(p)))
|
| 221 |
+
|
| 222 |
+
sos = cupy.zeros((n_sections, 6))
|
| 223 |
+
|
| 224 |
+
# Construct the system, reversing order so the "worst" are last
|
| 225 |
+
for si in range(n_sections-1, -1, -1):
|
| 226 |
+
# Select the next "worst" pole
|
| 227 |
+
p1_idx = idx_worst(p)
|
| 228 |
+
p1 = p[p1_idx]
|
| 229 |
+
p = cupy.delete(p, p1_idx)
|
| 230 |
+
|
| 231 |
+
# Pair that pole with a zero
|
| 232 |
+
|
| 233 |
+
if cupy.isreal(p1) and cupy.isreal(p).sum() == 0:
|
| 234 |
+
# Special case (1): last remaining real pole
|
| 235 |
+
if pairing != 'minimal':
|
| 236 |
+
z1_idx = _nearest_real_complex_idx(z, p1, 'real')
|
| 237 |
+
z1 = z[z1_idx]
|
| 238 |
+
z = cupy.delete(z, z1_idx)
|
| 239 |
+
sos[si] = _single_zpksos(cupy.r_[z1, 0], cupy.r_[p1, 0], 1)
|
| 240 |
+
elif len(z) > 0:
|
| 241 |
+
z1_idx = _nearest_real_complex_idx(z, p1, 'real')
|
| 242 |
+
z1 = z[z1_idx]
|
| 243 |
+
z = cupy.delete(z, z1_idx)
|
| 244 |
+
sos[si] = _single_zpksos([z1], [p1], 1)
|
| 245 |
+
else:
|
| 246 |
+
sos[si] = _single_zpksos([], [p1], 1)
|
| 247 |
+
|
| 248 |
+
elif (len(p) + 1 == len(z)
|
| 249 |
+
and not cupy.isreal(p1)
|
| 250 |
+
and cupy.isreal(p).sum() == 1
|
| 251 |
+
and cupy.isreal(z).sum() == 1):
|
| 252 |
+
|
| 253 |
+
# Special case (2): there's one real pole and one real zero
|
| 254 |
+
# left, and an equal number of poles and zeros to pair up.
|
| 255 |
+
# We *must* pair with a complex zero
|
| 256 |
+
|
| 257 |
+
z1_idx = _nearest_real_complex_idx(z, p1, 'complex')
|
| 258 |
+
z1 = z[z1_idx]
|
| 259 |
+
z = cupy.delete(z, z1_idx)
|
| 260 |
+
sos[si] = _single_zpksos(
|
| 261 |
+
cupy.r_[z1, z1.conj()], cupy.r_[p1, p1.conj()], 1)
|
| 262 |
+
|
| 263 |
+
else:
|
| 264 |
+
if cupy.isreal(p1):
|
| 265 |
+
prealidx = cupy.flatnonzero(cupy.isreal(p))
|
| 266 |
+
p2_idx = prealidx[idx_worst(p[prealidx])]
|
| 267 |
+
p2 = p[p2_idx]
|
| 268 |
+
p = cupy.delete(p, p2_idx)
|
| 269 |
+
else:
|
| 270 |
+
p2 = p1.conj()
|
| 271 |
+
|
| 272 |
+
# find closest zero
|
| 273 |
+
if len(z) > 0:
|
| 274 |
+
z1_idx = _nearest_real_complex_idx(z, p1, 'any')
|
| 275 |
+
z1 = z[z1_idx]
|
| 276 |
+
z = cupy.delete(z, z1_idx)
|
| 277 |
+
|
| 278 |
+
if not cupy.isreal(z1):
|
| 279 |
+
sos[si] = _single_zpksos(
|
| 280 |
+
cupy.r_[z1, z1.conj()], cupy.r_[p1, p2], 1)
|
| 281 |
+
else:
|
| 282 |
+
if len(z) > 0:
|
| 283 |
+
z2_idx = _nearest_real_complex_idx(z, p1, 'real')
|
| 284 |
+
z2 = z[z2_idx]
|
| 285 |
+
assert cupy.isreal(z2)
|
| 286 |
+
z = cupy.delete(z, z2_idx)
|
| 287 |
+
sos[si] = _single_zpksos(cupy.r_[z1, z2], [p1, p2], 1)
|
| 288 |
+
else:
|
| 289 |
+
sos[si] = _single_zpksos([z1], [p1, p2], 1)
|
| 290 |
+
else:
|
| 291 |
+
# no more zeros
|
| 292 |
+
sos[si] = _single_zpksos([], [p1, p2], 1)
|
| 293 |
+
|
| 294 |
+
assert len(p) == len(z) == 0 # we've consumed all poles and zeros
|
| 295 |
+
del p, z
|
| 296 |
+
|
| 297 |
+
# put gain in first sos
|
| 298 |
+
sos[0][:3] *= k
|
| 299 |
+
return sos
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def _cplxreal(z, tol=None):
|
| 303 |
+
"""
|
| 304 |
+
Split into complex and real parts, combining conjugate pairs.
|
| 305 |
+
|
| 306 |
+
The 1-D input vector `z` is split up into its complex (zc) and real (zr)
|
| 307 |
+
elements. Every complex element must be part of a complex-conjugate pair,
|
| 308 |
+
which are combined into a single number (with positive imaginary part) in
|
| 309 |
+
the output. Two complex numbers are considered a conjugate pair if their
|
| 310 |
+
real and imaginary parts differ in magnitude by less than ``tol * abs(z)``.
|
| 311 |
+
|
| 312 |
+
Parameters
|
| 313 |
+
----------
|
| 314 |
+
z : array_like
|
| 315 |
+
Vector of complex numbers to be sorted and split
|
| 316 |
+
tol : float, optional
|
| 317 |
+
Relative tolerance for testing realness and conjugate equality.
|
| 318 |
+
Default is ``100 * spacing(1)`` of `z`'s data type (i.e., 2e-14 for
|
| 319 |
+
float64)
|
| 320 |
+
|
| 321 |
+
Returns
|
| 322 |
+
-------
|
| 323 |
+
zc : ndarray
|
| 324 |
+
Complex elements of `z`, with each pair represented by a single value
|
| 325 |
+
having positive imaginary part, sorted first by real part, and then
|
| 326 |
+
by magnitude of imaginary part. The pairs are averaged when combined
|
| 327 |
+
to reduce error.
|
| 328 |
+
zr : ndarray
|
| 329 |
+
Real elements of `z` (those having imaginary part less than
|
| 330 |
+
`tol` times their magnitude), sorted by value.
|
| 331 |
+
|
| 332 |
+
Raises
|
| 333 |
+
------
|
| 334 |
+
ValueError
|
| 335 |
+
If there are any complex numbers in `z` for which a conjugate
|
| 336 |
+
cannot be found.
|
| 337 |
+
|
| 338 |
+
See Also
|
| 339 |
+
--------
|
| 340 |
+
scipy.signal.cmplxreal
|
| 341 |
+
|
| 342 |
+
Examples
|
| 343 |
+
--------
|
| 344 |
+
>>> a = [4, 3, 1, 2-2j, 2+2j, 2-1j, 2+1j, 2-1j, 2+1j, 1+1j, 1-1j]
|
| 345 |
+
>>> zc, zr = _cplxreal(a)
|
| 346 |
+
>>> print(zc)
|
| 347 |
+
[ 1.+1.j 2.+1.j 2.+1.j 2.+2.j]
|
| 348 |
+
>>> print(zr)
|
| 349 |
+
[ 1. 3. 4.]
|
| 350 |
+
"""
|
| 351 |
+
|
| 352 |
+
z = cupy.atleast_1d(z)
|
| 353 |
+
if z.size == 0:
|
| 354 |
+
return z, z
|
| 355 |
+
elif z.ndim != 1:
|
| 356 |
+
raise ValueError('_cplxreal only accepts 1-D input')
|
| 357 |
+
|
| 358 |
+
if tol is None:
|
| 359 |
+
# Get tolerance from dtype of input
|
| 360 |
+
tol = 100 * cupy.finfo((1.0 * z).dtype).eps
|
| 361 |
+
|
| 362 |
+
# Sort by real part, magnitude of imaginary part (speed up further sorting)
|
| 363 |
+
z = z[cupy.lexsort(cupy.array([abs(z.imag), z.real]))]
|
| 364 |
+
|
| 365 |
+
# Split reals from conjugate pairs
|
| 366 |
+
real_indices = abs(z.imag) <= tol * abs(z)
|
| 367 |
+
zr = z[real_indices].real
|
| 368 |
+
|
| 369 |
+
if len(zr) == len(z):
|
| 370 |
+
# Input is entirely real
|
| 371 |
+
return cupy.array([]), zr
|
| 372 |
+
|
| 373 |
+
# Split positive and negative halves of conjugates
|
| 374 |
+
z = z[~real_indices]
|
| 375 |
+
zp = z[z.imag > 0]
|
| 376 |
+
zn = z[z.imag < 0]
|
| 377 |
+
|
| 378 |
+
if len(zp) != len(zn):
|
| 379 |
+
raise ValueError('Array contains complex value with no matching '
|
| 380 |
+
'conjugate.')
|
| 381 |
+
|
| 382 |
+
# Find runs of (approximately) the same real part
|
| 383 |
+
same_real = cupy.diff(zp.real) <= tol * abs(zp[:-1])
|
| 384 |
+
diffs = cupy.diff(cupy.r_[0, same_real, 0])
|
| 385 |
+
run_starts = cupy.nonzero(diffs > 0)[0]
|
| 386 |
+
run_stops = cupy.nonzero(diffs < 0)[0]
|
| 387 |
+
|
| 388 |
+
# Sort each run by their imaginary parts
|
| 389 |
+
for i in range(len(run_starts)):
|
| 390 |
+
start = run_starts[i]
|
| 391 |
+
stop = run_stops[i] + 1
|
| 392 |
+
for chunk in (zp[start:stop], zn[start:stop]):
|
| 393 |
+
chunk[...] = chunk[cupy.lexsort(cupy.array([abs(chunk.imag)]))]
|
| 394 |
+
|
| 395 |
+
# Check that negatives match positives
|
| 396 |
+
if any(abs(zp - zn.conj()) > tol * abs(zn)):
|
| 397 |
+
raise ValueError('Array contains complex value with no matching '
|
| 398 |
+
'conjugate.')
|
| 399 |
+
|
| 400 |
+
# Average out numerical inaccuracy in real vs imag parts of pairs
|
| 401 |
+
zc = (zp + zn.conj()) / 2
|
| 402 |
+
|
| 403 |
+
return zc, zr
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def normalize(b, a):
|
| 407 |
+
"""Normalize numerator/denominator of a continuous-time transfer function.
|
| 408 |
+
|
| 409 |
+
If values of `b` are too close to 0, they are removed. In that case, a
|
| 410 |
+
BadCoefficients warning is emitted.
|
| 411 |
+
|
| 412 |
+
Parameters
|
| 413 |
+
----------
|
| 414 |
+
b: array_like
|
| 415 |
+
Numerator of the transfer function. Can be a 2-D array to normalize
|
| 416 |
+
multiple transfer functions.
|
| 417 |
+
a: array_like
|
| 418 |
+
Denominator of the transfer function. At most 1-D.
|
| 419 |
+
|
| 420 |
+
Returns
|
| 421 |
+
-------
|
| 422 |
+
num: array
|
| 423 |
+
The numerator of the normalized transfer function. At least a 1-D
|
| 424 |
+
array. A 2-D array if the input `num` is a 2-D array.
|
| 425 |
+
den: 1-D array
|
| 426 |
+
The denominator of the normalized transfer function.
|
| 427 |
+
|
| 428 |
+
Notes
|
| 429 |
+
-----
|
| 430 |
+
Coefficients for both the numerator and denominator should be specified in
|
| 431 |
+
descending exponent order (e.g., ``s^2 + 3s + 5`` would be represented as
|
| 432 |
+
``[1, 3, 5]``).
|
| 433 |
+
|
| 434 |
+
See Also
|
| 435 |
+
--------
|
| 436 |
+
scipy.signal.normalize
|
| 437 |
+
|
| 438 |
+
"""
|
| 439 |
+
num, den = b, a
|
| 440 |
+
|
| 441 |
+
den = cupy.atleast_1d(den)
|
| 442 |
+
num = cupy.atleast_2d(_align_nums(num))
|
| 443 |
+
|
| 444 |
+
if den.ndim != 1:
|
| 445 |
+
raise ValueError("Denominator polynomial must be rank-1 array.")
|
| 446 |
+
if num.ndim > 2:
|
| 447 |
+
raise ValueError("Numerator polynomial must be rank-1 or"
|
| 448 |
+
" rank-2 array.")
|
| 449 |
+
if cupy.all(den == 0):
|
| 450 |
+
raise ValueError("Denominator must have at least on nonzero element.")
|
| 451 |
+
|
| 452 |
+
# Trim leading zeros in denominator, leave at least one.
|
| 453 |
+
den = _trim_zeros(den, 'f')
|
| 454 |
+
|
| 455 |
+
# Normalize transfer function
|
| 456 |
+
num, den = num / den[0], den / den[0]
|
| 457 |
+
|
| 458 |
+
# Count numerator columns that are all zero
|
| 459 |
+
leading_zeros = 0
|
| 460 |
+
for col in num.T:
|
| 461 |
+
if cupy.allclose(col, 0, atol=1e-14):
|
| 462 |
+
leading_zeros += 1
|
| 463 |
+
else:
|
| 464 |
+
break
|
| 465 |
+
|
| 466 |
+
# Trim leading zeros of numerator
|
| 467 |
+
if leading_zeros > 0:
|
| 468 |
+
warnings.warn("Badly conditioned filter coefficients (numerator): the "
|
| 469 |
+
"results may be meaningless", BadCoefficients)
|
| 470 |
+
# Make sure at least one column remains
|
| 471 |
+
if leading_zeros == num.shape[1]:
|
| 472 |
+
leading_zeros -= 1
|
| 473 |
+
num = num[:, leading_zeros:]
|
| 474 |
+
|
| 475 |
+
# Squeeze first dimension if singular
|
| 476 |
+
if num.shape[0] == 1:
|
| 477 |
+
num = num[0, :]
|
| 478 |
+
|
| 479 |
+
return num, den
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def _relative_degree(z, p):
|
| 483 |
+
"""
|
| 484 |
+
Return relative degree of transfer function from zeros and poles
|
| 485 |
+
"""
|
| 486 |
+
degree = len(p) - len(z)
|
| 487 |
+
if degree < 0:
|
| 488 |
+
raise ValueError("Improper transfer function. "
|
| 489 |
+
"Must have at least as many poles as zeros.")
|
| 490 |
+
else:
|
| 491 |
+
return degree
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def bilinear_zpk(z, p, k, fs):
|
| 495 |
+
r"""
|
| 496 |
+
Return a digital IIR filter from an analog one using a bilinear transform.
|
| 497 |
+
|
| 498 |
+
Transform a set of poles and zeros from the analog s-plane to the digital
|
| 499 |
+
z-plane using Tustin's method, which substitutes ``2*fs*(z-1) / (z+1)`` for
|
| 500 |
+
``s``, maintaining the shape of the frequency response.
|
| 501 |
+
|
| 502 |
+
Parameters
|
| 503 |
+
----------
|
| 504 |
+
z : array_like
|
| 505 |
+
Zeros of the analog filter transfer function.
|
| 506 |
+
p : array_like
|
| 507 |
+
Poles of the analog filter transfer function.
|
| 508 |
+
k : float
|
| 509 |
+
System gain of the analog filter transfer function.
|
| 510 |
+
fs : float
|
| 511 |
+
Sample rate, as ordinary frequency (e.g., hertz). No prewarping is
|
| 512 |
+
done in this function.
|
| 513 |
+
|
| 514 |
+
Returns
|
| 515 |
+
-------
|
| 516 |
+
z : ndarray
|
| 517 |
+
Zeros of the transformed digital filter transfer function.
|
| 518 |
+
p : ndarray
|
| 519 |
+
Poles of the transformed digital filter transfer function.
|
| 520 |
+
k : float
|
| 521 |
+
System gain of the transformed digital filter.
|
| 522 |
+
|
| 523 |
+
See Also
|
| 524 |
+
--------
|
| 525 |
+
lp2lp_zpk, lp2hp_zpk, lp2bp_zpk, lp2bs_zpk
|
| 526 |
+
bilinear
|
| 527 |
+
scipy.signal.bilinear_zpk
|
| 528 |
+
|
| 529 |
+
"""
|
| 530 |
+
z = cupy.atleast_1d(z)
|
| 531 |
+
p = cupy.atleast_1d(p)
|
| 532 |
+
|
| 533 |
+
degree = _relative_degree(z, p)
|
| 534 |
+
|
| 535 |
+
fs2 = 2.0 * fs
|
| 536 |
+
|
| 537 |
+
# Bilinear transform the poles and zeros
|
| 538 |
+
z_z = (fs2 + z) / (fs2 - z)
|
| 539 |
+
p_z = (fs2 + p) / (fs2 - p)
|
| 540 |
+
|
| 541 |
+
# Any zeros that were at infinity get moved to the Nyquist frequency
|
| 542 |
+
z_z = cupy.append(z_z, -cupy.ones(degree))
|
| 543 |
+
|
| 544 |
+
# Compensate for gain change
|
| 545 |
+
k_z = k * (cupy.prod(fs2 - z) / cupy.prod(fs2 - p)).real
|
| 546 |
+
|
| 547 |
+
return z_z, p_z, k_z
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def lp2lp_zpk(z, p, k, wo=1.0):
|
| 551 |
+
r"""
|
| 552 |
+
Transform a lowpass filter prototype to a different frequency.
|
| 553 |
+
|
| 554 |
+
Return an analog low-pass filter with cutoff frequency `wo`
|
| 555 |
+
from an analog low-pass filter prototype with unity cutoff frequency,
|
| 556 |
+
using zeros, poles, and gain ('zpk') representation.
|
| 557 |
+
|
| 558 |
+
Parameters
|
| 559 |
+
----------
|
| 560 |
+
z : array_like
|
| 561 |
+
Zeros of the analog filter transfer function.
|
| 562 |
+
p : array_like
|
| 563 |
+
Poles of the analog filter transfer function.
|
| 564 |
+
k : float
|
| 565 |
+
System gain of the analog filter transfer function.
|
| 566 |
+
wo : float
|
| 567 |
+
Desired cutoff, as angular frequency (e.g., rad/s).
|
| 568 |
+
Defaults to no change.
|
| 569 |
+
|
| 570 |
+
Returns
|
| 571 |
+
-------
|
| 572 |
+
z : ndarray
|
| 573 |
+
Zeros of the transformed low-pass filter transfer function.
|
| 574 |
+
p : ndarray
|
| 575 |
+
Poles of the transformed low-pass filter transfer function.
|
| 576 |
+
k : float
|
| 577 |
+
System gain of the transformed low-pass filter.
|
| 578 |
+
|
| 579 |
+
See Also
|
| 580 |
+
--------
|
| 581 |
+
lp2hp_zpk, lp2bp_zpk, lp2bs_zpk, bilinear
|
| 582 |
+
lp2lp
|
| 583 |
+
scipy.signal.lp2lp_zpk
|
| 584 |
+
|
| 585 |
+
"""
|
| 586 |
+
z = cupy.atleast_1d(z)
|
| 587 |
+
p = cupy.atleast_1d(p)
|
| 588 |
+
wo = float(wo) # Avoid int wraparound
|
| 589 |
+
|
| 590 |
+
degree = _relative_degree(z, p)
|
| 591 |
+
|
| 592 |
+
# Scale all points radially from origin to shift cutoff frequency
|
| 593 |
+
z_lp = wo * z
|
| 594 |
+
p_lp = wo * p
|
| 595 |
+
|
| 596 |
+
# Each shifted pole decreases gain by wo, each shifted zero increases it.
|
| 597 |
+
# Cancel out the net change to keep overall gain the same
|
| 598 |
+
k_lp = k * wo**degree
|
| 599 |
+
|
| 600 |
+
return z_lp, p_lp, k_lp
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def lp2hp_zpk(z, p, k, wo=1.0):
|
| 604 |
+
r"""
|
| 605 |
+
Transform a lowpass filter prototype to a highpass filter.
|
| 606 |
+
|
| 607 |
+
Return an analog high-pass filter with cutoff frequency `wo`
|
| 608 |
+
from an analog low-pass filter prototype with unity cutoff frequency,
|
| 609 |
+
using zeros, poles, and gain ('zpk') representation.
|
| 610 |
+
|
| 611 |
+
Parameters
|
| 612 |
+
----------
|
| 613 |
+
z : array_like
|
| 614 |
+
Zeros of the analog filter transfer function.
|
| 615 |
+
p : array_like
|
| 616 |
+
Poles of the analog filter transfer function.
|
| 617 |
+
k : float
|
| 618 |
+
System gain of the analog filter transfer function.
|
| 619 |
+
wo : float
|
| 620 |
+
Desired cutoff, as angular frequency (e.g., rad/s).
|
| 621 |
+
Defaults to no change.
|
| 622 |
+
|
| 623 |
+
Returns
|
| 624 |
+
-------
|
| 625 |
+
z : ndarray
|
| 626 |
+
Zeros of the transformed high-pass filter transfer function.
|
| 627 |
+
p : ndarray
|
| 628 |
+
Poles of the transformed high-pass filter transfer function.
|
| 629 |
+
k : float
|
| 630 |
+
System gain of the transformed high-pass filter.
|
| 631 |
+
|
| 632 |
+
See Also
|
| 633 |
+
--------
|
| 634 |
+
lp2lp_zpk, lp2bp_zpk, lp2bs_zpk, bilinear
|
| 635 |
+
lp2hp
|
| 636 |
+
scipy.signal.lp2hp_zpk
|
| 637 |
+
|
| 638 |
+
Notes
|
| 639 |
+
-----
|
| 640 |
+
This is derived from the s-plane substitution
|
| 641 |
+
|
| 642 |
+
.. math:: s \rightarrow \frac{\omega_0}{s}
|
| 643 |
+
|
| 644 |
+
This maintains symmetry of the lowpass and highpass responses on a
|
| 645 |
+
logarithmic scale.
|
| 646 |
+
|
| 647 |
+
"""
|
| 648 |
+
z = cupy.atleast_1d(z)
|
| 649 |
+
p = cupy.atleast_1d(p)
|
| 650 |
+
wo = float(wo)
|
| 651 |
+
|
| 652 |
+
degree = _relative_degree(z, p)
|
| 653 |
+
|
| 654 |
+
# Invert positions radially about unit circle to convert LPF to HPF
|
| 655 |
+
# Scale all points radially from origin to shift cutoff frequency
|
| 656 |
+
z_hp = wo / z
|
| 657 |
+
p_hp = wo / p
|
| 658 |
+
|
| 659 |
+
# If lowpass had zeros at infinity, inverting moves them to origin.
|
| 660 |
+
z_hp = cupy.append(z_hp, cupy.zeros(degree))
|
| 661 |
+
|
| 662 |
+
# Cancel out gain change caused by inversion
|
| 663 |
+
k_hp = k * cupy.real(cupy.prod(-z) / cupy.prod(-p))
|
| 664 |
+
|
| 665 |
+
return z_hp, p_hp, k_hp
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
def lp2bp_zpk(z, p, k, wo=1.0, bw=1.0):
|
| 669 |
+
r"""
|
| 670 |
+
Transform a lowpass filter prototype to a bandpass filter.
|
| 671 |
+
|
| 672 |
+
Return an analog band-pass filter with center frequency `wo` and
|
| 673 |
+
bandwidth `bw` from an analog low-pass filter prototype with unity
|
| 674 |
+
cutoff frequency, using zeros, poles, and gain ('zpk') representation.
|
| 675 |
+
|
| 676 |
+
Parameters
|
| 677 |
+
----------
|
| 678 |
+
z : array_like
|
| 679 |
+
Zeros of the analog filter transfer function.
|
| 680 |
+
p : array_like
|
| 681 |
+
Poles of the analog filter transfer function.
|
| 682 |
+
k : float
|
| 683 |
+
System gain of the analog filter transfer function.
|
| 684 |
+
wo : float
|
| 685 |
+
Desired passband center, as angular frequency (e.g., rad/s).
|
| 686 |
+
Defaults to no change.
|
| 687 |
+
bw : float
|
| 688 |
+
Desired passband width, as angular frequency (e.g., rad/s).
|
| 689 |
+
Defaults to 1.
|
| 690 |
+
|
| 691 |
+
Returns
|
| 692 |
+
-------
|
| 693 |
+
z : ndarray
|
| 694 |
+
Zeros of the transformed band-pass filter transfer function.
|
| 695 |
+
p : ndarray
|
| 696 |
+
Poles of the transformed band-pass filter transfer function.
|
| 697 |
+
k : float
|
| 698 |
+
System gain of the transformed band-pass filter.
|
| 699 |
+
|
| 700 |
+
See Also
|
| 701 |
+
--------
|
| 702 |
+
lp2lp_zpk, lp2hp_zpk, lp2bs_zpk, bilinear
|
| 703 |
+
lp2bp
|
| 704 |
+
scipy.signal.lp2bp_zpk
|
| 705 |
+
|
| 706 |
+
Notes
|
| 707 |
+
-----
|
| 708 |
+
This is derived from the s-plane substitution
|
| 709 |
+
|
| 710 |
+
.. math:: s \rightarrow \frac{s^2 + {\omega_0}^2}{s \cdot \mathrm{BW}}
|
| 711 |
+
|
| 712 |
+
This is the "wideband" transformation, producing a passband with
|
| 713 |
+
geometric (log frequency) symmetry about `wo`.
|
| 714 |
+
|
| 715 |
+
"""
|
| 716 |
+
z = cupy.atleast_1d(z)
|
| 717 |
+
p = cupy.atleast_1d(p)
|
| 718 |
+
wo = float(wo)
|
| 719 |
+
bw = float(bw)
|
| 720 |
+
|
| 721 |
+
degree = _relative_degree(z, p)
|
| 722 |
+
|
| 723 |
+
# Scale poles and zeros to desired bandwidth
|
| 724 |
+
z_lp = z * bw/2
|
| 725 |
+
p_lp = p * bw/2
|
| 726 |
+
|
| 727 |
+
# Square root needs to produce complex result, not NaN
|
| 728 |
+
z_lp = z_lp.astype(complex)
|
| 729 |
+
p_lp = p_lp.astype(complex)
|
| 730 |
+
|
| 731 |
+
# Duplicate poles and zeros and shift from baseband to +wo and -wo
|
| 732 |
+
z_bp = cupy.concatenate((z_lp + cupy.sqrt(z_lp**2 - wo**2),
|
| 733 |
+
z_lp - cupy.sqrt(z_lp**2 - wo**2)))
|
| 734 |
+
p_bp = cupy.concatenate((p_lp + cupy.sqrt(p_lp**2 - wo**2),
|
| 735 |
+
p_lp - cupy.sqrt(p_lp**2 - wo**2)))
|
| 736 |
+
|
| 737 |
+
# Move degree zeros to origin, leaving degree zeros at infinity for BPF
|
| 738 |
+
z_bp = cupy.append(z_bp, cupy.zeros(degree))
|
| 739 |
+
|
| 740 |
+
# Cancel out gain change from frequency scaling
|
| 741 |
+
k_bp = k * bw**degree
|
| 742 |
+
|
| 743 |
+
return z_bp, p_bp, k_bp
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
def lp2bs_zpk(z, p, k, wo=1.0, bw=1.0):
|
| 747 |
+
r"""
|
| 748 |
+
Transform a lowpass filter prototype to a bandstop filter.
|
| 749 |
+
|
| 750 |
+
Return an analog band-stop filter with center frequency `wo` and
|
| 751 |
+
stopband width `bw` from an analog low-pass filter prototype with unity
|
| 752 |
+
cutoff frequency, using zeros, poles, and gain ('zpk') representation.
|
| 753 |
+
|
| 754 |
+
Parameters
|
| 755 |
+
----------
|
| 756 |
+
z : array_like
|
| 757 |
+
Zeros of the analog filter transfer function.
|
| 758 |
+
p : array_like
|
| 759 |
+
Poles of the analog filter transfer function.
|
| 760 |
+
k : float
|
| 761 |
+
System gain of the analog filter transfer function.
|
| 762 |
+
wo : float
|
| 763 |
+
Desired stopband center, as angular frequency (e.g., rad/s).
|
| 764 |
+
Defaults to no change.
|
| 765 |
+
bw : float
|
| 766 |
+
Desired stopband width, as angular frequency (e.g., rad/s).
|
| 767 |
+
Defaults to 1.
|
| 768 |
+
|
| 769 |
+
Returns
|
| 770 |
+
-------
|
| 771 |
+
z : ndarray
|
| 772 |
+
Zeros of the transformed band-stop filter transfer function.
|
| 773 |
+
p : ndarray
|
| 774 |
+
Poles of the transformed band-stop filter transfer function.
|
| 775 |
+
k : float
|
| 776 |
+
System gain of the transformed band-stop filter.
|
| 777 |
+
|
| 778 |
+
See Also
|
| 779 |
+
--------
|
| 780 |
+
lp2lp_zpk, lp2hp_zpk, lp2bp_zpk, bilinear
|
| 781 |
+
lp2bs
|
| 782 |
+
scipy.signal.lp2bs_zpk
|
| 783 |
+
|
| 784 |
+
Notes
|
| 785 |
+
-----
|
| 786 |
+
This is derived from the s-plane substitution
|
| 787 |
+
|
| 788 |
+
.. math:: s \rightarrow \frac{s \cdot \mathrm{BW}}{s^2 + {\omega_0}^2}
|
| 789 |
+
|
| 790 |
+
This is the "wideband" transformation, producing a stopband with
|
| 791 |
+
geometric (log frequency) symmetry about `wo`.
|
| 792 |
+
|
| 793 |
+
"""
|
| 794 |
+
z = cupy.atleast_1d(z)
|
| 795 |
+
p = cupy.atleast_1d(p)
|
| 796 |
+
wo = float(wo)
|
| 797 |
+
bw = float(bw)
|
| 798 |
+
|
| 799 |
+
degree = _relative_degree(z, p)
|
| 800 |
+
|
| 801 |
+
# Invert to a highpass filter with desired bandwidth
|
| 802 |
+
z_hp = (bw/2) / z
|
| 803 |
+
p_hp = (bw/2) / p
|
| 804 |
+
|
| 805 |
+
# Square root needs to produce complex result, not NaN
|
| 806 |
+
z_hp = z_hp.astype(complex)
|
| 807 |
+
p_hp = p_hp.astype(complex)
|
| 808 |
+
|
| 809 |
+
# Duplicate poles and zeros and shift from baseband to +wo and -wo
|
| 810 |
+
z_bs = cupy.concatenate((z_hp + cupy.sqrt(z_hp**2 - wo**2),
|
| 811 |
+
z_hp - cupy.sqrt(z_hp**2 - wo**2)))
|
| 812 |
+
p_bs = cupy.concatenate((p_hp + cupy.sqrt(p_hp**2 - wo**2),
|
| 813 |
+
p_hp - cupy.sqrt(p_hp**2 - wo**2)))
|
| 814 |
+
|
| 815 |
+
# Move any zeros that were at infinity to the center of the stopband
|
| 816 |
+
z_bs = cupy.append(z_bs, cupy.full(degree, +1j*wo))
|
| 817 |
+
z_bs = cupy.append(z_bs, cupy.full(degree, -1j*wo))
|
| 818 |
+
|
| 819 |
+
# Cancel out gain change caused by inversion
|
| 820 |
+
k_bs = k * cupy.real(cupy.prod(-z) / cupy.prod(-p))
|
| 821 |
+
|
| 822 |
+
return z_bs, p_bs, k_bs
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
def bilinear(b, a, fs=1.0):
|
| 826 |
+
r"""
|
| 827 |
+
Return a digital IIR filter from an analog one using a bilinear transform.
|
| 828 |
+
|
| 829 |
+
Transform a set of poles and zeros from the analog s-plane to the digital
|
| 830 |
+
z-plane using Tustin's method, which substitutes ``2*fs*(z-1) / (z+1)`` for
|
| 831 |
+
``s``, maintaining the shape of the frequency response.
|
| 832 |
+
|
| 833 |
+
Parameters
|
| 834 |
+
----------
|
| 835 |
+
b : array_like
|
| 836 |
+
Numerator of the analog filter transfer function.
|
| 837 |
+
a : array_like
|
| 838 |
+
Denominator of the analog filter transfer function.
|
| 839 |
+
fs : float
|
| 840 |
+
Sample rate, as ordinary frequency (e.g., hertz). No prewarping is
|
| 841 |
+
done in this function.
|
| 842 |
+
|
| 843 |
+
Returns
|
| 844 |
+
-------
|
| 845 |
+
b : ndarray
|
| 846 |
+
Numerator of the transformed digital filter transfer function.
|
| 847 |
+
a : ndarray
|
| 848 |
+
Denominator of the transformed digital filter transfer function.
|
| 849 |
+
|
| 850 |
+
See Also
|
| 851 |
+
--------
|
| 852 |
+
lp2lp, lp2hp, lp2bp, lp2bs
|
| 853 |
+
bilinear_zpk
|
| 854 |
+
scipy.signal.bilinear
|
| 855 |
+
|
| 856 |
+
"""
|
| 857 |
+
fs = float(fs)
|
| 858 |
+
a, b = map(cupy.atleast_1d, (a, b))
|
| 859 |
+
D = a.shape[0] - 1
|
| 860 |
+
N = b.shape[0] - 1
|
| 861 |
+
|
| 862 |
+
M = max(N, D)
|
| 863 |
+
Np, Dp = M, M
|
| 864 |
+
|
| 865 |
+
bprime = cupy.empty(Np + 1, float)
|
| 866 |
+
aprime = cupy.empty(Dp + 1, float)
|
| 867 |
+
|
| 868 |
+
# XXX (ev-br): worth turning into a ufunc invocation? (loops are short)
|
| 869 |
+
for j in range(Dp + 1):
|
| 870 |
+
val = 0.0
|
| 871 |
+
for i in range(N + 1):
|
| 872 |
+
bNi = b[N - i] * (2 * fs)**i
|
| 873 |
+
for k in range(i + 1):
|
| 874 |
+
for s in range(M - i + 1):
|
| 875 |
+
if k + s == j:
|
| 876 |
+
val += comb(i, k) * comb(M - i, s) * bNi * (-1)**k
|
| 877 |
+
bprime[j] = cupy.real(val)
|
| 878 |
+
|
| 879 |
+
for j in range(Dp + 1):
|
| 880 |
+
val = 0.0
|
| 881 |
+
for i in range(D + 1):
|
| 882 |
+
aDi = a[D - i] * (2 * fs)**i
|
| 883 |
+
for k in range(i + 1):
|
| 884 |
+
for s in range(M - i + 1):
|
| 885 |
+
if k + s == j:
|
| 886 |
+
val += comb(i, k) * comb(M - i, s) * aDi * (-1)**k
|
| 887 |
+
aprime[j] = cupy.real(val)
|
| 888 |
+
|
| 889 |
+
return normalize(bprime, aprime)
|
| 890 |
+
|
| 891 |
+
|
| 892 |
+
def lp2lp(b, a, wo=1.0):
|
| 893 |
+
r"""
|
| 894 |
+
Transform a lowpass filter prototype to a different frequency.
|
| 895 |
+
|
| 896 |
+
Return an analog low-pass filter with cutoff frequency `wo`
|
| 897 |
+
from an analog low-pass filter prototype with unity cutoff frequency, in
|
| 898 |
+
transfer function ('ba') representation.
|
| 899 |
+
|
| 900 |
+
Parameters
|
| 901 |
+
----------
|
| 902 |
+
b : array_like
|
| 903 |
+
Numerator polynomial coefficients.
|
| 904 |
+
a : array_like
|
| 905 |
+
Denominator polynomial coefficients.
|
| 906 |
+
wo : float
|
| 907 |
+
Desired cutoff, as angular frequency (e.g. rad/s).
|
| 908 |
+
Defaults to no change.
|
| 909 |
+
|
| 910 |
+
Returns
|
| 911 |
+
-------
|
| 912 |
+
b : array_like
|
| 913 |
+
Numerator polynomial coefficients of the transformed low-pass filter.
|
| 914 |
+
a : array_like
|
| 915 |
+
Denominator polynomial coefficients of the transformed low-pass filter.
|
| 916 |
+
|
| 917 |
+
See Also
|
| 918 |
+
--------
|
| 919 |
+
lp2hp, lp2bp, lp2bs, bilinear
|
| 920 |
+
lp2lp_zpk
|
| 921 |
+
scipy.signal.lp2lp
|
| 922 |
+
|
| 923 |
+
Notes
|
| 924 |
+
-----
|
| 925 |
+
This is derived from the s-plane substitution
|
| 926 |
+
|
| 927 |
+
.. math:: s \rightarrow \frac{s}{\omega_0}
|
| 928 |
+
|
| 929 |
+
"""
|
| 930 |
+
a, b = map(cupy.atleast_1d, (a, b))
|
| 931 |
+
try:
|
| 932 |
+
wo = float(wo)
|
| 933 |
+
except TypeError:
|
| 934 |
+
wo = float(wo[0])
|
| 935 |
+
d = len(a)
|
| 936 |
+
n = len(b)
|
| 937 |
+
M = max(d, n)
|
| 938 |
+
pwo = wo ** cupy.arange(M - 1, -1, -1)
|
| 939 |
+
start1 = max((n - d, 0))
|
| 940 |
+
start2 = max((d - n, 0))
|
| 941 |
+
b = b * pwo[start1] / pwo[start2:]
|
| 942 |
+
a = a * pwo[start1] / pwo[start1:]
|
| 943 |
+
return normalize(b, a)
|
| 944 |
+
|
| 945 |
+
|
| 946 |
+
def lp2hp(b, a, wo=1.0):
|
| 947 |
+
r"""
|
| 948 |
+
Transform a lowpass filter prototype to a highpass filter.
|
| 949 |
+
|
| 950 |
+
Return an analog high-pass filter with cutoff frequency `wo`
|
| 951 |
+
from an analog low-pass filter prototype with unity cutoff frequency, in
|
| 952 |
+
transfer function ('ba') representation.
|
| 953 |
+
|
| 954 |
+
Parameters
|
| 955 |
+
----------
|
| 956 |
+
b : array_like
|
| 957 |
+
Numerator polynomial coefficients.
|
| 958 |
+
a : array_like
|
| 959 |
+
Denominator polynomial coefficients.
|
| 960 |
+
wo : float
|
| 961 |
+
Desired cutoff, as angular frequency (e.g., rad/s).
|
| 962 |
+
Defaults to no change.
|
| 963 |
+
|
| 964 |
+
Returns
|
| 965 |
+
-------
|
| 966 |
+
b : array_like
|
| 967 |
+
Numerator polynomial coefficients of the transformed high-pass filter.
|
| 968 |
+
a : array_like
|
| 969 |
+
Denominator polynomial coefficients of the transformed high-pass
|
| 970 |
+
filter.
|
| 971 |
+
|
| 972 |
+
See Also
|
| 973 |
+
--------
|
| 974 |
+
lp2lp, lp2bp, lp2bs, bilinear
|
| 975 |
+
lp2hp_zpk
|
| 976 |
+
scipy.signal.lp2hp
|
| 977 |
+
|
| 978 |
+
Notes
|
| 979 |
+
-----
|
| 980 |
+
This is derived from the s-plane substitution
|
| 981 |
+
|
| 982 |
+
.. math:: s \rightarrow \frac{\omega_0}{s}
|
| 983 |
+
|
| 984 |
+
This maintains symmetry of the lowpass and highpass responses on a
|
| 985 |
+
logarithmic scale.
|
| 986 |
+
"""
|
| 987 |
+
a, b = map(cupy.atleast_1d, (a, b))
|
| 988 |
+
try:
|
| 989 |
+
wo = float(wo)
|
| 990 |
+
except TypeError:
|
| 991 |
+
wo = float(wo[0])
|
| 992 |
+
d = len(a)
|
| 993 |
+
n = len(b)
|
| 994 |
+
if wo != 1:
|
| 995 |
+
pwo = wo ** cupy.arange(max(d, n))
|
| 996 |
+
else:
|
| 997 |
+
pwo = cupy.ones(max(d, n), b.dtype)
|
| 998 |
+
if d >= n:
|
| 999 |
+
outa = a[::-1] * pwo
|
| 1000 |
+
outb = cupy.resize(b, (d,))
|
| 1001 |
+
outb[n:] = 0.0
|
| 1002 |
+
outb[:n] = b[::-1] * pwo[:n]
|
| 1003 |
+
else:
|
| 1004 |
+
outb = b[::-1] * pwo
|
| 1005 |
+
outa = cupy.resize(a, (n,))
|
| 1006 |
+
outa[d:] = 0.0
|
| 1007 |
+
outa[:d] = a[::-1] * pwo[:d]
|
| 1008 |
+
|
| 1009 |
+
return normalize(outb, outa)
|
| 1010 |
+
|
| 1011 |
+
|
| 1012 |
+
def lp2bp(b, a, wo=1.0, bw=1.0):
|
| 1013 |
+
r"""
|
| 1014 |
+
Transform a lowpass filter prototype to a bandpass filter.
|
| 1015 |
+
|
| 1016 |
+
Return an analog band-pass filter with center frequency `wo` and
|
| 1017 |
+
bandwidth `bw` from an analog low-pass filter prototype with unity
|
| 1018 |
+
cutoff frequency, in transfer function ('ba') representation.
|
| 1019 |
+
|
| 1020 |
+
Parameters
|
| 1021 |
+
----------
|
| 1022 |
+
b : array_like
|
| 1023 |
+
Numerator polynomial coefficients.
|
| 1024 |
+
a : array_like
|
| 1025 |
+
Denominator polynomial coefficients.
|
| 1026 |
+
wo : float
|
| 1027 |
+
Desired passband center, as angular frequency (e.g., rad/s).
|
| 1028 |
+
Defaults to no change.
|
| 1029 |
+
bw : float
|
| 1030 |
+
Desired passband width, as angular frequency (e.g., rad/s).
|
| 1031 |
+
Defaults to 1.
|
| 1032 |
+
|
| 1033 |
+
Returns
|
| 1034 |
+
-------
|
| 1035 |
+
b : array_like
|
| 1036 |
+
Numerator polynomial coefficients of the transformed band-pass filter.
|
| 1037 |
+
a : array_like
|
| 1038 |
+
Denominator polynomial coefficients of the transformed band-pass
|
| 1039 |
+
filter.
|
| 1040 |
+
|
| 1041 |
+
See Also
|
| 1042 |
+
--------
|
| 1043 |
+
lp2lp, lp2hp, lp2bs, bilinear
|
| 1044 |
+
lp2bp_zpk
|
| 1045 |
+
scipy.signal.lp2bp
|
| 1046 |
+
|
| 1047 |
+
Notes
|
| 1048 |
+
-----
|
| 1049 |
+
This is derived from the s-plane substitution
|
| 1050 |
+
|
| 1051 |
+
.. math:: s \rightarrow \frac{s^2 + {\omega_0}^2}{s \cdot \mathrm{BW}}
|
| 1052 |
+
|
| 1053 |
+
This is the "wideband" transformation, producing a passband with
|
| 1054 |
+
geometric (log frequency) symmetry about `wo`.
|
| 1055 |
+
|
| 1056 |
+
"""
|
| 1057 |
+
a, b = map(cupy.atleast_1d, (a, b))
|
| 1058 |
+
D = len(a) - 1
|
| 1059 |
+
N = len(b) - 1
|
| 1060 |
+
artype = cupy.mintypecode((a.dtype, b.dtype))
|
| 1061 |
+
ma = max(N, D)
|
| 1062 |
+
Np = N + ma
|
| 1063 |
+
Dp = D + ma
|
| 1064 |
+
bprime = cupy.empty(Np + 1, artype)
|
| 1065 |
+
aprime = cupy.empty(Dp + 1, artype)
|
| 1066 |
+
wosq = wo * wo
|
| 1067 |
+
for j in range(Np + 1):
|
| 1068 |
+
val = 0.0
|
| 1069 |
+
for i in range(0, N + 1):
|
| 1070 |
+
for k in range(0, i + 1):
|
| 1071 |
+
if ma - i + 2 * k == j:
|
| 1072 |
+
val += comb(i, k) * b[N - i] * (wosq) ** (i - k) / bw ** i
|
| 1073 |
+
bprime[Np - j] = val
|
| 1074 |
+
|
| 1075 |
+
for j in range(Dp + 1):
|
| 1076 |
+
val = 0.0
|
| 1077 |
+
for i in range(0, D + 1):
|
| 1078 |
+
for k in range(0, i + 1):
|
| 1079 |
+
if ma - i + 2 * k == j:
|
| 1080 |
+
val += comb(i, k) * a[D - i] * (wosq) ** (i - k) / bw ** i
|
| 1081 |
+
aprime[Dp - j] = val
|
| 1082 |
+
|
| 1083 |
+
return normalize(bprime, aprime)
|
| 1084 |
+
|
| 1085 |
+
|
| 1086 |
+
def lp2bs(b, a, wo=1.0, bw=1.0):
|
| 1087 |
+
r"""
|
| 1088 |
+
Transform a lowpass filter prototype to a bandstop filter.
|
| 1089 |
+
|
| 1090 |
+
Return an analog band-stop filter with center frequency `wo` and
|
| 1091 |
+
bandwidth `bw` from an analog low-pass filter prototype with unity
|
| 1092 |
+
cutoff frequency, in transfer function ('ba') representation.
|
| 1093 |
+
|
| 1094 |
+
Parameters
|
| 1095 |
+
----------
|
| 1096 |
+
b : array_like
|
| 1097 |
+
Numerator polynomial coefficients.
|
| 1098 |
+
a : array_like
|
| 1099 |
+
Denominator polynomial coefficients.
|
| 1100 |
+
wo : float
|
| 1101 |
+
Desired stopband center, as angular frequency (e.g., rad/s).
|
| 1102 |
+
Defaults to no change.
|
| 1103 |
+
bw : float
|
| 1104 |
+
Desired stopband width, as angular frequency (e.g., rad/s).
|
| 1105 |
+
Defaults to 1.
|
| 1106 |
+
|
| 1107 |
+
Returns
|
| 1108 |
+
-------
|
| 1109 |
+
b : array_like
|
| 1110 |
+
Numerator polynomial coefficients of the transformed band-stop filter.
|
| 1111 |
+
a : array_like
|
| 1112 |
+
Denominator polynomial coefficients of the transformed band-stop
|
| 1113 |
+
filter.
|
| 1114 |
+
|
| 1115 |
+
See Also
|
| 1116 |
+
--------
|
| 1117 |
+
lp2lp, lp2hp, lp2bp, bilinear
|
| 1118 |
+
lp2bs_zpk
|
| 1119 |
+
scipy.signal.lp2bs
|
| 1120 |
+
|
| 1121 |
+
Notes
|
| 1122 |
+
-----
|
| 1123 |
+
This is derived from the s-plane substitution
|
| 1124 |
+
|
| 1125 |
+
.. math:: s \rightarrow \frac{s \cdot \mathrm{BW}}{s^2 + {\omega_0}^2}
|
| 1126 |
+
|
| 1127 |
+
This is the "wideband" transformation, producing a stopband with
|
| 1128 |
+
geometric (log frequency) symmetry about `wo`.
|
| 1129 |
+
"""
|
| 1130 |
+
a, b = map(cupy.atleast_1d, (a, b))
|
| 1131 |
+
D = len(a) - 1
|
| 1132 |
+
N = len(b) - 1
|
| 1133 |
+
artype = cupy.mintypecode((a.dtype, b.dtype))
|
| 1134 |
+
M = max(N, D)
|
| 1135 |
+
Np = M + M
|
| 1136 |
+
Dp = M + M
|
| 1137 |
+
bprime = cupy.empty(Np + 1, artype)
|
| 1138 |
+
aprime = cupy.empty(Dp + 1, artype)
|
| 1139 |
+
wosq = wo * wo
|
| 1140 |
+
for j in range(Np + 1):
|
| 1141 |
+
val = 0.0
|
| 1142 |
+
for i in range(0, N + 1):
|
| 1143 |
+
for k in range(0, M - i + 1):
|
| 1144 |
+
if i + 2 * k == j:
|
| 1145 |
+
val += (comb(M - i, k) * b[N - i] *
|
| 1146 |
+
(wosq) ** (M - i - k) * bw ** i)
|
| 1147 |
+
bprime[Np - j] = val
|
| 1148 |
+
|
| 1149 |
+
for j in range(Dp + 1):
|
| 1150 |
+
val = 0.0
|
| 1151 |
+
for i in range(0, D + 1):
|
| 1152 |
+
for k in range(0, M - i + 1):
|
| 1153 |
+
if i + 2 * k == j:
|
| 1154 |
+
val += (comb(M - i, k) * a[D - i] *
|
| 1155 |
+
(wosq) ** (M - i - k) * bw ** i)
|
| 1156 |
+
aprime[Dp - j] = val
|
| 1157 |
+
|
| 1158 |
+
return normalize(bprime, aprime)
|
| 1159 |
+
|
| 1160 |
+
|
| 1161 |
+
# ### LTI conversions ###
|
| 1162 |
+
|
| 1163 |
+
def zpk2tf(z, p, k):
|
| 1164 |
+
"""
|
| 1165 |
+
Return polynomial transfer function representation from zeros and poles
|
| 1166 |
+
|
| 1167 |
+
Parameters
|
| 1168 |
+
----------
|
| 1169 |
+
z : array_like
|
| 1170 |
+
Zeros of the transfer function.
|
| 1171 |
+
p : array_like
|
| 1172 |
+
Poles of the transfer function.
|
| 1173 |
+
k : float
|
| 1174 |
+
System gain.
|
| 1175 |
+
|
| 1176 |
+
Returns
|
| 1177 |
+
-------
|
| 1178 |
+
b : ndarray
|
| 1179 |
+
Numerator polynomial coefficients.
|
| 1180 |
+
a : ndarray
|
| 1181 |
+
Denominator polynomial coefficients.
|
| 1182 |
+
|
| 1183 |
+
See Also
|
| 1184 |
+
--------
|
| 1185 |
+
scipy.signal.zpk2tf
|
| 1186 |
+
"""
|
| 1187 |
+
if z.ndim > 1:
|
| 1188 |
+
raise NotImplementedError(f"zpk2tf: z.ndim = {z.ndim}.")
|
| 1189 |
+
b = _polycoeffs_from_zeros(z) * k
|
| 1190 |
+
a = _polycoeffs_from_zeros(p)
|
| 1191 |
+
return b, a
|
| 1192 |
+
|
| 1193 |
+
|
| 1194 |
+
def tf2zpk(b, a):
|
| 1195 |
+
r"""Return zero, pole, gain (z, p, k) representation from a numerator,
|
| 1196 |
+
denominator representation of a linear filter.
|
| 1197 |
+
|
| 1198 |
+
Parameters
|
| 1199 |
+
----------
|
| 1200 |
+
b : array_like
|
| 1201 |
+
Numerator polynomial coefficients.
|
| 1202 |
+
a : array_like
|
| 1203 |
+
Denominator polynomial coefficients.
|
| 1204 |
+
|
| 1205 |
+
Returns
|
| 1206 |
+
-------
|
| 1207 |
+
z : ndarray
|
| 1208 |
+
Zeros of the transfer function.
|
| 1209 |
+
p : ndarray
|
| 1210 |
+
Poles of the transfer function.
|
| 1211 |
+
k : float
|
| 1212 |
+
System gain.
|
| 1213 |
+
|
| 1214 |
+
Warning
|
| 1215 |
+
-------
|
| 1216 |
+
This function may synchronize the device.
|
| 1217 |
+
|
| 1218 |
+
See Also
|
| 1219 |
+
--------
|
| 1220 |
+
scipy.signal.tf2zpk
|
| 1221 |
+
|
| 1222 |
+
Notes
|
| 1223 |
+
-----
|
| 1224 |
+
If some values of `b` are too close to 0, they are removed. In that case,
|
| 1225 |
+
a BadCoefficients warning is emitted.
|
| 1226 |
+
|
| 1227 |
+
The `b` and `a` arrays are interpreted as coefficients for positive,
|
| 1228 |
+
descending powers of the transfer function variable. So the inputs
|
| 1229 |
+
:math:`b = [b_0, b_1, ..., b_M]` and :math:`a =[a_0, a_1, ..., a_N]`
|
| 1230 |
+
can represent an analog filter of the form:
|
| 1231 |
+
|
| 1232 |
+
.. math::
|
| 1233 |
+
|
| 1234 |
+
H(s) = \frac
|
| 1235 |
+
{b_0 s^M + b_1 s^{(M-1)} + \cdots + b_M}
|
| 1236 |
+
{a_0 s^N + a_1 s^{(N-1)} + \cdots + a_N}
|
| 1237 |
+
|
| 1238 |
+
or a discrete-time filter of the form:
|
| 1239 |
+
|
| 1240 |
+
.. math::
|
| 1241 |
+
|
| 1242 |
+
H(z) = \frac
|
| 1243 |
+
{b_0 z^M + b_1 z^{(M-1)} + \cdots + b_M}
|
| 1244 |
+
{a_0 z^N + a_1 z^{(N-1)} + \cdots + a_N}
|
| 1245 |
+
|
| 1246 |
+
This "positive powers" form is found more commonly in controls
|
| 1247 |
+
engineering. If `M` and `N` are equal (which is true for all filters
|
| 1248 |
+
generated by the bilinear transform), then this happens to be equivalent
|
| 1249 |
+
to the "negative powers" discrete-time form preferred in DSP:
|
| 1250 |
+
|
| 1251 |
+
.. math::
|
| 1252 |
+
|
| 1253 |
+
H(z) = \frac
|
| 1254 |
+
{b_0 + b_1 z^{-1} + \cdots + b_M z^{-M}}
|
| 1255 |
+
{a_0 + a_1 z^{-1} + \cdots + a_N z^{-N}}
|
| 1256 |
+
|
| 1257 |
+
Although this is true for common filters, remember that this is not true
|
| 1258 |
+
in the general case. If `M` and `N` are not equal, the discrete-time
|
| 1259 |
+
transfer function coefficients must first be converted to the "positive
|
| 1260 |
+
powers" form before finding the poles and zeros.
|
| 1261 |
+
|
| 1262 |
+
"""
|
| 1263 |
+
b, a = normalize(b, a)
|
| 1264 |
+
b = (b + 0.0) / a[0]
|
| 1265 |
+
a = (a + 0.0) / a[0]
|
| 1266 |
+
k = b[0].copy()
|
| 1267 |
+
b /= b[0]
|
| 1268 |
+
z = roots(b)
|
| 1269 |
+
p = roots(a)
|
| 1270 |
+
return z, p, k
|
| 1271 |
+
|
| 1272 |
+
|
| 1273 |
+
def tf2sos(b, a, pairing=None, *, analog=False):
|
| 1274 |
+
"""
|
| 1275 |
+
Return second-order sections from transfer function representation
|
| 1276 |
+
|
| 1277 |
+
Parameters
|
| 1278 |
+
----------
|
| 1279 |
+
b : array_like
|
| 1280 |
+
Numerator polynomial coefficients.
|
| 1281 |
+
a : array_like
|
| 1282 |
+
Denominator polynomial coefficients.
|
| 1283 |
+
pairing : {None, 'nearest', 'keep_odd', 'minimal'}, optional
|
| 1284 |
+
The method to use to combine pairs of poles and zeros into sections.
|
| 1285 |
+
See `zpk2sos` for information and restrictions on `pairing` and
|
| 1286 |
+
`analog` arguments.
|
| 1287 |
+
analog : bool, optional
|
| 1288 |
+
If True, system is analog, otherwise discrete.
|
| 1289 |
+
|
| 1290 |
+
Returns
|
| 1291 |
+
-------
|
| 1292 |
+
sos : ndarray
|
| 1293 |
+
Array of second-order filter coefficients, with shape
|
| 1294 |
+
``(n_sections, 6)``. See `sosfilt` for the SOS filter format
|
| 1295 |
+
specification.
|
| 1296 |
+
|
| 1297 |
+
See Also
|
| 1298 |
+
--------
|
| 1299 |
+
scipy.signal.tf2sos
|
| 1300 |
+
|
| 1301 |
+
Notes
|
| 1302 |
+
-----
|
| 1303 |
+
It is generally discouraged to convert from TF to SOS format, since doing
|
| 1304 |
+
so usually will not improve numerical precision errors. Instead, consider
|
| 1305 |
+
designing filters in ZPK format and converting directly to SOS. TF is
|
| 1306 |
+
converted to SOS by first converting to ZPK format, then converting
|
| 1307 |
+
ZPK to SOS.
|
| 1308 |
+
|
| 1309 |
+
"""
|
| 1310 |
+
return zpk2sos(*tf2zpk(b, a), pairing=pairing, analog=analog)
|
| 1311 |
+
|
| 1312 |
+
|
| 1313 |
+
def sos2tf(sos):
|
| 1314 |
+
"""
|
| 1315 |
+
Return a single transfer function from a series of second-order sections
|
| 1316 |
+
|
| 1317 |
+
Parameters
|
| 1318 |
+
----------
|
| 1319 |
+
sos : array_like
|
| 1320 |
+
Array of second-order filter coefficients, must have shape
|
| 1321 |
+
``(n_sections, 6)``. See `sosfilt` for the SOS filter format
|
| 1322 |
+
specification.
|
| 1323 |
+
|
| 1324 |
+
Returns
|
| 1325 |
+
-------
|
| 1326 |
+
b : ndarray
|
| 1327 |
+
Numerator polynomial coefficients.
|
| 1328 |
+
a : ndarray
|
| 1329 |
+
Denominator polynomial coefficients.
|
| 1330 |
+
|
| 1331 |
+
See Also
|
| 1332 |
+
--------
|
| 1333 |
+
scipy.signal.sos2tf
|
| 1334 |
+
|
| 1335 |
+
"""
|
| 1336 |
+
sos = cupy.asarray(sos)
|
| 1337 |
+
result_type = sos.dtype
|
| 1338 |
+
if result_type.kind in 'bui':
|
| 1339 |
+
result_type = cupy.float64
|
| 1340 |
+
|
| 1341 |
+
b = cupy.array([1], dtype=result_type)
|
| 1342 |
+
a = cupy.array([1], dtype=result_type)
|
| 1343 |
+
n_sections = sos.shape[0]
|
| 1344 |
+
for section in range(n_sections):
|
| 1345 |
+
b = cupy.polymul(b, sos[section, :3])
|
| 1346 |
+
a = cupy.polymul(a, sos[section, 3:])
|
| 1347 |
+
return b, a
|
| 1348 |
+
|
| 1349 |
+
|
| 1350 |
+
def sos2zpk(sos):
|
| 1351 |
+
"""
|
| 1352 |
+
Return zeros, poles, and gain of a series of second-order sections
|
| 1353 |
+
|
| 1354 |
+
Parameters
|
| 1355 |
+
----------
|
| 1356 |
+
sos : array_like
|
| 1357 |
+
Array of second-order filter coefficients, must have shape
|
| 1358 |
+
``(n_sections, 6)``. See `sosfilt` for the SOS filter format
|
| 1359 |
+
specification.
|
| 1360 |
+
|
| 1361 |
+
Returns
|
| 1362 |
+
-------
|
| 1363 |
+
z : ndarray
|
| 1364 |
+
Zeros of the transfer function.
|
| 1365 |
+
p : ndarray
|
| 1366 |
+
Poles of the transfer function.
|
| 1367 |
+
k : float
|
| 1368 |
+
System gain.
|
| 1369 |
+
|
| 1370 |
+
Notes
|
| 1371 |
+
-----
|
| 1372 |
+
The number of zeros and poles returned will be ``n_sections * 2``
|
| 1373 |
+
even if some of these are (effectively) zero.
|
| 1374 |
+
|
| 1375 |
+
See Also
|
| 1376 |
+
--------
|
| 1377 |
+
scipy.signal.sos2zpk
|
| 1378 |
+
|
| 1379 |
+
"""
|
| 1380 |
+
n_sections = sos.shape[0]
|
| 1381 |
+
z = cupy.zeros(n_sections*2, cupy.complex128)
|
| 1382 |
+
p = cupy.zeros(n_sections*2, cupy.complex128)
|
| 1383 |
+
k = 1.
|
| 1384 |
+
for section in range(n_sections):
|
| 1385 |
+
# XXX: may just solve a quadratic equation instead of tf2zpk
|
| 1386 |
+
zpk = tf2zpk(sos[section, :3], sos[section, 3:])
|
| 1387 |
+
z[2*section:2*section + len(zpk[0])] = zpk[0]
|
| 1388 |
+
p[2*section:2*section + len(zpk[1])] = zpk[1]
|
| 1389 |
+
k *= zpk[2]
|
| 1390 |
+
return z, p, k
|
| 1391 |
+
|
| 1392 |
+
|
| 1393 |
+
def tf2ss(num, den):
|
| 1394 |
+
r"""Transfer function to state-space representation.
|
| 1395 |
+
|
| 1396 |
+
Parameters
|
| 1397 |
+
----------
|
| 1398 |
+
num, den : array_like
|
| 1399 |
+
Sequences representing the coefficients of the numerator and
|
| 1400 |
+
denominator polynomials, in order of descending degree. The
|
| 1401 |
+
denominator needs to be at least as long as the numerator.
|
| 1402 |
+
|
| 1403 |
+
Returns
|
| 1404 |
+
-------
|
| 1405 |
+
A, B, C, D : ndarray
|
| 1406 |
+
State space representation of the system, in controller canonical
|
| 1407 |
+
form.
|
| 1408 |
+
|
| 1409 |
+
See Also
|
| 1410 |
+
--------
|
| 1411 |
+
scipy.signal.tf2ss
|
| 1412 |
+
"""
|
| 1413 |
+
# Controller canonical state-space representation.
|
| 1414 |
+
# if M+1 = len(num) and K+1 = len(den) then we must have M <= K
|
| 1415 |
+
# states are found by asserting that X(s) = U(s) / D(s)
|
| 1416 |
+
# then Y(s) = N(s) * X(s)
|
| 1417 |
+
#
|
| 1418 |
+
# A, B, C, and D follow quite naturally.
|
| 1419 |
+
#
|
| 1420 |
+
num, den = normalize(num, den) # Strips zeros, checks arrays
|
| 1421 |
+
nn = len(num.shape)
|
| 1422 |
+
if nn == 1:
|
| 1423 |
+
num = cupy.asarray([num], num.dtype)
|
| 1424 |
+
M = num.shape[1]
|
| 1425 |
+
K = len(den)
|
| 1426 |
+
if M > K:
|
| 1427 |
+
msg = "Improper transfer function. `num` is longer than `den`."
|
| 1428 |
+
raise ValueError(msg)
|
| 1429 |
+
if M == 0 or K == 0: # Null system
|
| 1430 |
+
return (cupy.array([], float),
|
| 1431 |
+
cupy.array([], float),
|
| 1432 |
+
cupy.array([], float),
|
| 1433 |
+
cupy.array([], float))
|
| 1434 |
+
|
| 1435 |
+
# pad numerator to have same number of columns has denominator
|
| 1436 |
+
num = cupy.hstack((cupy.zeros((num.shape[0], K - M), num.dtype), num))
|
| 1437 |
+
|
| 1438 |
+
if num.shape[-1] > 0:
|
| 1439 |
+
D = cupy.atleast_2d(num[:, 0])
|
| 1440 |
+
|
| 1441 |
+
else:
|
| 1442 |
+
# We don't assign it an empty array because this system
|
| 1443 |
+
# is not 'null'. It just doesn't have a non-zero D
|
| 1444 |
+
# matrix. Thus, it should have a non-zero shape so that
|
| 1445 |
+
# it can be operated on by functions like 'ss2tf'
|
| 1446 |
+
D = cupy.array([[0]], float)
|
| 1447 |
+
|
| 1448 |
+
if K == 1:
|
| 1449 |
+
D = D.reshape(num.shape)
|
| 1450 |
+
|
| 1451 |
+
return (cupy.zeros((1, 1)), cupy.zeros((1, D.shape[1])),
|
| 1452 |
+
cupy.zeros((D.shape[0], 1)), D)
|
| 1453 |
+
|
| 1454 |
+
frow = -cupy.array([den[1:]])
|
| 1455 |
+
A = cupy.r_[frow, cupy.eye(K - 2, K - 1)]
|
| 1456 |
+
B = cupy.eye(K - 1, 1)
|
| 1457 |
+
C = num[:, 1:] - cupy.outer(num[:, 0], den[1:])
|
| 1458 |
+
D = D.reshape((C.shape[0], B.shape[1]))
|
| 1459 |
+
|
| 1460 |
+
return A, B, C, D
|
| 1461 |
+
|
| 1462 |
+
|
| 1463 |
+
def ss2tf(A, B, C, D, input=0):
|
| 1464 |
+
r"""State-space to transfer function.
|
| 1465 |
+
|
| 1466 |
+
A, B, C, D defines a linear state-space system with `p` inputs,
|
| 1467 |
+
`q` outputs, and `n` state variables.
|
| 1468 |
+
|
| 1469 |
+
Parameters
|
| 1470 |
+
----------
|
| 1471 |
+
A : array_like
|
| 1472 |
+
State (or system) matrix of shape ``(n, n)``
|
| 1473 |
+
B : array_like
|
| 1474 |
+
Input matrix of shape ``(n, p)``
|
| 1475 |
+
C : array_like
|
| 1476 |
+
Output matrix of shape ``(q, n)``
|
| 1477 |
+
D : array_like
|
| 1478 |
+
Feedthrough (or feedforward) matrix of shape ``(q, p)``
|
| 1479 |
+
input : int, optional
|
| 1480 |
+
For multiple-input systems, the index of the input to use.
|
| 1481 |
+
|
| 1482 |
+
Returns
|
| 1483 |
+
-------
|
| 1484 |
+
num : 2-D ndarray
|
| 1485 |
+
Numerator(s) of the resulting transfer function(s). `num` has one row
|
| 1486 |
+
for each of the system's outputs. Each row is a sequence representation
|
| 1487 |
+
of the numerator polynomial.
|
| 1488 |
+
den : 1-D ndarray
|
| 1489 |
+
Denominator of the resulting transfer function(s). `den` is a sequence
|
| 1490 |
+
representation of the denominator polynomial.
|
| 1491 |
+
|
| 1492 |
+
Warning
|
| 1493 |
+
-------
|
| 1494 |
+
This function may synchronize the device.
|
| 1495 |
+
|
| 1496 |
+
See Also
|
| 1497 |
+
--------
|
| 1498 |
+
scipy.signal.ss2tf
|
| 1499 |
+
|
| 1500 |
+
"""
|
| 1501 |
+
# transfer function is C (sI - A)**(-1) B + D
|
| 1502 |
+
|
| 1503 |
+
# Check consistency and make them all rank-2 arrays
|
| 1504 |
+
A, B, C, D = abcd_normalize(A, B, C, D)
|
| 1505 |
+
|
| 1506 |
+
nout, nin = D.shape
|
| 1507 |
+
if input >= nin:
|
| 1508 |
+
raise ValueError("System does not have the input specified.")
|
| 1509 |
+
|
| 1510 |
+
# make SIMO from possibly MIMO system.
|
| 1511 |
+
B = B[:, input:input + 1]
|
| 1512 |
+
D = D[:, input:input + 1]
|
| 1513 |
+
|
| 1514 |
+
try:
|
| 1515 |
+
den = poly(A)
|
| 1516 |
+
except ValueError:
|
| 1517 |
+
den = 1
|
| 1518 |
+
|
| 1519 |
+
if (prod(B.shape) == 0) and (prod(C.shape) == 0):
|
| 1520 |
+
num = cupy.ravel(D)
|
| 1521 |
+
if (prod(D.shape) == 0) and (prod(A.shape) == 0):
|
| 1522 |
+
den = []
|
| 1523 |
+
return num, den
|
| 1524 |
+
|
| 1525 |
+
num_states = A.shape[0]
|
| 1526 |
+
type_test = A[:, 0] + B[:, 0] + C[0, :] + D + 0.0
|
| 1527 |
+
num = cupy.empty((nout, num_states + 1), type_test.dtype)
|
| 1528 |
+
for k in range(nout):
|
| 1529 |
+
Ck = cupy.atleast_2d(C[k, :])
|
| 1530 |
+
num[k] = poly(A - B @ Ck) + (D[k] - 1) * den
|
| 1531 |
+
|
| 1532 |
+
return num, den
|
| 1533 |
+
|
| 1534 |
+
|
| 1535 |
+
def zpk2ss(z, p, k):
|
| 1536 |
+
"""Zero-pole-gain representation to state-space representation
|
| 1537 |
+
|
| 1538 |
+
Parameters
|
| 1539 |
+
----------
|
| 1540 |
+
z, p : sequence
|
| 1541 |
+
Zeros and poles.
|
| 1542 |
+
k : float
|
| 1543 |
+
System gain.
|
| 1544 |
+
|
| 1545 |
+
Returns
|
| 1546 |
+
-------
|
| 1547 |
+
A, B, C, D : ndarray
|
| 1548 |
+
State space representation of the system, in controller canonical
|
| 1549 |
+
form.
|
| 1550 |
+
|
| 1551 |
+
See Also
|
| 1552 |
+
--------
|
| 1553 |
+
scipy.signal.zpk2ss
|
| 1554 |
+
|
| 1555 |
+
"""
|
| 1556 |
+
return tf2ss(*zpk2tf(z, p, k))
|
| 1557 |
+
|
| 1558 |
+
|
| 1559 |
+
def ss2zpk(A, B, C, D, input=0):
|
| 1560 |
+
"""State-space representation to zero-pole-gain representation.
|
| 1561 |
+
|
| 1562 |
+
A, B, C, D defines a linear state-space system with `p` inputs,
|
| 1563 |
+
`q` outputs, and `n` state variables.
|
| 1564 |
+
|
| 1565 |
+
Parameters
|
| 1566 |
+
----------
|
| 1567 |
+
A : array_like
|
| 1568 |
+
State (or system) matrix of shape ``(n, n)``
|
| 1569 |
+
B : array_like
|
| 1570 |
+
Input matrix of shape ``(n, p)``
|
| 1571 |
+
C : array_like
|
| 1572 |
+
Output matrix of shape ``(q, n)``
|
| 1573 |
+
D : array_like
|
| 1574 |
+
Feedthrough (or feedforward) matrix of shape ``(q, p)``
|
| 1575 |
+
input : int, optional
|
| 1576 |
+
For multiple-input systems, the index of the input to use.
|
| 1577 |
+
|
| 1578 |
+
Returns
|
| 1579 |
+
-------
|
| 1580 |
+
z, p : sequence
|
| 1581 |
+
Zeros and poles.
|
| 1582 |
+
k : float
|
| 1583 |
+
System gain.
|
| 1584 |
+
|
| 1585 |
+
See Also
|
| 1586 |
+
--------
|
| 1587 |
+
scipy.signal.ss2zpk
|
| 1588 |
+
|
| 1589 |
+
"""
|
| 1590 |
+
return tf2zpk(*ss2tf(A, B, C, D, input=input))
|
| 1591 |
+
|
| 1592 |
+
|
| 1593 |
+
# ### Low-level analog filter prototypes ###
|
| 1594 |
+
|
| 1595 |
+
# TODO (ev-br): move to a better place (_filter_design.py (?))
|
| 1596 |
+
|
| 1597 |
+
def buttap(N):
|
| 1598 |
+
"""Return (z,p,k) for analog prototype of Nth-order Butterworth filter.
|
| 1599 |
+
|
| 1600 |
+
The filter will have an angular (e.g., rad/s) cutoff frequency of 1.
|
| 1601 |
+
|
| 1602 |
+
See Also
|
| 1603 |
+
--------
|
| 1604 |
+
butter : Filter design function using this prototype
|
| 1605 |
+
scipy.signal.buttap
|
| 1606 |
+
|
| 1607 |
+
"""
|
| 1608 |
+
if abs(int(N)) != N:
|
| 1609 |
+
raise ValueError("Filter order must be a nonnegative integer")
|
| 1610 |
+
z = cupy.array([])
|
| 1611 |
+
m = cupy.arange(-N+1, N, 2)
|
| 1612 |
+
# Middle value is 0 to ensure an exactly real pole
|
| 1613 |
+
p = -cupy.exp(1j * pi * m / (2 * N))
|
| 1614 |
+
k = 1
|
| 1615 |
+
return z, p, k
|
| 1616 |
+
|
| 1617 |
+
|
| 1618 |
+
def cheb1ap(N, rp):
|
| 1619 |
+
"""
|
| 1620 |
+
Return (z,p,k) for Nth-order Chebyshev type I analog lowpass filter.
|
| 1621 |
+
|
| 1622 |
+
The returned filter prototype has `rp` decibels of ripple in the passband.
|
| 1623 |
+
|
| 1624 |
+
The filter's angular (e.g. rad/s) cutoff frequency is normalized to 1,
|
| 1625 |
+
defined as the point at which the gain first drops below ``-rp``.
|
| 1626 |
+
|
| 1627 |
+
See Also
|
| 1628 |
+
--------
|
| 1629 |
+
cheby1 : Filter design function using this prototype
|
| 1630 |
+
|
| 1631 |
+
"""
|
| 1632 |
+
if abs(int(N)) != N:
|
| 1633 |
+
raise ValueError("Filter order must be a nonnegative integer")
|
| 1634 |
+
elif N == 0:
|
| 1635 |
+
# Avoid divide-by-zero error
|
| 1636 |
+
# Even order filters have DC gain of -rp dB
|
| 1637 |
+
return cupy.array([]), cupy.array([]), 10**(-rp/20)
|
| 1638 |
+
z = cupy.array([])
|
| 1639 |
+
|
| 1640 |
+
# Ripple factor (epsilon)
|
| 1641 |
+
eps = cupy.sqrt(10 ** (0.1 * rp) - 1.0)
|
| 1642 |
+
mu = 1.0 / N * cupy.arcsinh(1 / eps)
|
| 1643 |
+
|
| 1644 |
+
# Arrange poles in an ellipse on the left half of the S-plane
|
| 1645 |
+
m = cupy.arange(-N+1, N, 2)
|
| 1646 |
+
theta = pi * m / (2*N)
|
| 1647 |
+
p = -cupy.sinh(mu + 1j*theta)
|
| 1648 |
+
|
| 1649 |
+
k = cupy.prod(-p, axis=0).real
|
| 1650 |
+
if N % 2 == 0:
|
| 1651 |
+
k = k / cupy.sqrt(1 + eps * eps)
|
| 1652 |
+
|
| 1653 |
+
return z, p, k
|
| 1654 |
+
|
| 1655 |
+
|
| 1656 |
+
def cheb2ap(N, rs):
|
| 1657 |
+
"""
|
| 1658 |
+
Return (z,p,k) for Nth-order Chebyshev type I analog lowpass filter.
|
| 1659 |
+
|
| 1660 |
+
The returned filter prototype has `rs` decibels of ripple in the stopband.
|
| 1661 |
+
|
| 1662 |
+
The filter's angular (e.g. rad/s) cutoff frequency is normalized to 1,
|
| 1663 |
+
defined as the point at which the gain first reaches ``-rs``.
|
| 1664 |
+
|
| 1665 |
+
See Also
|
| 1666 |
+
--------
|
| 1667 |
+
cheby2 : Filter design function using this prototype
|
| 1668 |
+
|
| 1669 |
+
"""
|
| 1670 |
+
if abs(int(N)) != N:
|
| 1671 |
+
raise ValueError("Filter order must be a nonnegative integer")
|
| 1672 |
+
elif N == 0:
|
| 1673 |
+
# Avoid divide-by-zero warning
|
| 1674 |
+
return cupy.array([]), cupy.array([]), 1
|
| 1675 |
+
|
| 1676 |
+
# Ripple factor (epsilon)
|
| 1677 |
+
de = 1.0 / cupy.sqrt(10 ** (0.1 * rs) - 1)
|
| 1678 |
+
mu = cupy.arcsinh(1.0 / de) / N
|
| 1679 |
+
|
| 1680 |
+
if N % 2:
|
| 1681 |
+
m = cupy.concatenate((cupy.arange(-N+1, 0, 2),
|
| 1682 |
+
cupy.arange(2, N, 2)))
|
| 1683 |
+
else:
|
| 1684 |
+
m = cupy.arange(-N+1, N, 2)
|
| 1685 |
+
|
| 1686 |
+
z = -cupy.conjugate(1j / cupy.sin(m * pi / (2.0 * N)))
|
| 1687 |
+
|
| 1688 |
+
# Poles around the unit circle like Butterworth
|
| 1689 |
+
p = -cupy.exp(1j * pi * cupy.arange(-N+1, N, 2) / (2 * N))
|
| 1690 |
+
# Warp into Chebyshev II
|
| 1691 |
+
p = cupy.sinh(mu) * p.real + 1j * cupy.cosh(mu) * p.imag
|
| 1692 |
+
p = 1.0 / p
|
| 1693 |
+
|
| 1694 |
+
k = (cupy.prod(-p, axis=0) / cupy.prod(-z, axis=0)).real
|
| 1695 |
+
return z, p, k
|
| 1696 |
+
|
| 1697 |
+
|
| 1698 |
+
# ### Elliptic filter prototype ###
|
| 1699 |
+
|
| 1700 |
+
_POW10_LOG10 = math.log(10)
|
| 1701 |
+
|
| 1702 |
+
|
| 1703 |
+
def _pow10m1(x):
|
| 1704 |
+
"""10 ** x - 1 for x near 0"""
|
| 1705 |
+
return cupy.expm1(_POW10_LOG10 * x)
|
| 1706 |
+
|
| 1707 |
+
|
| 1708 |
+
def _ellipdeg(n, m1):
|
| 1709 |
+
"""Solve degree equation using nomes
|
| 1710 |
+
|
| 1711 |
+
Given n, m1, solve
|
| 1712 |
+
n * K(m) / K'(m) = K1(m1) / K1'(m1)
|
| 1713 |
+
for m
|
| 1714 |
+
|
| 1715 |
+
See [1], Eq. (49)
|
| 1716 |
+
|
| 1717 |
+
References
|
| 1718 |
+
----------
|
| 1719 |
+
.. [1] Orfanidis, "Lecture Notes on Elliptic Filter Design",
|
| 1720 |
+
https://www.ece.rutgers.edu/~orfanidi/ece521/notes.pdf
|
| 1721 |
+
"""
|
| 1722 |
+
# number of terms in solving degree equation
|
| 1723 |
+
_ELLIPDEG_MMAX = 7
|
| 1724 |
+
|
| 1725 |
+
K1 = special.ellipk(m1)
|
| 1726 |
+
K1p = special.ellipkm1(m1)
|
| 1727 |
+
|
| 1728 |
+
q1 = cupy.exp(-pi * K1p / K1)
|
| 1729 |
+
q = q1 ** (1/n)
|
| 1730 |
+
|
| 1731 |
+
mnum = cupy.arange(_ELLIPDEG_MMAX + 1)
|
| 1732 |
+
mden = cupy.arange(1, _ELLIPDEG_MMAX + 2)
|
| 1733 |
+
|
| 1734 |
+
num = (q ** (mnum * (mnum+1))).sum()
|
| 1735 |
+
den = 1 + 2 * (q ** (mden**2)).sum()
|
| 1736 |
+
|
| 1737 |
+
return 16 * q * (num / den) ** 4
|
| 1738 |
+
|
| 1739 |
+
|
| 1740 |
+
def _arc_jac_sn(w, m):
|
| 1741 |
+
"""Inverse Jacobian elliptic sn
|
| 1742 |
+
|
| 1743 |
+
Solve for z in w = sn(z, m)
|
| 1744 |
+
|
| 1745 |
+
Parameters
|
| 1746 |
+
----------
|
| 1747 |
+
w : complex scalar
|
| 1748 |
+
argument
|
| 1749 |
+
|
| 1750 |
+
m : scalar
|
| 1751 |
+
modulus; in interval [0, 1]
|
| 1752 |
+
|
| 1753 |
+
|
| 1754 |
+
See [1], Eq. (56)
|
| 1755 |
+
|
| 1756 |
+
References
|
| 1757 |
+
----------
|
| 1758 |
+
.. [1] Orfanidis, "Lecture Notes on Elliptic Filter Design",
|
| 1759 |
+
https://www.ece.rutgers.edu/~orfanidi/ece521/notes.pdf
|
| 1760 |
+
|
| 1761 |
+
"""
|
| 1762 |
+
# Maximum number of iterations in Landen transformation recursion
|
| 1763 |
+
# sequence. 10 is conservative; unit tests pass with 4, Orfanidis
|
| 1764 |
+
# (see _arc_jac_cn [1]) suggests 5.
|
| 1765 |
+
_ARC_JAC_SN_MAXITER = 10
|
| 1766 |
+
|
| 1767 |
+
def _complement(kx):
|
| 1768 |
+
# (1-k**2) ** 0.5; the expression below
|
| 1769 |
+
# works for small kx
|
| 1770 |
+
return ((1 - kx) * (1 + kx)) ** 0.5
|
| 1771 |
+
|
| 1772 |
+
k = m ** 0.5
|
| 1773 |
+
|
| 1774 |
+
if k > 1:
|
| 1775 |
+
return cupy.nan
|
| 1776 |
+
elif k == 1:
|
| 1777 |
+
return cupy.arctanh(w)
|
| 1778 |
+
|
| 1779 |
+
ks = [k]
|
| 1780 |
+
niter = 0
|
| 1781 |
+
while ks[-1] != 0:
|
| 1782 |
+
k_ = ks[-1]
|
| 1783 |
+
k_p = _complement(k_)
|
| 1784 |
+
ks.append((1 - k_p) / (1 + k_p))
|
| 1785 |
+
niter += 1
|
| 1786 |
+
if niter > _ARC_JAC_SN_MAXITER:
|
| 1787 |
+
raise ValueError('Landen transformation not converging')
|
| 1788 |
+
|
| 1789 |
+
K = cupy.prod(1 + cupy.array(ks[1:])) * pi/2
|
| 1790 |
+
|
| 1791 |
+
wns = [w]
|
| 1792 |
+
|
| 1793 |
+
for kn, knext in zip(ks[:-1], ks[1:]):
|
| 1794 |
+
wn = wns[-1]
|
| 1795 |
+
wnext = (2 * wn /
|
| 1796 |
+
((1 + knext) * (1 + _complement(kn * wn))))
|
| 1797 |
+
wns.append(wnext)
|
| 1798 |
+
|
| 1799 |
+
u = 2 / pi * cupy.arcsin(wns[-1])
|
| 1800 |
+
|
| 1801 |
+
z = K * u
|
| 1802 |
+
return z
|
| 1803 |
+
|
| 1804 |
+
|
| 1805 |
+
def _arc_jac_sc1(w, m):
|
| 1806 |
+
"""Real inverse Jacobian sc, with complementary modulus
|
| 1807 |
+
|
| 1808 |
+
Solve for z in w = sc(z, 1-m)
|
| 1809 |
+
|
| 1810 |
+
w - real scalar
|
| 1811 |
+
|
| 1812 |
+
m - modulus
|
| 1813 |
+
|
| 1814 |
+
Using that sc(z, m) = -i * sn(i * z, 1 - m)
|
| 1815 |
+
cf scipy/signal/_filter_design.py analog for an explanation
|
| 1816 |
+
and a reference.
|
| 1817 |
+
|
| 1818 |
+
"""
|
| 1819 |
+
|
| 1820 |
+
zcomplex = _arc_jac_sn(1j * w, m)
|
| 1821 |
+
if abs(zcomplex.real) > 1e-14:
|
| 1822 |
+
raise ValueError
|
| 1823 |
+
|
| 1824 |
+
return zcomplex.imag
|
| 1825 |
+
|
| 1826 |
+
|
| 1827 |
+
def ellipap(N, rp, rs):
|
| 1828 |
+
"""Return (z,p,k) of Nth-order elliptic analog lowpass filter.
|
| 1829 |
+
|
| 1830 |
+
The filter is a normalized prototype that has `rp` decibels of ripple
|
| 1831 |
+
in the passband and a stopband `rs` decibels down.
|
| 1832 |
+
|
| 1833 |
+
The filter's angular (e.g., rad/s) cutoff frequency is normalized to 1,
|
| 1834 |
+
defined as the point at which the gain first drops below ``-rp``.
|
| 1835 |
+
|
| 1836 |
+
See Also
|
| 1837 |
+
--------
|
| 1838 |
+
ellip : Filter design function using this prototype
|
| 1839 |
+
scipy.signal.elliap
|
| 1840 |
+
|
| 1841 |
+
"""
|
| 1842 |
+
if abs(int(N)) != N:
|
| 1843 |
+
raise ValueError("Filter order must be a nonnegative integer")
|
| 1844 |
+
elif N == 0:
|
| 1845 |
+
# Avoid divide-by-zero warning
|
| 1846 |
+
# Even order filters have DC gain of -rp dB
|
| 1847 |
+
return cupy.array([]), cupy.array([]), 10**(-rp/20)
|
| 1848 |
+
elif N == 1:
|
| 1849 |
+
p = -cupy.sqrt(1.0 / _pow10m1(0.1 * rp))
|
| 1850 |
+
k = -p
|
| 1851 |
+
z = []
|
| 1852 |
+
return cupy.asarray(z), cupy.asarray(p), k
|
| 1853 |
+
|
| 1854 |
+
eps_sq = _pow10m1(0.1 * rp)
|
| 1855 |
+
|
| 1856 |
+
eps = cupy.sqrt(eps_sq)
|
| 1857 |
+
ck1_sq = eps_sq / _pow10m1(0.1 * rs)
|
| 1858 |
+
if ck1_sq == 0:
|
| 1859 |
+
raise ValueError("Cannot design a filter with given rp and rs"
|
| 1860 |
+
" specifications.")
|
| 1861 |
+
|
| 1862 |
+
m = _ellipdeg(N, ck1_sq)
|
| 1863 |
+
capk = special.ellipk(m)
|
| 1864 |
+
j = cupy.arange(1 - N % 2, N, 2)
|
| 1865 |
+
EPSILON = 2e-16
|
| 1866 |
+
|
| 1867 |
+
s, c, d, phi = special.ellipj(j * capk / N, m * cupy.ones_like(j))
|
| 1868 |
+
snew = cupy.compress(cupy.abs(s) > EPSILON, s, axis=-1)
|
| 1869 |
+
z = 1.j / (cupy.sqrt(m) * snew)
|
| 1870 |
+
z = cupy.concatenate((z, z.conj()))
|
| 1871 |
+
|
| 1872 |
+
r = _arc_jac_sc1(1. / eps, ck1_sq)
|
| 1873 |
+
v0 = capk * r / (N * special.ellipk(ck1_sq))
|
| 1874 |
+
|
| 1875 |
+
sv, cv, dv, phi = special.ellipj(v0, 1 - m)
|
| 1876 |
+
p = -(c * d * sv * cv + 1j * s * dv) / (1 - (d * sv) ** 2.0)
|
| 1877 |
+
|
| 1878 |
+
if N % 2:
|
| 1879 |
+
mask = cupy.abs(p.imag) > EPSILON * \
|
| 1880 |
+
cupy.sqrt((p * p.conj()).sum(axis=0).real)
|
| 1881 |
+
newp = cupy.compress(mask, p, axis=-1)
|
| 1882 |
+
p = cupy.concatenate((p, newp.conj()))
|
| 1883 |
+
else:
|
| 1884 |
+
p = cupy.concatenate((p, p.conj()))
|
| 1885 |
+
|
| 1886 |
+
k = (cupy.prod(-p, axis=0) / cupy.prod(-z, axis=0)).real
|
| 1887 |
+
if N % 2 == 0:
|
| 1888 |
+
k = k / cupy.sqrt(1 + eps_sq)
|
| 1889 |
+
|
| 1890 |
+
return z, p, k
|
| 1891 |
+
|
| 1892 |
+
|
| 1893 |
+
# ### *ord functions to accopany *ap functions
|
| 1894 |
+
|
| 1895 |
+
def _validate_gpass_gstop(gpass, gstop):
|
| 1896 |
+
|
| 1897 |
+
if gpass <= 0.0:
|
| 1898 |
+
raise ValueError("gpass should be larger than 0.0")
|
| 1899 |
+
elif gstop <= 0.0:
|
| 1900 |
+
raise ValueError("gstop should be larger than 0.0")
|
| 1901 |
+
elif gpass > gstop:
|
| 1902 |
+
raise ValueError("gpass should be smaller than gstop")
|
| 1903 |
+
|
| 1904 |
+
|
| 1905 |
+
def _pre_warp(wp, ws, analog):
|
| 1906 |
+
# Pre-warp frequencies for digital filter design
|
| 1907 |
+
if not analog:
|
| 1908 |
+
passb = cupy.tan(pi * wp / 2.0)
|
| 1909 |
+
stopb = cupy.tan(pi * ws / 2.0)
|
| 1910 |
+
else:
|
| 1911 |
+
passb = wp * 1.0
|
| 1912 |
+
stopb = ws * 1.0
|
| 1913 |
+
return passb, stopb
|
| 1914 |
+
|
| 1915 |
+
|
| 1916 |
+
def _validate_wp_ws(wp, ws, fs, analog):
|
| 1917 |
+
wp = cupy.atleast_1d(wp)
|
| 1918 |
+
ws = cupy.atleast_1d(ws)
|
| 1919 |
+
if fs is not None:
|
| 1920 |
+
if analog:
|
| 1921 |
+
raise ValueError("fs cannot be specified for an analog filter")
|
| 1922 |
+
wp = 2 * wp / fs
|
| 1923 |
+
ws = 2 * ws / fs
|
| 1924 |
+
|
| 1925 |
+
filter_type = 2 * (len(wp) - 1) + 1
|
| 1926 |
+
if wp[0] >= ws[0]:
|
| 1927 |
+
filter_type += 1
|
| 1928 |
+
|
| 1929 |
+
return wp, ws, filter_type
|
| 1930 |
+
|
| 1931 |
+
|
| 1932 |
+
def _find_nat_freq(stopb, passb, gpass, gstop, filter_type, filter_kind):
|
| 1933 |
+
if filter_type == 1: # low
|
| 1934 |
+
nat = stopb / passb
|
| 1935 |
+
elif filter_type == 2: # high
|
| 1936 |
+
nat = passb / stopb
|
| 1937 |
+
elif filter_type == 3: # stop
|
| 1938 |
+
wp0 = _optimize.fminbound(band_stop_obj, passb[0], stopb[0] - 1e-12,
|
| 1939 |
+
args=(0, passb, stopb, gpass, gstop,
|
| 1940 |
+
filter_kind),
|
| 1941 |
+
disp=0)
|
| 1942 |
+
passb[0] = wp0
|
| 1943 |
+
wp1 = _optimize.fminbound(band_stop_obj, stopb[1] + 1e-12, passb[1],
|
| 1944 |
+
args=(1, passb, stopb, gpass, gstop,
|
| 1945 |
+
filter_kind),
|
| 1946 |
+
disp=0)
|
| 1947 |
+
passb[1] = wp1
|
| 1948 |
+
nat = ((stopb * (passb[0] - passb[1])) /
|
| 1949 |
+
(stopb ** 2 - passb[0] * passb[1]))
|
| 1950 |
+
elif filter_type == 4: # pass
|
| 1951 |
+
nat = ((stopb ** 2 - passb[0] * passb[1]) /
|
| 1952 |
+
(stopb * (passb[0] - passb[1])))
|
| 1953 |
+
else:
|
| 1954 |
+
raise ValueError(f"should not happen: {filter_type=}.")
|
| 1955 |
+
|
| 1956 |
+
nat = min(cupy.abs(nat))
|
| 1957 |
+
return nat, passb
|
| 1958 |
+
|
| 1959 |
+
|
| 1960 |
+
def _postprocess_wn(WN, analog, fs):
|
| 1961 |
+
wn = WN if analog else cupy.arctan(WN) * 2.0 / pi
|
| 1962 |
+
if len(wn) == 1:
|
| 1963 |
+
wn = wn[0]
|
| 1964 |
+
if fs is not None:
|
| 1965 |
+
wn = wn * fs / 2
|
| 1966 |
+
return wn
|
| 1967 |
+
|
| 1968 |
+
|
| 1969 |
+
def band_stop_obj(wp, ind, passb, stopb, gpass, gstop, type):
|
| 1970 |
+
"""
|
| 1971 |
+
Band Stop Objective Function for order minimization.
|
| 1972 |
+
|
| 1973 |
+
Returns the non-integer order for an analog band stop filter.
|
| 1974 |
+
|
| 1975 |
+
Parameters
|
| 1976 |
+
----------
|
| 1977 |
+
wp : scalar
|
| 1978 |
+
Edge of passband `passb`.
|
| 1979 |
+
ind : int, {0, 1}
|
| 1980 |
+
Index specifying which `passb` edge to vary (0 or 1).
|
| 1981 |
+
passb : ndarray
|
| 1982 |
+
Two element sequence of fixed passband edges.
|
| 1983 |
+
stopb : ndarray
|
| 1984 |
+
Two element sequence of fixed stopband edges.
|
| 1985 |
+
gstop : float
|
| 1986 |
+
Amount of attenuation in stopband in dB.
|
| 1987 |
+
gpass : float
|
| 1988 |
+
Amount of ripple in the passband in dB.
|
| 1989 |
+
type : {'butter', 'cheby', 'ellip'}
|
| 1990 |
+
Type of filter.
|
| 1991 |
+
|
| 1992 |
+
Returns
|
| 1993 |
+
-------
|
| 1994 |
+
n : scalar
|
| 1995 |
+
Filter order (possibly non-integer).
|
| 1996 |
+
|
| 1997 |
+
See Also
|
| 1998 |
+
--------
|
| 1999 |
+
scipy.signal.band_stop_obj
|
| 2000 |
+
|
| 2001 |
+
"""
|
| 2002 |
+
|
| 2003 |
+
_validate_gpass_gstop(gpass, gstop)
|
| 2004 |
+
|
| 2005 |
+
passbC = passb.copy()
|
| 2006 |
+
passbC[ind] = wp
|
| 2007 |
+
nat = (stopb * (passbC[0] - passbC[1]) /
|
| 2008 |
+
(stopb ** 2 - passbC[0] * passbC[1]))
|
| 2009 |
+
nat = min(cupy.abs(nat))
|
| 2010 |
+
|
| 2011 |
+
if type == 'butter':
|
| 2012 |
+
GSTOP = 10 ** (0.1 * cupy.abs(gstop))
|
| 2013 |
+
GPASS = 10 ** (0.1 * cupy.abs(gpass))
|
| 2014 |
+
n = (cupy.log10((GSTOP - 1.0) / (GPASS - 1.0)) / (2 * cupy.log10(nat)))
|
| 2015 |
+
elif type == 'cheby':
|
| 2016 |
+
GSTOP = 10 ** (0.1 * cupy.abs(gstop))
|
| 2017 |
+
GPASS = 10 ** (0.1 * cupy.abs(gpass))
|
| 2018 |
+
n = cupy.arccosh(
|
| 2019 |
+
cupy.sqrt((GSTOP - 1.0) / (GPASS - 1.0))) / cupy.arccosh(nat)
|
| 2020 |
+
elif type == 'ellip':
|
| 2021 |
+
GSTOP = 10 ** (0.1 * gstop)
|
| 2022 |
+
GPASS = 10 ** (0.1 * gpass)
|
| 2023 |
+
arg1 = cupy.sqrt((GPASS - 1.0) / (GSTOP - 1.0))
|
| 2024 |
+
arg0 = 1.0 / nat
|
| 2025 |
+
d0 = special.ellipk(cupy.array([arg0 ** 2, 1 - arg0 ** 2]))
|
| 2026 |
+
d1 = special.ellipk(cupy.array([arg1 ** 2, 1 - arg1 ** 2]))
|
| 2027 |
+
n = (d0[0] * d1[1] / (d0[1] * d1[0]))
|
| 2028 |
+
else:
|
| 2029 |
+
raise ValueError("Incorrect type: %s" % type)
|
| 2030 |
+
return n
|
| 2031 |
+
|
| 2032 |
+
|
| 2033 |
+
def buttord(wp, ws, gpass, gstop, analog=False, fs=None):
|
| 2034 |
+
"""Butterworth filter order selection.
|
| 2035 |
+
|
| 2036 |
+
Return the order of the lowest order digital or analog Butterworth filter
|
| 2037 |
+
that loses no more than `gpass` dB in the passband and has at least
|
| 2038 |
+
`gstop` dB attenuation in the stopband.
|
| 2039 |
+
|
| 2040 |
+
Parameters
|
| 2041 |
+
----------
|
| 2042 |
+
wp, ws : float
|
| 2043 |
+
Passband and stopband edge frequencies.
|
| 2044 |
+
|
| 2045 |
+
For digital filters, these are in the same units as `fs`. By default,
|
| 2046 |
+
`fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
|
| 2047 |
+
where 1 is the Nyquist frequency. (`wp` and `ws` are thus in
|
| 2048 |
+
half-cycles / sample.) For example:
|
| 2049 |
+
|
| 2050 |
+
- Lowpass: wp = 0.2, ws = 0.3
|
| 2051 |
+
- Highpass: wp = 0.3, ws = 0.2
|
| 2052 |
+
- Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6]
|
| 2053 |
+
- Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5]
|
| 2054 |
+
|
| 2055 |
+
For analog filters, `wp` and `ws` are angular frequencies
|
| 2056 |
+
(e.g., rad/s).
|
| 2057 |
+
gpass : float
|
| 2058 |
+
The maximum loss in the passband (dB).
|
| 2059 |
+
gstop : float
|
| 2060 |
+
The minimum attenuation in the stopband (dB).
|
| 2061 |
+
analog : bool, optional
|
| 2062 |
+
When True, return an analog filter, otherwise a digital filter is
|
| 2063 |
+
returned.
|
| 2064 |
+
fs : float, optional
|
| 2065 |
+
The sampling frequency of the digital system.
|
| 2066 |
+
|
| 2067 |
+
.. versionadded:: 1.2.0
|
| 2068 |
+
|
| 2069 |
+
Returns
|
| 2070 |
+
-------
|
| 2071 |
+
ord : int
|
| 2072 |
+
The lowest order for a Butterworth filter which meets specs.
|
| 2073 |
+
wn : ndarray or float
|
| 2074 |
+
The Butterworth natural frequency (i.e. the "3dB frequency"). Should
|
| 2075 |
+
be used with `butter` to give filter results. If `fs` is specified,
|
| 2076 |
+
this is in the same units, and `fs` must also be passed to `butter`.
|
| 2077 |
+
|
| 2078 |
+
See Also
|
| 2079 |
+
--------
|
| 2080 |
+
scipy.signal.buttord
|
| 2081 |
+
butter : Filter design using order and critical points
|
| 2082 |
+
cheb1ord : Find order and critical points from passband and stopband spec
|
| 2083 |
+
cheb2ord, ellipord
|
| 2084 |
+
iirfilter : General filter design using order and critical frequencies
|
| 2085 |
+
iirdesign : General filter design using passband and stopband spec
|
| 2086 |
+
|
| 2087 |
+
"""
|
| 2088 |
+
_validate_gpass_gstop(gpass, gstop)
|
| 2089 |
+
wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog)
|
| 2090 |
+
passb, stopb = _pre_warp(wp, ws, analog)
|
| 2091 |
+
nat, passb = _find_nat_freq(
|
| 2092 |
+
stopb, passb, gpass, gstop, filter_type, 'butter')
|
| 2093 |
+
|
| 2094 |
+
GSTOP = 10 ** (0.1 * cupy.abs(gstop))
|
| 2095 |
+
GPASS = 10 ** (0.1 * cupy.abs(gpass))
|
| 2096 |
+
ord = int(cupy.ceil(cupy.log10((GSTOP - 1.0) /
|
| 2097 |
+
(GPASS - 1.0)) / (2 * cupy.log10(nat))))
|
| 2098 |
+
|
| 2099 |
+
# Find the Butterworth natural frequency WN (or the "3dB" frequency")
|
| 2100 |
+
# to give exactly gpass at passb.
|
| 2101 |
+
try:
|
| 2102 |
+
W0 = (GPASS - 1.0) ** (-1.0 / (2.0 * ord))
|
| 2103 |
+
except ZeroDivisionError:
|
| 2104 |
+
W0 = 1.0
|
| 2105 |
+
warnings.warn("Order is zero...check input parameters.",
|
| 2106 |
+
RuntimeWarning, 2)
|
| 2107 |
+
|
| 2108 |
+
# now convert this frequency back from lowpass prototype
|
| 2109 |
+
# to the original analog filter
|
| 2110 |
+
|
| 2111 |
+
if filter_type == 1: # low
|
| 2112 |
+
WN = W0 * passb
|
| 2113 |
+
elif filter_type == 2: # high
|
| 2114 |
+
WN = passb / W0
|
| 2115 |
+
elif filter_type == 3: # stop
|
| 2116 |
+
WN = cupy.empty(2, float)
|
| 2117 |
+
discr = cupy.sqrt((passb[1] - passb[0]) ** 2 +
|
| 2118 |
+
4 * W0 ** 2 * passb[0] * passb[1])
|
| 2119 |
+
WN[0] = ((passb[1] - passb[0]) + discr) / (2 * W0)
|
| 2120 |
+
WN[1] = ((passb[1] - passb[0]) - discr) / (2 * W0)
|
| 2121 |
+
WN = cupy.sort(cupy.abs(WN))
|
| 2122 |
+
elif filter_type == 4: # pass
|
| 2123 |
+
W0 = cupy.array([-W0, W0], dtype=float)
|
| 2124 |
+
WN = (-W0 * (passb[1] - passb[0]) / 2.0 +
|
| 2125 |
+
cupy.sqrt(W0 ** 2 / 4.0 * (passb[1] - passb[0]) ** 2 +
|
| 2126 |
+
passb[0] * passb[1]))
|
| 2127 |
+
WN = cupy.sort(cupy.abs(WN))
|
| 2128 |
+
else:
|
| 2129 |
+
raise ValueError("Bad type: %s" % filter_type)
|
| 2130 |
+
|
| 2131 |
+
wn = _postprocess_wn(WN, analog, fs)
|
| 2132 |
+
|
| 2133 |
+
return ord, wn
|
| 2134 |
+
|
| 2135 |
+
|
| 2136 |
+
def cheb1ord(wp, ws, gpass, gstop, analog=False, fs=None):
|
| 2137 |
+
"""Chebyshev type I filter order selection.
|
| 2138 |
+
|
| 2139 |
+
Return the order of the lowest order digital or analog Chebyshev Type I
|
| 2140 |
+
filter that loses no more than `gpass` dB in the passband and has at
|
| 2141 |
+
least `gstop` dB attenuation in the stopband.
|
| 2142 |
+
|
| 2143 |
+
Parameters
|
| 2144 |
+
----------
|
| 2145 |
+
wp, ws : float
|
| 2146 |
+
Passband and stopband edge frequencies.
|
| 2147 |
+
|
| 2148 |
+
For digital filters, these are in the same units as `fs`. By default,
|
| 2149 |
+
`fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
|
| 2150 |
+
where 1 is the Nyquist frequency. (`wp` and `ws` are thus in
|
| 2151 |
+
half-cycles / sample.) For example:
|
| 2152 |
+
|
| 2153 |
+
- Lowpass: wp = 0.2, ws = 0.3
|
| 2154 |
+
- Highpass: wp = 0.3, ws = 0.2
|
| 2155 |
+
- Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6]
|
| 2156 |
+
- Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5]
|
| 2157 |
+
|
| 2158 |
+
For analog filters, `wp` and `ws` are angular frequencies
|
| 2159 |
+
(e.g., rad/s).
|
| 2160 |
+
gpass : float
|
| 2161 |
+
The maximum loss in the passband (dB).
|
| 2162 |
+
gstop : float
|
| 2163 |
+
The minimum attenuation in the stopband (dB).
|
| 2164 |
+
analog : bool, optional
|
| 2165 |
+
When True, return an analog filter, otherwise a digital filter is
|
| 2166 |
+
returned.
|
| 2167 |
+
fs : float, optional
|
| 2168 |
+
The sampling frequency of the digital system.
|
| 2169 |
+
|
| 2170 |
+
Returns
|
| 2171 |
+
-------
|
| 2172 |
+
ord : int
|
| 2173 |
+
The lowest order for a Chebyshev type I filter that meets specs.
|
| 2174 |
+
wn : ndarray or float
|
| 2175 |
+
The Chebyshev natural frequency (the "3dB frequency") for use with
|
| 2176 |
+
`cheby1` to give filter results. If `fs` is specified,
|
| 2177 |
+
this is in the same units, and `fs` must also be passed to `cheby1`.
|
| 2178 |
+
|
| 2179 |
+
See Also
|
| 2180 |
+
--------
|
| 2181 |
+
scipy.signal.cheb1ord
|
| 2182 |
+
cheby1 : Filter design using order and critical points
|
| 2183 |
+
buttord : Find order and critical points from passband and stopband spec
|
| 2184 |
+
cheb2ord, ellipord
|
| 2185 |
+
iirfilter : General filter design using order and critical frequencies
|
| 2186 |
+
iirdesign : General filter design using passband and stopband spec
|
| 2187 |
+
|
| 2188 |
+
"""
|
| 2189 |
+
_validate_gpass_gstop(gpass, gstop)
|
| 2190 |
+
wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog)
|
| 2191 |
+
passb, stopb = _pre_warp(wp, ws, analog)
|
| 2192 |
+
nat, passb = _find_nat_freq(
|
| 2193 |
+
stopb, passb, gpass, gstop, filter_type, 'cheby')
|
| 2194 |
+
|
| 2195 |
+
GSTOP = 10 ** (0.1 * cupy.abs(gstop))
|
| 2196 |
+
GPASS = 10 ** (0.1 * cupy.abs(gpass))
|
| 2197 |
+
v_pass_stop = cupy.arccosh(cupy.sqrt((GSTOP - 1.0) / (GPASS - 1.0)))
|
| 2198 |
+
ord = int(cupy.ceil(v_pass_stop / cupy.arccosh(nat)))
|
| 2199 |
+
|
| 2200 |
+
# Natural frequencies are just the passband edges
|
| 2201 |
+
wn = _postprocess_wn(passb, analog, fs)
|
| 2202 |
+
|
| 2203 |
+
return ord, wn
|
| 2204 |
+
|
| 2205 |
+
|
| 2206 |
+
def cheb2ord(wp, ws, gpass, gstop, analog=False, fs=None):
|
| 2207 |
+
"""Chebyshev type II filter order selection.
|
| 2208 |
+
|
| 2209 |
+
Return the order of the lowest order digital or analog Chebyshev Type II
|
| 2210 |
+
filter that loses no more than `gpass` dB in the passband and has at least
|
| 2211 |
+
`gstop` dB attenuation in the stopband.
|
| 2212 |
+
|
| 2213 |
+
Parameters
|
| 2214 |
+
----------
|
| 2215 |
+
wp, ws : float
|
| 2216 |
+
Passband and stopband edge frequencies.
|
| 2217 |
+
|
| 2218 |
+
For digital filters, these are in the same units as `fs`. By default,
|
| 2219 |
+
`fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
|
| 2220 |
+
where 1 is the Nyquist frequency. (`wp` and `ws` are thus in
|
| 2221 |
+
half-cycles / sample.) For example:
|
| 2222 |
+
|
| 2223 |
+
- Lowpass: wp = 0.2, ws = 0.3
|
| 2224 |
+
- Highpass: wp = 0.3, ws = 0.2
|
| 2225 |
+
- Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6]
|
| 2226 |
+
- Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5]
|
| 2227 |
+
|
| 2228 |
+
For analog filters, `wp` and `ws` are angular frequencies
|
| 2229 |
+
(e.g., rad/s).
|
| 2230 |
+
gpass : float
|
| 2231 |
+
The maximum loss in the passband (dB).
|
| 2232 |
+
gstop : float
|
| 2233 |
+
The minimum attenuation in the stopband (dB).
|
| 2234 |
+
analog : bool, optional
|
| 2235 |
+
When True, return an analog filter, otherwise a digital filter is
|
| 2236 |
+
returned.
|
| 2237 |
+
fs : float, optional
|
| 2238 |
+
The sampling frequency of the digital system.
|
| 2239 |
+
|
| 2240 |
+
Returns
|
| 2241 |
+
-------
|
| 2242 |
+
ord : int
|
| 2243 |
+
The lowest order for a Chebyshev type II filter that meets specs.
|
| 2244 |
+
wn : ndarray or float
|
| 2245 |
+
The Chebyshev natural frequency (the "3dB frequency") for use with
|
| 2246 |
+
`cheby2` to give filter results. If `fs` is specified,
|
| 2247 |
+
this is in the same units, and `fs` must also be passed to `cheby2`.
|
| 2248 |
+
|
| 2249 |
+
See Also
|
| 2250 |
+
--------
|
| 2251 |
+
scipy.signal.cheb2ord
|
| 2252 |
+
cheby2 : Filter design using order and critical points
|
| 2253 |
+
buttord : Find order and critical points from passband and stopband spec
|
| 2254 |
+
cheb1ord, ellipord
|
| 2255 |
+
iirfilter : General filter design using order and critical frequencies
|
| 2256 |
+
iirdesign : General filter design using passband and stopband spec
|
| 2257 |
+
|
| 2258 |
+
"""
|
| 2259 |
+
_validate_gpass_gstop(gpass, gstop)
|
| 2260 |
+
wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog)
|
| 2261 |
+
passb, stopb = _pre_warp(wp, ws, analog)
|
| 2262 |
+
nat, passb = _find_nat_freq(
|
| 2263 |
+
stopb, passb, gpass, gstop, filter_type, 'cheby')
|
| 2264 |
+
|
| 2265 |
+
GSTOP = 10 ** (0.1 * cupy.abs(gstop))
|
| 2266 |
+
GPASS = 10 ** (0.1 * cupy.abs(gpass))
|
| 2267 |
+
v_pass_stop = cupy.arccosh(cupy.sqrt((GSTOP - 1.0) / (GPASS - 1.0)))
|
| 2268 |
+
ord = int(cupy.ceil(v_pass_stop / cupy.arccosh(nat)))
|
| 2269 |
+
|
| 2270 |
+
# Find frequency where analog response is -gpass dB.
|
| 2271 |
+
# Then convert back from low-pass prototype to the original filter.
|
| 2272 |
+
|
| 2273 |
+
new_freq = cupy.cosh(1.0 / ord * v_pass_stop)
|
| 2274 |
+
new_freq = 1.0 / new_freq
|
| 2275 |
+
|
| 2276 |
+
if filter_type == 1:
|
| 2277 |
+
nat = passb / new_freq
|
| 2278 |
+
elif filter_type == 2:
|
| 2279 |
+
nat = passb * new_freq
|
| 2280 |
+
elif filter_type == 3:
|
| 2281 |
+
nat = cupy.empty(2, dtype=float)
|
| 2282 |
+
nat[0] = (new_freq / 2.0 * (passb[0] - passb[1]) +
|
| 2283 |
+
cupy.sqrt(new_freq ** 2 * (passb[1] - passb[0]) ** 2 / 4.0 +
|
| 2284 |
+
passb[1] * passb[0]))
|
| 2285 |
+
nat[1] = passb[1] * passb[0] / nat[0]
|
| 2286 |
+
elif filter_type == 4:
|
| 2287 |
+
nat = cupy.empty(2, dtype=float)
|
| 2288 |
+
nat[0] = (1.0 / (2.0 * new_freq) * (passb[0] - passb[1]) +
|
| 2289 |
+
cupy.sqrt((passb[1] - passb[0]) ** 2 / (4.0 * new_freq ** 2)
|
| 2290 |
+
+ passb[1] * passb[0]))
|
| 2291 |
+
nat[1] = passb[0] * passb[1] / nat[0]
|
| 2292 |
+
|
| 2293 |
+
wn = _postprocess_wn(nat, analog, fs)
|
| 2294 |
+
|
| 2295 |
+
return ord, wn
|
| 2296 |
+
|
| 2297 |
+
|
| 2298 |
+
def ellipord(wp, ws, gpass, gstop, analog=False, fs=None):
|
| 2299 |
+
"""Elliptic (Cauer) filter order selection.
|
| 2300 |
+
|
| 2301 |
+
Return the order of the lowest order digital or analog elliptic filter
|
| 2302 |
+
that loses no more than `gpass` dB in the passband and has at least
|
| 2303 |
+
`gstop` dB attenuation in the stopband.
|
| 2304 |
+
|
| 2305 |
+
Parameters
|
| 2306 |
+
----------
|
| 2307 |
+
wp, ws : float
|
| 2308 |
+
Passband and stopband edge frequencies.
|
| 2309 |
+
|
| 2310 |
+
For digital filters, these are in the same units as `fs`. By default,
|
| 2311 |
+
`fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
|
| 2312 |
+
where 1 is the Nyquist frequency. (`wp` and `ws` are thus in
|
| 2313 |
+
half-cycles / sample.) For example:
|
| 2314 |
+
|
| 2315 |
+
- Lowpass: wp = 0.2, ws = 0.3
|
| 2316 |
+
- Highpass: wp = 0.3, ws = 0.2
|
| 2317 |
+
- Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6]
|
| 2318 |
+
- Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5]
|
| 2319 |
+
|
| 2320 |
+
For analog filters, `wp` and `ws` are angular frequencies
|
| 2321 |
+
(e.g., rad/s).
|
| 2322 |
+
gpass : float
|
| 2323 |
+
The maximum loss in the passband (dB).
|
| 2324 |
+
gstop : float
|
| 2325 |
+
The minimum attenuation in the stopband (dB).
|
| 2326 |
+
analog : bool, optional
|
| 2327 |
+
When True, return an analog filter, otherwise a digital filter is
|
| 2328 |
+
returned.
|
| 2329 |
+
fs : float, optional
|
| 2330 |
+
The sampling frequency of the digital system.
|
| 2331 |
+
|
| 2332 |
+
Returns
|
| 2333 |
+
-------
|
| 2334 |
+
ord : int
|
| 2335 |
+
The lowest order for an Elliptic (Cauer) filter that meets specs.
|
| 2336 |
+
wn : ndarray or float
|
| 2337 |
+
The Chebyshev natural frequency (the "3dB frequency") for use with
|
| 2338 |
+
`ellip` to give filter results. If `fs` is specified,
|
| 2339 |
+
this is in the same units, and `fs` must also be passed to `ellip`.
|
| 2340 |
+
|
| 2341 |
+
See Also
|
| 2342 |
+
--------
|
| 2343 |
+
scipy.signal.ellipord
|
| 2344 |
+
ellip : Filter design using order and critical points
|
| 2345 |
+
buttord : Find order and critical points from passband and stopband spec
|
| 2346 |
+
cheb1ord, cheb2ord
|
| 2347 |
+
iirfilter : General filter design using order and critical frequencies
|
| 2348 |
+
iirdesign : General filter design using passband and stopband spec
|
| 2349 |
+
"""
|
| 2350 |
+
_validate_gpass_gstop(gpass, gstop)
|
| 2351 |
+
wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog)
|
| 2352 |
+
passb, stopb = _pre_warp(wp, ws, analog)
|
| 2353 |
+
nat, passb = _find_nat_freq(
|
| 2354 |
+
stopb, passb, gpass, gstop, filter_type, 'ellip')
|
| 2355 |
+
|
| 2356 |
+
arg1_sq = _pow10m1(0.1 * gpass) / _pow10m1(0.1 * gstop)
|
| 2357 |
+
arg0 = 1.0 / nat
|
| 2358 |
+
d0 = special.ellipk(arg0 ** 2), special.ellipkm1(arg0 ** 2)
|
| 2359 |
+
d1 = special.ellipk(arg1_sq), special.ellipkm1(arg1_sq)
|
| 2360 |
+
ord = int(cupy.ceil(d0[0] * d1[1] / (d0[1] * d1[0])))
|
| 2361 |
+
|
| 2362 |
+
wn = _postprocess_wn(passb, analog, fs)
|
| 2363 |
+
|
| 2364 |
+
return ord, wn
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_iir_filter_design.py
ADDED
|
@@ -0,0 +1,994 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from cupyx.scipy.signal._iir_filter_conversions import (
|
| 10 |
+
buttap, cheb1ap, cheb2ap, ellipap, buttord, ellipord, cheb1ord, cheb2ord,
|
| 11 |
+
_validate_gpass_gstop)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# FIXME
|
| 15 |
+
|
| 16 |
+
def besselap():
|
| 17 |
+
raise NotImplementedError
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
bessel_norms = {'fix': 'me'}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def iirfilter(N, Wn, rp=None, rs=None, btype='band', analog=False,
|
| 24 |
+
ftype='butter', output='ba', fs=None):
|
| 25 |
+
"""
|
| 26 |
+
IIR digital and analog filter design given order and critical points.
|
| 27 |
+
|
| 28 |
+
Design an Nth-order digital or analog filter and return the filter
|
| 29 |
+
coefficients.
|
| 30 |
+
|
| 31 |
+
Parameters
|
| 32 |
+
----------
|
| 33 |
+
N : int
|
| 34 |
+
The order of the filter.
|
| 35 |
+
Wn : array_like
|
| 36 |
+
A scalar or length-2 sequence giving the critical frequencies.
|
| 37 |
+
|
| 38 |
+
For digital filters, `Wn` are in the same units as `fs`. By default,
|
| 39 |
+
`fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
|
| 40 |
+
where 1 is the Nyquist frequency. (`Wn` is thus in
|
| 41 |
+
half-cycles / sample.)
|
| 42 |
+
|
| 43 |
+
For analog filters, `Wn` is an angular frequency (e.g., rad/s).
|
| 44 |
+
|
| 45 |
+
When Wn is a length-2 sequence, ``Wn[0]`` must be less than ``Wn[1]``.
|
| 46 |
+
rp : float, optional
|
| 47 |
+
For Chebyshev and elliptic filters, provides the maximum ripple
|
| 48 |
+
in the passband. (dB)
|
| 49 |
+
rs : float, optional
|
| 50 |
+
For Chebyshev and elliptic filters, provides the minimum attenuation
|
| 51 |
+
in the stop band. (dB)
|
| 52 |
+
btype : {'bandpass', 'lowpass', 'highpass', 'bandstop'}, optional
|
| 53 |
+
The type of filter. Default is 'bandpass'.
|
| 54 |
+
analog : bool, optional
|
| 55 |
+
When True, return an analog filter, otherwise a digital filter is
|
| 56 |
+
returned.
|
| 57 |
+
ftype : str, optional
|
| 58 |
+
The type of IIR filter to design:
|
| 59 |
+
|
| 60 |
+
- Butterworth : 'butter'
|
| 61 |
+
- Chebyshev I : 'cheby1'
|
| 62 |
+
- Chebyshev II : 'cheby2'
|
| 63 |
+
- Cauer/elliptic: 'ellip'
|
| 64 |
+
- Bessel/Thomson: 'bessel'
|
| 65 |
+
|
| 66 |
+
output : {'ba', 'zpk', 'sos'}, optional
|
| 67 |
+
Filter form of the output:
|
| 68 |
+
|
| 69 |
+
- second-order sections (recommended): 'sos'
|
| 70 |
+
- numerator/denominator (default) : 'ba'
|
| 71 |
+
- pole-zero : 'zpk'
|
| 72 |
+
|
| 73 |
+
In general the second-order sections ('sos') form is
|
| 74 |
+
recommended because inferring the coefficients for the
|
| 75 |
+
numerator/denominator form ('ba') suffers from numerical
|
| 76 |
+
instabilities. For reasons of backward compatibility the default
|
| 77 |
+
form is the numerator/denominator form ('ba'), where the 'b'
|
| 78 |
+
and the 'a' in 'ba' refer to the commonly used names of the
|
| 79 |
+
coefficients used.
|
| 80 |
+
|
| 81 |
+
Note: Using the second-order sections form ('sos') is sometimes
|
| 82 |
+
associated with additional computational costs: for
|
| 83 |
+
data-intense use cases it is therefore recommended to also
|
| 84 |
+
investigate the numerator/denominator form ('ba').
|
| 85 |
+
|
| 86 |
+
fs : float, optional
|
| 87 |
+
The sampling frequency of the digital system.
|
| 88 |
+
|
| 89 |
+
Returns
|
| 90 |
+
-------
|
| 91 |
+
b, a : ndarray, ndarray
|
| 92 |
+
Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
|
| 93 |
+
Only returned if ``output='ba'``.
|
| 94 |
+
z, p, k : ndarray, ndarray, float
|
| 95 |
+
Zeros, poles, and system gain of the IIR filter transfer
|
| 96 |
+
function. Only returned if ``output='zpk'``.
|
| 97 |
+
sos : ndarray
|
| 98 |
+
Second-order sections representation of the IIR filter.
|
| 99 |
+
Only returned if ``output='sos'``.
|
| 100 |
+
|
| 101 |
+
See Also
|
| 102 |
+
--------
|
| 103 |
+
butter : Filter design using order and critical points
|
| 104 |
+
cheby1, cheby2, ellip, bessel
|
| 105 |
+
buttord : Find order and critical points from passband and stopband spec
|
| 106 |
+
cheb1ord, cheb2ord, ellipord
|
| 107 |
+
iirdesign : General filter design using passband and stopband spec
|
| 108 |
+
scipy.signal.iirfilter
|
| 109 |
+
|
| 110 |
+
"""
|
| 111 |
+
ftype, btype, output = [x.lower() for x in (ftype, btype, output)]
|
| 112 |
+
|
| 113 |
+
Wn = cupy.asarray(Wn)
|
| 114 |
+
# if cupy.any(Wn <= 0):
|
| 115 |
+
# raise ValueError("filter critical frequencies must be greater than 0")
|
| 116 |
+
|
| 117 |
+
if Wn.size > 1 and not Wn[0] < Wn[1]:
|
| 118 |
+
raise ValueError("Wn[0] must be less than Wn[1]")
|
| 119 |
+
|
| 120 |
+
if fs is not None:
|
| 121 |
+
if analog:
|
| 122 |
+
raise ValueError("fs cannot be specified for an analog filter")
|
| 123 |
+
Wn = 2*Wn/fs
|
| 124 |
+
|
| 125 |
+
try:
|
| 126 |
+
btype = band_dict[btype]
|
| 127 |
+
except KeyError as e:
|
| 128 |
+
raise ValueError(
|
| 129 |
+
"'%s' is an invalid bandtype for filter." % btype) from e
|
| 130 |
+
|
| 131 |
+
try:
|
| 132 |
+
typefunc = filter_dict[ftype][0]
|
| 133 |
+
except KeyError as e:
|
| 134 |
+
raise ValueError(
|
| 135 |
+
"'%s' is not a valid basic IIR filter." % ftype) from e
|
| 136 |
+
|
| 137 |
+
if output not in ['ba', 'zpk', 'sos']:
|
| 138 |
+
raise ValueError("'%s' is not a valid output form." % output)
|
| 139 |
+
|
| 140 |
+
if rp is not None and rp < 0:
|
| 141 |
+
raise ValueError("passband ripple (rp) must be positive")
|
| 142 |
+
|
| 143 |
+
if rs is not None and rs < 0:
|
| 144 |
+
raise ValueError("stopband attenuation (rs) must be positive")
|
| 145 |
+
|
| 146 |
+
# Get analog lowpass prototype
|
| 147 |
+
if typefunc == buttap:
|
| 148 |
+
z, p, k = typefunc(N)
|
| 149 |
+
elif typefunc == besselap:
|
| 150 |
+
z, p, k = typefunc(N, norm=bessel_norms[ftype])
|
| 151 |
+
elif typefunc == cheb1ap:
|
| 152 |
+
if rp is None:
|
| 153 |
+
raise ValueError("passband ripple (rp) must be provided to "
|
| 154 |
+
"design a Chebyshev I filter.")
|
| 155 |
+
z, p, k = typefunc(N, rp)
|
| 156 |
+
elif typefunc == cheb2ap:
|
| 157 |
+
if rs is None:
|
| 158 |
+
raise ValueError("stopband attenuation (rs) must be provided to "
|
| 159 |
+
"design an Chebyshev II filter.")
|
| 160 |
+
z, p, k = typefunc(N, rs)
|
| 161 |
+
elif typefunc == ellipap:
|
| 162 |
+
if rs is None or rp is None:
|
| 163 |
+
raise ValueError("Both rp and rs must be provided to design an "
|
| 164 |
+
"elliptic filter.")
|
| 165 |
+
z, p, k = typefunc(N, rp, rs)
|
| 166 |
+
else:
|
| 167 |
+
raise NotImplementedError("'%s' not implemented in iirfilter." % ftype)
|
| 168 |
+
|
| 169 |
+
# Pre-warp frequencies for digital filter design
|
| 170 |
+
if not analog:
|
| 171 |
+
if cupy.any(Wn <= 0) or cupy.any(Wn >= 1):
|
| 172 |
+
if fs is not None:
|
| 173 |
+
raise ValueError("Digital filter critical frequencies must "
|
| 174 |
+
f"be 0 < Wn < fs/2 (fs={fs} -> fs/2={fs/2})")
|
| 175 |
+
raise ValueError("Digital filter critical frequencies "
|
| 176 |
+
"must be 0 < Wn < 1")
|
| 177 |
+
fs = 2.0
|
| 178 |
+
warped = 2 * fs * cupy.tan(pi * Wn / fs)
|
| 179 |
+
else:
|
| 180 |
+
warped = Wn
|
| 181 |
+
|
| 182 |
+
# transform to lowpass, bandpass, highpass, or bandstop
|
| 183 |
+
if btype in ('lowpass', 'highpass'):
|
| 184 |
+
if cupy.size(Wn) != 1:
|
| 185 |
+
raise ValueError('Must specify a single critical frequency Wn '
|
| 186 |
+
'for lowpass or highpass filter')
|
| 187 |
+
|
| 188 |
+
if btype == 'lowpass':
|
| 189 |
+
z, p, k = lp2lp_zpk(z, p, k, wo=warped)
|
| 190 |
+
elif btype == 'highpass':
|
| 191 |
+
z, p, k = lp2hp_zpk(z, p, k, wo=warped)
|
| 192 |
+
elif btype in ('bandpass', 'bandstop'):
|
| 193 |
+
try:
|
| 194 |
+
bw = warped[1] - warped[0]
|
| 195 |
+
wo = cupy.sqrt(warped[0] * warped[1])
|
| 196 |
+
except IndexError as e:
|
| 197 |
+
raise ValueError('Wn must specify start and stop frequencies for '
|
| 198 |
+
'bandpass or bandstop filter') from e
|
| 199 |
+
|
| 200 |
+
if btype == 'bandpass':
|
| 201 |
+
z, p, k = lp2bp_zpk(z, p, k, wo=wo, bw=bw)
|
| 202 |
+
elif btype == 'bandstop':
|
| 203 |
+
z, p, k = lp2bs_zpk(z, p, k, wo=wo, bw=bw)
|
| 204 |
+
else:
|
| 205 |
+
raise NotImplementedError("'%s' not implemented in iirfilter." % btype)
|
| 206 |
+
|
| 207 |
+
# Find discrete equivalent if necessary
|
| 208 |
+
if not analog:
|
| 209 |
+
z, p, k = bilinear_zpk(z, p, k, fs=fs)
|
| 210 |
+
|
| 211 |
+
# Transform to proper out type (pole-zero, state-space, numer-denom)
|
| 212 |
+
if output == 'zpk':
|
| 213 |
+
return z, p, k
|
| 214 |
+
elif output == 'ba':
|
| 215 |
+
return zpk2tf(z, p, k)
|
| 216 |
+
elif output == 'sos':
|
| 217 |
+
return zpk2sos(z, p, k, analog=analog)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def butter(N, Wn, btype='low', analog=False, output='ba', fs=None):
|
| 221 |
+
"""
|
| 222 |
+
Butterworth digital and analog filter design.
|
| 223 |
+
|
| 224 |
+
Design an Nth-order digital or analog Butterworth filter and return
|
| 225 |
+
the filter coefficients.
|
| 226 |
+
|
| 227 |
+
Parameters
|
| 228 |
+
----------
|
| 229 |
+
N : int
|
| 230 |
+
The order of the filter. For 'bandpass' and 'bandstop' filters,
|
| 231 |
+
the resulting order of the final second-order sections ('sos')
|
| 232 |
+
matrix is ``2*N``, with `N` the number of biquad sections
|
| 233 |
+
of the desired system.
|
| 234 |
+
Wn : array_like
|
| 235 |
+
The critical frequency or frequencies. For lowpass and highpass
|
| 236 |
+
filters, Wn is a scalar; for bandpass and bandstop filters,
|
| 237 |
+
Wn is a length-2 sequence.
|
| 238 |
+
|
| 239 |
+
For a Butterworth filter, this is the point at which the gain
|
| 240 |
+
drops to 1/sqrt(2) that of the passband (the "-3 dB point").
|
| 241 |
+
|
| 242 |
+
For digital filters, if `fs` is not specified, `Wn` units are
|
| 243 |
+
normalized from 0 to 1, where 1 is the Nyquist frequency (`Wn` is
|
| 244 |
+
thus in half cycles / sample and defined as 2*critical frequencies
|
| 245 |
+
/ `fs`). If `fs` is specified, `Wn` is in the same units as `fs`.
|
| 246 |
+
|
| 247 |
+
For analog filters, `Wn` is an angular frequency (e.g. rad/s).
|
| 248 |
+
btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional
|
| 249 |
+
The type of filter. Default is 'lowpass'.
|
| 250 |
+
analog : bool, optional
|
| 251 |
+
When True, return an analog filter, otherwise a digital filter is
|
| 252 |
+
returned.
|
| 253 |
+
output : {'ba', 'zpk', 'sos'}, optional
|
| 254 |
+
Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or
|
| 255 |
+
second-order sections ('sos'). Default is 'ba' for backwards
|
| 256 |
+
compatibility, but 'sos' should be used for general-purpose filtering.
|
| 257 |
+
fs : float, optional
|
| 258 |
+
The sampling frequency of the digital system.
|
| 259 |
+
|
| 260 |
+
Returns
|
| 261 |
+
-------
|
| 262 |
+
b, a : ndarray, ndarray
|
| 263 |
+
Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
|
| 264 |
+
Only returned if ``output='ba'``.
|
| 265 |
+
z, p, k : ndarray, ndarray, float
|
| 266 |
+
Zeros, poles, and system gain of the IIR filter transfer
|
| 267 |
+
function. Only returned if ``output='zpk'``.
|
| 268 |
+
sos : ndarray
|
| 269 |
+
Second-order sections representation of the IIR filter.
|
| 270 |
+
Only returned if ``output='sos'``.
|
| 271 |
+
|
| 272 |
+
See Also
|
| 273 |
+
--------
|
| 274 |
+
buttord, buttap
|
| 275 |
+
iirfilter
|
| 276 |
+
scipy.signal.butter
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
Notes
|
| 280 |
+
-----
|
| 281 |
+
The Butterworth filter has maximally flat frequency response in the
|
| 282 |
+
passband.
|
| 283 |
+
|
| 284 |
+
If the transfer function form ``[b, a]`` is requested, numerical
|
| 285 |
+
problems can occur since the conversion between roots and
|
| 286 |
+
the polynomial coefficients is a numerically sensitive operation,
|
| 287 |
+
even for N >= 4. It is recommended to work with the SOS
|
| 288 |
+
representation.
|
| 289 |
+
|
| 290 |
+
.. warning::
|
| 291 |
+
Designing high-order and narrowband IIR filters in TF form can
|
| 292 |
+
result in unstable or incorrect filtering due to floating point
|
| 293 |
+
numerical precision issues. Consider inspecting output filter
|
| 294 |
+
characteristics `freqz` or designing the filters with second-order
|
| 295 |
+
sections via ``output='sos'``.
|
| 296 |
+
"""
|
| 297 |
+
return iirfilter(N, Wn, btype=btype, analog=analog,
|
| 298 |
+
output=output, ftype='butter', fs=fs)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def cheby1(N, rp, Wn, btype='low', analog=False, output='ba', fs=None):
|
| 302 |
+
"""
|
| 303 |
+
Chebyshev type I digital and analog filter design.
|
| 304 |
+
|
| 305 |
+
Design an Nth-order digital or analog Chebyshev type I filter and
|
| 306 |
+
return the filter coefficients.
|
| 307 |
+
|
| 308 |
+
Parameters
|
| 309 |
+
----------
|
| 310 |
+
N : int
|
| 311 |
+
The order of the filter.
|
| 312 |
+
rp : float
|
| 313 |
+
The maximum ripple allowed below unity gain in the passband.
|
| 314 |
+
Specified in decibels, as a positive number.
|
| 315 |
+
Wn : array_like
|
| 316 |
+
A scalar or length-2 sequence giving the critical frequencies.
|
| 317 |
+
For Type I filters, this is the point in the transition band at which
|
| 318 |
+
the gain first drops below -`rp`.
|
| 319 |
+
|
| 320 |
+
For digital filters, `Wn` are in the same units as `fs`. By default,
|
| 321 |
+
`fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
|
| 322 |
+
where 1 is the Nyquist frequency. (`Wn` is thus in
|
| 323 |
+
half-cycles / sample.)
|
| 324 |
+
|
| 325 |
+
For analog filters, `Wn` is an angular frequency (e.g., rad/s).
|
| 326 |
+
btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional
|
| 327 |
+
The type of filter. Default is 'lowpass'.
|
| 328 |
+
analog : bool, optional
|
| 329 |
+
When True, return an analog filter, otherwise a digital filter is
|
| 330 |
+
returned.
|
| 331 |
+
output : {'ba', 'zpk', 'sos'}, optional
|
| 332 |
+
Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or
|
| 333 |
+
second-order sections ('sos'). Default is 'ba' for backwards
|
| 334 |
+
compatibility, but 'sos' should be used for general-purpose filtering.
|
| 335 |
+
fs : float, optional
|
| 336 |
+
The sampling frequency of the digital system.
|
| 337 |
+
|
| 338 |
+
Returns
|
| 339 |
+
-------
|
| 340 |
+
b, a : ndarray, ndarray
|
| 341 |
+
Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
|
| 342 |
+
Only returned if ``output='ba'``.
|
| 343 |
+
z, p, k : ndarray, ndarray, float
|
| 344 |
+
Zeros, poles, and system gain of the IIR filter transfer
|
| 345 |
+
function. Only returned if ``output='zpk'``.
|
| 346 |
+
sos : ndarray
|
| 347 |
+
Second-order sections representation of the IIR filter.
|
| 348 |
+
Only returned if ``output='sos'``.
|
| 349 |
+
|
| 350 |
+
See Also
|
| 351 |
+
--------
|
| 352 |
+
cheb1ord, cheb1ap
|
| 353 |
+
iirfilter
|
| 354 |
+
scipy.signal.cheby1
|
| 355 |
+
|
| 356 |
+
Notes
|
| 357 |
+
-----
|
| 358 |
+
The Chebyshev type I filter maximizes the rate of cutoff between the
|
| 359 |
+
frequency response's passband and stopband, at the expense of ripple in
|
| 360 |
+
the passband and increased ringing in the step response.
|
| 361 |
+
|
| 362 |
+
Type I filters roll off faster than Type II (`cheby2`), but Type II
|
| 363 |
+
filters do not have any ripple in the passband.
|
| 364 |
+
|
| 365 |
+
The equiripple passband has N maxima or minima (for example, a
|
| 366 |
+
5th-order filter has 3 maxima and 2 minima). Consequently, the DC gain is
|
| 367 |
+
unity for odd-order filters, or -rp dB for even-order filters.
|
| 368 |
+
"""
|
| 369 |
+
return iirfilter(N, Wn, rp=rp, btype=btype, analog=analog,
|
| 370 |
+
output=output, ftype='cheby1', fs=fs)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def cheby2(N, rs, Wn, btype='low', analog=False, output='ba', fs=None):
|
| 374 |
+
"""
|
| 375 |
+
Chebyshev type II digital and analog filter design.
|
| 376 |
+
|
| 377 |
+
Design an Nth-order digital or analog Chebyshev type II filter and
|
| 378 |
+
return the filter coefficients.
|
| 379 |
+
|
| 380 |
+
Parameters
|
| 381 |
+
----------
|
| 382 |
+
N : int
|
| 383 |
+
The order of the filter.
|
| 384 |
+
rs : float
|
| 385 |
+
The minimum attenuation required in the stop band.
|
| 386 |
+
Specified in decibels, as a positive number.
|
| 387 |
+
Wn : array_like
|
| 388 |
+
A scalar or length-2 sequence giving the critical frequencies.
|
| 389 |
+
For Type II filters, this is the point in the transition band at which
|
| 390 |
+
the gain first reaches -`rs`.
|
| 391 |
+
|
| 392 |
+
For digital filters, `Wn` are in the same units as `fs`. By default,
|
| 393 |
+
`fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
|
| 394 |
+
where 1 is the Nyquist frequency. (`Wn` is thus in
|
| 395 |
+
half-cycles / sample.)
|
| 396 |
+
|
| 397 |
+
For analog filters, `Wn` is an angular frequency (e.g., rad/s).
|
| 398 |
+
btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional
|
| 399 |
+
The type of filter. Default is 'lowpass'.
|
| 400 |
+
analog : bool, optional
|
| 401 |
+
When True, return an analog filter, otherwise a digital filter is
|
| 402 |
+
returned.
|
| 403 |
+
output : {'ba', 'zpk', 'sos'}, optional
|
| 404 |
+
Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or
|
| 405 |
+
second-order sections ('sos'). Default is 'ba' for backwards
|
| 406 |
+
compatibility, but 'sos' should be used for general-purpose filtering.
|
| 407 |
+
fs : float, optional
|
| 408 |
+
The sampling frequency of the digital system.
|
| 409 |
+
|
| 410 |
+
Returns
|
| 411 |
+
-------
|
| 412 |
+
b, a : ndarray, ndarray
|
| 413 |
+
Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
|
| 414 |
+
Only returned if ``output='ba'``.
|
| 415 |
+
z, p, k : ndarray, ndarray, float
|
| 416 |
+
Zeros, poles, and system gain of the IIR filter transfer
|
| 417 |
+
function. Only returned if ``output='zpk'``.
|
| 418 |
+
sos : ndarray
|
| 419 |
+
Second-order sections representation of the IIR filter.
|
| 420 |
+
Only returned if ``output='sos'``.
|
| 421 |
+
|
| 422 |
+
See Also
|
| 423 |
+
--------
|
| 424 |
+
cheb2ord, cheb2ap
|
| 425 |
+
iirfilter
|
| 426 |
+
scipy.signal.cheby2
|
| 427 |
+
|
| 428 |
+
Notes
|
| 429 |
+
-----
|
| 430 |
+
The Chebyshev type II filter maximizes the rate of cutoff between the
|
| 431 |
+
frequency response's passband and stopband, at the expense of ripple in
|
| 432 |
+
the stopband and increased ringing in the step response.
|
| 433 |
+
|
| 434 |
+
Type II filters do not roll off as fast as Type I (`cheby1`).
|
| 435 |
+
"""
|
| 436 |
+
return iirfilter(N, Wn, rs=rs, btype=btype, analog=analog,
|
| 437 |
+
output=output, ftype='cheby2', fs=fs)
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def ellip(N, rp, rs, Wn, btype='low', analog=False, output='ba', fs=None):
|
| 441 |
+
"""
|
| 442 |
+
Elliptic (Cauer) digital and analog filter design.
|
| 443 |
+
|
| 444 |
+
Design an Nth-order digital or analog elliptic filter and return
|
| 445 |
+
the filter coefficients.
|
| 446 |
+
|
| 447 |
+
Parameters
|
| 448 |
+
----------
|
| 449 |
+
N : int
|
| 450 |
+
The order of the filter.
|
| 451 |
+
rp : float
|
| 452 |
+
The maximum ripple allowed below unity gain in the passband.
|
| 453 |
+
Specified in decibels, as a positive number.
|
| 454 |
+
rs : float
|
| 455 |
+
The minimum attenuation required in the stop band.
|
| 456 |
+
Specified in decibels, as a positive number.
|
| 457 |
+
Wn : array_like
|
| 458 |
+
A scalar or length-2 sequence giving the critical frequencies.
|
| 459 |
+
For elliptic filters, this is the point in the transition band at
|
| 460 |
+
which the gain first drops below -`rp`.
|
| 461 |
+
|
| 462 |
+
For digital filters, `Wn` are in the same units as `fs`. By default,
|
| 463 |
+
`fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
|
| 464 |
+
where 1 is the Nyquist frequency. (`Wn` is thus in
|
| 465 |
+
half-cycles / sample.)
|
| 466 |
+
|
| 467 |
+
For analog filters, `Wn` is an angular frequency (e.g., rad/s).
|
| 468 |
+
btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional
|
| 469 |
+
The type of filter. Default is 'lowpass'.
|
| 470 |
+
analog : bool, optional
|
| 471 |
+
When True, return an analog filter, otherwise a digital filter is
|
| 472 |
+
returned.
|
| 473 |
+
output : {'ba', 'zpk', 'sos'}, optional
|
| 474 |
+
Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or
|
| 475 |
+
second-order sections ('sos'). Default is 'ba' for backwards
|
| 476 |
+
compatibility, but 'sos' should be used for general-purpose filtering.
|
| 477 |
+
fs : float, optional
|
| 478 |
+
The sampling frequency of the digital system.
|
| 479 |
+
|
| 480 |
+
Returns
|
| 481 |
+
-------
|
| 482 |
+
b, a : ndarray, ndarray
|
| 483 |
+
Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
|
| 484 |
+
Only returned if ``output='ba'``.
|
| 485 |
+
z, p, k : ndarray, ndarray, float
|
| 486 |
+
Zeros, poles, and system gain of the IIR filter transfer
|
| 487 |
+
function. Only returned if ``output='zpk'``.
|
| 488 |
+
sos : ndarray
|
| 489 |
+
Second-order sections representation of the IIR filter.
|
| 490 |
+
Only returned if ``output='sos'``.
|
| 491 |
+
|
| 492 |
+
See Also
|
| 493 |
+
--------
|
| 494 |
+
ellipord, ellipap
|
| 495 |
+
iirfilter
|
| 496 |
+
scipy.signal.ellip
|
| 497 |
+
|
| 498 |
+
Notes
|
| 499 |
+
-----
|
| 500 |
+
Also known as Cauer or Zolotarev filters, the elliptical filter maximizes
|
| 501 |
+
the rate of transition between the frequency response's passband and
|
| 502 |
+
stopband, at the expense of ripple in both, and increased ringing in the
|
| 503 |
+
step response.
|
| 504 |
+
|
| 505 |
+
As `rp` approaches 0, the elliptical filter becomes a Chebyshev
|
| 506 |
+
type II filter (`cheby2`). As `rs` approaches 0, it becomes a Chebyshev
|
| 507 |
+
type I filter (`cheby1`). As both approach 0, it becomes a Butterworth
|
| 508 |
+
filter (`butter`).
|
| 509 |
+
|
| 510 |
+
The equiripple passband has N maxima or minima (for example, a
|
| 511 |
+
5th-order filter has 3 maxima and 2 minima). Consequently, the DC gain is
|
| 512 |
+
unity for odd-order filters, or -rp dB for even-order filters.
|
| 513 |
+
"""
|
| 514 |
+
return iirfilter(N, Wn, rs=rs, rp=rp, btype=btype, analog=analog,
|
| 515 |
+
output=output, ftype='elliptic', fs=fs)
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def iirdesign(wp, ws, gpass, gstop, analog=False, ftype='ellip', output='ba',
|
| 519 |
+
fs=None):
|
| 520 |
+
"""Complete IIR digital and analog filter design.
|
| 521 |
+
|
| 522 |
+
Given passband and stopband frequencies and gains, construct an analog or
|
| 523 |
+
digital IIR filter of minimum order for a given basic type. Return the
|
| 524 |
+
output in numerator, denominator ('ba'), pole-zero ('zpk') or second order
|
| 525 |
+
sections ('sos') form.
|
| 526 |
+
|
| 527 |
+
Parameters
|
| 528 |
+
----------
|
| 529 |
+
wp, ws : float or array like, shape (2,)
|
| 530 |
+
Passband and stopband edge frequencies. Possible values are scalars
|
| 531 |
+
(for lowpass and highpass filters) or ranges (for bandpass and bandstop
|
| 532 |
+
filters).
|
| 533 |
+
For digital filters, these are in the same units as `fs`. By default,
|
| 534 |
+
`fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
|
| 535 |
+
where 1 is the Nyquist frequency. For example:
|
| 536 |
+
|
| 537 |
+
- Lowpass: wp = 0.2, ws = 0.3
|
| 538 |
+
- Highpass: wp = 0.3, ws = 0.2
|
| 539 |
+
- Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6]
|
| 540 |
+
- Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5]
|
| 541 |
+
|
| 542 |
+
For analog filters, `wp` and `ws` are angular frequencies
|
| 543 |
+
(e.g., rad/s). Note, that for bandpass and bandstop filters passband
|
| 544 |
+
must lie strictly inside stopband or vice versa.
|
| 545 |
+
gpass : float
|
| 546 |
+
The maximum loss in the passband (dB).
|
| 547 |
+
gstop : float
|
| 548 |
+
The minimum attenuation in the stopband (dB).
|
| 549 |
+
analog : bool, optional
|
| 550 |
+
When True, return an analog filter, otherwise a digital filter is
|
| 551 |
+
returned.
|
| 552 |
+
ftype : str, optional
|
| 553 |
+
The type of IIR filter to design:
|
| 554 |
+
|
| 555 |
+
- Butterworth : 'butter'
|
| 556 |
+
- Chebyshev I : 'cheby1'
|
| 557 |
+
- Chebyshev II : 'cheby2'
|
| 558 |
+
- Cauer/elliptic: 'ellip'
|
| 559 |
+
|
| 560 |
+
output : {'ba', 'zpk', 'sos'}, optional
|
| 561 |
+
Filter form of the output:
|
| 562 |
+
|
| 563 |
+
- second-order sections (recommended): 'sos'
|
| 564 |
+
- numerator/denominator (default) : 'ba'
|
| 565 |
+
- pole-zero : 'zpk'
|
| 566 |
+
|
| 567 |
+
In general the second-order sections ('sos') form is
|
| 568 |
+
recommended because inferring the coefficients for the
|
| 569 |
+
numerator/denominator form ('ba') suffers from numerical
|
| 570 |
+
instabilities. For reasons of backward compatibility the default
|
| 571 |
+
form is the numerator/denominator form ('ba'), where the 'b'
|
| 572 |
+
and the 'a' in 'ba' refer to the commonly used names of the
|
| 573 |
+
coefficients used.
|
| 574 |
+
|
| 575 |
+
Note: Using the second-order sections form ('sos') is sometimes
|
| 576 |
+
associated with additional computational costs: for
|
| 577 |
+
data-intense use cases it is therefore recommended to also
|
| 578 |
+
investigate the numerator/denominator form ('ba').
|
| 579 |
+
|
| 580 |
+
fs : float, optional
|
| 581 |
+
The sampling frequency of the digital system.
|
| 582 |
+
|
| 583 |
+
.. versionadded:: 1.2.0
|
| 584 |
+
|
| 585 |
+
Returns
|
| 586 |
+
-------
|
| 587 |
+
b, a : ndarray, ndarray
|
| 588 |
+
Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
|
| 589 |
+
Only returned if ``output='ba'``.
|
| 590 |
+
z, p, k : ndarray, ndarray, float
|
| 591 |
+
Zeros, poles, and system gain of the IIR filter transfer
|
| 592 |
+
function. Only returned if ``output='zpk'``.
|
| 593 |
+
sos : ndarray
|
| 594 |
+
Second-order sections representation of the IIR filter.
|
| 595 |
+
Only returned if ``output='sos'``.
|
| 596 |
+
|
| 597 |
+
See Also
|
| 598 |
+
--------
|
| 599 |
+
scipy.signal.iirdesign
|
| 600 |
+
butter : Filter design using order and critical points
|
| 601 |
+
cheby1, cheby2, ellip, bessel
|
| 602 |
+
buttord : Find order and critical points from passband and stopband spec
|
| 603 |
+
cheb1ord, cheb2ord, ellipord
|
| 604 |
+
iirfilter : General filter design using order and critical frequencies
|
| 605 |
+
"""
|
| 606 |
+
try:
|
| 607 |
+
ordfunc = filter_dict[ftype][1]
|
| 608 |
+
except KeyError as e:
|
| 609 |
+
raise ValueError("Invalid IIR filter type: %s" % ftype) from e
|
| 610 |
+
except IndexError as e:
|
| 611 |
+
raise ValueError(("%s does not have order selection. Use "
|
| 612 |
+
"iirfilter function.") % ftype) from e
|
| 613 |
+
|
| 614 |
+
_validate_gpass_gstop(gpass, gstop)
|
| 615 |
+
|
| 616 |
+
wp = cupy.atleast_1d(wp)
|
| 617 |
+
ws = cupy.atleast_1d(ws)
|
| 618 |
+
|
| 619 |
+
if wp.shape[0] != ws.shape[0] or wp.shape not in [(1,), (2,)]:
|
| 620 |
+
raise ValueError("wp and ws must have one or two elements each, and"
|
| 621 |
+
"the same shape, got %s and %s"
|
| 622 |
+
% (wp.shape, ws.shape))
|
| 623 |
+
|
| 624 |
+
if any(wp <= 0) or any(ws <= 0):
|
| 625 |
+
raise ValueError("Values for wp, ws must be greater than 0")
|
| 626 |
+
|
| 627 |
+
if not analog:
|
| 628 |
+
if fs is None:
|
| 629 |
+
if any(wp >= 1) or any(ws >= 1):
|
| 630 |
+
raise ValueError("Values for wp, ws must be less than 1")
|
| 631 |
+
elif any(wp >= fs/2) or any(ws >= fs/2):
|
| 632 |
+
raise ValueError("Values for wp, ws must be less than fs/2"
|
| 633 |
+
" (fs={} -> fs/2={})".format(fs, fs/2))
|
| 634 |
+
|
| 635 |
+
if wp.shape[0] == 2:
|
| 636 |
+
if not ((ws[0] < wp[0] and wp[1] < ws[1]) or
|
| 637 |
+
(wp[0] < ws[0] and ws[1] < wp[1])):
|
| 638 |
+
raise ValueError("Passband must lie strictly inside stopband"
|
| 639 |
+
" or vice versa")
|
| 640 |
+
|
| 641 |
+
band_type = 2 * (len(wp) - 1)
|
| 642 |
+
band_type += 1
|
| 643 |
+
if wp[0] >= ws[0]:
|
| 644 |
+
band_type += 1
|
| 645 |
+
|
| 646 |
+
btype = {1: 'lowpass', 2: 'highpass',
|
| 647 |
+
3: 'bandstop', 4: 'bandpass'}[band_type]
|
| 648 |
+
|
| 649 |
+
N, Wn = ordfunc(wp, ws, gpass, gstop, analog=analog, fs=fs)
|
| 650 |
+
return iirfilter(N, Wn, rp=gpass, rs=gstop, analog=analog, btype=btype,
|
| 651 |
+
ftype=ftype, output=output, fs=fs)
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
def iircomb(w0, Q, ftype='notch', fs=2.0, *, pass_zero=False):
|
| 655 |
+
"""
|
| 656 |
+
Design IIR notching or peaking digital comb filter.
|
| 657 |
+
|
| 658 |
+
A notching comb filter consists of regularly-spaced band-stop filters with
|
| 659 |
+
a narrow bandwidth (high quality factor). Each rejects a narrow frequency
|
| 660 |
+
band and leaves the rest of the spectrum little changed.
|
| 661 |
+
|
| 662 |
+
A peaking comb filter consists of regularly-spaced band-pass filters with
|
| 663 |
+
a narrow bandwidth (high quality factor). Each rejects components outside
|
| 664 |
+
a narrow frequency band.
|
| 665 |
+
|
| 666 |
+
Parameters
|
| 667 |
+
----------
|
| 668 |
+
w0 : float
|
| 669 |
+
The fundamental frequency of the comb filter (the spacing between its
|
| 670 |
+
peaks). This must evenly divide the sampling frequency. If `fs` is
|
| 671 |
+
specified, this is in the same units as `fs`. By default, it is
|
| 672 |
+
a normalized scalar that must satisfy ``0 < w0 < 1``, with
|
| 673 |
+
``w0 = 1`` corresponding to half of the sampling frequency.
|
| 674 |
+
Q : float
|
| 675 |
+
Quality factor. Dimensionless parameter that characterizes
|
| 676 |
+
notch filter -3 dB bandwidth ``bw`` relative to its center
|
| 677 |
+
frequency, ``Q = w0/bw``.
|
| 678 |
+
ftype : {'notch', 'peak'}
|
| 679 |
+
The type of comb filter generated by the function. If 'notch', then
|
| 680 |
+
the Q factor applies to the notches. If 'peak', then the Q factor
|
| 681 |
+
applies to the peaks. Default is 'notch'.
|
| 682 |
+
fs : float, optional
|
| 683 |
+
The sampling frequency of the signal. Default is 2.0.
|
| 684 |
+
pass_zero : bool, optional
|
| 685 |
+
If False (default), the notches (nulls) of the filter are centered on
|
| 686 |
+
frequencies [0, w0, 2*w0, ...], and the peaks are centered on the
|
| 687 |
+
midpoints [w0/2, 3*w0/2, 5*w0/2, ...]. If True, the peaks are centered
|
| 688 |
+
on [0, w0, 2*w0, ...] (passing zero frequency) and vice versa.
|
| 689 |
+
|
| 690 |
+
Returns
|
| 691 |
+
-------
|
| 692 |
+
b, a : ndarray, ndarray
|
| 693 |
+
Numerator (``b``) and denominator (``a``) polynomials
|
| 694 |
+
of the IIR filter.
|
| 695 |
+
|
| 696 |
+
Raises
|
| 697 |
+
------
|
| 698 |
+
ValueError
|
| 699 |
+
If `w0` is less than or equal to 0 or greater than or equal to
|
| 700 |
+
``fs/2``, if `fs` is not divisible by `w0`, if `ftype`
|
| 701 |
+
is not 'notch' or 'peak'
|
| 702 |
+
|
| 703 |
+
See Also
|
| 704 |
+
--------
|
| 705 |
+
scipy.signal.iircomb
|
| 706 |
+
iirnotch
|
| 707 |
+
iirpeak
|
| 708 |
+
|
| 709 |
+
Notes
|
| 710 |
+
-----
|
| 711 |
+
The TF implementation of the
|
| 712 |
+
comb filter is numerically stable even at higher orders due to the
|
| 713 |
+
use of a single repeated pole, which won't suffer from precision loss.
|
| 714 |
+
|
| 715 |
+
References
|
| 716 |
+
----------
|
| 717 |
+
Sophocles J. Orfanidis, "Introduction To Signal Processing",
|
| 718 |
+
Prentice-Hall, 1996, ch. 11, "Digital Filter Design"
|
| 719 |
+
"""
|
| 720 |
+
|
| 721 |
+
# Convert w0, Q, and fs to float
|
| 722 |
+
w0 = float(w0)
|
| 723 |
+
Q = float(Q)
|
| 724 |
+
fs = float(fs)
|
| 725 |
+
|
| 726 |
+
# Check for invalid cutoff frequency or filter type
|
| 727 |
+
ftype = ftype.lower()
|
| 728 |
+
if not 0 < w0 < fs / 2:
|
| 729 |
+
raise ValueError("w0 must be between 0 and {}"
|
| 730 |
+
" (nyquist), but given {}.".format(fs / 2, w0))
|
| 731 |
+
if ftype not in ('notch', 'peak'):
|
| 732 |
+
raise ValueError('ftype must be either notch or peak.')
|
| 733 |
+
|
| 734 |
+
# Compute the order of the filter
|
| 735 |
+
N = round(fs / w0)
|
| 736 |
+
|
| 737 |
+
# Check for cutoff frequency divisibility
|
| 738 |
+
if abs(w0 - fs/N)/fs > 1e-14:
|
| 739 |
+
raise ValueError('fs must be divisible by w0.')
|
| 740 |
+
|
| 741 |
+
# Compute frequency in radians and filter bandwidth
|
| 742 |
+
# Eq. 11.3.1 (p. 574) from reference [1]
|
| 743 |
+
w0 = (2 * pi * w0) / fs
|
| 744 |
+
w_delta = w0 / Q
|
| 745 |
+
|
| 746 |
+
# Define base gain values depending on notch or peak filter
|
| 747 |
+
# Compute -3dB attenuation
|
| 748 |
+
# Eqs. 11.4.1 and 11.4.2 (p. 582) from reference [1]
|
| 749 |
+
if ftype == 'notch':
|
| 750 |
+
G0, G = 1, 0
|
| 751 |
+
elif ftype == 'peak':
|
| 752 |
+
G0, G = 0, 1
|
| 753 |
+
GB = 1 / math.sqrt(2)
|
| 754 |
+
|
| 755 |
+
# Compute beta
|
| 756 |
+
# Eq. 11.5.3 (p. 591) from reference [1]
|
| 757 |
+
beta = math.sqrt((GB**2 - G0**2) / (G**2 - GB**2)) * \
|
| 758 |
+
math.tan(N * w_delta / 4)
|
| 759 |
+
|
| 760 |
+
# Compute filter coefficients
|
| 761 |
+
# Eq 11.5.1 (p. 590) variables a, b, c from reference [1]
|
| 762 |
+
ax = (1 - beta) / (1 + beta)
|
| 763 |
+
bx = (G0 + G * beta) / (1 + beta)
|
| 764 |
+
cx = (G0 - G * beta) / (1 + beta)
|
| 765 |
+
|
| 766 |
+
# Last coefficients are negative to get peaking comb that passes zero or
|
| 767 |
+
# notching comb that doesn't.
|
| 768 |
+
negative_coef = ((ftype == 'peak' and pass_zero) or
|
| 769 |
+
(ftype == 'notch' and not pass_zero))
|
| 770 |
+
|
| 771 |
+
# Compute numerator coefficients
|
| 772 |
+
# Eq 11.5.1 (p. 590) or Eq 11.5.4 (p. 591) from reference [1]
|
| 773 |
+
# b - cz^-N or b + cz^-N
|
| 774 |
+
b = cupy.zeros(N + 1)
|
| 775 |
+
b[0] = bx
|
| 776 |
+
if negative_coef:
|
| 777 |
+
b[-1] = -cx
|
| 778 |
+
else:
|
| 779 |
+
b[-1] = +cx
|
| 780 |
+
|
| 781 |
+
# Compute denominator coefficients
|
| 782 |
+
# Eq 11.5.1 (p. 590) or Eq 11.5.4 (p. 591) from reference [1]
|
| 783 |
+
# 1 - az^-N or 1 + az^-N
|
| 784 |
+
a = cupy.zeros(N + 1)
|
| 785 |
+
a[0] = 1
|
| 786 |
+
if negative_coef:
|
| 787 |
+
a[-1] = -ax
|
| 788 |
+
else:
|
| 789 |
+
a[-1] = +ax
|
| 790 |
+
|
| 791 |
+
return b, a
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
def iirnotch(w0, Q, fs=2.0):
|
| 795 |
+
"""
|
| 796 |
+
Design second-order IIR notch digital filter.
|
| 797 |
+
|
| 798 |
+
A notch filter is a band-stop filter with a narrow bandwidth
|
| 799 |
+
(high quality factor). It rejects a narrow frequency band and
|
| 800 |
+
leaves the rest of the spectrum little changed.
|
| 801 |
+
|
| 802 |
+
Parameters
|
| 803 |
+
----------
|
| 804 |
+
w0 : float
|
| 805 |
+
Frequency to remove from a signal. If `fs` is specified, this is in
|
| 806 |
+
the same units as `fs`. By default, it is a normalized scalar that must
|
| 807 |
+
satisfy ``0 < w0 < 1``, with ``w0 = 1`` corresponding to half of the
|
| 808 |
+
sampling frequency.
|
| 809 |
+
Q : float
|
| 810 |
+
Quality factor. Dimensionless parameter that characterizes
|
| 811 |
+
notch filter -3 dB bandwidth ``bw`` relative to its center
|
| 812 |
+
frequency, ``Q = w0/bw``.
|
| 813 |
+
fs : float, optional
|
| 814 |
+
The sampling frequency of the digital system.
|
| 815 |
+
|
| 816 |
+
Returns
|
| 817 |
+
-------
|
| 818 |
+
b, a : ndarray, ndarray
|
| 819 |
+
Numerator (``b``) and denominator (``a``) polynomials
|
| 820 |
+
of the IIR filter.
|
| 821 |
+
|
| 822 |
+
See Also
|
| 823 |
+
--------
|
| 824 |
+
scipy.signal.iirnotch
|
| 825 |
+
|
| 826 |
+
References
|
| 827 |
+
----------
|
| 828 |
+
Sophocles J. Orfanidis, "Introduction To Signal Processing",
|
| 829 |
+
Prentice-Hall, 1996
|
| 830 |
+
"""
|
| 831 |
+
|
| 832 |
+
return _design_notch_peak_filter(w0, Q, "notch", fs)
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
def iirpeak(w0, Q, fs=2.0):
|
| 836 |
+
"""
|
| 837 |
+
Design second-order IIR peak (resonant) digital filter.
|
| 838 |
+
|
| 839 |
+
A peak filter is a band-pass filter with a narrow bandwidth
|
| 840 |
+
(high quality factor). It rejects components outside a narrow
|
| 841 |
+
frequency band.
|
| 842 |
+
|
| 843 |
+
Parameters
|
| 844 |
+
----------
|
| 845 |
+
w0 : float
|
| 846 |
+
Frequency to be retained in a signal. If `fs` is specified, this is in
|
| 847 |
+
the same units as `fs`. By default, it is a normalized scalar that must
|
| 848 |
+
satisfy ``0 < w0 < 1``, with ``w0 = 1`` corresponding to half of the
|
| 849 |
+
sampling frequency.
|
| 850 |
+
Q : float
|
| 851 |
+
Quality factor. Dimensionless parameter that characterizes
|
| 852 |
+
peak filter -3 dB bandwidth ``bw`` relative to its center
|
| 853 |
+
frequency, ``Q = w0/bw``.
|
| 854 |
+
fs : float, optional
|
| 855 |
+
The sampling frequency of the digital system.
|
| 856 |
+
|
| 857 |
+
|
| 858 |
+
Returns
|
| 859 |
+
-------
|
| 860 |
+
b, a : ndarray, ndarray
|
| 861 |
+
Numerator (``b``) and denominator (``a``) polynomials
|
| 862 |
+
of the IIR filter.
|
| 863 |
+
|
| 864 |
+
See Also
|
| 865 |
+
--------
|
| 866 |
+
scpy.signal.iirpeak
|
| 867 |
+
|
| 868 |
+
References
|
| 869 |
+
----------
|
| 870 |
+
Sophocles J. Orfanidis, "Introduction To Signal Processing",
|
| 871 |
+
Prentice-Hall, 1996
|
| 872 |
+
"""
|
| 873 |
+
|
| 874 |
+
return _design_notch_peak_filter(w0, Q, "peak", fs)
|
| 875 |
+
|
| 876 |
+
|
| 877 |
+
def _design_notch_peak_filter(w0, Q, ftype, fs=2.0):
|
| 878 |
+
"""
|
| 879 |
+
Design notch or peak digital filter.
|
| 880 |
+
|
| 881 |
+
Parameters
|
| 882 |
+
----------
|
| 883 |
+
w0 : float
|
| 884 |
+
Normalized frequency to remove from a signal. If `fs` is specified,
|
| 885 |
+
this is in the same units as `fs`. By default, it is a normalized
|
| 886 |
+
scalar that must satisfy ``0 < w0 < 1``, with ``w0 = 1``
|
| 887 |
+
corresponding to half of the sampling frequency.
|
| 888 |
+
Q : float
|
| 889 |
+
Quality factor. Dimensionless parameter that characterizes
|
| 890 |
+
notch filter -3 dB bandwidth ``bw`` relative to its center
|
| 891 |
+
frequency, ``Q = w0/bw``.
|
| 892 |
+
ftype : str
|
| 893 |
+
The type of IIR filter to design:
|
| 894 |
+
|
| 895 |
+
- notch filter : ``notch``
|
| 896 |
+
- peak filter : ``peak``
|
| 897 |
+
fs : float, optional
|
| 898 |
+
The sampling frequency of the digital system.
|
| 899 |
+
|
| 900 |
+
Returns
|
| 901 |
+
-------
|
| 902 |
+
b, a : ndarray, ndarray
|
| 903 |
+
Numerator (``b``) and denominator (``a``) polynomials
|
| 904 |
+
of the IIR filter.
|
| 905 |
+
"""
|
| 906 |
+
|
| 907 |
+
# Guarantee that the inputs are floats
|
| 908 |
+
w0 = float(w0)
|
| 909 |
+
Q = float(Q)
|
| 910 |
+
w0 = 2 * w0 / fs
|
| 911 |
+
|
| 912 |
+
# Checks if w0 is within the range
|
| 913 |
+
if w0 > 1.0 or w0 < 0.0:
|
| 914 |
+
raise ValueError("w0 should be such that 0 < w0 < 1")
|
| 915 |
+
|
| 916 |
+
# Get bandwidth
|
| 917 |
+
bw = w0 / Q
|
| 918 |
+
|
| 919 |
+
# Normalize inputs
|
| 920 |
+
bw = bw * pi
|
| 921 |
+
w0 = w0 * pi
|
| 922 |
+
|
| 923 |
+
# Compute -3dB attenuation
|
| 924 |
+
gb = 1 / math.sqrt(2)
|
| 925 |
+
|
| 926 |
+
if ftype == "notch":
|
| 927 |
+
# Compute beta: formula 11.3.4 (p.575) from reference [1]
|
| 928 |
+
beta = (math.sqrt(1.0 - gb**2.0) / gb) * math.tan(bw / 2.0)
|
| 929 |
+
elif ftype == "peak":
|
| 930 |
+
# Compute beta: formula 11.3.19 (p.579) from reference [1]
|
| 931 |
+
beta = (gb / math.sqrt(1.0 - gb**2.0)) * math.tan(bw / 2.0)
|
| 932 |
+
else:
|
| 933 |
+
raise ValueError("Unknown ftype.")
|
| 934 |
+
|
| 935 |
+
# Compute gain: formula 11.3.6 (p.575) from reference [1]
|
| 936 |
+
gain = 1.0 / (1.0 + beta)
|
| 937 |
+
|
| 938 |
+
# Compute numerator b and denominator a
|
| 939 |
+
# formulas 11.3.7 (p.575) and 11.3.21 (p.579)
|
| 940 |
+
# from reference [1]
|
| 941 |
+
if ftype == "notch":
|
| 942 |
+
b = [gain * x for x in (1.0, -2.0 * math.cos(w0), 1.0)]
|
| 943 |
+
else:
|
| 944 |
+
b = [(1.0 - gain) * x for x in (1.0, 0.0, -1.0)]
|
| 945 |
+
|
| 946 |
+
a = [1.0, -2.0 * gain * math.cos(w0), 2.0 * gain - 1.0]
|
| 947 |
+
|
| 948 |
+
a = cupy.asarray(a)
|
| 949 |
+
b = cupy.asarray(b)
|
| 950 |
+
|
| 951 |
+
return b, a
|
| 952 |
+
|
| 953 |
+
|
| 954 |
+
filter_dict = {'butter': [buttap, buttord],
|
| 955 |
+
'butterworth': [buttap, buttord],
|
| 956 |
+
|
| 957 |
+
'cauer': [ellipap, ellipord],
|
| 958 |
+
'elliptic': [ellipap, ellipord],
|
| 959 |
+
'ellip': [ellipap, ellipord],
|
| 960 |
+
|
| 961 |
+
'bessel': [besselap],
|
| 962 |
+
'bessel_phase': [besselap],
|
| 963 |
+
'bessel_delay': [besselap],
|
| 964 |
+
'bessel_mag': [besselap],
|
| 965 |
+
|
| 966 |
+
'cheby1': [cheb1ap, cheb1ord],
|
| 967 |
+
'chebyshev1': [cheb1ap, cheb1ord],
|
| 968 |
+
'chebyshevi': [cheb1ap, cheb1ord],
|
| 969 |
+
|
| 970 |
+
'cheby2': [cheb2ap, cheb2ord],
|
| 971 |
+
'chebyshev2': [cheb2ap, cheb2ord],
|
| 972 |
+
'chebyshevii': [cheb2ap, cheb2ord],
|
| 973 |
+
}
|
| 974 |
+
|
| 975 |
+
band_dict = {'band': 'bandpass',
|
| 976 |
+
'bandpass': 'bandpass',
|
| 977 |
+
'pass': 'bandpass',
|
| 978 |
+
'bp': 'bandpass',
|
| 979 |
+
|
| 980 |
+
'bs': 'bandstop',
|
| 981 |
+
'bandstop': 'bandstop',
|
| 982 |
+
'bands': 'bandstop',
|
| 983 |
+
'stop': 'bandstop',
|
| 984 |
+
|
| 985 |
+
'l': 'lowpass',
|
| 986 |
+
'low': 'lowpass',
|
| 987 |
+
'lowpass': 'lowpass',
|
| 988 |
+
'lp': 'lowpass',
|
| 989 |
+
|
| 990 |
+
'high': 'highpass',
|
| 991 |
+
'highpass': 'highpass',
|
| 992 |
+
'h': 'highpass',
|
| 993 |
+
'hp': 'highpass',
|
| 994 |
+
}
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_iir_utils.py
ADDED
|
@@ -0,0 +1,737 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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6 |
+
from cupy._core._scalar import get_typename
|
| 7 |
+
from cupy_backends.cuda.api import runtime
|
| 8 |
+
from cupyx.scipy.signal._arraytools import axis_slice
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _get_typename(dtype):
|
| 12 |
+
typename = get_typename(dtype)
|
| 13 |
+
if cupy.dtype(dtype).kind == 'c':
|
| 14 |
+
typename = 'thrust::' + typename
|
| 15 |
+
elif typename == 'float16':
|
| 16 |
+
if runtime.is_hip:
|
| 17 |
+
# 'half' in name_expressions weirdly raises
|
| 18 |
+
# HIPRTC_ERROR_NAME_EXPRESSION_NOT_VALID in getLoweredName() on
|
| 19 |
+
# ROCm
|
| 20 |
+
typename = '__half'
|
| 21 |
+
else:
|
| 22 |
+
typename = 'half'
|
| 23 |
+
return typename
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
FLOAT_TYPES = [cupy.float16, cupy.float32, cupy.float64]
|
| 27 |
+
INT_TYPES = [cupy.int8, cupy.int16, cupy.int32, cupy.int64]
|
| 28 |
+
COMPLEX_TYPES = [cupy.complex64, cupy.complex128]
|
| 29 |
+
UNSIGNED_TYPES = [cupy.uint8, cupy.uint16, cupy.uint32, cupy.uint64]
|
| 30 |
+
TYPES = FLOAT_TYPES + INT_TYPES + UNSIGNED_TYPES + COMPLEX_TYPES # type: ignore # NOQA
|
| 31 |
+
TYPE_PAIRS = [(x, y) for x, y in product(TYPES, TYPES)
|
| 32 |
+
if cupy.promote_types(x, y) is cupy.dtype(x)]
|
| 33 |
+
|
| 34 |
+
TYPE_NAMES = [_get_typename(t) for t in TYPES]
|
| 35 |
+
TYPE_PAIR_NAMES = [(_get_typename(x), _get_typename(y)) for x, y in TYPE_PAIRS]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
IIR_KERNEL = r"""
|
| 39 |
+
#include <cupy/math_constants.h>
|
| 40 |
+
#include <cupy/carray.cuh>
|
| 41 |
+
#include <cupy/complex.cuh>
|
| 42 |
+
|
| 43 |
+
template<typename U, typename T>
|
| 44 |
+
__global__ void compute_correction_factors(
|
| 45 |
+
const int m, const int k, const T* b, U* out) {
|
| 46 |
+
int idx = blockDim.x * blockIdx.x + threadIdx.x;
|
| 47 |
+
if(idx >= k) {
|
| 48 |
+
return;
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
U* out_start = out + idx * (k + m);
|
| 52 |
+
U* out_off = out_start + k;
|
| 53 |
+
|
| 54 |
+
for(int i = 0; i < m; i++) {
|
| 55 |
+
U acc = 0.0;
|
| 56 |
+
for(int j = 0; j < k; j++) {
|
| 57 |
+
acc += ((U) b[j]) * out_off[i - j - 1];
|
| 58 |
+
|
| 59 |
+
}
|
| 60 |
+
out_off[i] = acc;
|
| 61 |
+
}
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
template<typename T>
|
| 65 |
+
__global__ void first_pass_iir(
|
| 66 |
+
const int m, const int k, const int n, const int n_blocks,
|
| 67 |
+
const int carries_stride, const T* factors, T* out,
|
| 68 |
+
T* carries) {
|
| 69 |
+
int orig_idx = blockDim.x * (blockIdx.x % n_blocks) + threadIdx.x;
|
| 70 |
+
|
| 71 |
+
int num_row = blockIdx.x / n_blocks;
|
| 72 |
+
int idx = 2 * orig_idx + 1;
|
| 73 |
+
|
| 74 |
+
if(idx >= n) {
|
| 75 |
+
return;
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
int group_num = idx / m;
|
| 79 |
+
int group_pos = idx % m;
|
| 80 |
+
|
| 81 |
+
T* out_off = out + num_row * n;
|
| 82 |
+
T* carries_off = carries + num_row * carries_stride;
|
| 83 |
+
|
| 84 |
+
T* group_start = out_off + m * group_num;
|
| 85 |
+
T* group_carries = carries_off + k * group_num;
|
| 86 |
+
|
| 87 |
+
int pos = group_pos;
|
| 88 |
+
int up_bound = pos;
|
| 89 |
+
int low_bound = pos;
|
| 90 |
+
int rel_pos;
|
| 91 |
+
|
| 92 |
+
for(int level = 1, iter = 1; level < m; level *=2, iter++) {
|
| 93 |
+
int sz = min(pow(2.0f, ((float) iter)), ((float) m));
|
| 94 |
+
|
| 95 |
+
if(level > 1) {
|
| 96 |
+
int factor = ceil(pos / ((float) sz));
|
| 97 |
+
up_bound = sz * factor - 1;
|
| 98 |
+
low_bound = up_bound - level + 1;
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
if(level == 1) {
|
| 102 |
+
pos = low_bound;
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
if(pos < low_bound) {
|
| 106 |
+
pos += level / 2;
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
if(pos + m * group_num >= n) {
|
| 110 |
+
break;
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
rel_pos = pos % level;
|
| 114 |
+
T carry = 0.0;
|
| 115 |
+
for(int i = 1; i <= min(k, level); i++) {
|
| 116 |
+
T k_value = group_start[low_bound - i];
|
| 117 |
+
const T* k_factors = factors + (m + k) * (i - 1) + k;
|
| 118 |
+
T factor = k_factors[rel_pos];
|
| 119 |
+
carry += k_value * factor;
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
group_start[pos] += carry;
|
| 123 |
+
__syncthreads();
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
if(pos >= m - k) {
|
| 127 |
+
if(carries != NULL) {
|
| 128 |
+
group_carries[pos - (m - k)] = group_start[pos];
|
| 129 |
+
}
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
template<typename T>
|
| 135 |
+
__global__ void correct_carries(
|
| 136 |
+
const int m, const int k, const int n_blocks, const int carries_stride,
|
| 137 |
+
const int offset, const T* factors, T* carries) {
|
| 138 |
+
|
| 139 |
+
int idx = threadIdx.x;
|
| 140 |
+
int pos = idx + (m - k);
|
| 141 |
+
T* row_carries = carries + carries_stride * blockIdx.x;
|
| 142 |
+
|
| 143 |
+
for(int i = offset; i < n_blocks; i++) {
|
| 144 |
+
T* this_carries = row_carries + k * (i + (1 - offset));
|
| 145 |
+
T* prev_carries = row_carries + k * (i - offset);
|
| 146 |
+
|
| 147 |
+
T carry = 0.0;
|
| 148 |
+
for(int j = 1; j <= k; j++) {
|
| 149 |
+
const T* k_factors = factors + (m + k) * (j - 1) + k;
|
| 150 |
+
T factor = k_factors[pos];
|
| 151 |
+
T k_value = prev_carries[k - j];
|
| 152 |
+
carry += factor * k_value;
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
this_carries[idx] += carry;
|
| 156 |
+
__syncthreads();
|
| 157 |
+
}
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
template<typename T>
|
| 161 |
+
__global__ void second_pass_iir(
|
| 162 |
+
const int m, const int k, const int n, const int carries_stride,
|
| 163 |
+
const int n_blocks, const int offset, const T* factors,
|
| 164 |
+
T* carries, T* out) {
|
| 165 |
+
|
| 166 |
+
int idx = blockDim.x * (blockIdx.x % n_blocks) + threadIdx.x;
|
| 167 |
+
idx += offset * m;
|
| 168 |
+
|
| 169 |
+
int row_num = blockIdx.x / n_blocks;
|
| 170 |
+
int n_group = idx / m;
|
| 171 |
+
int pos = idx % m;
|
| 172 |
+
|
| 173 |
+
if(idx >= n) {
|
| 174 |
+
return;
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
T* out_off = out + row_num * n;
|
| 178 |
+
T* carries_off = carries + row_num * carries_stride;
|
| 179 |
+
const T* prev_carries = carries_off + (n_group - offset) * k;
|
| 180 |
+
|
| 181 |
+
T carry = 0.0;
|
| 182 |
+
for(int i = 1; i <= k; i++) {
|
| 183 |
+
const T* k_factors = factors + (m + k) * (i - 1) + k;
|
| 184 |
+
T factor = k_factors[pos];
|
| 185 |
+
T k_value = prev_carries[k - i];
|
| 186 |
+
carry += factor * k_value;
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
out_off[idx] += carry;
|
| 190 |
+
}
|
| 191 |
+
"""
|
| 192 |
+
|
| 193 |
+
IIR_SOS_KERNEL = r"""
|
| 194 |
+
#include <cupy/math_constants.h>
|
| 195 |
+
#include <cupy/carray.cuh>
|
| 196 |
+
#include <cupy/complex.cuh>
|
| 197 |
+
|
| 198 |
+
template<typename T>
|
| 199 |
+
__global__ void pick_carries(
|
| 200 |
+
const int m, const int n, const int carries_stride, const int n_blocks,
|
| 201 |
+
const int offset, T* x, T* carries) {
|
| 202 |
+
|
| 203 |
+
int idx = m * (blockIdx.x % n_blocks) + threadIdx.x + m - 2;
|
| 204 |
+
int pos = threadIdx.x;
|
| 205 |
+
int row_num = blockIdx.x / n_blocks;
|
| 206 |
+
int n_group = idx / m;
|
| 207 |
+
|
| 208 |
+
T* x_off = x + row_num * n;
|
| 209 |
+
T* carries_off = carries + row_num * carries_stride;
|
| 210 |
+
T* group_carries = carries_off + (n_group + (1 - offset)) * 2;
|
| 211 |
+
|
| 212 |
+
if(idx >= n) {
|
| 213 |
+
return;
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
group_carries[pos] = x_off[idx];
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
template<typename U, typename T>
|
| 220 |
+
__global__ void compute_correction_factors_sos(
|
| 221 |
+
const int m, const T* f_const, U* all_out) {
|
| 222 |
+
|
| 223 |
+
extern __shared__ __align__(sizeof(T)) thrust::complex<double> bc_d[2];
|
| 224 |
+
T* b_c = reinterpret_cast<T*>(bc_d);
|
| 225 |
+
|
| 226 |
+
extern __shared__ __align__(sizeof(T)) thrust::complex<double> off_d[4];
|
| 227 |
+
U* off_cache = reinterpret_cast<U*>(off_d);
|
| 228 |
+
|
| 229 |
+
int idx = threadIdx.x;
|
| 230 |
+
int num_section = blockIdx.x;
|
| 231 |
+
|
| 232 |
+
const int n_const = 6;
|
| 233 |
+
const int a_off = 3;
|
| 234 |
+
const int k = 2;
|
| 235 |
+
const int off_idx = 1;
|
| 236 |
+
|
| 237 |
+
U* out = all_out + num_section * k * m;
|
| 238 |
+
U* out_start = out + idx * m;
|
| 239 |
+
const T* b = f_const + num_section * n_const + a_off + 1;
|
| 240 |
+
|
| 241 |
+
b_c[idx] = b[idx];
|
| 242 |
+
__syncthreads();
|
| 243 |
+
|
| 244 |
+
U* this_cache = off_cache + k * idx;
|
| 245 |
+
this_cache[off_idx - idx] = 1;
|
| 246 |
+
this_cache[idx] = 0;
|
| 247 |
+
|
| 248 |
+
for(int i = 0; i < m; i++) {
|
| 249 |
+
U acc = 0.0;
|
| 250 |
+
for(int j = 0; j < k; j++) {
|
| 251 |
+
acc += -((U) b_c[j]) * this_cache[off_idx - j];
|
| 252 |
+
|
| 253 |
+
}
|
| 254 |
+
this_cache[0] = this_cache[1];
|
| 255 |
+
this_cache[1] = acc;
|
| 256 |
+
out_start[i] = acc;
|
| 257 |
+
}
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
template<typename T>
|
| 262 |
+
__global__ void first_pass_iir_sos(
|
| 263 |
+
const int m, const int n, const int n_blocks,
|
| 264 |
+
const T* factors, T* out, T* carries) {
|
| 265 |
+
|
| 266 |
+
extern __shared__ unsigned int thread_status[2];
|
| 267 |
+
extern __shared__ __align__(sizeof(T)) thrust::complex<double> fc_d[2 * 1024];
|
| 268 |
+
T* factor_cache = reinterpret_cast<T*>(fc_d);
|
| 269 |
+
|
| 270 |
+
int orig_idx = blockDim.x * (blockIdx.x % n_blocks) + threadIdx.x;
|
| 271 |
+
|
| 272 |
+
int num_row = blockIdx.x / n_blocks;
|
| 273 |
+
int idx = 2 * orig_idx + 1;
|
| 274 |
+
const int k = 2;
|
| 275 |
+
|
| 276 |
+
if(idx >= n) {
|
| 277 |
+
return;
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
int group_num = idx / m;
|
| 281 |
+
int group_pos = idx % m;
|
| 282 |
+
T* out_off = out + num_row * n;
|
| 283 |
+
T* carries_off = carries + num_row * n_blocks * k;
|
| 284 |
+
|
| 285 |
+
T* group_start = out_off + m * group_num;
|
| 286 |
+
T* group_carries = carries_off + group_num * k;
|
| 287 |
+
|
| 288 |
+
const T* section_factors = factors;
|
| 289 |
+
T* section_carries = group_carries;
|
| 290 |
+
|
| 291 |
+
factor_cache[group_pos] = section_factors[group_pos];
|
| 292 |
+
factor_cache[group_pos - 1] = section_factors[group_pos - 1];
|
| 293 |
+
factor_cache[m + group_pos] = section_factors[m + group_pos];
|
| 294 |
+
factor_cache[m + group_pos - 1] = section_factors[m + group_pos - 1];
|
| 295 |
+
__syncthreads();
|
| 296 |
+
|
| 297 |
+
int pos = group_pos;
|
| 298 |
+
int up_bound = pos;
|
| 299 |
+
int low_bound = pos;
|
| 300 |
+
int rel_pos;
|
| 301 |
+
|
| 302 |
+
for(int level = 1, iter = 1; level < m; level *= 2, iter++) {
|
| 303 |
+
int sz = min(pow(2.0f, ((float) iter)), ((float) m));
|
| 304 |
+
|
| 305 |
+
if(level > 1) {
|
| 306 |
+
int factor = ceil(pos / ((float) sz));
|
| 307 |
+
up_bound = sz * factor - 1;
|
| 308 |
+
low_bound = up_bound - level + 1;
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
if(level == 1) {
|
| 312 |
+
pos = low_bound;
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
if(pos < low_bound) {
|
| 316 |
+
pos += level / 2;
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
if(pos + m * group_num >= n) {
|
| 320 |
+
break;
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
rel_pos = pos % level;
|
| 324 |
+
T carry = 0.0;
|
| 325 |
+
for(int i = 1; i <= min(k, level); i++) {
|
| 326 |
+
T k_value = group_start[low_bound - i];
|
| 327 |
+
const T* k_factors = factor_cache + m * (i - 1);
|
| 328 |
+
T factor = k_factors[rel_pos];
|
| 329 |
+
carry += k_value * factor;
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
group_start[pos] += carry;
|
| 333 |
+
__syncthreads();
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
if(pos >= m - k) {
|
| 337 |
+
if(carries != NULL) {
|
| 338 |
+
section_carries[pos - (m - k)] = group_start[pos];
|
| 339 |
+
}
|
| 340 |
+
}
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
template<typename T>
|
| 344 |
+
__global__ void correct_carries_sos(
|
| 345 |
+
const int m, const int n_blocks, const int carries_stride,
|
| 346 |
+
const int offset, const T* factors, T* carries) {
|
| 347 |
+
|
| 348 |
+
extern __shared__ __align__(sizeof(T)) thrust::complex<double> fcd3[4];
|
| 349 |
+
T* factor_cache = reinterpret_cast<T*>(fcd3);
|
| 350 |
+
|
| 351 |
+
int idx = threadIdx.x;
|
| 352 |
+
const int k = 2;
|
| 353 |
+
int pos = idx + (m - k);
|
| 354 |
+
T* row_carries = carries + carries_stride * blockIdx.x;
|
| 355 |
+
|
| 356 |
+
factor_cache[2 * idx] = factors[pos];
|
| 357 |
+
factor_cache[2 * idx + 1] = factors[m + pos];
|
| 358 |
+
__syncthreads();
|
| 359 |
+
|
| 360 |
+
for(int i = offset; i < n_blocks; i++) {
|
| 361 |
+
T* this_carries = row_carries + k * (i + (1 - offset));
|
| 362 |
+
T* prev_carries = row_carries + k * (i - offset);
|
| 363 |
+
|
| 364 |
+
T carry = 0.0;
|
| 365 |
+
for(int j = 1; j <= k; j++) {
|
| 366 |
+
// const T* k_factors = factors + m * (j - 1);
|
| 367 |
+
// T factor = k_factors[pos];
|
| 368 |
+
T factor = factor_cache[2 * idx + (j - 1)];
|
| 369 |
+
T k_value = prev_carries[k - j];
|
| 370 |
+
carry += factor * k_value;
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
this_carries[idx] += carry;
|
| 374 |
+
__syncthreads();
|
| 375 |
+
}
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
template<typename T>
|
| 379 |
+
__global__ void second_pass_iir_sos(
|
| 380 |
+
const int m, const int n, const int carries_stride,
|
| 381 |
+
const int n_blocks, const int offset, const T* factors,
|
| 382 |
+
T* carries, T* out) {
|
| 383 |
+
|
| 384 |
+
extern __shared__ __align__(sizeof(T)) thrust::complex<double> fcd2[2 * 1024];
|
| 385 |
+
T* factor_cache = reinterpret_cast<T*>(fcd2);
|
| 386 |
+
|
| 387 |
+
extern __shared__ __align__(sizeof(T)) thrust::complex<double> c_d[2];
|
| 388 |
+
T* carries_cache = reinterpret_cast<T*>(c_d);
|
| 389 |
+
|
| 390 |
+
int idx = blockDim.x * (blockIdx.x % n_blocks) + threadIdx.x;
|
| 391 |
+
idx += offset * m;
|
| 392 |
+
|
| 393 |
+
int row_num = blockIdx.x / n_blocks;
|
| 394 |
+
int n_group = idx / m;
|
| 395 |
+
int pos = idx % m;
|
| 396 |
+
const int k = 2;
|
| 397 |
+
|
| 398 |
+
T* out_off = out + row_num * n;
|
| 399 |
+
T* carries_off = carries + row_num * carries_stride;
|
| 400 |
+
const T* prev_carries = carries_off + (n_group - offset) * k;
|
| 401 |
+
|
| 402 |
+
if(pos < k) {
|
| 403 |
+
carries_cache[pos] = prev_carries[pos];
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
if(idx >= n) {
|
| 407 |
+
return;
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
factor_cache[pos] = factors[pos];
|
| 411 |
+
factor_cache[pos + m] = factors[pos + m];
|
| 412 |
+
__syncthreads();
|
| 413 |
+
|
| 414 |
+
T carry = 0.0;
|
| 415 |
+
for(int i = 1; i <= k; i++) {
|
| 416 |
+
const T* k_factors = factor_cache + m * (i - 1);
|
| 417 |
+
T factor = k_factors[pos];
|
| 418 |
+
T k_value = carries_cache[k - i];
|
| 419 |
+
carry += factor * k_value;
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
out_off[idx] += carry;
|
| 423 |
+
}
|
| 424 |
+
|
| 425 |
+
template<typename T>
|
| 426 |
+
__global__ void fir_sos(
|
| 427 |
+
const int m, const int n, const int carries_stride, const int n_blocks,
|
| 428 |
+
const int offset, const T* sos, T* carries, T* out) {
|
| 429 |
+
|
| 430 |
+
extern __shared__ __align__(sizeof(T)) thrust::complex<double> fir_cc[1024 + 2];
|
| 431 |
+
T* fir_cache = reinterpret_cast<T*>(fir_cc);
|
| 432 |
+
|
| 433 |
+
extern __shared__ __align__(sizeof(T)) thrust::complex<double> fir_b[3];
|
| 434 |
+
T* b = reinterpret_cast<T*>(fir_b);
|
| 435 |
+
|
| 436 |
+
int idx = blockDim.x * (blockIdx.x % n_blocks) + threadIdx.x;
|
| 437 |
+
int row_num = blockIdx.x / n_blocks;
|
| 438 |
+
int n_group = idx / m;
|
| 439 |
+
int pos = idx % m;
|
| 440 |
+
const int k = 2;
|
| 441 |
+
|
| 442 |
+
T* out_row = out + row_num * n;
|
| 443 |
+
T* out_off = out_row + n_group * m;
|
| 444 |
+
T* carries_off = carries + row_num * carries_stride;
|
| 445 |
+
T* this_carries = carries_off + k * (n_group + (1 - offset));
|
| 446 |
+
T* group_carries = carries_off + (n_group - offset) * k;
|
| 447 |
+
|
| 448 |
+
if(pos <= k) {
|
| 449 |
+
b[pos] = sos[pos];
|
| 450 |
+
}
|
| 451 |
+
|
| 452 |
+
if(pos < k) {
|
| 453 |
+
if(offset && n_group == 0) {
|
| 454 |
+
fir_cache[pos] = 0;
|
| 455 |
+
} else {
|
| 456 |
+
fir_cache[pos] = group_carries[pos];
|
| 457 |
+
}
|
| 458 |
+
}
|
| 459 |
+
|
| 460 |
+
if(idx >= n) {
|
| 461 |
+
return;
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
fir_cache[pos + k] = out_off[pos];
|
| 465 |
+
__syncthreads();
|
| 466 |
+
|
| 467 |
+
T acc = 0.0;
|
| 468 |
+
for(int i = k; i >= 0; i--) {
|
| 469 |
+
acc += fir_cache[pos + i] * b[k - i];
|
| 470 |
+
}
|
| 471 |
+
|
| 472 |
+
out_off[pos] = acc;
|
| 473 |
+
}
|
| 474 |
+
""" # NOQA
|
| 475 |
+
|
| 476 |
+
IIR_MODULE = cupy.RawModule(
|
| 477 |
+
code=IIR_KERNEL, options=('-std=c++11',),
|
| 478 |
+
name_expressions=[f'compute_correction_factors<{x}, {y}>'
|
| 479 |
+
for x, y in TYPE_PAIR_NAMES] +
|
| 480 |
+
[f'correct_carries<{x}>' for x in TYPE_NAMES] +
|
| 481 |
+
[f'first_pass_iir<{x}>' for x in TYPE_NAMES] +
|
| 482 |
+
[f'second_pass_iir<{x}>' for x in TYPE_NAMES])
|
| 483 |
+
|
| 484 |
+
IIR_SOS_MODULE = cupy.RawModule(
|
| 485 |
+
code=IIR_SOS_KERNEL, options=('-std=c++11',),
|
| 486 |
+
name_expressions=[f'compute_correction_factors_sos<{x}, {y}>'
|
| 487 |
+
for x, y in TYPE_PAIR_NAMES] +
|
| 488 |
+
[f'pick_carries<{x}>' for x in TYPE_NAMES] +
|
| 489 |
+
[f'correct_carries_sos<{x}>' for x in TYPE_NAMES] +
|
| 490 |
+
[f'first_pass_iir_sos<{x}>' for x in TYPE_NAMES] +
|
| 491 |
+
[f'second_pass_iir_sos<{x}>' for x in TYPE_NAMES] +
|
| 492 |
+
[f'fir_sos<{x}>' for x in TYPE_NAMES])
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def _get_module_func(module, func_name, *template_args):
|
| 496 |
+
args_dtypes = [_get_typename(arg.dtype) for arg in template_args]
|
| 497 |
+
template = ', '.join(args_dtypes)
|
| 498 |
+
kernel_name = f'{func_name}<{template}>' if template_args else func_name
|
| 499 |
+
kernel = module.get_function(kernel_name)
|
| 500 |
+
return kernel
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def collapse_2d(x, axis):
|
| 504 |
+
x = cupy.moveaxis(x, axis, -1)
|
| 505 |
+
x_shape = x.shape
|
| 506 |
+
x = x.reshape(-1, x.shape[-1])
|
| 507 |
+
if not x.flags.c_contiguous:
|
| 508 |
+
x = x.copy()
|
| 509 |
+
return x, x_shape
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def collapse_2d_rest(x, axis):
|
| 513 |
+
x = cupy.moveaxis(x, axis + 1, -1)
|
| 514 |
+
x_shape = x.shape
|
| 515 |
+
x = x.reshape(x.shape[0], -1, x.shape[-1])
|
| 516 |
+
if not x.flags.c_contiguous:
|
| 517 |
+
x = x.copy()
|
| 518 |
+
return x, x_shape
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
def compute_correction_factors(a, block_sz, dtype):
|
| 522 |
+
k = a.size
|
| 523 |
+
correction = cupy.eye(k, dtype=dtype)
|
| 524 |
+
correction = cupy.c_[
|
| 525 |
+
correction[::-1], cupy.empty((k, block_sz), dtype=dtype)]
|
| 526 |
+
corr_kernel = _get_module_func(
|
| 527 |
+
IIR_MODULE, 'compute_correction_factors', correction, a)
|
| 528 |
+
corr_kernel((k,), (1,), (block_sz, k, a, correction))
|
| 529 |
+
return correction
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
def apply_iir(x, a, axis=-1, zi=None, dtype=None, block_sz=1024):
|
| 533 |
+
# GPU throughput is faster when using single precision floating point
|
| 534 |
+
# numbers
|
| 535 |
+
# x = x.astype(cupy.float32)
|
| 536 |
+
if dtype is None:
|
| 537 |
+
dtype = cupy.result_type(x.dtype, a.dtype)
|
| 538 |
+
|
| 539 |
+
a = a.astype(dtype)
|
| 540 |
+
|
| 541 |
+
if zi is not None:
|
| 542 |
+
zi = zi.astype(dtype)
|
| 543 |
+
|
| 544 |
+
x_shape = x.shape
|
| 545 |
+
x_ndim = x.ndim
|
| 546 |
+
axis = _normalize_axis_index(axis, x_ndim)
|
| 547 |
+
k = a.size
|
| 548 |
+
n = x_shape[axis]
|
| 549 |
+
|
| 550 |
+
if x_ndim > 1:
|
| 551 |
+
x, x_shape = collapse_2d(x, axis)
|
| 552 |
+
if zi is not None:
|
| 553 |
+
zi, _ = collapse_2d(zi, axis)
|
| 554 |
+
|
| 555 |
+
out = cupy.array(x, dtype=dtype, copy=True)
|
| 556 |
+
|
| 557 |
+
num_rows = 1 if x.ndim == 1 else x.shape[0]
|
| 558 |
+
n_blocks = (n + block_sz - 1) // block_sz
|
| 559 |
+
total_blocks = num_rows * n_blocks
|
| 560 |
+
|
| 561 |
+
correction = cupy.eye(k, dtype=dtype)
|
| 562 |
+
correction = cupy.c_[
|
| 563 |
+
correction[::-1], cupy.empty((k, block_sz), dtype=dtype)]
|
| 564 |
+
carries = cupy.empty(
|
| 565 |
+
(num_rows, n_blocks, k), dtype=dtype)
|
| 566 |
+
|
| 567 |
+
corr_kernel = _get_module_func(
|
| 568 |
+
IIR_MODULE, 'compute_correction_factors', correction, a)
|
| 569 |
+
first_pass_kernel = _get_module_func(IIR_MODULE, 'first_pass_iir', out)
|
| 570 |
+
second_pass_kernel = _get_module_func(IIR_MODULE, 'second_pass_iir', out)
|
| 571 |
+
carry_correction_kernel = _get_module_func(
|
| 572 |
+
IIR_MODULE, 'correct_carries', out)
|
| 573 |
+
|
| 574 |
+
corr_kernel((k,), (1,), (block_sz, k, a, correction))
|
| 575 |
+
first_pass_kernel((total_blocks,), (block_sz // 2,),
|
| 576 |
+
(block_sz, k, n, n_blocks, (n_blocks) * k,
|
| 577 |
+
correction, out, carries))
|
| 578 |
+
|
| 579 |
+
if zi is not None:
|
| 580 |
+
if zi.ndim == 1:
|
| 581 |
+
zi = cupy.broadcast_to(zi, (num_rows, 1, zi.size))
|
| 582 |
+
elif zi.ndim == 2:
|
| 583 |
+
zi = zi.reshape(num_rows, 1, zi.shape[-1])
|
| 584 |
+
|
| 585 |
+
if carries.size == 0:
|
| 586 |
+
carries = zi
|
| 587 |
+
else:
|
| 588 |
+
carries = cupy.concatenate((zi, carries), axis=1)
|
| 589 |
+
|
| 590 |
+
if not carries.flags.c_contiguous:
|
| 591 |
+
carries = carries.copy()
|
| 592 |
+
|
| 593 |
+
if n_blocks > 1 or zi is not None:
|
| 594 |
+
starting_group = int(zi is None)
|
| 595 |
+
blocks_to_merge = n_blocks - starting_group
|
| 596 |
+
carries_stride = (n_blocks + (1 - starting_group)) * k
|
| 597 |
+
carry_correction_kernel(
|
| 598 |
+
(num_rows,), (k,),
|
| 599 |
+
(block_sz, k, n_blocks, carries_stride, starting_group,
|
| 600 |
+
correction, carries))
|
| 601 |
+
second_pass_kernel(
|
| 602 |
+
(num_rows * blocks_to_merge,), (block_sz,),
|
| 603 |
+
(block_sz, k, n, carries_stride, blocks_to_merge,
|
| 604 |
+
starting_group, correction, carries, out))
|
| 605 |
+
|
| 606 |
+
if x_ndim > 1:
|
| 607 |
+
out = out.reshape(x_shape)
|
| 608 |
+
out = cupy.moveaxis(out, -1, axis)
|
| 609 |
+
if not out.flags.c_contiguous:
|
| 610 |
+
out = out.copy()
|
| 611 |
+
|
| 612 |
+
return out
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
def compute_correction_factors_sos(sos, block_sz, dtype):
|
| 616 |
+
n_sections = sos.shape[0]
|
| 617 |
+
correction = cupy.empty((n_sections, 2, block_sz), dtype=dtype)
|
| 618 |
+
corr_kernel = _get_module_func(
|
| 619 |
+
IIR_SOS_MODULE, 'compute_correction_factors_sos', correction, sos)
|
| 620 |
+
corr_kernel((n_sections,), (2,), (block_sz, sos, correction))
|
| 621 |
+
return correction
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
def apply_iir_sos(x, sos, axis=-1, zi=None, dtype=None, block_sz=1024,
|
| 625 |
+
apply_fir=True, out=None):
|
| 626 |
+
if dtype is None:
|
| 627 |
+
dtype = cupy.result_type(x.dtype, sos.dtype)
|
| 628 |
+
|
| 629 |
+
sos = sos.astype(dtype)
|
| 630 |
+
|
| 631 |
+
if zi is not None:
|
| 632 |
+
zi = zi.astype(dtype)
|
| 633 |
+
|
| 634 |
+
x_shape = x.shape
|
| 635 |
+
x_ndim = x.ndim
|
| 636 |
+
n_sections = sos.shape[0]
|
| 637 |
+
axis = _normalize_axis_index(axis, x_ndim)
|
| 638 |
+
k = 2
|
| 639 |
+
n = x_shape[axis]
|
| 640 |
+
zi_shape = None
|
| 641 |
+
|
| 642 |
+
if x_ndim > 1:
|
| 643 |
+
x, x_shape = collapse_2d(x, axis)
|
| 644 |
+
|
| 645 |
+
if zi is not None:
|
| 646 |
+
zi, zi_shape = collapse_2d_rest(zi, axis)
|
| 647 |
+
|
| 648 |
+
if out is None:
|
| 649 |
+
out = cupy.array(x, dtype=dtype, copy=True)
|
| 650 |
+
|
| 651 |
+
num_rows = 1 if x.ndim == 1 else x.shape[0]
|
| 652 |
+
n_blocks = (n + block_sz - 1) // block_sz
|
| 653 |
+
total_blocks = num_rows * n_blocks
|
| 654 |
+
|
| 655 |
+
correction = compute_correction_factors_sos(sos, block_sz, dtype)
|
| 656 |
+
carries = cupy.empty(
|
| 657 |
+
(num_rows, n_blocks, k), dtype=dtype)
|
| 658 |
+
all_carries = carries
|
| 659 |
+
zi_out = None
|
| 660 |
+
if zi is not None:
|
| 661 |
+
zi_out = cupy.empty_like(zi)
|
| 662 |
+
all_carries = cupy.empty(
|
| 663 |
+
(num_rows, n_blocks + 1, k), dtype=dtype)
|
| 664 |
+
|
| 665 |
+
first_pass_kernel = _get_module_func(
|
| 666 |
+
IIR_SOS_MODULE, 'first_pass_iir_sos', out)
|
| 667 |
+
second_pass_kernel = _get_module_func(
|
| 668 |
+
IIR_SOS_MODULE, 'second_pass_iir_sos', out)
|
| 669 |
+
carry_correction_kernel = _get_module_func(
|
| 670 |
+
IIR_SOS_MODULE, 'correct_carries_sos', out)
|
| 671 |
+
fir_kernel = _get_module_func(IIR_SOS_MODULE, 'fir_sos', out)
|
| 672 |
+
carries_kernel = _get_module_func(IIR_SOS_MODULE, 'pick_carries', out)
|
| 673 |
+
|
| 674 |
+
starting_group = int(zi is None)
|
| 675 |
+
blocks_to_merge = n_blocks - starting_group
|
| 676 |
+
carries_stride = (n_blocks + (1 - starting_group)) * k
|
| 677 |
+
|
| 678 |
+
carries_kernel((num_rows * n_blocks,), (k,),
|
| 679 |
+
(block_sz, n, carries_stride, n_blocks, starting_group,
|
| 680 |
+
out, all_carries))
|
| 681 |
+
|
| 682 |
+
for s in range(n_sections):
|
| 683 |
+
b = sos[s]
|
| 684 |
+
if zi is not None:
|
| 685 |
+
section_zi = zi[s, :, :2]
|
| 686 |
+
all_carries[:, 0, :] = section_zi
|
| 687 |
+
zi_out[s, :, :2] = axis_slice(out, n - 2, n)
|
| 688 |
+
|
| 689 |
+
if apply_fir:
|
| 690 |
+
fir_kernel((num_rows * n_blocks,), (block_sz,),
|
| 691 |
+
(block_sz, n, carries_stride, n_blocks, starting_group,
|
| 692 |
+
b, all_carries, out))
|
| 693 |
+
|
| 694 |
+
first_pass_kernel(
|
| 695 |
+
(total_blocks,), (block_sz // 2,),
|
| 696 |
+
(block_sz, n, n_blocks, correction[s], out, carries))
|
| 697 |
+
|
| 698 |
+
if n_blocks > 1 or zi is not None:
|
| 699 |
+
if zi is not None:
|
| 700 |
+
section_zi = zi[s, :, 2:]
|
| 701 |
+
all_carries[:, 0, :] = section_zi
|
| 702 |
+
all_carries[:, 1:, :] = carries
|
| 703 |
+
|
| 704 |
+
carry_correction_kernel(
|
| 705 |
+
(num_rows,), (k,),
|
| 706 |
+
(block_sz, n_blocks, carries_stride, starting_group,
|
| 707 |
+
correction[s], all_carries))
|
| 708 |
+
second_pass_kernel(
|
| 709 |
+
(num_rows * blocks_to_merge,), (block_sz,),
|
| 710 |
+
(block_sz, n, carries_stride, blocks_to_merge,
|
| 711 |
+
starting_group, correction[s], all_carries, out))
|
| 712 |
+
|
| 713 |
+
if apply_fir:
|
| 714 |
+
carries_kernel(
|
| 715 |
+
(num_rows * n_blocks,), (k,),
|
| 716 |
+
(block_sz, n, carries_stride, n_blocks, starting_group,
|
| 717 |
+
out, all_carries))
|
| 718 |
+
|
| 719 |
+
if zi is not None:
|
| 720 |
+
zi_out[s, :, 2:] = axis_slice(out, n - 2, n)
|
| 721 |
+
|
| 722 |
+
if x_ndim > 1:
|
| 723 |
+
out = out.reshape(x_shape)
|
| 724 |
+
out = cupy.moveaxis(out, -1, axis)
|
| 725 |
+
if not out.flags.c_contiguous:
|
| 726 |
+
out = out.copy()
|
| 727 |
+
|
| 728 |
+
if zi is not None:
|
| 729 |
+
zi_out = zi_out.reshape(zi_shape)
|
| 730 |
+
if len(zi_shape) > 2:
|
| 731 |
+
zi_out = cupy.moveaxis(zi_out, -1, axis)
|
| 732 |
+
if not zi_out.flags.c_contiguous:
|
| 733 |
+
zi_out = zi_out.copy()
|
| 734 |
+
|
| 735 |
+
if zi is not None:
|
| 736 |
+
return out, zi_out
|
| 737 |
+
return out
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_lti_conversion.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cupy
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def _none_to_empty_2d(arg):
|
| 5 |
+
if arg is None:
|
| 6 |
+
return cupy.zeros((0, 0))
|
| 7 |
+
else:
|
| 8 |
+
return arg
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _atleast_2d_or_none(arg):
|
| 12 |
+
if arg is not None:
|
| 13 |
+
return cupy.atleast_2d(arg)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _shape_or_none(M):
|
| 17 |
+
if M is not None:
|
| 18 |
+
return M.shape
|
| 19 |
+
else:
|
| 20 |
+
return (None,) * 2
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _choice_not_none(*args):
|
| 24 |
+
for arg in args:
|
| 25 |
+
if arg is not None:
|
| 26 |
+
return arg
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _restore(M, shape):
|
| 30 |
+
if M.shape == (0, 0):
|
| 31 |
+
return cupy.zeros(shape)
|
| 32 |
+
else:
|
| 33 |
+
if M.shape != shape:
|
| 34 |
+
raise ValueError("The input arrays have incompatible shapes.")
|
| 35 |
+
return M
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def abcd_normalize(A=None, B=None, C=None, D=None):
|
| 39 |
+
"""Check state-space matrices and ensure they are 2-D.
|
| 40 |
+
|
| 41 |
+
If enough information on the system is provided, that is, enough
|
| 42 |
+
properly-shaped arrays are passed to the function, the missing ones
|
| 43 |
+
are built from this information, ensuring the correct number of
|
| 44 |
+
rows and columns. Otherwise a ValueError is raised.
|
| 45 |
+
|
| 46 |
+
Parameters
|
| 47 |
+
----------
|
| 48 |
+
A, B, C, D : array_like, optional
|
| 49 |
+
State-space matrices. All of them are None (missing) by default.
|
| 50 |
+
See `ss2tf` for format.
|
| 51 |
+
|
| 52 |
+
Returns
|
| 53 |
+
-------
|
| 54 |
+
A, B, C, D : array
|
| 55 |
+
Properly shaped state-space matrices.
|
| 56 |
+
|
| 57 |
+
Raises
|
| 58 |
+
------
|
| 59 |
+
ValueError
|
| 60 |
+
If not enough information on the system was provided.
|
| 61 |
+
|
| 62 |
+
"""
|
| 63 |
+
A, B, C, D = map(_atleast_2d_or_none, (A, B, C, D))
|
| 64 |
+
|
| 65 |
+
MA, NA = _shape_or_none(A)
|
| 66 |
+
MB, NB = _shape_or_none(B)
|
| 67 |
+
MC, NC = _shape_or_none(C)
|
| 68 |
+
MD, ND = _shape_or_none(D)
|
| 69 |
+
|
| 70 |
+
p = _choice_not_none(MA, MB, NC)
|
| 71 |
+
q = _choice_not_none(NB, ND)
|
| 72 |
+
r = _choice_not_none(MC, MD)
|
| 73 |
+
if p is None or q is None or r is None:
|
| 74 |
+
raise ValueError("Not enough information on the system.")
|
| 75 |
+
|
| 76 |
+
A, B, C, D = map(_none_to_empty_2d, (A, B, C, D))
|
| 77 |
+
A = _restore(A, (p, p))
|
| 78 |
+
B = _restore(B, (p, q))
|
| 79 |
+
C = _restore(C, (r, p))
|
| 80 |
+
D = _restore(D, (r, q))
|
| 81 |
+
|
| 82 |
+
return A, B, C, D
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_ltisys.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
vllm/lib/python3.10/site-packages/cupyx/scipy/signal/_max_len_seq.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cupy
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
_mls_taps = {2: [1], 3: [2], 4: [3], 5: [3], 6: [5], 7: [6], 8: [7, 6, 1],
|
| 5 |
+
9: [5], 10: [7], 11: [9], 12: [11, 10, 4], 13: [12, 11, 8],
|
| 6 |
+
14: [13, 12, 2], 15: [14], 16: [15, 13, 4], 17: [14],
|
| 7 |
+
18: [11], 19: [18, 17, 14], 20: [17], 21: [19], 22: [21],
|
| 8 |
+
23: [18], 24: [23, 22, 17], 25: [22], 26: [25, 24, 20],
|
| 9 |
+
27: [26, 25, 22], 28: [25], 29: [27], 30: [29, 28, 7],
|
| 10 |
+
31: [28], 32: [31, 30, 10]}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
MAX_LEN_SEQ_KERNEL = r"""
|
| 14 |
+
#include <cupy/math_constants.h>
|
| 15 |
+
#include <cupy/carray.cuh>
|
| 16 |
+
#include <cupy/complex.cuh>
|
| 17 |
+
|
| 18 |
+
extern "C" __global__ void max_len_seq(
|
| 19 |
+
long long length, long long n_taps, int n_state, long long* taps,
|
| 20 |
+
signed char* state, signed char* seq) {
|
| 21 |
+
|
| 22 |
+
int idx = blockDim.x * blockIdx.x + threadIdx.x;
|
| 23 |
+
for(long long i = 0; i < length; i++) {
|
| 24 |
+
signed char next_state = state[(idx + 1) % n_state];
|
| 25 |
+
if(idx == n_state - 1) {
|
| 26 |
+
seq[i] = state[0];
|
| 27 |
+
for(int n_tap = 0; n_tap < n_taps; n_tap++) {
|
| 28 |
+
long long tap = taps[n_tap];
|
| 29 |
+
next_state ^= state[tap];
|
| 30 |
+
}
|
| 31 |
+
}
|
| 32 |
+
state[idx] = next_state;
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
_max_len_seq = cupy.RawKernel(MAX_LEN_SEQ_KERNEL, 'max_len_seq')
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def max_len_seq(nbits, state=None, length=None, taps=None):
|
| 41 |
+
"""
|
| 42 |
+
Maximum length sequence (MLS) generator.
|
| 43 |
+
|
| 44 |
+
Parameters
|
| 45 |
+
----------
|
| 46 |
+
nbits : int
|
| 47 |
+
Number of bits to use. Length of the resulting sequence will
|
| 48 |
+
be ``(2**nbits) - 1``. Note that generating long sequences
|
| 49 |
+
(e.g., greater than ``nbits == 16``) can take a long time.
|
| 50 |
+
state : array_like, optional
|
| 51 |
+
If array, must be of length ``nbits``, and will be cast to binary
|
| 52 |
+
(bool) representation. If None, a seed of ones will be used,
|
| 53 |
+
producing a repeatable representation. If ``state`` is all
|
| 54 |
+
zeros, an error is raised as this is invalid. Default: None.
|
| 55 |
+
length : int, optional
|
| 56 |
+
Number of samples to compute. If None, the entire length
|
| 57 |
+
``(2**nbits) - 1`` is computed.
|
| 58 |
+
taps : array_like, optional
|
| 59 |
+
Polynomial taps to use (e.g., ``[7, 6, 1]`` for an 8-bit sequence).
|
| 60 |
+
If None, taps will be automatically selected (for up to
|
| 61 |
+
``nbits == 32``).
|
| 62 |
+
|
| 63 |
+
Returns
|
| 64 |
+
-------
|
| 65 |
+
seq : array
|
| 66 |
+
Resulting MLS sequence of 0's and 1's.
|
| 67 |
+
state : array
|
| 68 |
+
The final state of the shift register.
|
| 69 |
+
|
| 70 |
+
Notes
|
| 71 |
+
-----
|
| 72 |
+
The algorithm for MLS generation is generically described in:
|
| 73 |
+
|
| 74 |
+
https://en.wikipedia.org/wiki/Maximum_length_sequence
|
| 75 |
+
|
| 76 |
+
The default values for taps are specifically taken from the first
|
| 77 |
+
option listed for each value of ``nbits`` in:
|
| 78 |
+
|
| 79 |
+
https://web.archive.org/web/20181001062252/http://www.newwaveinstruments.com/resources/articles/m_sequence_linear_feedback_shift_register_lfsr.htm
|
| 80 |
+
|
| 81 |
+
""" # NOQA
|
| 82 |
+
if taps is None:
|
| 83 |
+
if nbits not in _mls_taps:
|
| 84 |
+
known_taps = cupy.array(list(_mls_taps.keys()))
|
| 85 |
+
raise ValueError('nbits must be between %s and %s if taps is None'
|
| 86 |
+
% (known_taps.min(), known_taps.max()))
|
| 87 |
+
taps = cupy.array(_mls_taps[nbits], cupy.int64)
|
| 88 |
+
else:
|
| 89 |
+
taps = cupy.unique(cupy.array(taps, cupy.int64))[::-1]
|
| 90 |
+
if cupy.any(taps < 0) or cupy.any(taps > nbits) or taps.size < 1:
|
| 91 |
+
raise ValueError('taps must be non-empty with values between '
|
| 92 |
+
'zero and nbits (inclusive)')
|
| 93 |
+
taps = cupy.array(taps) # needed for Cython and Pythran
|
| 94 |
+
|
| 95 |
+
n_max = (2 ** nbits) - 1
|
| 96 |
+
if length is None:
|
| 97 |
+
length = n_max
|
| 98 |
+
else:
|
| 99 |
+
length = int(length)
|
| 100 |
+
if length < 0:
|
| 101 |
+
raise ValueError('length must be greater than or equal to 0')
|
| 102 |
+
|
| 103 |
+
# We use int8 instead of bool here because NumPy arrays of bools
|
| 104 |
+
# don't seem to work nicely with Cython
|
| 105 |
+
if state is None:
|
| 106 |
+
state = cupy.ones(nbits, dtype=cupy.int8, order='c')
|
| 107 |
+
else:
|
| 108 |
+
# makes a copy if need be, ensuring it's 0's and 1's
|
| 109 |
+
state = cupy.array(state, dtype=bool, order='c').astype(cupy.int8)
|
| 110 |
+
if state.ndim != 1 or state.size != nbits:
|
| 111 |
+
raise ValueError('state must be a 1-D array of size nbits')
|
| 112 |
+
if cupy.all(state == 0):
|
| 113 |
+
raise ValueError('state must not be all zeros')
|
| 114 |
+
|
| 115 |
+
seq = cupy.empty(length, dtype=cupy.int8, order='c')
|
| 116 |
+
n_taps = len(taps)
|
| 117 |
+
|
| 118 |
+
_max_len_seq((1,), (nbits,), (length, n_taps, nbits, taps, state, seq))
|
| 119 |
+
return seq, state
|