Initial commit

This commit is contained in:
Kasiaaaaaa committed 2026-09-22 11:52:03 +02:00
commit d89b82be4a
103 files changed
+23110

No files matched your search

View File
Whitespace-only changes.
+327
View File
@@ -0,0 +1,327 @@
# --------------------------------------------------------------------------
# Authors:
# ------ MATlAB ------
# 2010-03-15: 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-01-28: 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 expe_options import expe_options
from collections import OrderedDict
import warnings
import scipy.io as sio
import cPickle
import random
import numpy as np
import glob
import os
from tools.load_matrix import loadmat
def expe_build_conditions(options):
'''
This function creates the list of conditions that will be tested in the
experiment.
Without argument, it just returns the `expe` structure as well as the
list of `options`.
With an option argument that contains a `res_filename` field, it saves
them in a result file.
Modify the "Build test block" section to change which conditions are to
be stested.
WARNING: Once saved in a result file, the conditions are not modified
anymore at runtime even if the code is modified. This is done on purpose
so that we always know what were the options used for a specific
experimental session.
'''
# If all syllables need to be rebuilt (overwrites cached files)
FORCE_REBUIL_SYLLS = 0
# --- GUI options ---
options["instructions"] = {}
options["instructions"]["training"] = "You are going to hear three triplets of different syllables. \n" +\
"One of the triplets is said with a different voice. \n" +\
"Your task is to click on the button that corresponds to the different voice. \n"
options["instructions"]["test"] = options["instructions"]["training"]
# --- Signal options ---
options["fs"] = 44100
# options["attenuation_dB"] = 27 # General attenuation
mat = loadmat('./calibration.mat')
cal = mat["calibration"]
options["attenuation_dB"] = cal["fishy"] # Calibrated attenuation
options["ear"] = "both" # right, left, or both
# --- Design specifications ---
options["test"] = {}
options["test"]["n_repeat"] = 1 # Number of repetition per condition
options["test"]["step_size_modifier"] = 1/np.sqrt(2)
# When difference <= to this times the step-size, decrease the step size
options["test"]["change_step_size_condition"] = 2
# Change step-size every n trials
options["test"]["change_step_size_n_trials"] = 15
options["test"]["initial_step_size"] = 2 # Semitones
options["test"]["starting_difference"] = 12 # Semitones
options["test"]["down_up"] = np.array([2, 1]) # 2-down, 1-up => 70.7%
options["test"]["terminate_on_n_turns"] = 8
options["test"]["terminate_on_n_trials"] = 100
options["test"]["retry"] = 1 # number of retries if measure failed
options["test"]["threshold_on_last_n_trials"] = 6
options["training"] = {}
options["training"]["n_repeat"] = 1 # Number of repetition per condition
options["training"]["step_size_modifier"] = 1
# When difference <= to this times the step-size, decrease the step size
options["training"]["change_step_size_condition"] = 1
# Change step-size every n trials
options["training"]["change_step_size_n_trials"] = 15
options["training"]["initial_step_size"] = 3 # Semitones
options["training"]["starting_difference"] = 6 # Semitones
options["training"]["down_up"] = np.array([2, 1]) # 2-down, 1-up => 70.7%
options["training"]["terminate_on_n_turns"] = 0
options["training"]["terminate_on_n_trials"] = 6
options["training"]["retry"] = 0 # number of retries if measure failed
options["training"]["threshold_on_last_n_trials"] = 5
# --- Stimuli options ---
ref_f0 = 242.0 # This is the average pitch of the original voice
options["ref_f0"] = ref_f0
options["test"]["voices"] = {}
options["test"]["voices"]["v1"] = {}
options["test"]["voices"]["v1"]["label"] = 'female'
options["test"]["voices"]["v1"]["f0"] = ref_f0
options["test"]["voices"]["v1"]["ser"] = 1.0
options["test"]["voices"]["v2"] = {}
options["test"]["voices"]["v2"]["label"] = 'male'
options["test"]["voices"]["v2"]["f0"] = ref_f0/2.0
options["test"]["voices"]["v2"]["ser"] = 1 * np.power(2, -3.8/12)
options["test"]["voices"]["v3"] = {}
options["test"]["voices"]["v3"]["label"] = 'child'
options["test"]["voices"]["v3"]["f0"] = round(ref_f0*np.power(2, 5.0/12))
options["test"]["voices"]["v3"]["ser"] = 1 * np.power(2, 7.0/12)
options["test"]["voices"]["v4"] = {}
options["test"]["voices"]["v4"]["label"] = 'male-gpr'
options["test"]["voices"]["v4"]["f0"] = ref_f0/2.0
options["test"]["voices"]["v4"]["ser"] = 1.0
options["test"]["voices"]["v5"] = {}
options["test"]["voices"]["v5"]["label"] = 'male-vtl'
options["test"]["voices"]["v5"]["f0"] = options["test"]["voices"]["v1"]["f0"]
options["test"]["voices"]["v5"]["ser"] = 1 * np.power(2, -3.8/12)
options["test"]["voices"]["v6"] = {}
options["test"]["voices"]["v6"]["label"] = 'child-gpr'
options["test"]["voices"]["v6"]["f0"] = round(ref_f0*np.power(2, 5.0/12))
options["test"]["voices"]["v6"]["ser"] = 1.0
options["test"]["voices"]["v7"] = {}
options["test"]["voices"]["v7"]["label"] = 'child-vtl'
options["test"]["voices"]["v7"]["f0"] = options["test"]["voices"]["v1"]["f0"]
options["test"]["voices"]["v7"]["ser"] = 1 * np.power(2, 7.0/12)
options["training"]["voices"] = options["test"]["voices"]
# -- Voice pairing choices
# 1 2 : female -> Male
# 1 4 : Female -> Male GPR
# 1 5 : Female -> Male VTL
# 1 3 : Female -> Child
# 1 6 : Female -> Child GPR
# 1 7 : Female -> Child VTL
options["test"]["voice_pairs"] = np.matrix('1 4; 1 5; 1 6; 1 7')
options["training"]["voice_pairs"] = np.matrix('1 2; 1 3')
if options["language"] == "EN":
options["sound_path"] = './stimuli/fishy/en'
options["sound_path_store"] = './stimuli_store/en'
options["tmp_path"] = './tmp/en'
elif options["language"] == "NL":
options["sound_path"] = './stimuli/fishy/nl'
options["sound_path_store"] = './stimuli_store/nl'
options["tmp_path"] = './tmp/nl'
if not os.path.exists(options["tmp_path"]):
os.mkdir(options["tmp_path"])
if not os.path.exists(options["sound_path_store"]):
os.mkdir(options["sound_path_store"])
syllable_list = []
dir_waves = [f for f in os.listdir(
options["sound_path"]) if f.endswith(".wav")]
for file in dir_waves:
if file.endswith(".wav"):
syllable_list.append(file)
for i in range(len(syllable_list)):
syllable_list[i] = syllable_list[i].replace('.wav', '')
options["syllables"] = np.array(syllable_list)
options["sounds_for_calibration"] = []
for f in range(len(dir_waves)):
options["sounds_for_calibration"].append(
os.path.join(options["sound_path"], dir_waves[f]))
options["n_syll"] = 3
options["inter_syllable_silence"] = 50.0e-3
options["syllable_duration"] = 200.0e-3
options["f0_contour_step_size"] = 1.0/3.0 # semitones
# options["f0_contours"] = np.array([[-1, 0, +1], [+1, 0, -1], np.add([-1.0, 1.0, -1.0], 1.0/3), np.subtract([1, -1, 1], 1.0/3), np.add(
# [-1, -1, 1], 1.0/3), np.subtract([1, 1, -1], 1.0/3), np.subtract([-1, 1, 1], 1.0/3), np.add([1, -1, -1], 1.0/3)])
options["f0_contours"] = np.array([[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [
1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])
options["inter_triplet_interval"] = 250.0e-3
options["force_rebuild_sylls"] = FORCE_REBUIL_SYLLS
# --- Vocoder options ---
# Base Parameters
p = {}
p["envelope"] = {}
p["envelope"]["method"] = 'low-pass'
p["envelope"]["rectify"] = 'half-wave'
p["envelope"]["order"] = 2
p["synth"] = {}
p["synth"]["carrier"] = 'noise'
p["synth"]["filter_before"] = False
p["synth"]["filter_after"] = True
p["synth"]["f0"] = 1.0
options["vocoder"] = {}
options["vocoder"]['v1'] = {}
options["vocoder"]['v1']["label"] = 'noise'
options["vocoder"]['v1']["description"] = 'Noise-band vocoder, 6 bands from 1250 to 7000, envelope cutoff defined per band.'
options["vocoder"]['v1']["parameters"] = p
options["vocoder"]['v2'] = {}
options["vocoder"]['v2']["label"] = 'sin'
options["vocoder"]['v2']["description"] = 'Sinewave vocoder, 6 bands from 1250 to 7000, envelope cutoff defined per band, not refiltered after modulation.'
options["vocoder"]['v2']["parameters"] = p
options["vocoder"]['v2']["parameters"]["synth"]["carrier"] = 'sin'
options["vocoder"]['v2']["parameters"]["synth"]["filter_after"] = False
options["vocoder"]['v3'] = {}
options["vocoder"]['v3']["label"] = 'lownoise'
options["vocoder"]['v3']["description"] = 'Low-noise-noise-band vocoder, 6 bands from 1250 to 7000, envelope cutoff defined per band.'
options["vocoder"]['v3']["parameters"] = p
options["vocoder"]['v3']["parameters"]["synth"]["carrier"] = 'low-noise'
options["vocoder"]["v4"] = {}
options["vocoder"]['v4']["label"] = 'pshc'
options["vocoder"]['v4']["description"] = 'PSHC vocoder, 6 bands from 1250 to 7000, envelope cutoff defined per band.'
options["vocoder"]['v4']["parameters"] = p
options["vocoder"]['v4']["parameters"]["synth"]["carrier"] = 'pshc'
# === Build test block ===
test = {}
# def update(d1, d2):
# for k, v in d2.items():
# if k in d1 and isinstance(v, dict) and isinstance(d1[k], dict):
# update(d1[k], v)
# else:
# d1[k] = v
m, _ = options["test"]["voice_pairs"].shape
for ir in range(options["test"]["n_repeat"]):
for i_vp in range(m): # iterate for each row in voice_pairs
condition = {}
condition["ref_voice"] = options["test"]["voice_pairs"][i_vp, 0]
condition["dir_voice"] = options["test"]["voice_pairs"][i_vp, 1]
condition["visual_feedback"] = 1.0
condition["sound_feedback"] = 1.0
# Should not be removed
condition["i_repeat"] = ir
condition["done"] = 0
condition["attempts"] = 0
if not "conditions" in test:
test["conditions"] = [condition]
else:
test["conditions"].append(condition)
# items = test["conditions"].items()
test["conditions"] = random.sample(
test["conditions"], len(test["conditions"]))
# === Build training block ===
training = {}
m, _ = options["training"]["voice_pairs"].shape
for ir in range(options["training"]["n_repeat"]):
for i_vp in range(m): # iterate for each row in voice_pairs
condition = {}
condition["ref_voice"] = options["training"]["voice_pairs"][i_vp, 0]
condition["dir_voice"] = options["training"]["voice_pairs"][i_vp, 1]
condition["visual_feedback"] = 1.0
condition["sound_feedback"] = 1.0
# Should not be removed
condition["i_repeat"] = ir
condition["done"] = 0
condition["attempts"] = 0
if not "conditions" in training:
training["conditions"] = [condition]
else:
training["conditions"].append(condition)
# items = test["conditions"].items()
# Randomise the order of the conditions
training["conditions"] = random.sample(
training["conditions"], len(training["conditions"]))
# === Create expe dictionary and save .mat file ===
expe = {}
expe["test"] = test
expe["training"] = training
if "res_filename" in options:
# with open(options["res_filename"], 'w') as f:
# cPickle.dump([options, expe, p], f)
sio.savemat(options["res_filename"], mdict={
'expe': expe, 'options': options, 'p': p})
else:
warnings.warn("The test file was not saved: no filename provided.")
return expe, options
+339
View File
@@ -0,0 +1,339 @@
# --------------------------------------------------------------------------
# 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)
+46
View File
@@ -0,0 +1,46 @@
# --------------------------------------------------------------------------
# Authors:
# ------ MATlAB ------
# 2017-03-29: Etienne Gaudrain <etienne.gaudrain@cnrs.fr>
# ------ Python ------
# 2020-01-27: 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/>.
# --------------------------------------------------------------------------
import os
def expe_options(options):
'''Defines the basic options'''
options["result_path"] = "./results/" + options["subject_name"]
options["result_prefix"] = 'jnd_'
options["logs_path"] = './logs/fishy'
options["log_file"] = os.path.join(options["result_path"], 'status.txt')
# DELETE Relevant paths, but may not be necessary
options["path"] = {}
options["path"]["straight"] = 'straight'
options["path"]["sqlite"] = 'sqlite'
options["path"]["vocoder"] = 'vocoder'
options["path"]["audio"] = 'audiotsm'
options["experiment_begin"] = 1
return options
+924
View File
@@ -0,0 +1,924 @@
# --------------------------------------------------------------------------
# Authors:
# ------ MATlAB ------
# 2013-02-24: Etienne Gaudrain <e.p.c.gaudrain@rug.nl>
# 2017-03-29: Etienne Gaudrain <etienne.gaudrain@cnrs.fr>
# ------ Python ------
# 2020-01-28: 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/>.
# --------------------------------------------------------------------------
# ----- System packages
import sys
import os
import warnings
import datetime
import pickle
import random
import time
import logging
from collections import OrderedDict
# ----- Third party packages
import numpy as np
# import matplotlib.pyplot as plt
import soundfile as sf
import scipy.io as sio
# from matplotlib.animation import FuncAnimation
from naoqi import ALBroker
# ----- File imports
from Robot.RobotFishy import RobotFishy
import tools.settings as settings
from tools.exit_condition import ExitExperimentModule
from expe_make_stim import expe_make_stim
from tools.load_matrix import loadmat
# Ignores division and invalid warnings sent to the console
np.seterr(divide='ignore', invalid='ignore')
# Global variables that assit in live tracking the responses in each trial
global PLT_CLOSED
global FIG
global AX1
PLT_CLOSED = True
# --- Create a log file
def expe_robot(ip, port, lang, options, phase, subject):
global PLT_CLOSED
if os.path.exists("{}/thresholds_temp.p".format(options["result_path"])):
print "Checking previous save data"
saveFromPickle(options)
# -- Start an instance of SAM
sam = type('', (), {})()
create_sam = True
if create_sam:
sam = RobotFishy(ip, port, lang, subject)
# -- Set initial volume
# print 'Connected to SAM'
ave_time = np.array([])
# gen_logger = logging.getLogger("gen_logger")
expe_logger = logging.getLogger("expe_logger")
time_logger = logging.getLogger("time_logger")
halfWay = [
"\\vct=110\\You're about halfway. Keep going!\\vct=100\\",
"\\vct=110\\You've reached the halfway point. Great!\\vct=100\\",
"\\vct=110\\Half down, half to go!\\vct=100\\"
]
threeQuarters = [
"\\vct=110\\You're almost done!\\vct=100\\",
"\\vct=110\\Just a few more left!\\vct=100\\",
"\\vct=110\\You're nearing the end!\\vct=100\\"
]
# with open(options["res_filename"], 'r') as f:
# options, expe, p = pickle.load(f)
# -- Load the .mat file
mat_contents = loadmat(options["res_filename"])
expe = mat_contents['expe']
options = mat_contents['options']
try:
results = mat_contents['results']
except KeyError:
# Create a new results dictionary if one is not found or this is a new subject
results = {}
try:
thresholds_dict = mat_contents["thresholds"]
except KeyError:
thresholds_dict = OrderedDict()
p = mat_contents['p']
track = loadmat(options["res_tracker"])
exp = track["tracker"]
starting = 1
# SIMUL = 0 - Run the experiment with a participant
# SIMUL = 1 - Autonomously mimick step process
# SIMUL = 2 - Always give correct answer
# SIMUL = 3 - Always give random answer
SIMUL = 0
DEBUG = 1
PILOT = 3
PRESENT = 1
terminate = 0
beginning_of_session = datetime.datetime.now()
# Intialise the done array to store if a task has been completed
done = []
pilot = 0
# === Main Loop that runs experiment ===
while np.mean(done) != 1:
# while pilot < PILOT:
pilot += 1
# Reintialises the done array and reappend for when a task has been completed
done = []
for i in range(len(expe[phase]["conditions"])):
done.append(expe[phase]["conditions"][i]["done"])
# If this is the beginning of the test, Sam introduces the experiment and what to do
if options["instructions"][
phase] and starting and phase == "training" and exp[
"experiment_begin"]:
try:
sam.intro()
except AttributeError:
pass
exp["experiment_begin"] = 0
sio.savemat(options["res_tracker"], mdict={"tracker": exp})
pass
if starting:
try:
if phase == "test":
sam.simple_say("Welcome to the testing phase of the game.")
pass
else:
sam.fishyIntro()
pass
pass
sam.game_break()
except AttributeError:
pass
starting = 0
# Find the next task that has not yet been completed
try:
i_condition = done.index(0)
# i_condition = 7
except ValueError:
break
expe_logger.info(
"\n=============== Testing condition {} / {} ============\n\n".
format(i_condition + 1, len(expe[phase]["conditions"])))
print "\n=============== Testing condition {} / {} ============\n\n".format(
i_condition + 1, len(expe[phase]["conditions"]))
condition = expe[phase]["conditions"][i_condition]
# if condition["vocoder"] > 0:
# print "{}\n\n".format(options["vocoder"][condition["vocoder"]]["label"])
# --- Prepare unitary vector for this voice direction ---
u_f0 = 12 * np.log2(
options["test"]["voices"]['v' + str(condition["dir_voice"])]["f0"]
/
options["test"]["voices"]['v' + str(condition["ref_voice"])]["f0"])
u_ser = 12 * np.log2(
options["test"]["voices"]['v' + str(condition["dir_voice"])]["ser"]
/ options["test"]["voices"]['v' +
str(condition["ref_voice"])]["ser"])
u = np.array([u_f0, u_ser])
u = u / np.sqrt(np.sum(np.power(u, 2)))
expe_logger.info(
"\n=============== Unitary vector {} ============\n\n".format(
str(u)))
# --- Adaptive procedure ---
difference = options[phase]["starting_difference"]
step_size = options[phase]["initial_step_size"]
response_correct = np.array([])
decision_vector = []
steps = np.array([])
differences = np.array([difference])
beginning_of_run = datetime.datetime.now()
# Set probability of encouragement
prob_encou = 0.1
response_tracker = 0
half_way = 1
three_quarter = 1
while True:
expe_logger.info("========== Trial========\n\n")
# Prepare the trial
trial = condition
# Compute the test voice
new_voice_st = difference * u
trial["f0"] = options["test"]["voices"][
'v' + str(trial["ref_voice"])]["f0"] * np.array(
[1, np.power(2, new_voice_st[0] / 12)])
trial["ser"] = options["test"]["voices"][
'v' + str(condition["ref_voice"])]["ser"] * np.array(
[1, np.power(2, new_voice_st[1] / 12)])
options["f0_contours"] = np.array(options["f0_contours"])
c, _ = options["f0_contours"].shape
ifc = np.random.permutation(c)
trial["f0_contours"] = options["f0_contours"][ifc[0:3], :]
isyll = np.random.permutation(len(options["syllables"]))
trial["syllables"] = []
syll_array = np.array([x.strip() for x in options["syllables"]])
options["syllables"] = syll_array
for _ in range(2):
trial["syllables"].append(
options["syllables"][isyll[0:options["n_syll"]]])
# Prepare the stimulus
if PRESENT == 0:
i_correct = 1
ave_time = np.append(ave_time, 1)
else:
settings.time_taken = time.time()
xOut, fs, i_correct = expe_make_stim(options, trial, p)
filenames = []
# Create the files with the stimuli
for i in range(len(xOut)):
filenames.append('stimulus_{}.wav'.format(i + 1))
# x = xOut[i] * 10 ** -options["attenuation_dB"]/20
sf.write(
filenames[i],
np.concatenate((np.zeros(
(1024 * 3, 2)), xOut[i], np.zeros((1024 * 3, 2)))),
fs)
tme = time.time() - settings.time_taken
time_logger.info(
"Time to generate 3 stimulus files: {}".format(tme))
ave_time = np.append(ave_time, tme)
filenames_combined = '{}, {}, {}'.format(
filenames[0], filenames[1], filenames[2])
# Send the stimuli files to Sam
try:
sam.aad.setOutputVolume(sam.stimulus_volume)
sam.play_sounds(filenames_combined)
sam.aad.setOutputVolume(sam.speaking_volume)
except AttributeError:
pass
# for i in range(len(xOut)):
# os.remove(filenames[i])
pass
# Start time for response time of subject
t = time.time()
# -- Collect the response ---
# Fill the response dictionary
response = {}
response["input"] = [i_correct, 1]
if SIMUL == 1:
i_clicked = i_correct
while differences[-1] < 0.01:
i_clicked = i_correct - 1
break
elif SIMUL == 3:
if difference + np.random.randn(1) > 1:
i_clicked = i_correct
else:
i_clicked = i_correct + 1
else:
try:
i_clicked = sam.answer(response["input"])
except AttributeError:
pass
pass
#
# i_clicked = random.randint(0, 3)
response["response_time"] = time.time() - t
response["timestamp"] = 'Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(
datetime.datetime.now())
response["button_clicked"] = i_clicked
if i_correct == i_clicked:
response["correct"] = True
else:
response["correct"] = False
response_correct = np.append(response_correct, response["correct"])
decision_vector.append(response["correct"])
response["condition"] = condition
response["condition"]["u"] = u
response["trial"] = trial
response["trial"]["v"] = difference * u
expe_logger.info(
'Difference \t\t\t: {:1f} st ({:1f} st GPR, {:1f} st VTL) \n'.
format(difference, difference * u[0], difference * u[1]))
expe_logger.info('Correct button\t\t\t: {}\n'.format(i_correct))
expe_logger.info('Clicked response\t\t\t: {}\n'.format(i_clicked))
expe_logger.info('Response time\t\t\t: {} ms\n'.format(
round(response["response_time"] * 1000)))
expe_logger.info(
'Time since beginning of run\t: {}\n'.format(beginning_of_run))
expe_logger.info('Time since beginning of session\t: {}\n'.format(
beginning_of_session))
# Add response to results structure
n_attempt = expe[phase]["conditions"][i_condition]["attempts"] + 1
attempt_idx = n_attempt - 1
if not phase in results or i_condition <= len(
results[phase]["conditions"]):
att = {}
if not phase in results:
results[phase] = {}
keys = ["differences", "steps", "diff_i_top", "sd"]
att = dict.fromkeys(keys, np.empty([]))
att["threshold"] = 0
att["responses"] = {}
if i_condition == 1:
pass
if not "conditions" in results[phase]:
# results[phase]["conditions"] = np.array([attempt])
results[phase]["conditions"] = {}
if not "c" + str(i_condition) in results[phase]["conditions"]:
results[phase]["conditions"]["c" + str(i_condition)] = {}
# results[phase]["conditions"]["c" + str(i_condition)]["att"] = np.array([att])
results[phase]["conditions"]["c" +
str(i_condition)]["att"] = {
"responses": {},
"differences": [],
"steps": [],
"diff_i_tp": [],
"threshold": 0,
"sd": 0,
"duration": 0,
"exit_reason": ""
}
# else:
# # results[phase]["conditions"] = np.append(
# # results[phase]["conditions"], attempt)
# try:
# # results[phase]["conditions"]["c" + str(i_condition)]["att"] = np.append(
# # results[phase]["conditions"]["c" + str(i_condition)]["att"], att)
# results[phase]["conditions"]["c" +
# str(i_condition)]["att"] = {""}
# except KeyError:
# results[phase]["conditions"]["c" +
# str(i_condition)] = {}
# results[phase]["conditions"]["c" + str(i_condition)]["att"] = np.array([
# att])
# if not results[phase]["conditions"]["c" + str(i_condition)]["att"][attempt_idx]["responses"]:
# results[phase]["conditions"]["c" + str(i_condition)]["att"][attempt_idx]["responses"] = [
# response]
# if not results[phase]["conditions"]["c" + str(i_condition)]["att"]["responses"]:
# results[phase]["conditions"]["c" +
# str(i_condition)]["att"]["responses"] = [response]
# else:
# # results[phase]["conditions"]["c" + str(i_condition)]["att"][attempt_idx]["responses"].append(
# # response)
# results[phase]["conditions"]["c" +
# str(i_condition)]["att"]["responses"].append(response)
results[phase]["conditions"]["c" +
str(i_condition)]["att"]["responses"][
"r" +
str(response_tracker)] = response
response_tracker += 1
# --- Probability for encourangement ---
if phase == "test":
encou_answer = 'correct'
if i_clicked != i_correct:
prob_encou = prob_encou + 0.05
encou_answer = 'wrong'
if np.random.rand() < prob_encou:
try:
resp = sam.encouragement(encou_answer)
except AttributeError:
pass
prob_encou = 0.1
time.sleep(0.5)
# --- Prepare parameters for next trial ---
if len(decision_vector) >= options[phase]["down_up"][0] and all(
v == 1
for v in decision_vector[-1 -
options[phase]["down_up"][1]:]):
# The last n_down responses were correct -> Reduce
# difference by step_size, then update step_size
expe_logger.info(
'-- Where going down by {} st \n'.format(step_size))
difference = difference - step_size
steps = np.append(steps, -step_size)
differences = np.append(differences, difference)
# Update step size.
if difference <= options[phase][
"change_step_size_condition"] * step_size or len(
differences
) % options[phase]["change_step_size_n_trials"] == 0:
expe_logger.info(
'Step size is getting updated; was {} st'.format(
step_size))
step_size = step_size * \
options[phase]["step_size_modifier"]
expe_logger.info(
'step size is now {} st\n'.format(step_size))
# Reset decision vector
decision_vector = []
elif len(decision_vector) >= options[phase]["down_up"][1] and all(
v == 0
for v in decision_vector[-1 -
options[phase]["down_up"][1]:]):
# The last n_up responses were incorrect -> Increase
# difference by step_size. No update of step_size when going up
expe_logger.info('-- Where going up by {}\n'.format(step_size))
difference = difference + step_size
steps = np.append(steps, step_size)
differences = np.append(differences, difference)
decision_vector = []
else:
expe_logger.info('-- Where going neither up or down\n')
steps = np.append(steps, 0)
differences = np.append(differences, difference)
# x = np.abs(np.sign(steps[np.nonzero(steps)]))
# x = x[np.nonzero(np.diff(x))]
nturns = np.sum(np.diff(np.sign(steps[steps != 0])) != 0)
# nturns = np.sum(np.nonzero(np.diff(np.sign(np.nonzero(steps)))))
# --- Check if an exit condition has been reached ---
print nturns
if phase == "test":
if nturns == (options[phase]["terminate_on_n_turns"] /
2) and half_way:
n = random.randint(0, 2)
sam.simple_say(halfWay[n])
half_way = 0
elif nturns == ((3 * options[phase]["terminate_on_n_turns"]) /
4) and three_quarter:
n = random.randint(0, 2)
sam.simple_say(threeQuarters[n])
three_quarter = 0
if phase == "test":
if nturns >= options[phase]["terminate_on_n_turns"]:
expe_logger.info(
'====== END OF RUN due to enough turns =========\n')
print '==== END OF RUN due to enough turns =========\n'
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["exit_reason"] = 'nturns'
results[phase]["conditions"][
"c" +
str(i_condition)]["att"]["exit_reason"] = 'nturns'
expe[phase]["conditions"][i_condition]["done"] = 1
expe[phase]["conditions"][i_condition]["attempts"] += 1
i_nz = np.nonzero(steps)
i_d = np.nonzero(np.diff(np.sign(steps[steps != 0])) != 0)
i_tp = i_nz[0][i_d] + 1
i_tp = np.append(i_tp, len(differences))
i_tp = i_tp[-1 -
options[phase]["threshold_on_last_n_trials"]:]
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["diff_i_tp"] = i_tp
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["diff_i_tp"] = [i_tp]
thr = np.mean(differences[i_tp - 1])
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["threshold"] = thr
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["threshold"] = thr
sd = np.std(differences[i_tp - 1], ddof=1)
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["sd"] = sd
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["sd"] = sd
expe_logger.info(
'Threshold: {} st ({} st GPR, {} st VTL)\n'.format(
thr, thr * u[0], thr * u[1]))
print 'Threshold: {} st ({} st GPR, {} st VTL)\n'.format(
thr, thr * u[0], thr * u[1])
thresholds_dict["Trial_" +
str(i_condition + 1)] = OrderedDict()
f0_1 = condition["f0"][0]
f0_2 = condition["f0"][1]
ser_1 = condition["ser"][0]
ser_2 = condition["ser"][1]
if f0_1 != f0_2 and ser_1 != ser_2:
thresholds_dict["Trial_" +
str(i_condition +
1)]["condition"] = "f0&VTL"
elif ser_1 != ser_2:
thresholds_dict["Trial_" + str(i_condition +
1)]["condition"] = "VTL"
elif f0_1 != f0_2:
thresholds_dict["Trial_" + str(i_condition +
1)]["condition"] = "f0"
thresholds_dict["Trial_" +
str(i_condition + 1)]["threshold"] = {}
thresholds_dict["Trial_" +
str(i_condition +
1)]["threshold"]["threshold"] = thr
thresholds_dict["Trial_" +
str(i_condition +
1)]["threshold"]["f0"] = thr * u[0]
thresholds_dict["Trial_" +
str(i_condition +
1)]["threshold"]["vtl"] = thr * u[1]
# thresholds_dict["Trial_"+str(i_condition)]["threshold"] = 'Threshold: {} st ({} st GPR, {} st VTL)\n'.format(
# thr, thr*u[0], thr*u[1])
break
# elif len(response_correct) >= 20:
elif len(response_correct
) >= options[phase]["terminate_on_n_trials"]:
expe_logger.info(
'====== END OF RUN due to too many trials ======\n')
print '====== END OF RUN due to too many trials ======\n'
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["exit_reason"] = 'ntrials'
results[phase]["conditions"][
"c" +
str(i_condition)]["att"]["exit_reason"] = 'ntrials'
expe[phase]["conditions"][i_condition]["attempts"] += 1
# Should we retry?
if expe[phase]["conditions"][i_condition][
"attempts"] >= options[phase]["retry"] + 1:
# retry = sam.retry()
# retry = 0
# if retry:
# pass
# else:
# # sam.ending()
# pass
expe[phase]["conditions"][i_condition]["done"] = 1
# results[phase]["conditions"]["c" + str(i_condition)]["att"][attempt_idx]["diff_i_tp"] = np.empty([
# ])
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["diff_i_tp"] = np.empty(
[])
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["threshold"] = 0
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["threshold"] = 0
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["sd"] = 0
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["sd"] = 0
break
elif len(response_correct) >= options[phase][
"change_step_size_n_trials"] and all(
v == 0 for v in response_correct[
-1 -
options[phase]["change_step_size_n_trials"]:]):
# All last trials are incorrect
expe_logger.info(
'====== END OF RUN due to too many incorrect answers ======\n'
)
print '====== END OF RUN due to too many incorrect answers ======\n'
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["exit_reason"] = 'nwrong'
results[phase]["conditions"][
"c" +
str(i_condition)]["att"]["exit_reason"] = 'nwrong'
expe[phase]["conditions"][i_condition]["attempts"] += 1
# Try again?
if expe[phase]["conditions"][i_condition][
"attempts"] >= options[phase]["retry"] + 1:
# retry = sam.retry()
# if retry:
# pass
# else:
# sam.ending()
# pass
expe[phase]["conditions"][i_condition]["done"] = 1
break
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["differences"] = differences
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["steps"] = steps
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["differences"] = differences
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["steps"] = steps
else:
if len(response_correct
) >= options[phase]["terminate_on_n_trials"]:
expe_logger.info(
'====== END OF Training RUN due to too many trials ======\n'
)
print '====== END OF Training RUN due to too many trials ======\n'
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["exit_reason"] = 'ntrials'
results[phase]["conditions"][
"c" +
str(i_condition)]["att"]["exit_reason"] = 'ntrials'
expe[phase]["conditions"][i_condition]["attempts"] += 1
# Should we retry?
if expe[phase]["conditions"][i_condition][
"attempts"] >= options[phase]["retry"] + 1:
# retry = sam.retry()
# retry = 0
# if retry:
# pass
# else:
# # sam.ending()
# pass
expe[phase]["conditions"][i_condition]["done"] = 1
# results[phase]["conditions"]["c" + str(i_condition)]["att"][attempt_idx]["diff_i_tp"] = np.empty([
# ])
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["threshold"] = 0
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["sd"] = 0
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["diff_i_tp"] = np.empty(
[])
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["threshold"] = 0
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["sd"] = 0
break
# if DEBUG:
# # Plot the matplotlib graphs if DEBUG is True
# plot_differences(results, differences, response_correct)
# --- Save the response of the current task in .mat file ---
check = 1
# Close the current open plot and set the plot tracker to True so a new figure can be created for the next trial
# plt.close()
PLT_CLOSED = True
delete_last_lines(n=6)
avg_time = np.mean(ave_time)
time_logger.info(
"Average time taken to generate three stimulus files for one trial: {}"
.format(avg_time))
time_logger.info("Average time (min): {}".format(
str(datetime.timedelta(seconds=avg_time))))
tot_time = avg_time * len(ave_time)
time_logger.info("Total time of trial: {}".format(
datetime.timedelta(seconds=tot_time)))
try:
sam.simple_say("Thats the end of this task.")
except AttributeError:
pass
if i_condition == len(done) - 1:
terminate = 1
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'))
pickle.dump(
thresholds_dict,
open("{}/thresholds_temp.p".format(options["result_path"]), 'wb'))
pickle.dump(p, open("{}/p_temp.p".format(options["result_path"]),
'wb'))
# sio.savemat(options["res_filename"], mdict={
# 'expe': expe,
# 'options': options,
# 'results': results,
# 'thresholds': thresholds_dict,
# 'p': p})
if phase == "test":
if np.mean(done) == 1:
break
if not terminate:
try:
sam.take_break()
except AttributeError:
pass
pass
elif phase == "training":
done = [
expe[phase]["conditions"][i]["done"]
for i in range(len(expe[phase]["conditions"]))
]
if np.mean(done) == 1:
break
try:
sam.simple_say(
"When you're ready to continue, touch the top of my head.")
sam.mtn.setStiffnesses(["HeadYaw", "HeadPitch"], [1.0, 1.0])
sam.hoofd_beweging()
sam.mtn.setStiffnesses(["HeadYaw", "HeadPitch"], [0.0, 0.0])
except AttributeError:
pass
# --- End of adaptive loop ---
# --- Save the response of the whole trial in .mat file ---
saveFromPickle(options)
# sio.savemat(options["res_filename"], mdict={
# 'expe': expe, 'options': options, 'results': results, 'thresholds': thresholds_dict, 'p': p}, appendmat=True)
complete = []
for i in expe[phase]["conditions"]:
complete.append(i["done"])
# --- Create the report status for the trial ---
report_status(options["subject_name"], phase, np.sum(complete),
len(complete), options["log_file"])
# TODO Possibly add a game break message
# Once out of the main loop, tell the researcher
sys.stdout.write("==== END OF EXPERIMENT. ====\n")
for k, v in thresholds_dict.iteritems():
for key, value in v.iteritems():
if v[key] == "VTL" or v[key] == "f0":
expe_logger.info(k)
expe_logger.info("Condition: " + v[key])
if phase == "test":
exp["experiments"]["fishy"] = 1
sio.savemat(options["res_tracker"], mdict={"tracker": exp})
try:
sam.simple_say(" and also the end of the testing phase.")
except AttributeError:
pass
else:
try:
sam.simple_say(" and also the end of the training phase")
except AttributeError:
pass
pass
exp_tracker = np.array(
[exp["experiments"][key] for key in exp["experiments"].keys()])
if np.mean(exp_tracker) == 1:
try:
sam.ending()
except AttributeError:
pass
expe_logger.info(
"==== END OF EXPERIMENT ({}). Thank you for your participation".
format(phase))
def report_status(subj, phase, i, n, logFile):
with open(logFile, 'w') as f:
f.write('{} : {} : {}/{}\n'.format(subj, phase, i, n))
f.close()
# def plot_differences(results, differences, response_correct):
# '''
# Creates the matplotlib graphs of the responses.
# ax1 shows the steps of the adaptive loop and ax2 shows something else...
# '''
# global PLT_CLOSED
# global FIG
# global AX1
# if PLT_CLOSED:
# create_fig()
# fig = FIG
# ax1 = AX1
# plt.cla()
# x = np.arange(len(differences)-1)
# y = np.array(differences[:-1])
# ax1.plot(x, y, 'r--')
# ax1.plot(len(differences) +
# np.array([-1, 0]), differences[len(differences)-2:], 'b--')
# ax1.plot(x[np.where(response_correct == 1)],
# y[np.where(response_correct == 1)], 'g--')
# ax1.plot(x[np.where(response_correct == 0)],
# y[np.where(response_correct == 0)], 'y--')
# # ax2.plot([options[phase]["voices"]["v" + str(condition["ref_voice"])]["f0"],
# # options[phase]["voices"]["v" + str(condition["dir_voice"])]["f0"]],
# # [options[phase]["voices"]["v" + str(condition["ref_voice"])]["ser"],
# # options[phase]["voices"]["v" + str(condition["dir_voice"])]["ser"]])
# # for i_resp in range(len(results[phase]["conditions"]["c" + str(i_condition)]["att"][attempt_idx]["responses"])):
# # if results[phase]["conditions"]["c" + str(i_condition)]["att"][attempt_idx]["responses"][i_resp]["correct"]:
# # ax2.plot(results[phase]["conditions"]["c" + str(i_condition)]
# # ["att"][attempt_idx]["responses"][i_resp]["trial"]["f0"][1],
# # results[phase]["conditions"]["c" + str(i_condition)]
# # ["att"][attempt_idx]["responses"][i_resp]["trial"]["ser"][1], 'm-')
# # else:
# # ax2.plot(results[phase]["conditions"]["c" + str(i_condition)]
# # ["att"][attempt_idx]["responses"][i_resp]["trial"]["f0"][1],
# # results[phase]["conditions"]["c" + str(i_condition)]
# # ["att"][attempt_idx]["responses"][i_resp]["trial"]["ser"][1], 'm-')
# # for i_sp in range(len(options[phase]["voices"])):
# # ax2.plot(options[phase]["voices"]["v" + str(i_sp+1)]["f0"],
# # options[phase]["voices"]["v" + str(i_sp+1)]["ser"], 'g:')
# # plt.tight_layout()
# # plt.show()
# # plt.draw()
# fig.canvas.draw()
# plt.pause(0.0001)
# def create_fig():
# '''Creates an instance of a matplotlib figure and sets the global variables accordingly.'''
# global PLT_CLOSED
# global FIG
# global AX1
# if PLT_CLOSED:
# (FIG, AX1) = plt.subplots(1)
# FIG.suptitle("Debug Mode")
# PLT_CLOSED = False
def delete_last_lines(n=1):
CURSOR_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'
for _ in range(n):
sys.stdout.write(CURSOR_UP_ONE)
sys.stdout.write(ERASE_LINE)
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'))
thresholds_dict = pickle.load(
open("{}/thresholds_temp.p".format(options["result_path"]), 'rb'))
p = pickle.load(
open("{}/p_temp.p".format(options["result_path"]), 'rb'))
sio.savemat(options["res_filename"],
mdict={
"expe": expe,
"options": opt,
"results": results,
"thresholds": thresholds_dict,
"p": p
})
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"]))
os.remove("{}/thresholds_temp.p".format(options["result_path"]))
os.remove("{}/p_temp.p".format(options["result_path"]))
except Exception as e:
print e
return
+174
View File
@@ -0,0 +1,174 @@
# --------------------------------------------------------------------------
# Authors:
# ------ MATlAB ------
# 2010-03-16: Etienne Gaudrain <etienne.gaudrain@mrc-cbu.cam.ac.uk>
# 2013-02-24: Etienne Gaudrain <e.p.c.gaudrain@rug.nl>
# 2017-03-29: Etienne Gaudrain <etienne.gaudrain@cnrs.fr>
# ------ Python ------
# 2020-01-28: 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/>.
# --------------------------------------------------------------------------
import sys
import os
import expe_robot
import ctypes
import time
import logging
import datetime
import expe_build_conditions
import expe_options
import tools.settings as settings
from scipy.io import savemat
from naoqi import ALBroker
from tools.exit_condition import ExitExperimentModule
VERSION = 20202801
expe_exit = None
def setup_logger(name, log_file, level=logging.INFO):
"""To setup as many loggers as you want"""
formatter = logging.Formatter('%(levelname)s:%(message)s')
handler = logging.FileHandler(log_file)
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.setLevel(level)
logger.addHandler(handler)
logger.propagate = False
return logger
def main(options, subject, phase, lang, p_exists, ip='127.0.0.1', port=9559):
'''
Runs the experiment.
SUBJECT is a string identifying the subject.
PHASE is either 'training' or 'test'
IP is the ipaddress of Sam when connected to a relevant network
PORT is the port for connection to Sam
'''
options["subject_name"] = subject
options["language"] = lang
options = expe_options.expe_options(options)
# Adds necessary paths. So far not in use.
added_path = []
added_path.append(options["path"]["audio"])
added_path.append(options["path"]["vocoder"])
# Create the results directory in the current directory if it does not already exist
if not os.path.exists(options["result_path"]):
os.mkdir(options["result_path"])
# Create the logs directory in the current directory if it does not already exist
if not os.path.exists(options["logs_path"]):
os.mkdir(options["logs_path"])
# Create the subject's file path
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})
# Create various loggers to track different elements
log_filename = os.path.join(
options["logs_path"],
"{}{}_{}_robot.mat".format(options["result_prefix"], lang.lower(),
subject))
options["log_filename"] = log_filename
# tracks participants progress
expe_logger = setup_logger("expe_logger", options["log_filename"])
# tracks general information
gen_logger = setup_logger("gen_logger", "./logs/general.log")
time_logger = setup_logger("time_logger", "./logs/time_check.log")
# gen_logger = setup_logger("gen_logger", gen_logs)
# Check if the subject's file already exists, otherwise create it
if p_exists is None:
if not os.path.exists(res_filename):
msg = "The subject '{}' does not exist. Create it?".format(subject)
print msg
ans = raw_input("(Y/n): ")
if ans.lower() == 'y':
expe_build_conditions.expe_build_conditions(options, lang)
# -- Create new logging file
expe_logger.info(
"====== Beginning new log for subject: {} ======".format(
subject))
expe_logger.info("====== Date of creation: {} \n\n".format(
datetime.datetime.today()))
elif ans.lower() == 'n':
sys.exit()
else:
raise "that is not a valid choice"
else:
msg = "Found {}. Use this file?".format(subject)
print msg
ans = raw_input("(Y/n): ")
expe_logger.info(
"===== Continuing previous created experiment =====")
expe_logger.info("===== Date: {}\n\n".format(
datetime.datetime.today()))
if ans.lower() == 'n':
sys.exit()
elif not p_exists:
expe_build_conditions.expe_build_conditions(options)
# run the robot experiment
gen_logger.info("***** Starting general logging *****\n\n")
time_logger.info("***** Starting time check logging *****\n\n")
# Used when testing the time it takes to generate stimulus files
matlab = True
if matlab:
time_logger.info("=== Using matlab stimulus generation ===\n")
else:
time_logger.info("=== Using PyWorld stimulus generation === \n")
expe_robot.expe_robot(ip, port, lang, options, phase, subject)
if __name__ == "__main__":
options = {}
main(options, "test", "test", "en")
+46
View File
@@ -0,0 +1,46 @@
import os
import soundfile as sf
import pyworld as pw
import numpy as np
import scipy.io as spio
from expe_options import expe_options
from expe_build_conditions import expe_build_conditions
def preprocess(language):
options = {}
options["language"] = language
options["subject_name"] = ''
options = expe_options(options)
_, options = expe_build_conditions(options)
for i in range(len(options["syllables"])):
syll = options["syllables"][i]
print "%02d/%02d - %s\n" % (i, len(options["syllables"]), syll)
wavIn = os.path.join(options["sound_path"], syll + ".wav")
mat = os.path.join(options["sound_path_store"], syll + '.pyworld.mat')
if not os.path.exists(mat):
x, fs = sf.read(wavIn)
_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
})