alfred3 package

alfred3.element module

Provides element classes for adding content to pages.

All elements are derived from the base Element. There are currently four kinds of elements:

  • Display elements are used to present something

  • Input elements are used to allow subject input

  • Action elements trigger some kind of action, when they are interacted with.

  • Utility elements are used for different kinds of handy things

    The following tables give an overview over all of these elements.

Element bases

Element Name

Description

Element

Basis for all elements

LabelledElement

Basis for elements with labels

InputElement

Basis for elements with user input

RowLayout

Basis for horizontal layouting

Display Elements

Element Name

Description

Html

Displays html code

Text

Displays text. Can render Markdown, html, and emoji shortcodes

CodeBlock

Displays code with syntax highlighting

Image

Displays an image

Audio

Plays sound

Video

Displays a video

MatPlot

Displays a matplotlib.figure.Figure

Hline

Displays a horizontal line on the page

ButtonLabels

Additional labels for SingleChoiceButtons or MultipleChoiceButtons

BarLabels

Additional labels for SingleChoiceBar or MultipleChoiceBar

Input Elements

Element Name

Description

TextEntry

A simple text entry field

TextArea

A text area field for multiline input

RegEntry

TextEntry with input validation via regular expressions

NumberEntry

TextEntry that specializes on numbers

SingleChoice

Radiobuttons, allowing selection of one out of several options

SingleChoiceList

Dropdown list, allowing selection of one out of several options

SingleChoiceButtons

Buttons, allowing selection of one out of several options

SingleChoiceBar

Toolbar of SingleChoiceButtons

MultipleChoice

Checkboxes, allowing selection of multiple options

MultipleChoiceButtons

Buttons, allowing selection of multiple options

MultipleChoiceBar

Toolbar of MultipleChoiceButtons

MultipleChoiceList

Scrollable list, allowing selection of multiple options

Action Elements

Element Name

Description

SubmittingButtons

Buttons which trigger the experiment to move forward on click

JumpButtons

Buttons which trigger the experiment to jump to a specific page on click

DynamicJumpButtons

JumpButtons, which get their target page dynamically from another element on the same page

JumpList

Dropbown of pages for jumping

Utility Elements

Element Name

Description

Row

Aligns multiple elements horizontally in a row

Stack

Stacks multiple elements in a row on top of each other. Think “multi-row-cell”

VerticalSpace

Adds vertical space

Style

Adds CSS code to a page

JavaScript

Adds JavaScript code to a page

HideNavigation

Removes to navigation buttons from a page

WebExitEnabler

Turns the “Do you really want to leave?” dialogue upon closing of a page off

Value

Saves a value to the experiment data without displaying anything

Data

Alias for Value

alfred3.element.jinja_env = <jinja2.environment.Environment object>

jinja2.Environment, giving access to included jinja-templates.

class alfred3.element.RowLayout(ncols: int, valign_cols: List[str] = None, responsive: bool = True)

Bases: object

Provides layouting functionality for responsive horizontal positioning of elements.

Default behavior is to have equal-width columns with an automatic breakpoint on extra small screens (i.e. all columns get the bootstrap class ‘col-sm’ by default).

The layout’s width attributes can be accessed an changed to customize appearance. In this example, we change the width of the columns on screens of “small” and bigger width, so that we have narrow columns to the right and left (each taking up 2/12 of the available space), and one wide column (taking up 8/12 of the space) in the middle. On “extra small” screens, the columns will be stacked vertically and each take up the full width.

You can define widths for five breakpoints individually, allowing for fine-grained control (see attributes).

Parameters
  • ncols – Number of columns to arrange in a row.

  • valign_cols – List of vertical column alignments. Valid values are ‘auto’ (default), ‘top’, ‘center’, and ‘bottom’.

  • responsive – Boolean, indicating whether breakpoints should be responsive, or not.

Examples

layout = RowLayout(ncols=3) # 3 columns of equal width
layout.width_sm = [2, 8, 2]
ncols

Number of columns

responsive

Indicates whether breakpoints should be responsive, or not.

width_xs

List of column widths on screens of size ‘xs’ or bigger (<576px). Content must be integers between 1 and 12.

width_sm

List of column widths on screens of size ‘s’ or bigger (>=576px). Content must be integers between 1 and 12.

width_md

List of column widths on screens of size ‘md’ or bigger (>=768px). Content must be integers between 1 and 12.

width_lg

List of column widths on screens of size ‘lg’ or bigger (>=992px). Content must be integers between 1 and 12.

width_xl

List of column widths on screens of size ‘xl’ or bigger (>=1200px). Content must be integers between 1 and 12.

col_breaks(col: int)str

Returns the column breakpoints for a specific column as strings for use as bootstrap classes.

Parameters

col – Column index (starts at 0)

format_breaks(breaks: List[int], bp: str) → List[str]

Takes a list of column sizes (in integers from 1 to 12) and returns a corresponding list of formatted Bootstrap column classes.

Parameters
  • breaks – List of integers, indicating the breakpoints.

  • bp – Specifies the relevant bootstrap breakpoint. (xs, sm, md, lg, or xl).

property valign_cols

Vertical column alignments.

Valid values are ‘auto’ (default), ‘top’, ‘center’, and ‘bottom’. Can be specified upon initalization or modified as instance attribute.

Each element of the list refers to one column. If it contains fewer elements than the number of columns, the last entry of the list will be used as value for the unreferenced columns.

Examples

All columns of the following layout will be aligned to the bottom of the row (specified upon initialization):

layout1 = RowLayout(ncols=3, valign_cols=["bottom"])

The first column of the following layout will be aligned top, the 2nd and 3rd columns will be aligned bottom (specified after initialization):

