Exemplo n.º 1
0
def logo_text_line(text):
    blank = stimuli.Canvas(size=(600, 400))
    stimuli.TextLine(text="Version " + forceDAQVersion, position=(0, 80),
                     text_size=14,
                     text_colour=constants.C_EXPYRIMENT_ORANGE).plot(blank)
    stimuli.TextLine(text=text).plot(blank)
    return blank
Exemplo n.º 2
0
def _make_graph(x, y, colour):
    """Make the graph."""

    graph = stimuli.Canvas(size=(max(x) * 3 + 10, max(y) * 3 + 10))
    for counter in range(len(x)):
        dot = stimuli.Dot(radius=1, colour=colour)
        dot.position = (x[counter] * 3 - graph.size[0] / 2 + 5,
                        y[counter] * 3 - graph.size[1] / 2 + 5)
        dot.plot(graph)
    return graph
Exemplo n.º 3
0
def create_3cards(card1, card2, card3):
    """ create a surface with the 3 cards """
    surf = stimuli.Canvas((3 * W + 2 * GAP, H), (0, 0))
    stim[card1].plot(C[0])
    stim[card2].plot(C[1])
    stim[card3].plot(C[2])
    C[0].plot(surf)
    C[1].plot(surf)
    C[2].plot(surf)
    surf.preload()
    return surf
Exemplo n.º 4
0
    def prepare(self):

        if not self.prepared:
            self._canvas = stimuli.Canvas(
                self.experiment.expyriment.screen.size,
                colour=self.background_color.backend_color)
            for stim in self.stim_list:
                stim.plot(self._canvas)
            self._canvas.preload()
            self.prepared = True
        return self.experiment.time()
Exemplo n.º 5
0
def logo_text_line(text):
    blank = stimuli.Canvas(size=(600, 400))
    logo = stimuli.Picture(filename=os.path.join(os.path.dirname(__file__),
                            "pytrak_logo.png"), position = (0, 150))
    logo.scale(0.6)
    stimuli.TextLine(text="Version " + __version__, position=(0,80),
                     text_size = 14,
                     text_colour=misc.constants.C_EXPYRIMENT_ORANGE).plot(blank)
    logo.plot(blank)
    stimuli.TextLine(text=text).plot(blank)
    return blank
Exemplo n.º 6
0
    def prepare(self):
        """See openexp._canvas.legacy"""

        if not self.prepared:
            self._canvas = stimuli.Canvas( \
             self.experiment.expyriment.screen.size, colour= \
             self._canvas_color)
            for stim in self.stim_list:
                stim.plot(self._canvas)
            self._canvas.preload()
            self.prepared = True
        return self.experiment.time()
Exemplo n.º 7
0
    def __init__(self, screen_size,  pos_y, clef_name="g", design="bw", text=None):

        self.background_colour = constants.C_WHITE
        self.foreground_colour = constants.C_BLACK
        self.clef_name = clef_name

        # Position of field
        self.pos_x = 0
        self.pos_y = pos_y[self.clef_name]

        self.field_position = [self.pos_x, self.pos_y]

        # Size of field is 1 / factor of whole screen
        factor = 3.5
        field_x = screen_size[0] / 2
        field_y = screen_size[1] / factor
        self.field_size = [field_x, field_y]

        self.Field = stimuli.Canvas(size=self.field_size, position=self.field_position, colour=self.background_colour)

        # Text field for debugging
        if text is not None:
            self.text = text
            text = stimuli.TextBox(self.text, [100,100])
            text.plot(self.Field)

        # Add lines
        self.distance = screen_size[0] / 60
        line_radius = screen_size[0]/10

        for i in range(-2, 3, 1):
            item = {
                'start_point': [-line_radius, self.pos_x - (i * self.distance)],
                'end_point': [line_radius, self.pos_x - (i * self.distance)],
                'line_width': 2,
                'colour': self.foreground_colour
                }
            line = stimuli.Line(item['start_point'], item['end_point'], item['line_width'], colour=item['colour'])
            line.plot(self.Field)

        # Add clef
        clef_pos_x = line_radius * 1.2
        clef = stimuli.Picture('Stimuli/clef_' + design + '_' + clef_name + '.jpg', position=[-clef_pos_x, 0])
        clef.scale(3.9 * screen_size[0] / 100000)
        clef.plot(self.Field)
