Пример #1
0
    def _create_surface(self):
        """Create the surface of the stimulus."""

        surface = pygame.image.load(unicode2str(self._filename,
                                                fse=True)).convert_alpha()
        if self._logging:
            expyriment._active_exp._event_file_log(
                "Picture,loaded,{0}".format(unicode2str(self._filename)), 1)
        return surface
Пример #2
0
    def _create_surface(self):
        """Create the surface of the stimulus."""

        surface = pygame.image.load(unicode2str(self._filename,
                                                fse=True)).convert_alpha()
        if self._logging:
            expyriment._active_exp._event_file_log(
                "Picture,loaded,{0}".format(unicode2str(self._filename)), 1)
        return surface
Пример #3
0
    def __init__(self, filename, position=None):
        """Create a video stimulus.
    
        Parameters
        ----------
        filename : str
            filename (incl. path) of the video
        position : (int, int), optional
            position of the stimulus
            
        Notes
        -----
        Only MPEG-1 movies with MP3 audio are supported. You can use ffmpeg
        (www.ffmpeg.org) to convert from other formats:
        
            ffmpeg -i <inputfile> -vcodec mpeg1video -acodec libmp3lame -intra -qscale 2  <outputfile.mpg>
        
        The -qscale option is the quality setting. It can take values from 1 to 31.
        1 is the best quality, but big file size. 31 is the worst quality, but
        small file size. Play around with this setting to get a good balance
        between quality and file size.

        """

        _visual.Stimulus.__init__(self, filename)
        self._filename = filename
        self._is_preloaded = False
        self._frame = 0
        if position:
            self._position = position
        else:
            self._position = defaults.video_position
        if not (os.path.isfile(self._filename)):
            raise IOError("The video file {0} does not exists".format(
                unicode2str(self._filename)))
Пример #4
0
    def _create_surface(self):
        """Create the surface of the stimulus."""

        rect = pygame.Rect((0, 0), self.size)

        if os.path.isfile(self._text_font):
            _font = pygame.font.Font(unicode2str(self._text_font, fse=True),
                                     self._text_size)
        else:
            _font = pygame.font.Font(self._text_font, self._text_size)

        _font.set_bold(self.text_bold)
        _font.set_italic(self.text_italic)
        _font.set_underline(self.text_underline)

        if type(self.text) is not unicode:
            # Pygame wants latin-1 encoding here for character strings
            
            _text = str2unicode(self.text).encode('latin-1')
        else:
            _text = self.text
        surface = self.render_textrect(self.format_block(_text),
                                       _font, rect, self.text_colour,
                                       self.background_colour,
                                       self.text_justification)
        return surface
Пример #5
0
    def play(self):
        """Play the video stimulus from the current position.
        
        Notes
        -----
        When the audio from the video should be played as well, the audiosystem
        has to be stopped (by calling expyriment.control.stop_audiosystem() )
        BEFORE the video stimulus is preloaded! After the stimulus has been played
        the audiosystem can be started again (by calling
        expyriment.control.start_audiosystem() ).

        When showing videos in large dimensions, and your computer is not fast
        enough, frames might be dropped! When using Video.wait_frame() or
        Video.wait_end(), dropped video frames will be reported and logged.
        
        """

        if mixer.get_init() is not None:
            message = "Mixer is still initialized, cannot play audio! Call \
expyriment.control.stop_audiosystem() before preloading the video."
            print "Warning: ", message
            if self._logging:
                expyriment._active_exp._event_file_log(
                    "Video,warning," + message)

        if not self._is_preloaded:
            self.preload()
        if self._logging:
            expyriment._active_exp._event_file_log(
                "Video,playing,{0}".format(unicode2str(self._filename)))
        self._file.play()
Пример #6
0
    def _create_surface(self):
        """Create the surface of the stimulus."""

        if os.path.isfile(self._text_font):
            _font = pygame.font.Font(unicode2str(self._text_font, fse=True),
                                     self._text_size)
        else:
            _font = pygame.font.Font(self._text_font, self._text_size)

        _font.set_bold(self.text_bold)
        _font.set_italic(self.text_italic)
        _font.set_underline(self.text_underline)
        if type(self.text) is not unicode:
            # Pygame wants latin-1 encoding here for character strings
            _text = str2unicode(self.text).encode('latin-1')
        else:
            _text = self.text
        if self.background_colour:
            surface = _font.render(_text, True, self.text_colour,
                                self.background_colour)
        else:
            surface = _font.render(_text, True, self.text_colour)
        surface = surface.convert_alpha()

        if self._max_width > 0 and surface.get_size()[0] > self._max_width:
            # trim too long text lines
            self._text = self._text[:-2] + "~"
            surface = self._create_surface() # recursion

        return surface
Пример #7
0
    def __init__(self, filename, position=None):
        """Create a video stimulus.
    
        Parameters
        ----------
        filename : str
            filename (incl. path) of the video
        position : (int, int), optional
            position of the stimulus
            
        Notes
        -----
        Only MPEG-1 movies with MP3 audio are supported. You can use ffmpeg
        (www.ffmpeg.org) to convert from other formats:
        
            ffmpeg -i <inputfile> -vcodec mpeg1video -acodec libmp3lame -intra -qscale 2  <outputfile.mpg>
        
        The -qscale option is the quality setting. It can take values from 1 to 31.
        1 is the best quality, but big file size. 31 is the worst quality, but
        small file size. Play around with this setting to get a good balance
        between quality and file size.

        """

        _visual.Stimulus.__init__(self, filename)
        self._filename = filename
        self._is_preloaded = False
        self._frame = 0
        if position:
            self._position = position
        else:
            self._position = defaults.video_position
        if not(os.path.isfile(self._filename)):
            raise IOError("The video file {0} does not exists".format(
                unicode2str(self._filename)))
Пример #8
0
    def preload(self):
        """Preload stimulus to memory.
        
        Notes
        -----
        When the audio from the video should be played as well, the audiosystem
        has to be stopped (by calling expyriment.control.stop_audiosystem() )
        BEFORE the video stimulus is preloaded! After the stimulus has been played
        the audiosystem can be started again (by calling
        expyriment.control.start_audiosystem() ).
        
        """

        if not self._is_preloaded:
            self._file = pygame.movie.Movie(
                unicode2str(self._filename, fse=True))
            screen_size = expyriment._active_exp.screen.surface.get_size()
            self._pos = [
                screen_size[0] / 2 - self._file.get_size()[0] / 2 +
                self._position[0], screen_size[1] / 2 -
                self._file.get_size()[1] / 2 - self._position[1]
            ]
            size = self._file.get_size()
            self._surface = pygame.surface.Surface(size)
            self._file.set_display(self._surface)
            self._is_preloaded = True
Пример #9
0
    def _create_surface(self):
        """Create the surface of the stimulus."""

        if os.path.isfile(self._text_font):
            _font = pygame.font.Font(unicode2str(self._text_font, fse=True),
                                     self._text_size)
        else:
            _font = pygame.font.Font(self._text_font, self._text_size)

        _font.set_bold(self.text_bold)
        _font.set_italic(self.text_italic)
        _font.set_underline(self.text_underline)
        if type(self.text) is not unicode:
            # Pygame wants latin-1 encoding here for character strings
            _text = str2unicode(self.text).encode('latin-1')
        else:
            _text = self.text
        if self.background_colour:
            surface = _font.render(_text, True, self.text_colour,
                                   self.background_colour)
        else:
            surface = _font.render(_text, True, self.text_colour)
        surface.convert_alpha()

        if self._max_width > 0 and surface.get_size()[0] > self._max_width:
            # trim too long text lines
            self._text = self._text[:-2] + "~"
            surface = self._create_surface()  # recursion

        return surface
Пример #10
0
    def preload(self):
        """Preload stimulus to memory.
        
        Notes
        -----
        When the audio from the video should be played as well, the audiosystem
        has to be stopped (by calling expyriment.control.stop_audiosystem() )
        BEFORE the video stimulus is preloaded! After the stimulus has been played
        the audiosystem can be started again (by calling
        expyriment.control.start_audiosystem() ).
        
        """

        if not self._is_preloaded:
            self._file = pygame.movie.Movie(unicode2str(self._filename,
                                                        fse=True))
            screen_size = expyriment._active_exp.screen.surface.get_size()
            self._pos = [screen_size[0] / 2 - self._file.get_size()[0] / 2 +
                         self._position[0],
                         screen_size[1] / 2 - self._file.get_size()[1] / 2 -
                         self._position[1]]
            size = self._file.get_size()
            self._surface = pygame.surface.Surface(size)
            self._file.set_display(self._surface)
            self._is_preloaded = True
