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

Add lspcheck #60

Merged
merged 3 commits into from
Dec 18, 2023
Merged
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
1 change: 1 addition & 0 deletions diffsptk/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
from .lpccheck import LinearPredictiveCoefficientsStabilityCheck
from .lsp2lpc import LineSpectralPairsToLinearPredictiveCoefficients
from .lsp2sp import LineSpectralPairsToSpectrum
from .lspcheck import LineSpectralPairsStabilityCheck
from .magic_intpl import MagicNumberInterpolation
from .mc2b import MelCepstrumToMLSADigitalFilterCoefficients
from .mcpf import MelCepstrumPostfiltering
Expand Down
5 changes: 3 additions & 2 deletions diffsptk/core/lpc2lsp.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,9 @@ def forward(self, a):
q = self.root_q(q)
p = torch.angle(p[..., 0::2])
q = torch.angle(q[..., 0::2])
w, _ = torch.sort(torch.cat([p, q], dim=-1))
w, _ = torch.sort(torch.cat((p, q), dim=-1))

w = w.view_as(a)
w = torch.cat([K, self.convert(w)], dim=-1)
w = self.convert(w)
w = torch.cat((K, w), dim=-1)
return w
2 changes: 1 addition & 1 deletion diffsptk/core/lpccheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def __init__(self, lpc_order, margin=1e-16, warn_type="warn"):

self.bound = 1 - margin

assert 0 < margin and margin < 1
assert 0 < margin < 1

self.lpc2par = LinearPredictiveCoefficientsToParcorCoefficients(
lpc_order, warn_type=warn_type
Expand Down
2 changes: 1 addition & 1 deletion diffsptk/core/lsp2lpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,5 +106,5 @@ def forward(self, w):
a = 0.5 * (p + q)

a = a.view_as(w)
a = torch.cat([K, a], dim=-1)
a = torch.cat((K, a), dim=-1)
return a
108 changes: 108 additions & 0 deletions diffsptk/core/lspcheck.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# ------------------------------------------------------------------------ #
# Copyright 2022 SPTK Working Group #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
# ------------------------------------------------------------------------ #

import warnings

import torch
import torch.nn as nn

from ..misc.utils import check_size


class LineSpectralPairsStabilityCheck(nn.Module):
"""See `this page <https://sp-nitech.github.io/sptk/latest/main/lspcheck.html>`_
for details.

Parameters
----------
lsp_order : int >= 0 [scalar]
Order of LSP, :math:`M`.

rate : [0 <= float <= 1]
Rate of distance between two adjacent LSPs.

n_iter : int >= 0 [scalar]
Number of iterations for modification.

warn_type : ['ignore', 'warn', 'exit']
Behavior for unstable LSP.

"""

def __init__(self, lsp_order, rate=0, n_iter=1, warn_type="warn"):
super(LineSpectralPairsStabilityCheck, self).__init__()

self.lsp_order = lsp_order
self.min_distance = rate * torch.pi / (self.lsp_order + 1)
self.n_iter = n_iter
self.warn_type = warn_type

assert 0 <= self.lsp_order
assert 0 <= rate <= 1
assert 0 <= self.n_iter
assert self.warn_type in ("ignore", "warn", "exit")

def forward(self, w1):
"""Check stability of LSP.

Parameters
----------
w1 : Tensor [shape=(..., M+1)]
LSP coefficients.

Returns
-------
w2 : Tensor [shape=(..., M+1)]
Modified LSP coefficients.

Examples
--------
>>> w1 = torch.tensor([0, 0, 1]) * torch.pi
>>> lspcheck = diffsptk.LineSpectralPairsStabilityCheck(2, rate=0.01)
>>> w2 = lspcheck(w1)
>>> w2
tensor([0.0000, 0.0105, 3.1311])

"""
check_size(w1.size(-1), self.lsp_order + 1, "dimension of LSP")

K, w = torch.split(w1, [1, self.lsp_order], dim=-1)
distance = w[..., 1:] - w[..., :-1]
if torch.any(distance <= 0) or torch.any(w <= 0) or torch.any(torch.pi <= w):
if self.warn_type == "ignore":
pass
elif self.warn_type == "warn":
warnings.warn("Unstable LSP coefficients")
elif self.warn_type == "exit":
raise RuntimeError("Unstable LSP coefficients")
else:
raise RuntimeError

w = w.clone()
for _ in range(self.n_iter):
for m in range(self.lsp_order - 1):
n = m + 1
distance = w[..., n] - w[..., m]
step_size = 0.5 * torch.clip(self.min_distance - distance, 0)
w[..., m] -= step_size
w[..., n] += step_size
w = torch.clip(w, self.min_distance, torch.pi - self.min_distance)
distance = w[..., 1:] - w[..., :-1]
if torch.all(self.min_distance - 1e-16 <= distance):
break

w2 = torch.cat((K, w), dim=-1)
return w2
2 changes: 1 addition & 1 deletion diffsptk/core/root_pol.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def forward(self, a):
# Make companion matrix.
a = -a[..., 1:] / a[..., :1] # (..., M)
E = self.eye.expand(a.size()[:-1] + self.eye.size())
A = torch.cat([a.unsqueeze(-2), E], dim=-2) # (..., M, M)
A = torch.cat((a.unsqueeze(-2), E), dim=-2) # (..., M, M)

# Find roots as eigenvalues.
x, _ = torch.linalg.eig(A)
Expand Down
2 changes: 1 addition & 1 deletion docs/core/lpc2lsp.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ lpc2lsp
.. autoclass:: diffsptk.LinearPredictiveCoefficientsToLineSpectralPairs
:members:

.. seealso:: :ref:`lpc` :ref:`lsp2sp` :ref:`lsp2lpc`
.. seealso:: :ref:`lpc` :ref:`lsp2lpc` :ref:`lsp2sp` :ref:`lspcheck`
9 changes: 9 additions & 0 deletions docs/core/lspcheck.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
.. _lspccheck:

lspcheck
--------

.. autoclass:: diffsptk.LineSpectralPairsStabilityCheck
:members:

.. seealso:: :ref:`lpc2lsp`
43 changes: 43 additions & 0 deletions tests/test_lspcheck.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# ------------------------------------------------------------------------ #
# Copyright 2022 SPTK Working Group #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
# ------------------------------------------------------------------------ #

import pytest
import torch

import diffsptk
import tests.utils as U


@pytest.mark.parametrize("device", ["cpu", "cuda"])
def test_compatibility(device, L=32, M=9, rate=0.8, B=2):
lspcheck = diffsptk.LineSpectralPairsStabilityCheck(
M, rate=rate, n_iter=1, warn_type="ignore"
)

U.check_compatibility(
device,
lspcheck,
[],
f"nrand -l {B*L} | lpc -l {L} -m {M} | lpc2lsp -m {M}",
f"lspcheck -m {M} -r {rate} -e 0 -x",
[],
dx=M + 1,
dy=M + 1,
)

U.check_differentiable(
device, [lspcheck, lambda x: torch.sort(x)[0], torch.abs], [B, M + 1]
)