layout2 = RowLayout(ncols=3)
layout2.valign_cols = ["top", "bottom"]
Type

List[str]

class alfred3.element.Element(name: str = None, font_size: Union[str, int] = None, align: str = 'left', width: str = 'full', height: str = None, position: str = 'center', showif: dict = None, instance_level_logging: bool = False)

Bases: object

Element baseclass, providing basic functionality for all elements.

Parameters
  • name – Name of the element. This should be a unique identifier. It will be used to identify the corresponding data in the final data set.

  • font_size – Font size for text in the element. Can be ‘normal’ (default), ‘big’, ‘huge’, or an integer giving the desired size in pt.

  • align – Horizontal alignment of text in the element. Does not usually apply to labels. Think of it as an alignment that applies to the innermost layer of an element (while labels are generally located at outer layers). See LabelledElement for more on labelled elements. Can be ‘left’ (default), ‘center’, ‘right’, or ‘justify’.

  • position – Horizontal position of the full element on the page. Values can be ‘left’, ‘center’ (default), ‘end’, or any valid value for the justify-content flexbox utility. Takes effect only, when the element is not full-width.

  • width – Defines the horizontal width of the element from small screens upwards. It’s always full-width on extra small screens. Possible values are ‘narrow’, ‘medium’, ‘wide’, and ‘full’. For more detailed control, you can define the element_width attribute.

  • height – Vertical height of the element’s display area. Supply a string with a unit, e.g. “80px”. Usually, the default is fine. For adding vertical space to a page, you should prefer the VerticalSpace element, as it is sematically more clear.

  • showif – A dictionary, defining conditions that must be met for the element to be shown. The conditions take the form of key-value pairs, where each key is an element name and the value is the required input. See showif for details.

  • instance_level_logging – If True, the element will use an instance-specific logger, thereby allowing detailed fine- tuning of its logging behavior.

See also

  • How to create a custom element

Notes

The Element does not have its own display. It is used only to inherit functionality.

base_template: jinja2.environment.Template = <Template 'Element.html.j2'>

Base template for the element, which will be used to hold the rendered element template. Gets rendered by web_widget

element_template: jinja2.environment.Template = None

The element’s specific, inner template. Gets rendered by inner_html

page

The element’s parent Page (i.e. the page on which it is displayed).

exp

The Experiment to which this element belongs

experiment

Alias for exp

align

Alignment of inner element (does not apply to labels)

height

Vertical height of the element

instance_level_logging

Boolean flag, indicating whether the element should spawn its own logger, or use the class-specific logger. Can be set to True to allow for very fine-grained logging. In most cases, it is fine to leave it at the default (False)

log

A QueuedLoggingInterface, offering logging through the methods debug, info, warning, error, exception, and log.

property showif

Conditions that have to be met for the element to be shown.

The showif dictionary can contain multiple conditions as key- value-pairs. The element will only be shown, if all conditions are met. You can use all names that show up in the main dataset. That includes:

  • The names of all input elements that were shown before the current page

  • The names of all input elements on the current page

  • The experiment metadata, including exp_condition, exp_start_time, and more. See Experiment.metadata

Note

If you wish to implement more sophisticated conditions (e.g. linking conditions with ‘or’ instead of ‘and’), you can do so by using if-statements in an on_show or on_each_show page-hook.

Those conditions will not work for elements on the same page though. If you want to create complex showif conditions depending on elements on the same page, you have to implement them in JavaScript yourself. See add_js() and JavaScript for information on how to add JavaScript.

Examples

This is a simple showif based on experiment condition. The text element in this example will only be shown to subjects in the condition “one”:

import alfred3 as al
exp = al.Experiment()

@exp.setup
def setup(exp):
    exp.condition = al.random_condition("one", "two")

@exp.member
class MyPage(al.Page):
    name = "my_page"

    def on_exp_access(self):
        self += al.Text("This is text", showif={"exp_condition": "one"})

This is a more complex condition using the hook method. The text element on page2 will only be show to subjects, if they spent more than 20 seconds on page1:

import alfred3 as al
exp = al.Experiment()
exp += al.Page(name="page1")

@exp.member
class SecondPage(al.Page):
    name = "page2"

    def on_first_show(self):
        if sum(self.exp.page1.durations) > 20:
            self += al.Text("This is text")

See also

Page hooks

Type

dict

property converted_width

List of bootstrap column widths at different screen sizes.

Converted from width.

Type

list

property width

Element width

Type

str

property position

Position of the whole element on the page.

Determines the element position, when an element is not full-width.

Type

str

property font_size

Font size

Type

int

property element_width

Returns a string of column width definitions.

Manually setting the width

The element width list can contain up to 5 width definitions, specified as integers from 1 to 12. The integers refer to the five breakbpoints in Bootstrap 4’s 12-column-grid system, i.e. [xs, sm, md, lg, xl]:

>>> element = Element()
>>> element.element_width = [12, 8, 8, 7, 6]
element.element_width
"col-12 col-sm-8 col-md-8 col-lg-7 col-xl-6"

Width resultion order

If there is no width defined for a certain screen size, the next smaller entry is used. For example, the following definition will lead to full width on extra small screens and 8/12 widths on all larger widths:

element = Element()
element.element_width = [12, 8]

To make an element full-width on extra small and small screens and half-width on medium, large and extra large screens, follow this example:

element = Element()
element.element_width = [12, 12, 6]
Type

str

property name

Unique identifier for the element.

The element name will be used to identify the corresponding input in the final dataset.

Type

str

property should_be_shown

Boolean, indicating whether the element is meant to be shown.

Evaluates all showif conditions. Can be set manually. Returns False, if the element’s parent page should not be shown.

Type

bool

property section

The direct parent section of this element’s page.