def stimulus_question_presentation(Answer):
    canvas = stimuli.Canvas(
        size=screen_size
    )  #create canvas w/ size of the screen/screen surface. Must create new canvas every time or canvases will overwrite themselves
    trial.stimuli[0].plot(canvas)
    stimuli.TextScreen(
        heading='Is it a {}?'.format(trial.get_factor('Stimulus')),
        text=Answer).plot(canvas)  # {} replaces by desired factor
    canvas.present(
    )  #canvas with trial and text stimuli above will be presented
    key, rt = exp.keyboard.wait(constants.K_ALL_DIGITS)
    exp.data.add(
        [
            block_name,
            trial.get_factor('Stimulus'),
            trial.get_factor('Type'),
            trial.get_factor('Filenumber'), [chr(key)], key, rt
        ]
    )  #[chr(key)] dont get keyboard key number but number pressed by participant (useful for participants with different keyboards e.g. french/chinese)
Exemplo n.º 9
0
    def __init__(self, screen_size, position=[0, 0]):
        self.keys = list()
        self.index = int()
        self.Canvas = stimuli.Canvas([screen_size[0] - 100, 200],
                                     position,
                                     colour=[30, 30, 30])
        self.MouseBool = False
        # fill list of piano keys according to order of appearance in key_info.py
        for iKey in key_mapping:
            k = PianoKey(iKey)
            self.keys.append(k)

        # plot the keys; first all whites and then black on top
        self.whities = [x for x in self.keys if x.white_key]

        self.blackies = [x for x in self.keys if x.white_key == False]

        for iKey in self.whities:
            iKey.Key.plot(self.Canvas)
        for iKey in self.blackies:
            iKey.Key.plot(self.Canvas)
