Last active
January 20, 2025 07:00
-
-
Save tam17aki/752be79a011fd066dece99f702c32446 to your computer and use it in GitHub Desktop.
An implementation of "Griffin-Lim Like Phase Recovery via Alternating Direction Method of Multipliers" in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
"""Demonstration script for Griffin-Lim like phase recovery via ADMM. | |
Copyright (C) 2025 by Akira TAMAMORI | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. | |
""" | |
import argparse | |
from typing import NamedTuple | |
import numpy as np | |
import numpy.typing as npt | |
import soundfile as sf | |
from librosa.core.spectrum import istft, stft | |
from pesq import pesq | |
from pystoi.stoi import stoi | |
class Arguments(NamedTuple): | |
"""Defines a class for miscellaneous configurations.""" | |
in_file: str # input wav file | |
out_file: str # output (reconstructed) wav file | |
class ADMMConfig(NamedTuple): | |
"""Defines a class for ADMM configurations.""" | |
rho: float # ADMM parameter | |
n_steps: int # Number of optimization steps | |
class FeatureConfig(NamedTuple): | |
"""Defines a class for configurations of feature extraction.""" | |
n_fft: int = 1024 # FFT points | |
hop_length: int = 256 # Hop length | |
window: str = "hann" # Window type | |
def check_positive_float(value: str) -> float: | |
"""Check positivity of float value. | |
Args: | |
value (str): Float value in string. | |
Returns: | |
fvalue (float): Positive float value. | |
Raises: | |
ArgumentTypeError: An error occurred in taking non-positive float value. | |
""" | |
fvalue: float = -1.0 | |
try: | |
fvalue = float(value) | |
except ValueError as exc: | |
raise argparse.ArgumentTypeError(f"'{value}' is invalid float value.") from exc | |
if fvalue <= 0: | |
raise argparse.ArgumentTypeError(f"{value} is an invalid positive float value") | |
return fvalue | |
def check_positive_int(value: str) -> int: | |
"""Check positivity of integer value. | |
Args: | |
value (str): Integer value in string. | |
Returns: | |
ivalue (int): Positive integer value. | |
Raises: | |
ArgumentTypeError: An error occurred in taking non-positive integer value. | |
""" | |
ivalue: int = -1 | |
try: | |
ivalue = int(value) | |
except ValueError as exc: | |
raise argparse.ArgumentTypeError(f"'{value}' is invalid int value.") from exc | |
if ivalue <= 0: | |
raise argparse.ArgumentTypeError(f"{value} is an invalid positive int value.") | |
return ivalue | |
def parse_args() -> tuple[Arguments, ADMMConfig]: | |
"""Parse command line arguments. | |
Returns: | |
arguments (Arguments): Miscellaneous configurations. | |
admm_config (ADMMConfig): Configurations of ADMM. | |
""" | |
parser = argparse.ArgumentParser( | |
description="Demonstration script for Griffin-Lim like phase recovery via ADMM" | |
) | |
parser.add_argument("--in_file", type=str, default="in.wav", help="Input wav file") | |
parser.add_argument( | |
"--out_file", type=str, default="out.wav", help="Output wav file" | |
) | |
parser.add_argument( | |
"--rho", type=check_positive_float, default="0.1", help="ADMM parameter" | |
) | |
parser.add_argument( | |
"--n_steps", | |
type=check_positive_int, | |
default="500", | |
help="Number of optimization steps", | |
) | |
args = parser.parse_args() | |
arguments = Arguments(in_file=args.in_file, out_file=args.out_file) | |
admm_config = ADMMConfig(rho=args.rho, n_steps=args.n_steps) | |
return arguments, admm_config | |
def amp_constrained_proj( | |
x: npt.NDArray[np.complex128], amp_spec: npt.NDArray[np.float64] | |
) -> npt.NDArray[np.complex128]: | |
"""Perform amplitude-constrained projection. | |
This projection operation replaces the magnitude of each element in | |
the input complex spectrogram `x` with the corresponding value in the | |
target amplitude spectrogram `amp_spec`, while preserving the phase | |
spectrogram from the input `x` | |
Args: | |
x (npt.NDArray[np.complex128]): complex-valued spectrogram. | |
amp_spec (npt.NDArray[np.float64]): amplitude spectrogram. | |
Returns: | |
projected (npt.NDArray[np.complex128]): projected complex-valued spectrogram. | |
""" | |
y = amp_spec * np.exp(1j * np.angle(x)) | |
projected: npt.NDArray[np.complex128] = y.astype(np.complex128) | |
return projected | |
def consistency_proj( | |
x: npt.NDArray[np.complex128], n_fft: int, hop_length: int, window: str | |
) -> npt.NDArray[np.complex128]: | |
"""Perform linear projection satifying STFT consistency criterion. | |
Args: | |
x (npt.NDArray[np.complex128]): complex-valued spectrogram. | |
n_fft (int): FFT window size. | |
hop_length (int): Hop length. | |
window (str): Window type. | |
Returns: | |
projected (npt.NDArray[np.complex128]): projected spectrogram. | |
""" | |
projected = stft( | |
istft(x, hop_length=hop_length, window=window), | |
n_fft=n_fft, | |
hop_length=hop_length, | |
window=window, | |
) | |
return projected | |
def proximity_squared( | |
x: npt.NDArray[np.complex128], rho: float, n_fft: int, hop_length: int, window: str | |
) -> npt.NDArray[np.complex128]: | |
"""Apply proximity operator of the squared distance to complex-valued spectrogram. | |
Args: | |
x (npt.NDArray[np.complex128]): complex-valued spectrogram. | |
rho (float): ADMM parameter. | |
n_fft (int): FFT window size. | |
hop_length (int): Hop length. | |
window (str): Window type. | |
Returns: | |
npt.NDArray[np.complex128]: mixture of input and its projected spectrogram. | |
""" | |
return (rho * x + consistency_proj(x, n_fft, hop_length, window)) / (1.0 + rho) | |
def admm_phase_recovery( | |
amp_spec: npt.NDArray[np.float64], | |
feat_config: FeatureConfig, | |
admm_config: ADMMConfig, | |
) -> npt.NDArray[np.complex128]: | |
"""Perform ADMM-based phase recovery. | |
This function implements phase recovery using the Alternating Direction | |
Method of Multipliers (ADMM) algorithm, as described in the following paper: | |
"Griffin-Lim like phase recovery via alternating direction method of multipliers," | |
Yoshiki Masuyama, Kohei Yatabe, and Yasuhiro Oikawa | |
IEEE Signal Processing Letters, vol.26, no.1, pp.184--188, Jan. 2019. | |
https://ieeexplore.ieee.org/document/8552369 | |
Args: | |
amp_spec (npt.NDArray[np.float64]): Amplitude spectrogram. | |
feat_config (FeatureConfig): Configurations of feature extraction. | |
admm_config (ADMMConfig): Configurations of ADMM. | |
Returns: | |
recovered_spec (npt.NDArray[np.complex128]): Recovered STFT spectrogram. | |
""" | |
n_fft = feat_config.n_fft | |
hop_length = feat_config.hop_length | |
window = feat_config.window | |
rho = admm_config.rho | |
n_steps = admm_config.n_steps | |
random_phase = np.random.uniform(-np.pi, np.pi, amp_spec.shape) | |
x = amp_spec * np.exp(1j * random_phase).astype(np.complex128) | |
z = x | |
u = np.zeros(amp_spec.shape, dtype=np.complex128) | |
for _ in range(n_steps): | |
x = amp_constrained_proj(z - u, amp_spec) | |
z = proximity_squared(x + u, rho, n_fft, hop_length, window) | |
u = u + x - z | |
recovered_spec: npt.NDArray[np.complex128] = x | |
return recovered_spec | |
def calculate_estoi( | |
orig_signal: npt.NDArray[np.float64], | |
reconst_signal: npt.NDArray[np.float64], | |
sr: int, | |
) -> float: | |
"""Calculate Extended Short-Time Objective Intelligibility (ESTOI). | |
Args: | |
orig_signal (npt.NDArray[np.float64]): Original time-domain signal. | |
reconst_signal (npt.NDArray[np.float64]): Reconstructed time-domain signal. | |
sr (int): Sampling rate. | |
Returns: | |
float: ESTOI score. | |
""" | |
if orig_signal.size > reconst_signal.size: | |
orig_signal = orig_signal[: reconst_signal.size] | |
else: | |
reconst_signal = reconst_signal[: orig_signal.size] | |
estoi_score: float = stoi(orig_signal, reconst_signal, sr, extended=True) | |
return estoi_score | |
def calculate_pesq( | |
orig_signal: npt.NDArray[np.float64], | |
reconst_signal: npt.NDArray[np.float64], | |
sr: int, | |
) -> float: | |
"""Calculate Perceptual Evaluation of Speech Quality (PESQ). | |
Args: | |
orig_signal (npt.NDArray[np.float64]): Original time-domain signal. | |
reconst_signal (npt.NDArray[np.float64]): Reconstructed time-domain signal. | |
sr (int): Sampling rate. | |
Returns: | |
float: PESQ score. | |
""" | |
pesq_score: float = pesq(sr, orig_signal, reconst_signal, "wb") | |
return pesq_score | |
def main() -> None: | |
"""Perform demonstration.""" | |
args, admm_config = parse_args() | |
feat_config = FeatureConfig() | |
n_fft = feat_config.n_fft | |
hop_length = feat_config.hop_length | |
window = feat_config.window | |
orig_signal, sr = sf.read(args.in_file) | |
amp_spec = np.abs( | |
stft(orig_signal, n_fft=n_fft, hop_length=hop_length, window=window) | |
) | |
recovered_spec = admm_phase_recovery(amp_spec, feat_config, admm_config) | |
reconst_signal = istft(recovered_spec, hop_length=hop_length, window=window) | |
sf.write(args.out_file, reconst_signal, sr) | |
estoi_score = calculate_estoi(orig_signal, reconst_signal, sr) | |
pesq_score = calculate_pesq(orig_signal, reconst_signal, sr) | |
print(f"ESTOI = {estoi_score:.6f}, PESQ = {pesq_score:.6f}") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment