# -------------------------------------------------------------------------- # Authors: # ------ MATlAB ------ # 2013-02-24: Etienne Gaudrain # 2017-03-29: Etienne Gaudrain # ------ 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