Exemplo n.º 10
0
    def _test1():
        info = """This will test the visual stimulus presentation timing specifics of your system.
During the test, you will see two squares on the screen.
After the test, you will be asked to indicate which (if any) of those two squares were flickering.

[Press RETURN to continue]"""
        # TODO test very slow quit
        text = stimuli.TextScreen("Visual stimulus presentation test", info)
        #y = []
        #for x in [16, 32, 48, 64]:
        #    y.extend([x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, ])
        #graph1 = _make_graph(range(60), y, [0, 255, 0])
        #y = range(80)
        #graph2 = _make_graph(range(60), y, [255, 0, 0])
        #graph1.position = (-200, -100)
        #graph2.position = (200, -100)
        text.present()
        #graph1.present(clear=False, update=False)
        #graph2.present(clear=False)
        exp.keyboard.wait([constants.K_RETURN])

        message = stimuli.TextScreen("Running", "Please wait...")
        message.present()
        message.present()
        message.present()
        c1 = stimuli.Canvas((400, 400))
        c2 = stimuli.Canvas((400, 400))
        c3 = stimuli.Canvas((400, 400))
        frame1 = stimuli.Rectangle((100, 100), position=(-100, 0))
        frame2 = stimuli.Rectangle((100, 100), position=(100, 0))
        bg = stimuli.Rectangle((90, 90), colour=exp.background_colour)
        bg.plot(frame1)
        bg.plot(frame2)
        frame1.plot(c1)
        frame2.plot(c2)
        frame1.plot(c3)
        frame2.plot(c3)
        c1.preload()
        c2.preload()
        c3.preload()
        c1.present(clear=False)
        c2.present(clear=False)
        c3.present(clear=False)

        s1 = stimuli.Circle(1, colour=exp.background_colour)
        s2 = stimuli.Circle(1, colour=exp.background_colour)
        s1.preload()
        s2.preload()
        todo_time = range(0, 60) * 3
        randomize.shuffle_list(todo_time)
        actual_time = []
        for x in todo_time:
            s1.present(clear=False)
            start = get_time()
            exp.clock.wait(x)
            s2.present(clear=False)
            actual_time.append((get_time() - start) * 1000)
            exp.clock.wait(expyriment.design.randomize.rand_int(30, 60))

        # determine refresh_rate
        tmp = []
        for _x in range(100):
            start = get_time()
            s1.present(clear=False)
            tmp.append(get_time() - start)
            start = get_time()
            s2.present(clear=False)
            tmp.append(get_time() - start)
        refresh_rate = 1000 / (statistics.mean(tmp) * 1000)

        #text = stimuli.TextScreen("Results", "[Press RETURN to continue]")
        #graph = _make_graph(todo_time, actual_time, [150, 150, 150])
        #graph.position = (0, -100)
        #text.present(update=False)
        #graph.present(clear=False)
        #exp.keyboard.wait([constants.K_RETURN])
        #text = stimuli.TextScreen(
        #    "Which picture looks most similar to the results?",
        #    "[Press LEFT or RIGHT arrow key]")
        #y = []
        #for x in [16, 32, 48, 64]:
        #    y.extend([x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, ])
        #graph1 = _make_graph(range(60), y, [0, 255, 0])
        #y = range(80)
        #graph2 = _make_graph(range(60), y, [255, 0, 0])
        #graph1.position = (-200, -100)
        #graph2.position = (200, -100)
        #text.present(update=False)
        #graph1.present(clear=False, update=False)
        #graph2.present(clear=False)
        #key, _rt = exp.keyboard.wait([constants.K_LEFT,
        #                             constants.K_RIGHT])
        #if key == constants.K_LEFT:
        #    response1 = "Steps"
        #elif key == constants.K_RIGHT:
        #    response1 = "Line"
        #else:
        #    response1 = None

        # show histogram of presentation delays
        def expected_delay(presentation_time, refresh_rate):
            refresh_time = 1000.0 / refresh_rate
            return refresh_time - (presentation_time % refresh_time)

        # delay = map(lambda x: x[1]- x[0], zip(todo_time, actual_time))
        unexplained_delay = map(
            lambda x: x[1] - x[0] - expected_delay(x[0], refresh_rate),
            zip(todo_time, actual_time))
        hist, hist_str = _histogram(unexplained_delay)
        inaccuracies = []
        delayed_presentations = 0
        for key in hist.keys():
            inaccuracies.extend([key % (1000 / refresh_rate)] * hist[key])
            if key != 0:
                delayed_presentations += hist[key]
        inaccuracy = int(round(sum(inaccuracies) / float(len(inaccuracies))))
        delayed = round(100 * delayed_presentations / 180.0, 2)

        text = stimuli.TextScreen(
            "How many of the two squares were flickering?",
            "[Press 0, 1 or 2]")
        text.present()
        key, _rt = exp.keyboard.wait(
            [constants.K_0, constants.K_1, constants.K_2])
        if key == constants.K_0:
            response = 0
        elif key == constants.K_1:
            response = 1
        elif key == constants.K_2:
            response = 2

        info = stimuli.TextScreen("Results", "")
        results1 = stimuli.TextScreen(
            "",
            "Estimated Screen Refresh Rate:     {0} Hz (~ every {1} ms)\n\n".
            format(int(round(refresh_rate)), int(1000.0 / refresh_rate)),
            text_font="freemono",
            text_size=16,
            text_bold=True,
            text_justification=0,
            position=(0, 40))
        results2 = stimuli.TextScreen(
            "",
            "Detected Framebuffer Pages:        {0}\n\n".format(response + 1),
            text_font="freemono",
            text_size=16,
            text_bold=True,
            text_justification=0,
            position=(0, 20))
        if inaccuracy != 0:
            results3_colour = [255, 0, 0]
        else:
            results3_colour = [0, 255, 0]
        results3 = stimuli.TextScreen(
            "",
            "Average Reporting Inaccuracy:      {0} ms\n\n".format(inaccuracy),
            text_font="freemono",
            text_size=16,
            text_bold=True,
            text_justification=0,
            text_colour=results3_colour,
            position=(0, -20))
        if delayed > 10:
            results4_colour = [255, 0, 0]
        elif 10 > delayed > 1:
            results4_colour = [255, 255, 0]
        else:
            results4_colour = [0, 255, 0]
        results4 = stimuli.TextScreen(
            "",
            "Unexplained Presentation Delays:   {0} %\n\n\n".format(delayed),
            text_font="freemono",
            text_size=16,
            text_bold=True,
            text_justification=0,
            text_colour=results4_colour,
            position=(0, -40))
        results5 = stimuli.TextScreen("",
                                      hist_str,
                                      text_font="freemono",
                                      text_size=16,
                                      text_bold=True,
                                      text_justification=0,
                                      position=(0, -100))
        results1.plot(info)
        results2.plot(info)
        results3.plot(info)
        results4.plot(info)
        results5.plot(info)
        info2 = stimuli.TextLine("[Press RETURN to continue]",
                                 position=(0, -160))
        info2.plot(info)
        info.present()
        exp.keyboard.wait([constants.K_RETURN])

        return todo_time, actual_time, refresh_rate, inaccuracy, delayed, response
