import numpy as np import soundfile as sf import time import datetime import sys import os import cPickle as pickle from tools.load_matrix import loadmat from scipy.io import savemat from Robot.RobotCRM import RobotCRM from crm_make_stimulus import makeStim def robot(ip, port, lang, options, phase): results = {} sam = RobotCRM(ip, port, lang, options["subject_name"]) try: saveFromPickle(options) except IOError: pass mat = loadmat(options["res_filename"]) expe = mat["expe"] options = mat["options"] if "results" in mat: results = mat["results"] track = loadmat(options["res_tracker"]) exp = track["tracker"] nbreak = 0 starting = 1 simulate = False done = [] while np.mean(done) != 1: done = [] for i in range(len(expe[phase]["trials"])): done.append(expe[phase]["trials"][i]["done"]) nbreak += 1 if nbreak > options[phase]["block_size"]: nbreak = 0 # TODO: Something to add a break. try: i_trial = done.index(0) except ValueError: break track_trial = i_trial + 1 if exp["experiment_begin"]: trials = { "current_trial": track_trial, "total_trials": len(expe[phase]["trials"]) } with open('./crm/trials.p', 'wb') as f: pickle.dump(trials, f) time.sleep(5) # sam.intro() exp["experiment_begin"] = 0 savemat(options["res_tracker"], mdict={"tracker": exp}) if starting: trials = { "current_trial": track_trial, "total_trials": len(expe[phase]["trials"]) } with open('./crm/trials.p', 'wb') as f: pickle.dump(trials, f) if phase == "test": if lang == "EN": sam.simple_say("Welcome to the testing phase of the game.") elif lang == "NL": sam.simple_say( "Welkom bij de testronde van dit spelletje.") else: # sam.crmIntro() pass # sam.crmIntro() sam.game_break() if phase == "test" and i_trial == np.round(len(done) / 2): if lang == "EN": sam.simple_say("You've reached halfway.") if lang == "NL": sam.simple_say("") sam.take_break() starting = 0 # for i in range(len(expe[phase]["trials"])): # done.append(expe[phase]["trials"][i]["done"]) # nbreak += 1 # if nbreak > options[phase]["block_size"]: # nbreak = 0 # # TODO: Something to add a break. # try: # i_trial = done.index(0) # except ValueError: # break trial = expe[phase]["trials"][i_trial] xOut, fs, info = makeStim(options, trial) # xOut = xOut*np.power(10, options["attenuation_dB"]/20) xOut = xOut * 10.0**(options["attenuation_dB"] / 20) m = np.max(np.abs(xOut)) if m > .98: xOut = xOut / m * .98 print "xOut was rescaled to avoid clipping by a factor %.2f" % ( 0.98 / m) sf.write('stimulus.wav', xOut, fs) correct_answer = { "colour": trial["target"]["colour"], "number": trial["target"]["number"] } # === Play stimulus then delete file sam.aad.setOutputVolume(sam.stimulus_volume) sam.play_sounds('stimulus.wav', lang) sam.aad.setOutputVolume(sam.speaking_volume) # os.remove('stimulus.wav) # === Get response response = {} response["timestamp"] = str(datetime.datetime.now()) if not simulate: resp, resp_time = sam.answer(correct_answer, trial["visual_feedback"], track_trial, len(expe[phase]["trials"])) else: resp = {"number": 4, "colour": "pink"} resp_time = 1.0 response["response_time(ms)"] = round(resp_time * 100, 2) # resp = correct_answer response["colour"] = resp["colour"] response["number"] = resp["number"] response["correct"] = response["colour"] == correct_answer[ "colour"] and response["number"] == correct_answer["number"] response["info"] = info response["trial"] = trial # === Save results if not phase in results: results[phase] = {} results[phase]["responses"] = np.array([response]) else: results[phase]["responses"] = np.append( results[phase]["responses"], response) expe[phase]["trials"][i_trial]["done"] = 1 a = time.time() pickle.dump( expe, open("{}/expe_temp.p".format(options["result_path"]), 'wb')) pickle.dump( options, open("{}/options_temp.p".format(options["result_path"]), 'wb')) pickle.dump( results, open("{}/results_temp.p".format(options["result_path"]), 'wb')) print "results saved: " + str(time.time() - a) if phase == "training": if lang == "EN": sam.simple_say("That's the end of the training phase.") elif lang == "NL": sam.simple_say("Dit is het einde van de oefenronde ") else: exp["experiments"]["crm"] = 1 savemat(options["res_tracker"], mdict={"tracker": exp}) if lang == "EN": sam.simple_say("That's the end of the testing phase. Well done.") elif lang == "NL": sam.simple_say("Dit is het einde van de test. Goed gedaan.") exp_tracker = np.array( [exp["experiments"][key] for key in exp["experiments"].keys()]) saveFromPickle(options) if np.mean(exp_tracker) == 1: sam.ending() # except: # saveFromPickle(options) # savemat(options["res_filename"], mdict={ # "expe": expe, "options": opt, "results": results}) def saveFromPickle(options): print "-------" print "Loading results" print "-------" try: expe = pickle.load( open("{}/expe_temp.p".format(options["result_path"]), 'rb')) opt = pickle.load( open("{}/options_temp.p".format(options["result_path"]), 'rb')) results = pickle.load( open("{}/results_temp.p".format(options["result_path"]), 'rb')) os.remove("{}/expe_temp.p".format(options["result_path"])) os.remove("{}/options_temp.p".format(options["result_path"])) os.remove("{}/results_temp.p".format(options["result_path"])) savemat(options["res_filename"], mdict={ "expe": expe, "options": opt, "results": results }) except Exception as e: print e return