Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Polysub addition #26656

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions ivy/functional/backends/jax/experimental/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from ivy.functional.backends.jax import JaxArray
import ivy


# Array API Standard #
# ------------------ #

Expand Down Expand Up @@ -163,3 +164,10 @@ def hz_to_mel(f):
upper_slopes = (upper_edge_mel - spec_bin_mels) / (upper_edge_mel - center_mel)
mel_weights = jnp.maximum(zero, jnp.minimum(lower_slopes, upper_slopes))
return jnp.pad(mel_weights, [[1, 0], [0, 0]])


def polysub(
poly1: JaxArray,
poly2: JaxArray,
) -> JaxArray:
return jnp.polysub(poly1, poly2)
21 changes: 21 additions & 0 deletions ivy/functional/backends/mxnet/experimental/creation.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from typing import Union, Optional, Tuple
import mxnet as mx
import numpy as np
from mxnet.ndarray import NDArray

from ivy.utils.exceptions import IvyNotImplementedException

Expand Down Expand Up @@ -62,3 +63,23 @@ def blackman_window(
out: Optional[Union[(None, mx.ndarray.NDArray)]] = None,
) -> Union[(None, mx.ndarray.NDArray)]:
raise IvyNotImplementedException()


def polysub(poly1: NDArray, poly2: NDArray) -> NDArray:
# Pad the coefficients to have the same length (necessary for subtraction)
max_length = max(poly1.shape[0], poly2.shape[0])
poly1 = mx.nd.pad(
poly1,
mode="constant",
pad_width=(0, max_length - poly1.shape[0]),
constant_value=0,
)
poly2 = mx.nd.pad(
poly2,
mode="constant",
pad_width=(0, max_length - poly2.shape[0]),
constant_value=0,
)

# Calculate the difference of the polynomials
return poly1 - poly2
4 changes: 4 additions & 0 deletions ivy/functional/backends/numpy/experimental/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,3 +204,7 @@ def hz_to_mel(f):
upper_slopes = (upper_edge_mel - spec_bin_mels) / (upper_edge_mel - center_mel)
mel_weights = np.maximum(zero, np.minimum(lower_slopes, upper_slopes))
return np.pad(mel_weights, [[1, 0], [0, 0]])


def polysub(poly1: np.ndarray, poly2: np.ndarray) -> np.ndarray:
return np.polysub(poly1, poly2)
18 changes: 18 additions & 0 deletions ivy/functional/backends/paddle/experimental/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,21 @@ def mel_weight_matrix(
upper_edge_hertz,
)
return paddle.transpose(mel_mat, (1, 0))


def polysub(poly1_coeffs: paddle.Tensor, poly2_coeffs: paddle.Tensor) -> paddle.Tensor:
max_length = max(poly1_coeffs.shape[0], poly1_coeffs.shape[0])
padded_poly1_coeffs = paddle.concat(
[
poly1_coeffs,
paddle.zeros([max_length - poly1_coeffs.shape[0]], dtype="float32"),
]
)
padded_poly2_coeffs = paddle.concat(
[
poly2_coeffs,
paddle.zeros([max_length - poly2_coeffs.shape[0]], dtype="float32"),
]
)

return padded_poly1_coeffs - padded_poly2_coeffs
9 changes: 9 additions & 0 deletions ivy/functional/backends/tensorflow/experimental/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,12 @@ def mel_weight_matrix(
lower_edge_hertz=lower_edge_hertz,
upper_edge_hertz=upper_edge_hertz,
)


def polysub(poly1: tf.Tensor, poly2: tf.Tensor) -> tf.Tensor:
max_length = max(poly1.shape[0], poly2.shape[0])

poly1 = tf.pad(poly1, paddings=[[0, max_length - poly1.shape[0]]])
poly2 = tf.pad(poly2, paddings=[[0, max_length - poly2.shape[0]]])