Exemplo n.º 11
0
def run_test_suite():
    """Run the Expyriment test suite."""

    import expyriment.design.extras
    import expyriment.stimuli.extras
    import expyriment.io.extras
    import expyriment.misc.extras

    quit_experiment = False
    if not expyriment._active_exp.is_initialized:
        defaults.initialize_delay = 0
        defaults.event_logging = 0
        exp = expyriment.design.Experiment()
        exp.testsuite = True
        expyriment.control.initialize(exp)
        quit_experiment = True
    else:
        exp = expyriment._active_exp

    # make menu and code for test functions
    test_functions = ['', '', '']
    menu = [
        "1) Visual stimulus presentation", "2) Auditory stimulus presentation",
        "3) Font Viewer"
    ]
    for mod, cl in _find_self_tests():
        test_functions.append("rtn = {0}.{1}._self_test(exp)".format(mod, cl))
        menu.append("{0}) {1} test".format(len(test_functions), cl))

    menu.append("{0}) Write protocol".format(len(test_functions) + 1))
    menu.append("{0}) Quit".format(len(test_functions) + 2))
    test_functions.extend(
        ['rtn = _write_protocol(exp, results)', 'go_on=False;rtn=[];'])

    background = stimuli.Canvas(size=[400, 600])
    pict = stimuli.Picture(constants.EXPYRIMENT_LOGO_FILE, position=(0, 200))
    pict.scale(0.5)
    pict.plot(background)

    results = expyriment.get_system_info()

    try:
        import android
        mouse = expyriment.io.Mouse(show_cursor=False)
    except ImportError:
        android = None
        mouse = None

    preselected_item = 0
    go_on = True
    while go_on:
        select = expyriment.io.TextMenu("Test suite",
                                        menu,
                                        width=350,
                                        justification=0,
                                        background_stimulus=background,
                                        mouse=mouse).get(preselected_item)

        if select == 0:
            rtn = _stimulus_timing(exp)
            results["testsuite_visual_timing_todo"] = rtn[0]
            results["testsuite_visual_timing_actual"] = rtn[1]
            results["testsuite_visual_sync_refresh_rate"] = str(rtn[2]) + " Hz"
            results["testsuite_visual_timing_inaccuracy"] = str(rtn[3]) + " ms"
            results["testsuite_visual_timing_delayed"] = str(rtn[4]) + " %"
            results["testsuite_visual_flipping_user"] = rtn[5]
            delay = map(
                lambda x: x[1] - x[0],
                zip(results["testsuite_visual_timing_todo"],
                    results["testsuite_visual_timing_actual"]))
            results["testsuite_visual_timing_delay_histogram"], _ = _histogram(
                delay)
            if ogl is not None and exp.screen.open_gl:
                results["testsuite_visual_opengl_vendor"] = ogl.glGetString(
                    ogl.GL_VENDOR)
                results["testsuite_visual_opengl_renderer"] = ogl.glGetString(
                    ogl.GL_RENDERER)
                results["testsuite_visual_opengl_version"] = ogl.glGetString(
                    ogl.GL_VERSION)
                extensions = ogl.glGetString(ogl.GL_EXTENSIONS).split(" ")
                if extensions[-1] == "":
                    extensions = extensions[:-1]
                results["testsuite_visual_opengl_extensions"] = extensions
            else:
                results["testsuite_visual_opengl_vendor"] = ""
                results["testsuite_visual_opengl_renderer"] = ""
                results["testsuite_visual_opengl_version"] = ""
                results["testsuite_visual_pygame_driver"] = ""
                results["testsuite_visual_opengl_extensions"] = ""
            results[
                "testsuite_visual_pygame_driver"] = pygame.display.get_driver(
                )
            results["testsuite_visual_pygame_screensize"] = exp.screen.size
            preselected_item = select + 1
        elif select == 1:
            results["testsuite_audio_user"] = _audio_playback(exp)
            try:
                results["testsuite_audio_frequency"] = str(
                    pygame.mixer.get_init()[0]) + " Hz"
                results["testsuite_audio_bitdepth"] = str(
                    abs(pygame.mixer.get_init()[1])) + " bit"
                results["testsuite_audio_channels"] = pygame.mixer.get_init(
                )[2]
            except:
                results["testsuite_audio_frequency"] = ""
                results["testsuite_audio_bitdepth"] = ""
                results["testsuite_audio_channels"] = ""
            preselected_item = select + 1
        elif select == 2:
            _font_viewer(exp)
            preselected_item = select + 1
        else:
            exec(test_functions[select])
            results.update(rtn)
            preselected_item = select + 1

    if quit_experiment:
        expyriment.control.end(goodbye_delay=0,
                               goodbye_text="Quitting test suite")
