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.
+187
View File
@@ -0,0 +1,187 @@
# --------------------------------------------------------------------------
# Authors:
# ------ MATlAB ------
# Paolo Toffanin <p.toffanin@umcg.nl>, RuG, UMCG, Groningen, NL
# Jacqueline Libert
# Leanne Nagels < leanne.nagels@rug.nl >
# Etienne Gaudrain <etienne.gaudrain@cnrs.fr> - 2017-12-05
# CNRS, CRNL, Lyon, FR | RuG, UMCG, Groningen, NL
# ------ Python ------
# 2020-04-13: 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 numpy as np
from scipy import io as sio
import warnings
import os
import re
from tools.load_matrix import loadmat
def expe_build_conditions(options):
'''
Creates the EXPE structure that contains the trials for the PICKA
Emotion experiment.
Note: the emotion names listed in options[test][emotions] must coincide
with the file names of the sound material, as well as with the file
names of the sprite images.
'''
# options["sound_folder"] = "./stimuli/emotion/en"
options["sound_folder"] = "./stimuli/emotion/"
options["sound_filemask"] = ".wav"
mat = loadmat('./calibration.mat')
cal = mat["calibration"]
options["attenuation_dB"] = cal["emotion"]
# Parse the corpus
options = parse_corpus(options)
# Select emotions for test
options["test"]["emotions"] = ['angry', 'sad', 'happy']
options["order_button_emotions"] = np.random.permutation(
options["test"]["emotions"])
# Select emotions for training
options["training"]["emotions"] = ['angry', 'sad', 'happy']
options["order_button_emotions"] = np.random.permutation(
options["training"]["emotions"])
for e in range(len(options["test"]["emotions"])):
if options["test"]["emotions"][e] not in options["test"]["corpus"]:
raise ValueError("Emotion '{}' was not found in the selected corpus...".format(
options["test"]["emotions"][e]))
# Number of repetitions per emotion
options["test"]["n_repeat"] = float("Inf")
# === Create the test trials ===
test = {}
for i_emotion in range(len(options["test"]["emotions"])):
emotion = options["test"]["emotions"][i_emotion]
n = len(options["test"]["corpus"][emotion])
if np.isinf(options["test"]["n_repeat"]):
item_order = np.array(range(0, n))
else:
item_order = []
while len(item_order) < options["test"]["n_repeat"]:
item_order.append(np.random.permutation(
np.min([options["test"]["n_repeat"], n])))
for ir in range(int(np.min([options["test"]["n_repeat"], len(item_order)]))):
trial = options["test"]["corpus"][emotion][item_order[ir]]
trial["emotion"] = emotion
trial["i_repeat"] = ir
trial["done"] = 0
if not "trials" in test:
test["trials"] = [trial]
else:
test["trials"].append(trial)
expe = {}
expe["test"] = {}
expe["test"]["trials"] = np.random.permutation(test["trials"])
# === Create the training trials ===
training = {}
for i_trial in range(len(options["training"]["corpus"])):
trial = options["training"]["corpus"][i_trial]
trial["done"] = 0
if not "trials" in training:
training["trials"] = [trial]
else:
training["trials"].append(trial)
expe["training"] = {}
expe["training"]["trials"] = np.random.permutation(training["trials"])
if "res_filename" in options:
sio.savemat(options["res_filename"], mdict={
'expe': expe, 'options': options})
else:
warnings.warn("The test file was not saved: no filename provided.")
return expe, options
def parse_corpus(options):
options["sounds_for_calibration"] = {}
if not "test" in options:
options["test"] = {}
if not "training" in options:
options["training"] = {}
options["test"]["corpus"] = {}
lst = [f for f in os.listdir(os.path.join(
options["sound_folder"])) if f.endswith(options["sound_filemask"])]
for k in range(len(lst)):
options["sounds_for_calibration"][k] = os.path.join(
options["sound_folder"], lst[k])
_, fname = os.path.split(lst[k])
tokens = re.split("[" + re.escape("_") + "]", fname)
if tokens[0] == "training":
item = {}
item["file"] = lst[k]
item["talker"] = float(tokens[1][1:])
item["emotion"] = tokens[2]
item["sentence"] = float(tokens[3][1:])
item["utterance"] = float(tokens[4][1:].split(".")[0])
if not "corpus" in options["training"]:
options["training"]["corpus"] = [item]
else:
options["training"]["corpus"].append(item)
else:
item = {}
item["file"] = lst[k]
item["talker"] = float(tokens[0][1:])
emotion = tokens[1]
item["sentence"] = float(tokens[2][1:])
item["utterance"] = float(tokens[3][1:].split(".")[0])
if not emotion in options["test"]["corpus"]:
options["test"]["corpus"][emotion] = [item]
else:
options["test"]["corpus"][emotion].append(item)
return options
def explode(sep, string):
rem = string
table = []
while rem:
tokens = re.split("[" + re.escape(sep) + "]", rem)
token = tokens[0]
rem = sep.join(tokens[1:])
table.append(token)
return table
+49
View File
@@ -0,0 +1,49 @@
# --------------------------------------------------------------------------
# Authors:
# ------ MATlAB ------
# Paolo Toffanin <p.toffanin@umcg.nl>, RuG, UMCG, Groningen, NL
# Jacqueline Libert
# Leanne Nagels < leanne.nagels@rug.nl >
# Etienne Gaudrain <etienne.gaudrain@cnrs.fr> - 2017-12-05
# CNRS, CRNL, Lyon, FR | RuG, UMCG, Groningen, NL
# ------ Python ------
# 2020-04-13: 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):
options["result_path"] = "./results/" + options["subject_name"]
if not os.path.exists(options["result_path"]):
os.mkdir(options["result_path"])
# result prefix
options["result_prefix"] = "emo_"
# label
options["experiment_label"] = "PICKA :: Emotion"
# options["subject_age"] = subject["age"]
# options["subject_sex"] = subject["sex"]
options["res_filename"] = os.path.join(options["result_path"], "{}{}_{}_robot.mat".format(
options["result_prefix"], options["language"].lower(), options["subject_name"]))
options["experiment_begin"] = 1
return options
+169
View File
@@ -0,0 +1,169 @@
# --------------------------------------------------------------------------
# Authors:
# ------ MATlAB ------
# Paolo Toffanin <p.toffanin@umcg.nl>, RuG, UMCG, Groningen, NL
# Jacqueline Libert
# Leanne Nagels < leanne.nagels@rug.nl >
# Etienne Gaudrain <etienne.gaudrain@cnrs.fr> - 2017-12-05
# CNRS, CRNL, Lyon, FR | RuG, UMCG, Groningen, NL
# ------ Python ------
# 2020-04-13: 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
import numpy as np
import soundfile as sf
import datetime
import time
from Robot.RobotEmotion import RobotEmotion
from tools.load_matrix import loadmat
from scipy import io as sio
def robot(ip, port, lang, options, phase):
# -- Start an instance of SAM
sam = RobotEmotion(ip, port, lang)
# -- Set initial volume
# NAO
simulateSubj = False
if options["subject_name"] == "test":
simulateSubj = True
# Create the result dictionary and load the subject's results/options file
results = {}
mat_contents = loadmat(options["res_filename"])
expe = mat_contents['expe']
options = mat_contents['options']
track = loadmat(options["res_tracker"])
exp = track["tracker"]
if not "gain" in options:
options["gain"] = 0
# === Main Loop ===
ladderstep = 1
starting = 1
itrial_session = 0
done = []
# === Main Loop that runs experiment ===
while np.mean(done) != 1:
# Reintialises the done array and reappend for when a task has been completed
done = []
for i in range(len(expe[phase]["trials"])):
done.append(expe[phase]["trials"][i]["done"])
try:
i_trial = done.index(0)
itrial_session = itrial_session + 1
except ValueError:
break
print "Trial {} of {}".format(itrial_session, len(done) + 1)
if exp["experiment_begin"]:
# NAO
sam.intro()
exp["experiment_begin"] = 0
sio.savemat(options["res_tracker"], mdict={"tracker": exp})
if starting:
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:
# NAO
sam.emotionIntro()
pass
sam.game_break()
starting = 0
trial = expe[phase]["trials"][i_trial]
# y, fs = sf.read(os.path.join(options["sound_folder"], trial["file"]))
os.chdir(options["sound_folder"])
x, fs = sf.read(trial["file"])
x = x * 10.0 ** options["attenuation_dB"]/20
sf.write('./gen_stimulus.wav', x, fs)
# NAO
sam.aad.setOutputVolume(sam.stimulus_volume)
sam.play_sounds('gen_stimulus.wav', lang)
sam.aad.setOutputVolume(sam.speaking_volume)
os.remove('./gen_stimulus.wav')
os.chdir('../../')
tic = time.time()
response = {}
response["trial"] = trial
if simulateSubj:
# response["timestamp"] = datetime.datetime.now()
response["response_time(ms)"] = round((time.time() - tic)*100, 2)
response["emotion"] = options[phase]["emotions"][np.random.randint(
len(options[phase]["emotions"]))]
response["correct"] = response["emotion"] == trial["emotion"]
else:
response["timestamp"] = datetime.datetime.now()
response["emotion"] = sam.answer(trial["emotion"], 1)
response["response_time"] = round((time.time() - tic)*100, 2)
response["correct"] = response["emotion"] == trial["emotion"]
print("Clicked button: {}\n".format(response["emotion"]))
print("Response time: {} ms\n".format(
round(response["response_time"] * 1000)))
print("Response correct: {} \n\n".format(response["correct"]))
expe[phase]["trials"][i_trial]["done"] = 1
if not phase in results:
results[phase] = {}
results[phase]["responses"] = [response]
else:
results[phase]["responses"].append(response)
sio.savemat(options["res_filename"], mdict={
"options": options, "expe": expe, "results": results})
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"]["emotion"] = 1
sio.savemat(options["res_tracker"], mdict={"tracker": exp})
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.")
exp_tracker = np.array([exp["experiments"][key]
for key in exp["experiments"].keys()])
if np.mean(exp_tracker) == 1:
sam.ending()
+95
View File
@@ -0,0 +1,95 @@
# --------------------------------------------------------------------------
# Authors:
# ------ MATlAB ------
# Paolo Toffanin <p.toffanin@umcg.nl>, RuG, UMCG, Groningen, NL
# Jacqueline Libert
# Leanne Nagels < leanne.nagels@rug.nl >
# Etienne Gaudrain <etienne.gaudrain@cnrs.fr> - 2017-12-05
# CNRS, CRNL, Lyon, FR | RuG, UMCG, Groningen, NL
# ------ Python ------
# 2020-04-13: 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
import sys
from scipy.io import savemat
from emotion_options import expe_options as emotion_options
from emotion_build_conditions import expe_build_conditions as build_conditions
from emotion_robot import robot
def main(options, subject, phase, lang, p_exists, ip, port):
options = {}
options["subject_name"] = subject
options["language"] = lang
options = emotion_options(options)
if p_exists is not None:
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 p_exists:
build_conditions(options)
else:
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(options["res_filename"]):
msg = "The subject '{}' does not exist. Create it?".format(
options["subject_name"])
print msg
ans = raw_input("(Y/n): ")
if ans.lower() == 'y':
build_conditions(options)
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): ")
if ans.lower() == 'n':
sys.exit()
robot(ip, port, lang, options, phase)