return tf.subtract(poly1, poly2)
12 changes: 12 additions & 0 deletions ivy/functional/backends/torch/experimental/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,3 +245,15 @@ def hz_to_mel(f):
upper_slopes = (upper_edge_mel - spec_bin_mels) / (upper_edge_mel - center_mel)
mel_weights = torch.maximum(zero, torch.minimum(lower_slopes, upper_slopes))
return torch.nn.functional.pad(mel_weights, (0, 0, 1, 0))


def polysub(poly1: torch.Tensor, poly2: torch.Tensor) -> torch.Tensor:
max_length = max(poly1.shape[0], poly2.shape[0])
poly1 = torch.cat(
(poly1, torch.zeros(max_length - poly1.shape[0], dtype=poly1.dtype)), dim=0
)
poly2 = torch.cat(
(poly2, torch.zeros(max_length - poly2.shape[0], dtype=poly2.dtype)), dim=0
)

return torch.sub(poly1, poly2, alpha=0)
143 changes: 86 additions & 57 deletions ivy/functional/ivy/experimental/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,8 @@ def vorbis_window(
dtype: Optional[Union[ivy.Dtype, ivy.NativeDtype]] = None,
out: Optional[ivy.Array] = None,
) -> ivy.Array:
"""
Return an array that contains a vorbis power complementary window of size
window_length.
"""Return an array that contains a vorbis power complementary window of
size window_length.
samuelmaina marked this conversation as resolved.
Show resolved Hide resolved

Parameters
----------
Expand Down Expand Up @@ -76,9 +75,8 @@ def hann_window(
dtype: Optional[Union[ivy.Dtype, ivy.NativeDtype]] = None,
out: Optional[ivy.Array] = None,
) -> ivy.Array:
"""
Generate a Hann window. The Hanning window is a taper formed by using a weighted
cosine.
"""Generate a Hann window. The Hanning window is a taper formed by using a
weighted cosine.

Parameters
----------
Expand Down Expand Up @@ -125,8 +123,8 @@ def kaiser_window(
dtype: Optional[Union[ivy.Dtype, ivy.NativeDtype]] = None,
out: Optional[ivy.Array] = None,
) -> ivy.Array:
"""
Compute the Kaiser window with window length window_length and shape beta.
"""Compute the Kaiser window with window length window_length and shape
beta.

Parameters
----------
Expand Down Expand Up @@ -172,9 +170,8 @@ def kaiser_bessel_derived_window(
dtype: Optional[Union[ivy.Dtype, ivy.NativeDtype]] = None,
out: Optional[ivy.Array] = None,
) -> ivy.Array:
"""
Compute the Kaiser bessel derived window with window length window_length and shape
beta.
"""Compute the Kaiser bessel derived window with window length
window_length and shape beta.

Parameters
----------
Expand Down Expand Up @@ -226,8 +223,7 @@ def hamming_window(
dtype: Optional[Union[ivy.Dtype, ivy.NativeDtype]] = None,
out: Optional[ivy.Array] = None,
) -> ivy.Array:
"""
Compute the Hamming window with window length window_length.
"""Compute the Hamming window with window length window_length.

Parameters
----------
Expand Down Expand Up @@ -292,16 +288,16 @@ def tril_indices(
*,
device: Optional[Union[ivy.Device, ivy.NativeDevice]] = None,
) -> Tuple[ivy.Array, ...]:
"""
Return the indices of the lower triangular part of a row by col matrix in a 2-by-N
shape (tuple of two N dimensional arrays), where the first row contains row
coordinates of all indices and the second row contains column coordinates. Indices
are ordered based on rows and then columns. The lower triangular part of the matrix
is defined as the elements on and below the diagonal. The argument k controls which
diagonal to consider. If k = 0, all elements on and below the main diagonal are
retained. A positive value excludes just as many diagonals below the main diagonal,
and similarly a negative value includes just as many diagonals above the main
diagonal. The main diagonal are the set of indices {(i,i)} for i∈[0,min{n_rows,
"""Return the indices of the lower triangular part of a row by col matrix
in a 2-by-N shape (tuple of two N dimensional arrays), where the first row
contains row coordinates of all indices and the second row contains column
coordinates. Indices are ordered based on rows and then columns. The lower
triangular part of the matrix is defined as the elements on and below the
diagonal. The argument k controls which diagonal to consider. If k = 0,
all elements on and below the main diagonal are retained. A positive value
excludes just as many diagonals below the main diagonal, and similarly a
negative value includes just as many diagonals above the main diagonal. The
main diagonal are the set of indices {(i,i)} for i∈[0,min{n_rows,
n_cols}−1].