property tree

String, giving the exact position in the experiment.

The tree is composed of the names of all sections and the element’s page dots. Example for an element that belongs to a page “hello_world” that was added directly to the experiment:

_root._content.hello_world

_root and _content are basic sections that alfred always includes in an experiment.

Type

str

property short_tree

String, giving the exact position in the experiment.

This version of the tree omits the _root._content part that is the same for all elements.

Type

str

property css_code

A list of tuples, which contain a priority and CSS code.

Type

List[tuple]

property css_urls

A list of tuples, which contain a priority and an url pointing to CSS code.

Type

List[tuple]

property js_code

A list of tuples, which contain a priority and Javascript.

Type

List[tuple]

property js_urls

A list of tuples, which contain a priority and an url pointing to JavaScript.

Type

List[tuple]

property template_data

Dictionary of data to be passed on to jinja templates.

When deriving a new element class, you will often want to redefine this property to add template data. When doing so, remember to retrieve the basic template data with super():

import alfred3 as al

class NewElement(al.Element):

    @property
    def template_data(self):
        d = super().template_data
        d["my_value"] = "this is my value"

        return d    # don't forget to return the dictionary!

The call super().template_data applies the parent classes code to the current object. That way, you only need to define values that differ from the parent class.

Note

Be aware that, by default, the same template data will be passed to the respective templates when rendering inner_html / element_template and web_widget / base_template.

Type

dict

added_to_experiment(experiment)

Tells the element that it was added to an experiment.

The experiment is made available to the element, and the element’s logging interface initializes its experiment-specific logging.

This is also the place where the element’s name is checked for experiment-wide uniqueness.

Parameters

experiment – The alfred experiment to which the element was added.

added_to_page(page)

Tells the element that it was added to a page.

The page and the experiment are made available to the element.

Parameters

page – The page to which the element was added.

prepare_web_widget()

Hook for computations for preparing an element’s web widget.

This method is supposed to be overridden by derived elements if necessary.

property inner_html

Renders the element template element_template.

Hands over the data returned by template_data, renders the template and returns the resulting html code.

If no element_template is defined, None is returned. Usually, the inner html gets placed into the higher-level :attr: .base_template, when Element.web_widget gets called.

Returns

Inner html code for this element.

Return type

str

property web_widget

The element’s rendered html code for display on a page.

This is done by rendering the base_template with the template_data and injecting the inner_html into it.

Returns

The full html code for this element.

Return type

str

property css_class_element

Returns the name of the element’s CSS class.

On the webpage generated by alfred3, all elements reside in some sort of container which has a CSS class of the element’s css_class_element. The name is composed as the element’s class name, followed by -element.

Examples

This is a simplified illustration of the html structure of a text element. Let’s say, the element was instantiated with the name “example_text”. The element’s css_class_element will be Text-element:

>>> import alfred3 as al
>>> ex = Text("This is an example", name="example_text")
>>> ex.css_class_element
Text-element

The html code generated by this element is structured as follows

<div class="Text-element-container" id="example_text-container">
  ...
  <div class="Text-element" id="example_text">
    <p>This is an example</p>
  </div>
  ...
</div>

Note that the element receives two CSS classes and two IDs, one each for the outer container and one for the innermost layer. The outer container includes the element’s base template (e.g. Element.html, or LabelledElement.html), while the inner layer includes the specific element- template (e.g. TextElement.html).

property css_class_container

Returns the name the element container’s CSS class.

The class can be used for CSS styling.

See also

See css_class_element for details.

Type

str

add_css(code: str, priority: int = 10)

Adds CSS to the element.

This is most useful when writing new elements. To simply add element-related CSS code to a page, usually the CSS element is a better choice.

Parameters
  • code – Css code

  • priority – Can be used to influence the order in which code is added to the page. Sorting is ascending, i.e. the lowest numbers appear closest to the top of the page.

See also

The CSS element can be used to add generic CSS code to a page.

add_js(code: str, priority: int = 10)

Adds Javascript to the element.

This is most useful when writing new elements. To simply add element-related JavaScript code to a page, usually the JavaScript element is a better choice.

Parameters
  • code – Css code

  • priority – Can be used to influence the order in which code is added to the page. Sorting is ascending, i.e. the lowest numbers appear closest to the top of the page.

See also

The JavaScript element can be used to add generic JavsScript code to a page.

class alfred3.element.Row(*elements: alfred3.element.Element, valign_cols: List[str] = None, height: str = 'auto', name: str = None, showif: dict = None, elements_full_width: bool = True)

Bases: alfred3.element.Element

Allows you to arrange up to 12 elements in a row.

The row will arrange your elements using Bootstrap 4’s grid system and breakpoints, making the arrangement responsive to different screen sizes. You can customize the behavior of the row for five different screen sizes (Bootstrap 4’s default break points) with the width attributes of its layout attribute.

If you don’t specify breakpoints manually via the layout attribute, the columns will default to equal width and wrap on breakpoints automatically.

Parameters
  • elements – The elements that you want to arrange in a row.

  • valign_cols – List of vertical column alignments. Valid values are ‘auto’ (default), ‘top’, ‘center’, and ‘bottom’. The elements of the list correspond to the row’s columns. See RowLayout.valign_cols

  • height – Custom row height (with unit, e.g. ‘100px’).

  • elements_full_width – A switch, telling the row whether you wish it to resize all elements in it to full-width (default: True). This switch exists, because some elements might default to a smaller width, but when using them in a Row, you usually want them to span the full width of their column.

Notes

  • CSS-class: row-element

In Bootstrap’s grid, the horizontal space is divided into 12 equally wide units. You can define the horizontal width of a column by assigning it a number of those units. A column of width 12 will take up all available horizontal space, other columns will be placed below such a full-width column.

