Timeline
********


AsyncCodeBlock
==============

class psynet.timeline.AsyncCodeBlock(function, wait=True, expected_wait=None, check_interval=2.0, waiting_message=None, max_wait_time=20.0, on_timeout=None, priority=None)

   A version of CodeBlock that executes its function asynchronously.

   Parameters:
      * **function** ("Callable") -- A function with up to two
        arguments named "participant" and "experiment".

      * **wait** ("bool") -- If "True", then the participant will be
        held on a wait page until the function has finished. If
        "False", the participant will proceed immediately, and the
        function will execute in the background.

      * **expected_wait** ("Optional"["float"]) -- Only relevant if
        "wait=True"; corresponds to the time we expect the participant
        to wait on the wait page.

      * **check_interval** ("float") -- Only relevant if "wait=True";
        corresponds to the fallback interval between checks when no
        completion wake arrives. Default: 2.0 seconds.

      * **max_wait_time** ("float") -- Only relevant if "wait=True";
        the participant is failed if the function has not finished
        after this many seconds. Default: 20.0 seconds.

      * **on_timeout** ("Optional"["Callable"]) -- Only relevant if
        "wait=True"; a function called with "participant=..." when the
        participant's page next checks in after "max_wait_time",
        unless the function has finished or failed by then. The
        function keeps running in the background. "on_timeout" must
        not commit the database session.

      * **waiting_message** ("Optional"["str"]) -- Only relevant if
        "wait=True"; overlay message while waiting. Markup is allowed.
        Omit to keep the stock wait copy.

      * **priority** ("Optional"["str"]) -- Priority of the function's
        "WorkerAsyncJob", ""high"" or ""low"". Defaults to ""high"" if
        "wait=True", because the participant is waiting for it, and
        ""low"" otherwise.


CodeBlock
=========

class psynet.timeline.CodeBlock(function)

   A timeline component that executes some back-end logic without
   showing anything to the participant.

   Parameters:
      **function** ("Callable") -- A function with up to two arguments
      named "participant" and "experiment", that is executed once the
      participant reaches the corresponding part of the timeline.


CURRENT_ANSWER
==============

psynet.timeline.CURRENT_ANSWER

   Pass as a page's "time_limit_answer" to record what the participant
   has entered when time runs out.


Conditional statements
======================

psynet.timeline.conditional(label, condition, logic_if_true, logic_if_false=None, fix_time_credit=False, bound_progress=True, log_chosen_branch=True, time_estimate=None)

   Executes a series of elts if and only if a certain condition is
   satisfied.

   Parameters:
      * **label** ("str") -- Internal label to assign to the
        construct.

      * **condition** ("Callable") -- A function with up to two
        arguments named "participant" and "experiment", that is
        executed once the participant reaches the corresponding part
        of the timeline. Its result is converted with "bool()", so a
        truthy value such as a number or a non-empty list chooses
        "logic_if_true".

      * **logic_if_true** -- An elt (or list of elts) to display if
        "condition" returns "True".

      * **logic_if_false** -- An optional elt (or list of elts) to
        display if "condition" returns "False".

      * **fix_time_credit** ("bool") -- Whether participants should
        receive the same time credit irrespective of the branch taken.
        Defaults to "False"; if set to "True", all participants
        receive the same credit, corresponding to the branch with the
        maximum time credit.

      * **bound_progress** ("bool") -- Whether the progress estimate
        should be 'bound' such that, whatever happens, when the
        participant exits the conditional construct, the progress
        estimate will be the same as if the participant had taken the
        branch with the maximum time credit. Defaults to "True".

      * **log_chosen_branch** ("bool") -- Whether to keep a log of
        which participants took each branch; defaults to "True".

      * **time_estimate** ("float") -- An optional time estimate to
        use for the conditional construct. If not provided, the time
        estimate will be estimated by computing time estimates for the
        two branches and taking the maximum.

   Returns:
      * *list* -- A list of elts that can be embedded in a timeline
        using "psynet.timeline.join()".


Elt
===

class psynet.timeline.Elt


Event
=====