Пример #11
0
    def play(self):
        """Play the video stimulus from the current position.
        
        Notes
        -----
        When the audio from the video should be played as well, the audiosystem
        has to be stopped (by calling expyriment.control.stop_audiosystem() )
        BEFORE the video stimulus is preloaded! After the stimulus has been played
        the audiosystem can be started again (by calling
        expyriment.control.start_audiosystem() ).

        When showing videos in large dimensions, and your computer is not fast
        enough, frames might be dropped! When using Video.wait_frame() or
        Video.wait_end(), dropped video frames will be reported and logged.
        
        """

        if mixer.get_init() is not None:
            message = "Mixer is still initialized, cannot play audio! Call \
expyriment.control.stop_audiosystem() before preloading the video."

            print "Warning: ", message
            if self._logging:
                expyriment._active_exp._event_file_log("Video,warning," +
                                                       message)

        if not self._is_preloaded:
            self.preload()
        if self._logging:
            expyriment._active_exp._event_file_log("Video,playing,{0}".format(
                unicode2str(self._filename)))
        self._file.play()
Пример #12
0
    def _create_surface(self):
        """Create the surface of the stimulus."""

        rect = pygame.Rect((0, 0), self.size)

        if os.path.isfile(self._text_font):
            _font = pygame.font.Font(unicode2str(self._text_font, fse=True),
                                     self._text_size)
        else:
            _font = pygame.font.Font(self._text_font, self._text_size)

        _font.set_bold(self.text_bold)
        _font.set_italic(self.text_italic)
        _font.set_underline(self.text_underline)

        if type(self.text) is not unicode:
            # Pygame wants latin-1 encoding here for character strings
            _text = str2unicode(self.text).encode('latin-1')
        else:
            _text = self.text
        surface = self.render_textrect(self.format_block(_text),
                                       _font, rect, self.text_colour,
                                       self.background_colour,
                                       self.text_justification)
        return surface
Пример #13
0
    def _create_surface(self):
        """Create the surface of the stimulus."""

        if os.path.isfile(self._text_font):
            _font = pygame.font.Font(unicode2str(self._text_font, fse=True),
                                     self._text_size)
        else:
            _font = pygame.font.Font(self._text_font, self._text_size)

        _font.set_bold(self.text_bold)
        _font.set_italic(self.text_italic)
        _font.set_underline(self.text_underline)
        if type(self.text) is not unicode:
            # Pygame wants latin-1 encoding here for character strings
            _text = str2unicode(self.text).encode('latin-1')
        else:
            _text = self.text
        if self.background_colour:
            text = _font.render(_text, True, self.text_colour,
                                self.background_colour)
        else:
            text = _font.render(_text, True, self.text_colour)
        text.convert_alpha()
        surface = text
        return surface
Пример #14
0
    def add_experiment_info(self, text):
        """Adds a text the subject info header.

        Notes
        -----
        The next data.save() might take longer!

        """

        if isinstance(text, types.UnicodeType):
            text = "{0}".format(unicode2str(text))
        elif type(text) is not str:
            text = "{0}".format(text)
        for line in text.splitlines():
            self._experiment_info.append("{0}e {1}{2}".format(
                unicode2str(self.comment_char), line,
                unicode2str(defaults.outputfile_eol)))
Пример #15
0
    def save(self):
        """Save the new data to data-file.

        Returns
        -------
        time : int
            the time it took to execute this method

        """

        start = get_time()
        if len(self._subject_info) > 0 or len(self._experiment_info) > 0  \
                or self._variable_names_changed:
            # Re-write header and varnames
            tmpfile_name = "{0}{1}{2}".format(self.directory, os.path.sep, uuid.uuid4())
            os.rename(self._fullpath, tmpfile_name)
            fl = open(self._fullpath, 'w+')
            tmpfl = open(tmpfile_name, 'r')
            section = None
            while True:
                line = tmpfl.readline()
                if not line:
                    break
                if line.startswith(self.comment_char + "e"):
                    section = "e"
                elif line.startswith(self.comment_char + "s"):
                    section = "s"
                else:
                    if section == "e":  # Previous line was last #e
                        if len(self._experiment_info) > 0:
                            fl.write("".join(self._experiment_info))
                            self._experiment_info = []
                        section = None
                    elif section == "s":  # Previous line was last #s
                        if len(self._subject_info) > 0:
                            fl.write("".join(self._subject_info))
                            self._subject_info = []
                        section = None

                        # Re-write variable names after #s-section
                        fl.write(unicode2str(
                            self.variable_names + defaults.outputfile_eol))
                        self._variable_names_changed = False
                        line = ''  # Skip old varnames
                fl.write(line)
            tmpfl.close()
            fl.close()

            os.remove(tmpfile_name)
            self._subject_info = []
            self._experiment_info = []

        if self._buffer != []:
            OutputFile.save(self)
            if self._logging:
                expyriment._active_exp._event_file_log("Data,saved")

        return int((get_time() - start) * 1000)
Пример #16
0
    def get(self, default_input=""):
        """Get input from user.

        Notes
        -----
        This displays and updates the input box automatically. Pressing ENTER
        returns the user input. Pressing ESC quits, returning an empty string.

        Parameters
        ----------
        default_input : str, optional
            default input in the textbox

        See Also
        --------
        design.experiment.register_wait_callback_function

        """

        if android_show_keyboard is not None:
            android_show_keyboard()
        self._user = []
        for char in default_input:
            self._user.append(char)
        self._create()
        self._update()
        if self._ascii_filter is None:
            ascii_filter = range(0, 256) + constants.K_ALL_KEYPAD_DIGITS
        else:
            ascii_filter = self._ascii_filter
        while True:
            inkey, string = self._get_key()
            if inkey == pygame.K_BACKSPACE:
                self._user = self._user[0:-1]
            elif inkey == pygame.K_RETURN or inkey == pygame.K_KP_ENTER:
                break
            elif inkey != pygame.K_LCTRL or inkey != pygame.K_RCTRL:
                if not self._user_text_surface_size[0] >= self._max_size[0]:
                    if android is not None:
                        if inkey in ascii_filter:
                            if inkey in constants.K_ALL_KEYPAD_DIGITS:
                                inkey = numpad_digit_code2ascii(inkey)
                            self._user.append(chr(inkey))
                    else:
                        if inkey in constants.K_ALL_KEYPAD_DIGITS:
                            self._user.append(
                                chr(numpad_digit_code2ascii(inkey)))
                        elif string and ord(string) in ascii_filter:
                            self._user.append(string)
            self._update()
        got = "".join(self._user)
        if self._logging:
            expyriment._active_exp._event_file_log(
                "TextInput,entered,{0}".format(unicode2str(got)))
        if android_hide_keyboard is not None:
            android_hide_keyboard()
        return got
Пример #17
0
    def get(self, default_input=""):
        """Get input from user.

        Notes
        -----
        This displays and updates the input box automatically. Pressing ENTER
        returns the user input. Pressing ESC quits, returning an empty string.

        Parameters
        ----------
        default_input : str, optional
            default input in the textbox

        See Also
        --------
        design.experiment.register_wait_callback_function

        """

        if android_show_keyboard is not None:
            android_show_keyboard()
        self._user = []
        for char in default_input:
            self._user.append(char)
        self._create()
        self._update()
        if self._ascii_filter is None:
            ascii_filter = range(0, 256) + constants.K_ALL_KEYPAD_DIGITS
        else:
            ascii_filter = self._ascii_filter
        while True:
            inkey, string = self._get_key()
            if inkey == pygame.K_BACKSPACE:
                self._user = self._user[0:-1]
            elif inkey == pygame.K_RETURN or inkey == pygame.K_KP_ENTER:
                break
            elif inkey != pygame.K_LCTRL or inkey != pygame.K_RCTRL:
                if not self._user_text_surface_size[0] >= self._max_size[0]:
                    if android is not None:
                        if inkey in ascii_filter:
                            if inkey in constants.K_ALL_KEYPAD_DIGITS:
                                inkey = numpad_digit_code2ascii(inkey)
                            self._user.append(chr(inkey))
                    else:
                        if inkey in constants.K_ALL_KEYPAD_DIGITS:
                            self._user.append(chr(numpad_digit_code2ascii(inkey)))
                        elif string and ord(string) in ascii_filter:
                            self._user.append(string)
            self._update()
        got = "".join(self._user)
        if self._logging:
            expyriment._active_exp._event_file_log("TextInput,entered,{0}".format(unicode2str(got)))
        if android_hide_keyboard is not None:
            android_hide_keyboard()
        return got
