import os import sys import pandas as pd import numpy as np from load_matrix import loadmat def main(game, path, lang, age, des): os.chdir(path) if game == "fishy": export_jnd(lang, age, des) elif game == "gender": export_gender(lang, age, des) elif game == "emotion": export_emotion(lang, age, des) elif game == "crm": export_crm(lang, age, des) def export_jnd(lang, age, des): res_path = "./" output_path = des export_filename = os.path.join( output_path, "JND_" + lang + "_" + age + ".csv") table = pd.DataFrame(columns=["subject", "ref_f0", "dir_f0", "ref_ser", "dir_ser", "ref_voice", "dir_voice", "threshold", "threshold_f0", "threshold_vtl", "sd", "response_datetime"]) for d in os.listdir(res_path): if d.startswith("NH" + age): subject_dir = os.path.join(res_path, d) f = os.path.join(subject_dir, "jnd_" + lang.lower() + "_" + d + "_robot.mat") try: mat = loadmat(f) results = mat["results"] options = mat["options"] for i in range(0, len(results["test"]["conditions"])): responses = {} att = {} try: att = results["test"]["conditions"]["c" + str(i)]["att"] responses = att["responses"] resp = responses["r" + str(len(responses)-1)] except (KeyError, TypeError): att = results["test"]["conditions"]["c" + str(i)]["att"][0] responses = att["responses"] resp = responses[len(responses)-1] subject = options["subject_name"] trial = resp["trial"] u_f0 = 12 * np.log2(options["test"]["voices"]['v' + str(trial["dir_voice"])] ["f0"] / options["test"]["voices"]['v' + str(trial["ref_voice"])]["f0"]) u_ser = 12 * np.log2(options["test"]["voices"]['v' + str(trial["dir_voice"])] ["ser"] / options["test"]["voices"]['v' + str(trial["ref_voice"])]["ser"]) u = np.array([u_f0, u_ser]) u = u / np.sqrt(np.sum(np.power(u, 2))) ex = { "subject": subject, "ref_f0": options["test"]["voices"]["v" + str(trial["ref_voice"])]["f0"], "dir_f0": options["test"]["voices"]["v" + str(trial["dir_voice"])]["f0"], "ref_ser": options["test"]["voices"]["v" + str(trial["ref_voice"])]["ser"], "dir_ser": options["test"]["voices"]["v" + str(trial["dir_voice"])]["ser"], "ref_voice": options["test"]["voices"]["v" + str(trial["ref_voice"])]["label"], "dir_voice": options["test"]["voices"]["v" + str(trial["dir_voice"])]["label"], "threshold": att["threshold"], "threshold_f0": att["threshold"] * u[0], "threshold_vtl": att["threshold"] * u[1], "sd": att["sd"], "response_datetime": resp["timestamp"], } table = table.append(ex, True) except (KeyError, IOError) as e: print e print "Could not retrieve necessary matrices. \n Skipping participant: " + d table.to_csv(export_filename) def export_gender(lang, age, des): res_path = "./" output_path = des export_filename = os.path.join( output_path, "Gender_" + lang + "_" + age + ".csv") table = pd.DataFrame(columns=["subject", "df0", "dvtl", "word", "answer", "gender", "response_datetime", "response_time"]) for d in os.listdir(res_path): if d.startswith("NH" + age): subject_dir = os.path.join(res_path, d) f = os.path.join(subject_dir, "gen_" + lang.lower() + "_" + d + "_robot.mat") try: mat = loadmat(f) results = mat["results"] options = mat["options"] gen_responses = mat["gender_response"] resp = {} i = 1 for r in results["test"]["responses"]: subject = options["subject_name"] try: trial = r["trial"] if "trial " in list(gen_responses["test"].keys())[0]: gen_trial = gen_responses["test"]["trial " + str(i)] elif "trial_" in list(gen_responses["test"].keys())[0]: gen_trial = gen_responses["test"]["trial_" + str(i)] resp = r resp_ans = r["response_answer"] except TypeError: resp = results["test"]["responses"][r] if "trial " in list(gen_responses["test"].keys())[0]: gen_trial = gen_responses["test"]["trial " + str(int(r[1:])+1)] elif "trial_" in list(gen_responses["test"].keys())[0]: gen_trial = gen_responses["test"]["trial_" + str(int(r[1:])+1)] trial = resp["trial"] resp_ans = resp["response_answer"] ex = { "subject": subject, "df0": gen_trial["f0(st)"], "dvtl": gen_trial["VTL(st)"], "word": trial["word"], "answer": resp_ans["answer"], "gender": gen_trial["answer"], "is_female": 1 if gen_trial["answer"] == "Girl" else 0, "response_datetime": resp["timestamp"], "response_time": resp["response_time"], } table = table.append(ex, True) i += 1 except (KeyError, IOError) as e: print e print "Could not retrieve necessary matrices. \n Skipping participant: " + d table.to_csv(export_filename) def export_emotion(lang, age, des): res_path = './' output_path = des export_filename = os.path.join( output_path, "Emotion_" + lang + "_" + age + ".csv") table = pd.DataFrame(columns=[ "subject", "emotion", "file", "utterance", "talker", "sentence", "correct", "response_time"]) for d in os.listdir(res_path): if d.startswith("NH" + age): subject_dir = os.path.join(res_path, d) f = os.path.join(subject_dir, "emo_" + lang.lower() + "_" + d + "_robot.mat") try: mat = loadmat(f) results = mat["results"] options = mat["options"] resp = {} for r in results["test"]["responses"]: subject = options["subject_name"] try: trial = r["trial"] resp = r except TypeError: resp = results["test"]["responses"][r] trial = resp["trial"] ex = { "subject": subject, "emotion": trial["emotion"], "file": trial["file"], "utterance": trial["utterance"], "talker": trial["talker"], "sentence": trial["sentence"], "correct": resp["correct"], "response_time": resp["response_time"], } table = table.append(ex, True) except (KeyError, IOError) as e: print e print "Could not retrieve necessary matrices. \n Skipping participant: " + d table.to_csv(export_filename) def export_crm(lang, age, des): res_path = './' output_path = des export_filename = os.path.join( output_path, "CRM_" + lang + "_" + age + ".csv") table = pd.DataFrame(columns=[ "subject", "correct", "colour", "number", "call_sign", "sound_file", "dF0", "dVTL", "tmr", "response_time"]) for d in os.listdir(res_path): if d.startswith("NH" + age): subject_dir = os.path.join(res_path, d) f = os.path.join(subject_dir, "crm_" + lang.lower() + "_" + d + "_robot.mat") try: mat = loadmat(f) results = mat["results"] options = mat["options"] resp = {} for r in results["test"]["responses"]: subject = options["subject_name"] try: trial = r["trial"] resp = r except TypeError: resp = results["test"]["responses"][r] trial = resp["trial"] ex = { "subject": subject, "correct": resp["correct"], "colour": trial["target"]["colour"], "number": trial["target"]["number"], "call_sign": trial["target"]["call_sign"], "sound_file": trial["target"]["sound_file"], "dF0": trial["voice"]["dF0"], "dVTL": trial["voice"]["dVTL"], "tmr": trial["tmr"], "response_time": resp["response_time"] } table = table.append(ex, True) except (KeyError, IOError) as e: print e print "Could not retrieve necessary matrices. Skipping participant: " + d table.to_csv(export_filename) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description="The main script used to run SAM", epilog="Written by Luke Meyer , adapted from MATLAB script by Etienne Gaudrain \nCopyright 2017 CNRS (FR), UMCG (NL)", formatter_class=argparse.RawDescriptionHelpFormatter) # parser.add_argument( # '-f', '--file', help="Path to results file", required=True) # parser.add_argument( # '-pp', '--port', help="Port that SAM has open for connection.", default=9559, type=int) parser.add_argument( '-g', '--game', help="The game for the current experiment.", choices=["gender", "fishy", "emotion", "crm"], required=True) # parser.add_argument('--version', help="Displays current version", # action='version', version='Version = {}'.format(VERSION)) parser.add_argument( '-p', '--path', help="Path to results folder if not in current directory, INCLUDING ./results. Please use absolute path.", default='./') parser.add_argument( '-a', '--age', help="Age group to be exported.", default="A", choices=["A", "K"], required=True) parser.add_argument( '-l', '--lang', help="Experiment language to be exported.", default="EN", choices=["EN", "NL"], required=True) parser.add_argument('-d', '--destination', help="Path to destination of exported results.", default="./", required=True) args = parser.parse_args() # mat = loadmat(args.file) # options = mat["options"] # results = mat["results"] # os.chdir("/home/nao/Documents/Sam_files/Python_scripts") main(args.game, args.path, args.lang, args.age, args.destination)