Notes
Expand Down Expand Up @@ -390,10 +386,9 @@ def eye_like(
device: Optional[Union[ivy.Device, ivy.NativeDevice]] = None,
out: Optional[ivy.Array] = None,
) -> ivy.Array:
"""
Return a 2D array filled with ones on the k diagonal and zeros elsewhere. having the
same ``shape`` as the first and last dim of input array ``x``. input array ``x``
should to be 2D.
"""Return a 2D array filled with ones on the k diagonal and zeros
elsewhere. having the same ``shape`` as the first and last dim of input
array ``x``. input array ``x`` should to be 2D.

Parameters
----------
Expand Down Expand Up @@ -483,8 +478,7 @@ def _iter_product(*args, repeat=1):
def ndenumerate(
input: Iterable,
) -> Generator:
"""
Multidimensional index iterator.
"""Multidimensional index iterator.

Parameters
----------
Expand Down Expand Up @@ -523,8 +517,7 @@ def _ndenumerate(input):
def ndindex(
shape: Tuple,
) -> Generator:
"""
Multidimensional index iterator.
"""Multidimensional index iterator.

Parameters
----------
Expand Down Expand Up @@ -557,8 +550,7 @@ def indices(
dtype: Union[ivy.Dtype, ivy.NativeDtype] = ivy.int64,
sparse: bool = False,
) -> Union[ivy.Array, Tuple[ivy.Array, ...]]:
"""
Return an array representing the indices of a grid.
"""Return an array representing the indices of a grid.

Parameters
----------
Expand Down Expand Up @@ -618,9 +610,8 @@ def unsorted_segment_min(
segment_ids: Union[ivy.Array, ivy.NativeArray],
num_segments: Union[int, ivy.Array, ivy.NativeArray],
) -> ivy.Array:
"""
Compute the minimum along segments of an array. Segments are defined by an integer
array of segment IDs.
"""Compute the minimum along segments of an array. Segments are defined by
an integer array of segment IDs.

Note
----
Expand Down Expand Up @@ -658,9 +649,8 @@ def unsorted_segment_sum(
segment_ids: Union[ivy.Array, ivy.NativeArray],
num_segments: Union[int, ivy.Array, ivy.NativeArray],
) -> ivy.Array:
"""
Compute the sum of elements along segments of an array. Segments are defined by an
integer array of segment IDs.
"""Compute the sum of elements along segments of an array. Segments are
defined by an integer array of segment IDs.

Parameters
----------
Expand Down Expand Up @@ -698,10 +688,10 @@ def blackman_window(
dtype: Optional[Union[ivy.Dtype, ivy.NativeDtype]] = None,
out: Optional[ivy.Array] = None,
) -> ivy.Array:
"""
Generate a Blackman window. The Blackman window is a taper formed by using the first
three terms of a summation of cosines. It was designed to have close to the minimal
leakage possible. It is close to optimal, only slightly worse than a Kaiser window.
"""Generate a Blackman window. The Blackman window is a taper formed by
using the first three terms of a summation of cosines. It was designed to
have close to the minimal leakage possible. It is close to optimal, only
slightly worse than a Kaiser window.

Parameters
----------
Expand Down Expand Up @@ -747,8 +737,7 @@ def random_tucker(
seed: Optional[int] = None,
non_negative: Optional[bool] = False,
) -> Union[ivy.TuckerTensor, ivy.Array]:
"""
Generate a random Tucker tensor.
"""Generate a random Tucker tensor.