Пример #18
0
    def write_line(self, content):
        """Write a text line to files.

        Parameters
        ----------
        content : str
            content to be written (anything, will be casted to str)

        """
        self.write(content)
        self.write(unicode2str(defaults.outputfile_eol))
Пример #19
0
    def write_comment(self, comment):
        """Write a comment line to files.

        (i.e., text is proceeded by comment char).

        Parameters
        ----------
        comment : str
            comment to be written (anything, will be casted to str)

        """

        self.write(unicode2str(self.comment_char))
        self.write_line(comment)
Пример #20
0
    def add_subject_info(self, text):
        """Adds a text the subject info header.

        Subject information can be extracted afterwards using
        misc.data_preprocessing.read_data_file. To defined between subject
        variables use a syntax like this: "gender = female" or
        "handedness : left"

        Parameters
        ----------
        text : str
            subject infomation to be add to the file header

        Notes
        -----
        The next data.save() might take longer!


        """

        self._subject_info.append("{0}s {1}{2}".format(
            unicode2str(self.comment_char), unicode2str(text),
            unicode2str(defaults.outputfile_eol)))
Пример #21
0
    def write(self, content):
        """Write to file.

        Parameters
        ----------
        content : str
            content to be written (anything, will be casted to str)

        """

        if type(content) is unicode:
            self._buffer.append(unicode2str(content))
        else:
            self._buffer.append(str(content))
Пример #22
0
    def log(self, event):
        """Log an event.

        Parameters
        ----------
        event : anything
            the event to be logged (anything, will be casted to str)

        """

        if isinstance(event, types.UnicodeType):
            event = unicode2str(event)
        line = repr(self._clock.time) + self.delimiter + str(event)
        self.write_line(line)
Пример #23
0
    def write_list(self, list_):
        """Write a list in a row. Data are separated by a delimiter.

        Parameters
        ----------
        list_ : list
            list to be written

        """

        for elem in list:
            self.write(elem)
            self.write(',')
        self.write(unicode2str(defaults.outputfile_eol))
Пример #24
0
 def _typecheck_and_cast2str(data):
     """Check if data are string or numeric and cast to string"""
     if data is None:
         data = "None"
     if isinstance(data, types.UnicodeType):
         return unicode2str(data)
     elif type(data) in [types.StringType, types.IntType,
                         types.LongType, types.FloatType,
                         types.BooleanType]:
         return str(data)
     else:
         message = "Data to be added must to be " + \
             "booleans, strings, numerics (i.e. floats or integers) " + \
             "or None.\n {0} is not allowed.".format(type(data))
         raise TypeError(message)
Пример #25
0
    def preload(self):
        """Preload stimulus to memory."""

        if not self._is_preloaded:
            self._file = pygame.movie.Movie(unicode2str(self._filename,
                                                        fse=True))
            screen_size = expyriment._active_exp.screen.surface.get_size()
            self._pos = [screen_size[0] / 2 - self._file.get_size()[0] / 2 +
                         self._position[0],
                         screen_size[1] / 2 - self._file.get_size()[1] / 2 -
                         self._position[1]]
            size = self._file.get_size()
            self._surface = pygame.surface.Surface(size)
            self._file.set_display(self._surface)
            self._is_preloaded = True
Пример #26
0
 def _typecheck_and_cast2str(data):
     """Check if data are string or numeric and cast to string"""
     if data is None:
         data = "None"
     if isinstance(data, types.UnicodeType):
         return unicode2str(data)
     elif isinstance(data, types.StringType):
         return str(data)
     elif type(data) in [types.IntType, types.LongType, types.FloatType,
                         types.BooleanType]:
         return repr(data)
     else:
         message = "Data to be added must to be " + \
             "booleans, strings, numerics (i.e. floats or integers) " + \
             "or None.\n {0} is not allowed.".format(type(data))
         raise TypeError(message)
Пример #27
0
    def __init__(self, filename):
        """Create an audio stimulus.

        Parameters
        ----------
        filename : str
            the filename

        """

        Stimulus.__init__(self, filename)
        self._filename = filename
        self._file = None
        self._is_preloaded = False
        if not(os.path.isfile(self._filename)):
            raise IOError("The audio file {0} does not exists".format(
                unicode2str(self._filename)))
Пример #28
0
    def play(self):
        """Play the video stimulus from the current position."""

        if mixer.get_init() is not None:
            message = "Mixer is still initialized, cannot play audio! Call \
expyriment.control.stop_audiosystem() before preloading the video."
            print "Warning: ", message
            if self._logging:
                expyriment._active_exp._event_file_log(
                    "Video,warning," + message)

        if not self._is_preloaded:
            self.preload()
        if self._logging:
            expyriment._active_exp._event_file_log(
                "Video,playing,{0}".format(unicode2str(self._filename)))
        self._file.play()
Пример #29
0
    def __init__(self, filename):
        """Create an audio stimulus.

        Parameters
        ----------
        filename : str
            the filename

        """

        Stimulus.__init__(self, filename)
        self._filename = filename
        self._file = None
        self._is_preloaded = False
        if not (os.path.isfile(self._filename)):
            raise IOError("The audio file {0} does not exists".format(
                unicode2str(self._filename)))
Пример #30
0
    def __init__(self, filename, position=None):
        """Create a picture.

        Parameters
        ----------
        filename : str
            filename (incl. path) of the picture file
        position :(int,int), optional
            position of the stimulus

        """

        if position is None:
            position = defaults.picture_position
        Visual.__init__(self, position, log_comment=filename)
        self._filename = filename
        if not(os.path.isfile(self._filename)):
            raise IOError("The picture file '{0}' does not exist".format(
                unicode2str(filename)))
Пример #31
0
    def __init__(self, filename, position=None):
        """Create a picture.

        Parameters
        ----------
        filename : str
            filename (incl. path) of the picture file
        position :(int,int), optional
            position of the stimulus

        """

        if position is None:
            position = defaults.picture_position
        Visual.__init__(self, position, log_comment=filename)
        self._filename = filename
        if not (os.path.isfile(self._filename)):
            raise IOError("The picture file '{0}' does not exist".format(
                unicode2str(filename)))
Пример #32
0
    def __init__(self, filename, encoding=None):
        """Create an input file.

        All lines in the specified text file will be read into a list of
        strings.

        Parameters
        ----------
        filename : str, optional
            name of the input file

        encoding : str, optional
            the encoding used to read the content of the file

        """

        self._filename = filename
        self._current_line = 1
        self._lines = []
        if not(os.path.isfile(self._filename)):
            raise IOError("The input file '{0}' does not exist.".format(
                unicode2str(self._filename)))

        if encoding is None:
            with open(filename, 'r') as fl:
                first_line = fl.readline()
                encoding = re.findall("coding[:=]\s*([-\w.]+)", first_line)
                if encoding == []:
                    second_line = fl.readline()
                    encoding = re.findall("coding[:=]\s*([-\w.]+)",
                                          second_line)
                    if encoding == []:
                        encoding = [None]
        else:
            encoding = [encoding]
        with codecs.open(self._filename, 'rb', encoding[0],
                         errors='replace') as f:
            for line in f:
                self._lines.append(str2unicode(line.rstrip('\r\n')))
Пример #33
0
    def __init__(self, filename, position=None):
        """Create a video stimulus.

        Parameters
        ----------
        filename : str
            filename (incl. path) of the video
        position : (int, int), optional
            position of the stimulus

        """

        _visual.Stimulus.__init__(self, filename)
        self._filename = filename
        self._is_preloaded = False
        self._frame = 0
        if position:
            self._position = position
        else:
            self._position = defaults.video_position
        if not(os.path.isfile(self._filename)):
            raise IOError("The video file {0} does not exists".format(
                unicode2str(self._filename)))
