def pause(): """Pause a running experiment. This will show a pause screen and waits for ENTER to be pressed to continue. """ if not expyriment._active_exp.is_initialized: raise Exception("Experiment is not initialized!") experiment = expyriment._active_exp experiment._event_file_log("Experiment,paused") screen_colour = experiment.screen.colour experiment._screen.colour = [0, 0, 0] old_logging = experiment.log_level experiment.set_log_level(0) if android is not None: position = (0, 200) else: position = (0, 0) stimuli.TextLine("Paused", position=position, text_colour=misc.constants.C_EXPYRIMENT_ORANGE, text_size=24).present() experiment.set_log_level(old_logging) experiment._screen.colour = screen_colour stimuli._stimulus.Stimulus._id_counter -= 1 misc.Clock().wait(200) if android is None: experiment.keyboard.wait() else: experiment.mouse.wait_press() experiment._event_file_log("Experiment,resumed")
def __init__(self, screen_refresh_interval_indicator, screen_refresh_interval_plotter, recorder, remote_control, level_detection_parameter, data_min_max, plotter_pixel_min_max, indicator_pixel_min_max, screen_size, plot_axis): self.screen_refresh_interval_indicator = screen_refresh_interval_indicator self.screen_refresh_interval_plotter = screen_refresh_interval_plotter self.plot_axis = plot_axis self.recorder = recorder self.remote_control = remote_control self.level_detection_parameter = level_detection_parameter self.background = RecordingScreen(window_size=screen_size, filename=recorder.filename, remote_control=remote_control) self.scaling_plotter = Scaling(min=data_min_max[0], max=data_min_max[1], pixel_min=plotter_pixel_min_max[0], pixel_max=plotter_pixel_min_max[1]) self.scaling_indicator = Scaling(min=data_min_max[0], max=data_min_max[1], pixel_min=indicator_pixel_min_max[0], pixel_max=indicator_pixel_min_max[1]) self.sensor_processes = recorder.force_sensor_processes self.n_sensors = len(self.sensor_processes) self.history = [] for _ in range(self.n_sensors): self.history.append( SensorHistory(history_size=config.moving_average_size, number_of_parameter=3)) self._start_recording_time = 0 self.pause_recording = True self.quit_recording = False self.clear_screen = True self.thresholds = None self.set_marker = False self.last_udp_data = None self._last_processed_smpl = [0] * self.n_sensors self._last_recording_status = None self._last_thresholds = None self._clock = misc.Clock() self.sensor_info_str = "" for tmp in self.recorder.sensor_settings_list: self.sensor_info_str = self.sensor_info_str + \ "{0}: {1}\n".format(tmp.device_name, tmp.sensor_name) self.sensor_info_str = self.sensor_info_str.strip() self.plot_indicator = True self.plot_filtered = False if self.n_sensors == 1: self.plot_data_indicator = config.plot_data_indicator_for_single_sensor self.plot_data_plotter = config.plot_data_plotter_for_single_sensor else: self.plot_data_indicator = config.plot_data_indicator_for_two_sensors self.plot_data_plotter = config.plot_data_plotter_for_two_sensors # plot data parameter names self.plot_data_indicator_names = [] for x in self.plot_data_indicator: self.plot_data_indicator_names.append(self.recorder.sensor_settings_list[x[0]].device_name +\ "_" + ForceData.forces_names[ x[1]]) self.plot_data_plotter_names = [] for x in self.plot_data_plotter: self.plot_data_plotter_names.append( str(x[0]) + "_" + ForceData.forces_names[x[1]])
control.defaults.audiosystem_buffer_size = 256 control.initialize(exp) ## bs = stimuli.BlankScreen() square_top = stimuli.Rectangle((400, 400), position=(0, 300)) tone = stimuli.Tone(TONE_DURATION, 440) bs.preload() square_top.preload() tone.preload() ## control.start(skip_ready_screen=True) clock = misc.Clock() exp.screen.clear() bs.present(update=True) nframe = 0 t1 = clock.time while clock.time - t1 <= 1000: bs.present(update=True) nframe += 1 FPS = nframe frame = stimuli.Canvas((800, 800)) msg = stimuli.TextScreen("", f"""This script displays a white rectangle, plays a tone and clears the screen, in a loop.
def initialize(experiment=None): """Initialize an experiment. This initializes an experiment defined by 'experiment' as well as the underlying expyriment system. If 'experiment' is None, a new Experiment object will be created and returned. Furthermore, a screen, a clock, a keyboard and a event file are created and added to the experiment. The initialization screen is shown for a short delay to ensure that Python is fully initialized and time accurate. Afterwards, "Preparing experiment..." is presented on the screen. After experiment initialize the following additional properties are available: - experiment.screen -- the current screen - experiment.clock -- the main clock - experiment.keyboard -- the main keyboard - experiment.mouse -- the main mouse - experiment.event -- the main event file Parameters ---------- experiment : design.Experiment, optional the experiment to initialize Returns ------- exp : design.Experiment initialized experiment """ if experiment is None: experiment = design.Experiment() if experiment.log_level is None: experiment.set_log_level(defaults.event_logging) if is_interactive_mode() and not expyriment.control.defaults.window_mode \ and not hasattr(experiment, "testsuite"): print """ Python is running in an interactive shell but Expyriment wants to initialize a fullscreen.""" quest = "Do you want to switch to windows mode?" ans = raw_input(quest + " (Y/n) ").strip().lower() if ans == "" or ans == "y" or ans == "yes": print "Switched to windows mode" expyriment.control.defaults.window_mode = True stdout_logging = defaults.stdout_logging expyriment._active_exp = experiment old_logging = experiment.log_level experiment.set_log_level(0) # switch off for the first screens _keyboard.quit_key = defaults.quit_key _keyboard.pause_key = defaults.pause_key _keyboard.refresh_key = defaults.refresh_key _keyboard.end_function = end _keyboard.pause_function = pause mixer.pre_init(defaults.audiosystem_sample_rate, defaults.audiosystem_bit_depth, defaults.audiosystem_channels, defaults.audiosystem_buffer_size) if defaults.audiosystem_autostart: mixer.init() mixer.init() # Needed on some systems experiment._clock = misc.Clock() experiment._screen = Screen(colour=(0, 0, 0), open_gl=defaults.open_gl, window_mode=defaults.window_mode, window_size=defaults.window_size) # Hack for IDLE: quit pygame and call atexit functions when crashing if is_idle_running() and sys.argv[0] != "": try: import idlelib.run def wrap(orig_func): def newfunc(*a, **kw): pygame.quit() import atexit atexit._run_exitfuncs() idlelib.run.flush_stdout = orig_func return orig_func(*a, **kw) return newfunc idlelib.run.flush_stdout = wrap(idlelib.run.flush_stdout) except ImportError: pass experiment._data = None experiment._subject = None experiment._is_initialized = True # required before EventFile if old_logging > 0: experiment._events = EventFile( additional_suffix=experiment.filename_suffix, time_stamp=True) if stdout_logging: _set_stdout_logging(experiment._events) else: experiment._events = None experiment._keyboard = Keyboard() experiment._mouse = Mouse(show_cursor=False) logo = stimuli.Picture(misc.constants.EXPYRIMENT_LOGO_FILE, position=(0, 100)) logo.scale((0.7, 0.7)) text = stimuli.TextLine("Version {0}".format(expyriment.get_version()), text_size=14, text_colour=misc.constants.C_EXPYRIMENT_ORANGE, background_colour=(0, 0, 0), position=(0, 40)) canvas = stimuli.Canvas((600, 300), colour=(0, 0, 0)) canvas2 = stimuli.Canvas((600, 300), colour=(0, 0, 0)) logo.plot(canvas) text.plot(canvas) hash_ = expyriment.get_experiment_secure_hash() if hash_ is not None: txt = "{0} ({1})".format(os.path.split(sys.argv[0])[1], hash_) if len(expyriment._secure_hash.module_hashes_as_string()) > 0: txt += ", {0}".format( expyriment._secure_hash.module_hashes_as_string()) text2 = stimuli.TextLine( txt, text_size=14, text_colour=misc.constants.C_EXPYRIMENT_ORANGE, background_colour=(0, 0, 0), position=(0, 10)) text2.plot(canvas) canvas.preload(True) canvas._set_surface(canvas._get_surface().convert()) start = experiment.clock.time r = [x for x in range(256) if x % 5 == 0] stopped = False if defaults.initialize_delay > 0: for x in r: canvas._get_surface().set_alpha(x) canvas2.clear_surface() canvas.plot(canvas2) canvas2.present() experiment.clock.wait(1) key = experiment.keyboard.check(pygame.K_ESCAPE, check_for_control_keys=False) if key is not None: stopped = True break duration = experiment.clock.time - start if duration < 2000 and not stopped: start = experiment.clock.time while experiment.clock.time - start < 2000: key = experiment.keyboard.check(pygame.K_ESCAPE, check_for_control_keys=False) if key is not None: stopped = True break r = [x for x in range(256)[::-1] if x % 5 == 0] if not stopped: for x in r: canvas._get_surface().set_alpha(x) canvas2.clear_surface() canvas.plot(canvas2) canvas2.present() experiment.clock.wait(1) key = experiment.keyboard.check(pygame.K_ESCAPE, check_for_control_keys=False) if key is not None: break stimuli.TextLine("Preparing experiment...", text_size=24, text_colour=misc.constants.C_EXPYRIMENT_PURPLE).present() experiment._screen.colour = experiment.background_colour experiment.set_log_level(old_logging) stimuli._stimulus.Stimulus._id_counter = 0 return experiment
def end(goodbye_text=None, goodbye_delay=None, confirmation=False, fast_quit=None, system_exit=False): """End expyriment. Parameters ---------- goodbye_text : str, optional text to present on the screen when quitting goodbye_delay : int, optional period to show the goodbye_text confirmation : bool, optional ask for confirmation (default = False) fast_quit : bool, optional quit faster by hiding the screen before actually quitting (default = None) system_exit : bool, optional call Python's sys.exit() method when ending expyriment (default = False) Returns ------- out : bool True if Expyriment (incl. Pygame) has been quit. """ if not expyriment._active_exp.is_initialized: pygame.quit() if system_exit: sys.exit() return True experiment = expyriment._active_exp if confirmation: experiment._event_file_log("Experiment,paused") screen_colour = experiment.screen.colour experiment._screen.colour = [0, 0, 0] if android is not None: position = (0, 200) else: position = (0, 0) stimuli.TextLine("Quitting Experiment? (y/n)", position=position, text_colour=misc.constants.C_EXPYRIMENT_ORANGE, text_size=24).present() stimuli._stimulus.Stimulus._id_counter -= 1 char = Keyboard().wait_char(["y", "n"], check_for_control_keys=False) if char[0] == "n": experiment._screen.colour = screen_colour experiment._event_file_log("Experiment,resumed") return False experiment._event_file_log("Experiment,ended") if goodbye_text is None: goodbye_text = defaults.goodbye_text if goodbye_delay is None: goodbye_delay = defaults.goodbye_delay if experiment.events is not None: experiment.events.save() if experiment.data is not None: experiment.data.save() if fast_quit is None: fast_quit = defaults.fast_quit if fast_quit and experiment.is_started: if experiment.screen.window_mode: pygame.display.set_mode(experiment.screen._window_size) pygame.display.iconify() try: experiment._screen.colour = [0, 0, 0] stimuli.TextLine(goodbye_text, position=(0, 0), text_colour=misc.constants.C_EXPYRIMENT_PURPLE, text_size=24).present() stimuli._stimulus.Stimulus._id_counter -= 1 except: pass if not fast_quit: misc.Clock().wait(goodbye_delay) expyriment._active_exp = design.Experiment("None") pygame.quit() return True
(c) O. Lindemann for two sensor setups """ from expyriment import misc, control, stimuli, io from . import remote_control as rc FORCE_SERVER_IP = "192.168.1.2" WEAK, FINE, STRONG = [0, 1, 2] STR_FULL_FORCE = u"kräftig" STR_LESS_FORCE = u"sacht" stopwatch = misc.Clock() udp = rc.init_udp_connection() print udp def runtimeerror(exp, text): stimuli.TextScreen("ERROR", text).present() exp.keyboard.wait() control.end() udp.send(rc.Command.QUIT) exit() def start(exp, time_for_feedback=10): """ returns true if feedback is OK waits a particular time (in sec) for feedback and
def record_data(remote_control, recording_screen): if trakstar is None or exp is None: raise RuntimeError("Pytrak not initialized") refresh_interval = 50 refresh_timer = misc.Clock() history = SensorHistory(history_size = 10, number_of_parameter=3) # TODO: set history size recording_screen.stimulus().present() #start trakstar thread trakstar_thread = TrakSTARRecordingThread(trakstar) trakstar_thread.start() # start plotter threads plotter = PlotterXYZ(attached_sensors=trakstar.attached_sensors, expyriment_screen_size=exp.screen.size, refresh_time = 0.02) plotter.start() exp.keyboard.clear() trakstar_thread.start_recording() quit_recording = False set_marker = False was_moving = None was_inside = None detection_sensor_id = 1 # TODO: which sensor? while not quit_recording: # process keyboard key = exp.keyboard.check(check_for_control_keys=False) command_array = [process_key_input(key)] # get data and process data_array = trakstar_thread.get_data_array() for data in data_array: if data.has_key(detection_sensor_id): history.update(data[detection_sensor_id][:3]) ## movement detection # move = history.is_moving(velocity_threshold=4, # min_n_samples=10, # sampling_rate=80) # TODO settings! #if move is not None and move != was_moving: # set_marker = True # was_moving = move # if remote_control: # output # if move: # udp_connection.send("M_START") # else: # udp_connection.send("M_STOP") # position detection inside = history.is_in_reference_area() if inside is not None and inside != was_inside: set_marker = True was_inside = inside if remote_control: # output if inside: udp_connection.send("D_INSIDE") else: udp_connection.send("D_OUTSIDE") if len(data['udp']) > 0: set_marker = True plotter.add_values(data, set_marker=set_marker) set_marker = False if remote_control: # input command_array.append(process_udp_input(data['udp'])) # refresh screen once in a while if refresh_timer.stopwatch_time >=refresh_interval: refresh_timer.reset_stopwatch() if trakstar_thread.is_recording: plotter.update() else: recording_screen.stimulus("Paused recording").present() # process commands of last loop (ignore Nones) for command in filter(lambda x:x is not None, command_array): if command == Command.quit: quit_recording = True break elif command == Command.toggle_pause: if trakstar_thread.is_recording: trakstar_thread.pause_recording() else: recording_screen.stimulus().present() trakstar_thread.start_recording() elif command == Command.increase_scaling: plotter.scaling += 0.01 elif command == Command.decrease_scaling: plotter.scaling -= 0.01 elif command == Command.normalize_plotting: plotter.reset_start_values() elif command == Command.set_reference_position: print "set reference point" history.set_reference_area(radius= 10) # TODO settings elif command == Command.set_marker: set_marker = True plotter.stop() trakstar_thread.stop()