Parameters
----------
Expand Down Expand Up @@ -817,8 +806,7 @@ def random_cp(
seed: Optional[int] = None,
normalise_factors: Optional[bool] = True,
) -> Union[ivy.CPTensor, ivy.Array]:
"""
Generate a random CP tensor.
"""Generate a random CP tensor.

Parameters
----------
Expand Down Expand Up @@ -872,8 +860,7 @@ def random_tr(
full: Optional[bool] = False,
seed: Optional[int] = None,
) -> Union[ivy.TRTensor, ivy.Array]:
"""
Generate a random TR tensor.
"""Generate a random TR tensor.

Parameters
----------
Expand Down Expand Up @@ -931,8 +918,7 @@ def random_parafac2(
seed: Optional[int] = None,
normalise_factors: Optional[bool] = True,
) -> Union[ivy.Parafac2Tensor, ivy.Array]:
"""
Generate a random PARAFAC2 tensor.
"""Generate a random PARAFAC2 tensor.

Parameters
----------
Expand Down Expand Up @@ -987,8 +973,7 @@ def random_tt(
dtype: Optional[Union[ivy.Dtype, ivy.NativeDtype]] = None,
seed: Optional[int] = None,
) -> Union[ivy.TTTensor, ivy.Array]:
"""
Generate a random TT/MPS tensor.
"""Generate a random TT/MPS tensor.

Parameters
----------
Expand Down Expand Up @@ -1097,10 +1082,10 @@ def mel_weight_matrix(
lower_edge_hertz: float = 0.0,
upper_edge_hertz: float = 3000.0,
):
"""
Generate a MelWeightMatrix that can be used to re-weight a Tensor containing a
linearly sampled frequency spectra (from DFT or STFT) into num_mel_bins frequency
information based on the [lower_edge_hertz, upper_edge_hertz]
"""Generate a MelWeightMatrix that can be used to re-weight a Tensor
containing a linearly sampled frequency spectra (from DFT or STFT) into
num_mel_bins frequency information based on the [lower_edge_hertz,
upper_edge_hertz]

range on the mel scale. This function defines the mel scale in terms of a frequency
in hertz according to the following formula: mel(f) = 2595 * log10(1 + f/700)
Expand Down Expand Up @@ -1137,3 +1122,47 @@ def mel_weight_matrix(
lower_edge_hertz,
upper_edge_hertz,
)


@handle_exceptions
@handle_nestable
@to_native_arrays_and_back
def polysub(poly1: ivy.Array, poly2: ivy.Array) -> ivy.Array:
"""

Parameters
----------
poly1: A 1D array representing the polynomial 1 co-efficients.
poly2: A 1D array representing the polynomial 2 co-efficients

Example 1:
- Equations:
- Polynomial 1: 2x^3 + 3x^2 - x + 5
- Polynomial 2: x^2 - 4x + 1
- Array Representations:
- Polynomial 1: [2, 3, -1, 5]
- Polynomial 2: [0, 1, -4, 1]
- Resulting Polynomial:
- 2x^3 + 2x^2 + 3x + 4
- Array Representation of Resulting Polynomial:
- [2, 2, 3, 4]



Example 2:
- Equations:
- Polynomial 1: 6x^3 + 4x^2 - 3x + 2
- Polynomial 2: 4x^4 + x^3 - 2x^2 + 5x
- Array Representations:
- Polynomial 1: [6, 4, -3, 2]
- Polynomial 2: [0, 4, 1, -2, 5]
- Resulting Polynomial:
- -4x^4 - 5x^3 + 6x^2 + 8x + 2
- Array Representation of Resulting Polynomial:
- [-4, -5, 6, 8, 2]

Returns
-------
A 1D array representing the resultant polynomial after subtraction.
"""
return ivy.current_backend().polysub(poly1, poly2)
Loading