Пример #34
0
    def save(self, filename):
        """Save the stimulus as image.

        Parameters
        ----------
        filename : str
            name of the file to write (possible extensions are BMP, TGA, PNG,
            or JPEG with TGA being the default)

        Notes
        -----
        Depending on the size of the stimulus, this method may take some time
        to compute!

        """

        parts = filename.split(".")
        if len(parts) > 1:
            parts[-1] = parts[-1].lower()
        else:
            parts.append("tga")
        filename = ".".join(parts)
        pygame.image.save(self._get_surface(), unicode2str(filename))
    def save(self, filename):
        """Save the stimulation protocol to a csv file.
        
        Parameters
        ----------
        
        filename : str
            The name of the file to save the protocol to
            
        """

        with open(filename, 'w') as f:
            try:
                locale_enc = locale.getdefaultlocale()[1]
            except:
                locale_enc = "UTF-8"
            f.write("# -*- coding: {0} -*-\n".format(locale_enc))
            f.write("#unit={0}\n".format(self._unit))
            f.write("condition,begin,end,weight\n")
            for condition in self._conditions:
                for event in condition["events"]:
                    f.write("{0},{1},{2},{3}\n".format(
                        unicode2str(condition["name"]), event["begin"],
                        event["end"], event["weight"]))
Пример #36
0
def start(experiment=None, auto_create_subject_id=None, subject_id=None,
            skip_ready_screen=False):
    """Start an experiment.

    This starts an experiment defined by 'experiment' and asks for the subject
    number. When the subject number is entered and confirmed by ENTER, a data
    file is created.
    Eventually, "Ready" will be shown on the screen and the method waits for
    ENTER to be pressed.

    After experiment start the following additional properties are available:

    * experiment.subject -- the current subject id
    * experiment.data    -- the main data file

    Parameters
    ----------
    experiment : design.Experiment, optional (DEPRECATED)
        don't use this parameter, it only exists to keep backward compatibility
    auto_create_subject_id : bool, optional
        if True new subject id will be created automatically
    subject_id : integer, optional
        start with a specific subject_id;
        no subject id input mask will be presented; subject_id must be an
        integer; setting this paramter overrules auto_create_subject_id
    skip_ready_screen : bool, optional
        if True ready screen will be skipped (default=False)

    Returns
    -------
    exp : design.Experiment
        The started experiment will be returned.

    """

    if experiment is None:
        experiment = expyriment._active_exp
    if experiment != expyriment._active_exp:
        raise Exception("Experiment is not the currently initialized " +
                        "experiment!")
    if experiment.is_started:
        raise Exception("Experiment is already started!")
    if subject_id is not None:
        if not isinstance(subject_id, int):
            raise Exception("Subject id must be an integer. " +
                    "{0} is not allowed.".format(type(subject_id)))
        auto_create_subject_id = True
    elif auto_create_subject_id is None:
        auto_create_subject_id = defaults.auto_create_subject_id

    experiment._is_started = True
    # temporarily switch off log_level
    old_logging = experiment.log_level
    experiment.set_log_level(0)
    screen_colour = experiment.screen.colour
    experiment._screen.colour = [0, 0, 0]
    if subject_id is None:
        default_number = DataFile.get_next_subject_number()
    else:
        default_number = subject_id

    if not auto_create_subject_id:
        if android is not None:
            background_stimulus = stimuli.BlankScreen(colour=(0, 0, 0))
            fields = [stimuli.Circle(radius=100, colour=(70, 70, 70),
                                     position=(0, 70), anti_aliasing=10),
                      stimuli.Circle(radius=100, colour=(70, 70, 70),
                                     position=(0, -70), anti_aliasing=10),
                      stimuli.Rectangle(size=(50, 50), colour=(70, 70, 70),
                                        position=(120, 0))]
            fields[0].scale((0.25, 0.25))
            fields[1].scale((0.25, 0.25))
            plusminus = [
                stimuli.TextLine("Subject Number:", text_size=24,
                                 text_colour=constants.C_EXPYRIMENT_PURPLE,
                                 position=(-182, 0)),
                stimuli.FixCross(size=(15, 15), position=(0, 70),
                                 colour=(0, 0, 0), line_width=2),
                stimuli.FixCross(size=(15, 2), position=(0, -70),
                                 colour=(0, 0, 0), line_width=2),
                stimuli.TextLine(text = "Go", text_size=18, position=(120, 0),
                                 text_colour=(0, 0, 0))]
            subject_id = default_number
            while True:
                text = stimuli.TextLine(
                    text="{0}".format(subject_id),
                    text_size=28,
                    text_colour=constants.C_EXPYRIMENT_ORANGE)
                btn = TouchScreenButtonBox(
                    button_fields=fields,
                    stimuli=plusminus+[text],
                    background_stimulus=background_stimulus)
                btn.show()
                key, rt = btn.wait()
                if key == fields[0]:
                    subject_id += 1
                elif key == fields[1]:
                    subject_id -= 1
                    if subject_id <= 0:
                        subject_id = 0
                elif key == fields[2]:
                    break
            experiment._subject = int(subject_id)

        else:
            position = (0, 0)
            while True:
                ask_for_subject = TextInput(
                    message="Subject Number:",
                    position=position,
                    message_colour=misc.constants.C_EXPYRIMENT_PURPLE,
                    message_text_size=24,
                    user_text_colour=misc.constants.C_EXPYRIMENT_ORANGE,
                    user_text_size=20,
                    background_colour=(0, 0, 0),
                    frame_colour=(70, 70, 70),
                    ascii_filter=misc.constants.K_ALL_DIGITS)
                subject_id = ask_for_subject.get(repr(default_number))
                try:
                    experiment._subject = int(subject_id)
                    break
                except:
                    pass

    else:
        experiment._subject = default_number

    experiment.screen.clear()
    experiment.screen.update()
    experiment._data = DataFile(additional_suffix=experiment.filename_suffix)
    experiment.data.add_variable_names(experiment.data_variable_names)
    for txt in experiment.experiment_info:
        experiment.data.add_experiment_info(txt)
    for line in experiment.__str__().splitlines():
        experiment.data.add_experiment_info(line)

    for f in experiment.bws_factor_names:
        _permuted_bws_factor_condition = \
            experiment.get_permuted_bws_factor_condition(f)
        if isinstance(_permuted_bws_factor_condition, unicode):
            _permuted_bws_factor_condition = \
                unicode2str(_permuted_bws_factor_condition)
        experiment.data.add_subject_info("{0} = {1}".format(
            unicode2str(f), _permuted_bws_factor_condition))

    if experiment.events is not None:
        experiment.events._time_stamp = experiment.data._time_stamp
        experiment.events.rename(experiment.events.standard_file_name)

    number = defaults.initialize_delay - int(experiment.clock.time / 1000)
    if number > 0:
        text = stimuli.TextLine("Initializing, please wait...",
                                text_size=24,
                                text_colour=(160, 70, 250),
                                position=(0, 0))
        stimuli._stimulus.Stimulus._id_counter -= 1
        text.present()
        text.present()  # for flipping with double buffer
        text.present()  # for flipping with tripple buffer
    while number > 0:
        counter = stimuli.TextLine(
            "{num:02d}".format(num=number),
            text_font='FreeMono',
            text_size=18,
            text_bold=True,
            text_colour=misc.constants.C_EXPYRIMENT_ORANGE,
            position=(0, -50),
            background_colour=(0, 0, 0))

        stimuli._stimulus.Stimulus._id_counter -= 1
        counter.present(clear=False)
        number -= 1
        key = experiment.keyboard.wait(pygame.K_ESCAPE, duration=1000,
                                       check_for_control_keys=False)
        if key[0] is not None:
            break

    position = (0, 0)
    if not skip_ready_screen:
        stimuli.TextLine("Ready", position=position, text_size=24,
                     text_colour=misc.constants.C_EXPYRIMENT_ORANGE).present()
        stimuli._stimulus.Stimulus._id_counter -= 1
        if android is None:
            experiment.keyboard.wait()
        else:
            experiment.mouse.wait_press()
    experiment.set_log_level(old_logging)
    experiment._screen.colour = screen_colour
    experiment.log_design_to_event_file()
    experiment._event_file_log("Experiment,started")
    return experiment
Пример #37
0
    def preload(self):
        """Preload stimulus to memory."""

        if not self._is_preloaded:
            self._file = mixer.Sound(unicode2str(self._filename, fse=True))
            self._is_preloaded = True