You can define the column width for each of five breakpoints separately. The definition will be valid for screens of the respective size up to the next breakpoint.

See https://getbootstrap.com/docs/4.5/layout/grid/#grid-options for detailed documentation of how Bootstrap’s breakpoints work.

Examples

A minimal experiment with a row:

import alfred3 as al
exp = al.Experiment()

@exp.member
class HelloWorld(al.Page):
    name = "hello_world"

    def on_exp_access(self):
        el1 = al.Text("text")
        el2 = al.TextEntry(toplab="lab", name="example")

        self += al.Row(el1, el2)

The arrangement will look like this:

|=========|========|
|   el1   |  el2   |
|=========|========|
elements

List of the elements in this row

layout

An instance of RowLayout, used for layouting. You can use this attribute to finetune column widths via the width attributes (e.g. RowLayout.width_xs)

height

Custom row height (with unit, e.g. ‘100px’).

elements_full_width

If True, all elements will take up the full horizontal space of their column, regardless of the element’s Element.element_width and Element.width attributes.

added_to_page(page)

Tells the element that it was added to a page.

The page and the experiment are made available to the element.

Parameters

page – The page to which the element was added.

property template_data

Dictionary of data to be passed on to jinja templates.

When deriving a new element class, you will often want to redefine this property to add template data. When doing so, remember to retrieve the basic template data with super():

import alfred3 as al

class NewElement(al.Element):

    @property
    def template_data(self):
        d = super().template_data
        d["my_value"] = "this is my value"

        return d    # don't forget to return the dictionary!

The call super().template_data applies the parent classes code to the current object. That way, you only need to define values that differ from the parent class.

Note

Be aware that, by default, the same template data will be passed to the respective templates when rendering inner_html / element_template and web_widget / base_template.

Type

dict

class alfred3.element.Stack(*elements: alfred3.element.Element, **kwargs)

Bases: alfred3.element.Row

Stacks multiple elements on top of each other.

Stacks are intended for use in Rows. They allow you to flexibly arrange elements in a grid.

Parameters
  • *elements – The elements to stack.

  • **kwargs – Keyword arguments that are passend on to the parent class Row.

Notes

  • CSS-class: stack-element

  • Html element id: elid-<name> (<name> is the Element.name attribute, defined at initialization.)

Examples

A minimal experiment with a stack in a row:

import alfred3 as al
exp = al.Experiment()

@exp.member
class HelloWorld(al.Page):
    name = "hello_world"

    def on_exp_access(self):
        el1 = al.Text("text")
        el2 = al.TextEntry(toplab="lab", name="example")
        el3 = al.Text("long text")

        self += al.Row(al.Stack(el1, el2), el3)

The arrangement will look like this:

|=========|========|
|   el1   |        |
|=========|  el3   |
|   el2   |        |
|=========|========|
class alfred3.element.VerticalSpace(space: str = '1em')

Bases: alfred3.element.Element

The easiest way to add vertical space to a page.

Parameters

space – Desired space in any unit that is understood by a CSS margin (e.g. em, px, cm). Include the unit (e.g. ‘1em’).

Notes

CSS-class: vertical-space-element

Examples

Example of vertical space added between two text elements:

import alfred3 as al
exp = al.Experiment()

@exp.member
class HelloWorld(al.Page):
    name = "hello_world"

    def on_exp_access(self):
        self += al.Text("Element 1")
        self += al.VerticalSpace("100px")
        self += al.Text("Element 2")
class alfred3.element.Style(code: str = None, url: str = None, path: str = None, priority: int = 10)

Bases: alfred3.element.Element

Adds CSS code to a page.

CSS styling can be used to change the appearance of page or individual elements.

Notes

A style is added to a specific page, and thus only affects the layout of that page. To change the appearance of the whole experiment, you can define your styles in a .css file in your experiment directory and reference it in the config.conf in the option style of the section layout.

See also

  • How to reference a CSS file in the config.conf

  • CSS classes and element IDs of alfred3 elements

class alfred3.element.HideNavigation

Bases: alfred3.element.Style

Removes the forward/backward/finish navigation buttons from a page.

See also

  • Using JumpButtons and JumpList, you can add custom navigation elements to a page.

  • By defining the Page.custom_move() method on a page, you can implement highly customized movement behavior.

class alfred3.element.JavaScript(code: str = None, url: str = None, path: str = None, priority: int = 10)

Bases: alfred3.element.Element

Adds JavaScript to a page.

Javascript can be used to implement dynamic behavior on the client side.

See also

  • CSS classes and IDs of alfred3 elements.

class alfred3.element.WebExitEnabler

Bases: alfred3.element.JavaScript

Removes the “Do you really want to leave?” popup upon closing a page.

By default, subjects are asked to confirm their desire to leave a running experiment. You can turn off this behavior by adding this element to a page.

class alfred3.element.Html(html: str = None, path: Union[pathlib.Path, str] = None, **element_args)

Bases: alfred3.element.Element

Displays html code on a page.

Parameters
  • html – Html to be displayed.

  • path – Filepath to a file with html code (relative to the experiment directory).

  • **kwargs – Keyword arguments passed to the parent class Element.

Notes

  • CSS-class: html-element

This works very similar to Text. The most notable difference is that the Text element expects markdown, and therefore generally renders input text in a <p> tag. This is not always desirable for custom html, because it adds a margin at the bottom of the text.

The Html element renders neither markdown, nor emoji shortcodes.

Examples

Adding a simple div to the experiment:

import alfred3 as al
exp = al.Experiment()

@exp.member
class HelloWorld(al.Page):
    name = "hello_world"

    def on_exp_access(self):
        self += al.Html("<div id='mydiv'>Text in div</div>")
