Skip to content

sweetbean.block

Block

A block of stimuli (for example, an instruction, training, or test block)

Source code in sweetbean/block.py
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
class Block:
    """
    A block of stimuli (for example, an instruction, training, or test block)
    """

    stimuli: List[Any] = []
    js = ""
    timeline = None
    extensions: Dict = {}

    def __init__(self, stimuli, timeline=None):
        """
        Arguments:
            stimuli: a list of stimuli
            timeline: a list of dictionaries with the name of the timeline variables
        """
        if timeline is None:
            timeline = []
        self.stimuli = stimuli
        self.timeline = timeline
        self.extensions["touch_layouts"] = []

    def to_js(self, template_timeline_token=None):
        """
        Build jsPsych trial source for this block.

        If ``template_timeline_token`` is set (see :meth:`Experiment.compile`), the
        timeline data is omitted here and injected later via
        :meth:`Experiment.to_js_string_from_template` for faster multi-condition builds.
        """
        self.js = "{timeline: ["
        for s in self.stimuli:
            self.extensions["touch_layouts"].append(s.create_touch_layout())
            s.to_js()
            self.js += s.js + ","
        self.js = self.js[:-1]
        if isinstance(self.timeline, CodeVariable):
            if template_timeline_token is not None:
                raise ValueError(
                    "template_timeline_token is not supported when timeline is a CodeVariable"
                )
            self.js += f"], timeline_variables: {self.timeline.name}" + "}"
        elif template_timeline_token is not None:
            self.js += f"], timeline_variables: {template_timeline_token}" + "}"
        else:
            self.js += f"], timeline_variables: {sb_to_js(self.timeline)}" + "}"

    def to_image(self, path, data, sequence=True, timeline_idx="random", zoom_factor=3):
        """
        Create an image of the stimuli sequence of the block
        Arguments:
            path: the path to save the image
            data: if needed data can be passed in for the stimuli
                (for example, correct if the sequence contains a feedback stimulus)
            sequence: if True, the images are combined into one image else they are
                stored separately
            timeline_idx: the index of the timeline element to use, if "random" a random
                timeline element is chosen, if none, the whole timeline is shown
            zoom_factor: the factor by which the images are zoomed (can be a list if
                different zoom factors for each stimulus are needed)

        """

        data_in = []
        shared_variables = {}
        for s in self.stimuli:
            _shared_variables = s.return_shared_variables()
            for s_key in _shared_variables:
                shared_variables[s_key] = _shared_variables[s_key].value
        if not self.timeline:
            timeline = [{}]
        else:
            timeline = self.timeline

        if timeline_idx == "random":
            timeline = [timeline[random.randint(0, len(timeline) - 1)]]
        elif timeline_idx is not None:
            timeline = [timeline[timeline_idx]]

        k = 0
        images = []
        durations = []
        for t in timeline:
            for s in self.stimuli:
                if s.arg["duration"] == 0:
                    continue
                html = HTML_PREAMBLE
                html += "jsPsych = initJsPsych();\n"
                html += "trials = [\n"
                s._prepare_args_l(t, data_in, shared_variables)
                s.to_js_for_image()
                html += s.js
                html += "];\n"
                html += "jsPsych.run(trials);"
                html += HTML_APPENDIX
                image = asyncio.run(render_html_to_image(html))
                duration = s.l_args["duration"] if "duration" in s.l_args else 0
                images.append(image)
                durations.append(duration)
                if data and k < len(data):
                    data_in.append(data[k])
                k += 1

        if not sequence:
            if path:
                for idx, i in enumerate(images):
                    i.save(f"{path}/stimulus_{idx}.png")
                return
            return images, durations
        result_image = create_stimulus_sequence(
            images, durations, zoom_factor=zoom_factor
        )
        if path:
            result_image.save(path)
            return
        return result_image

__init__(stimuli, timeline=None)

Parameters:

Name Type Description Default
stimuli

a list of stimuli

required
timeline

a list of dictionaries with the name of the timeline variables