Пример #38
0
    def __init__(self, text, size, position=None, text_font=None,
                 text_size=None, text_bold=None, text_italic=None,
                 text_underline=None, text_justification=None,
                 text_colour=None, background_colour=None,
                 do_not_trim_words=None):
        """Create a text box.

        Notes
        -----
        text_font can be both, a name or path to a font file!
        When text_font is a name, Expyriment will try to find a font that
        best matches the given name.
        If no matching font can be found, or if the given font file cannot be
        found, the Pygame system default will be used.
        In any case the value of the attribute text_font will always
        resemble the font that is actually in use!

        Parameters
        ----------
        text : str
            text to wrap
        size : (int, int)
            size of the text box
        position : (int, int), optional
            position of the stimulus
        text_font : str, optional
            text font to use as a name or as a path to a font file
        text_size : int, optional
            size of the text
        text_bold : bool, optional
            font should be bold
        text_italic : bool, optional
            font should be italic
        text_underline : bool, optional
            font should get an underline
        text_justification : int, optional
            text justification, 0 (left), 1 (center), 2 (right)
        text_colour : (int, int, int), optional
            colour of the text
        background_colour : (int, int, int), optional
            background colour
        do_not_trim_words: bool, optional
            if True, words that exceed the width of the text box
            will be not be trimmed and an exception is raise instead.
            default: False

        """

        pygame.font.init()

        if position is None:
            position = defaults.textbox_position
        Visual.__init__(self, position)
        self._text = text
        self._size = size
        if text_size is None:
            text_size = defaults.textbox_text_size
        if text_size is not None:
            self._text_size = text_size
        else:
            self._text_size = expyriment._active_exp.text_size

        if text_font is None:
            text_font = defaults.textbox_text_font
        if text_font is not None:
            self._text_font = find_font(text_font)
        else:
            self._text_font = find_font(expyriment._active_exp.text_font)
        try:
            _font = pygame.font.Font(unicode2str(self._text_font, fse=True),
                                     10)
            _font = None
        except:
            raise IOError("Font '{0}' not found!".format(text_font))
        if text_bold is not None:
            self._text_bold = text_bold
        else:
            self._text_bold = defaults.textbox_text_bold
        if text_italic is not None:
            self._text_italic = text_italic
        else:
            self._text_italic = defaults.textbox_text_italic
        if text_underline is not None:
            self._text_underline = text_underline
        else:
            self._text_underline = defaults.textbox_text_underline
        if text_justification is not None:
            self._text_justification = text_justification
        else:
            self._text_justification = defaults.textbox_text_justification
        if text_colour is not None:
            self._text_colour = text_colour
        else:
            if defaults.textbox_text_colour is not None:
                self._text_colour = defaults.textbox_text_colour
            else:
                self._text_colour = expyriment._active_exp.foreground_colour
        if background_colour is not None:
            self._background_colour = background_colour
        else:
            self._background_colour = \
                defaults.textbox_background_colour
        if do_not_trim_words is not None:
            self._do_not_trim_words = do_not_trim_words
        else:
            self._do_not_trim_words = defaults.textbox_do_not_trim_words
Пример #39
0
    def wait_char(self, char, duration=None, check_for_control_keys=True):
        """Wait for character(s) (optionally for a certain amount of time).

        This function will wait for one or more characters and returns the
        found character as well as the reaction time.
        (This function clears the event queue!)

        Parameters
        ----------
        char : int or list
            a specific character or list of characters to wait for
        duration : int, optional
            maximal time to wait in ms
        check_for_control_keys : bool, optional
            checks if control key has been pressed (default=True)

        Returns
        -------
        found : char
            pressed charater
        rt : int
            reaction time in ms

        See Also
        --------
        design.experiment.register_wait_callback_function

        """

        if expyriment.control.defaults._skip_wait_functions:
            return None, None
        start = get_time()
        rt = None
        found_char = None
        self.clear()
        try:
            char = list(char)
        except:
            char = [char]
        pygame.event.pump()
        done = False

        while not done:
            rtn_callback = expyriment._active_exp._execute_wait_callback()
            if isinstance(rtn_callback, expyriment.control.CallbackQuitEvent):
                    done = True
                    rt = int((get_time() - start) * 1000)
                    found_char = rtn_callback

            for event in pygame.event.get([pygame.KEYUP, pygame.KEYDOWN]):
                if check_for_control_keys and Keyboard.process_control_keys(event):
                    done = True
                elif event.type == pygame.KEYDOWN:
                    if event.unicode in char:
                        rt = int((get_time() - start) * 1000)
                        found_char = event.unicode
                        done = True
            if duration and not done:
                done = int((get_time() - start) * 1000) >= duration
            time.sleep(0.0005)
        if self._logging:
            expyriment._active_exp._event_file_log(
                        "Keyboard,received,{0},wait_char".format(
                        unicode2str(found_char)))
        return found_char, rt
Пример #40
0
    def preload(self):
        """Preload stimulus to memory."""

        if not self._is_preloaded:
            self._file = mixer.Sound(unicode2str(self._filename, fse=True))
            self._is_preloaded = True
def start(experiment=None,
          auto_create_subject_id=None,
          subject_id=None,
          skip_ready_screen=False):
    """Start an experiment.

    This starts an experiment defined by 'experiment' and asks for the subject
    number. When the subject number is entered and confirmed by ENTER, a data
    file is created.
    Eventually, "Ready" will be shown on the screen and the method waits for
    ENTER to be pressed.

    After experiment start the following additional properties are available:

    * experiment.subject -- the current subject id
    * experiment.data    -- the main data file

    Parameters
    ----------
    experiment : design.Experiment, optional (DEPRECATED)
        don't use this parameter, it only exists to keep backward compatibility
    auto_create_subject_id : bool, optional
        if True new subject id will be created automatically
    subject_id : integer, optional
        start with a specific subject_id;
        no subject id input mask will be presented; subject_id must be an
        integer; setting this paramter overrules auto_create_subject_id
    skip_ready_screen : bool, optional
        if True ready screen will be skipped (default=False)

    Returns
    -------
    exp : design.Experiment
        The started experiment will be returned.

    """

    if experiment is None:
        experiment = expyriment._active_exp
    if experiment != expyriment._active_exp:
        raise Exception("Experiment is not the currently initialized " +
                        "experiment!")
    if experiment.is_started:
        raise Exception("Experiment is already started!")
    if subject_id is not None:
        if not isinstance(subject_id, int):
            raise Exception("Subject id must be an integer. " +
                            "{0} is not allowed.".format(type(subject_id)))
        auto_create_subject_id = True
    elif auto_create_subject_id is None:
        auto_create_subject_id = defaults.auto_create_subject_id

    experiment._is_started = True
    # temporarily switch off log_level
    old_logging = experiment.log_level
    experiment.set_log_level(0)
    screen_colour = experiment.screen.colour
    experiment._screen.colour = [0, 0, 0]
    if subject_id is None:
        default_number = DataFile.get_next_subject_number()
    else:
        default_number = subject_id

    if not auto_create_subject_id:
        if android is not None:
            background_stimulus = stimuli.BlankScreen(colour=(0, 0, 0))
            fields = [
                stimuli.Circle(radius=100,
                               colour=(70, 70, 70),
                               position=(0, 70),
                               anti_aliasing=10),
                stimuli.Circle(radius=100,
                               colour=(70, 70, 70),
                               position=(0, -70),
                               anti_aliasing=10),
                stimuli.Rectangle(size=(50, 50),
                                  colour=(70, 70, 70),
                                  position=(120, 0))
            ]
            fields[0].scale((0.25, 0.25))
            fields[1].scale((0.25, 0.25))
            plusminus = [
                stimuli.TextLine("Subject Number:",
                                 text_size=24,
                                 text_colour=constants.C_EXPYRIMENT_PURPLE,
                                 position=(-182, 0)),
                stimuli.FixCross(size=(15, 15),
                                 position=(0, 70),
                                 colour=(0, 0, 0),
                                 line_width=2),
                stimuli.FixCross(size=(15, 2),
                                 position=(0, -70),
                                 colour=(0, 0, 0),
                                 line_width=2),
                stimuli.TextLine(text="Go",
                                 text_size=18,
                                 position=(120, 0),
                                 text_colour=(0, 0, 0))
            ]
            subject_id = default_number
            while True:
                text = stimuli.TextLine(
                    text="{0}".format(subject_id),
                    text_size=28,
                    text_colour=constants.C_EXPYRIMENT_ORANGE)
                btn = TouchScreenButtonBox(
                    button_fields=fields,
                    stimuli=plusminus + [text],
                    background_stimulus=background_stimulus)
                btn.show()
                key, rt = btn.wait()
                if key == fields[0]:
                    subject_id += 1
                elif key == fields[1]:
                    subject_id -= 1
                    if subject_id <= 0:
                        subject_id = 0
                elif key == fields[2]:
                    break
            experiment._subject = int(subject_id)

        else:
            position = (0, 0)
            while True:
                ask_for_subject = TextInput(
                    message="Subject Number:",
                    position=position,
                    message_colour=misc.constants.C_EXPYRIMENT_PURPLE,
                    message_text_size=24,
                    user_text_colour=misc.constants.C_EXPYRIMENT_ORANGE,
                    user_text_size=20,
                    background_colour=(0, 0, 0),
                    frame_colour=(70, 70, 70),
                    ascii_filter=misc.constants.K_ALL_DIGITS)
                subject_id = ask_for_subject.get(repr(default_number))
                try:
                    experiment._subject = int(subject_id)
                    break
                except:
                    pass

    else:
        experiment._subject = default_number

    experiment.screen.clear()
    experiment.screen.update()
    experiment._data = DataFile(additional_suffix=experiment.filename_suffix)
    experiment.data.add_variable_names(experiment.data_variable_names)
    for txt in experiment.experiment_info:
        experiment.data.add_experiment_info(txt)
    for line in experiment.__str__().splitlines():
        experiment.data.add_experiment_info(line)

    for f in experiment.bws_factor_names:
        _permuted_bws_factor_condition = \
            experiment.get_permuted_bws_factor_condition(f)
        if isinstance(_permuted_bws_factor_condition, unicode):
            _permuted_bws_factor_condition = \
                unicode2str(_permuted_bws_factor_condition)
        experiment.data.add_subject_info("{0} = {1}".format(
            unicode2str(f), _permuted_bws_factor_condition))

    if experiment.events is not None:
        experiment.events._time_stamp = experiment.data._time_stamp
        experiment.events.rename(experiment.events.standard_file_name)

    number = defaults.initialize_delay - int(experiment.clock.time / 1000)
    if number > 0:
        text = stimuli.TextLine("Initializing, please wait...",
                                text_size=24,
                                text_colour=(160, 70, 250),
                                position=(0, 0))
        stimuli._stimulus.Stimulus._id_counter -= 1
        text.present()
        text.present()  # for flipping with double buffer
        text.present()  # for flipping with tripple buffer
    while number > 0:
        counter = stimuli.TextLine(
            "{num:02d}".format(num=number),
            text_font='FreeMono',
            text_size=18,
            text_bold=True,
            text_colour=misc.constants.C_EXPYRIMENT_ORANGE,
            position=(0, -50),
            background_colour=(0, 0, 0))

        stimuli._stimulus.Stimulus._id_counter -= 1
        counter.present(clear=False)
        number -= 1
        key = experiment.keyboard.wait(pygame.K_ESCAPE,
                                       duration=1000,
                                       check_for_control_keys=False)
        if key[0] is not None:
            break

    position = (0, 0)
    if not skip_ready_screen:
        stimuli.TextLine(
            "Ready",
            position=position,
            text_size=24,
            text_colour=misc.constants.C_EXPYRIMENT_ORANGE).present()
        stimuli._stimulus.Stimulus._id_counter -= 1
        if android is None:
            experiment.keyboard.wait()
        else:
            experiment.mouse.wait_press()
    experiment.set_log_level(old_logging)
    experiment._screen.colour = screen_colour
    experiment.log_design_to_event_file()
    experiment._event_file_log("Experiment,started")
    return experiment