property html_code

The element’s html code

Type

str

class alfred3.element.Text(text: str = None, path: Union[pathlib.Path, str] = None, width: str = None, emojize: bool = True, **kwargs)

Bases: alfred3.element.Element

Displays text.

You can use GitHub-flavored Markdown syntax and common emoji shortcodes . Additionally, you can use raw html for advanced formatting.

Parameters
  • text – Text to be displayed.

  • path – Filepath to a textfile (relative to the experiment directory).

  • width – Element width. Usage is the same as in Element, but the Text element uses its own specific default, which ensures good readability in most cases on different screen sizes.

  • emojize – If True (default), emoji shortcodes in the text will be converted to unicode (i.e. emojis will be displayed).

  • **kwargs – Keyword arguments passed to the parent class Element.

Notes

CSS-class: text-element

Examples

A simple text element, including a 😊 (:blush:) emoji added to a page:

import alfred3 as al
exp = al.Experiment()

@exp.member
class HelloWorld(al.Page):
    name = "hello_world"

    def on_exp_access(self):
        self += al.Text("This is text :blush:")
path

Path to a textfile, if specified in the init

Type

pathlib.Path

emojize

Boolean flag, indicating whether emoji shortcodes should be interpreted

Type

bool

render_text()str

Renders the markdown and emoji shortcodes in text

Returns

Text rendered to html code

Return type

str

property text

The text to be displayed

Type

str

class alfred3.element.Hline(name: str = None, font_size: Union[str, int] = None, align: str = 'left', width: str = 'full', height: str = None, position: str = 'center', showif: dict = None, instance_level_logging: bool = False)

Bases: alfred3.element.Element

A simple horizontal line.

class alfred3.element.CodeBlock(text: str = None, path: Union[pathlib.Path, str] = None, lang: str = 'auto', width: str = 'full', **element_args)

Bases: alfred3.element.Text

A convenience element for displaying highlighted code.

Parameters
  • text – The code to be displayed.

  • path – path: Filepath to a textfile (relative to the experiment directory) from which to read code.

  • lang – The programming language to highlight 1 . Defaults to ‘auto’, which tries to auto-detect the right language.

  • **kwargs – Keyword arguments are passed on to the parent elements Text and Element

Notes

  • CSS-class: code-element

1

See https://prismjs.com/index.html#supported-languages for an overview of possible language codes. Note though that we may not support all possible languages.

class alfred3.element.Label(text, width='full', **kwargs)

Bases: alfred3.element.Text

A child of the Text element, serving as label for other elements.

Notes

  • CSS-class: label-element

layout

Layouting facility for controlling the column breaks and vertical alignment of the label. Gets set by LabelledElement automatically.

Type

RowLayout

layout_col

Tells the label which column of the layout it is

property col_breaks

The label’s breakpoints for diferent screen sizes.

property vertical_alignment

The label’s vertical alignment

class alfred3.element.LabelledElement(toplab: str = None, leftlab: str = None, rightlab: str = None, bottomlab: str = None, layout: List[int] = None, **kwargs)

Bases: alfred3.element.Element

An intermediate Element class which provides support for labels.

This class is used as a base class for all elements that come equipped with labels.

Parameters
  • toplab – String or instance of Label, which will be used to label the element.

  • leftlab – String or instance of Label, which will be used to label the element.

  • rightlab – String or instance of Label, which will be used to label the element.

  • bottomlab – String or instance of Label, which will be used to label the element.

  • layout – A list of integers, specifying the allocation of horizontal space between leftlab, main element widget and rightlab. Uses Bootstraps 12-column-grid, i.e. you can choose integers between 1 and 12.

property toplab

Label above of the main element widget.

Type

Label

property bottomlab

Label below of the main element widget.

Type

Label

property leftlab

Label to the left of the main element widget.

Type

Label

property rightlab

Label to the right of the main element widget.

Type

Label

property labels

Returns the labels in a single, nicely formatted string.

Type

str

class alfred3.element.ProgressBar(progress: Union[str, float, int] = 'auto', bar_height: str = '6px', show_text: bool = False, striped: bool = True, style: str = 'primary', animated: bool = False, round_corners: bool = False, **kwargs)

Bases: alfred3.element.LabelledElement

Displays a progress bar.

Parameters
  • progress – Can be either “auto”, or a number between 0 and 100. If “auto”, the progress is calculated from the current progress of the experiment. If a number is supplied, that number will be used as the progress to be displayed.

  • bar_height – Height of the progress bar. Supply a string with unit, e.g. “6px”.

  • text (show) – Indicates, whether the progress bar should include text with the current progress.

  • striped – Indicates, whether the progress bar shoulb be striped.

  • style – Determines the color of the progress bar. Possible values are “primary”, “secondary”, “info”, “success”, “warning”, “danger”, “light”, “dark”.

  • animated – Determines, whether a striped progress bar should be equipped with an animation.

  • round – Determines, whether the corners of the progress bar should be round.

See also

See ExperimentSession.progress_bar for more information on the experiment-wide progress bar.

Notes

If the argument show_text is True, the text’s appearance can be altered via CSS. It receives a class of “css_class_element-text” and an id of “name-text”. You can use the method add_css() to append fitting CSS to the bar (see examples).

Examples

Overriding the default experiment-wide progress bar:

import alfred3 as al
exp = al.Experiment()

@exp.setup
def setup(exp_session):
    exp_session.progress_bar = al.ProgressBar(show_text=True, bar_height="15px")

exp += al.Page(name="example_page")

Adding a progress bar as an element to a page:

import alfred3 as al
exp = al.Experiment()

@exp.member
class Example(al.Page):
    name = "example_page"

    def on_exp_access(self):
        self += al.ProgressBar()

