Static
******

Static trial assignment built on one-node networks.

Static trial makers expose nodes as their public assignment candidates
while reusing chain-network availability and capacity checks
internally. Experiment authors customize node eligibility with
"custom_node_filter" and ranking with "select_node"; network
adaptation remains an implementation detail.

class psynet.trial.static.StaticNetwork(*args, **kwargs)

   Bases: "ChainNetwork"

   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.

   full

      Whether the network is currently full

   id

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

   max_size

      How big the network can get, this number is used by the full()
      method to decide whether the network is full

   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.

   role

      The role of the network. By default dallinger initializes all
      networks as either "practice" or "experiment"

   time_of_death

      the time at which failing occurred

   type

      A String giving the name of the class. Defaults to "network".
      This allows subclassing.

   vars

class psynet.trial.static.StaticNode(*args, **kwargs)

   Bases: "ChainNode"

   create_definition_from_seed(seed, experiment, participant)

      Creates a node definition from a seed. The seed comes from the
      previous node in the chain. In many cases (e.g. iterated
      reproduction) the definition will be trivially equal to the
      seed, but in some cases we may introduce some kind of stochastic
      alteration to produce the definition.

      Parameters:
         * **seed** (*object*) -- The seed, passed from the previous
           state in the chain.

         * **experiment** -- An instantiation of
           "psynet.experiment.Experiment", corresponding to the
           current experiment.

         * **participant** -- The participant who initiated the
           creation of the node.

      Returns:
         * *object* -- The derived definition. Should be suitable for
           serialisation to JSON.

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

   network

      the network the node is in

   network_id

      the id of the network that this node is a part of

   participant

      the participant the node is associated with

   participant_id

      the id of the participant whose node this is

   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.

   summarize_trials(trials, experiment, participant)

      Summarizes the trials at the node to produce a seed that can be
      passed to the next node in the chain.

      Parameters:
         * **trials** ("list") -- Trials to be summarized. By default
           only trials that are completed (i.e. have received a
           response) and processed (i.e. aren't waiting for an async
           job) are provided here.

         * **experiment** -- An instantiation of
           "psynet.experiment.Experiment", corresponding to the
           current experiment.

         * **participant** -- The participant who initiated the
           creation of the node.

      Returns:
         * *object* -- The derived seed. Should be suitable for
           serialisation to JSON.

   time_of_death

      the time at which failing occurred

   type

      A String giving the name of the class. Defaults to "node". This
      allows subclassing.

   vars

