Experiment
**********

class psynet.experiment.Experiment(**kwargs)

   Bases: "Experiment"

   The main experiment class from which to inherit when building
   experiments.

   Several experiment options can be set through the experiment class.
   For example, the storage back-end can be selected by setting the
   "asset_storage" attribute:

      class Exp(psynet.experiment.Experiment):

   Config variables can be set here, amongst other places (see online
   documentation for details):

      class Exp(psynet.experiment.Experiment):
          config = {
              "min_reward_for_paid_early_exit": 0.15,
              "show_early_exit_button": True,
          }

   Custom CSS stylesheets can be included here, to style the
   appearance of the experiment:

      class Exp(psynet.experiment.Experiment):
          css_links = ["static/theme.css"]

   CSS can also be included directly as part of the experiment class
   via the "css" attribute, see "custom_theme" demo for details.

   There are a number of variables tied to an experiment all of which
   are documented below. They have been assigned reasonable default
   values which can be overridden when defining an experiment (see
   method "_default_variables"). Also, they can be enriched with new
   variables in the following way:

      import psynet.experiment

      class Exp(psynet.experiment.Experiment):
          variables = {
              "new_variable": "some-value",  # Adding a new variable
          }

   These variables can then be changed in the course of experiment,
   just like (e.g.) participant variables.

      from psynet.timeline import CodeBlock

      CodeBlock(lambda experiment: experiment.var.set("custom-variable", 42))

   Default experiment variables accessible through
   *psynet.experiment.Experiment.var* are:

   max_participant_payment : *float*
      The maximum payment a participant is allowed to get, in the
      currency set by the "currency" configuration key. Default:
      *25.0*.

   soft_max_experiment_payment : *float*
      The recruiting process stops if "amount_spent()" (recorded
      "base_payment" + "bonus" for every participant, including those
      still in progress) exceeds this value. Default: *1000.0*.

   hard_max_experiment_payment : *float*
      Guarantees that in an experiment no more is spent than the value
      assigned. A bonus that would exceed this value is clipped to
      remaining room (or not paid if that remainder is below $0.01).
      "planned_bonus" stays the decided amount, delivered "bonus" is
      what was sent, and "bonus_status = capped". Default: *1100.0*.

   big_base_payment : *bool*
      Set this to *True* if you REALLY want to set *base_payment* to a
      value > 20.

   max_concurrent_participants : *int* or *None*
      The maximum number of participants taking the study at once;
      newcomers over the limit wait on the start page until there is
      space (see "is_at_capacity()"). Only supported with the
      "generic" and "hotair" recruiters. "0" admits nobody new.
      Default: *None* (no limit).

   There are also a few experiment variables that are set
   automatically and that should, in general, not be changed manually:

   psynet_version : *str*
      The version of the *psynet* package.

   dallinger_version : *str*
      The version of the *Dallinger* package.

   python_version : *str*
      The version of the *Python*.

   hard_max_experiment_payment_email_sent : *bool*
      Whether an email to the experimenter has already been sent
      indicating the *hard_max_experiment_payment* had been reached.
      Default: *False*. Once this is *True*, no more emails will be
      sent about this payment limit being reached.

   soft_max_experiment_payment_email_sent : *bool*
      Whether an email to the experimenter has already been sent
      indicating the *soft_max_experiment_payment* had been reached.
      Default: *False*. Once this is *True*, no more emails will be
      sent about this payment limit being reached.

   In addition to the config variables in Dallinger, PsyNet adds the
   following:

   wage_per_hour : *float*
      The payment in currency the participant gets per hour. Default:
      *9.0*.

   currency : *str*
      The currency in which the participant gets paid. Default: *$*.

   min_reward_for_paid_early_exit : *float*
      Minimum accumulated reward required before a paid recruiter
      permits paid Leave. Below this, the confirmation explains that
      leaving with payment is not yet allowed. Lucid termination is
      not gated by this value. Default: *0.20*.

   show_early_exit_button : *bool*
      If "True", participants may leave early for accumulated-reward
      compensation. The timeline footer then includes Leave (unless a
      page sets "show_early_exit_button=False"). Leave opens an in-
      page confirmation, while the error page provides a fallback if
      the timeline cannot continue. The ad page does not provide an
      early-exit control, and neither do the end-of-experiment pages,
      where leaving could only reduce the participant's payment.
      Confirming fails the participant so Prolific uses the
      unsuccessful/partial-payment route; Lucid terminates the panel
      session. Default "False". "Page(show_abort_button=...)" and
      "Page(show_termination_button=...)" are deprecated aliases for
      the per-page override; use "show_early_exit_button" instead.

   show_reward : *bool*
      If "True", then the participant's current estimated reward is
      displayed at the bottom of the page, and the end-of-experiment
      page reports it. If left unset, the recruiter decides:
      recruiters that pay through a platform show the reward, while
      generic and local recruitment does not. See "show_reward".

   show_footer : *bool*
      If "True" (default), then a footer may be displayed at the
      bottom of the page. It holds reward information if *show_reward*
      resolves to *True*, a 'Comment' button if
      *leave_comments_on_every_page* is set, and Leave if
      *show_early_exit_button* is set or the recruiter requires one
      (Lucid). The footer is omitted when none of these apply, so that
      an empty bar does not take up space.

   show_progress_bar : *bool*
      If "True" (default), then a progress bar is displayed at the top
      of the page.

   check_participant_opened_devtools : "bool"
      If "True", whenever a participant opens the developer tools in
      the web browser, this is logged as
      participant.var.opened_devtools = "True", and the participant is
      shown a warning alert message. Default: "False". Note: Chrome
      does not currently expose an official way of checking whether
      the participant opens the developer tools. People therefore have
      to rely on hacks to detect it. These hacks can often be broken
      by updates to Chrome. We've therefore disabled this check by
      default, to reduce the risk of false positives. Experimenters
      wishing to enable the check for an individual experiment are
      recommended to verify that the check works appropriately before
      relying on it. We'd be grateful for any contributions of updated
      developer tools checks.

   window_width : "int"
      Determines the width in pixels of the window that opens when the
      participant starts the experiment. Only active if
      recruiter.start_experiment_in_popup_window is True. Default:
      "1024".

   window_height : "int"
      Determines the width in pixels of the window that opens when the
      participant starts the experiment. Only active if
      recruiter.start_experiment_in_popup_window is True. Default:
      "768".

   supported_locales : "list"
      Locales (ISO language codes) that the experiment is translated
      into, e.g., "'["de", "nl"]'". Each deployment runs in the single
      locale set by "locale". Default: "'[]'".

   force_google_chrome : "bool"
      *Deprecated.* Forces the user to use a Chromium-based browser
      (Chrome, Edge, Brave, Opera). If another browser is used,
      participants see instructions to install Chrome. Default:
      "False".

      Note: when used with Lucid recruitment, the Lucid qualification
      (QuestionID 1035) gates on the Chrome brand only, so
      Edge/Brave/Opera participants are excluded at the recruitment
      stage even though PsyNet would admit them. This mismatch cannot
      be resolved until Lucid exposes Chromium-based precodes. Prefer
      "browser_capabilities" for feature requirements; leave this
      unset to admit all modern browsers.

   leave_comments_on_every_page : "bool"
      Allows the user to leave comments on every page. Default:
      "False".

   force_incognito_mode : "bool"
      Forces the user to open the experiment in a private browsing
      (i.e. incognito mode). This is helpful as incognito mode
      prevents the user from accessing their browsing history, which
      could be used to influence the experiment. Furthermore it does
      not enable addons which can interfere with the experiment. If
      the user is not using incognito mode, it will give detailed
      instructions on how to open the experiment in incognito mode.
      Default: "False".

   allow_mobile_devices : "bool"
      Allows the user to use mobile devices. If it is set to false it
      will tell the user to open the experiment on their computer.
      Default: "True".

   needs_internet_access: "bool"
      Indicates whether the experiment needs internet access. Can be
      set to "False" for lab or field studies. Default: "True".

   debug_ssh_app : "bool"
      Marks an SSH app as one that "psynet debug ssh" (or "psynet
      performance-test ssh") deployed, which sets it. When "psynet
      destroy ssh" cannot check such an app for pending async jobs, it
      destroys the app instead of refusing. When the check runs,
      pending jobs are handled as for any other app. Don't set it
      yourself. Default: "False".

   performance_test_app : "bool"
      Marks an SSH app as one that "psynet performance-test ssh" may
      load, reset and pre-fill, which means that its data is
      disposable. "performance-test ssh" sets it when it deploys an
      app for its tests, and refuses to run on apps without it.
      Setting it yourself declares that the app's data may be deleted.
      Default: "False".

   performance_test_local_packages : "str"
      The packages, "psynet" and/or "dallinger" separated by commas,
      that "psynet performance-test ssh" built into the app's image
      from local checkouts ("--use-local-psynet", "--use-local-
      dallinger"). It sets this when it deploys the app, and later
      updates of the app build them in again. Don't set it yourself.
      Default: unset.

   Parameters:
      **session** -- The experiment's connection to the database.

   exception HandledError(message=None, participant=None, participant_id=None, **kwargs)

      Bases: "Exception"

   class RejectedConsentLogic(*args, **kwargs)

      Bases: "UnsuccessfulEndLogic"

      before_debrief_logic()

         Return timeline logic to run after "before_debrief", such as
         an "AsyncCodeBlock".

         Return type:
            "Union"["Elt", "List"["Elt"], "EltCollection"]

      static has_rejected_consent_to_report(experiment, participant)

         Whether the recruiter needs to hear about the rejection, so a
         worker job is worth queuing.

         Return type:
            "bool"

      static report_rejected_consent(experiment, participant)

         Tell the recruiter that the participant rejected consent.

         Runs in a worker process because recruiters call their
         platform here; the participant does not wait for it. For
         Lucid it is queued before the debrief page, because its auto-
         redirect bypasses "release_participant". The redirect and
         this call send Lucid the same terminate callback, so either
         may arrive first.

         Return type:
            "None"

   class SuccessfulEndLogic(time_limit=None)

      Bases: "EndLogic"

   class UnsuccessfulEndLogic(failure_tags=None, *, failure_message=None, time_limit=None, **kwargs)

      Bases: "EndLogic"

      Show the early-end page to a participant who failed or was
      screened out.

      Parameters:
         * **failure_tags** ("Optional"["List"]) -- Tags appended to
           the participant's "failure_tags" on this page.

         * **time_limit** ("Optional"["float"]) -- See "EndLogic".

         * **failure_message** ("Union"["str", "Callable", "None"]) --
           Optional line that says why the participant stopped early,
           or a function of "participant" (and, if it asks for them,
           other context arguments such as "experiment") that returns
           one, or "None". Without one, or when it returns "None",
           PsyNet explains its own multiplayer reasons: waiting too
           long at a barrier, being too slow to reach the next one, or
           the group becoming too small. A plain string replaces these
           built-in lines for every participant, so prefer a function
           that returns "None" for reasons you don't handle. Returning
           """" shows no line at all. If the function raises, PsyNet
           logs the error and shows its built-in line.

      failure_reason(participant)

         Return the line explaining why the participant stopped early,
         or "None".

   accept_websocket_connection(participant_id, scope)

      Accept a websocket connection only from one of the participant's
      own pages.

      PsyNet's pages send "websocket_scope" as the connection's scope.

   classmethod amount_spent()

      Return recorded spend across all participants.

      This is the sum of each participant's "base_payment" and
      "bonus", including people who have started the study but not
      finished. A participant is assigned "base_payment =
      experiment.base_payment" when they start, so their full study
      base is already reserved here while they are still in progress.
      Do not add a separate outstanding- base term on top of this
      figure (for example when applying spend caps).

      After payment is recorded, "base_payment" may be rewritten to
      the platform amount actually used (for example a Prolific
      screen-out reward, or "0" for a returned submission). "bonus"
      stays "None" until a transfer succeeds. Planned bonuses that
      were capped, dismissed, or left unconfirmed are not included.

   apply_payment_caps(participant, bonus)

      Return the bonus that may actually be transferred after spend
      caps.

      If paying "bonus" would exceed "hard_max_experiment_payment",
      the payout is clipped to remaining room (or "0" if none).
      "planned_bonus" stays the decided amount and the experimenter is
      emailed once. "bonus_status" is not set here; the caller settles
      "capped" after the transfer claim. If it would exceed
      "max_participant_payment", the bonus is reduced to the remaining
      room under that cap without using "capped" unless the hard cap
      already reduced it.

      Return type:
         "float"

   assignment_abandoned(participant)

      What to do if a participant abandons the hit.

      This runs when a notification from AWS is received indicating
      that *participant* has run out of time. Calls
      "fail_participant()".

   assignment_reassigned(participant)

      What to do if the assignment assigned to a participant is
      reassigned to another participant while the first participant is
      still working.

      This runs when a participant is created with the same
      assignment_id as another participant if the earlier participant
      still has the status "working". Calls "fail_participant()".

   assignment_returned(participant)

      What to do if a participant returns the hit.

      This runs when a notification from AWS is received indicating
      that *participant* has returned the experiment assignment. Calls
      "fail_participant()".

   attention_check_failed(participant)

      Ignore Dallinger's post-submission attention check.

      See "data_check_failed()".

   property authenticated_session

      Return a dashboard-authenticated session for the current thread.

      "requests.Session" is not thread-safe, so each thread keeps its
      own session. The process logs in once per server and every
      thread's session reuses that login's cookies, so bots running in
      threads don't each log in.

   classmethod backup_database()

      Store a fresh complete export as the deployment's latest
      artifact.

   bonus(participant)

      The bonus to be awarded to the given participant.

      Return the value of the bonus to be paid to *participant*. By
      default returns 0.

   browser_capabilities: frozenset = frozenset({})

      Browser features the experiment requires, such as
      "{"microphone"}".

      PsyNet screens participants for these at the start of the
      timeline; see "get_browser_capability_check()" and
      Configuration.

   classmethod build_export_archive(export_dir, *, assets='collected', asset_bytes='include')

      Build the canonical export in "export_dir" and zip it beside
      that tree.

      "asset_bytes="manifest"" describes the selected assets without
      copying their bytes, for clients that fetch the bytes
      themselves.

   classmethod busy_response()

      Return HTTP 503 so clients retry instead of treating this as
      success.

      JSON is the default: bots retry on "status" / "submission"
      "busy", and POSTs plus "mode=json" stay machine-readable.
      Browser HTML GET requests get a short refresh page instead of
      raw JSON.

   change_lucid_status()

      Set the Lucid survey status chosen on the dashboard's Lucid tab.

   classmethod check_max_concurrent_participants_support(config)

      Reject participant limits for recruiters that send paid
      participants.

      Raises:
         * **ValueError** -- If the class sets an invalid
           "max_concurrent_participants".

         * **RuntimeError** -- If the recruiter named in the
           configuration (ignoring the     debug-mode stand-in) is
           missing, unknown or doesn't support     participant limits.

   check_recruiter_exit(participant)

      Refuse "/recruiter-exit" unless its "unique_id" is the
      participant's.

      An experiment that overrides this method must return the result
      of "super().check_recruiter_exit(participant)" whenever it would
      otherwise return "None".

   static check_recruiter_support(config)

      Reject recruitment platforms that PsyNet no longer supports.

   classmethod check_size(*, heroku=False)

      Reject deployment plans that exceed the configured package
      limit.

   classmethod check_stale_ad_page_override()

      Fail fast when an experiment overrides removed Lab ad hooks.

   classmethod check_stale_bonus_override()

      Fail fast when an experiment overrides removed payment methods.

      Payment amounts are decided by the recruiter's "decide_payment"
      method; an "Experiment.bonus" or "check_bonus" override would be
      silently ignored.

   classmethod check_stale_error_page_override()

      Fail fast when an experiment overrides a removed error-page
      hook.

   classmethod check_unused_dallinger_quality_checks()

      Reject experiment overrides of unused Dallinger quality-check
      hooks.

      PsyNet fails participants during the timeline ("fail()",
      "UnsuccessfulEndPage") and does not call Dallinger's
      "data_check" / "attention_check" path, which would otherwise set
      "bad_data" / "did_not_attend".

   check_worker_status(participant)

      Refuse "/worker_complete" and "/worker_failed" unless their
      "unique_id" is the participant's.

      Dallinger also calls this from "/handle-error", which then still
      records the error report but doesn't complete the participant.

      An experiment that overrides this method must return the result
      of "super().check_worker_status(participant)" whenever it would
      otherwise return "None".

   clip_bonus_for_spend_caps(participant, bonus, *, record=True)

      Return "(payable, hard_capped)" after experiment spend caps.

      "hard_capped" is True when "hard_max_experiment_payment" reduced
      the payout. This method does not use "bonus_status" as the clip
      signal; "record=True" still writes "planned_bonus" and sends cap
      emails, but does not set "capped" (settlement happens after the
      transfer claim). "record=False" is for dashboard Pay, which must
      not settle the participant before the POST.

      The hard cap is evaluated per payout against current
      "amount_spent()"; it is not latched after the first clip.
      Concurrent payouts can each see the same remainder and together
      spend past the cap. Soft experiment spend limits are enforced
      when recruiting ("need_more_participants"), not here. In-
      progress participants already reserve their study base inside
      "amount_spent()"; see that method rather than adding a separate
      outstanding-base term here.

      Return type:
         "tuple"["float", "bool"]

   commit_payment_state()

      Persist claimed payment fields so a crash cannot replay a POST.

      Recruiters call this just before posting a payment. Like any
      commit, it raises inside timeline steps, so payments made from
      experiment code belong in an "AsyncCodeBlock".

   compile_translations_if_necessary(locales_dir, namespace)

      Compiles translations if necessary.

   classmethod config_defaults()

      Override this classmethod to register new default values for
      config variables. Remember to call super!

   classmethod config_settings()

      Values set in the experiment's "config" dictionary.

      These are the experimenter's explicit decisions: they override
      the user's "~/.dallingerconfig". The experiment's "config.txt"
      formally takes precedence over them (though PsyNet forbids
      setting the same key in both places), followed by environment
      variables and runtime writes.

   create_participant(*args, **kwargs)

      Creates and returns a new participant object. Uses
      "participant_constructor" as the constructor.

      Parameters:
         * **worker_id** (*str*) -- the recruiter Worker Id

         * **hit_id** (*str*) -- the recruiter HIT Id

         * **assignment_id** (*str*) -- the recruiter Assignment Id

         * **mode** (*str*) -- the application mode

         * **recruiter_name** (*str*) -- the recruiter name

         * **fingerprint_hash** (*str*) -- the user's fingerprint

         * **entry_information** -- a JSON serializable data structure
           containing additional participant entry information

      Returns:
         A "Participant" instance

      Note:

        This method is called inside a PostgreSQL transaction-level
        advisory lock ("pg_advisory_xact_lock"). That lock is released
        automatically when the surrounding transaction commits.
        Overrides must therefore **not** call "session.commit()",
        since doing so releases the lock early and allows concurrent
        signup requests to enter the critical section before the
        current one has finished.

   classmethod dashboard_recordings()

      Show deposited, pending, and unavailable answer/background
      recordings.

   data_check_failed(participant)

      Ignore Dallinger's post-submission data check.

      PsyNet quality screening happens during the timeline via
      "performance_check()". Dallinger's "data_check" runs after the
      participant has already submitted. To fail a participant after
      they have finished, call "fail()".

   decide_and_record_payment(participant)

      Decide how the participant should be paid and write it to the
      ledger.

      Return type:
         "PaymentDecision"

   dismiss_review_bonus(participant)

      Clear payment review without posting a bonus.

      Marks bonus status dismissed so a later submission-complete
      replay will not POST. "planned_bonus" and "bonus_attempt_detail"
      are kept as a record of the skipped amount and last pay attempt.

      Return type:
         "tuple"["str", "str"]

   early_exit_allowed(participant)

      Return whether the participant may leave with the paid outcome.

      For paid recruiters this is the configured reward threshold by
      default. Below that threshold, Leave still opens a confirmation
      that offers return without payment. Override this method to
      customize eligibility for the paid recruiter path.

   classmethod error_page(participant=None, error_text=None, recruiter=None, external_submit_url=None, locale=DEFAULT_LOCALE)

      Prepare any fatal-error recovery plan, then render its page.

      Callers that already prepared recovery (or are rendering a
      stored plan from "/timeline") still go through this helper;
      preparation is idempotent. The separate "/error-page" route
      stays untracked. Recruiters with nothing to ask skip the
      interactive recovery page: the plan is committed on the server
      and this helper redirects to "/timeline", which finalizes the
      session and still tells the participant that an error occurred.
      Without a "unique_id" it finalizes worker-complete itself and
      renders that error page.

   static export_path()

      Return the default export destination, "exports/latest".

   static export_preflight()

      Describe this deployment so a client can validate it before
      downloading.

   classmethod extra_parameters()

      Register PsyNet-specific configuration parameters.

   fail_participant(participant)

      Fail a participant using PsyNet's participant-failure contract.

      This Dallinger compatibility shim calls "fail()" and does not
      fail owned nodes. Do not override it; PsyNet rejects subclasses
      that do. Recruiter premature-exit handling stays on
      "_handle_premature_exit()".

   classmethod fail_participant_on_error(participant, error)

      Record the exception type without choosing the session outcome.

      Fatal-error recovery owns "participant.fail("error_recovery")"
      when it stores an error-recovery plan.

   classmethod get_arrival_notice()

      Return the current partner-ready notice for the arrival
      websocket.

      Redis pub/sub can miss a partner who arrived before this socket
      subscribed. The browser fetches this snapshot on open.

   static get_asset_by_access_token(access_token, subpath=None)

      Serve a managed or on-demand asset via its permanent access
      token.

   classmethod get_basic_data(context=None, **kwargs)

      Return the experiment's basic data, a summary for analysis
      defined by the experimenter.

      Parameters:
         * **context** (*str**, **optional*) --

           Where the data is being requested:

           * ""monitor"": the dashboard's Basic data tab;

           * ""route"": the "/basic_data" HTTP endpoint;

           * ""export"": "psynet export";

           * ""backup"": automatic backups.

           The default implementation ignores it; an override can
           return different data depending on the context.

         * ****kwargs** -- Query parameters from the dashboard tab or
           the "/basic_data" endpoint, including "dashboard_user" and
           "dashboard_password" for the endpoint. Empty for exports
           and backups.

      Returns:
         A dictionary of JSON-serializable data, saved as
         "basic_data.json" in exports. When "context" is ""export"",
         the values may instead be pandas data frames, each saved as a
         CSV file under "basic_data/"; the other contexts need JSON-
         serializable data. Return "None" if the experiment defines no
         basic data. See Basic data.

      Return type:
         dict | None

      Raises:
         **DataError** -- If the data cannot be retrieved.

   classmethod get_browser_capability_check()

      Return the module that screens participants' browsers.

      PsyNet inserts the returned module at the very start of the
      timeline, before any consent pages, when the experiment class is
      defined. The default checks "browser_capabilities" and returns
      "None" (no check) if that set is empty. Override this method to
      customize the check, or return "None" to place
      "BrowserCapabilityCheck" in the timeline yourself.

      The insertion happens once per timeline, on the first experiment
      class that uses it, even if the timeline comes from a mixin. A
      subclass whose effective "browser_capabilities" or method
      differs from its parent's, for example through a second base
      class, must therefore define its own "timeline".

      Returns:
         The browser-check module, or "None" to skip automatic
         insertion.

      Return type:
         Module or None

   classmethod get_group_prompt()

      Draw a live group display again after members joined or left.

   static get_last_n_from_class(klass, limit=1000)

      Returns the last n objects from the given class.

      Return type:
         "List"["object"]

   classmethod get_participant_from_assignment_id(assignment_id, for_update=False)

      Get a participant with a specified "assignment_id". Throws a
      "sqlalchemy.orm.exc.NoResultFound" error if there is no such
      participant, or a "sqlalchemy.orm.exc.MultipleResultsFound"
      error if there are multiple such participants.

      Parameters:
         * **assignment_id** ("str") -- ID of the participant to
           retrieve.

         * **for_update** ("bool") -- Set to "True" if you plan to
           update this Participant object. The Participant object will
           be locked for update in the database and only released at
           the end of the transaction.

      Returns:
         * *The corresponding participant object.*

   classmethod get_participant_from_participant_id(participant_id, for_update=False)

      Get a participant with a specified "participant_id". Throws a
      "ValueError" if the "participant_id" is not a valid integer, a
      "sqlalchemy.orm.exc.NoResultFound" error if there is no such
      participant, or a "sqlalchemy.orm.exc.MultipleResultsFound"
      error if there are multiple such participants.

      Parameters:
         * **participant_id** ("int") -- ID of the participant to
           retrieve.

         * **for_update** ("bool") -- Set to "True" if you plan to
           update this Participant object. The Participant object will
           be locked for update in the database and only released at
           the end of the transaction.

      Returns:
         * *The corresponding participant object.*

   classmethod get_participant_from_unique_id(unique_id, for_update=False)

      Get a participant with a specified "unique_id". Throws a
      "sqlalchemy.orm.exc.NoResultFound" error if there is no such
      participant, or a "sqlalchemy.orm.exc.MultipleResultsFound"
      error if there are multiple such participants.

      Parameters:
         * **unique_id** ("str") -- Unique ID of the participant to
           retrieve.

         * **for_update** ("bool") -- Set to "True" if you plan to
           update this Participant object. The Participant object will
           be locked for update in the database and only released at
           the end of the transaction.

      Returns:
         * *The corresponding participant object.*

   classmethod get_participant_from_worker_id(worker_id, for_update=False)

      Get the most recent participant with a specified "worker_id".

      Repeat worker IDs can produce several participants. This returns
      the newest row. Throws "sqlalchemy.orm.exc.NoResultFound" if
      none match.

      Parameters:
         * **worker_id** ("str") -- ID of the participant to retrieve.

         * **for_update** ("bool") -- Set to "True" if you plan to
           update this Participant object. The Participant object will
           be locked for update in the database and only released at
           the end of the transaction.

      Returns:
         * *The corresponding participant object.*

   classmethod get_status(lookback_s=60)

      Return the status of the experiment as a dictionary.

   classmethod get_username()

      Return the account that launched this process.

      "os.getlogin" reports the login that started the Docker daemon.
      Inside a container that name is root even when the process uid
      is the SSH user, so the account database and "USER" are used
      instead.

   classmethod get_waiting_status()

      Tell a waiting page whether its barrier has released the
      participant.

   static google_search_console()

      This route is disabled by default, but can be enabled by setting
      *enable_google_search_console = true* in config.txt. Enabling
      this route allows the site to be claimed in the Google Search
      Console dashboard of the computational.audition@gmail.com Google
      account. This allows the account to investigate and debug Chrome
      warnings (e.g. 'Deceptive website ahead'). See
      https://search.google.com/u/4/search-console.

   classmethod handle_error(error, **kwargs)

      Roll back the failed work, save the error's record, then notify.

      "kwargs" are the ORM objects the error concerns ("participant",
      "trial", "async_job", ...). They and their parents are recorded
      by ID; objects that were never saved, and values that are not
      ORM objects, are ignored. Because this rolls back and commits
      the session, call it from code that owns the transaction, not
      from inside a timeline step.

   handle_websocket_message(message, *, channel_name, participant_id=None, scope=None, receive_time=None)

      Pass "/experiment-socket" messages to the channel's
      "WebSocketElt" handlers.

      Handlers with "requires_checked_connection" run here, on the web
      process holding the socket, with the participant the connection
      was checked for. If a channel has any such handler, its other
      handlers don't receive "/experiment-socket" messages. Messages
      on other channels go to "receive_message" as Dallinger's default
      does.

   health()

      Report availability and a small public-safe snapshot of the
      experiment.

      This endpoint is unauthenticated. It never includes participant
      counts, errors, dashboard URLs, or other internal details.

   hidden_dashboards

   initial_recruitment_size = 1

      int, the number of participants requested when the experiment
      first starts. Default is 1.

   initialize_bot(bot)

      This function is called when a bot is created. It can be used to
      set stochastic random parameters corresponding to participant
      latent traits, for example.

      e.g.

      "`bot.var.musician = True"

   is_at_capacity()

      Return whether the study is too busy to admit a newcomer right
      now.

      While this returns "True", newcomers wait on the start page,
      which tells them that many people are taking part and retries
      every 20 to 40 seconds. It is called before each new participant
      is created, including those retries, so keep it cheap; after it
      returns "True", each web process skips it for 2 seconds.
      Returning participants are never refused. Use it only for load:
      the waiting message and retries don't suit closing the study
      (for example outside certain hours).

      By default, the study is at capacity once the experiment
      variable "max_concurrent_participants" participants are active
      (see "psynet.capacity.count_active_participants()"). Because it
      is an experiment variable, the limit can change while the study
      runs, for example "experiment.var.max_concurrent_participants =
      80". Override this method to measure load differently, for
      example to count participants as active for 30 minutes after
      their last page:

         from psynet.capacity import count_active_participants

         def is_at_capacity(self):
             limit = self.var.max_concurrent_participants
             return limit is not None and count_active_participants(1800) >= limit

      Only supported with the "generic" and "hotair" recruiters.

      Return type:
         bool

   is_complete()

      Report whether the experiment has finished, as shown by
      "/summary".

      "psynet debug local --legacy" stops itself once this returns
      "True". Performance tests set "PSYNET_PERFORMANCE_TEST=1" to
      keep the server alive between bots, which arrive outside
      recruitment.

   log(text, key='?????', force=False)

      Log "text" at INFO on the "psynet" logger, after "key".

      Replaces Dallinger's version, which prints to stdout, so that
      messages such as recruiter notifications get the server's log
      format and level.

      Parameters:
         * **text** (*str*) -- The message.

         * **key** (*str*) -- A short tag shown before the message.
           Tags without letters or digits, such as Dallinger's "-----"
           and "?????", are left out.

         * **force** (*bool*) -- Log even if "self.verbose" is false.

   classmethod log_to_db(error, token, log_line_number, **kwargs)

      Add an "ErrorRecord" to the current transaction.

      Rendering runs in a read-only transaction, so errors reported
      while rendering are only logged and notified.

   classmethod log_to_notifier(token, line_number, formatted_traceback=None, **kwargs)

      Notify the researcher of an error, with the traceback being
      handled.

      Pass "formatted_traceback" when calling this outside the
      "except" block, where "traceback.format_exc()" no longer sees
      the error.

   monitoring_statistics(**kwarg)

      The default data used for the monitoring panels

      Parameters:
         ****kw** -- arguments passed in from the request

      Returns:
         An "OrderedDict()" mapping panel titles to data structures
         describing the experiment state.

   network_structure(network_roles=None, network_ids=None, collapsed=False, transformations=False)

      Return network monitor payload with PsyNet trials in the infos
      slot.

      Dallinger's network monitor still expects an "infos" list linked
      to nodes via "origin_id". PsyNet trials live in the "trial"
      table and use "node_id", so we substitute trial rows and alias
      "origin_id".

   on_launch()

      This function is called upon experiment launch. Unlike the
      background tasks, this function is blocking: recruitment won't
      start until the function has returned.

   on_recruiter_submission_complete(participant, event)

      Record payment fields, complete or approve on the platform, pay
      the bonus, and recruit.

      PsyNet owns this handler rather than calling Dallinger's
      implementation. Status and platform base are always re-recorded
      (so a Prolific listener replay that reset status to "submitted"
      is restored). "bonus_status" skips a repeat money transfer:
      PsyNet posts a bonus at most once. Recruitment still runs if the
      first bonus transfer fails; a later replay does not recruit
      again. Opening an unconfirmed person polls the platform into the
      participant table and offers Pay bonus or Dismiss. If the
      platform refuses the decided study base, that is flagged on the
      participant so they do not silently look fully paid. Dallinger's
      unused "data_check" / "attention_check" hooks are not run.

   classmethod organize_dashboard_tabs(tabs)

      A hook for custom organization of dashboard tabs in subclasses.

   participant_constructor(*args, **kwargs)

      An ex silico participant.

   pay_decided_bonus(participant, decision, *, reason=None)

      Report the outcome and transfer any bonus after spend-cap
      checks.

      Returns True if the outcome for this participant is finished
      (reported, paid, capped, or already settled). Returns False if
      the platform rejected the report/transfer or a previous attempt
      already failed. PsyNet calls "report_submission_outcome" at most
      once automatically. The participant row is locked, then the
      attempt is claimed by setting "bonus_status = unconfirmed",
      "planned_bonus", and a last-attempt placeholder before the
      recruiter call, so a later replay will not report or pay again.
      "unconfirmed" skips a second automatic POST even on local
      recruiters. The default skips sub-cent bonuses and delegates
      real transfers to "reward_bonus"; recruiters with
      "reports_zero_outcomes" can report every amount. Sub-cent
      bonuses for other recruiters settle locally without claiming
      "unconfirmed". A failed call stays unconfirmed and asks the
      experimenter to review on the Participants dashboard. A hard-cap
      clip keeps "planned_bonus" as the decided amount and finishes as
      "capped" even when a remainder was sent.

      Does not re-apply caps or send emails when already settled.
      Raises wherever "_check_external_call_allowed" does (timeline
      steps, savepoints, rendering), even when there is nothing to
      pay.

      Return type:
         "bool"

   pay_review_bonus(participant)

      Poll the platform, then retry the remaining payment outcome.

      Re-applies spend caps to "planned_bonus" (the decided amount).
      If the platform already reports at least that payable remainder,
      record it and skip the POST. Otherwise POST "payable -
      apparent", not the full decided amount. Automatic submission-
      complete still posts at most once; this is the human-gated extra
      attempt.

      Reloads the participant with "FOR UPDATE" and does not commit
      before the platform call, so a second overlapping Pay blocks on
      the row (or is refused if this request already claimed the
      retry). Committing first would drop that lock while status is
      still "unconfirmed" and allow two POSTs.

      Return type:
         "tuple"["str", "str"]

   plan_exit(participant, context)

      Delegate one participant exit decision to the active recruiter.

      Return type:
         "ExitPlan"

   pre_deploy(redeploying_from_archive=False, *, update=False)

      Prepare the experiment for deployment, on the machine that
      launches it.

      Assets deposited during this method count as prepared before
      launch, so they are left out of "psynet export". Deposit assets
      from a "PreDeployRoutine" rather than from an override of this
      method.

      Parameters:
         * **redeploying_from_archive** (*bool*) -- Skip asset
           deposits and the database snapshot.

         * **update** (*bool*) -- Prepare only the image for an in-
           place SSH update. The running app keeps its database and
           assets, so networks, pre-deploy routines, asset deposits
           and the snapshot are skipped.

   prepare_voluntary_exit_plan(participant)

      Store one stable Leave plan for the participant's current page.

      Return type:
         "ExitPlan"

   static prepared_voluntary_exit_plan(participant)

      Return the prepared Leave plan for the current page, if present.

      Return type:
         "Optional"["ExitPlan"]

   process_response(participant_id, raw_answer, blobs, metadata, page_uuid, client_ip_address, answer=NoArgumentProvided, *, timeline_hold_resume=False, interrupted=False)

      Advance the participant after one "/response" write.

      Parameters:
         * **interrupted** (*bool*) -- Set by a barrier's waiting page
           that ends because the participant was released (see
           "release_grace" on "Barrier"). The page is then not
           validated and its answer is not saved. If the participant
           has not been released, the submission is rejected without a
           message, so the page keeps waiting. Keyword-only.

         * **timeline_hold_resume** (*bool*) -- If True, a still-
           waiting overlay check does not take "FOR UPDATE" so last-
           arrival can still lock waiters with "NOWAIT". A resume that
           will advance locks the participant with "NOWAIT" so it
           cannot sit in "lock_timeout" behind that GET. A submitted
           "page_uuid" that still matches this participant's hold
           record is a catch-up after a partner already advanced the
           waiter, for both hold-resume and ordinary submits,
           including leftover overlays already on a later hold.
           Keyword-only; overrides should accept "**kwargs" or this
           argument.

   property protected_routes

      Dallinger routes PsyNet always protects, plus any the config
      adds.

   pseudonym_scheme = <psynet.pseudonym.PseudonymScheme object>

      How participants are named to each other in groups and chat
      rooms.

      See "PseudonymScheme" and Pseudonyms.

   publish_to_participants(payload, participant_ids, scope=None)

      Send a payload to specific participants' WebSocket connections.

      Behaves like Dallinger's "publish_to_participants()", but
      refuses payloads whose "type" is one that PsyNet's own pages
      trust, such as ""timeline_hold_wake"". Wrap forwarded
      participant content in a message with your own fixed "type"
      instead of forwarding a participant's payload unchanged.

      Parameters:
         * **payload** (*object*) -- The JSON-serializable message to
           deliver.

         * **participant_ids** (*list** of **int** or **str**, or
           **int** or **str*) -- The participants to deliver to.

         * **scope** (*str** or **None*) -- Deliver only to
           connections that supplied this scope.

      Raises:
         **ValueError** -- If "payload" is a dict whose "type" is
         reserved by PsyNet.

   reason_to_stay_awake()

      Keep a docker-ssh app awake while async jobs are pending.

      Idle hibernation stops the workers and the web process, so
      pending "WorkerAsyncJob" and "LocalAsyncJob" jobs would not
      finish.

      Returns:
         A short reason for the deploy logs, or "None" to allow sleep.

      Return type:
         str or None

   static receive_media_upload(recording_id)

      Receive reserved media independently of the participant
      transaction.

   receive_message(message, channel_name=None, participant=None, node=None, receive_time=None)

      Dispatch incoming WebSocket messages to the "WebSocketElt"
      handlers for the given channel.

      This override is activated automatically when any "WebSocketElt"
      instances are present in the timeline. Handlers are keyed by
      channel name, so each Elt only receives messages from its own
      channel.

   recruit()

      Recruit participants to the experiment as needed.

      This method runs whenever a participant successfully completes
      the experiment (participants who fail to finish successfully are
      automatically replaced). By default it recruits 1 participant at
      a time until all networks are full.

   property recruiter_class

      Return the recruiter's class without building a recruiter.

      Dallinger routes create a new experiment object for every
      request, so instantiating "self.recruiter" just to check its
      type is expensive.

   recruiter_exit_info(participant)

      Ask the recruiter which completion-code type to use for this
      participant's exit URL. Returning "None" selects the recruiter's
      default code.

      The code actually issued is stored on
      "participant.issued_completion_code_type" so later payment
      decisions and the Prolific "COMPLETE" call match what the
      platform should pay, even if the participant is failed
      afterwards.

   classmethod render_error()

      Render an untracked error page, or redirect legacy tracked
      visits.

      Tracked recovery is owned by "/timeline?unique_id=...". This
      route never treats enumerable "participant_id" as session
      authority: a legacy "unique_id" query is redirected to
      "/timeline", and every other visit gets a read-only untracked
      page.

   render_exit_message(participant)

      This method is currently only called if the 'generic' recruiter
      is selected. We may propagate it to other recruiter methods
      eventually too. If left unchanged, PsyNet's themed thank-you
      page is shown ("psynet_exit_recruiter.html"), with the
      assignment ID as a reference. Otherwise, one can return a custom
      message in various ways. If you return a string, this will be
      escaped appropriately and presented as text. To show HTML that
      you wrote yourself, return a "markupsafe.Markup" string.
      Alternatively, more complex HTML structures can be constructed
      using the Python package "dominate", see Examples for details.

      -[ Examples ]-

      This would be appropriate for experiments with no payment:

         tags.div(
             tags.p("Thank you for participating in this experiment!"),
             tags.p("Your responses have been saved. You may close this page."),
         )

      This kind of structure could be used for passing participants to
      a particular URL in Prolific:

         tags.div(
             tags.p("Thank you for participating in this experiment!"),
             tags.p("Please click the following URL to continue back to Prolific:"),
             tags.a("Finish experiment", href="https://prolific.com"),
         )

   static renew_media_uploads()

      Renew the leases of recordings the browser is still holding.

   classmethod report_error(error, **kwargs)

      Log the error, add its record to the current transaction, and
      notify.

      The caller's transaction decides whether the record is saved;
      "handle_error()" commits it after rolling back the failed work.

   static rotate_export_history(export_path)

      Archive a previous export under "exports/history".

      Callers must invoke this only once the new export is known to be
      available, so that a failed export cannot discard the previous
      one. Returns the archive directory, or "None" if there was
      nothing to archive.

   classmethod route_participant_status(participant_id)

      Describe the participant's current status for automated tests.

      Bots use this to check what the current page shows and what
      response to submit. The response is the status as JSON, unless
      the bot's response to the page includes files. In that case it
      is a zip file containing:

      * status.json: the status

      * bot_response_files/: the files that the participant would
        upload as a response to the page

   property show_reward: bool

      Whether participants are shown their accumulated reward.

      The "show_reward" config variable wins when the experiment sets
      it. Otherwise the recruiter decides, through
      "shows_reward_by_default": recruiters that pay through a
      platform show the reward, while local and generic recruitment
      does not, since PsyNet cannot pay anyone there.

      This is the only place that decision is made; the footer, the
      progress endpoint, and the debrief page all read it.

   property supported_locales

      Returns the list of supported locales for the experiment.

      This can be specified in the config.txt file, or inferred from
      the locales present in the locales directory.

   table_columns(table='participant', polymorphic_identity=None)

      Return the Database tab's columns, adding each participant's
      pseudonym.

   table_data(start, length, table='participant', **kwargs)

      Return a page of the Database tab's rows, adding each
      participant's pseudonym.

   classmethod terminate_participant()

      Terminate a Lucid respondent and send them back to their panel.

      An existing participant is only terminated by a request that
      carries their "unique_id". A bare "RID" or "assignmentId" is
      accepted only when no participant has that RID yet (for example
      the mobile-phone check on the ad page), so it can end only a
      session that has not started. A request whose "assignmentId",
      "RID" and "unique_id" name different RIDs is refused, as is any
      request when several participants share the RID. Experiments
      that don't recruit through Lucid return 404.

   test_check_bot(bot, **kwargs)

      Check one bot at the end of the test.

      By default, the bot must not have failed, unless it dropped out
      with "drop_out()" or the test called "allow_failure()" for it,
      for example for group members failed because a partner dropped
      out. Override this for other checks.

   test_serial_run_bots(bots)

      Defines the logic for testing the experiment serially (i.e. not
      running bots in parallel). This is useful for testing specific
      experiment logic, but less useful for load-testing.

      By default, this method is very simple: it just iterates over
      each bot in turn, and runs that bot from the beginning to the
      end of the experiment.

      Experiments can override this method to implement more complex
      logic. When doing so, it's worth familiarizing yourself a little
      with how the BotDriver class works. Unlike many other classes in
      PsyNet, it's not a SQLAlchemy model, but rather a utility class
      that wraps an underlying SQLAlchemy model (the Bot class). See
      the class's documentation for more details.

   static trigger_export()

      Build a complete export and store it, without sending it
      anywhere.

      A GET (such as the Slack "Trigger export" link) only shows a
      button that POSTs here, so that links on other sites cannot
      start an export.

   classmethod update_deployment_id()

      Record a new deployment ID, unless "--update" is keeping the
      running one.

   with_lucid_recruitment()

      Return whether participants are recruited through Lucid.

   with_prolific_recruitment()

      Return whether participants are recruited through Prolific.

class psynet.experiment.ExperimentConfig(*args, **kwargs)

   Bases: "Base", "SQLMixin"

   This SQL-backed class provides a way to store experiment
   configuration variables that can change over the course of the
   experiment. See "psynet.experiment.Experiment" documentation for
   example usage.

   creation_time = None

      the time at which the Network was created.

   details

      a generic column for storing structured JSON data

   failed = None

      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 = None

      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...

   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.

   time_of_death = None

      the time at which failing occurred

   type

   vars

class psynet.experiment.ExperimentStatus(*args, **kwargs)

   Bases: "Base", "SQLMixin"

   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...

   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.

   time_of_death

      the time at which failing occurred

   to_dict()

      Determines the information that is shown for this object in the
      dashboard.

   type

   vars

class psynet.experiment.Request(*args, **kwargs)

   Bases: "Base", "SQLMixin"

   creation_time

      the time at which the Network was created.

   details

      a generic column for storing structured JSON data

   failed = None

      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 = None

      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...

   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.

   time_of_death = None

      the time at which failing occurred

   to_dict()

      Determines the information that is shown for this object in the
      dashboard.

   type

class psynet.experiment.ResponseResult(payload, page=None, flask_response=None, skip_write=False, recording_response_id=None)

   Bases: "object"

   Carry response state from the write phase to HTTP rendering.

psynet.experiment.get_experiment() -> Experiment

   Returns an initialized instance of the experiment class.

   Return type:
      "Experiment"

psynet.experiment.get_trial_maker(trial_maker_id) -> TrialMaker

   Return the trial maker with the given ID from the experiment's
   timeline.

   Return type:
      "TrialMaker"

psynet.experiment.handle_shutdown_signal(signum, frame)

   Shut down on SIGINT or SIGTERM.

   Dallinger's server processes ("dallinger_heroku_web", "_worker" and
   "_clock") exit with status 0, and the clock first records that the
   experiment went offline. Other processes, such as "psynet"
   commands, bots and tests, raise "KeyboardInterrupt" on SIGINT and
   "SystemExit(128 + signum)" on SIGTERM, so that their cleanup runs
   and they exit with a failure status.

   This is installed when the module is imported, so it replaces
   handlers installed before then, such as those of gunicorn's
   workers, and is replaced by those installed later, such as those of
   RQ's "work()". A clock stopped before its configuration has loaded,
   for example by Ctrl+C while it reimports the experiment after a
   code change, exits without recording anything: loading the
   configuration would import the half-imported experiment again and
   fail.

psynet.experiment.import_local_experiment()

   Load the local experiment package, module, and class.

   Returns a dict with "package" (the "dallinger_experiment" package),
   "module" (the "experiment" module), and "class" (the Experiment
   subclass). Dallinger already imports the experiment directory as a
   package, so siblings of "experiment.py" use "from . import
   my_module". This function does not put the experiment directory on
   "sys.path".

   -[ Notes ]-

   TODO: Is it a problem if we try to import_local_experiment before
   config.load() has been called?

psynet.experiment.is_experiment_launched()

   Return "True" once "Experiment.on_launch()" has finished.

   Useful as a guard in scheduled tasks that should not run before
   launch.

psynet.experiment.json_serial(obj)

   JSON serializer for objects not serializable by default json code

psynet.experiment.pre_deploy_constant(key, func)

   Registers a pre-deploy constant. A pre-deploy constant is a value
   that is computed before the experiment is deployed, and then stored
   in a file in the .deploy directory. When the value is accessed
   during the deployed experiment, the value is retrieved from the
   file rather than being computed again. A common application is
   experiments whose design is determined by the contents of a
   directory, such as experiments that use audio stimuli, which are
   not uploaded directly to the experiment server and hence cannot be
   accessed by file listing commands.

   Parameters:
      * **key** (*str*) -- The key of the pre-deploy constant. If it's
        not a string, it will be converted to one using
        "psynet.serialize.serialize".

      * **func** (*callable*) -- A callable that computes and returns
        the value of the pre-deploy constant.

   Return type:
      The value of the pre-deploy constant.

   -[ Examples ]-

   # You could place this in your experiment.py file to list the files
   in the "data" directory. >>> data_files =
   pre_deploy_constant("data_files", sorted(os.listdir("data")))

psynet.experiment.validate_browser_capabilities(capabilities)

   Return "capabilities" as a frozenset, raising ValueError for
   invalid tokens.


Scheduled tasks
===============

"scheduled_task" is re-exported from Dallinger. Use it on a static
method of your experiment class to run code on the clock process, for
example "@scheduled_task("interval", seconds=10, max_instances=1)".

psynet.experiment.scheduled_task(trigger, **kwargs)

   Creates a decorator to register experiment functions or
   classmethods as tasks for the clock process. Accepts all arguments
   for *apscheduler.schedulers.base.BaseSchedule.scheduled_job* The
   task registration is deferred until clock server setup to allow
   tasks to be overridden by subclasses.

   Parameters:
      * **trigger** -- an "apscheduler" trigger type. One of
        "interval", "cron", or "date"

      * ****kwargs** -- other arguments for
        *apscheduler.schedulers.base.BaseSchedule.scheduled_job*
        generally used for trigger arguments to determine the run
        interval.

   Returns:
      A decorator to register methods from a class as scheduled tasks.
