Participant
***********

psynet.participant.get_participant(participant_id, for_update=False)

   Returns the participant with a given ID. For loads that don't lock,
   we recommend just using SQLAlchemy directly instead of this
   function. If you plan to update this Participant object, use
   "for_update=True" here rather than a plain "with_for_update()"
   query: one that waits for the lock can join the participant's
   current trial as it was before the wait.

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

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

   Return type:
      "Participant"

   Returns:
      * "psynet.participant.Participant" -- The requested participant.

class psynet.participant.Participant(*args, **kwargs)

   Represents an individual participant taking the experiment. The
   object is linked to the database - when you make changes to the
   object, it should be mirrored in the database.

   Users should not have to instantiate these objects directly.

   The class extends the "Participant" class from base Dallinger
   ("dallinger.models.Participant") to add some useful features, in
   particular the ability to store arbitrary variables.

   The following attributes are recommended for external use:

   * "answer"

   * "var"

   * "failure_tags"

   The following method is recommended for external use:

   * "append_failure_tags()"

   See below for more details.

   id

      The participant's unique ID.

      Type:
         int

   elt_id

      Represents the participant's position in the timeline. Should
      not be modified directly. The position is represented as a list,
      where the first element corresponds to the index of the
      participant within the timeline's underlying list
      representation, and successive elements (if any) represent the
      participant's position within (potentially nested) page makers.
      For example, "[10, 3, 2]" would mean go to element 10 in the
      timeline (0-indexing), which must be a page maker; go to element
      3 within that page maker, which must also be a page maker; go to
      element 2 within that page maker.

      Type:
         list

   elt_bounds

      Represents the number of elements at each level of the current
      "elt_id" hierarchy; used to work out when to leave a page maker
      and go up to the next level. Should not be modified directly.

      Type:
         list

   page_uuid

      A long unique string that is randomly generated when the
      participant advances to a new page, used as a passphrase to
      guarantee the security of data transmission from front-end to
      back-end. Should not be modified directly.

      Type:
         str

   page_count

      The number of pages that the participant has advanced through.
      Should not be modified directly.

      Type:
         int

   complete

      Whether the participant has successfully completed the
      experiment. A participant is considered to have successfully
      completed the experiment once they hit a "SuccessfulEndPage".
      Should not be modified directly.

      Type:
         bool

   early_exited

      Whether the participant's session ended through an early-exit
      plan, either after they confirmed Leave or during automatic
      error recovery.

      Type:
         bool

   exit_plan

      The server-owned "ExitPlan" snapshot for this participant's
      terminal outcome.

      Type:
         dict or None

   answer

      The most recent answer submitted by the participant. Can take
      any form that can be automatically serialized to JSON. Should
      not be modified directly.

      Type:
         object

   response

      An object of class "Response" providing detailed information
      about the last response submitted by the participant. This is a
      more detailed version of "answer".

      Type:
         Response

   branch_log

      Stores the conditional branches that the participant has taken
      through the experiment. Should not be modified directly.

      Type:
         list

   failure_tags

      Stores tags that identify the reason that the participant has
      failed the experiment (if any). For example, if a participant
      fails a microphone pre-screening test, one might add
      "failed_mic_test" to this tag list. Should be modified using the
      method "append_failure_tags()".

      Type:
         list

   var

      A repository for arbitrary variables; see "VarStore" for
      details.

      Type:
         "VarStore"

   progress

      The participant's estimated progress through the experiment.

      Type:
         float [0 <= x <= 1]

   client_ip_address

      The participant's IP address as reported by Flask.

      Type:
         str

   answer_is_fresh

      "True" if the current value of "participant.answer" (and
      similarly "participant.last_response_id" and
      "participant.last_response") comes from the last page that the
      participant saw, "False" otherwise.

      Type:
         bool

   browser_platform

      Information about the participant's browser version and OS
      platform.

      Type:
         str

   all_trials

      A list of all trials for that participant.

      Type:
         list

   alive_trials

      A list of all non-failed trials for that participant.

      Type:
         list

   failed_trials

      A list of all failed trials for that participant.

      Type:
         list

   append_failure_tags(*tags)

      Appends tags to the participant's list of failure tags.
      Duplicate tags are ignored. See "failure_tags" for details.

      Parameters:
         ***tags** -- Tags to append.

      Returns:
         * "psynet.participant.Participant" -- The updated
           "Participant" object.

   assignment_id

      A String, the assignment id of the participant.

   property async_processes

      Deprecated alias of "async_jobs".

   base_pay

      The amount the participant was paid for finishing the
      experiment.

   bonus

      the amount the participant was paid as a bonus.

   property bonus_needs_review

      True when the automatic bonus POST is unconfirmed on an external
      recruiter.

   property bonus_status_label

      Experimenter-facing bonus outcome. See "display_bonus_status".

   calculate_reward()

      Calculates and returns the currently accumulated reward for the
      given participant.

      Returns:
         The reward as a "float".

   creation_time

      the time at which the Network was created.

   property current_trial

      This property is used to deal with some flakiness we've seen in
      the underlying SQLAlchemy relationship. For some unclear reason,
      we sometimes end up in a situation where the foreign key
      current_trial_id is not None, but the _current_trial attribute
      is (incorrectly) None. The following code detects this situation
      and retries loading the attribute a few times.

   details

      a generic column for storing structured JSON data

   end_time

      The time at which the participant finished.

   entry_information

      column containing structured data from the recruiter

   fail(reason=None, *, redirect_to_end=True)

      Mark this participant as failed.

      Incomplete trials are failed here. Completed trials stay unless
      a TrialMaker performance-check policy treats them as unusable. A
      completed participant can still be failed; they are not
      redirected off the successful-end page. Already-failed calls are
      a no-op.

      If they are still on the main timeline, they are redirected to
      "unsuccessful_end". They are also removed from active sync
      groups. Whether that dissolves a group left below its "quorum"
      is described in Groups below quorum. See Handling failed
      participants and trials.

      Parameters:
         * **reason** (*str**, **optional*) -- Failure tag to append,
           for example ""premature_exit"".

         * **redirect_to_end** (*bool**, **optional*) -- Whether to
           enter the unsuccessful-end timeline branch. Error recovery
           sets this to "False" because its exit plan owns the
           terminal handoff.

   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.

   property failure_cascade

      Return no owned objects. "failed" is not an ownership marker.

   fingerprint_hash

      A String, the fingerprint hash of the participant.

   hit_id

      A String, the id of the hit the participant is working on

   in_sync_group(group_type)

      Return whether the participant is in an active group of
      "group_type".

      This becomes "False" once they leave the group, for example
      after a barrier removes them for being late (with any
      "late_action"), or when their group is dissolved.

      Return type:
         "bool"

   latest_sync_group(group_type)

      Return the participant's latest group of "group_type", or "None"
      if they had none.

      Unlike "active_sync_groups", this includes a group they have
      left or that has ended, so a page can still show that group's
      history, for example with "rounds()".

      Return type:
         "Optional"["SyncGroup"]

   mode

      live, sandbox or debug.

      Type:
         A String, the mode in which Dallinger is running

   classmethod needing_payment_review()

      Participants whose automatic bonus transfer is unconfirmed.

      PsyNet already used its one automatic platform bonus POST (or
      was interrupted while doing so). Local recruiters such as HotAir
      are omitted: they have no external platform to review. Open the
      participant on the Participants dashboard to compare with the
      platform, then pay or dismiss.

   classmethod needing_platform_base_retry(*, max_attempts)

      Participants whose unpaid study base the next check should
      retry.

      "platform_base_unpaid" plus fewer than "max_attempts" failed
      retries. The bound exists so a permanently refused row (wrong
      code, returned, rejected) eventually stops consuming platform
      requests and the researcher is asked to take over.

   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 pseudonym

      Return the name, colour and icon that other participants see,
      for example "Blue fox".

      See "PseudonymScheme".

   recruiter_id

      A String, the nickname of the recruiter used by this
      participant.

   set_pseudonym(color, animal)

      Give this participant a particular pseudonym, by colour and
      animal key.

      The keys must exist in the experiment's "PseudonymScheme". A
      pseudonym set here is kept, even if another member of a group
      has it too; only derived pseudonyms are made unique, in the
      participant's first "SyncGroup" (see Pseudonyms).

   status

      String representing the current status of the participant, can
      be:

      * "abandoned" - they ran out of time

      * "approved" - their work has been approved and they have been
        paid

      * "bad_data" - the participant finished, but their data was
        malformed

      * "did_not_attend" - the participant finished, but failed the
        attention check

      * "missing_notification" - this indicates that Dallinger has
        inferred that a Mechanical Turk notification corresponding to
        this participant failed to arrive. This is an uncommon, but
        potentially serious issue.

      * "overrecruited" - number of recruited participants exceed
        number required for the experiment, so this participant will
        not be used

      * "recruiter_submission_started" - participant has submitted
        their assignment to their recruiter, but the recruiter is
        still processing it

      * "rejected" - their work has been rejected

      * "replaced" - they have been replaced by another participant

      * "returned" - they returned the hit before finishing

      * "screened_out" - they were screened out (Prolific only)

      * "submitted" - participant's assignment submission processing
        has been completed by their recruiter

      * "working" - participant is working

   sync_group_link(group_type)

      Return the participant's link to their latest group of
      "group_type", or "None".

      The link records their membership, including "admitted_at" (when
      the group admitted them, "None" while pending) and
      "admission_points_passed" (how many of the group's admission
      points released them once admitted), for example to work out how
      long a member has been in a society. It stays readable after
      they leave.

      Return type:
         "Optional"["ParticipantLinkSyncGroup"]

   sync_group_removal_reason(group_type)

      Return why the participant is not in a group of "group_type".

      Returns "None" if they are in such a group, or if they were
      never in one and no grouper of that type let them continue
      without one. Returns ""no_group_formed"" if the last grouper of
      that type that they reached, with
      "max_wait_action="continue_without_group"", found them no group
      in time, even if they were in a group of that type before.
      Otherwise returns why they left their latest group of that type:
      ""late"" (removed by a barrier's "late_after", with any
      "late_action", from its group or a group listed in its
      "also_leave"), ""waited_too_long"" (waited at a barrier for
      longer than its "max_wait_time", with any "max_wait_action"),
      ""group_dissolved"" (still in the group when it was dissolved
      below its quorum, with any "below_quorum"), ""moved_on"" (a
      "Regrouper" took them out of their previous group: seen while
      they wait at the regrouper, and after they sit a round out, even
      if they then fail there; once they are in the next group this
      returns "None"), ""finished"" (left after playing their part),
      ""not_admitted"" (joined as a pending member but was turned away
      before an admission point admitted them, for example after its
      "newcomer_max_wait" or because top-ups stopped; never failed),
      ""left_experiment"" (failed, including returning the study, and
      for a member's other groups when a barrier's
      "late_action="fail"" or "max_wait_action="fail"", or a
      dissolving group's "below_quorum="fail"", fails them), or
      ""removed_by_experimenter"" (removed from the dashboard, or by
      "remove_participant()" with that reason). A player sat out of
      their first round was never in a group, so this returns "None"
      for them; check "sat_out()" or "in_sync_group" instead.

      To explain an early end, map the reasons your game can meet to
      your own text. A missing reason raises "KeyError", so include
      ""removed_by_experimenter"", which a dashboard removal can give
      in any game:

         ENDED_EARLY_TEXTS = {
             "late": "You were away for too long, so the game ended early for you.",
             "group_dissolved": "Too few players stayed, so the game ended early.",
             "removed_by_experimenter": "You were removed from the game.",
         }
         text = ENDED_EARLY_TEXTS[participant.sync_group_removal_reason("team")]

      Return type:
         "Optional"["str"]

   time_of_death

      the time at which failing occurred

   timed_out_since_barrier

      whether the latest timed page answered outside waiting logic and
      outside a trial's feedback since the last barrier ended on its
      time limit. The next barrier copies it onto the visit
      ("ParticipantLinkBarrier.ran_out_of_time") and clears it. To
      find answers given when a time limit ran out, read
      "psynet.trial.main.Trial.time_limit_reached" or
      "psynet.timeline.Response.time_limit_reached" instead.

      Type:
         Internal

   to_dict()

      Return the participant's fields without the raw pseudonym keys.

      The Database tab adds the pseudonym itself (see
      "psynet.experiment.Experiment.table_data()"), so participant
      JSON responses don't depend on translations.

   type

      a String giving the name of the class. Defaults to
      "participant". This allows subclassing.

   unique_id

      A String, a concatenation of "worker_id" and "assignment_id"

   vars

   property websocket_scope

      Return the token that this participant's pages open websockets
      with.

      "accept_websocket_connection()" checks it. It is derived from
      "unique_id" by HMAC, so Dallinger can log and store it without
      revealing the "unique_id". Treat it as a secret all the same:
      anyone holding it can open checked websockets as this
      participant.

   worker_id

      A String, the worker id of the participant.