class psynet.trial.static.StaticTrial(*args, **kwargs)

   Bases: "ChainTrial"

   A Trial class for static experiments.

   The user must override the "time_estimate" class attribute,
   providing the estimated duration of the trial in seconds. This is
   used for predicting the participant's reward and for constructing
   the progress bar.

   time_estimate

      The estimated duration of the trial (including any feedback), in
      seconds. This should generally correspond to the (sum of the)
      "time_estimate" parameters in the page(s) generated by
      "show_trial", plus the "time_estimate" parameter in the page
      generated by "show_feedback" (if defined). This is used for
      predicting the participant's reward and for constructing the
      progress bar.

      Type:
         numeric

   participant_id

      The ID of the associated participant. The user should not
      typically change this directly. Stored in "property1" in the
      database.

      Type:
         int

   answer

      The response returned by the participant. This is serialised to
      JSON, so it shouldn't be too big. The user should not typically
      change this directly. Stored in "details" in the database.

      Type:
         Object

   definition

      A dictionary of parameters defining the trial, inherited from
      the respective "Stimulus" object.

   participant_group

      The associated participant group.

   block

      The block in which the trial is situated.

   complete

      Whether the trial has been completed (i.e. received a response
      from the participant). It is set once all of "show_trial()"'s
      pages have ended, before "show_feedback()", and also when a
      barrier's release ends the trial's page in "waiting_logic"
      before it is answered, in which case the trial is failed with
      "failed_reason="interrupted_by_release"", not finalized, and
      gets no "show_feedback()". The user should not typically change
      this directly.

   creation_time

      the time at which the Network was created.

   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.

   group_round

      The "SyncGroupRound" this trial was played in, shared with the
      trials of the other members in the round, or "None" for
      ungrouped trials. Its "var" holds the group's results for the
      round, and "group_round.trials" the partners' trials.

   id

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

   position

      Zero-based creation position among all trials from this trial
      maker for the participant, or, for trials made by "Trial.cue()",
      among the participant's trials in the same module.

   show_trial(experiment, participant)

      Returns a "Page" object, or alternatively a list of such
      objects, that solicits an answer from the participant.

      Parameters:
         * **experiment** -- An instantiation of
           "psynet.experiment.Experiment", corresponding to the
           current experiment.

         * **participant** -- An instantiation of
           "psynet.participant.Participant", corresponding to the
           current participant.

   sync_group_id

      The group of the trial maker's (or, for cued trials, the trial
      class's) "sync_group_type" that the participant was in when the
      trial was created, kept after the group ends.

   sync_group_outcome

      when the trial maker prepares the group's next trials,
      ""stayed"" is written on the complete trials of the members
      still in the group. "None" while nothing has happened yet, and
      for ungrouped trials.

      Type:
         How the group's round ended for this player, for a trial in a
         group's round ("group_round"), one of "SyncGroupOutcome". It
         is written during the trial's pages, that is, before
         "complete" is set

      Type:
         ""stayed"" once a "GroupBarrier" in those pages, such as in
         "show_trial()", releases the group with the player in it,
         after which it doesn't change. Before that, why the player
         left the group, one of the reasons of "remove_participant()",
         such as ""late"", ""waited_too_long"", ""left_experiment"" or
         ""group_dissolved"" or ""removed_by_experimenter"". Leaving
         after a release, for example by being late at a later
         barrier, shows in "sync_group_removal_reason()" and in the
         "left" of the next barrier's "on_release" instead. Barriers
         and departures after the trial's pages, such as in
         "show_feedback()" or between rounds, write nothing. The
         exception is a trial maker's round that no barrier in the
         trial's pages released

   sync_group_role

      The participant's role in "sync_group_id", if a Regrouper gave
      one.

   sync_group_round

      Which round of "sync_group_id" this trial belongs to, counted
      from 0. A member who joined the group late shares the group's
      numbers. In a trial maker, a leader told to wait gives the group
      no trials, so the followers wait too and no number is used up.
      It equals the "number" of "group_round".

   sync_group_round_id

      ID of "group_round".

   time_of_death

      the time at which failing occurred

   type

   vars