Пример #42
0
def show_documentation(docu_type=None):
    """Show the Expyriment documentation.


    Parameters
    ----------
    docu_type : int
        documentation type. Three options are available:
            1) Open online documentation
            2) Open online API reference
            3) Open API reference and search tool

    """

    from expyriment import get_version

    def call_info():
        print ""
        print "Call show_documentation with the following arguments to get further information:"
        print "     show_documentation(1) -- Open local documentation in web browser"
        print "     show_documentation(2) -- Open online documentation in web browser"
        print "     show_documentation(3) -- Open API Reference Tool"
        print ""

    import subprocess
    import os
    import sys
    import webbrowser

    f = os.path.abspath(__file__)
    path = os.path.abspath(os.path.join(os.path.split(f)[0], ".."))
    if docu_type is None:
        print "Welcome to Expyriment {0}".format(get_version())
        print ""
        author = __author__.replace(",", ",\n        ")
        print "Website: http://expyriment.org"
        print "License: GNU GPL v3"
        print "Authors: {0}".format(author)
        call_info()
    elif docu_type == 1:
        docu = os.path.join(sys.prefix, 'share', 'expyriment', 'documentation',
                            'html', 'index.html')
        if os.path.exists(docu):
            from expyriment.misc import unicode2str
            webbrowser.open(unicode2str('file://' + docu), new=1)
        else:
            print "No local documentation found"
    elif docu_type == 2:
        webbrowser.open("http://docs.expyriment.org/", new=1)
    elif docu_type == 3:
        python_executable = sys.executable.replace("pythonw.exe", "python.exe")
        call = '"' + "{0}".format(python_executable) + \
                '" -m expyriment._api_reference_tool'
        _proc = subprocess.Popen(call,
                                 shell=True,
                                 stdin=None,
                                 stdout=None,
                                 cwd=path)
    else:
        print "Unknown documentation type"
        call_info()
Пример #43
0
    def wait_char(self, char, duration=None, check_for_control_keys=True):
        """Wait for character(s) (optionally for a certain amount of time).

        This function will wait for one or more characters and returns the
        found character as well as the reaction time.
        (This function clears the event queue!)

        Parameters
        ----------
        char : int or list
            a specific character or list of characters to wait for
        duration : int, optional
            maximal time to wait in ms
        check_for_control_keys : bool, optional
            checks if control key has been pressed (default=True)

        Returns
        -------
        found : char
            pressed charater
        rt : int
            reaction time in ms

        See Also
        --------
        design.experiment.register_wait_callback_function

        """

        if expyriment.control.defaults._skip_wait_functions:
            return None, None
        start = get_time()
        rt = None
        found_char = None
        self.clear()
        try:
            char = list(char)
        except:
            char = [char]
        pygame.event.pump()
        done = False

        while not done:
            rtn_callback = expyriment._active_exp._execute_wait_callback()
            if isinstance(rtn_callback, expyriment.control.CallbackQuitEvent):
                done = True
                rt = int((get_time() - start) * 1000)
                found_char = rtn_callback

            for event in pygame.event.get([pygame.KEYUP, pygame.KEYDOWN]):
                if check_for_control_keys and Keyboard.process_control_keys(
                        event):
                    done = True
                elif event.type == pygame.KEYDOWN:
                    if event.unicode in char:
                        rt = int((get_time() - start) * 1000)
                        found_char = event.unicode
                        done = True
            if duration and not done:
                done = int((get_time() - start) * 1000) >= duration
            time.sleep(0.0005)
        if self._logging:
            expyriment._active_exp._event_file_log(
                "Keyboard,received,{0},wait_char".format(
                    unicode2str(found_char)))
        return found_char, rt
Пример #44
0
    def __init__(self, text, position=None, text_font=None, text_size=None,
                 text_bold=None, text_italic=None, text_underline=None,
                 text_colour=None, background_colour=None, max_width=None):
        """Create a text line stimulus.

        NOTE: text_font can be both, a name or path to a font file!
        When text_font is a name, Expyriment will try to find a font that
        best matches the given name.
        If no matching font can be found, or if the given font file cannot be
        found, the Pygame system default will be used.
        In any case the value of the attribute text_font will always
        resemble the font that is actually in use!

        Parameters
        ----------
        text : str
            text to show (str)
        position : (int, int), optional
            position of the stimulus
        text_font : str, optional
            font to use as name or as path to a font file
        text_size : int, optional
            text size
        text_bold : bool, optional
            font should be bold
        text_italic : bool, optional
            font should be italic
        text_underline : bool, optional
            font should get an underline
        text_colour : (int, int, int), optional
            text colour
        background_colour : (int, int, int), optional
            background colour
        max_width: int, optional
            maximum surface width of the text line stimulus
            if this parameter is defined, text lines that exceed this
            surface width will be trimmed (indicated by a '~' as last letter)

        """

        pygame.font.init()
        if position is None:
            position = defaults.textline_position
        Visual.__init__(self, position, log_comment=text)
        self._text = text
        self._max_width = max_width
        if text_size is None:
            text_size = defaults.textline_text_size
        if text_size is not None:
            self._text_size = text_size
        else:
            self._text_size = expyriment._active_exp.text_size
        if text_font is None:
            text_font = defaults.textline_text_font
        if text_font is not None:
            self._text_font = find_font(text_font)
        else:
            self._text_font = find_font(expyriment._active_exp.text_font)
        try:
            _font = pygame.font.Font(unicode2str(self._text_font, fse=True),
                                     10)
            _font = None
        except:
            raise IOError("Font '{0}' not found!".format(text_font))
        if text_bold is not None:
            self._text_bold = text_bold
        else:
            self._text_bold = defaults.textline_text_bold
        if text_italic is not None:
            self._text_italic = text_italic
        else:
            self._text_italic = defaults.textline_text_italic
        if text_underline is not None:
            self._text_underline = text_underline
        else:
            self._text_underline = defaults.textline_text_underline
        if text_colour is None:
            text_colour = defaults.textline_text_colour
        if text_colour is not None:
            self._text_colour = text_colour
        else:
            self._text_colour = expyriment._active_exp.foreground_colour
        if background_colour is not None:
            self._background_colour = background_colour
        else:
            self._background_colour = \
                defaults.textline_background_colour