Altering the progress bar text’s apperance, applied to the experiment-wide progress bar. Note that the experiment-wide progress bar always receives the name “progress_bar_”:

import alfred3 as al
exp = al.Experiment()

@exp.setup
def setup(exp):
    exp.progress_bar = al.ProgressBar(show_text=True, bar_height="15px")
    exp.progress_bar.add_css("#progress_bar_ {font-size: 12pt;}")

exp += al.Page(name="example_page")
class alfred3.element.InputElement(toplab: str = None, force_input: bool = False, default: Union[str, int, float] = None, description: str = None, disabled: bool = False, no_input_corrective_hint: str = None, **kwargs)

Bases: alfred3.element.LabelledElement

Base class for elements that allow data input.

Parameters
  • toplab – String or instance of Label, which will be used to label the element. The other labels (leftlab, rightlab, bottomlab) are supported aswell. Specify them as keyword arguments, not positional arguments.

  • force_input – If True, users can only progress to the next page if they enter data into this field. Note that a NoValidationSection or similar sections might overrule this setting.

  • default – Default value. Type depends on the element type.

  • description – An additional description of the element. This will show up in the alfred-generated codebook. It has no effect on the display of the experiment, as it only serves as a descriptor for humans.

  • no_input_corrective_hint – Hint to be displayed if force_input set to True and no user input registered. Defaults to the experiment-wide value specified in config.conf.

  • **kwargs – Further keyword arguments are passed on to the parent classes LabelledElement and Element.

Notes

The InputElement does not have its own display. It is used only to inherit functionality.

can_display_corrective_hints_in_line: bool = True

Boolean flag, indicating whether the element’s html template has a dedicated container for corrective hints. If False, corrective hints regarding this element will be placed in the general page-wide conainer for such hints.

description

Detailed description of this element to be added to the automatically generated codebook

show_corrective_hints

Flag, indicating whether corrective hints regarding this element should be shown.

hint_manager

A MessageManager, handling the corrective hints for this element.

disabled

A boolean flag, indicating whether the element is disabled A disabled input element is shown and displays its input value, but subjects cannot enter any data.

property corrective_hints

Shortcut for accessing the element’s corrective hints.

Yields

str – Corrective hint.

property debug_value

Value to be used as a default in debug mode.

This value is read from config.conf. Only used, if there is no dedicated default for this element.

Notes

The property searches for an option of the form <element_class>_debug in the section debug of config.conf. If no option is found, the return value is None

Type

Union[str, None]

property debug_enabled

Boolean flag, indicating whether debug mode is enabled and default values should be set.

Type

bool

property default

Default value of this element.

The data type can vary, depending on the element.

Type

Union[str, int, float]

property force_input

If True, subjects must fill this element to proceed.

Type

bool

validate_data()bool

Method for validation of input to the element.

Returns

True, if the input is correct and subjects may

proceed to the next page, False, if the input is not in the correct form.

Return type

bool

property no_input_hint

Hint for subjects, if they left a force_input field empty.

Type

str

property default_no_input_hint

Default hint if subject input is missing in force_entry elements.

This value is read from config.conf. Only used, if there is no dedicated no_input_hint for this element.

Notes

The property searches for an option of the form <element_class>_debug in the section debug of config.conf. If no option is found, the return value is “You need to enter something”.

Type

str

property input

Subject input to this element.

Type

str

property data

Dictionary of element data.

Includes the subject input and the element’s codebook_data.

Type

dict

set_data(d: dict)

Sets the input data.

Parameters

d – A dictionary with data.

Notes

The d dictionary will usually be a dictionary of all data collected on a page.

property codebook_data

Information about the element in dictionary form.

Type

dict

class alfred3.element.Data(value: Union[str, int, float], description: str = None, **kwargs)

Bases: alfred3.element.InputElement

Data can be used to save data without any display.

Example:

Data(value="test", name="mydata")
Parameters

value – The value that you want to save.

class alfred3.element.Value(value: Union[str, int, float], description: str = None, **kwargs)

Bases: alfred3.element.Data

class alfred3.element.TextEntry(toplab: str = None, prefix: str = None, suffix: str = None, placeholder: str = None, **kwargs)

Bases: alfred3.element.InputElement

Provides a text entry field.

Parameters
  • prefix – Prefix for the input field.

  • suffix – Suffix for the input field.

  • placeholder – Placeholder text, displayed inside the input field.

  • default – Default value.

  • **kwargs – Further keyword arguments that are passed on to the parent class InputElement.

validate_data()

Method for validation of input to the element.

Returns

True, if the input is correct and subjects may

proceed to the next page, False, if the input is not in the correct form.

Return type

bool

property codebook_data

Information about the element in dictionary form.

Type

dict

class alfred3.element.TextArea(toplab: str = None, nrows: int = 5, **kwargs)

Bases: alfred3.element.TextEntry

class alfred3.element.Choice(label: str = None, label_id: str = None, id: str = None, name: str = None, value: str = None, type: str = 'radio', checked: bool = False, css_class: str = None, disabled: bool = False)

Bases: object

Dataclass for managing choices.

class alfred3.element.ChoiceElement(*choice_labels, vertical: bool = False, shuffle: bool = False, align: str = 'center', **kwargs)

Bases: alfred3.element.InputElement, abc.ABC

prepare_web_widget()

Hook for computations for preparing an element’s web widget.

This method is supposed to be overridden by derived elements if necessary.

class alfred3.element.SingleChoice(*choice_labels, vertical: bool = False, shuffle: bool = False, align: str = 'center', **kwargs)

Bases: alfred3.element.ChoiceElement

property codebook_data

Information about the element in dictionary form.

Type