class psynet.trial.static.StaticTrialMaker(*, id_, trial_class, nodes, expected_trials_per_participant, max_trials_per_participant=None, recruit_mode=None, target_n_participants=None, n_participants_completion='experiment', target_trials_per_node=None, max_trials_per_block=None, allow_repeated_nodes=False, block_order='random', node_order='balanced', balance_across_nodes=None, check_performance_at_end=False, check_performance_every_trial=False, fail_trials_on_premature_exit=False, fail_trials_on_participant_performance_check=True, n_repeat_trials=0, assets=None, choose_participant_group=None, sync_group_type=None, sync_group_max_wait_time=<class 'psynet.utils.NoArgumentProvided'>, sync_group_max_wait_action='fail', sync_group_late_after=None, sync_group_late_action=None, sync_group_also_leave=None, sync_group_waiting_message=None, sync_group_newcomer_max_wait=None)

   Bases: "ChainTrialMaker"

   Administers a sequence of trials in a static experiment. The class
   is intended for use with the "StaticTrial" helper class. which
   should be customised to show the relevant node for the experimental
   paradigm.

   The user may also override the following methods, if desired:

   * "choose_participant_group()";
        Only relevant if the trial maker uses nodes with non-default
        participant groups. In this case the experimenter is expected
        to supply a function that takes participant as an argument and
        returns the chosen participant group for that trial maker. For
        example, to randomly assign participants to one of two groups
        called g1 and g2, one could write:

           choose_participant_group=lambda participant: random.choice(["g1", "g2"])

        Similarly, to alternate participants between two groups, one
        could write:

           choose_participant_group=lambda participant: ["g1", "g2"][participant.id % 2]

   * "select_node()"; selects one of the eligible nodes for the
     participant's next trial.

   * "custom_node_filter()"; filters eligible nodes before selection.

   * "on_complete()", run once the sequence of trials is complete.

   * "performance_check()"; checks the performance of the participant
     with a view to rejecting poor-performing participants.

   * "compute_performance_reward()"; computes the final performance
     reward to assign to the participant.

   Further customisable options are available in the constructor's
   parameter list, documented below.

   Parameters:
      * **trial_class** -- The class object for trials administered by
        this maker (should subclass "StaticTrial").

      * **nodes** ("Union"["callable", "List"["StaticNode"], "None"])
        -- The nodes to be administered to the participants. This can
        be provided as a list of "StaticNode" objects, or as a
        function (taking no arguments) that can be called to generate
        such a list. The latter is useful for generating nodes based
        on local files (e.g. large media assets) that are not
        available on the deployed server.

      * **expected_trials_per_participant** ("Union"["int", "str"]) --
        Expected number of trials that each participant will complete.
        This is used for timeline/progress estimation purposes. This
        can either be an integer, or the string ""n_nodes"", which
        will be read as referring to the number of nodes in "nodes".

      * **max_trials_per_participant** ("Union"["int", "str", "None"])
        -- Maximum number of trials that each participant may complete
        (optional); once this number is reached, the participant will
        move on to the next stage in the timeline. This can either be
        an integer, or the string ""n_nodes"", which will be read as
        referring to the number of nodes in "nodes".

      * **recruit_mode** ("Optional"["str"]) -- Selects a recruitment
        criterion for determining whether to recruit another
        participant. The built-in criteria are ""n_participants"" and
        ""n_trials"". ""n_participants"" needs
        "target_n_participants", and ""n_trials"" needs
        "target_trials_per_node"; giving a target without its mode
        raises an error. Defaults to "None", which leaves recruitment
        to the rest of the experiment, for example for a practice
        trial maker.

      * **target_n_participants** ("Optional"["int"]) -- Target number
        of participants to recruit for the experiment. Requires
        "recruit_mode="n_participants""; passing it with "None" or
        ""n_trials"" raises an error. Which completions fill the quota
        is controlled by "n_participants_completion".

      * **n_participants_completion** ("Literal"["'experiment'",
        "'trial_maker'"]) -- Which kind of completion counts toward
        "target_n_participants". ""experiment"" (default) counts
        participants who successfully finish the whole experiment.
        ""trial_maker"" counts participants who finish this
        TrialMaker, even if they later leave before the experiment end
        page. In-progress participants still occupy a slot in both
        cases, including people who have not yet reached this
        TrialMaker, so PsyNet does not immediately recruit a
        replacement. ""trial_maker"" raises an error with
        "recruit_mode=None" or ""n_trials"".

      * **target_trials_per_node** ("Optional"["int"]) -- Target
        number of trials to recruit for each node. "None" (the
        default) means unlimited. When set, it must be a positive
        number; "0" is rejected. Requires "recruit_mode="n_trials"";
        passing it with any other mode raises an error. It does not
        cap selection: a node can receive more trials than its target,
        for example when participants recruited together finish at the
        same time.

      * **max_trials_per_block** ("Optional"["int"]) -- Determines the
        maximum number of trials that a participant will be allowed to
        experience in each block, including failed trials. Note that
        this number does not include repeat trials.

      * **allow_repeated_nodes** ("bool") -- Determines whether the
        participant can be administered the same node more than once.

      * **block_order** ("Union"["str", "list", "callable"]) -- The
        order in which the participant works through blocks:
        ""random"" (the default), ""listed"" (the order in which
        blocks first appear in "nodes"), a list of block names, or a
        function returning such a list. The function may take any of
        "participant", "experiment" and "blocks". See Trial order.

      * **node_order** ("Union"["str", "callable", "dict"]) -- The
        order in which the participant receives nodes within a block:
        ""balanced"" (the default; nodes with the fewest trials from
        any participant first, excluding failed trials), ""random"",
        ""listed"" (the order of "nodes"), a function returning the
        planned nodes, or a dict giving one of these values for every
        block. A function may take any of "participant", "experiment",
        "block" and "nodes"; returning fewer nodes than it was given
        also filters them. See Trial order.

      * **check_performance_at_end** ("bool") -- If "True", the
        participant's performance is evaluated at the end of the
        series of trials. Defaults to "False". See
        "performance_check()" for implementing performance checks.

      * **check_performance_every_trial** ("bool") -- If "True", the
        participant's performance is evaluated after each trial.
        Defaults to "False". See "performance_check()" for
        implementing performance checks.

      * **fail_trials_on_premature_exit** ("bool") -- See
        "TrialMaker".

      * **fail_trials_on_participant_performance_check** ("bool") --
        See "TrialMaker". Defaults to "True".

      * **n_repeat_trials** ("int") -- Number of repeat trials to
        present to the participant. These trials are typically used to
        estimate the reliability of the participant's responses.
        Repeat trials are presented at the end of the trial maker,
        after all blocks have been completed. Defaults to 0.

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

        Only relevant if the trial maker uses nodes with non-default
        participant groups. In this case the experimenter is expected
        to supply a function that takes participant as an argument and
        returns the chosen participant group for that trial maker. For
        example, to randomly assign participants to one of two groups
        called g1 and g2, one could write:

           choose_participant_group=lambda participant: random.choice(["g1", "g2"])

        Similarly, to alternate participants between two groups, one
        could write:

           choose_participant_group=lambda participant: ["g1", "g2"][participant.id % 2]

      * **sync_group_type** ("Optional"["str"]) -- Optional SyncGroup
        type to use for synchronizing participant allocation to nodes.
        When this is set, then the ordinary node allocation logic will
        only apply to the 'leader' of each SyncGroup. The other
        members of this SyncGroup will follow that leader around, so
        that in every given trial the SyncGroup works on the same node
        together. The other "sync_group_*" options raise an error
        without it.

      * **sync_group_waiting_message** -- The message and time limits
        of the trial maker's own sync-group waits; see "TrialMaker".

      * **sync_group_max_wait_time** ("Union"["float", "Callable",
        "None"]) -- The message and time limits of the trial maker's
        own sync-group waits; see "TrialMaker".

      * **sync_group_max_wait_action** ("Literal"["'fail'",
        "'leave_group'"]) -- The message and time limits of the trial
        maker's own sync-group waits; see "TrialMaker".

      * **sync_group_late_after** ("Optional"["float"]) -- The message
        and time limits of the trial maker's own sync-group waits; see
        "TrialMaker".

      * **sync_group_late_action** ("Optional"["Literal"["'fail'",
        "'leave_group'"]]) -- The message and time limits of the trial
        maker's own sync-group waits; see "TrialMaker".

      * **sync_group_also_leave** ("Optional"["Sequence"["str"]]) --
        The message and time limits of the trial maker's own sync-
        group waits; see "TrialMaker".

      * **sync_group_newcomer_max_wait** ("Optional"["float"]) -- The
        message and time limits of the trial maker's own sync-group
        waits; see "TrialMaker".

   check_timeout_interval_sec

      How often to check for trials that have timed out, in seconds
      (default = 30). Users are invited to override this.

      Type:
         float

   response_timeout_sec

      How long until a trial's response times out, in seconds (default
      = 60) (i.e. how long PsyNet will wait for the participant's
      response to a trial). This is a lower bound on the actual
      timeout time, which depends on when the timeout daemon next
      runs, which in turn depends on "check_timeout_interval_sec".
      Users are invited to override this.

      Type:
         float

   async_timeout_sec

      How long an async job may run before it times out, in seconds
      (default = 300), counted from when the job starts running, not
      from when it is queued. This is a lower bound on the actual
      timeout time, which depends on when the timeout daemon next
      runs, which in turn depends on "check_timeout_interval_sec".
      Users are invited to override this.

      Type:
         float

   network_query

      An SQLAlchemy query for retrieving all networks owned by the
      current trial maker. Can be used for operations such as the
      following: "self.network_query.count()".

      Type:
         sqlalchemy.orm.Query

   n_networks

      Returns the number of networks owned by the trial maker.

      Type:
         int

   networks

      Returns the networks owned by the trial maker.

      Type:
         list

   performance_threshold

      Threshold for the built-in performance check chosen by
      "performance_check_type", defaults to -1.0. The participant
      passes when the score (the summed trial scores, the proportion
      of non-failed trials, or the consistency) is at least this
      value.

      Type:
         float

   end_performance_check_waits

      If "True" (default), then the final performance check waits
      until all trials no longer have any pending async jobs, and
      until trials that are ready to finalize have been finalized (so
      their scores are set).

      Type:
         bool

   custom_node_filter(nodes, participant, experiment)

      Filter eligible static nodes before selection.

      Override this to remove nodes the participant must not receive.
      The default returns "nodes" unchanged. Ranking among eligible
      nodes belongs in "select_node".

      If you override this method, a deprecated
      "custom_network_filter" on the same maker is not applied.

   filter_nodes_query(query, participant, experiment)

      Narrow the database query that finds candidate nodes.

      Override this to remove nodes in SQL rather than in Python.
      "query" selects each node's "self.network_class" joined to the
      node ("self.node_class") and already applies PsyNet's built-in
      checks. Add conditions with "query.filter(...)", typically on
      columns of your node class ("self.node_class" is always
      "StaticNode", so use your own subclass, e.g.
      "ColorNode.difficulty"), and return the result. Unlike
      "custom_node_filter()", this keeps selection fast when there are
      many nodes.

   find_nodes(participant, experiment)

      Return eligible static nodes, or ""wait"" / ""exit"".

      Override "select_node" to change which eligible node is
      assigned. To wait, exit, or drop candidates after built-in
      availability checks, override this method, call
      "super().find_nodes", then filter or return ""wait"" / ""exit"".
      "select_node" cannot return those outcomes. Overriding this
      method loads every eligible node on each trial;
      "before_selection()" and "filter_nodes_query()" keep selection
      in the database. An empty list finishes the participant's
      current block; ""exit"" leaves the trial maker, skipping any
      remaining blocks.

   node_priority(participant, experiment)

      Return SQL expressions that rank eligible nodes.

      PsyNet only considers nodes in the participant's current block.
      It orders them by these expressions (ascending; use ".desc()" to
      reverse), then by balancing when "node_order="balanced"" (the
      default), then randomly. The default "select_node" takes the
      first node in that order. Expressions may use columns of your
      node class (e.g. "ColorNode.difficulty") and
      "self.network_class". Planned node orders (""listed"" or a
      function) cannot be combined with this hook. Defining it stops
      balanced selection from giving simultaneous requests different
      nodes, so they may share the top-ranked node.

   select_node(nodes, participant, experiment)

      Select from a nonempty list of eligible nodes.

      Return a node from "nodes" or "Selection(value, context)".
      Returning "None" raises "TypeError". The returned node must be
      one of the objects in "nodes", not a re-queried copy.
