Archived
340 lines
11 KiB
Python
340 lines
11 KiB
Python
# --------------------------------------------------------------------------
|
|
# Authors:
|
|
# ------ MATlAB ------
|
|
# 2010-03-16: Etienne Gaudrain <etienne.gaudrain@mrc-cbu.cam.ac.uk>
|
|
# 2011-10-20: Etienne Gaudrain <etienne.gaudrain@mrc-cbu.cam.ac.uk>
|
|
# 2013-04-22: Etienne Gaudrain <e.p.c.gaudrain@rug.nl>
|
|
# 2017-03-27: Etienne Gaudrain <etienne.gaudrain@cnrs.fr>
|
|
# ------ Python ------
|
|
# 2020-02-10: Luke Meyer < l.meyer.5@student.rug.nl >
|
|
|
|
# Copyright MRC-CBSU(UK), CNRS(FR), UMCG(NL) and the author(s).
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
# it under the terms of the GNU General Public License as published by
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY
|
|
# without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU General Public License for more details.
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
# along with this program. If not, see < http: // www.gnu.org/licenses/>.
|
|
# --------------------------------------------------------------------------
|
|
|
|
from pyworld import pyworld as pw
|
|
import numpy as np
|
|
import os
|
|
import math
|
|
import warnings
|
|
import logging
|
|
from time import clock
|
|
from scipy import interpolate
|
|
import scipy.io as spio
|
|
import soundfile as sf
|
|
from resampy import resample
|
|
import random
|
|
import collections
|
|
import matplotlib.pyplot as plt
|
|
# from audiotsm import phasevocoder
|
|
# from audiotsm.io.wav import WavReader, WavWriter
|
|
from tools.load_matrix import loadmat
|
|
|
|
import sys
|
|
|
|
# -- Uncomment for when using the MATLAB/Python API ---
|
|
# import matlab.engine
|
|
# future = matlab.engine.start_matlab(async=True)
|
|
# eng = future.result()
|
|
# eng.addpath('../Nao-PICKA scripts/Expe_files/lib/STRAIGHTV40_006b')
|
|
|
|
|
|
time_logger = logging.getLogger("time_logger")
|
|
expe_logger = logging.getLogger("expe_logger")
|
|
|
|
|
|
def expe_make_stim(options, trial, p):
|
|
'''
|
|
Generates the stimuli files for a given trial
|
|
and how the trial has been specified
|
|
'''
|
|
|
|
xOut_temp = collections.OrderedDict()
|
|
f0 = [trial["f0"][0], trial["f0"][1]]
|
|
ser = [trial["ser"][0], trial["ser"][1]]
|
|
|
|
for i in range(len(trial["syllables"])):
|
|
|
|
sylls = trial["syllables"][i]
|
|
x = np.array([])
|
|
|
|
for j in range(len(sylls)):
|
|
|
|
tmp = f0[i]
|
|
octave = options["f0_contour_step_size"] * \
|
|
(trial["f0_contours"][j, i] / 12.0)
|
|
|
|
sf0 = tmp * np.power(2, octave)
|
|
t = clock()
|
|
y, fs = straight_process(sylls[j], sf0, ser[i], options, p, trial)
|
|
# y = y * np.power(10, -options["attenuation_dB"]/20.0)
|
|
y = y * 10 ** options["attenuation_dB"]/20.0
|
|
stim_time = clock() - t
|
|
time_logger.info(
|
|
"Time to generate single stimulus: {}".format(stim_time))
|
|
|
|
if fs != options["fs"]:
|
|
y = resample(y, options["fs"], fs, filter="kaiser_fast")
|
|
options["fs"] = fs
|
|
|
|
d1 = int(round(options["syllable_duration"]*fs) - len(y))
|
|
|
|
if d1 > 0:
|
|
# Adds padding because the syllable signal is too short
|
|
npad_L = int(math.floor(d1/20))
|
|
npad_R = int(d1-npad_L)
|
|
|
|
nr = int(math.floor(1e-3 * fs))
|
|
y[0:nr] = y[0:nr] * np.linspace(0, 1, num=nr).conj().T
|
|
y[len(y)-nr:] = y[len(y)-nr:] * np.linspace(1, 0, num=nr).T
|
|
|
|
y = np.concatenate(
|
|
(np.zeros((npad_L,)), y, np.zeros((npad_R,))))
|
|
|
|
elif d1 < 0:
|
|
# The synthesised signal is too long
|
|
y = y[0:len(y)-d1]
|
|
nr = int(math.floor(1e-3 * fs)) # 1 ms linear ramp at the end
|
|
y[len(y)-nr:] = y[len(y)-nr:] * np.linspace(1, 0, num=nr).T
|
|
|
|
else:
|
|
nr = int(math.floor(1e-3 * fs))
|
|
y[0:nr] = y[0:nr] * np.linspace(0, 1, num=nr).conj().T
|
|
y[len(y)-nr:] = y[len(y)-nr:] * np.linspace(1, 0, num=nr).T
|
|
|
|
x = np.concatenate((x, y))
|
|
zeros = np.zeros(
|
|
(int(math.floor(fs*options["inter_syllable_silence"])),))
|
|
|
|
if j != len(sylls):
|
|
x = np.concatenate((x, zeros))
|
|
|
|
# TODO come back to coding in the vocoder
|
|
# if trial["vocoder"] > 0:
|
|
# pass
|
|
|
|
if options["ear"] == 'right':
|
|
x = np.matrix([np.zeros(np.size(x))], x)
|
|
elif options["ear"] == 'left':
|
|
x = np.matrix([x], [np.zeros(np.size(x))])
|
|
elif options["ear"] == 'both':
|
|
x = np.tile(x, (2, 1)).T
|
|
else:
|
|
raise ValueError(
|
|
"Options.ear = {} is not implemented.".format(options["ear"]))
|
|
|
|
if i == 0:
|
|
xOut_temp[0] = x
|
|
xOut_temp[1] = x
|
|
else:
|
|
xOut_temp[2] = x
|
|
|
|
# Create a random permutation array according to the length of xOut_temp
|
|
i_order = np.random.permutation(len(xOut_temp))
|
|
|
|
keys = list(xOut_temp.keys())
|
|
keys = [keys[i] for i in i_order]
|
|
# Create the ordered dictionary that holds the randomised stimuli in the order given
|
|
xOut = collections.OrderedDict()
|
|
i = 0
|
|
for key in keys:
|
|
xOut[i] = xOut_temp[key]
|
|
i += 1
|
|
i_correct = np.where(i_order == 2)
|
|
i_correct = i_correct[0][0]
|
|
|
|
return xOut, fs, i_correct
|
|
|
|
|
|
def straight_process(syll, t_f0, ser, options, p, trial):
|
|
'''
|
|
Generates the individual stimuli files
|
|
'''
|
|
|
|
wavIn = os.path.join(options["sound_path"], syll + ".wav")
|
|
wavOut = make_fname(
|
|
wavIn, t_f0, ser, options["syllable_duration"], options["tmp_path"], trial)
|
|
y = []
|
|
fs = 0
|
|
|
|
if not os.path.exists(wavOut) or options["force_rebuild_sylls"]:
|
|
|
|
# Matlab
|
|
# mat = os.path.join(options["sound_path"], syll + '.straight.mat')
|
|
# PyWorld
|
|
mat = os.path.join(options["sound_path_store"], syll + '.pyworld.mat')
|
|
# Intialise varibales so they are accessible in the correct scope
|
|
f0 = []
|
|
fs = 0
|
|
sp = []
|
|
ap = []
|
|
freq = []
|
|
temp_pos = []
|
|
x_rms = 0
|
|
|
|
if os.path.exists(mat):
|
|
# Load the data from the .mat file
|
|
load_mat = loadmat(mat)
|
|
f0 = load_mat['f0']
|
|
fs = load_mat['fs']
|
|
sp = np.array(load_mat['sp'])
|
|
ap = np.array(load_mat['ap'])
|
|
# Needed for PyWorld
|
|
freq = np.array(load_mat["frequencies"])
|
|
temp_pos = np.array(load_mat["temporal_positions"])
|
|
x_rms = load_mat['x_rms']
|
|
else:
|
|
pass
|
|
x, fs = sf.read(wavIn)
|
|
|
|
# --- Using MATLAB scripts
|
|
# x = x.tolist()
|
|
# mat_x = matlab.double(x)
|
|
# mat_fs = matlab.single([fs])
|
|
# f0, ap = eng.exstraightsource(mat_x, mat_fs)
|
|
|
|
# --- Using PyWORLD script
|
|
# -- Works for f0 and VTL changes
|
|
_f0, t = pw.dio(x, fs)
|
|
f0 = pw.stonemask(x, _f0, t, fs)
|
|
sp = pw.cheaptrick(x, f0, t, fs)
|
|
ap = pw.d4c(x, f0, t, fs)
|
|
freq = np.arange(0, np.size(sp, axis=1),
|
|
dtype='float64') / (np.size(sp)) * fs/2
|
|
temp_pos = t
|
|
|
|
x_rms = np.sqrt(np.mean(x**2))
|
|
duration = len(x/fs)
|
|
|
|
spio.savemat(mat, mdict={'fs': fs, 'f0': f0,
|
|
'sp': sp, 'ap': ap,
|
|
'x_rms': x_rms,
|
|
'frequencies': freq,
|
|
'temporal_positions': t,
|
|
'duration': duration
|
|
})
|
|
|
|
mf0_arr = []
|
|
|
|
for i in f0:
|
|
if i != 0:
|
|
mf0_arr.append(np.log(i))
|
|
|
|
mf0 = np.e**(np.mean(np.array(mf0_arr)))
|
|
|
|
for i in range(len(f0)):
|
|
if f0[i] != 0:
|
|
f0[i] = f0[i] / mf0 * t_f0
|
|
|
|
# Only necessary when running the MATLAB code
|
|
try:
|
|
p["timeAxisMappingTable"] = (
|
|
options["syllable_duration"] * 1e3)/len(f0)
|
|
|
|
except ZeroDivisionError as e:
|
|
print "-------- ERROR : " + str(e) + ' ------------'
|
|
print "length f0 was 0"
|
|
p["timeAxisMappingTable"] = 0
|
|
p["frequencyAxisMappingTable"] = ser.item()
|
|
|
|
# --- Uncomment when using the MATLAB scripts
|
|
# mat_f0 = f0.tolist()
|
|
# mat_f0 = matlab.double(mat_f0)
|
|
# mat_sp = sp.tolist()
|
|
# mat_sp = matlab.double(mat_sp)
|
|
# mat_ap = ap.tolist()
|
|
# mat_ap = matlab.double(mat_ap)
|
|
# mat_fs = matlab.single([fs])
|
|
# y_mat = eng.exstraightsynth(mat_f0, mat_sp, mat_ap, mat_fs, p)
|
|
|
|
# --- Uncomment when using PyWORLD script
|
|
sp = sp_ap_creation(sp, temp_pos, freq, ser)
|
|
ap = sp_ap_creation(ap, temp_pos, freq, ser)
|
|
if f0.flags['C_CONTIGUOUS']:
|
|
f0 = np.ascontiguousarray(f0, dtype=np.float)
|
|
sp = np.ascontiguousarray(
|
|
sp, dtype=np.float)
|
|
ap = np.ascontiguousarray(
|
|
ap, dtype=np.float)
|
|
|
|
y_mat = pw.synthesize(f0, sp, ap, fs)
|
|
|
|
y = np.array(y_mat)
|
|
|
|
y = y / np.sqrt(np.mean(y**2)) * x_rms
|
|
|
|
if np.amax(np.absolute(y)) > 1:
|
|
expe_logger.warn("Output was normalised for {}".format(wavOut))
|
|
y = 0.98 * y / np.amax(np.absolute(y))
|
|
|
|
sf.write(wavOut, y, fs)
|
|
|
|
y, fs = sf.read(wavOut)
|
|
|
|
# axes = np.arange(0, len(y))
|
|
# ax.plot(axes, y)
|
|
# fig.savefig("test1.png")
|
|
# plt.show()
|
|
|
|
else:
|
|
y, fs = sf.read(wavOut)
|
|
|
|
return y, fs
|
|
|
|
|
|
def make_fname(wav, f0, ser, d, destPath, trial):
|
|
'''Generates the file name for the new stimulus'''
|
|
|
|
_, namext = os.path.split(wav)
|
|
name, ext = os.path.splitext(namext)
|
|
|
|
try:
|
|
int(math.floor(f0))
|
|
except ValueError as e:
|
|
print e
|
|
|
|
# fname = "{}_GPR{}_ser{}_D{}".format(name, math.floor(f0), ser, math.floor(d*1e3))
|
|
fname = "%s_GPR%d_ser%.2f_D%d" % (
|
|
name, int(math.floor(f0)), ser, int(math.floor(d*1e3)))
|
|
fname = os.path.join(destPath, fname + ext)
|
|
|
|
return fname
|
|
|
|
|
|
def sp_ap_creation(mat, temp, freq, ser):
|
|
'''
|
|
Interpolates the spectrogram and aperiodicity, respectively
|
|
using the same temporal positions, but new freq that takes
|
|
into account the ser value (ser = np.power(2, -dVTL/12)).
|
|
Ser is usually provided by the defined options in
|
|
expe_build_conditions
|
|
'''
|
|
# x = np.arange(1, mat.shape[1]+1)
|
|
# y = np.arange(1, mat.shape[0]+1)
|
|
|
|
# f = interpolate.interp2d(x, y, mat, kind='cubic')
|
|
f = interpolate.RectBivariateSpline(temp, freq, mat)
|
|
|
|
interp = f(temp, freq.T/ser)
|
|
|
|
return interp
|
|
|
|
# xs = np.arange(1, spe["spectrogram"].shape[1]+1)
|
|
# ys = np.arange(1, spe["spectrogram"].shape[0]+1)
|
|
# fis = interp2d(xs, ys, spe["spectrogram"], 'cubic')
|
|
# spe["spectrogram"] = fis(spe["temporal_positions"],
|
|
# spe["frequencies"]/ser)
|