dict

class alfred3.element.SingleChoiceButtons(*choice_labels, button_width: Union[str, list] = 'equal', button_style: Union[str, list] = 'btn-outline-dark', button_corners: str = None, **kwargs)

Bases: alfred3.element.SingleChoice

“align” parameter has no effect in labels.

Keyword Arguments
  • button_width – Can be used to manually define the width of buttons. If you supply a single string, the same width will be applied to all buttons in the element. If you supply “auto”, button width will be determined automatically. You can also supply a list of specific widths for each individual button. You must specify a unit, e.g. ‘140px’. Defaults to “equal”.

  • button_style – Can be used for quick color-styling, using Bootstraps default color keywords: btn-primary, btn-secondary, btn-success, btn-info, btn-warning, btn-danger, btn-light, btn-dark. You can also use the “outline” variant to get outlined buttons (eg. “btn-outline-secondary”). If you specify a single string, this style is applied to all buttons in the element. If you supply a list, you can define individual styles for each button. If you supply a list that is shorter than the list of labels, the last style will be repeated for remaining buttons. Advanced user can supply their own CSS classes for button-styling.

  • button_toolbar – A boolean switch to toggle whether buttons should be layoutet as a connected toolbar (True), or as separate neighbouring buttons (False, default).

  • button_round_corners – A boolean switch to toggle whether buttons should be displayed with additionally rounded corners (True). Defaults to False.

prepare_web_widget()

Hook for computations for preparing an element’s web widget.

This method is supposed to be overridden by derived elements if necessary.

class alfred3.element.SingleChoiceBar(*choice_labels, button_width: Union[str, list] = 'equal', button_style: Union[str, list] = 'btn-outline-dark', button_corners: str = None, **kwargs)

Bases: alfred3.element.SingleChoiceButtons

class alfred3.element.MultipleChoice(*choice_labels, min: int = None, max: int = None, select_hint: str = None, default: Union[int, List[int]] = None, **kwargs)

Bases: alfred3.element.ChoiceElement

Checkboxes, allowing users to select multiple options.

Defining ‘min’, ‘max’ implies force_input.

validate_data()

Method for validation of input to the element.

Returns

True, if the input is correct and subjects may

proceed to the next page, False, if the input is not in the correct form.

Return type

bool

property data

Dictionary of element data.

Includes the subject input and the element’s codebook_data.

Type

dict

set_data(d)

Sets the input data.

Parameters

d – A dictionary with data.

Notes

The d dictionary will usually be a dictionary of all data collected on a page.

class alfred3.element.MultipleChoiceButtons(*choice_labels, min: int = None, max: int = None, select_hint: str = None, default: Union[int, List[int]] = None, **kwargs)

Bases: alfred3.element.MultipleChoice, alfred3.element.SingleChoiceButtons

Buttons, working as a MultipleChoice.

class alfred3.element.MultipleChoiceBar(*choice_labels, min: int = None, max: int = None, select_hint: str = None, default: Union[int, List[int]] = None, **kwargs)

Bases: alfred3.element.MultipleChoiceButtons

MultipleChoiceButtons, which are displayed as a toolbar instead of separate buttons.

class alfred3.element.ButtonLabels(*choice_labels, button_width: Union[str, list] = 'equal', button_style: Union[str, list] = 'btn-outline-dark', button_corners: str = None, **kwargs)

Bases: alfred3.element.SingleChoiceButtons

Disabled buttons. Example usecase might be additional labelling.

property data

Dictionary of element data.

Includes the subject input and the element’s codebook_data.

Type

dict

class alfred3.element.BarLabels(*choice_labels, button_width: Union[str, list] = 'equal', button_style: Union[str, list] = 'btn-outline-dark', button_corners: str = None, **kwargs)

Bases: alfred3.element.SingleChoiceBar

Disabled Button-Toolbar. Example usecase might be additional labelling.

property data

Dictionary of element data.

Includes the subject input and the element’s codebook_data.

Type

dict

class alfred3.element.SubmittingButtons(*choice_labels, button_style: Union[str, list] = 'btn-info', **kwargs)

Bases: alfred3.element.SingleChoiceButtons

SingleChoiceButtons that trigger submission of the current page on click.

class alfred3.element.JumpButtons(*choice_labels, button_style: Union[str, list] = 'btn-primary', **kwargs)

Bases: alfred3.element.SingleChoiceButtons

prepare_web_widget()

Hook for computations for preparing an element’s web widget.

This method is supposed to be overridden by derived elements if necessary.

validate_data()

Method for validation of input to the element.

Returns

True, if the input is correct and subjects may

proceed to the next page, False, if the input is not in the correct form.

Return type

bool

class alfred3.element.DynamicJumpButtons(*choice_labels, button_style: Union[str, list] = 'btn-primary', **kwargs)

Bases: alfred3.element.JumpButtons

validate_data()

Method for validation of input to the element.

Returns

True, if the input is correct and subjects may

proceed to the next page, False, if the input is not in the correct form.

Return type

bool

class alfred3.element.SingleChoiceList(*choice_labels, toplab: str = None, size: int = None, default: int = 1, **kwargs)

Bases: alfred3.element.SingleChoice

class alfred3.element.SelectPageList(toplab: str = None, scope: str = 'exp', check_jumpto: bool = True, check_jumpfrom: bool = True, show_all_in_scope: bool = True, **kwargs)

Bases: alfred3.element.SingleChoiceList

prepare_web_widget()

Hook for computations for preparing an element’s web widget.

This method is supposed to be overridden by derived elements if necessary.

set_data(d)

Sets the input data.

Parameters

d – A dictionary with data.

Notes

The d dictionary will usually be a dictionary of all data collected on a page.