Пример #45
0
    def __init__(self,
                 text,
                 position=None,
                 text_font=None,
                 text_size=None,
                 text_bold=None,
                 text_italic=None,
                 text_underline=None,
                 text_colour=None,
                 background_colour=None,
                 max_width=None):
        """Create a text line stimulus.

        NOTE: text_font can be both, a name or path to a font file!
        When text_font is a name, Expyriment will try to find a font that
        best matches the given name.
        If no matching font can be found, or if the given font file cannot be
        found, the Pygame system default will be used.
        In any case the value of the attribute text_font will always
        resemble the font that is actually in use!

        Parameters
        ----------
        text : str
            text to show (str)
        position : (int, int), optional
            position of the stimulus
        text_font : str, optional
            font to use as name or as path to a font file
        text_size : int, optional
            text size
        text_bold : bool, optional
            font should be bold
        text_italic : bool, optional
            font should be italic
        text_underline : bool, optional
            font should get an underline
        text_colour : (int, int, int), optional
            text colour
        background_colour : (int, int, int), optional
            background colour
        max_width: int, optional
            maximum surface width of the text line stimulus
            if this parameter is defined, text lines that exceed this
            surface width will be trimmed (indicated by a '~' as last letter)

        """

        pygame.font.init()
        if position is None:
            position = defaults.textline_position
        Visual.__init__(self, position, log_comment=text)
        self._text = text
        self._max_width = max_width
        if text_size is None:
            text_size = defaults.textline_text_size
        if text_size is not None:
            self._text_size = text_size
        else:
            self._text_size = expyriment._active_exp.text_size
        if text_font is None:
            text_font = defaults.textline_text_font
        if text_font is not None:
            self._text_font = find_font(text_font)
        else:
            self._text_font = find_font(expyriment._active_exp.text_font)
        try:
            _font = pygame.font.Font(unicode2str(self._text_font, fse=True),
                                     10)
            _font = None
        except:
            raise IOError("Font '{0}' not found!".format(text_font))
        if text_bold is not None:
            self._text_bold = text_bold
        else:
            self._text_bold = defaults.textline_text_bold
        if text_italic is not None:
            self._text_italic = text_italic
        else:
            self._text_italic = defaults.textline_text_italic
        if text_underline is not None:
            self._text_underline = text_underline
        else:
            self._text_underline = defaults.textline_text_underline
        if text_colour is None:
            text_colour = defaults.textline_text_colour
        if text_colour is not None:
            self._text_colour = text_colour
        else:
            self._text_colour = expyriment._active_exp.foreground_colour
        if background_colour is not None:
            self._background_colour = background_colour
        else:
            self._background_colour = \
                defaults.textline_background_colour
Пример #46
0
    def __init__(self, text, size, position=None, text_font=None,
                 text_size=None, text_bold=None, text_italic=None,
                 text_underline=None, text_justification=None,
                 text_colour=None, background_colour=None):
        """Create a text box.

        Notes
        -----
        text_font can be both, a name or path to a font file!
        When text_font is a name, Expyriment will try to find a font that
        best matches the given name.
        If no matching font can be found, or if the given font file cannot be
        found, the Pygame system default will be used.
        In any case the value of the attribute text_font will always
        resemble the font that is actually in use!

        Parameters
        ----------
        text : str
            text to wrap
        size : (int, int)
            size of the text box
        position : (int, int), optional
            position of the stimulus
        text_font : str, optional
            text font to use as a name or as a path to a font file
        text_size : int, optional
            size of the text
        text_bold : bool, optional
            font should be bold
        text_italic : bool, optional
            font should be italic
        text_underline : bool, optional
            font should get an underline
        text_justification : int, optional
            text justification, 0 (left), 1 (center), 2 (right)
        text_colour : (int, int, int), optional
            colour of the text
        background_colour : (int, int, int), optional
            background colour

        """

        pygame.font.init()

        if position is None:
            position = defaults.textbox_position
        Visual.__init__(self, position)
        self._text = text
        self._size = size
        if text_size is None:
            text_size = defaults.textbox_text_size
        if text_size is not None:
            self._text_size = text_size
        else:
            self._text_size = expyriment._active_exp.text_size

        if text_font is None:
            text_font = defaults.textbox_text_font
        if text_font is not None:
            self._text_font = find_font(text_font)
        else:
            self._text_font = find_font(expyriment._active_exp.text_font)
        try:
            _font = pygame.font.Font(unicode2str(self._text_font, fse=True),
                                     10)
            _font = None
        except:
            raise IOError("Font '{0}' not found!".format(text_font))
        if text_bold is not None:
            self._text_bold = text_bold
        else:
            self._text_bold = defaults.textbox_text_bold
        if text_italic is not None:
            self._text_italic = text_italic
        else:
            self._text_italic = defaults.textbox_text_italic
        if text_underline is not None:
            self._text_underline = text_underline
        else:
            self._text_underline = defaults.textbox_text_underline
        if text_justification is not None:
            self._text_justification = text_justification
        else:
            self._text_justification = defaults.textbox_text_justification
        if text_colour is not None:
            self._text_colour = text_colour
        else:
            if defaults.textbox_text_colour is not None:
                self._text_colour = defaults.textbox_text_colour
            else:
                self._text_colour = expyriment._active_exp.foreground_colour
        if background_colour is not None:
            self._background_colour = background_colour
        else:
            self._background_colour = \
                defaults.textbox_background_colour
