Archived
Initial commit
This commit is contained in:
commit
d89b82be4a
103 files changed
+23110
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,236 @@
|
||||
import numpy as np
|
||||
import os
|
||||
|
||||
from pick import pick
|
||||
from parse_corpus import parseCorpus
|
||||
from scipy.io import savemat
|
||||
import warnings
|
||||
from tools.load_matrix import loadmat
|
||||
|
||||
CALIBRATE = False
|
||||
|
||||
|
||||
def expe_build_conditions(options):
|
||||
options["fs"] = 44100
|
||||
options["gain"] = 0
|
||||
mat = loadmat('./calibration.mat')
|
||||
cal = mat["calibration"]
|
||||
options["attenuation_dB"] = cal["crm"]
|
||||
# options["attenuation_dB"] = 10 # Calibrated attenuation from fishy
|
||||
|
||||
options["target_corpus_language"] = options["language"]
|
||||
options["target_corpus_path"] = "./stimuli/crm/spk1F-" + \
|
||||
options["language"].lower()
|
||||
|
||||
if options["target_corpus_language"] == "tr_tr":
|
||||
options["target_corpus_filemask"] = 'cat_*.wav'
|
||||
else:
|
||||
options["target_corpus_filemask"] = 'dog_*.wav'
|
||||
|
||||
options["target_corpus"] = parseCorpus(options["target_corpus_path"],
|
||||
options["target_corpus_filemask"])
|
||||
|
||||
options["n_colours"] = len(options["target_corpus"]["colours"])
|
||||
options["n_numbers"] = len(options["target_corpus"]["numbers"])
|
||||
options["n_call_signs"] = len(options["target_corpus"]["call_signs"])
|
||||
|
||||
np.random.shuffle(options["target_corpus"]["colours"])
|
||||
|
||||
if options["target_corpus_language"] == "tr_tr":
|
||||
options["images"] = "girl+cat.jpg"
|
||||
else:
|
||||
options["images"] = "woman+dog.jpg"
|
||||
|
||||
# Masker options
|
||||
options["masker_corpus_language"] = options["language"]
|
||||
options["masker_corpus_path"] = options["target_corpus_path"]
|
||||
if options["target_corpus_language"] == "tr_tr":
|
||||
options["masker_corpus_filemask"] = "rabbit_*.wav"
|
||||
else:
|
||||
options["masker_corpus_filemask"] = "cat_*.wav"
|
||||
|
||||
lst = [
|
||||
f for f in os.listdir(options["masker_corpus_path"])
|
||||
if f.startswith(options["masker_corpus_filemask"].split('_')[0])
|
||||
and f.endswith('.wav')
|
||||
]
|
||||
options["masker_corpus"] = lst
|
||||
|
||||
options["sounds_for_calibration"] = []
|
||||
|
||||
lst = [
|
||||
f for f in os.listdir(options["target_corpus_path"])
|
||||
if f.startswith(options["target_corpus_filemask"].split('_')[0])
|
||||
and f.endswith('.wav')
|
||||
]
|
||||
|
||||
if not CALIBRATE:
|
||||
for k in range(len(lst)):
|
||||
options["sounds_for_calibration"].append(
|
||||
os.path.join(options["target_corpus_path"], lst[k]))
|
||||
|
||||
for k in range(len(options["masker_corpus"])):
|
||||
options["sounds_for_calibration"].append(
|
||||
os.path.join(options["masker_corpus_path"], lst[k]))
|
||||
else:
|
||||
for k in range(10):
|
||||
options["sounds_for_calibration"].append(
|
||||
os.path.join(options["target_corpus_path"], lst[k]))
|
||||
|
||||
for k in range(10):
|
||||
options["sounds_for_calibration"].append(
|
||||
os.path.join(options["masker_corpus_path"], lst[k]))
|
||||
|
||||
options["cache_path"] = "./stimuli_store/crm/spk1F-" + \
|
||||
options["masker_corpus_language"].lower()
|
||||
|
||||
if not os.path.exists(options["cache_path"]):
|
||||
os.makedirs(options["cache_path"])
|
||||
|
||||
options["voices"] = {}
|
||||
|
||||
i = 1
|
||||
|
||||
for dF0 in np.linspace(0, -12, 3):
|
||||
for dVTL in np.linspace(0, 3.8, 3):
|
||||
options["voices"]["v" + str(i)] = {}
|
||||
options["voices"]["v" + str(i)]["dF0"] = dF0
|
||||
options["voices"]["v" + str(i)]["dVTL"] = dVTL
|
||||
i += 1
|
||||
|
||||
options["n_voices"] = len(options["voices"])
|
||||
|
||||
# Check if NH or HI
|
||||
grp = ""
|
||||
if "subject_name" in options and options["subject_name"] != "":
|
||||
grp = options["subject_name"][0:2]
|
||||
else:
|
||||
grp = "NH"
|
||||
if grp == "NH":
|
||||
options["tmrs"] = np.array([-6, 0, 6, np.inf])
|
||||
elif grp == "HI" or grp == "CI":
|
||||
options["tmrs"] = np.array([0, 6, 12, np.inf])
|
||||
|
||||
# Strategy on hoe to change the TMR
|
||||
# - In the 'louder_constant' strategy, the TMR is such that we keep the target level constant for TMRs>0, and the masker level constant for TMRs<0
|
||||
# - In the 'constant_level' strategy, we keep the overall level constant
|
||||
|
||||
options["tmr_strategy"] = 'constant_level'
|
||||
|
||||
options["target_delay"] = 750e-3
|
||||
options["masker_end_delay"] = 250e-3
|
||||
options["masker_min_chunk_duration"] = 150e-3
|
||||
options["masker_max_chunk_duration"] = 300e-3
|
||||
options["masker_chunk_ramp"] = 2e-3
|
||||
options["masker_ramp"] = 50e-3
|
||||
|
||||
options["test"] = {}
|
||||
options["training"] = {}
|
||||
|
||||
options["test"]["n_repeat"] = 7
|
||||
options["training"]["n_repeat"] = 1
|
||||
|
||||
options["training"]["block_size"] = 20
|
||||
options["test"]["block_size"] = 30
|
||||
|
||||
test = {}
|
||||
|
||||
for i_repeat in range(options["test"]["n_repeat"]):
|
||||
for i_tmr in range(len(options["tmrs"])):
|
||||
if options["tmrs"][i_tmr] == np.inf:
|
||||
i_voices = np.array([1])
|
||||
else:
|
||||
i_voices = np.array([1, 3, 7, 9])
|
||||
|
||||
for i_voice in i_voices:
|
||||
trial = {}
|
||||
trial["target"] = {}
|
||||
|
||||
trial["target"]["colour"], trial["target"][
|
||||
"colour_index"] = pick(options["target_corpus"]["colours"])
|
||||
number, trial["target"]["number_index"] = pick(
|
||||
options["target_corpus"]["numbers"])
|
||||
|
||||
trial["target"]["number"] = int(number)
|
||||
|
||||
trial["target"]["call_sign"] = options[
|
||||
"target_corpus_filemask"].split('_')[0]
|
||||
trial["target"]["sound_file"] = '{}_{}_{}.wav'.format(
|
||||
trial["target"]["call_sign"], trial["target"]["colour"],
|
||||
trial["target"]["number"])
|
||||
|
||||
trial["image"] = options["images"][0]
|
||||
|
||||
trial["voice"] = options["voices"]["v" + str(i_voice)]
|
||||
trial["voice"]["index"] = i_voice
|
||||
|
||||
trial["i_repeat"] = i_repeat
|
||||
trial["tmr"] = options["tmrs"][i_tmr]
|
||||
trial["visual_feedback"] = 1
|
||||
trial["done"] = 0
|
||||
|
||||
if 'trials' not in test:
|
||||
test["trials"] = [trial]
|
||||
else:
|
||||
test["trials"].append(trial)
|
||||
|
||||
np.random.shuffle(test["trials"])
|
||||
|
||||
training = {}
|
||||
i = 1
|
||||
for i_repeat in range(options["training"]["n_repeat"]):
|
||||
for i_voice in range(options["n_voices"]):
|
||||
|
||||
trial = {}
|
||||
trial["target"] = {}
|
||||
|
||||
trial["target"]["colour"], trial["target"]["colour_index"] = pick(
|
||||
options["target_corpus"]["colours"])
|
||||
number, trial["target"]["number_index"] = pick(
|
||||
options["target_corpus"]["numbers"])
|
||||
|
||||
trial["target"]["number"] = int(number)
|
||||
|
||||
trial["target"]["call_sign"] = options[
|
||||
"target_corpus_filemask"].split('_')[0]
|
||||
trial["target"]["sound_file"] = '{}_{}_{}.wav'.format(
|
||||
trial["target"]["call_sign"], trial["target"]["colour"],
|
||||
trial["target"]["number"])
|
||||
|
||||
trial["image"] = options["images"][0]
|
||||
|
||||
trial["voice"] = options["voices"]["v" + str(i_voice + 1)]
|
||||
trial["voice"]["index"] = i_voice
|
||||
|
||||
trial["i_repeat"] = i_repeat
|
||||
|
||||
if i <= 2:
|
||||
trial["tmr"] = np.inf
|
||||
else:
|
||||
trial["tmr"] = 6
|
||||
i += 1
|
||||
|
||||
trial["visual_feedback"] = 1
|
||||
trial["done"] = 0
|
||||
|
||||
if 'trials' not in training:
|
||||
training["trials"] = [trial]
|
||||
else:
|
||||
training["trials"].append(trial)
|
||||
|
||||
training_short = {}
|
||||
training_short["trials"] = training["trials"][:4]
|
||||
expe = {}
|
||||
expe["test"] = test
|
||||
expe["training"] = training_short
|
||||
|
||||
if "res_filename" in options:
|
||||
savemat(options["res_filename"],
|
||||
mdict={
|
||||
"expe": expe,
|
||||
"options": options
|
||||
})
|
||||
else:
|
||||
warnings.warn("The test file was not saved: no filename provided")
|
||||
|
||||
return expe, options
|
||||
@@ -0,0 +1,326 @@
|
||||
import os
|
||||
import sys
|
||||
from resampy import resample
|
||||
from scipy.signal import resample_poly
|
||||
import nnresample
|
||||
import soundfile as sf
|
||||
import numpy as np
|
||||
from pick import pick
|
||||
from pyworld import pyworld as pw
|
||||
from gender.cosgate import cosgate
|
||||
import scipy.io as spio
|
||||
from scipy import interpolate as spi
|
||||
from tools.load_matrix import loadmat
|
||||
|
||||
np.set_printoptions(threshold=sys.maxsize)
|
||||
|
||||
|
||||
def makeStim(options, trial, is_demo=False):
|
||||
# trial["target"]["sound_file"] = 'dog_green_8.wav'
|
||||
|
||||
print "Reading soundfile '{}' as target...\n".format(
|
||||
trial["target"]["sound_file"])
|
||||
|
||||
x, fs = sf.read(os.path.join(
|
||||
options["target_corpus_path"], trial["target"]["sound_file"]))
|
||||
|
||||
# if fs != options["fs"]:
|
||||
# x = resample(x, fs, options["fs"], filter='kaiser_fast')
|
||||
# fs = options["fs"]
|
||||
|
||||
x_rms = np.sqrt(np.mean(x**2))
|
||||
|
||||
options["reference_rms"] = x_rms
|
||||
|
||||
if trial["tmr"] < np.inf:
|
||||
x = (x / x_rms) * 10 ** (trial["tmr"]/20.0)
|
||||
else:
|
||||
x = x / x_rms
|
||||
|
||||
options["target_delay"] = 750e-3
|
||||
options["masker_end_delay"] = 250e-3
|
||||
|
||||
target = np.array([])
|
||||
|
||||
target = np.append(target, np.zeros(
|
||||
int(np.round(options["target_delay"] * fs))))
|
||||
target = np.append(target, x)
|
||||
target = np.append(target, np.zeros(
|
||||
int(np.round(options["masker_end_delay"] * fs))))
|
||||
|
||||
masker, masker_dict = create_masker(options, trial, len(target))
|
||||
|
||||
masker_rms = np.sqrt(np.nanmean(masker**2))
|
||||
if trial["tmr"] < np.inf:
|
||||
masker = masker / masker_rms
|
||||
else:
|
||||
masker = 0 * masker
|
||||
|
||||
z = np.add(target, masker)
|
||||
|
||||
z_rms = np.sqrt(np.nanmean(z ** 2))
|
||||
|
||||
z = z/z_rms * options["reference_rms"]
|
||||
|
||||
info = {}
|
||||
|
||||
info["masker"] = masker_dict
|
||||
|
||||
|
||||
return z, fs, info
|
||||
|
||||
|
||||
def create_masker(options, trial, n_samples):
|
||||
fs = options["fs"]
|
||||
|
||||
masker_dict = {}
|
||||
masker = np.array([])
|
||||
|
||||
n_chunk = 1
|
||||
|
||||
while len(masker) < n_samples:
|
||||
sound_file, _ = pick(options["masker_corpus"])
|
||||
# sound_file = 'cat_pink_6.wav'
|
||||
masker_dict["stim_" + str(n_chunk)] = {}
|
||||
masker_dict["stim_" + str(n_chunk)]["soundfile"] = sound_file
|
||||
|
||||
y, fs = pyworld_process(os.path.join(
|
||||
options["masker_corpus_path"], sound_file.strip()), trial["voice"]["dF0"], trial["voice"]["dVTL"], options)
|
||||
# y = y * np.power(10, -options["attenuation_dB"]/20.0)
|
||||
y = y * 10.0 ** (options["attenuation_dB"]/20)
|
||||
|
||||
chunk_duration = np.random.rand() * (options["masker_max_chunk_duration"] -
|
||||
options["masker_min_chunk_duration"]) + options["masker_min_chunk_duration"]
|
||||
chunk_duration = np.round(chunk_duration*fs)
|
||||
|
||||
chunk_start = np.random.randint(len(y)-chunk_duration)
|
||||
|
||||
chunk_ind = chunk_start + np.array([0, chunk_duration-1])
|
||||
masker_dict["stim_" + str(n_chunk)]["chunk_indices"] = chunk_ind
|
||||
|
||||
chunk = y[int(chunk_ind[0]):int(chunk_ind[1])]
|
||||
|
||||
chunk = cosgate(chunk, fs, options["masker_chunk_ramp"])
|
||||
|
||||
masker = np.append(masker, chunk)
|
||||
|
||||
n_chunk = n_chunk + 1
|
||||
|
||||
masker = masker[:n_samples]
|
||||
masker = cosgate(masker, fs, options["masker_ramp"])
|
||||
|
||||
return masker, masker_dict
|
||||
|
||||
|
||||
def pyworld_process(wavIn, dF0, dVTL, options):
|
||||
# dF0 = 0
|
||||
# dVTL = 0
|
||||
_, wavIn_file = os.path.split(wavIn)
|
||||
wavIn_name, _ = os.path.splitext(wavIn_file)
|
||||
cache_path = options["cache_path"]
|
||||
|
||||
wavOut = make_fname(wavIn, dF0, dVTL, cache_path)
|
||||
|
||||
if not os.path.exists(wavOut) or options["force_rebuild_straight_output"]:
|
||||
if not os.path.exists(cache_path):
|
||||
os.mkdir(cache_path)
|
||||
|
||||
mat = os.path.join(cache_path, wavIn_name + ".pyworld.mat")
|
||||
|
||||
f0 = []
|
||||
fs = 0
|
||||
sp = []
|
||||
ap = []
|
||||
x_rms = 0
|
||||
|
||||
if os.path.exists(mat):
|
||||
load_mat = loadmat(mat)
|
||||
f0 = load_mat['f0']
|
||||
fs = load_mat['fs']
|
||||
freq = load_mat['frequencies']
|
||||
sp = load_mat['sp']
|
||||
ap = load_mat['ap']
|
||||
t = load_mat['temporal_positions']
|
||||
x_rms = load_mat['x_rms']
|
||||
else:
|
||||
x, fs = sf.read(wavIn)
|
||||
|
||||
# if fs != options['fs']:
|
||||
# x = resample(x, fs, options["fs"], filter='kaiser_best')
|
||||
# fs = options["fs"]
|
||||
_f0, t = pw.dio(x, fs)
|
||||
|
||||
f0, sp, ap = pw.wav2world(x, fs)
|
||||
freq = np.arange(0, np.size(sp, axis=1),
|
||||
dtype='float64') / (np.size(sp)) * fs/2
|
||||
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
|
||||
# })
|
||||
|
||||
f0 = f0 * 2.0 ** (dF0/12)
|
||||
mapp = mapp * 2.0 ** -(dVTL/12)
|
||||
|
||||
f0 = f0 * mapp
|
||||
|
||||
nfft = (sp.shape[1]-1)*2
|
||||
f = np.arange(sp.shape[1]) / float(nfft) * float(fs)
|
||||
t = np.arange(sp.shape[0]) / pw.default_frame_period
|
||||
|
||||
sp = Fast2DInterp(t, f, sp, type="cubic")(t, f)
|
||||
ap = Fast2DInterp(t, f, ap, type="cubic")(t, f)
|
||||
|
||||
# sp = sp_ap_creation(sp, t, f, mapp)
|
||||
# ap = sp_ap_creation(ap, t, f, mapp)
|
||||
# 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)
|
||||
f0, sp, ap = regularize_arrays(f0, sp, ap)
|
||||
y_mat = pw.synthesize(f0, sp, ap, fs)
|
||||
|
||||
y = np.array(y_mat)
|
||||
|
||||
y = y / np.sqrt(np.mean(y ** 2)) * x_rms
|
||||
|
||||
my = np.amax(np.absolute(y))
|
||||
|
||||
if np.amax(np.absolute(y)) > 1:
|
||||
# expe_logger.warn("Output was normalised for {}".format(wavOut))
|
||||
y_magnitude_factor = my/0.98
|
||||
y = 0.98 * y / np.amax(np.absolute(y))
|
||||
else:
|
||||
y_magnitude_factor = 1.0
|
||||
|
||||
sf.write(wavOut, y, fs)
|
||||
|
||||
else:
|
||||
y, fs = sf.read(wavOut)
|
||||
|
||||
return y, fs
|
||||
|
||||
|
||||
def make_fname(wav, f0, vtl, destPath):
|
||||
_, namext = os.path.split(wav)
|
||||
name, ext = os.path.splitext(namext)
|
||||
|
||||
fname = "{}_dF0{}_dVTL{}{}".format(name, f0, vtl, ext)
|
||||
fname = os.path.join(destPath, fname)
|
||||
|
||||
return fname
|
||||
|
||||
|
||||
def sp_ap_creation(mat, temp, freq, vtl, type='cubic'):
|
||||
'''
|
||||
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)
|
||||
|
||||
if type == 'cubic':
|
||||
f = spi.RectBivariateSpline(temp, freq, mat)
|
||||
elif type == 'linear':
|
||||
f = spi.interp2d(freq, temp, mat, kind='linear')
|
||||
else:
|
||||
raise ValueError('Interpolant type unknown: "%s"' % type)
|
||||
|
||||
if vtl != 0.0:
|
||||
interp = f(temp, freq.T/vtl)
|
||||
else:
|
||||
interp = f(temp, freq.T/1.0)
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def regularize_arrays(*args):
|
||||
"""
|
||||
Making sure the arrays passed as arguments are in the right format for pyworld.
|
||||
"""
|
||||
out = list()
|
||||
for x in args:
|
||||
out.append(np.require(x, requirements='C'))
|
||||
return tuple(out)
|
||||
|
||||
|
||||
class Fast2DInterp():
|
||||
"""
|
||||
Creates an interpolant object based on ``scipy.interpolate.RectBivariateSpline`` but
|
||||
dealing with out of range values.
|
||||
The constructor is: ``Fast2DInterp(x, y, z, ofrv=None)`` where ``x`` and ``y``
|
||||
are 1D arrays and ``z`` is a 2D array. The optional argument ``ofrv`` defines
|
||||
the value used for out of range inputs. If ``ofrv`` is ``None``, then the
|
||||
default behaviour of ``RectBivariateSpline`` is kept, i.e. the closest value is
|
||||
returned.
|
||||
The default type is ``linear``, which then makes use of ``scipy.interpolate.interp2d``.
|
||||
With ``cubic``, the ``RectBivariateSpline`` is used.
|
||||
Note that the class is not so useful in the end when used with ``linear``, but
|
||||
is useful if you want to use cubic-splines.
|
||||
"""
|
||||
|
||||
def __init__(self, x, y, z, ofrv=None, type='linear'):
|
||||
self.type = type
|
||||
|
||||
if self.type == 'cubic':
|
||||
self.interpolant = spi.RectBivariateSpline(x, y, z)
|
||||
elif self.type == 'linear':
|
||||
self.interpolant = spi.interp2d(y, x, z, kind='linear')
|
||||
else:
|
||||
raise ValueError('Interpolant type unknown: "%s"' % type)
|
||||
|
||||
self.x_range = (x[0], x[-1])
|
||||
self.y_range = (y[0], y[-1])
|
||||
|
||||
# Out of range value:
|
||||
self.ofrv = ofrv
|
||||
|
||||
def is_in_range(self, w, r):
|
||||
return np.logical_and(w >= r[0], w <= r[1])
|
||||
|
||||
def __call__(self, x, y):
|
||||
return self.interp(x, y)
|
||||
|
||||
def interp_(self, x, y):
|
||||
if self.type == 'cubic':
|
||||
return self.interpolant(x, y)
|
||||
elif self.type == 'linear':
|
||||
return self.interpolant(y, x)
|
||||
|
||||
def interp(self, x, y):
|
||||
if (np.isscalar(x) or len(x) == 1) and (np.isscalar(y) or len(y) == 1):
|
||||
if self.ofrv is not None:
|
||||
if self.is_in_range(x, self.x_range) and self.is_in_range(y, self.y_range):
|
||||
o = self.interp_(x, y)[0, 0]
|
||||
else:
|
||||
o = self.ofrv
|
||||
else:
|
||||
o = self.interp_(x, y)[0, 0]
|
||||
else:
|
||||
o = self.interp_(x, y)
|
||||
|
||||
if self.ofrv is not None:
|
||||
s = np.logical_and(self.is_in_range(
|
||||
xx, self.x_range), self.is_in_range(yy, self.y_range))
|
||||
o[s] = self.ofrv
|
||||
|
||||
return o
|
||||
@@ -0,0 +1,18 @@
|
||||
import os
|
||||
|
||||
|
||||
def expe_options(options):
|
||||
|
||||
options["result_path"] = "./results/" + options["subject_name"]
|
||||
|
||||
if not os.path.exists(options["result_path"]):
|
||||
os.mkdir(options["result_path"])
|
||||
|
||||
options["result_prefix"] = "crm_"
|
||||
|
||||
options["experiment_label"] = "PICKA :: CRM"
|
||||
|
||||
options["force_rebuild_straight_output"] = False
|
||||
options["experiment_begin"] = 1
|
||||
|
||||
return options
|
||||
@@ -0,0 +1,219 @@
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
import time
|
||||
import datetime
|
||||
import sys
|
||||
import os
|
||||
import cPickle as pickle
|
||||
from tools.load_matrix import loadmat
|
||||
from scipy.io import savemat
|
||||
from Robot.RobotCRM import RobotCRM
|
||||
from crm_make_stimulus import makeStim
|
||||
|
||||
|
||||
def robot(ip, port, lang, options, phase):
|
||||
results = {}
|
||||
sam = RobotCRM(ip, port, lang, options["subject_name"])
|
||||
try:
|
||||
saveFromPickle(options)
|
||||
except IOError:
|
||||
pass
|
||||
mat = loadmat(options["res_filename"])
|
||||
expe = mat["expe"]
|
||||
options = mat["options"]
|
||||
if "results" in mat:
|
||||
results = mat["results"]
|
||||
|
||||
track = loadmat(options["res_tracker"])
|
||||
exp = track["tracker"]
|
||||
|
||||
nbreak = 0
|
||||
starting = 1
|
||||
|
||||
simulate = False
|
||||
|
||||
done = []
|
||||
while np.mean(done) != 1:
|
||||
done = []
|
||||
for i in range(len(expe[phase]["trials"])):
|
||||
done.append(expe[phase]["trials"][i]["done"])
|
||||
nbreak += 1
|
||||
if nbreak > options[phase]["block_size"]:
|
||||
nbreak = 0
|
||||
# TODO: Something to add a break.
|
||||
try:
|
||||
i_trial = done.index(0)
|
||||
except ValueError:
|
||||
break
|
||||
track_trial = i_trial + 1
|
||||
if exp["experiment_begin"]:
|
||||
trials = {
|
||||
"current_trial": track_trial,
|
||||
"total_trials": len(expe[phase]["trials"])
|
||||
}
|
||||
with open('./crm/trials.p', 'wb') as f:
|
||||
pickle.dump(trials, f)
|
||||
time.sleep(5)
|
||||
# sam.intro()
|
||||
exp["experiment_begin"] = 0
|
||||
savemat(options["res_tracker"], mdict={"tracker": exp})
|
||||
if starting:
|
||||
trials = {
|
||||
"current_trial": track_trial,
|
||||
"total_trials": len(expe[phase]["trials"])
|
||||
}
|
||||
with open('./crm/trials.p', 'wb') as f:
|
||||
pickle.dump(trials, f)
|
||||
if phase == "test":
|
||||
if lang == "EN":
|
||||
sam.simple_say("Welcome to the testing phase of the game.")
|
||||
elif lang == "NL":
|
||||
sam.simple_say(
|
||||
"Welkom bij de testronde van dit spelletje.")
|
||||
else:
|
||||
# sam.crmIntro()
|
||||
pass
|
||||
# sam.crmIntro()
|
||||
sam.game_break()
|
||||
|
||||
if phase == "test" and i_trial == np.round(len(done) / 2):
|
||||
if lang == "EN":
|
||||
sam.simple_say("You've reached halfway.")
|
||||
if lang == "NL":
|
||||
sam.simple_say("")
|
||||
sam.take_break()
|
||||
|
||||
starting = 0
|
||||
|
||||
# for i in range(len(expe[phase]["trials"])):
|
||||
# done.append(expe[phase]["trials"][i]["done"])
|
||||
# nbreak += 1
|
||||
# if nbreak > options[phase]["block_size"]:
|
||||
# nbreak = 0
|
||||
# # TODO: Something to add a break.
|
||||
|
||||
# try:
|
||||
# i_trial = done.index(0)
|
||||
# except ValueError:
|
||||
# break
|
||||
|
||||
trial = expe[phase]["trials"][i_trial]
|
||||
|
||||
xOut, fs, info = makeStim(options, trial)
|
||||
|
||||
# xOut = xOut*np.power(10, options["attenuation_dB"]/20)
|
||||
xOut = xOut * 10.0**(options["attenuation_dB"] / 20)
|
||||
|
||||
m = np.max(np.abs(xOut))
|
||||
|
||||
if m > .98:
|
||||
xOut = xOut / m * .98
|
||||
print "xOut was rescaled to avoid clipping by a factor %.2f" % (
|
||||
0.98 / m)
|
||||
sf.write('stimulus.wav', xOut, fs)
|
||||
correct_answer = {
|
||||
"colour": trial["target"]["colour"],
|
||||
"number": trial["target"]["number"]
|
||||
}
|
||||
# === Play stimulus then delete file
|
||||
sam.aad.setOutputVolume(sam.stimulus_volume)
|
||||
sam.play_sounds('stimulus.wav', lang)
|
||||
sam.aad.setOutputVolume(sam.speaking_volume)
|
||||
|
||||
# os.remove('stimulus.wav)
|
||||
|
||||
# === Get response
|
||||
|
||||
response = {}
|
||||
|
||||
response["timestamp"] = str(datetime.datetime.now())
|
||||
if not simulate:
|
||||
resp, resp_time = sam.answer(correct_answer,
|
||||
trial["visual_feedback"], track_trial,
|
||||
len(expe[phase]["trials"]))
|
||||
|
||||
else:
|
||||
resp = {"number": 4, "colour": "pink"}
|
||||
resp_time = 1.0
|
||||
response["response_time(ms)"] = round(resp_time * 100, 2)
|
||||
# resp = correct_answer
|
||||
response["colour"] = resp["colour"]
|
||||
response["number"] = resp["number"]
|
||||
response["correct"] = response["colour"] == correct_answer[
|
||||
"colour"] and response["number"] == correct_answer["number"]
|
||||
response["info"] = info
|
||||
response["trial"] = trial
|
||||
|
||||
# === Save results
|
||||
if not phase in results:
|
||||
results[phase] = {}
|
||||
results[phase]["responses"] = np.array([response])
|
||||
else:
|
||||
results[phase]["responses"] = np.append(
|
||||
results[phase]["responses"], response)
|
||||
|
||||
expe[phase]["trials"][i_trial]["done"] = 1
|
||||
a = time.time()
|
||||
|
||||
pickle.dump(
|
||||
expe, open("{}/expe_temp.p".format(options["result_path"]), 'wb'))
|
||||
pickle.dump(
|
||||
options,
|
||||
open("{}/options_temp.p".format(options["result_path"]), 'wb'))
|
||||
pickle.dump(
|
||||
results,
|
||||
open("{}/results_temp.p".format(options["result_path"]), 'wb'))
|
||||
|
||||
print "results saved: " + str(time.time() - a)
|
||||
|
||||
if phase == "training":
|
||||
if lang == "EN":
|
||||
sam.simple_say("That's the end of the training phase.")
|
||||
elif lang == "NL":
|
||||
sam.simple_say("Dit is het einde van de oefenronde ")
|
||||
else:
|
||||
exp["experiments"]["crm"] = 1
|
||||
savemat(options["res_tracker"], mdict={"tracker": exp})
|
||||
if lang == "EN":
|
||||
sam.simple_say("That's the end of the testing phase. Well done.")
|
||||
elif lang == "NL":
|
||||
sam.simple_say("Dit is het einde van de test. Goed gedaan.")
|
||||
exp_tracker = np.array(
|
||||
[exp["experiments"][key] for key in exp["experiments"].keys()])
|
||||
|
||||
saveFromPickle(options)
|
||||
|
||||
if np.mean(exp_tracker) == 1:
|
||||
sam.ending()
|
||||
|
||||
# except:
|
||||
# saveFromPickle(options)
|
||||
# savemat(options["res_filename"], mdict={
|
||||
# "expe": expe, "options": opt, "results": results})
|
||||
|
||||
|
||||
def saveFromPickle(options):
|
||||
print "-------"
|
||||
print "Loading results"
|
||||
print "-------"
|
||||
try:
|
||||
expe = pickle.load(
|
||||
open("{}/expe_temp.p".format(options["result_path"]), 'rb'))
|
||||
opt = pickle.load(
|
||||
open("{}/options_temp.p".format(options["result_path"]), 'rb'))
|
||||
results = pickle.load(
|
||||
open("{}/results_temp.p".format(options["result_path"]), 'rb'))
|
||||
|
||||
os.remove("{}/expe_temp.p".format(options["result_path"]))
|
||||
os.remove("{}/options_temp.p".format(options["result_path"]))
|
||||
os.remove("{}/results_temp.p".format(options["result_path"]))
|
||||
savemat(options["res_filename"],
|
||||
mdict={
|
||||
"expe": expe,
|
||||
"options": opt,
|
||||
"results": results
|
||||
})
|
||||
except Exception as e:
|
||||
print e
|
||||
|
||||
return
|
||||
@@ -0,0 +1,42 @@
|
||||
import os
|
||||
from crm_options import expe_options as crmOptions
|
||||
from scipy.io import savemat
|
||||
from crm_robot import robot
|
||||
from crm_build_conditions import expe_build_conditions as buildConditions
|
||||
from tools.load_matrix import loadmat
|
||||
|
||||
|
||||
def main(options, subject, phase, lang, p_exists, ip, port):
|
||||
options = {}
|
||||
options["subject_name"] = subject
|
||||
options = crmOptions(options)
|
||||
|
||||
options["language"] = lang
|
||||
|
||||
res_filename = os.path.join(options["result_path"], '{}{}_{}_robot.mat'.format(
|
||||
options["result_prefix"], lang.lower(), subject))
|
||||
options["res_filename"] = res_filename
|
||||
|
||||
res_tracker = os.path.join(
|
||||
options["result_path"], '{}_tracker.mat'.format(subject))
|
||||
options["res_tracker"] = res_tracker
|
||||
if not os.path.exists(res_tracker):
|
||||
track = {}
|
||||
track["experiment_begin"] = 1
|
||||
|
||||
track["experiments"] = {}
|
||||
track["experiments"]["fishy"] = 0
|
||||
track["experiments"]["gender"] = 0
|
||||
track["experiments"]["emotion"] = 0
|
||||
track["experiments"]["crm"] = 0
|
||||
|
||||
savemat(res_tracker, mdict={"tracker": track})
|
||||
|
||||
if not os.path.exists(res_filename):
|
||||
expe, options = buildConditions(options)
|
||||
else:
|
||||
mat = loadmat(options["res_filename"])
|
||||
expe = mat["expe"]
|
||||
options = mat["options"]
|
||||
|
||||
robot(ip, port, lang, options, phase)
|
||||
@@ -0,0 +1,28 @@
|
||||
import os
|
||||
import numpy as np
|
||||
|
||||
|
||||
def parseCorpus(folder, filemask):
|
||||
|
||||
lst = [f for f in os.listdir(
|
||||
folder) if f.startswith(filemask.split('_')[0])]
|
||||
call_signs = []
|
||||
colours = []
|
||||
numbers = []
|
||||
|
||||
for i in range(len(lst)):
|
||||
_, filename = os.path.split(lst[i])
|
||||
f, _ = os.path.splitext(filename)
|
||||
|
||||
parts = f.split('_')
|
||||
|
||||
call_signs.append(parts[0])
|
||||
colours.append(parts[1])
|
||||
numbers.append(int(parts[2]))
|
||||
|
||||
corpus = {}
|
||||
corpus["call_signs"] = np.unique(call_signs)
|
||||
corpus["colours"] = np.unique(colours)
|
||||
corpus["numbers"] = np.unique(numbers)
|
||||
|
||||
return corpus
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import numpy as np
|
||||
|
||||
|
||||
def pick(lst):
|
||||
if len(locals()) < 2:
|
||||
n = 1
|
||||
|
||||
lst = np.array(lst)
|
||||
# i = np.random.permutation(len(lst))
|
||||
i = np.random.randint(len(lst))
|
||||
|
||||
k = lst[i]
|
||||
|
||||
return k, i
|
||||
@@ -0,0 +1,50 @@
|
||||
import os
|
||||
import numpy as np
|
||||
from crm_options import expe_options as crmOptions
|
||||
from crm_build_conditions import expe_build_conditions as buildConditions
|
||||
from crm_make_stimulus import pyworld_process
|
||||
|
||||
|
||||
def preprocess(mode, language, force):
|
||||
options = {}
|
||||
options["language"] = language
|
||||
options["subject_name"] = ""
|
||||
options = crmOptions(options)
|
||||
|
||||
expe, options = buildConditions(options)
|
||||
|
||||
options["force_rebuild_pyworld_output"] = force
|
||||
|
||||
print "=== Analysing all masker files ==="
|
||||
|
||||
for i in range(len(options["masker_corpus"])):
|
||||
fname = options["masker_corpus"][i]
|
||||
fname = os.path.join(options["masker_corpus_path"], fname)
|
||||
print "%02d/%d Analysing '%s' \n" % (i + 1,
|
||||
len(options["masker_corpus"]), fname)
|
||||
for j in range(1, len(options["voices"]) + 1):
|
||||
|
||||
voice = options["voices"]["v" + str(j)]
|
||||
pyworld_process(fname, voice["dF0"], voice["dVTL"], options)
|
||||
|
||||
if mode == "all":
|
||||
print "=== Synthesizing for all masker files ==="
|
||||
trials = expe["training"]["trials"] + expe["test"]["trials"]
|
||||
|
||||
k = 1
|
||||
|
||||
for i in range(len(trials)):
|
||||
trial = trials[i]
|
||||
|
||||
for j in range(len(options["masker_corpus"])):
|
||||
fname = options["masker_corpus"][j]
|
||||
fname = os.path.join(
|
||||
options["masker_corpus_path"], fname)
|
||||
print "%04d/%d Synthesizing'%s' for dF0=%.2f st, dVTL=%.2f st\n" % (k, len(trials) * len(
|
||||
options["masker_corpus"]), fname, trial["voice"]["dF0"], trial["voice"]["dVTL"])
|
||||
pyworld_process(
|
||||
fname, trial["voice"]["dF0"], trial["voice"]["dVTL"], options)
|
||||
|
||||
k += 1
|
||||
|
||||
print "\n"
|
||||
Reference in new issue
Block a user