class alfred3.element.JumpList(scope: str = 'exp', label: str = 'Jump', check_jumpto: bool = True, check_jumpfrom: bool = True, debugmode: bool = False, show_all_in_scope: bool = True, button_style: Union[str, list] = 'btn-dark', button_corners: str = 'normal', **kwargs)

Bases: alfred3.element.Row

prepare_web_widget()

Hook for computations for preparing an element’s web widget.

This method is supposed to be overridden by derived elements if necessary.

class alfred3.element.MultipleChoiceList(*choice_labels, toplab: str = None, size: int = None, **kwargs)

Bases: alfred3.element.MultipleChoice

set_data(d)

Sets the input data.

Parameters

d – A dictionary with data.

Notes

The d dictionary will usually be a dictionary of all data collected on a page.

class alfred3.element.Image(path: Union[str, pathlib.Path] = None, url: str = None, **kwargs)

Bases: alfred3.element.Element

added_to_experiment(experiment)

Tells the element that it was added to an experiment.

The experiment is made available to the element, and the element’s logging interface initializes its experiment-specific logging.

This is also the place where the element’s name is checked for experiment-wide uniqueness.

Parameters

experiment – The alfred experiment to which the element was added.

property template_data

Dictionary of data to be passed on to jinja templates.

When deriving a new element class, you will often want to redefine this property to add template data. When doing so, remember to retrieve the basic template data with super():

import alfred3 as al

class NewElement(al.Element):

    @property
    def template_data(self):
        d = super().template_data
        d["my_value"] = "this is my value"

        return d    # don't forget to return the dictionary!

The call super().template_data applies the parent classes code to the current object. That way, you only need to define values that differ from the parent class.

Note

Be aware that, by default, the same template data will be passed to the respective templates when rendering inner_html / element_template and web_widget / base_template.

Type

dict

class alfred3.element.Audio(path: Union[str, pathlib.Path] = None, url: str = None, controls: bool = True, autoplay: bool = False, loop: bool = False, align: str = 'center', **kwargs)

Bases: alfred3.element.Image

property template_data

Dictionary of data to be passed on to jinja templates.

When deriving a new element class, you will often want to redefine this property to add template data. When doing so, remember to retrieve the basic template data with super():

import alfred3 as al

class NewElement(al.Element):

    @property
    def template_data(self):
        d = super().template_data
        d["my_value"] = "this is my value"

        return d    # don't forget to return the dictionary!

The call super().template_data applies the parent classes code to the current object. That way, you only need to define values that differ from the parent class.

Note

Be aware that, by default, the same template data will be passed to the respective templates when rendering inner_html / element_template and web_widget / base_template.

Type

dict

class alfred3.element.Video(path: Union[str, pathlib.Path] = None, url: str = None, allow_fullscreen: bool = True, video_height: str = 'auto', video_width: str = '100%', **kwargs)

Bases: alfred3.element.Audio

Displays a video on the page.

Note

You can specify a filepath or a url as the source, but not both at the same time.

Parameters
  • path – Path to the video (relative to the experiment)

  • url – Url to the video

  • allow_fullscreen – Boolean, indicating whether users can enable fullscreen mode.

  • video_height – Video height in absolute pixels (without unit). Defaults to “auto”.

  • video_width – Video width in absolute pixels (without unit). Defaults to “100%”. It is recommended to use leave this parameter at the default value and use the general element parameter width for setting the width.

  • **kwargs

    The following keyword arguments are inherited from Audio:

    • controls

    • autoplay

    • loop

property template_data

Dictionary of data to be passed on to jinja templates.

When deriving a new element class, you will often want to redefine this property to add template data. When doing so, remember to retrieve the basic template data with super():

import alfred3 as al

class NewElement(al.Element):

    @property
    def template_data(self):
        d = super().template_data
        d["my_value"] = "this is my value"

        return d    # don't forget to return the dictionary!

The call super().template_data applies the parent classes code to the current object. That way, you only need to define values that differ from the parent class.

Note

Be aware that, by default, the same template data will be passed to the respective templates when rendering inner_html / element_template and web_widget / base_template.

Type

dict

class alfred3.element.MatPlot(fig, align: str = 'center', **kwargs)

Bases: alfred3.element.Element

Displays a matplotlib.figure.Figure object.

Note

When plotting in alfred, you need to use the Object-oriented matplotlib API (https://matplotlib.org/3.3.3/api/index.html#the-object-oriented-api).

Parameters
  • fig (matplotlib.figure.Figure) – The figure to display.

  • align – Alignment of the figure (‘left’, ‘right’, or ‘center’). Defaults to ‘center’.

Examples

Example usage is illustrated here. Note that the example_plot` will only be displayed if it is added to a page.

>>> import alfred3 as al
>>> from matplotlib.figure import Figure
>>> fig = Figure()
>>> ax = fig.add_subplot()
>>> ax.plot(range(10))
>>> example_plot = al.MatPlot(fig=fig, name="example))
>>> example_plot
MatPlot(name="example")
prepare_web_widget()

Hook for computations for preparing an element’s web widget.

This method is supposed to be overridden by derived elements if necessary.

property template_data

Dictionary of data to be passed on to jinja templates.

When deriving a new element class, you will often want to redefine this property to add template data. When doing so, remember to retrieve the basic template data with super():

import alfred3 as al

class NewElement(al.Element):

    @property
    def template_data(self):
        d = super().template_data
        d["my_value"] = "this is my value"

        return d    # don't forget to return the dictionary!

The call super().template_data applies the parent classes code to the current object. That way, you only need to define values that differ from the parent class.

Note

Be aware that, by default, the same template data will be passed to the respective templates when rendering inner_html / element_template and web_widget / base_template.

Type

dict