Пример #47
0
    def __init__(self,
                 message="",
                 position=None,
                 ascii_filter=None,
                 length=None,
                 message_text_size=None,
                 message_colour=None,
                 message_font=None,
                 message_bold=None,
                 message_italic=None,
                 user_text_size=None,
                 user_text_bold=None,
                 user_text_font=None,
                 user_text_colour=None,
                 background_colour=None,
                 frame_colour=None,
                 gap=None,
                 screen=None,
                 background_stimulus=None):
        """Create a text input box.

        Notes
        -----
        This stimulus is not optimized for timing accurate presentation!

        Parameters
        ----------
        message : str, optional
            message to show
        position : (int, int), optional
            position of the TextInput canvas
        length : int, optional
            the length of the text input frame in number of charaters
        ascii_filter : list, optional
            list of ASCII codes to filter for
        message_text_size : int, optional
            text size of the message
        message_colour : (int, int, int), optional
            text colour of the message
        message_font : str, optional
            text font of the message
        message_bold : bool, optional
            True if message text should be bold
        message_italic : bool, optional
            True if message text should be italic
        user_text_size : int, optional
            text size of the user input
        user_text_font : str, optional
            text font of the user input
        user_text_colour : (int, int ,int), optional
            text colour of the user input
        user_text_bold : bool, optional
            True if user text should be bold
        background_colour : (int, int, int), optional
        frame_colour : (int, int, int)
            colour of the frame
        gap : int, optional
            gap between message and user input
        screen : io.Screen, optional
            screen to present on
        background_stimulus : visual Expyriment stimulus, optional
            The background stimulus is a second stimulus that will be presented
            together with the TextInput. For both stimuli overlap TextInput
            will appear on top of the background_stimulus

        """

        if not expyriment._active_exp.is_initialized:
            raise RuntimeError(
                "Cannot create TextInput before expyriment.initialize()!")
        Input.__init__(self)
        self._message = message
        if position is not None:
            self._position = position
        else:
            self._position = defaults.textinput_position
        if ascii_filter is not None:
            self._ascii_filter = ascii_filter
        else:
            self._ascii_filter = defaults.textinput_ascii_filter
        if length is not None:
            self._length = length
        else:
            self._length = defaults.textinput_length
        if message_text_size is None:
            message_text_size = defaults.textinput_message_text_size
        if message_text_size is not None:
            self._message_text_size = message_text_size
        else:
            self._message_text_size = expyriment._active_exp.text_size
        if message_colour is None:
            message_colour = defaults.textinput_message_colour
        if message_colour is not None:
            self._message_colour = message_colour
        else:
            self._message_colour = expyriment._active_exp.foreground_colour
        if message_font is None:
            message_font = defaults.textinput_message_font
        if message_font is not None:
            self._message_font = find_font(message_font)
        else:
            self._message_font = find_font(expyriment._active_exp.text_font)
        try:
            _font = pygame.font.Font(unicode2str(self._message_font, fse=True),
                                     10)
        except:
            raise IOError("Font '{0}' not found!".format(message_font))
        if message_bold is not None:
            self._message_bold = message_bold
        else:
            self._message_bold = defaults.textinput_message_bold
        if message_italic is not None:
            self._message_italic = message_italic
        else:
            self._message_italic = defaults.textinput_message_italic
        if user_text_size is None:
            user_text_size = defaults.textinput_user_text_size
        if user_text_size is not None:
            self._user_text_size = user_text_size
        else:
            self._user_text_size = expyriment._active_exp.text_size

        if user_text_bold is not None:
            self._user_text_bold = user_text_bold
        else:
            self._user_text_bold = defaults.textinput_user_text_bold
        if user_text_font is None:
            user_text_font = defaults.textinput_user_text_font
        if user_text_font is not None:
            self._user_text_font = find_font(user_text_font)
        else:
            self._user_text_font = find_font(expyriment._active_exp.text_font)
        try:
            _font = pygame.font.Font(
                unicode2str(self._user_text_font, fse=True), 10)
        except:
            raise IOError("Font '{0}' not found!".format(user_text_font))
        if user_text_colour is None:
            user_text_colour = defaults.textinput_user_text_colour
        if user_text_colour is not None:
            self._user_text_colour = user_text_colour
        else:
            self._user_text_colour = expyriment._active_exp.foreground_colour
        if background_colour is None:
            background_colour = \
                defaults.textinput_background_colour
        if background_colour is not None:
            self._background_colour = background_colour
        else:
            self._background_colour = \
                expyriment._active_exp.background_colour
        if frame_colour is None:
            frame_colour = defaults.textinput_frame_colour
        if frame_colour is not None:
            self._frame_colour = frame_colour
        else:
            self._frame_colour = expyriment._active_exp.foreground_colour
        if gap is not None:
            self._gap = gap
        else:
            self._gap = defaults.textinput_gap
        if screen is not None:
            self._screen = screen
        else:
            self._screen = expyriment._active_exp.screen
        if background_stimulus is not None:
            # FIXME child of child of visual does not work as background stimulus, e.g. BlankScreen
            if background_stimulus.__class__.__base__ in \
                     [expyriment.stimuli._visual.Visual, expyriment.stimuli.Shape]:
                self._background_stimulus = background_stimulus
            else:
                raise TypeError("{0} ".format(type(background_stimulus)) +
                                "is not a valid background stimulus. " +
                                "Use an expyriment visual stimulus.")
        else:
            self._background_stimulus = None

        self._user = []
        self._user_text_surface_size = None
        self._max_size = None
        self._message_surface_size = None
        self._canvas = None
        self._canvas_size = None
Пример #48
0
    def __init__(self, heading, text, position=None, heading_font=None,
                 heading_size=None, heading_bold=None, heading_italic=None,
                 heading_underline=None, heading_colour=None, text_font=None,
                 text_size=None, text_bold=None, text_italic=None,
                 text_underline=None, text_colour=None,
                 text_justification=None, background_colour=None, size=None):
        """Create a text screen.

        Parameters
        ----------
        heading : str
            heading of the text screen
        text : str
            text of the text screen
        position : (int, int), optional
            position of the stimulus
        heading_font : str, optional
            heading font to use
        heading_size : int, optional
            heading font size
        heading_bold : bool, optional
            heading should be bold
        heading_italic : bool, optional
            heading should be italic
        heading_underline : bool, optional
            heading should get an underline
        heading_colour : (int,int,int), optional
            heding colour
        text_font : str, optional
            text font to use
        text_size : int, optional
            text font size
        text_bold : bool, optional
            text should be bold
        text_italic : bool, optional
            text should be italic
        text_underline : bool, optional
            text should get an underline
        text_colour : (int,int,int), optional
            text colour
        text_justification : int, optional
            0 (Left), 1(center), 2(right) (int) (optional)
        background_colour : (int, int, int), optional
            background_colour
        size : (int, int), optional
            size of the text screen

        """

        if position is None:
            position = defaults.textscreen_position
        Visual.__init__(self, position, log_comment="text_screen")
        self._heading = heading
        self._text = text
        if heading_font is None:
            heading_font = defaults.textscreen_heading_font
        if heading_font is not None:
            self._heading_font = find_font(heading_font)
        else:
            self._heading_font = find_font(expyriment._active_exp.text_font)
        try:
            _font = pygame.font.Font(
                unicode2str(self._heading_font, fse=True), 10)
            _font = None
        except:
            raise IOError("Font '{0}' not found!".format(heading_font))
        if heading_size is None:
            heading_size = defaults.textscreen_heading_size
        if heading_size:
            self._heading_size = heading_size
        else:
            self._heading_size = int(expyriment._active_exp.text_size
                                     * 1.2)
        if heading_bold is not None:
            self._heading_bold = heading_bold
        else:
            self._heading_bold = defaults.textscreen_heading_bold
        if heading_italic is not None:
            self._heading_italic = heading_italic
        else:
            self._heading_italic = \
                defaults.textscreen_heading_italic
        if heading_underline is not None:
            self._heading_underline = heading_underline
        else:
            self._heading_underline = \
                defaults.textscreen_heading_underline
        if heading_colour is None:
            heading_colour = defaults.textscreen_heading_colour
        if heading_colour is not None:
            self._heading_colour = heading_colour
        else:
            self._heading_colour = expyriment._active_exp.foreground_colour
        if text_font is None:
            text_font = defaults.textscreen_text_font
        if text_font is not None:
            self._text_font = find_font(text_font)
        else:
            self._text_font = find_font(expyriment._active_exp.text_font)
        try:
            _font = pygame.font.Font(unicode2str(self._text_font, fse=True),
                                     10)
            _font = None
        except:
            raise IOError("Font '{0}' not found!".format(text_font))
        if text_size is None:
            self._text_size = defaults.textscreen_text_size
        if text_size is not None:
            self._text_size = text_size
        else:
            self._text_size = expyriment._active_exp.text_size
        if text_bold is not None:
            self._text_bold = text_bold
        else:
            self._text_bold = defaults.textscreen_text_bold
        if text_italic is not None:
            self._text_italic = text_italic
        else:
            self._text_italic = defaults.textscreen_text_italic
        if text_underline is not None:
            self._text_underline = text_underline
        else:
            self._text_underline = defaults.textscreen_text_underline
        if text_colour is None:
            text_colour = defaults.textscreen_text_colour
        if text_colour is not None:
            self._text_colour = text_colour
        else:
            self._text_colour = expyriment._active_exp.foreground_colour
        if text_justification is not None:
            self._text_justification = text_justification
        else:
            self._text_justification = \
                defaults.textscreen_text_justification
        if size is not None:
            self._size = size
        else:
            size = defaults.textscreen_size
            if size is None:
                try:
                    self._size = (
                        expyriment._active_exp.screen.surface.get_size()[0] -
                        expyriment._active_exp.screen.surface.get_size()[0]
                        / 5,
                        expyriment._active_exp.screen.surface.get_size()[1] -
                        expyriment._active_exp.screen.surface.get_size()[1]
                        / 5)
                except:
                    raise RuntimeError("Cannot get size of screen!")

        if background_colour is not None:
            self._background_colour = background_colour
        else:
            self._background_colour = \
                defaults.textscreen_background_colour