class psynet.timeline.Event(is_triggered_by, trigger_condition='all', delay=0.0, once=False, message=None, message_color='black', js=None)

   Defines an event that occurs on the front-end for a given page.
   This event is triggered once custom conditions are satisfied; it
   can then trigger future events to occur. One can define custom JS
   code to be run when these events execute in one of two ways. One
   approach is to register this custom JS code by writing something
   like this:

      psynet.trial.onEvent("myEventId", function() {
          // custom code goes here
      });

   A second approach is to add JS code directly to the "js" argument
   of the present function.

   The resulting object should be passed to the "events" parameter in
   "Page".

   Parameters:
      * **is_triggered_by** -- Defines the triggers for the present
        event. A trigger can be specified either as a string
        corresponding to an event ID, for example ""trialStart"", or
        as an object of class "Trigger". The latter case is more
        flexible because it allows a particular trigger to be delayed
        by a specified number of seconds. Multiple triggers can be
        defined by instead passing a list of these strings or
        "Trigger" objects. Alternatively, one can pass "None", in
        which case the event won't be triggered automatically, but
        instead will only be triggered if/when
        "psynet.trial.registerEvent" is called in the Javascript
        front-end.

      * **trigger_condition** ("str") -- If this is set to ""all""
        (default), then all triggers must be satisfied before the
        event will be cued. If this is set to ""any"", then the event
        will be cued when any one of these triggers occurred.

      * **delay** ("float") -- Determines the time interval (in
        seconds) between the trigger condition being satisfied and the
        event being triggered (default = 0.0).

      * **once** ("bool") -- If "True", then the event will only be
        cued once, at the point when the trigger condition is first
        satisfied. If "False" (default), then the event will be recued
        each time one of the triggers is hit again.

      * **message** ("Optional"["str"]) -- Optional message to display
        when this event occurs (default = """").

      * **message_color** ("str") -- CSS colour for the message. Named
        colours such as "red", "green", "blue", "orange", "grey", and
        "black" are mapped to participant-theme tokens so they follow
        the palette and dark mode. "white" is left as CSS white. Other
        values (hex, "var(...)") are used as-is. Default ""black"",
        which resolves to "--psynet-text".

      * **js** ("Optional"["str"]) -- Optional Javascript code to
        execute when the event occurs (default = "None").


FailedValidation
================

class psynet.timeline.FailedValidation(message='Invalid response, please try again.')


for_loop
========

psynet.timeline.for_loop(*, label, iterate_over, logic, time_estimate_per_iteration=None, expected_repetitions=None, stop_if=None)

   Run "logic" once for each item of "iterate_over".

   Parameters:
      * **label** ("str") -- Label of the loop, unique among loops
        nested in each other.

      * **iterate_over** ("Union"["Sequence", "Callable"["...",
        "Sequence"]]) -- The items, or a function taking "participant"
        and/or "experiment" that returns them when the participant
        reaches the loop.

      * **logic** ("Union"["Elt", "List"["Elt"], "EltCollection",
        "Callable"["...", "Union"["Elt", "List"["Elt"],
        "EltCollection"]]]) -- Timeline logic for one iteration, or a
        function taking the item (and optionally "participant" and
        "experiment") that returns it.

      * **time_estimate_per_iteration** ("Optional"["float"]) --
        Seconds one iteration is expected to take. Required if "logic"
        is a function.

      * **expected_repetitions** -- Expected number of iterations,
        used for time estimates. Inferred from "iterate_over" when it
        is a sequence or a function without arguments.

      * **stop_if** ("Optional"["Callable"]) -- Optional function
        taking "participant" and/or "experiment", checked before each
        iteration. Once it returns "True" the loop ends, after the
        iteration in progress has finished. For example,
        "stop_if=left_team" ends a game's rounds once the participant
        has left their team.


join
====

psynet.timeline.join(*args, stop_if=None)

   Join timeline elements, lists of elements and collections into one
   list.

   Parameters:
      * **args** -- Elements, lists or tuples of them, collections
        such as barriers or trial makers, and functions (which become
        "CodeBlock" s). "None" is skipped.

      * **stop_if** ("Optional"["Callable"]) -- Optional function
        taking "participant" and/or "experiment". If given, it is
        checked before each argument, and once it returns "True" the
        participant skips the remaining arguments. Each argument runs
        whole once started, so pass "join(...)" as one argument for
        steps that must not be separated. A list or tuple is one
        argument too: unpack it, as in "join(*steps, stop_if=...)", to
        check between its elements. For example, "join(rules_page,
        game_starts_barrier, stop_if=left_group)" skips the barrier
        for a participant who left their group while reading the
        rules. Rounds of a group game are cued trials, which run whole
        anyway. Use "for_loop()" with "stop_if" to stop a loop, and a
        "conditional()" after the "join" to show something to those
        who stopped.


MediaSpec
=========

class psynet.timeline.MediaSpec(audio=None, image=None, html=None, video=None)

   This object enumerates the media assets available for a given
   "Page" object.

   Parameters:
      * **audio** (*dict*) --

        A dictionary of audio assets. Each item can either be a
        string, corresponding to the URL for a single file (e.g.
        "/static/audio/test.wav"), or a dictionary, corresponding to
        metadata for a batch of media assets. A batch dictionary must
        contain the field "url", providing the URL to the batch file,
        and the field "ids", providing the list of IDs for the batch's
        constituent assets. A valid audio argument might look like the
        following:

           {
               'bier': '/static/bier.wav',
               'my_batch': {
                   'url': '/static/file_concatenated.mp3',
                   'ids': ['funk_game_loop', 'honey_bee', 'there_it_is'],
                   'type': 'batch'
               }
           }

      * **html** (*dict*) -- An analogously structured dictionary of
        HTML stimuli (e.g., SVG stimuli).

      * **image** (*dict*) -- An analogously structured dictionary of
        image stimuli.

      * **video** (*dict*) -- An analogously structured dictionary of
        video stimuli.


Module
======

class psynet.timeline.Module(id_=None, *args, assets=None, nodes=None, state_class=None)


Page
====

class psynet.timeline.Page(*, time_estimate=None, template_path=None, template_str=None, template_fragment_path=None, template_fragment_str=None, template_arg=None, label='untitled', js_vars=None, js_links=None, js_dependencies=None, js_page_modules=None, js_page_code=None, media=None, scripts=None, css=None, css_links=None, contents=None, session_id=None, save_answer=True, events=None, progress_display=None, start_trial_automatically=True, show_early_exit_button=None, show_abort_button=None, show_termination_button=None, aggressive_termination_on_no_focus=False, bot_response=NoArgumentProvided, validate=None, framework_owned_template=False, requires_full_page_reload=False, expect_scrolling=None, delegated_render=False, background_recording=None, time_limit=None, time_limit_answer=None)

   The base class for pages, customised by passing values to the
   "__init__" function and by overriding the following methods:

   * "format_answer()"

   * "validate()"

   * "metadata()"

   Parameters:
      * **time_estimate** ("Optional"["float"]) -- Time estimated for
        the page.

      * **background_recording** -- Optional background video
        alongside the ordinary answer: ""camera"", ""screen"",
        ""both"", or a "VideoRecordConfig". Clips are optional by
        default; "required=True" holds finalization and fails the
        parent trial if its recording is missing. See Recording video
        and audio, and handling uploads.

      * **template_path** ("Optional"["str"]) -- Path to the jinja2
        template to use for the page.

      * **template_str** ("Optional"["str"]) -- Alternative way of
        specifying the jinja2 template as a string.

      * **template_fragment_path** ("Optional"["str"]) -- Path to a
        jinja2 template containing only the contents of the timeline
        page's "main_body" block. This is the recommended custom-
        template style for pages used with
        "inplace_timeline_transitions".

      * **template_fragment_str** ("Optional"["str"]) -- Alternative
        way of specifying a main-body template fragment as a string.

      * **framework_owned_template** ("bool") -- Internal marker for
        PsyNet-owned templates. Framework pages may still use complete
        templates in SPA mode because PsyNet controls their page shell
        and lifecycle; experiment-authored complete templates should
        use "template_fragment_path" or "template_fragment_str" for
        SPA.

      * **delegated_render** ("bool") -- If "True", this page is a
        thin timeline wrapper whose "render" method supplies the
        response. It cannot be combined with a template.

      * **requires_full_page_reload** ("bool") -- If "True", this page
        always uses a full browser reload rather than an in-place
        transition. Use this as a per-page opt-out while migrating
        older custom frontends. Deprecated "js_links" / "scripts" also
        set this automatically. Default: "False".

      * **expect_scrolling** ("Optional"["bool"]) -- Declares whether
        the page is expected to be taller than the browser window.
        When "False" (default), PsyNet's front-end tests require the
        page not to scroll at all, which catches stimuli that grow
        large enough to push content off screen or underneath the
        footer. Set it to "True" for pages that legitimately need
        scrolling, such as long consent forms. Subclasses may also
        declare it as a class attribute; passing "True" or "False" to
        the constructor overrides that default. It has no effect on
        how the page behaves for participants.

      * **template_arg** ("Optional"["Dict"]) -- Dictionary of
        arguments to pass to the jinja2 template. "{{ ... }}" escapes
        plain strings; pass HTML as "markupsafe.Markup" or a
        "dominate" tag, and write values inside "<script>" with "|
        tojson".

      * **label** ("str") -- Internal label to give the page, used for
        example in results saving.

      * **js_vars** ("Optional"["Dict"]) -- Dictionary of page-scoped
        values exposed to JavaScript through "psynet.var". Legacy
        access through matching "window" properties is deprecated and
        controlled by "legacy_js_var_globals".

      * **js_links** ("Optional"["Sequence"["str"]]) -- Deprecated
        list of classic JavaScript files executed as linked classic
        scripts. Using this argument forces a full page reload. Prefer
        "js_dependencies" or "js_page_modules".

      * **js_dependencies** ("Optional"["Sequence"["str"]]) --
        Optional list of JavaScript file URLs to load once per browser
        document.

      * **js_page_modules** ("Optional"["Sequence"["str"]]) --
        Optional JavaScript files activated for each page. Each file
        must export an "activate(context)" function and may return a
        cleanup function.

      * **js_page_code** ("Union"["str", "Sequence"["str"], "None"])
        -- Optional inline JavaScript activation code, supplied as a
        string, list, or tuple. Code receives the same "root",
        "trial", "vars", "page", and "psynet" values as a page module
        and may return cleanup.

      * **media** ("psynet.timeline.MediaSpec") -- Optional
        specification of media assets to preload (see the
        documentation for "psynet.timeline.MediaSpec").

      * **scripts** ("Optional"["Sequence"["str"]]) -- Deprecated
        classic inline JavaScript executed with global script
        semantics. Using this argument forces a full page reload.
        Prefer "js_page_code".

      * **css** ("Optional"["List"]) --

        Optional list of CSS specification to include in the page.
        Each specification should be represented as a string, which
        will be passed verbatim to the page's HTML. A valid CSS
        specification might look like this:

           .modal-content {
               background-color: #4989C8;
               margin: auto;
               padding: 20px;
               border: 1px solid #888;
               width: 80%;
           }

           .close {
               color: #aaaaaa;
               float: right;
               font-size: 28px;
               font-weight: bold;
           }

      * **css_links** ("Optional"["List"]) -- Optional list of links
        to CSS stylesheets to include in the page.

      * **contents** ("Optional"["Dict"]) -- Optional dictionary to
        store some experiment specific data. For example, in an
        experiment about melodies, the contents property might look
        something like this: {”melody”: [1, 5, 2]}.

      * **save_answer** ("bool") -- If "True" (default), then the
        answer generated by the page is saved to "participant.answer",
        and a link to the corresponding "Response" object is saved in
        "participant.last_response_id". If "False", these slots are
        left unchanged. If a string, then the answer is not only saved
        to "participant.answer" and "participant.last_response_id",
        but it is additionally saved as a participant variable named
        by that string.

      * **events** ("Optional"["Dict"]) -- An optional dictionary of
        event specifications for the page. This determines the timing
        of various Javascript events that happen on the page. Each key
        of this dictionary corresponds to a particular event. Each
        value should then correspond to an object of class "Event".
        The "Event" object specifies how the event is triggered by
        other events. For example, if I want to define an event that
        occurs 3 seconds after the trial starts, I would write
        "events={"myEvent": Event(is_triggered_by="trialStart",
        delay=3.0)}". Useful standard events to know are "pageReady"
        (the page is initialized and navigation is valid),
        "trialStart" (start of the trial), "promptStart" (start of the
        prompt), "promptEnd" (end of the prompt), "recordStart"
        (beginning of a recording), "recordEnd" (end of a recording),
        "responseEnable" (enables the response options), and
        "submitEnable" (enables the user to submit their response).
        These events and their triggers are set to sensible defaults,
        but the user is welcome to modify them for greater
        customization. See also the "update_events" methods of
        "Prompt" and "Control", which provide alternative ways to
        customize event sequences for modular pages.

      * **progress_display** ("Optional"["ProgressDisplay"]) --
        Optional "ProgressDisplay" object.

      * **show_early_exit_button** ("bool") -- If "True" or "False",
        force the footer Leave control on or off for this page. If
        omitted, Leave follows "show_early_exit_button" in the
        experiment config or the recruiter default (on for Lucid).

      * **show_abort_button** ("bool") -- Deprecated alias for
        "show_early_exit_button".

      * **show_termination_button** ("bool") -- Deprecated alias for
        "show_early_exit_button".

      * **start_trial_automatically** ("bool") -- If "True" (default),
        the trial starts automatically, e.g. by the playing of a
        queued audio file. Otherwise the trial will wait for the
        trialPrepare event to be triggered (e.g. by clicking a 'Play'
        button, or by calling
        *psynet.trial.registerEvent("trialPrepare")* in JS).

      * **bot_response** -- Optional fixed answer, function, or
        "BotResponse" defining how bots respond to this page, in the
        same forms as for "Control". If set, it overrides the page's
        "get_bot_response()" method (and, on a "ModularPage", the
        control's bot response). "bot_response=None" makes bots submit
        an answer of "None"; leave it unset to use the default bot
        response.

      * **validate** ("Optional"["callable"]) --

        Optional validation function to use for the participant's
        response. Alternatively, the validation function can be set by
        overriding this class's "validate" method. If no validation
        function is found, no validation is performed. See
        "validate()" for information about how to write this function.

        Validation functions provided via the present route may
        contain various optional arguments. Most typically the
        function will be of the form "lambda answer: ...` or ``lambda
        answer, participant: ...", but it is also possible to include
        the arguments "raw_answer", "response", "page", and
        "experiment". Note that "raw_answer" is the answer before
        applying "format_answer", and "answer" is the answer after
        applying "format_answer".

        Validation functions should return "None" if the validation
        passes, or if it fails a string corresponding to a message to
        pass to the participant.

        For example, a validation function testing that the answer
        contains exactly 3 characters might look like this: "lambda
        answer: "Answer must contain exactly 3 characters!" if
        len(answer) != 3 else None".

      * **time_limit** ("Optional"["float"]) --

        Optional seconds the participant has on this page. When they
        run out, the page submits itself and "time_limit_answer" is
        recorded.

        * The server counts from when the participant reached the
          page, so reloading the page does not restart the clock.

        * An answer that reaches the server more than 5 seconds after
          the limit counts as late and is treated the same way.

        * Answers given because of the time limit skip validation, and
          their "Response.time_limit_reached" is "True".

        * The page shows "N s left" at the top. An element with the
          attribute "data-psynet-seconds-left" in the page's content
          shows the countdown instead.

        * Just before the page submits itself, the browser dispatches
          a "psynet:timeLimitReached" event on "document", so custom
          JavaScript can stage its state in "psynet.response.staged"
          (kept only with "time_limit_answer=CURRENT_ANSWER", on pages
          without a built-in control).

        * Cannot be combined with "session_id".

      * **time_limit_answer** -- The answer recorded when "time_limit"
        runs out (default "None"), so passing it without "time_limit"
        raises an error. Pass "CURRENT_ANSWER" to record what the
        participant has entered so far instead: the page's controls
        submit their current answer, which is formatted as usual but
        not validated, so "format_answer" should accept an incomplete
        answer. If the page has no answer to submit, "None" is
        recorded. An answer that arrives more than 5 seconds after the
        limit is kept the same way.

   contents

      A dictionary containing experiment specific data.

      Type:
         dict

   session_id

      If session_id is not None, then it must be a string. If two
      consecutive pages occur with the same session_id, then when it's
      time to move to the second page, the browser will not navigate
      to a new page, but will instead update the Javascript variable
      psynet.page with metadata for the new page, and will trigger an
      event called pageUpdated. This event can be listened for with
      Javascript code like window.addEventListener(”pageUpdated”,
      ...).

      Type:
         str

   dynamically_update_progress_bar_and_reward

      If "True", then the page will regularly poll for updates to the
      progress bar and the reward. If "False" (default), the progress
      bar and reward are updated only on page refresh or on transition
      to the next page.

      Type:
         bool

   attributes(participant)

      Returns a dictionary of page metadata for the browser, including
      "session_id", "type", and "page_uuid". Partner-ready
      "arrival_updates" are included only when this participant is in
      an active sync group and the page is not already a timeline
      hold.

   call__get_bot_response(experiment, bot, response=NoArgumentProvided)

      Constructs the appropriate bot_response for the page.

      The bot_response can be specified in two main ways: - By passing
      an argument to the __init__ method - By overriding the
      "get_bot_response()" method

      The former takes priority.

   early_exit_available(experiment, participant)

      Return whether this page may offer the participant an early
      exit.

      Leaving early costs the participant the difference between the
      completion payment and the recruiter's early-exit payment, so it
      is never offered once the participant has nothing left to lose
      by finishing: end-of-experiment pages, release pages, and
      participants who have already left.

      Return type:
         "bool"

   format_answer(raw_answer, **kwargs)

      Formats the raw answer object returned from the participant's
      browser.

      Parameters:
         * **raw_answer** -- The raw answer object returned from the
           participant's browser.

         * ****kwargs** --

           Keyword arguments, including:

           1. "blobs": A dictionary of any blobs that were returned
              from the participant's browser.

           2. "metadata": The metadata returned from the participant's
              browser.

           3. "experiment": An instantiation of
              "psynet.experiment.Experiment", corresponding to the
              current experiment.

           4. "participant": An instantiation of
              "psynet.participant.Participant", corresponding to the
              current participant.

      Returns:
         * *Object* -- The formatted answer, suitable for
           serialisation to JSON and storage in the database.

   get_bot_response(experiment, bot)

      This function is used when a bot simulates a participant
      responding to a given page. In the simplest form, the function
      just returns the value of the answer that the bot returns, which
      is saved without passing through "format_answer". For more
      sophisticated treatment, the function can return a "BotResponse"
      object which contains other parameters such as "blobs" and
      "metadata". PsyNet's built-in answer controls return
      "BotResponse(raw_answer=...)" with what the browser would
      submit, so that bot answers pass through the same
      "format_answer" methods as browser answers.

   metadata(**kwargs)

      Compiles metadata about the page or its response from the
      participant. This metadata will be merged with the default
      metadata object returned from the browser, with any duplicate
      terms overwritten.

      Parameters:
         ****kwargs** --

         Keyword arguments, including:

         1. "raw_answer": The raw answer returned from the
            participant's browser.

         2. "answer": The formatted answer.

         3. "metadata": The original metadata returned from the
            participant's browser.

         3. "experiment": An instantiation of
            "psynet.experiment.Experiment", corresponding to the
            current experiment.

         4. "participant": An instantiation of
            "psynet.participant.Participant", corresponding to the
            current participant.

      Returns:
         * *dict* -- A dictionary of metadata.

   property min_duration

      Return the shortest time, in seconds, before a participant can
      submit this page.

      This is the earliest time at which the page's "submitEnable"
      event can fire, following the delays of its triggers (see
      "Event"), for example a recording's duration or an audio meter's
      "min_time". Events that only the page's JavaScript fires, such
      as the end of a media prompt, count as immediate, so this is a
      lower bound. Bots that simulate page times ("time_factor" above
      0) never submit sooner.

   property plain_text

      A plain text version of the page's content. This is used for
      testing purposes. Users are invited to override this method in
      subclasses.

   pre_render()

      This method is called immediately prior to rendering the page
      for the participant. It will be called again each time the
      participant refreshes the page.

   validate(response, **kwargs)

      Takes the "psynet.timeline.Response" object created by the page
      and runs a validation check to determine whether the participant
      may continue to the next page.

      Parameters:
         * **response** -- An instance of "psynet.timeline.Response".
           Typically the "answer" attribute of this object is most
           useful for validation.

         * ****kwargs** --

           Keyword arguments, including:

           1. "experiment": An instantiation of
              "psynet.experiment.Experiment", corresponding to the
              current experiment.

           2. "participant": An instantiation of
              "psynet.participant.Participant", corresponding to the
              current participant.

           3. "answer": The formatted answer returned by the
              participant.

           4. "raw_answer": The unformatted answer returned by the
              participant.

           5. "page": The page to which the participant is responding.

      Returns:
         * "None" or an object of class
           "psynet.timeline.FailedValidation" -- On the case of failed
           validation, an instantiation of
           "psynet.timeline.FailedValidation" containing a message to
           pass to the participant.


PageMaker
=========

class psynet.timeline.PageMaker(function, time_estimate=None, accumulate_answers=False, label='page_maker')

   A page maker is defined by a function that is executed when the
   participant requests the relevant page.

   Parameters:
      * **function** ("Callable"["...", "Union"["Elt", "List"["Elt"],
        "EltCollection"]]) -- A function that may take up to two
        arguments, named "experiment" and "participant". These
        arguments correspond to instantiations of the class objects
        "psynet.experiment.Experiment" and
        "psynet.participant.Participant" respectively. The function
        should return either a single test element (e.g.
        "psynet.timeline.Page", "psynet.timeline.PageMaker",
        "psynet.timeline.CodeBlock") or a list of such elements. Note
        that "psynet.timeline.PageMaker" objects can be nested
        arbitrarily deeply. Note also that, if the page maker returns
        multiple pages, then the function will be recomputed each time
        the participant progresses to the next page. This
        functionality can be used to make the latter pages depend on
        the earlier pages in the page maker.

      * **time_estimate** ("Optional"["float"]) -- Time estimated to
        complete the segment. This time estimate is used for
        predicting the overall length of the experiment and hence
        generating the progress bar. The actual time credit given to
        the participant is determined by "time_estimate" parameters
        provided to the pages generated by "function". However, there
        is an exception provided for back-compatibility: if "function"
        generates a list containing solely "psynet.timeline.Page" or
        "psynet.timeline.PageMaker" objects, and if those objects are
        all missing "time_estimate" values, then these "time_estimate"
        values will be imputed by dividing the parent
        "psynet.timeline.PageMaker"'s "time_estimate" by the number of
        produced elements.

      * **accumulate_answers** ("bool") -- If "True",
        "participant.answer" becomes a dict when the page maker
        starts, and each page saves its answer under its label as soon
        as it is submitted, so later pages can read earlier answers. A
        repeated label is saved as "label_1", "label_2" and so on.
        Answers from nested accumulating page makers or trials go into
        the same dict.


ParticipantFailRoutine
======================

class psynet.timeline.ParticipantFailRoutine(label, function)

   Runs a function whenever a participant is failed.

   Place it in the timeline; it does not show anything to the
   participant.

   Parameters:
      * **label** -- Label identifying the routine in the logs.

      * **function** -- Function to run. It can take "participant" and
        "experiment" as arguments.


Progress display
================

class psynet.timeline.ProgressDisplay(stages, start='trialStart', show_bar=True, show_caption=True, **kwargs)

class psynet.timeline.ProgressStage(time, caption='', color='var(--psynet-accent)', persistent=False)

   A timed segment of a "ProgressDisplay".

   "color" is a CSS colour for the bar segment and caption. Named
   colours such as "red", "green", "blue", "orange", and "grey" are
   mapped to participant-theme tokens so they follow the palette and
   dark mode. "white" is left as CSS white. Other values (hex,
   "var(...)") are used as-is. The default is "var(--psynet-accent)".


PreDeployRoutine
================

class psynet.timeline.PreDeployRoutine(label, function, args=None)

   Bases: "NullElt"

   A timeline component that allows for the definition of tasks to be
   performed before deployment. It is possible to make database
   changes as part of these routines and these will be propagated to
   the deployed experiment.

   Parameters:
      * **label** -- A label describing the pre-deployment task.

      * **function** -- The name of a function to be executed.

      * **args** -- The arguments for the function to be executed.


randomize
=========

psynet.timeline.randomize(*, label, logic)

   Randomizes the order of a series of logical units. This could be
   used, for example, to randomize the order of a series of
   questionnaires. Each participant will receive a different random
   order.

   Parameters:
      * **label** -- Internal label to assign to the construct.

      * **logic** -- A list to be randomized. Each element should be a
        unit of timeline logic, for example a trial maker or a
        sequence of Elts created through the join function.


Response
========

class psynet.timeline.Response(*args, **kwargs)

   Bases: "_Response"

   A database-backed object that stores the participant's response to
   a "Page". By default, one such object is created each time the
   participant tries to advance to a new page.

   answer

      The participant's answer, after formatting.

   page_type

      The type of page administered.

      Type:
         str

   successful_validation

      Whether the response validation was successful, allowing the
      participant to advance to the next page.

      Type:
         bool

   trial_id

      ID of "trial".

      Type:
         int

   trial

      The "Trial" whose pages ("show_trial()") the participant
      submitted this response on, including submissions rejected by
      validation. "None" for pages outside a trial, including feedback
      pages and pages submitted after the participant failed.
      Recordings follow a different rule: a recording made on a
      feedback page ("show_feedback()") is stored with the trial that
      just finished.

   property async_processes

      Deprecated alias of "async_jobs".

   creation_time

      the time at which the Network was created.

   details

      a generic column for storing structured JSON data

   failed

      boolean indicating whether the Network has failed which prompts
      Dallinger to ignore it unless specified otherwise. Objects are
      usually failed to indicate something has gone wrong.

   failed_reason

      an optional reason the object was failed. If the object is
      failed as part of a cascading failure triggered from another
      object, the chain of objects will be captured in this field.

   id

      a unique number for every entry. 1, 2, 3 and so on...

   property metadata

      A dictionary of metadata associated with the Response object.
      Stored in the "details" field in the database.

   property1

      a generic column that can be used to store experiment-specific
      details in String form.

   property2

      a generic column that can be used to store experiment-specific
      details in String form.

   property3

      a generic column that can be used to store experiment-specific
      details in String form.

   property4

      a generic column that can be used to store experiment-specific
      details in String form.

   property5

      a generic column that can be used to store experiment-specific
      details in String form.

   property time_limit_reached: bool

      Whether the page's "time_limit" ran out before this answer was
      given.

      See "Page".

   time_of_death

      the time at which failing occurred

   property too_late_for_group: bool

      Whether this answer arrived after the participant's group went
      on without them.

      It is "True" when a barrier removed the participant from their
      group for being late ("late_after", with any "late_action")
      while they were on this page, whether the group carried on or
      was dissolved. The group didn't use the answer, so a move in a
      game, for example, usually shouldn't count.

   type

   vars


Switch statements
=================

psynet.timeline.switch(label, function, branches, fix_time_credit=False, bound_progress=True, log_chosen_branch=True, time_estimate=None)

   Selects a series of elts to display to the participant according to
   a certain condition.

   Parameters:
      * **label** ("str") -- Internal label to assign to the
        construct.

      * **function** ("Callable") -- A function with up to two
        arguments named "participant" and "experiment", that is
        executed once the participant reaches the corresponding part
        of the timeline, returning a key value with which to index
        "branches".

      * **branches** ("dict") -- A dictionary indexed by the outputs
        of "function"; each value should correspond to an elt (or list
        of elts) that can be selected by "function".

      * **fix_time_credit** ("bool") -- Whether participants should
        receive the same time credit irrespective of the branch taken.
        Defaults to "False"; if set to "True", all participants
        receive the same credit, corresponding to the branch with the
        maximum time credit.

      * **bound_progress** ("bool") -- Whether the progress estimate
        should be 'bound' such that, whatever happens, when the
        participant exits the conditional construct, the progress
        estimate will be the same as if the participant had taken the
        branch with the maximum time credit. Defaults to "True".

      * **log_chosen_branch** ("bool") -- Whether to keep a log of
        which participants took each branch; defaults to "True".

      * **time_estimate** ("float") -- An optional time estimate to
        use for the switch construct. If not provided, the time
        estimate will be estimated by computing time estimates for all
        branches and taking the maximum.

   Returns:
      * *list* -- A list of elts that can be embedded in a timeline
        using "psynet.timeline.join()".


Timeline
========

class psynet.timeline.Timeline(*args, **branch_kwargs)


While loops
===========

psynet.timeline.while_loop(label, condition, logic, expected_repetitions, max_loop_time=None, fix_time_credit=True, fail_on_timeout=True, on_timeout=None, extend_while=None, _ends_in_released_pass=True)

   Loops a series of elts while a given criterion is satisfied. The
   criterion function is evaluated once at the beginning of each loop.
   Inside a barrier's "waiting_logic", the loop ends at its next check
   once the barrier releases the participant. This also ends PsyNet's
   own waits in that pass, such as waiting for a trial or for
   asynchronous processing.

   Parameters:
      * **label** ("str") -- Internal label to assign to the
        construct.

      * **condition** ("Callable") -- A function with up to two
        arguments named "participant" and "experiment", that is
        executed once the participant reaches the corresponding part
        of the timeline, returning a Boolean.

      * **logic** -- An elt (or list of elts) to display while
        "condition" returns "True". The loop uses copies of these
        elts, so a "GoTo" outside the loop can't target one of them.

      * **expected_repetitions** ("int") -- The number of times the
        loop is expected to be seen by a given participant. This
        doesn't have to be completely accurate, but it is used for
        estimating the length of the total experiment.

      * **max_loop_time** ("Union"["float", "Callable", "None"]) --
        The maximum time in seconds for staying in an active loop.
        Once exceeded, the participant is presented the
        "UnsuccessfulEndPage" unless "fail_on_timeout" is False.
        Default: None (unlimited). May also be a callable accepting
        "participant" and/or "experiment" and returning seconds or
        None. It is evaluated once on entering the loop; polling does
        not restart or recalculate the budget.

      * **fix_time_credit** -- Whether participants should receive the
        same time credit irrespective of whether "condition" returns
        "True" or not; defaults to "True", so that all participants
        receive the same credit.

      * **fail_on_timeout** -- Whether the participants should be
        failed when the "max_loop_time" is reached. Setting this to
        "False" will not return the "UnsuccessfulEndPage" when maximum
        time has elapsed but allow them to proceed to the next page.

      * **on_timeout** ("Optional"["Callable"]) -- Optional callable
        invoked when "max_loop_time" is exceeded. Called with
        "participant=...".

      * **extend_while** ("Optional"["Callable"]) -- Optional callable
        accepting "participant" and/or "experiment", checked at the
        start of each pass through the loop. Whenever it returns
        "True", the loop does not time out on that pass and the
        "max_loop_time" clock restarts from zero.

   Returns:
      * *list* -- A list of elts that can be embedded in a timeline
        using "psynet.timeline.join()".


NullElt
=======

class psynet.timeline.NullElt


WebSocketElt
============

class psynet.timeline.WebSocketElt(**kwargs)

   A timeline element that registers a WebSocket message handler on
   the experiment.

   Adding a "WebSocketElt" to the timeline will:

   1. Subscribe the experiment to "WebSocketElt.channel" at launch,
      enabling it to receive WebSocket messages on that channel.

   2. Register "handle_message" as a handler called by the
      experiment's "receive_message" whenever a message arrives on
      that channel.

   Each "WebSocketElt" subclass should define a unique "channel" name
   so that multiple Websocket consumers in the same timeline can
   remain isolated from one another.

   Example:

      from psynet.timeline import WebSocketElt

      class RoundOneChatElt(WebSocketElt):
          channel = "chat_round_one"

          def handle_message(self, message, channel_name, participant, node,
                             receive_time, experiment):
              import json
              data = json.loads(message)
              # ... process data ...

   channel

      The Redis channel name this Elt subscribes to. If "None", no
      subscribers will be registered.

      Type:
         str

   requires_checked_connection

      If "True", "handle_message" is called only for messages sent
      through "dallinger.openExperimentSocket({scope:
      psynetTemplateData.websocketScope})", whose connection PsyNet
      has checked belongs to "participant", and runs on the web
      process holding that socket. Messages on the channel from
      "/chat" sockets are ignored, because they can name any
      participant. Defaults to "False".

      Type:
         bool