None
Source code in sweetbean/block.py
46
47
48
49
50
51
52
53
54
55
56
def __init__(self, stimuli, timeline=None):
    """
    Arguments:
        stimuli: a list of stimuli
        timeline: a list of dictionaries with the name of the timeline variables
    """
    if timeline is None:
        timeline = []
    self.stimuli = stimuli
    self.timeline = timeline
    self.extensions["touch_layouts"] = []

to_image(path, data, sequence=True, timeline_idx='random', zoom_factor=3)

Create an image of the stimuli sequence of the block Arguments: path: the path to save the image data: if needed data can be passed in for the stimuli (for example, correct if the sequence contains a feedback stimulus) sequence: if True, the images are combined into one image else they are stored separately timeline_idx: the index of the timeline element to use, if "random" a random timeline element is chosen, if none, the whole timeline is shown zoom_factor: the factor by which the images are zoomed (can be a list if different zoom factors for each stimulus are needed)

Source code in sweetbean/block.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def to_image(self, path, data, sequence=True, timeline_idx="random", zoom_factor=3):
    """
    Create an image of the stimuli sequence of the block
    Arguments:
        path: the path to save the image
        data: if needed data can be passed in for the stimuli
            (for example, correct if the sequence contains a feedback stimulus)
        sequence: if True, the images are combined into one image else they are
            stored separately
        timeline_idx: the index of the timeline element to use, if "random" a random
            timeline element is chosen, if none, the whole timeline is shown
        zoom_factor: the factor by which the images are zoomed (can be a list if
            different zoom factors for each stimulus are needed)

    """

    data_in = []
    shared_variables = {}
    for s in self.stimuli:
        _shared_variables = s.return_shared_variables()
        for s_key in _shared_variables:
            shared_variables[s_key] = _shared_variables[s_key].value
    if not self.timeline:
        timeline = [{}]
    else:
        timeline = self.timeline

    if timeline_idx == "random":
        timeline = [timeline[random.randint(0, len(timeline) - 1)]]
    elif timeline_idx is not None:
        timeline = [timeline[timeline_idx]]

    k = 0
    images = []
    durations = []
    for t in timeline:
        for s in self.stimuli:
            if s.arg["duration"] == 0:
                continue
            html = HTML_PREAMBLE
            html += "jsPsych = initJsPsych();\n"
            html += "trials = [\n"
            s._prepare_args_l(t, data_in, shared_variables)
            s.to_js_for_image()
            html += s.js
            html += "];\n"
            html += "jsPsych.run(trials);"
            html += HTML_APPENDIX
            image = asyncio.run(render_html_to_image(html))
            duration = s.l_args["duration"] if "duration" in s.l_args else 0
            images.append(image)
            durations.append(duration)
            if data and k < len(data):
                data_in.append(data[k])
            k += 1

    if not sequence:
        if path:
            for idx, i in enumerate(images):
                i.save(f"{path}/stimulus_{idx}.png")
            return
        return images, durations
    result_image = create_stimulus_sequence(
        images, durations, zoom_factor=zoom_factor
    )
    if path:
        result_image.save(path)
        return
    return result_image

to_js(template_timeline_token=None)

Build jsPsych trial source for this block.

If template_timeline_token is set (see :meth:Experiment.compile), the timeline data is omitted here and injected later via :meth:Experiment.to_js_string_from_template for faster multi-condition builds.

Source code in sweetbean/block.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def to_js(self, template_timeline_token=None):
    """
    Build jsPsych trial source for this block.

    If ``template_timeline_token`` is set (see :meth:`Experiment.compile`), the
    timeline data is omitted here and injected later via
    :meth:`Experiment.to_js_string_from_template` for faster multi-condition builds.
    """
    self.js = "{timeline: ["
    for s in self.stimuli:
        self.extensions["touch_layouts"].append(s.create_touch_layout())
        s.to_js()
        self.js += s.js + ","
    self.js = self.js[:-1]
    if isinstance(self.timeline, CodeVariable):
        if template_timeline_token is not None:
            raise ValueError(
                "template_timeline_token is not supported when timeline is a CodeVariable"
            )
        self.js += f"], timeline_variables: {self.timeline.name}" + "}"
    elif template_timeline_token is not None:
        self.js += f"], timeline_variables: {template_timeline_token}" + "}"
    else:
        self.js += f"], timeline_variables: {sb_to_js(self.timeline)}" + "}"