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.
+40
View File
@@ -0,0 +1,40 @@
import math
import warnings
import numpy as np
def cosgate(x, fs, d):
if type(d) == 'list':
if len(d) == 1:
d = np.array([d, d])
elif len(d) > 2:
raise ValueError(
"The ramp duration argument can only be of length 1 or 2.")
else:
d = np.array([d])
d = d * fs
# Onset
k = np.array(range(0, int(d[0]-1)))
# if np.size(x, 2) == 1:
# k = k.T
x[[k+1]] = np.multiply(x[[k+1]], 1 -
(1 + np.cos(k * np.pi / (d[0]-1)) / 2))
# Offset
try:
k = np.array(range(0, int(d[1]-1)))
x[[-k]] = np.multiply(x[[-k]], 1 -
(1 + np.cos(k * np.pi / (d[1]-1)) / 2))
except IndexError:
k = np.array(range(0, int(d[0]-1)))
x[[-k]] = np.multiply(x[[-k]], 1 -
(1 + np.cos(k * np.pi / (d[0]-1)) / 2))
# if np.size(x, 2) == 1:
# k = k.T
y = x
return y
+202
View File
@@ -0,0 +1,202 @@
import numpy as np
import os
import wave
import math
from scipy.io import savemat
import warnings
from gender_options import expe_options
from tools.load_matrix import loadmat
def expe_build_conditions(options):
# Build Signal conditions
options["fs"] = 44100
# options["attenuation_dB"] = 7
mat = loadmat('./calibration.mat')
cal = mat["calibration"]
options["attenuation_dB"] = cal["gender"]
# options["attenuation_dB"] = 10 # Calibrated attenuation
options["ear"] = "both"
# Design specifications
options["test"] = {}
options["training"] = {}
options["test"]["n_repeat"] = 1
options["training"]["n_repeat"] = 1
word_list = []
if options["Bert"]:
options["test"]["f0s"] = np.array([0.0, -3.0, -6.0, -9.0, -12.0])
options["test"]["vtls"] = np.array([0, 0.7, 1.6, 2.4, 3.0, 3.6])
else:
options["test"]["f0s"] = np.array([0.0, -6.0, -12.0])
options["test"]["vtls"] = np.array([0, 1.8, 3.6])
options["training"]["f0s"] = np.array([0.0, -12.0])
options["training"]["vtls"] = np.array([0.0, 3.6])
nF0 = len(options["test"]["f0s"])
nVTL = len(options["test"]["vtls"])
if options["phase"] == "generation":
word_list = ["Bus", "Leeg", "Pen", "Vaak"]
elif options["phase"] == "test" or options["phase"] == "training":
if options["language"].lower() == "nl":
word_list = ["Bus", "Leeg", "Pen", "Vaak"]
elif options["language"].lower() == "en":
word_list = ["bike", "hat", "pool", "watch"]
options["test"]["word_list"] = word_list
options["training"]["word_list"] = word_list
nWords = len(word_list)
options["sound_path_local"] = os.path.join(
options["sound_path"], options["language"])
options["tmp_path_local"] = options["tmp_path"]
options["sounds_for_calibration"] = []
lst = [f for f in os.listdir(
options["tmp_path_local"]) if f.endswith(".wav")]
for f in range(len(lst)):
options["sounds_for_calibration"].append(
os.path.join(options["tmp_path_local"], lst[f]))
options["test"]["total_ntrials"] = nWords * nVTL * nF0
# oneSampleFile = os.path.join(options["tmp_path"], "{}_GPR{}_VTL{}.wav".format(word_list[0],
# options["test"]["f0s"][0], options["test"]["vtls"][0]))
# options["training"]["total_ntrials"] = len(
# word_list) * len(options["training"]["f0s"]) * len(options["training"]["vtls"])
options["training"]["total_ntrials"] = 7
# if os.path.exists(oneSampleFile):
# w = wave.open(oneSampleFile, 'r')
# frames = w.getnframes()
# rate = w.getframerate()
# duration = frames/float(rate)
# options["word_duration"] = duration
# else:
# options["word_duration"] = 850e-3
options["lowpass"] = 4000
options["force_rebuild_sylls"] = 0
# Build test block
# options["test"]["faces"] = np.array(["woman_1", "woman_2", "woman_3", "woman_4", "woman_5",
# "woman_6", "woman_7", "man_1", "man_2", "man_3", "man_4",
# "man_5", "man_6", "man_7"])
options["test"]["face_genders"] = ['man', 'woman']
options["test"]["number_faces"] = 7
options["training"]["face_genders"] = options["test"]["face_genders"]
options["training"]["number_faces"] = options["test"]["number_faces"]
# nFaces = len(options["test"]["faces"])
# nRepetitions = math.ceil(options["test"]["total_ntrials"]/nFaces)
# nFemales = sum([True for s in options["test"]
# ["faces"] if s.startswith("woman")])
# nMales = nFaces - nFemales
# indexes = np.tile(range(1, nFemales), int(nRepetitions))
# np.random.shuffle(indexes)
# indexes = np.delete(
# indexes, np.s_[options["test"]["total_ntrials"]/2:], None)
# indexesM = np.tile(range(1+nFemales, nMales+nFemales), int(nRepetitions))
# np.random.shuffle(indexesM)
# indexesM = np.delete(
# indexesM, np.s_[options["test"]["total_ntrials"]/2:], None)
# indexes = [indexes, indexesM]
# np.random.shuffle(indexes)
# np.random.shuffle(options["test"]["faces"])
# options["test"]["faces"] = options["test"]["faces"][indexes]
# TODO test Hands
test = {}
counter = 1
for ir in range(options["test"]["n_repeat"]):
for f0 in range(nF0):
for vtl in range(nVTL):
i_words = np.random.permutation(nWords)
for i_face_gender in range(2):
face_gender = options["test"]["face_genders"][i_face_gender]
i_word_start = i_face_gender * nWords / 2 + 1
for i_word in np.arange(nWords/2) - 1+i_word_start:
trial = {}
trial["f0"] = options["test"]["f0s"][f0]
trial["vtl"] = options["test"]["vtls"][vtl]
trial["word"] = options["test"]["word_list"][i_words[i_word]]
trial["i_repeat"] = ir
trial["done"] = 0
trial["face"] = '{}_{}'.format(
face_gender, np.random.randint(options["test"]["number_faces"]))
trial["face_gender"] = face_gender
if not "trials" in test:
test["trials"] = [trial]
else:
test["trials"].append(trial)
training = {}
nWords = len(options["training"]["word_list"])
for ir in range(options["training"]["n_repeat"]):
for i_v in range(len(options["training"]["f0s"])):
i_f0 = i_v
i_vtl = i_v
i_words = np.random.permutation(nWords)
for i_face_gender in range(2):
face_gender = options["training"]["face_genders"][i_face_gender]
i_word_start = i_face_gender*nWords/2+1
for i_word in np.arange(nWords/2) - 1+i_word_start:
trial = {}
trial["f0"] = options["training"]["f0s"][i_f0]
trial["vtl"] = options["training"]["vtls"][i_vtl]
trial["word"] = options["training"]["word_list"][i_words[i_word]]
trial["i_repeat"] = ir
trial["done"] = 0
trial["face"] = '{}_{}'.format(
face_gender, np.random.randint(options["test"]["number_faces"]))
trial["face_gender"] = face_gender
if not "trials" in training:
training["trials"] = [trial]
else:
training["trials"].append(trial)
# Create expe dictionary and save
expe = {}
if options["phase"] == "generation":
expe["test"] = {}
expe["test"]["trials"] = test["trials"]
else:
expe["test"] = {}
expe["training"] = {}
i_order = np.random.permutation(len(test["trials"]))
expe["test"]["trials"] = []
for i in i_order:
expe["test"]["trials"].append(test["trials"][i])
i_order = np.random.permutation(len(training["trials"]))
expe["training"]["trials"] = []
for i in i_order:
expe["training"]["trials"].append(training["trials"][i])
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
if __name__ == "__main__":
options = expe_options()
buildConditions(options)
+37
View File
@@ -0,0 +1,37 @@
import os
import numpy as np
from gender_build_conditions import expe_build_conditions as buildConditions
from gender_makeStimuli import makeStimuli
def generateStimuli(options, phase):
if os.path.exists(options["res_filename"]):
os.remove(options["res_filename"])
opt = raw_input("Delete previously processed sound files? (Y/n): ")
if opt.lower() == "y":
# os.remove(os.path.join(options["sound_path"], '*.wav'))
old = [f for f in os.listdir(
options["tmp_path"]) if f.endswith(".wav")]
for o in old:
os.remove(os.path.join(options["tmp_path"], o))
elif opt.lower() == 'n':
return
else:
raise ValueError("That is not a valid option")
expe, options = buildConditions(options)
done = []
while np.mean(done) != 1:
done = []
for i in range(len(expe[phase]["trials"])):
done.append(expe[phase]["trials"][i]["done"])
try:
itrial = done.index(0)
except ValueError:
break
trial = expe[phase]["trials"][itrial]
makeStimuli(options, trial)
expe[phase]["trials"][itrial]["done"] = 1
+285
View File
@@ -0,0 +1,285 @@
# --------------------------------------------------------------------------
# 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
from scipy.signal import butter, filtfilt
import soundfile as sf
from playsound import playsound
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
from gender_removeSilence import removeSilence
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 makeStimuli(options, trial):
'''
Generates the stimuli files for a given trial
and how the trial has been specified
'''
x = np.array([])
t = clock()
y, fs = straight_process(
trial["word"], trial["f0"], trial["vtl"], None, options)
y = y * np.power(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
# dl = int(round(options["word_duration"]*fs) - len(y))
# if dl > 0:
# # Adds padding because the syllable signal is too short
# npad_L = int(math.floor(dl/20))
# npad_R = int(dl-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 dl < 0:
# # The synthesised signal is too long
# y = y[0:len(y)-dl]
# 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))
print "%s -- F0: %5.1f Hz, VTL: %4.2f \n" % (
trial["word"], trial["f0"], trial["vtl"])
if options["lowpass"] != None:
b, a = butter(4, (options["lowpass"] * 2.0)/fs, 'low')
x = filtfilt(b, a, y)
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"]))
return x, fs
def straight_process(word, nb_st, vtl, d, options):
'''
Generates the individual stimuli files
'''
wavIn = os.path.join(options["sound_path"], word + ".wav")
wavOut = make_fname(
wavIn, nb_st, vtl, d, options["tmp_path"])
y = []
if not os.path.exists(wavOut) or options["force_rebuild_sylls"]:
mat = os.path.join(options["sound_path_store"], word + '.pyworld.mat')
# Intialise variables 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)
try:
x = x[:, 0]
except IndexError:
x = x[:]
x = np.ascontiguousarray(x, dtype=np.float)
# --- Using PyWORLD script
_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
duration = len(x/fs)
x_rms = np.sqrt(np.mean(x**2))
spio.savemat(mat, mdict={'fs': fs, 'f0': f0,
'sp': sp, 'ap': ap,
'x_rms': x_rms,
'frequencies': freq,
'temporal_positions': t,
'duration': duration
})
f0[np.where(f0 != 0)] = f0[np.where(f0 != 0)] * \
np.power(2, (nb_st/12))
mapp = 1 * np.power(2, -(vtl/12))
sp = sp_ap_creation(sp, temp_pos, freq, mapp)
ap = sp_ap_creation(ap, temp_pos, freq, 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)
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))
y_magnitude_factor = 0
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
# y = removeSilence(y, fs, 50e-3)
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, vtl, d, destPath):
'''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
if d == None:
fname = "%s_GPR%d_VTL%.2f" % (
name, int(math.floor(f0)), vtl)
else:
fname = "%s_GPR%d_VTL%.2f_D%d" % (
name, int(math.floor(f0)), vtl, int(math.floor(d*1e3)))
fname = os.path.join(destPath, fname + ext)
return fname
def sp_ap_creation(mat, temp, freq, vtl):
'''
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 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)
+51
View File
@@ -0,0 +1,51 @@
import os
import warnings
import sys
def expe_options(options):
# options["result_path"] = "./results/gender"
options["result_path"] = "./results/" + options["subject_name"]
options["sound_path"] = "./stimuli/gender/{}".format(
options["language"].lower())
options["sound_path_store"] = "./stimuli_store/gender/{}".format(
options["language"].lower())
if not os.path.exists(options["sound_path_store"]):
os.makedirs(options["sound_path_store"])
if not os.path.exists(options["sound_path"]):
os.makedirs(options["sound_path"])
if not "Bert" in options:
options["Bert"] = False
if options["Bert"]:
options["tmp_path"] = "./stimuli/gender/{}/processed/Bert".format(
options["language"].lower())
else:
options["tmp_path"] = "./stimuli/gender/{}/processed".format(
options["language"].lower())
options["result_prefix"] = "gen_"
if not os.listdir(options["sound_path"]):
raise ValueError("Sound path cannot be empty")
if not os.path.exists(options["tmp_path"]):
os.makedirs(options["tmp_path"])
# if not os.listdir(options["tmp_path"]) and options["phase"] != "generation":
# opt = raw_input(
# "Running experiment without preprocessing sounds? (Y/n)")
# if opt.lower() == "y":
# warnings.warn(
# "This will slow down the experiment substantially. Press ctrl+c to cancel if unhappy")
# elif opt.lower() == "n":
# warnings.warn(
# "Recommended to preprocess stimuli files before running the experiment.")
# sys.exit()
# else:
# raise ValueError("That is not a valid option")
options["experiment_begin"] = 1
return options
+39
View File
@@ -0,0 +1,39 @@
from cosgate import cosgate
from scipy.signal import butter, filtfilt
import numpy as np
import math
def removeSilence(y, fs, sampleDuration=750e-3):
sampleDuration = np.array([sampleDuration, sampleDuration])
d1 = sampleDuration[0]
d2 = sampleDuration[1]
b, a = butter(3, 50*2.0/fs, 'low')
fil = filtfilt(b, a, y)
fil = np.expand_dims(fil, axis=1)
e = np.max(fil, 1)
e = cosgate(e, fs, 20e-3)
c = 2 * np.max([np.array([[e[0:int(math.floor(d1*fs))]],
[e[len(e)-int(math.floor(d2*fs)):]]])])
# FIXME : There is a clicking at the beginning and end of sound. Speak to Etienne
# Onset
i1 = np.min(((e[:-1] < c) & (e[1:] >= c)).nonzero()[0])
# offset
i2 = np.max(((e[:-1] < c) & (e[1:] >= c)).nonzero()[0])
m = math.floor(20e-3 * fs)
i1 = int(np.max([1, i1 - m]))
i2 = int(np.max([len(y), i2 - m]))
y = cosgate(y[i1:i2], fs, 1e-3)
# bounds = np.array([i1, i2])
return y
+218
View File
@@ -0,0 +1,218 @@
import numpy as np
import os
import sys
import re
import random
import datetime
import soundfile as sf
import time
import logging
from playsound import playsound
from scipy.io import savemat
from gender_build_conditions import expe_build_conditions as buildConditions
from gender_makeStimuli import makeStimuli
from Robot.RobotGender import RobotGender
from tools.load_matrix import loadmat
def robot(expe, options, phase, lang, ip, port):
results = {}
gender_resp = {}
gender_resp[phase] = {}
starting = 1
# if phase == "training":
# starting = 1
mat = loadmat(options["res_filename"])
options = mat["options"]
expe = mat["expe"]
try:
results = mat['results']
except KeyError:
# Create a new results dictionary if one is not found or this is a new subject
results = {}
track = loadmat(options["res_tracker"])
exp = track["tracker"]
# --- Start an instance of Sam
sam = type('', (), {})()
create_sam = True
if create_sam:
sam = RobotGender(ip, port, lang)
# --- Set the initial volume
# --- Open loggers
expe_logger = logging.getLogger("expe_logger")
time_logger = logging.getLogger("time_logger")
autoplayer = False
terminate = 0
if options["subject_name"] == 'NHAtest':
os.remove(options["res_filename"])
autoplayer = True
resultsFiles = [os.path.join(options["result_path"], f) for f in os.listdir(
options["result_path"]) if f.endswith(".mat")]
nRep = len(resultsFiles) - sum([bool(re.search(options["subject_name"],
resultsFiles[i])) for i in range(len(resultsFiles))])
nRep = nRep + 1
options["subject_name"] = "NHAtest"
options["res_filename"] = os.path.join(
options["result_path"], "%sen_%s_robot.mat" % (
options["result_prefix"], options["subject_name"]))
# expe, options = buildConditions(options)
# === Main loop ===
# Intialise the done array to store if a task has been completed
done = []
expe_logger.info("##########\n\nStarting Gender experiment\n\n##########")
time_logger.info("##########\n\nStarting Gender experiment\n\n##########")
if starting and exp["experiment_begin"]:
try:
sam.intro()
sam.genderIntro()
except AttributeError:
pass
exp["experiment_begin"] = 0
savemat(options["res_tracker"], mdict={"tracker": exp})
elif starting:
try:
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.")
except AttributeError:
pass
pass
starting = 0
try:
sam.game_break()
except AttributeError:
pass
response_tracker = 0
while np.mean(done) != 1:
response = {}
done = [expe[phase]["trials"][i]["done"]
for i in range(len(expe[phase]["trials"]))]
if autoplayer:
starting = 1
try:
itrial = done.index(0)
except ValueError:
break
expe_logger.info("\n=============== Testing trial {} / {} ============\n\n".format(
itrial+1, len(expe[phase]["trials"])))
print "\n=============== Testing condition {} / {} ============\n\n".format(
itrial + 1, len(expe[phase]["trials"]))
trial = expe[phase]["trials"][itrial]
t = time.time()
xOut, fs = makeStimuli(options, trial)
sf.write('stimulus.wav', xOut, fs)
time_logger.info(
"Time to generate sound file: {}".format(time.time() - t))
t = time.time()
# time.sleep(1)
try:
sam.aad.setOutputVolume(sam.stimulus_volume)
sam.play_sounds('stimulus.wav', lang)
sam.aad.setOutputVolume(sam.speaking_volume)
except AttributeError:
pass
# time.sleep(2)
time_logger.info(
"Time to upload and play sound file: {}".format(time.time() - t))
os.remove('stimulus.wav')
try:
resp, chosen_gen = sam.answer()
except AttributeError:
pass
# resp = random.randint(0, 1)
# chosen_gen = ["Boy", "Girl"][np.random.randint(2)]
if autoplayer:
response["response_answer"] = {
"answer": [0, 1][np.random.randint(0, 2)],
"gender": ["Girl", "Boy"][np.random.randint(0, 2)]
}
response["response_time"] = 0
response["timestamp"] = str(datetime.datetime.now())
else:
t = time.time()
response["response_answer"] = resp
response["response_time"] = time.time() - t
response["timestamp"] = str(datetime.datetime.now())
response["trial"] = trial
if not phase in results:
results[phase] = {}
results[phase]["responses"] = {}
# results[phase]["responses"] = []
# else:
# results[phase]["responses"] = np.append(
# results[phase]["responses"], response)
results[phase]["responses"]["r" + str(response_tracker)] = response
response_tracker += 1
expe[phase]["trials"][itrial]["done"] = 1
try:
gender_resp_temp = {}
gender_resp_temp["answer"] = chosen_gen
gender_resp_temp["f0(st)"] = trial["f0"]
gender_resp_temp["VTL(st)"] = trial["vtl"]
gender_resp_temp["face_used"] = trial["face_gender"]
gender_resp[phase]["trial_" + str(itrial + 1)] = gender_resp_temp
except UnboundLocalError:
pass
if gender_resp_temp:
savemat(options["res_filename"], mdict={
"options": options, "expe": expe, "results": results, "gender_response": gender_resp})
else:
savemat(options["res_filename"], mdict={
"options": options, "expe": expe, "results": results})
if itrial == options[phase]["total_ntrials"]:
break
if phase == "training":
try:
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 ")
except AttributeError:
pass
pass
else:
exp["experiments"]["gender"] = 1
savemat(options["res_tracker"], mdict={"tracker": exp})
exp_tracker = np.array([exp["experiments"][key]
for key in exp["experiments"].keys()])
try:
if lang == "EN":
sam.simple_say(
"That's the end of the testing phase, and the end of this game.")
elif lang == "NL":
sam.simple_say(
"Dit is het einde van de test, en het einde van dit spelletje.")
except AttributeError:
pass
if np.mean(exp_tracker) == 1:
try:
sam.ending()
except AttributeError:
pass
pass
+56
View File
@@ -0,0 +1,56 @@
import os
from gender_options import expe_options as genOptions
from gender_build_conditions import expe_build_conditions as buildConditions
from gender_generateStimuli import generateStimuli
from gender_robot import robot
from tools.load_matrix import loadmat
from scipy.io import savemat
def main(options, subject, phase, language, p_exists=None, ip="127.0.0.1", port=9559):
options["subject_name"] = subject
options["language"] = language
options["phase"] = phase
options["Bert"] = False
options = genOptions(options)
try:
if not os.path.exists(options["result_path"]):
os.makedirs(options["result_path"])
except Exception as e:
print e
res_filename = os.path.join(options["result_path"], "{}{}_{}_robot.mat".format(
options["result_prefix"], language.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["experiments"] = {}
track["experiment_begin"] = 1
track["experiments"]["fishy"] = 0
track["experiments"]["gender"] = 0
track["experiments"]["emotion"] = 0
track["experiments"]["crm"] = 0
savemat(res_tracker, mdict={"tracker": track})
if options["subject_name"] == "generation":
generateStimuli(options, phase)
else:
if not os.path.exists(res_filename):
expe, options = buildConditions(options)
else:
mat = loadmat(options["res_filename"])
expe = mat["expe"]
options = mat["options"]
robot(expe, options, phase, language, ip, port)
if __name__ == "__main__":
options = {}
options["experiment_begin"] = 1
main(options, "generation", "test", "nl")
Whitespace-only changes.