Exemplo n.º 12
0
control.initialize(exp)

#######################   Stimuli Preparation ##################################

# load all card images in a dictionary mapping card name to Picture stimuli
cards_directory = "cards_pics_small"

stim = {
    op.splitext(f)[0]: stimuli.Picture(op.join(cards_directory, f))
    for f in os.listdir(cards_directory)
}

# canvas mapped onto left, middle and right rectangles
C = [
    stimuli.Canvas((W, H), (-SHIFT, 0)),
    stimuli.Canvas((W, H), (0, 0)),
    stimuli.Canvas((W, H), (+SHIFT, 0))
]

# Create mapping 3 cards triplets -> surfaces
three_cards_surfaces = dict()


def create_3cards(card1, card2, card3):
    """ create a surface with the 3 cards """
    surf = stimuli.Canvas((3 * W + 2 * GAP, H), (0, 0))
    stim[card1].plot(C[0])
    stim[card2].plot(C[1])
    stim[card3].plot(C[2])
    C[0].plot(surf)
Exemplo n.º 13
0
def main_loop(exp, recorder, remote_control=False):
    """udp command:
            "start", "pause", "stop"
            "thresholds = [x,...]" : start level detection for Fz parameter and set threshold
            "thresholds stop" : stop level detection
    """

    indicator_grid = 70  # distance between indicator center
    plotter_width = 900
    plotter_position = (0, -30)

    s = GUIStatus(
        screen_refresh_interval_indicator=config.
        screen_refresh_interval_indicator,
        screen_refresh_interval_plotter=config.
        gui_screen_refresh_interval_plotter,
        recorder=recorder,
        remote_control=remote_control,
        level_detection_parameter=ForceData.forces_names.index(
            config.level_detection_parameter),  # only one dimension
        screen_size=exp.screen.size,
        data_min_max=config.data_min_max,
        plotter_pixel_min_max=config.plotter_pixel_min_max,
        indicator_pixel_min_max=config.indicator_pixel_min_max,
        plot_axis=config.plot_axis)

    # plotter
    plotter_thread = None
    exp.keyboard.clear()

    while not s.quit_recording:  ######## process loop
        if s.pause_recording:
            sleep(0.01)

        ################################ process keyboard
        s.process_key(exp.keyboard.check(check_for_control_keys=False))

        ##############################  process udp
        udp = recorder.process_and_write_udp_events()
        while len(udp) > 0:
            s.process_udp_event(udp.pop(0))

        ########################### process new samples
        for x in s.check_new_samples():
            s.update_history(sensor=x)

            if s.thresholds is not None:
                # level change detection
                level_change, tmp = s.thresholds.get_level_change(
                    s.history[x].moving_average[s.level_detection_parameter],
                    channel=x)
                if level_change:
                    if x == 1:
                        recorder.udp.send_queue.put(RcCmd.CHANGED_LEVEL2 +
                                                    dumps(tmp))
                    else:
                        recorder.udp.send_queue.put(RcCmd.CHANGED_LEVEL +
                                                    dumps(tmp))

                # minmax detection
                tmp = s.thresholds.get_response_minmax(
                    s.history[x].moving_average[s.level_detection_parameter],
                    channel=x)
                if tmp is not None:
                    if x == 1:
                        recorder.udp.send_queue.put(RcCmd.RESPONSE_MINMAX2 +
                                                    dumps(tmp))
                    else:
                        recorder.udp.send_queue.put(RcCmd.RESPONSE_MINMAX +
                                                    dumps(tmp))

        ######################## show pause or recording screen
        if s.check_recording_status_change():
            if s.pause_recording:
                s.background.stimulus("writing data...").present()
                recorder.pause_recording()
                s.background.stimulus("Paused ('b' for baseline)").present()
                if remote_control:
                    recorder.udp.send_queue.put(RcCmd.FEEDBACK_PAUSED)
            else:
                recorder.start_recording()
                s.set_start_recording_time()
                s.background.stimulus().present()
                if remote_control:
                    recorder.udp.send_queue.put(RcCmd.FEEDBACK_STARTED)

        ###########################
        ########################### plotting
        ###########################

        if s.check_refresh_required():  #do not give priority to visual output
            update_rects = []

            if s.check_thresholds_changed():
                draw_plotter_thread_thresholds(plotter_thread, s.thresholds,
                                               s.scaling_plotter)

            if s.plot_indicator:
                ############################################  plot_indicator
                if plotter_thread is not None:
                    plotter_thread.stop()
                    plotter_thread = None

                ## indicator
                force_data_array = map(
                    lambda x: s.sensor_processes[x[0]].get_force(x[1]),
                    s.plot_data_indicator)

                for cnt in range(6):
                    x_pos = (-3 * indicator_grid) + (
                        cnt * indicator_grid) + 0.5 * indicator_grid

                    if cnt == s.level_detection_parameter:
                        thr = s.thresholds
                    else:
                        thr = None
                    li = level_indicator(value=force_data_array[cnt],
                                         text=s.plot_data_indicator_names[cnt],
                                         scaling=s.scaling_indicator,
                                         width=50,
                                         position=(x_pos, 0),
                                         thresholds=thr)
                    li.present(update=False, clear=False)
                    update_rects.append(get_pygame_rect(li, exp.screen.size))

                #line
                zero = s.scaling_indicator.data2pixel(
                    s.scaling_indicator.trim(0))
                rect = stimuli.Line(start_point=(-200, zero),
                                    end_point=(200, zero),
                                    line_width=1,
                                    colour=misc.constants.C_YELLOW)
                rect.present(update=False, clear=False)
                update_rects.append(get_pygame_rect(rect, exp.screen.size))

                # axis labels
                pos = (-220, -145)
                stimuli.Canvas(position=pos,
                               size=(30, 20),
                               colour=misc.constants.C_BLACK).present(
                                   update=False, clear=False)
                txt = stimuli.TextLine(position=pos,
                                       text=str(s.scaling_indicator.min),
                                       text_size=15,
                                       text_colour=misc.constants.C_YELLOW)
                txt.present(update=False, clear=False)
                update_rects.append(get_pygame_rect(txt, exp.screen.size))
                pos = (-220, 145)
                stimuli.Canvas(position=pos,
                               size=(30, 20),
                               colour=misc.constants.C_BLACK).present(
                                   update=False, clear=False)
                txt = stimuli.TextLine(position=pos,
                                       text=str(s.scaling_indicator.max),
                                       text_size=15,
                                       text_colour=misc.constants.C_YELLOW)
                txt.present(update=False, clear=False)
                update_rects.append(get_pygame_rect(txt, exp.screen.size))
                # end indicator

                stimuli.Canvas(position=(-250, 200),
                               size=(200, 50),
                               colour=misc.constants.C_BLACK).present(
                                   update=False, clear=False)
                txt = stimuli.TextBox(
                    text=str(s.sensor_info_str),
                    #background_colour=(30,30,30),
                    size=(200, 50),
                    text_size=15,
                    position=(-250, 200),
                    text_colour=misc.constants.C_YELLOW,
                    text_justification=0)
                txt.present(update=False, clear=False)
                update_rects.append(get_pygame_rect(txt, exp.screen.size))
            else:
                ############################################  plotter
                if plotter_thread is None:
                    plotter_thread = PlotterThread(
                        n_data_rows=len(s.plot_data_plotter),
                        data_row_colours=colours[:len(s.plot_data_plotter)],
                        y_range=[
                            s.scaling_plotter.pixel_min,
                            s.scaling_plotter.pixel_max
                        ],
                        width=plotter_width,
                        position=plotter_position,
                        background_colour=[10, 10, 10],
                        axis_colour=misc.constants.C_YELLOW)
                    plotter_thread.start()

                    if s.plot_axis:
                        plotter_thread.set_horizontal_lines(
                            y_values=[s.scaling_plotter.data2pixel(0)])

                    if s.thresholds is not None:
                        plotter_thread.set_horizontal_lines(
                            y_values=s.scaling_plotter.data2pixel(
                                np.array(s.thresholds.thresholds)))

                if s.clear_screen:
                    plotter_thread.clear_area()
                    s.clear_screen = False

                if s.plot_filtered:
                    tmp = np.array(map(
                        lambda x: s.history[x[0]].moving_average[x[1]],
                        s.plot_data_plotter),
                                   dtype=float)
                else:
                    tmp = np.array(map(
                        lambda x: s.sensor_processes[x[0]].get_force(x[1]),
                        s.plot_data_plotter),
                                   dtype=float)

                if s.thresholds is not None:
                    point_marker = s.thresholds.is_detecting_anything()
                else:
                    point_marker = False

                plotter_thread.add_values(
                    values=s.scaling_plotter.data2pixel(tmp),
                    set_marker=s.set_marker,
                    set_point_marker=point_marker)
                s.set_marker = False

                update_rects.append(
                    plotter_thread.get_plotter_rect(exp.screen.size))

                # axis labels
                axis_labels = (int(s.scaling_plotter.min),
                               int(s.scaling_plotter.max), 0)
                xpos = plotter_position[0] - (plotter_width / 2) - 20
                for cnt, ypos in enumerate(
                    (plotter_position[1] + s.scaling_plotter.pixel_min + 10,
                     plotter_position[1] + s.scaling_plotter.pixel_max - 10,
                     plotter_position[1] + s.scaling_plotter.data2pixel(0))):
                    stimuli.Canvas(position=(xpos, ypos),
                                   size=(50, 30),
                                   colour=misc.constants.C_BLACK).present(
                                       update=False, clear=False)
                    txt = stimuli.TextLine(position=(xpos, ypos),
                                           text=str(axis_labels[cnt]),
                                           text_size=15,
                                           text_colour=misc.constants.C_YELLOW)
                    txt.present(update=False, clear=False)
                    update_rects.append(get_pygame_rect(txt, exp.screen.size))

            # counter
            pos = (-230, 250)
            stimuli.Canvas(position=pos,
                           size=(400, 50),
                           colour=misc.constants.C_BLACK).present(update=False,
                                                                  clear=False)

            txt = stimuli.TextBox(
                position=pos,
                size=(400, 50),
                #background_colour=(30,30,30),
                text_size=15,
                text="n samples (total): {0}\nn samples: {1} ({2} sec.)".
                format(
                    str(map(SensorProcess.get_sample_cnt,
                            s.sensor_processes))[1:-1],
                    str(map(SensorProcess.get_buffer_size,
                            s.sensor_processes))[1:-1],
                    s.recording_duration_in_sec),
                text_colour=misc.constants.C_YELLOW,
                text_justification=0)
            txt.present(update=False, clear=False)
            update_rects.append(get_pygame_rect(txt, exp.screen.size))

            # Infos
            pos = (200, 250)
            tmp = stimuli.Canvas(position=pos,
                                 size=(400, 50),
                                 colour=misc.constants.C_BLACK)
            tmp.present(update=False, clear=False)
            update_rects.append(get_pygame_rect(tmp, exp.screen.size))
            if s.thresholds is not None:
                if s.n_sensors > 1:
                    tmp = [
                        s.thresholds.get_level(
                            s.level_detection_parameter_average(0)),
                        s.thresholds.get_level(
                            s.level_detection_parameter_average(1))
                    ]
                else:
                    tmp = s.thresholds.get_level(
                        s.level_detection_parameter_average(0))
                txt = stimuli.TextBox(position=pos,
                                      size=(400, 50),
                                      text_size=15,
                                      text="T: {0} L: {1}".format(
                                          s.thresholds, tmp),
                                      text_colour=misc.constants.C_YELLOW,
                                      text_justification=0)

                txt.present(update=False, clear=False)

            pos = (400, 250)
            tmp = stimuli.Canvas(position=pos,
                                 size=(400, 50),
                                 colour=misc.constants.C_BLACK)
            tmp.present(update=False, clear=False)
            update_rects.append(get_pygame_rect(tmp, exp.screen.size))
            if s.plot_filtered:
                txt = stimuli.TextBox(position=pos,
                                      size=(400, 50),
                                      text_size=15,
                                      text="Filtered data!",
                                      text_colour=misc.constants.C_YELLOW,
                                      text_justification=0)
                txt.present(update=False, clear=False)

            # last_udp input
            if s.last_udp_data is not None:
                pos = (420, 250)
                stimuli.Canvas(position=pos,
                               size=(200, 30),
                               colour=misc.constants.C_BLACK).present(
                                   update=False, clear=False)
                txt = stimuli.TextBox(
                    position=pos,
                    size=(200, 30),
                    #background_colour=(30,30,30),
                    text_size=15,
                    text="UDP:" + str(s.last_udp_data),
                    text_colour=misc.constants.C_YELLOW,
                    text_justification=0)
                txt.present(update=False, clear=False)
                update_rects.append(get_pygame_rect(txt, exp.screen.size))

            pygame.display.update(update_rects)
            # end plotting screen

        ##### end main  loop

    s.background.stimulus("Quitting").present()
    if plotter_thread is not None:
        plotter_thread.stop()
    recorder.pause_recording(s.background)
Exemplo n.º 14
0
tone.preload()

##
control.start(skip_ready_screen=True)
clock = misc.Clock()

exp.screen.clear()
bs.present(update=True)
nframe = 0
t1 = clock.time
while clock.time - t1 <= 1000:
    bs.present(update=True)
    nframe += 1
FPS = nframe

frame = stimuli.Canvas((800, 800))
msg = stimuli.TextScreen("",
                         f"""This script displays a white rectangle,
plays a tone and clears the screen, in a loop.

This permits to check the timing with some external equipment
(an oscilloscope, the Blackbox toolkit, etc.).

The current parameters are:

Tone duration = {TONE_DURATION} ms
Display duration = {SQUARE_DURATION} ms
Period = {PERIOD} ms
FPS = {FPS} Hz

Press any key for next screen (Later, to exit the program, just press 'Esc').""",
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