Exemplo n.º 1
0
    def __init__(self, additional_suffix, directory=None, delimiter=None,
                 clock=None, time_stamp=None):
        """Create an event file.

        Filename: {MAINFILE_NAME}_{SUBJECT_ID}_{TIME_STAMP}{ADD_SUFFIX}.xpd

        Parameters
        ----------
        additional_suffix : str
            additional suffix
        directory : str, optional
            directory of the file
        delimiter : str, optional
            symbol between timestamp and event
        clock : expyriment.Clock, optional
            an experimental clock
        time_stamp : bool, optional
            using time stamps, based on the experiment start time,
            not the current time

        """

        if directory is None:
            directory = defaults.eventfile_directory
        if additional_suffix is None:
            additional_suffix = ''
        if len(additional_suffix) > 0:
            suffix = ".{0}{1}".format(additional_suffix, self._file_suffix)
        else:
            suffix = self._file_suffix
        OutputFile.__init__(self, suffix, directory, time_stamp=time_stamp)
        if delimiter is not None:
            self._delimiter = delimiter
        else:
            self._delimiter = defaults.eventfile_delimiter
        if clock is not None:
            self._clock = clock
        else:
            if not expyriment._active_exp.is_initialized:
                raise RuntimeError(
                    "Cannot find a clock. Initialize Expyriment!")
            self._clock = expyriment._active_exp.clock

        try:
            display = repr(expyriment._active_exp.screen.window_size)
            window_mode = repr(expyriment._active_exp.screen.window_mode)
            opengl = repr(expyriment._active_exp.screen.open_gl)
        except:
            display = "unknown"
            window_mode = "unknown"
            opengl = "unknown"

        self.write_comment("sha1: {0}".format(
                                    expyriment.get_experiment_secure_hash()))
        self.write_comment("display: size={0}, window_mode={1}, opengl={2}"
                           .format(display, window_mode, opengl))
        self.write_comment("os: {0}".format(uname()))

        self.write_line("Time,Type,Event,Value,Detail,Detail2")
        self.save()
Exemplo n.º 2
0
    def __init__(self, additional_suffix, directory=None, delimiter=None,
                 time_stamp=None):
        """Create a data file.

        Filename: {MAINFILE_NAME}_{SUBJECT_ID}_{TIME_STAMP}{ADD_SUFFIX}.xpd

        Parameters
        ----------
        additional_suffix : str
            additional suffix
        directory : str, optional
            directory of the file
        delimiter : str, optional
            symbol between variables
        time_stamp : bool, optional
            using time stamps, based on the experiment start time,
            not the current time

        """

        if expyriment._active_exp.is_initialized:
            self._subject = expyriment._active_exp.subject
        else:
            self._subject = None
        if directory is None:
            directory = defaults.datafile_directory
        if additional_suffix is None:
            additional_suffix = ''
        if len(additional_suffix) > 0:
            suffix = ".{0}{1}".format(additional_suffix, self._file_suffix)
        else:
            suffix = self._file_suffix
        OutputFile.__init__(self, suffix, directory, time_stamp=time_stamp)
        if delimiter is not None:
            self._delimiter = delimiter
        else:
            self._delimiter = defaults.datafile_delimiter

        self._subject_info = []
        self._experiment_info = []
        self._variable_names = []

        self.write_comment("--EXPERIMENT INFO")
        self.write_comment("e mainfile: {0}".format(os.path.split(
                                                    sys.argv[0])[1]))

        self.write_comment("e sha1: {0}".format(
                                    expyriment.get_experiment_secure_hash()))
        self.write_comment("e modules: {0}".format(
                            expyriment._secure_hash.module_hashes_as_string()))
        self.write_comment("--SUBJECT INFO")
        self.write_comment("s id: {0}".format(self._subject))
        self.write_line(self.variable_names)
        self._variable_names_changed = False
        self.save()
Exemplo n.º 3
0
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 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
Exemplo n.º 5
0
    def __init__(self, additional_suffix, directory=None, delimiter=None,
                 clock=None, time_stamp=None):
        """Create an event file.

        Filename: {MAINFILE_NAME}_{SUBJECT_ID}_{TIME_STAMP}{ADD_SUFFIX}.xpd

        Parameters
        ----------
        additional_suffix : str
            additional suffix
        directory : str, optional
            directory of the file
        delimiter : str, optional
            symbol between timestamp and event
        clock : expyriment.Clock, optional
            an experimental clock
        time_stamp : bool, optional
            using time stamps, based on the experiment start time,
            not the current time

        """

        if directory is None:
            directory = defaults.eventfile_directory
        if additional_suffix is None:
            additional_suffix = ''
        if len(additional_suffix) > 0:
            suffix = ".{0}{1}".format(additional_suffix, self._file_suffix)
        else:
            suffix = self._file_suffix
        OutputFile.__init__(self, suffix, directory, time_stamp=time_stamp)
        if delimiter is not None:
            self._delimiter = delimiter
        else:
            self._delimiter = defaults.eventfile_delimiter
        if clock is not None:
            self._clock = clock
        else:
            if not expyriment._active_exp.is_initialized:
                raise RuntimeError(
                    "Cannot find a clock. Initialize Expyriment!")
            self._clock = expyriment._active_exp.clock

        try:
            display = repr(expyriment._active_exp.screen.window_size)
            window_mode = repr(expyriment._active_exp.screen.window_mode)
            open_gl = repr(expyriment._active_exp.screen.open_gl)
        except:
            display = "unknown"
            window_mode = "unknown"
            open_gl = "unknown"

        self.write_comment("sha1: {0}".format(
                                    expyriment.get_experiment_secure_hash()))
        self.write_comment("modules: {0}".format(
                            expyriment._secure_hash.module_hashes_as_string()))
        self.write_comment("display: size={0}, window_mode={1}, open_gl={2}".format(
            display, window_mode, open_gl))
        self.write_comment("os: {0}".format(uname()))

        self.write_line("Time,Type,Event,Value,Detail,Detail2")
        self.save()